]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Increased the file count to 16 bits when written to the object file.
[cc65] / src / ca65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                 Main program for the ca65 macroassembler                  */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2000 Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
12 /* EMail:        uz@musoftware.de                                            */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include <time.h>
41
42 /* common */
43 #include "cmdline.h"
44 #include "version.h"
45
46 /* ca65 */
47 #include "error.h"
48 #include "expr.h"
49 #include "filetab.h"
50 #include "global.h"
51 #include "incpath.h"
52 #include "instr.h"
53 #include "istack.h"
54 #include "listing.h"
55 #include "macro.h"
56 #include "nexttok.h"
57 #include "objcode.h"
58 #include "objfile.h"
59 #include "options.h"
60 #include "pseudo.h"
61 #include "scanner.h"
62 #include "symtab.h"
63 #include "ulabel.h"
64
65
66
67 /*****************************************************************************/
68 /*                                   Code                                    */
69 /*****************************************************************************/
70
71
72
73 static void Usage (void)
74 /* Print usage information and exit */
75 {
76     fprintf (stderr,
77              "Usage: %s [options] file\n"
78              "Short options:\n"
79              "  -g\t\t\tAdd debug info to object file\n"
80              "  -h\t\t\tHelp (this text)\n"
81              "  -i\t\t\tIgnore case of symbols\n"
82              "  -l\t\t\tCreate a listing if assembly was ok\n"
83              "  -o name\t\tName the output file\n"
84              "  -s\t\t\tEnable smart mode\n"
85              "  -v\t\t\tIncrease verbosity\n"
86              "  -D name[=value]\tDefine a symbol\n"
87              "  -I dir\t\tSet an include directory search path\n"
88              "  -U\t\t\tMark unresolved symbols as import\n"
89              "  -V\t\t\tPrint the assembler version\n"
90              "  -W n\t\t\tSet warning level n\n"
91              "\n"
92              "Long options:\n"
93              "  --auto-import\t\tMark unresolved symbols as import\n"
94              "  --cpu type\t\tSet cpu type\n"
95              "  --debug-info\t\tAdd debug info to object file\n"
96              "  --help\t\tHelp (this text)\n"
97              "  --ignore-case\t\tIgnore case of symbols\n"
98              "  --include-dir dir\tSet an include directory search path\n"
99              "  --listing\t\tCreate a listing if assembly was ok\n"
100              "  --pagelength n\tSet the page length for the listing\n"
101              "  --smart\t\tEnable smart mode\n"
102              "  --verbose\t\tIncrease verbosity\n"
103              "  --version\t\tPrint the assembler version\n",
104              ProgName);
105 }
106
107
108
109 static void SetOptions (void)
110 /* Set the option for the translator */
111 {
112     char Buf [256];
113
114     /* Set the translator */
115     sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
116     OptTranslator (Buf);
117
118     /* Set date and time */
119     OptDateTime ((unsigned long) time(0));
120 }
121
122
123
124 static void DefineSymbol (const char* Def)
125 /* Define a symbol from the command line */
126 {
127     const char* P;
128     unsigned I;
129     long Val;
130     char SymName [MAX_STR_LEN+1];
131
132     /* The symbol must start with a character or underline */
133     if (Def [0] != '_' && !isalpha (Def [0])) {
134         InvDef (Def);
135     }
136     P = Def;
137
138     /* Copy the symbol, checking the rest */
139     I = 0;
140     while (isalnum (*P) || *P == '_') {
141         if (I <= MAX_STR_LEN) {
142             SymName [I++] = *P;
143         }
144         ++P;
145     }
146     SymName [I] = '\0';
147
148     /* Do we have a value given? */
149     if (*P != '=') {
150         if (*P != '\0') {
151             InvDef (Def);
152         }
153         Val = 0;
154     } else {
155         /* We have a value */
156         ++P;
157         if (*P == '$') {
158             ++P;
159             if (sscanf (P, "%lx", &Val) != 1) {
160                 InvDef (Def);
161             }
162         } else {
163             if (sscanf (P, "%li", &Val) != 1) {
164                 InvDef (Def);
165             }
166         }
167     }
168
169     /* Check if have already a symbol with this name */
170     if (SymIsDef (SymName)) {
171         fprintf (stderr, "`%s' is already defined\n", SymName);
172         exit (EXIT_FAILURE);
173     }
174
175     /* Define the symbol */
176     SymDef (SymName, LiteralExpr (Val), 0);
177 }
178
179
180
181 static void OptAutoImport (const char* Opt, const char* Arg)
182 /* Mark unresolved symbols as imported */
183 {
184     AutoImport = 1;
185 }
186
187
188
189 static void OptCPU (const char* Opt, const char* Arg)
190 /* Handle the --cpu option */
191 {
192     if (Arg == 0) {
193         NeedArg (Opt);
194     }
195     if (strcmp (Arg, "6502") == 0) {
196         SetCPU (CPU_6502);
197     } else if (strcmp (Arg, "65C02") == 0) {
198         SetCPU (CPU_65C02);
199     } else if (strcmp (Arg, "65816") == 0) {
200         SetCPU (CPU_65816);
201 #ifdef SUNPLUS
202     } else if (strcmp (Arg, "sunplus") == 0) {
203         SetCPU (CPU_SUNPLUS);
204 #endif
205     } else {
206         fprintf (stderr, "Invalid CPU: `%s'\n", Arg);
207         exit (EXIT_FAILURE);
208     }
209 }
210
211
212
213 static void OptDebugInfo (const char* Opt, const char* Arg)
214 /* Add debug info to the object file */
215 {
216     DbgSyms = 1;
217 }
218
219
220
221 static void OptHelp (const char* Opt, const char* Arg)
222 /* Print usage information and exit */
223 {
224     Usage ();
225     exit (EXIT_SUCCESS);
226 }
227
228
229
230 static void OptIgnoreCase (const char* Opt, const char* Arg)
231 /* Ignore case on symbols */
232 {
233     IgnoreCase = 1;
234 }
235
236
237
238 static void OptIncludeDir (const char* Opt, const char* Arg)
239 /* Add an include search path */
240 {
241     if (Arg == 0) {
242         NeedArg (Opt);
243     }
244     AddIncludePath (Arg);
245 }
246
247
248
249 static void OptListing (const char* Opt, const char* Arg)
250 /* Create a listing file */
251 {
252     Listing = 1;
253 }
254
255
256
257 static void OptPageLength (const char* Opt, const char* Arg)
258 /* Handle the --pagelength option */
259 {
260     int Len;
261     if (Arg == 0) {
262         NeedArg (Opt);
263     }
264     Len = atoi (Arg);
265     if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
266         fprintf (stderr, "Invalid page length: %d\n", Len);
267         exit (EXIT_FAILURE);
268     }
269     PageLength = Len;
270 }
271
272
273
274 static void OptSmart (const char* Opt, const char* Arg)
275 /* Handle the -s/--smart options */
276 {
277     SmartMode = 1;
278 }
279
280
281
282 static void OptVerbose (const char* Opt, const char* Arg)
283 /* Increase verbosity */
284 {
285     ++Verbose;
286 }
287
288
289
290 static void OptVersion (const char* Opt, const char* Arg)
291 /* Print the assembler version */
292 {
293     fprintf (stderr,
294              "ca65 V%u.%u.%u - (C) Copyright 1998-2000 Ullrich von Bassewitz\n",
295              VER_MAJOR, VER_MINOR, VER_PATCH);
296 }
297
298
299
300 static void OneLine (void)
301 /* Assemble one line */
302 {
303     char Ident [MAX_STR_LEN+1];
304     int Done = 0;
305
306     /* Initialize the new listing line if we are actually reading from file
307      * and not from internally pushed input.
308      */
309     if (!HavePushedInput ()) {
310         InitListingLine ();
311     }
312
313     if (Tok == TOK_COLON) {
314         /* An unnamed label */
315         ULabDef ();
316         NextTok ();
317     }
318
319     /* Assemble the line */
320     if (Tok == TOK_IDENT) {
321
322         /* Is it a macro? */
323         if (IsMacro (SVal)) {
324
325             /* Yes, start a macro expansion */
326             MacExpandStart ();
327             Done = 1;
328
329         } else {
330
331             /* No, label. Remember the identifier, then skip it */
332             int HadWS = WS;     /* Did we have whitespace before the ident? */
333             strcpy (Ident, SVal);
334             NextTok ();
335
336             /* If a colon follows, this is a label definition. If there
337              * is no colon, it's an assignment.
338              */
339             if (Tok == TOK_EQ) {
340                 /* Skip the '=' */
341                 NextTok ();
342                 /* Define the symbol with the expression following the '=' */
343                 SymDef (Ident, Expression (), 0);
344                 /* Don't allow anything after a symbol definition */
345                 Done = 1;
346             } else {
347                 /* Define a label */
348                 SymDef (Ident, CurrentPC (), IsZPSeg ());
349                 /* Skip the colon. If NoColonLabels is enabled, allow labels
350                  * without a colon if there is no whitespace before the
351                  * identifier.
352                  */
353                 if (Tok != TOK_COLON) {
354                     if (HadWS || !NoColonLabels) {
355                         Error (ERR_COLON_EXPECTED);
356                     }
357                     if (Tok == TOK_NAMESPACE) {
358                         /* Smart :: handling */
359                         NextTok ();
360                     }
361                 } else {
362                     /* Skip the colon */
363                     NextTok ();
364                 }
365             }
366         }
367     }
368
369     if (!Done) {
370
371         if (TokIsPseudo (Tok)) {
372             /* A control command, IVal is index into table */
373             HandlePseudo ();
374         } else if (Tok == TOK_MNEMO) {
375             /* A mnemonic - assemble one instruction */
376             HandleInstruction (IVal);
377         } else if (Tok == TOK_IDENT && IsMacro (SVal)) {
378             /* A macro expansion */
379             MacExpandStart ();
380         }
381     }
382
383     /* Line separator must come here */
384     ConsumeSep ();
385 }
386
387
388
389 static void Assemble (void)
390 /* Start the ball rolling ... */
391 {
392     /* Prime the pump */
393     NextTok ();
394
395     /* Assemble lines until end of file */
396     while (Tok != TOK_EOF) {
397         OneLine ();
398     }
399 }
400
401
402
403 static void CreateObjFile (void)
404 /* Create the object file */
405 {
406     /* Open the object, write the header */
407     ObjOpen ();
408
409     /* Write the object file options */
410     WriteOptions ();
411
412     /* Write the list of input files */
413     WriteFiles ();
414
415     /* Write the segment data to the file */
416     WriteSegments ();
417
418     /* Write the import list */
419     WriteImports ();
420
421     /* Write the export list */
422     WriteExports ();
423
424     /* Write debug symbols if requested */
425     WriteDbgSyms ();
426
427     /* Write an updated header and close the file */
428     ObjClose ();
429 }
430
431
432
433 int main (int argc, char* argv [])
434 /* Assembler main program */
435 {
436     /* Program long options */
437     static const LongOpt OptTab[] = {
438         { "--auto-import",      0,      OptAutoImport           },
439         { "--cpu",              1,      OptCPU                  },
440         { "--debug-info",       0,      OptDebugInfo            },
441         { "--help",             0,      OptHelp                 },
442         { "--ignore-case",      0,      OptIgnoreCase           },
443         { "--include-dir",      1,      OptIncludeDir           },
444         { "--listing",          0,      OptListing              },
445         { "--pagelength",       1,      OptPageLength           },
446         { "--smart",            0,      OptSmart                },
447         { "--verbose",          0,      OptVerbose              },
448         { "--version",          0,      OptVersion              },
449     };
450
451     int I;
452
453     /* Initialize the cmdline module */
454     InitCmdLine (argc, argv, "ca65");
455
456     /* Enter the base lexical level. We must do that here, since we may
457      * define symbols using -D.
458      */
459     SymEnterLevel ();
460
461     /* Check the parameters */
462     I = 1;
463     while (I < argc) {
464
465         /* Get the argument */
466         const char* Arg = argv [I];
467
468         /* Check for an option */
469         if (Arg [0] == '-') {
470             switch (Arg [1]) {
471
472                 case '-':
473                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
474                     break;
475
476                 case 'g':
477                     OptDebugInfo (Arg, 0);
478                     break;
479
480                 case 'h':
481                     OptHelp (Arg, 0);
482                     break;
483
484                 case 'i':
485                     OptIgnoreCase (Arg, 0);
486                     break;
487
488                 case 'l':
489                     OptListing (Arg, 0);
490                     break;
491
492                 case 'o':
493                     OutFile = GetArg (&I, 2);
494                     break;
495
496                 case 's':
497                     OptSmart (Arg, 0);
498                     break;
499
500                 case 'v':
501                     OptVerbose (Arg, 0);
502                     break;
503
504                 case 'D':
505                     DefineSymbol (GetArg (&I, 2));
506                     break;
507
508                 case 'I':
509                     OptIncludeDir (Arg, GetArg (&I, 2));
510                     break;
511
512                 case 'U':
513                     OptAutoImport (Arg, 0);
514                     break;
515
516                 case 'V':
517                     OptVersion (Arg, 0);
518                     break;
519
520                 case 'W':
521                     WarnLevel = atoi (GetArg (&I, 2));
522                     break;
523
524                 default:
525                     UnknownOption (Arg);
526                     break;
527
528             }
529         } else {
530             /* Filename. Check if we already had one */
531             if (InFile) {
532                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
533                          ProgName, Arg);
534                 exit (EXIT_FAILURE);
535             } else {
536                 InFile = Arg;
537             }
538         }
539
540         /* Next argument */
541         ++I;
542     }
543
544     /* Do we have an input file? */
545     if (InFile == 0) {
546         fprintf (stderr, "%s: No input files\n", ProgName);
547         exit (EXIT_FAILURE);
548     }
549
550     /* Initialize the scanner, open the input file */
551     InitScanner (InFile);
552
553     /* Define the default options */
554     SetOptions ();
555
556     /* Assemble the input */
557     Assemble ();
558
559     /* If we didn't have any errors, check the unnamed labels */
560     if (ErrorCount == 0) {
561         ULabCheck ();
562     }
563
564     /* If we didn't have any errors, check the symbol table */
565     if (ErrorCount == 0) {
566         SymCheck ();
567     }
568
569     /* If we didn't have any errors, check and resolve the segment data */
570     if (ErrorCount == 0) {
571         SegCheck ();
572     }
573
574     /* Dump the data */
575     if (Verbose >= 2) {
576         SymDump (stdout);
577         SegDump ();
578     }
579
580     /* If we didn't have any errors, create the object and listing files */
581     if (ErrorCount == 0) {
582         CreateObjFile ();
583         if (Listing) {
584             CreateListing ();
585         }
586     }
587
588     /* Close the input file */
589     DoneScanner ();
590
591     /* Return an apropriate exit code */
592     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
593 }
594
595
596