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
65 uint32_t used_architectures; // Bitmask that records exactly which architectures were used during assembly
68 // Convert a string to uppercase
70 void strtoupper(char * s)
77 // Manipulate file extension.
79 // 'name' must be large enough to hold any possible filename. If 'stripp' is
80 // nonzero, any old extension is removed. If the file does not already have an
81 // extension, 'extension' is appended to the filename.
83 char * fext(char * name, char * extension, int stripp)
87 // Find beginning of "real" name (strip off path)
88 char * beg = strrchr(name, SLASHCHAR);
93 // Clobber any old extension, if requested
96 for(s=beg; *s && *s!='.'; ++s)
102 if (strrchr(beg, '.') == NULL)
103 strcat(beg, extension);
108 static int is_sep(char c)
110 const char *seps = PATH_SEPS;
112 for (seps = PATH_SEPS; *seps; seps++) {
121 // Return 'item'nth element of semicolon-seperated pathnames specified in the
122 // enviroment string 's'. Copy the pathname to 'buf'. Return 0 if the 'item'
123 // nth path doesn't exist.
125 // ['item' ranges from 0 to N-1, where N = #elements in search path]
127 int nthpath(char * env_var, int itemno, char * buf)
129 char * s = searchpath;
138 while (*s != EOS && !is_sep(*s++))
144 while (*s != EOS && !is_sep(*s))
153 // Display command line help
155 void DisplayHelp(void)
158 " %s [options] srcfile\n"
161 " -? or -h Display usage information\n"
162 " -dsymbol[=value] Define symbol (with optional value, default=0)\n"
163 " -e[errorfile] Send error messages to file, not stdout\n"
164 " -f[format] Output object file format\n"
166 " b: BSD (use this for Jaguar)\n"
169 " p: P56 (use this for DSP56001 only)\n"
170 " l: LOD (use this for DSP56001 only)\n"
171 " x: com/exe/xex (Atari 800)\n"
172 " r: absolute address\n"
173 " -g Output source level debug information (BSD object only)\n"
174 " -i[path] Directory to search for include files\n"
175 " -l[filename] Create an output listing file\n"
176 " -l*[filename] Create an output listing file without pagination\n"
177 " -m[cpu] Select default CPU. Available options:\n"
178 " 68000, 68020, 68030, 68040, 68060, 6502, tom, jerry, 56001\n"
179 " -n Don't do things behind your back in RISC assembler\n"
180 " -o file Output file name\n"
181 " +o[value] Turn a specific optimisation on\n"
182 " Available optimisation switches:\n"
183 " o0: Absolute long addresses to word\n"
184 " o1: move.l #x,dn/an to moveq\n"
185 " o2: Word branches to short\n"
186 " o3: Outer displacement 0(an) to (an)\n"
187 " o4: lea size(An),An to addq #size,An\n"
188 " o5: 68020+ Absolute long base/outer disp. to word\n"
189 " o6: Null branches to NOP\n"
190 " o7: clr.l Dx to moveq #0,Dx\n"
191 " o8: adda.w/l #x,Dy to addq.w/l #x,Dy\n"
192 " o9: adda.w/l #x,Ay to lea x(Dy),Ay\n"
193 " o10: 56001 Use short format for immediate values if possible\n"
194 " o11: 56001 Auto convert short addressing mode to long (default: on)\n"
195 " o30: Enforce PC relative (alternative name: op)\n"
196 " ~o[value] Turn a specific optimisation off\n"
197 " +oall Turn all optimisations on\n"
198 " ~oall Turn all optimisations off\n"
199 " -p Create an ST .prg (without symbols). Forces -fa\n"
200 " -ps Create an ST .prg (with symbols). Forces -fa\n"
201 " -px Create an ST .prg (with exsymbols). Forces -fa\n"
202 " -r[size] Pad segments to boundary size specified\n"
203 " w: word (2 bytes, default alignment)\n"
204 " l: long (4 bytes)\n"
205 " p: phrase (8 bytes)\n"
206 " d: double phrase (16 bytes)\n"
207 " q: quad phrase (32 bytes)\n"
208 " -s Warn about possible short branches\n"
209 " and applied optimisations\n"
210 " -u Force referenced and undefined symbols global\n"
211 " -v Set verbose mode\n"
212 " -x Turn on debugging mode\n"
213 " -y[pagelen] Set page line length (default: 61)\n"
214 " -4 Use C style operator precedence\n"
220 // Display version information
222 void DisplayVersion(void)
225 " _ __ _ __ ___ __ _ ___ \n"
226 "| '__| '_ ` _ \\ / _` |/ __|\n"
227 "| | | | | | | | (_| | (__ \n"
228 "|_| |_| |_| |_|\\__,_|\\___|\n"
229 "\nRenamed Macro Assembler\n"
230 "Copyright (C) 199x Landon Dyer, 2011-2022 Reboot and Friends\n"
231 "V%01i.%01i.%01i %s (%s)\n\n", MAJOR, MINOR, PATCH, __DATE__, PLATFORM);
235 // Parse optimisation options
237 int ParseOptimization(char * optstring)
243 if (*optstring == '+')
245 else if (*optstring != '~')
248 if (optstring[2] == 0)
249 return error(".opt called with zero arguments");
251 if ((optstring[2] == 'a' || optstring[2] == 'A')
252 && (optstring[3] == 'l' || optstring[3] == 'L')
253 && (optstring[4] == 'l' || optstring[4] == 'L'))
255 memset(optim_flags, onoff, OPT_COUNT * sizeof(int));
258 else if (optstring[1] == 'o' || optstring[1] == 'O') // Turn on specific optimisation
260 if (optstring[2] == 'p' || optstring[2] == 'P')
262 optim_flags[OPT_PC_RELATIVE] = onoff;
267 int opt_no = atoi(&optstring[2]);
269 if ((opt_no >= 0) && (opt_no < OPT_COUNT))
271 optim_flags[opt_no] = onoff;
274 // If opt_no is 2 digits then consume an extra character.
275 // Sounds a bit sleazy but we know we're not going to hit
276 // more than 100 optimisation switches so this should be
277 // fine. If we do hit that number then it'll probably be
278 // time to burn the whole codebase and start from scratch.
291 if (*optstring == ',')
297 static void ProcessFile(int fd, char *fname)
299 char *dbgname = fname;
303 fname = defname; // Kludge first filename
307 // First file operations:
308 if (firstfname == NULL)
310 // Record first filename.
313 // Validate option compatibility
316 if (obj_format != BSD)
318 printf("-g: debug information only supported with BSD object file format\n");
324 GenMainFileSym(dbgname);
329 include(fd, dbgname);
333 extern int reg68base[53];
334 extern int reg68tab[222];
335 extern int reg68check[222];
336 extern int reg68accept[222];
339 // Process command line arguments and do an assembly
341 int Process(int argc, char ** argv)
343 int argno; // Argument number
344 SYM * sy; // Pointer to a symbol record
345 char * s; // String pointer
346 int fd; // File descriptor
347 char fnbuf[FNSIZ]; // Filename buffer
349 int current_path_index = 0; // Iterator for search paths
351 errcnt = 0; // Initialize error count
352 listing = 0; // Initialize listing level
353 list_flag = 0; // Initialize listing flag
354 verb_flag = perm_verb_flag; // Initialize verbose flag
355 glob_flag = 0; // Initialize .globl flag
356 optim_warn_flag = 0; // Initialize short branch flag
357 debug = 0; // Initialize debug flag
358 objfname = NULL; // Initialize object filename
359 list_fname = NULL; // Initialize listing filename
360 err_fname = NULL; // Initialize error filename
361 obj_format = BSD; // Initialize object format
362 firstfname = NULL; // Initialize first filename
363 err_fd = ERROUT; // Initialize error file descriptor
364 err_flag = 0; // Initialize error flag
365 rgpu = 0; // Initialize GPU assembly flag
366 rdsp = 0; // Initialize DSP assembly flag
367 robjproc = 0; // Initialize OP assembly flag
368 lsym_flag = 1; // Include local symbols in object file
369 dsym_flag = 0; // No debug sym generation by default
370 orgactive = 0; // Not in RISC org section
371 orgwarning = 0; // No ORG warning issued
372 segpadsize = 2; // Initialize segment padding size
373 dsp_orgmap[0].start = 0; // Initialize 56001 org initial address
374 dsp_orgmap[0].memtype = ORG_P; // Initialize 56001 org start segment
375 m6502 = 0; // 6502 mode off by default
376 regbase = reg68base; // Initialise DFA register tables
377 regtab = reg68tab; // Idem
378 regcheck = reg68check; // Idem
379 regaccept = reg68accept; // Idem
380 correctMathRules = 0; // respect operator precedence
381 used_architectures = 0; // Initialise used architectures bitfield
382 // Initialize modules
383 InitSymbolTable(); // Symbol table
384 InitTokenizer(); // Tokenizer
385 InitLineProcessor(); // Line processor
386 InitExpression(); // Expression analyzer
387 InitSection(); // Section manager / code generator
388 InitMark(); // Mark tape-recorder
389 InitMacro(); // Macro processor
390 InitListing(); // Listing generator
391 Init6502(); // 6502 assembler
393 // Process command line arguments and assemble source files
394 for(argno=0; argno<argc; argno++)
396 if (*argv[argno] == '-')
398 switch (argv[argno][1])
401 correctMathRules = 1;
403 case 'd': // Define symbol
405 for(s=argv[argno]+2; *s!=EOS;)
414 if (argv[argno][2] == EOS)
416 printf("-d: empty symbol\n");
421 sy = lookup(argv[argno] + 2, 0, 0);
425 sy = NewSymbol(argv[argno] + 2, LABEL, 0);
429 sy->sattr = DEFINED | EQUATED | ABS;
430 sy->svalue = (*s ? (uint64_t)atoi(s) : 0);
432 case 'e': // Redirect error message output
434 err_fname = argv[argno] + 2;
436 case 'f': // -f<format>
438 switch (argv[argno][2])
441 case 'a': // -fa = Alcyon [the default]
445 case 'b': // -fb = BSD (Jaguar Recommended: 3 out 4 jaguars recommend it!)
453 case 'e': // -fe = ELF
457 case 'l': // -fl = LOD
461 case 'p': // -fp = P56
465 case 'x': // -fx = COM/EXE/XEX
469 case 'r': // -fr = Absolute address
474 printf("-f: unknown object format specified\n");
479 case 'g': // Debugging flag
483 case 'i': // Set directory search path
486 strcat(searchpatha, argv[argno] + 2);
487 strcat(searchpatha, ";");
488 searchpath = searchpatha;
490 // Check to see if include paths actually exist
491 char current_path[256];
493 for(i=current_path_index; nthpath("RMACPATH", i, current_path)!=0; i++)
495 if (strlen(current_path) > 0)
497 DIR * test = opendir(current_path);
501 printf("Invalid include path: %s\n", current_path);
510 current_path_index = i - 1;
513 case 'l': // Produce listing file
515 if (*(argv[argno] + 2) == '*')
517 list_fname = argv[argno] + 3;
518 list_pag = 0; // Special case - turn off pagination
522 list_fname = argv[argno] + 2;
531 if (strcmp(argv[argno] + 2, "68000") == 0)
533 else if (strcmp(argv[argno] + 2, "68020") == 0)
535 else if (strcmp(argv[argno] + 2, "68030") == 0)
537 else if (strcmp(argv[argno] + 2, "68040") == 0)
539 else if (strcmp(argv[argno] + 2, "68060") == 0)
541 else if (strcmp(argv[argno] + 2, "68881") == 0)
543 else if (strcmp(argv[argno] + 2, "68882") == 0)
545 else if (strcmp(argv[argno] + 2, "56001") == 0)
547 else if (strcmp(argv[argno] + 2, "6502") == 0)
549 else if (strcmp(argv[argno] + 2, "tom") == 0)
551 else if (strcmp(argv[argno] + 2, "jerry") == 0)
555 printf("Unrecognized CPU '%s'\n", argv[argno] + 2);
560 case 'o': // Direct object file output
562 if (argv[argno][2] != EOS)
563 objfname = argv[argno] + 2;
568 printf("Missing argument to -o");
573 objfname = argv[argno];
577 case 'p': /* -p: generate ".PRG" executable output */
580 * -p .PRG generation w/o symbols
581 * -ps .PRG generation with symbols
582 * -px .PRG generation with extended symbols
584 switch (argv[argno][2])
601 printf("-p: syntax error\n");
606 // Enforce Alcyon object format - kind of silly
607 // to ask for .prg output without it!
610 case 'r': // Pad seg to requested boundary size
612 switch(argv[argno][2])
614 case 'w': case 'W': segpadsize = 2; break;
615 case 'l': case 'L': segpadsize = 4; break;
616 case 'p': case 'P': segpadsize = 8; break;
617 case 'd': case 'D': segpadsize = 16; break;
618 case 'q': case 'Q': segpadsize = 32; break;
619 default: segpadsize = 2; break; // Effective autoeven();
622 case 's': // Warn about possible short branches and applied optimisations
626 case 'u': // Make undefined symbols .globl
630 case 'v': // Verbose flag
638 case 'x': // Turn on debugging
641 printf("~ Debugging ON\n");
643 case 'y': // -y<pagelen>
645 pagelen = atoi(argv[argno] + 2);
649 printf("-y: bad page length\n");
655 case EOS: // Input is stdin
656 ProcessFile(0, NULL);
658 case 'h': // Display command line usage
665 case 'n': // Turn off legacy mode
668 printf("Legacy mode OFF\n");
672 printf("Unknown switch: %s\n\n", argv[argno]);
678 else if (*argv[argno] == '+' || *argv[argno] == '~')
680 if (ParseOptimization(argv[argno]) != OK)
683 printf("Unknown switch: %s\n\n", argv[argno]);
691 strcpy(fnbuf, argv[argno]);
692 fext(fnbuf, ".s", 0);
697 printf("Cannot open: %s\n", fnbuf);
702 ProcessFile(fd, fnbuf);
706 // Wind-up processing;
707 // o save current section (no more code generation)
708 // o do auto-even of all sections (or boundary alignment as requested
710 // o save the last pc value for 6502 (if we used 6502 at all) and
711 // detemine if the last section contains anything
712 // o determine name of object file:
713 // - "foo.o" for linkable output;
714 // - "foo.prg" for GEMDOS executable (-p flag).
716 int temp_section = cursect;
718 for(i=TEXT; i<=BSS; i<<=1)
724 case 2: d_even(); break;
725 case 4: d_long(); break;
726 case 8: d_phrase(); break;
727 case 16: d_dphrase(); break;
728 case 32: d_qphrase(); break;
734 SwitchSection(M6502);
736 if (sloc != currentorg[0])
738 currentorg[1] = sloc;
742 // This looks like an awful kludge... !!! FIX !!!
743 if (temp_section & (M56001P | M56001X | M56001Y))
745 SwitchSection(temp_section);
747 if (chptr != dsp_currentorg->start)
749 dsp_currentorg->end = chptr;
756 if (objfname == NULL)
758 if (firstfname == NULL)
759 firstfname = defname;
761 // It's the size of fnbuf minus 5 because of the possible 4 char suffix
762 // + trailing null (added by fext()).
763 strncpy(fnbuf, firstfname, sizeof(fnbuf) - 5);
764 fext(fnbuf, (prg_flag ? ".prg" : ".o"), 1);
768 // With one pass finished, go back and:
769 // (1) run through all the fixups and resolve forward references;
770 // (1.5) ensure that remaining fixups can be handled by the linker
771 // (`lo68' format, extended (postfix) format....)
772 // (2) generate the output file image and symbol table;
773 // (3) generate relocation information from left-over fixups.
774 ResolveAllFixups(); // Do all fixups
775 StopMark(); // Stop mark tape-recorder
779 if ((fd = open(objfname, _OPEN_FLAGS, _PERM_MODE)) < 0)
780 CantCreateFile(objfname);
784 s = (prg_flag ? "executable" : "object");
785 printf("[Writing %s file: %s]\n", s, objfname);
798 printf("[Wrapping-up listing file]\n");
808 DEBUG dump_everything();
814 // Determine processor endianess
816 int GetEndianess(void)
819 char * p = (char *)&i;
828 // Application entry point
830 int main(int argc, char ** argv)
832 perm_verb_flag = 0; // Clobber "permanent" verbose flag
833 legacy_flag = 1; // Default is legacy mode on (:-P)
834 optim_flags[OPT_56K_SHORT] = 1; // This ensures compatibilty with Motorola's 56k assembler
836 cmdlnexec = argv[0]; // Obtain executable name
837 endian = GetEndianess(); // Get processor endianess
839 // If commands were passed in, process them
841 return Process(argc - 1, argv + 1);