2 // RMAC - Renamed Macro Assembler for all Atari computers
3 // RMAC.C - Main Application Code
4 // Copyright (C) 199x Landon Dyer, 2011-2022 Reboot and Friends
5 // RMAC derived from MADMAC v1.07 Written by Landon Dyer, 1986
6 // Source utilised with the kind permission of Landon Dyer
27 int perm_verb_flag; // Permanently verbose, interactive mode
28 int list_flag; // "-l" listing flag on command line
29 int list_pag = 1; // Enable listing pagination by default
30 int verb_flag; // Be verbose about what's going on
31 int m6502; // 1, assembling 6502 code
32 int glob_flag; // Assume undefined symbols are global
33 int lsym_flag; // Include local symbols in object file (ALWAYS true)
34 int dsym_flag; // Gen debug syms (Requires obj_format = BSD)
35 int optim_warn_flag; // Warn about possible short branches
36 int prg_flag; // !=0, produce .PRG executable (2=symbols)
37 int prg_extend; // !=0, output extended .PRG symbols
38 int legacy_flag; // Do stuff like insert code in RISC assembler
39 int obj_format; // Object format flag
40 int debug; // [1..9] Enable debugging levels
41 int err_flag; // '-e' specified
42 int err_fd; // File to write error messages to
43 int rgpu, rdsp; // Assembling Jaguar GPU or DSP code
44 int robjproc; // Assembling Jaguar Object Processor code
45 int dsp56001; // Assembling DSP 56001 code
46 int list_fd; // File to write listing to
47 int segpadsize; // Segment padding size
48 int endian; // Host processor endianess (0 = LE, 1 = BE)
49 int *regbase; // Points to current DFA register table (base)
50 int *regtab; // Points to current DFA register table (tab)
51 int *regcheck; // Points to current DFA register table (check)
52 int *regaccept; // Points to current DFA register table (accept)
53 char * objfname; // Object filename pointer
54 char * firstfname; // First source filename
55 char * cmdlnexec; // Executable name, pointer to ARGV[0]
56 char searchpatha[512] = { 0 }; // Buffer to hold searchpath when specified
57 char * searchpath = NULL; // Search path for include files
58 char defname[] = "noname.o"; // Default output filename
59 int optim_flags[OPT_COUNT_ALL] = { 0 }; // Specific optimisations on/off matrix
60 int activecpu = CPU_68000; // Active 68k CPU (68000 by default)
61 int activefpu = FPU_NONE; // Active FPU (none by default)
62 int org68k_active = 0; // .org switch for 68k (only with RAW output format)
63 uint32_t org68k_address; // .org for 68k
64 int correctMathRules; // 1, use C operator precedence in expressions
67 // Convert a string to uppercase
69 void strtoupper(char * s)
76 // Manipulate file extension.
78 // 'name' must be large enough to hold any possible filename. If 'stripp' is
79 // nonzero, any old extension is removed. If the file does not already have an
80 // extension, 'extension' is appended to the filename.
82 char * fext(char * name, char * extension, int stripp)
86 // Find beginning of "real" name (strip off path)
87 char * beg = strrchr(name, SLASHCHAR);
92 // Clobber any old extension, if requested
95 for(s=beg; *s && *s!='.'; ++s)
101 if (strrchr(beg, '.') == NULL)
102 strcat(beg, extension);
107 static int is_sep(char c)
109 const char *seps = PATH_SEPS;
111 for (seps = PATH_SEPS; *seps; seps++) {
120 // Return 'item'nth element of semicolon-seperated pathnames specified in the
121 // enviroment string 's'. Copy the pathname to 'buf'. Return 0 if the 'item'
122 // nth path doesn't exist.
124 // ['item' ranges from 0 to N-1, where N = #elements in search path]
126 int nthpath(char * env_var, int itemno, char * buf)
128 char * s = searchpath;
137 while (*s != EOS && !is_sep(*s++))
143 while (*s != EOS && !is_sep(*s))
152 // Display command line help
154 void DisplayHelp(void)
157 " %s [options] srcfile\n"
160 " -? or -h Display usage information\n"
161 " -dsymbol[=value] Define symbol (with optional value, default=0)\n"
162 " -e[errorfile] Send error messages to file, not stdout\n"
163 " -f[format] Output object file format\n"
165 " b: BSD (use this for Jaguar)\n"
168 " p: P56 (use this for DSP56001 only)\n"
169 " l: LOD (use this for DSP56001 only)\n"
170 " x: com/exe/xex (Atari 800)\n"
171 " r: absolute address\n"
172 " -g Output source level debug information (BSD object only)\n"
173 " -i[path] Directory to search for include files\n"
174 " -l[filename] Create an output listing file\n"
175 " -l*[filename] Create an output listing file without pagination\n"
176 " -m[cpu] Select default CPU. Available options:\n"
177 " 68000, 68020, 68030, 68040, 68060, 6502, tom, jerry, 56001\n"
178 " -n Don't do things behind your back in RISC assembler\n"
179 " -o file Output file name\n"
180 " +o[value] Turn a specific optimisation on\n"
181 " Available optimisation switches:\n"
182 " o0: Absolute long addresses to word\n"
183 " o1: move.l #x,dn/an to moveq\n"
184 " o2: Word branches to short\n"
185 " o3: Outer displacement 0(an) to (an)\n"
186 " o4: lea size(An),An to addq #size,An\n"
187 " o5: 68020+ Absolute long base/outer disp. to word\n"
188 " o6: Null branches to NOP\n"
189 " o7: clr.l Dx to moveq #0,Dx\n"
190 " o8: adda.w/l #x,Dy to addq.w/l #x,Dy\n"
191 " o9: adda.w/l #x,Ay to lea x(Dy),Ay\n"
192 " o10: 56001 Use short format for immediate values if possible\n"
193 " o11: 56001 Auto convert short addressing mode to long (default: on)\n"
194 " o30: Enforce PC relative (alternative name: op)\n"
195 " ~o[value] Turn a specific optimisation off\n"
196 " +oall Turn all optimisations on\n"
197 " ~oall Turn all optimisations off\n"
198 " -p Create an ST .prg (without symbols). Forces -fa\n"
199 " -ps Create an ST .prg (with symbols). Forces -fa\n"
200 " -px Create an ST .prg (with exsymbols). Forces -fa\n"
201 " -r[size] Pad segments to boundary size specified\n"
202 " w: word (2 bytes, default alignment)\n"
203 " l: long (4 bytes)\n"
204 " p: phrase (8 bytes)\n"
205 " d: double phrase (16 bytes)\n"
206 " q: quad phrase (32 bytes)\n"
207 " -s Warn about possible short branches\n"
208 " and applied optimisations\n"
209 " -u Force referenced and undefined symbols global\n"
210 " -v Set verbose mode\n"
211 " -x Turn on debugging mode\n"
212 " -y[pagelen] Set page line length (default: 61)\n"
213 " -4 Use C style operator precedence\n"
219 // Display version information
221 void DisplayVersion(void)
224 " _ __ _ __ ___ __ _ ___ \n"
225 "| '__| '_ ` _ \\ / _` |/ __|\n"
226 "| | | | | | | | (_| | (__ \n"
227 "|_| |_| |_| |_|\\__,_|\\___|\n"
228 "\nRenamed Macro Assembler\n"
229 "Copyright (C) 199x Landon Dyer, 2011-2022 Reboot and Friends\n"
230 "V%01i.%01i.%01i %s (%s)\n\n", MAJOR, MINOR, PATCH, __DATE__, PLATFORM);
234 // Parse optimisation options
236 int ParseOptimization(char * optstring)
242 if (*optstring == '+')
244 else if (*optstring != '~')
247 if (optstring[2] == 0)
248 return error(".opt called with zero arguments");
250 if ((optstring[2] == 'a' || optstring[2] == 'A')
251 && (optstring[3] == 'l' || optstring[3] == 'L')
252 && (optstring[4] == 'l' || optstring[4] == 'L'))
254 memset(optim_flags, onoff, OPT_COUNT * sizeof(int));
257 else if (optstring[1] == 'o' || optstring[1] == 'O') // Turn on specific optimisation
259 if (optstring[2] == 'p' || optstring[2] == 'P')
261 optim_flags[OPT_PC_RELATIVE] = onoff;
266 int opt_no = atoi(&optstring[2]);
268 if ((opt_no >= 0) && (opt_no < OPT_COUNT))
270 optim_flags[opt_no] = onoff;
273 // If opt_no is 2 digits then consume an extra character.
274 // Sounds a bit sleazy but we know we're not going to hit
275 // more than 100 optimisation switches so this should be
276 // fine. If we do hit that number then it'll probably be
277 // time to burn the whole codebase and start from scratch.
290 if (*optstring == ',')
296 static void ProcessFile(int fd, char *fname)
298 char *dbgname = fname;
302 fname = defname; // Kludge first filename
306 // First file operations:
307 if (firstfname == NULL)
309 // Record first filename.
312 // Validate option compatibility
315 if (obj_format != BSD)
317 printf("-g: debug information only supported with BSD object file format\n");
323 GenMainFileSym(dbgname);
328 include(fd, dbgname);
332 extern int reg68base[53];
333 extern int reg68tab[222];
334 extern int reg68check[222];
335 extern int reg68accept[222];
338 // Process command line arguments and do an assembly
340 int Process(int argc, char ** argv)
342 int argno; // Argument number
343 SYM * sy; // Pointer to a symbol record
344 char * s; // String pointer
345 int fd; // File descriptor
346 char fnbuf[FNSIZ]; // Filename buffer
348 int current_path_index = 0; // Iterator for search paths
350 errcnt = 0; // Initialize error count
351 listing = 0; // Initialize listing level
352 list_flag = 0; // Initialize listing flag
353 verb_flag = perm_verb_flag; // Initialize verbose flag
354 glob_flag = 0; // Initialize .globl flag
355 optim_warn_flag = 0; // Initialize short branch flag
356 debug = 0; // Initialize debug flag
357 objfname = NULL; // Initialize object filename
358 list_fname = NULL; // Initialize listing filename
359 err_fname = NULL; // Initialize error filename
360 obj_format = BSD; // Initialize object format
361 firstfname = NULL; // Initialize first filename
362 err_fd = ERROUT; // Initialize error file descriptor
363 err_flag = 0; // Initialize error flag
364 rgpu = 0; // Initialize GPU assembly flag
365 rdsp = 0; // Initialize DSP assembly flag
366 robjproc = 0; // Initialize OP assembly flag
367 lsym_flag = 1; // Include local symbols in object file
368 dsym_flag = 0; // No debug sym generation by default
369 orgactive = 0; // Not in RISC org section
370 orgwarning = 0; // No ORG warning issued
371 segpadsize = 2; // Initialize segment padding size
372 dsp_orgmap[0].start = 0; // Initialize 56001 org initial address
373 dsp_orgmap[0].memtype = ORG_P; // Initialize 56001 org start segment
374 m6502 = 0; // 6502 mode off by default
375 regbase = reg68base; // Initialise DFA register tables
376 regtab = reg68tab; // Idem
377 regcheck = reg68check; // Idem
378 regaccept = reg68accept; // Idem
379 correctMathRules = 0; // respect operator precedence
380 // Initialize modules
381 InitSymbolTable(); // Symbol table
382 InitTokenizer(); // Tokenizer
383 InitLineProcessor(); // Line processor
384 InitExpression(); // Expression analyzer
385 InitSection(); // Section manager / code generator
386 InitMark(); // Mark tape-recorder
387 InitMacro(); // Macro processor
388 InitListing(); // Listing generator
389 Init6502(); // 6502 assembler
391 // Process command line arguments and assemble source files
392 for(argno=0; argno<argc; argno++)
394 if (*argv[argno] == '-')
396 switch (argv[argno][1])
399 correctMathRules = 1;
401 case 'd': // Define symbol
403 for(s=argv[argno]+2; *s!=EOS;)
412 if (argv[argno][2] == EOS)
414 printf("-d: empty symbol\n");
419 sy = lookup(argv[argno] + 2, 0, 0);
423 sy = NewSymbol(argv[argno] + 2, LABEL, 0);
427 sy->sattr = DEFINED | EQUATED | ABS;
428 sy->svalue = (*s ? (uint64_t)atoi(s) : 0);
430 case 'e': // Redirect error message output
432 err_fname = argv[argno] + 2;
434 case 'f': // -f<format>
436 switch (argv[argno][2])
439 case 'a': // -fa = Alcyon [the default]
443 case 'b': // -fb = BSD (Jaguar Recommended: 3 out 4 jaguars recommend it!)
451 case 'e': // -fe = ELF
455 case 'l': // -fl = LOD
459 case 'p': // -fp = P56
463 case 'x': // -fx = COM/EXE/XEX
467 case 'r': // -fr = Absolute address
472 printf("-f: unknown object format specified\n");
477 case 'g': // Debugging flag
481 case 'i': // Set directory search path
484 strcat(searchpatha, argv[argno] + 2);
485 strcat(searchpatha, ";");
486 searchpath = searchpatha;
488 // Check to see if include paths actually exist
489 char current_path[256];
491 for(i=current_path_index; nthpath("RMACPATH", i, current_path)!=0; i++)
493 if (strlen(current_path) > 0)
495 DIR * test = opendir(current_path);
499 printf("Invalid include path: %s\n", current_path);
508 current_path_index = i - 1;
511 case 'l': // Produce listing file
513 if (*(argv[argno] + 2) == '*')
515 list_fname = argv[argno] + 3;
516 list_pag = 0; // Special case - turn off pagination
520 list_fname = argv[argno] + 2;
529 if (strcmp(argv[argno] + 2, "68000") == 0)
531 else if (strcmp(argv[argno] + 2, "68020") == 0)
533 else if (strcmp(argv[argno] + 2, "68030") == 0)
535 else if (strcmp(argv[argno] + 2, "68040") == 0)
537 else if (strcmp(argv[argno] + 2, "68060") == 0)
539 else if (strcmp(argv[argno] + 2, "68881") == 0)
541 else if (strcmp(argv[argno] + 2, "68882") == 0)
543 else if (strcmp(argv[argno] + 2, "56001") == 0)
545 else if (strcmp(argv[argno] + 2, "6502") == 0)
547 else if (strcmp(argv[argno] + 2, "tom") == 0)
549 else if (strcmp(argv[argno] + 2, "jerry") == 0)
553 printf("Unrecognized CPU '%s'\n", argv[argno] + 2);
558 case 'o': // Direct object file output
560 if (argv[argno][2] != EOS)
561 objfname = argv[argno] + 2;
566 printf("Missing argument to -o");
571 objfname = argv[argno];
575 case 'p': /* -p: generate ".PRG" executable output */
578 * -p .PRG generation w/o symbols
579 * -ps .PRG generation with symbols
580 * -px .PRG generation with extended symbols
582 switch (argv[argno][2])
599 printf("-p: syntax error\n");
604 // Enforce Alcyon object format - kind of silly
605 // to ask for .prg output without it!
608 case 'r': // Pad seg to requested boundary size
610 switch(argv[argno][2])
612 case 'w': case 'W': segpadsize = 2; break;
613 case 'l': case 'L': segpadsize = 4; break;
614 case 'p': case 'P': segpadsize = 8; break;
615 case 'd': case 'D': segpadsize = 16; break;
616 case 'q': case 'Q': segpadsize = 32; break;
617 default: segpadsize = 2; break; // Effective autoeven();
620 case 's': // Warn about possible short branches and applied optimisations
624 case 'u': // Make undefined symbols .globl
628 case 'v': // Verbose flag
636 case 'x': // Turn on debugging
639 printf("~ Debugging ON\n");
641 case 'y': // -y<pagelen>
643 pagelen = atoi(argv[argno] + 2);
647 printf("-y: bad page length\n");
653 case EOS: // Input is stdin
654 ProcessFile(0, NULL);
656 case 'h': // Display command line usage
663 case 'n': // Turn off legacy mode
666 printf("Legacy mode OFF\n");
670 printf("Unknown switch: %s\n\n", argv[argno]);
676 else if (*argv[argno] == '+' || *argv[argno] == '~')
678 if (ParseOptimization(argv[argno]) != OK)
681 printf("Unknown switch: %s\n\n", argv[argno]);
689 strcpy(fnbuf, argv[argno]);
690 fext(fnbuf, ".s", 0);
695 printf("Cannot open: %s\n", fnbuf);
700 ProcessFile(fd, fnbuf);
704 // Wind-up processing;
705 // o save current section (no more code generation)
706 // o do auto-even of all sections (or boundary alignment as requested
708 // o save the last pc value for 6502 (if we used 6502 at all) and
709 // detemine if the last section contains anything
710 // o determine name of object file:
711 // - "foo.o" for linkable output;
712 // - "foo.prg" for GEMDOS executable (-p flag).
714 int temp_section = cursect;
716 for(i=TEXT; i<=BSS; i<<=1)
722 case 2: d_even(); break;
723 case 4: d_long(); break;
724 case 8: d_phrase(); break;
725 case 16: d_dphrase(); break;
726 case 32: d_qphrase(); break;
732 SwitchSection(M6502);
734 if (sloc != currentorg[0])
736 currentorg[1] = sloc;
740 // This looks like an awful kludge... !!! FIX !!!
741 if (temp_section & (M56001P | M56001X | M56001Y))
743 SwitchSection(temp_section);
745 if (chptr != dsp_currentorg->start)
747 dsp_currentorg->end = chptr;
754 if (objfname == NULL)
756 if (firstfname == NULL)
757 firstfname = defname;
759 strcpy(fnbuf, firstfname);
760 fext(fnbuf, (prg_flag ? ".prg" : ".o"), 1);
764 // With one pass finished, go back and:
765 // (1) run through all the fixups and resolve forward references;
766 // (1.5) ensure that remaining fixups can be handled by the linker
767 // (`lo68' format, extended (postfix) format....)
768 // (2) generate the output file image and symbol table;
769 // (3) generate relocation information from left-over fixups.
770 ResolveAllFixups(); // Do all fixups
771 StopMark(); // Stop mark tape-recorder
775 if ((fd = open(objfname, _OPEN_FLAGS, _PERM_MODE)) < 0)
776 CantCreateFile(objfname);
780 s = (prg_flag ? "executable" : "object");
781 printf("[Writing %s file: %s]\n", s, objfname);
794 printf("[Wrapping-up listing file]\n");
804 DEBUG dump_everything();
810 // Determine processor endianess
812 int GetEndianess(void)
815 char * p = (char *)&i;
824 // Application entry point
826 int main(int argc, char ** argv)
828 perm_verb_flag = 0; // Clobber "permanent" verbose flag
829 legacy_flag = 1; // Default is legacy mode on (:-P)
830 optim_flags[OPT_56K_SHORT] = 1; // This ensures compatibilty with Motorola's 56k assembler
832 cmdlnexec = argv[0]; // Obtain executable name
833 endian = GetEndianess(); // Get processor endianess
835 // If commands were passed in, process them
837 return Process(argc - 1, argv + 1);