]> git.sur5r.net Git - cc65/blob - src/da65/main.c
Move code to a subroutine.
[cc65] / src / da65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                  Main program for the da65 disassembler                   */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2006 Ullrich von Bassewitz                                       */
10 /*               Römerstrasse 52                                             */
11 /*               D-70794 Filderstadt                                         */
12 /* EMail:        uz@cc65.org                                                 */
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 <limits.h>
41 #include <time.h>
42
43 /* common */
44 #include "abend.h"
45 #include "cmdline.h"
46 #include "cpu.h"
47 #include "fname.h"
48 #include "print.h"
49 #include "version.h"
50
51 /* da65 */
52 #include "attrtab.h"
53 #include "code.h"
54 #include "comments.h"
55 #include "data.h"
56 #include "error.h"
57 #include "global.h"
58 #include "infofile.h"
59 #include "labels.h"
60 #include "opctable.h"
61 #include "output.h"
62 #include "scanner.h"
63
64
65
66 /*****************************************************************************/
67 /*                                   Code                                    */
68 /*****************************************************************************/
69
70
71
72 static void Usage (void)
73 /* Print usage information and exit */
74 {
75     printf ("Usage: %s [options] [inputfile]\n"
76             "Short options:\n"
77             "  -g\t\t\tAdd debug info to object file\n"
78             "  -h\t\t\tHelp (this text)\n"
79             "  -i name\t\tSpecify an info file\n"
80             "  -o name\t\tName the output file\n"
81             "  -v\t\t\tIncrease verbosity\n"
82             "  -F\t\t\tAdd formfeeds to the output\n"
83             "  -S addr\t\tSet the start/load address\n"
84             "  -V\t\t\tPrint the disassembler version\n"
85             "\n"
86             "Long options:\n"
87             "  --argument-column n\tSpecify argument start column\n"
88             "  --comment-column n\tSpecify comment start column\n"
89             "  --comments n\t\tSet the comment level for the output\n"
90             "  --cpu type\t\tSet cpu type\n"
91             "  --debug-info\t\tAdd debug info to object file\n"
92             "  --formfeeds\t\tAdd formfeeds to the output\n"
93             "  --help\t\tHelp (this text)\n"
94             "  --hexoffs\t\tUse hexadecimal label offsets\n"
95             "  --info name\t\tSpecify an info file\n"
96             "  --label-break n\tAdd newline if label exceeds length n\n"
97             "  --mnemonic-column n\tSpecify mnemonic start column\n"
98             "  --pagelength n\tSet the page length for the listing\n"
99             "  --start-addr addr\tSet the start/load address\n"
100             "  --text-column n\tSpecify text start column\n"
101             "  --verbose\t\tIncrease verbosity\n"
102             "  --version\t\tPrint the disassembler version\n",
103             ProgName);
104 }
105
106
107
108 static void RangeCheck (const char* Opt, unsigned long Val,
109                         unsigned long Min, unsigned long Max)
110 /* Do a range check for the given option and abort if there's a range
111  * error.
112  */
113 {
114     if (Val < Min || Val > Max) {
115         Error ("Argument for %s outside valid range (%ld-%ld)", Opt, Min, Max);
116     }
117 }
118
119
120
121 static unsigned long CvtNumber (const char* Arg, const char* Number)
122 /* Convert a number from a string. Allow '$' and '0x' prefixes for hex
123  * numbers.
124  */
125 {
126     unsigned long Val;
127     int           Converted;
128     char          BoundsCheck;
129
130     /* Convert */
131     if (*Number == '$') {
132         ++Number;
133         Converted = sscanf (Number, "%lx%c", &Val, &BoundsCheck);
134     } else {
135         Converted = sscanf (Number, "%li%c", (long*)&Val, &BoundsCheck);
136     }
137
138     /* Check if we do really have a number */
139     if (Converted != 1) {
140         Error ("Invalid number given in argument: %s\n", Arg);
141     }
142
143     /* Return the result */
144     return Val;
145 }
146
147
148
149 static void OptArgumentColumn (const char* Opt, const char* Arg)
150 /* Handle the --argument-column option */
151 {
152     /* Convert the argument to a number */
153     unsigned long Val = CvtNumber (Opt, Arg);
154
155     /* Check for a valid range */
156     RangeCheck (Opt, Val, MIN_ACOL, MAX_ACOL);
157
158     /* Use the value */
159     ACol = (unsigned char) Val;
160 }
161
162
163
164 static void OptBytesPerLine (const char* Opt, const char* Arg)
165 /* Handle the --bytes-per-line option */
166 {
167     /* Convert the argument to a number */
168     unsigned long Val = CvtNumber (Opt, Arg);
169
170     /* Check for a valid range */
171     RangeCheck (Opt, Val, MIN_BYTESPERLINE, MAX_BYTESPERLINE);
172
173     /* Use the value */
174     BytesPerLine = (unsigned char) Val;
175 }
176
177
178
179 static void OptCommentColumn (const char* Opt, const char* Arg)
180 /* Handle the --comment-column option */
181 {
182     /* Convert the argument to a number */
183     unsigned long Val = CvtNumber (Opt, Arg);
184
185     /* Check for a valid range */
186     RangeCheck (Opt, Val, MIN_CCOL, MAX_CCOL);
187
188     /* Use the value */
189     CCol = (unsigned char) Val;
190 }
191
192
193
194 static void OptComments (const char* Opt, const char* Arg)
195 /* Handle the --comments option */
196 {
197     /* Convert the argument to a number */
198     unsigned long Val = CvtNumber (Opt, Arg);
199
200     /* Check for a valid range */
201     RangeCheck (Opt, Val, MIN_COMMENTS, MAX_COMMENTS);
202
203     /* Use the value */
204     Comments = (unsigned char) Val;
205 }
206
207
208
209 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
210 /* Handle the --cpu option */
211 {
212     /* Find the CPU from the given name */
213     CPU = FindCPU (Arg);
214     SetOpcTable (CPU);
215 }
216
217
218
219 static void OptDebugInfo (const char* Opt attribute ((unused)),
220                           const char* Arg attribute ((unused)))
221 /* Add debug info to the object file */
222 {
223     DebugInfo = 1;
224 }
225
226
227
228 static void OptFormFeeds (const char* Opt attribute ((unused)),
229                           const char* Arg attribute ((unused)))
230 /* Add form feeds to the output */
231 {
232     FormFeeds = 1;
233 }
234
235
236
237 static void OptHelp (const char* Opt attribute ((unused)),
238                      const char* Arg attribute ((unused)))
239 /* Print usage information and exit */
240 {
241     Usage ();
242     exit (EXIT_SUCCESS);
243 }
244
245
246
247 static void OptHexOffs (const char* Opt attribute ((unused)),
248                         const char* Arg attribute ((unused)))
249 /* Handle the --hexoffs option */
250 {
251     UseHexOffs = 1;
252 }
253
254
255
256 static void OptInfo (const char* Opt attribute ((unused)), const char* Arg)
257 /* Handle the --info option */
258 {
259     InfoSetName (Arg);
260 }
261
262
263
264 static void OptLabelBreak (const char* Opt, const char* Arg)
265 /* Handle the --label-break option */
266 {
267     /* Convert the argument to a number */
268     unsigned long Val = CvtNumber (Opt, Arg);
269
270     /* Check for a valid range */
271     RangeCheck (Opt, Val, MIN_LABELBREAK, MAX_LABELBREAK);
272
273     /* Use the value */
274     LBreak = (unsigned char) Val;
275 }
276
277
278
279 static void OptMnemonicColumn (const char* Opt, const char* Arg)
280 /* Handle the --mnemonic-column option */
281 {
282     /* Convert the argument to a number */
283     unsigned long Val = CvtNumber (Opt, Arg);
284
285     /* Check for a valid range */
286     RangeCheck (Opt, Val, MIN_MCOL, MAX_MCOL);
287
288     /* Use the value */
289     MCol = (unsigned char) Val;
290 }
291
292
293
294 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
295 /* Handle the --pagelength option */
296 {
297     int Len = atoi (Arg);
298     if (Len != 0) {
299         RangeCheck (Opt, Len, MIN_PAGE_LEN, MAX_PAGE_LEN);
300     }
301     PageLength = Len;
302 }
303
304
305
306 static void OptStartAddr (const char* Opt, const char* Arg)
307 /* Set the default start address */
308 {
309     StartAddr = CvtNumber (Opt, Arg);
310 }
311
312
313
314 static void OptTextColumn (const char* Opt, const char* Arg)
315 /* Handle the --text-column option */
316 {
317     /* Convert the argument to a number */
318     unsigned long Val = CvtNumber (Opt, Arg);
319
320     /* Check for a valid range */
321     RangeCheck (Opt, Val, MIN_TCOL, MAX_TCOL);
322
323     /* Use the value */
324     TCol = (unsigned char) Val;
325 }
326
327
328
329 static void OptVerbose (const char* Opt attribute ((unused)),
330                         const char* Arg attribute ((unused)))
331 /* Increase verbosity */
332 {
333     ++Verbosity;
334 }
335
336
337
338 static void OptVersion (const char* Opt attribute ((unused)),
339                         const char* Arg attribute ((unused)))
340 /* Print the disassembler version */
341 {
342     fprintf (stderr,
343              "da65 V%u.%u.%u - (C) Copyright 2000-2006, Ullrich von Bassewitz\n",
344              VER_MAJOR, VER_MINOR, VER_PATCH);
345 }
346
347
348
349 static void OneOpcode (unsigned RemainingBytes)
350 /* Disassemble one opcode */
351 {
352     /* Get the opcode from the current address */
353     unsigned char OPC = GetCodeByte (PC);
354
355     /* Get the opcode description for the opcode byte */
356     const OpcDesc* D = &OpcTable[OPC];
357
358     /* Get the output style for the current PC */
359     attr_t Style = GetStyleAttr (PC);
360
361     /* If we have a label at this address, output the label and an attached
362      * comment, provided that we aren't in a skip area.
363      */
364     if (Style != atSkip && MustDefLabel (PC)) {
365         const char* Comment = GetComment (PC);
366         if (Comment) {
367             UserComment (Comment);
368         }
369         DefLabel (GetLabelName (PC));
370     }
371
372     /* Check...
373      *   - ...if we have enough bytes remaining for the code at this address.
374      *   - ...if the current instruction is valid for the given CPU.
375      *   - ...if there is no label somewhere between the instruction bytes.
376      * If any of these conditions is false, switch to data mode.
377      */
378     if (Style == atDefault) {
379         if (D->Size > RemainingBytes) {
380             Style = atIllegal;
381             MarkAddr (PC, Style);
382         } else if (D->Flags & flIllegal) {
383             Style = atIllegal;
384             MarkAddr (PC, Style);
385         } else {
386             unsigned I;
387             for (I = 1; I < D->Size; ++I) {
388                 if (HaveLabel (PC+I)) {
389                     Style = atIllegal;
390                     MarkAddr (PC, Style);
391                     break;
392                 }
393             }
394         }
395     }
396
397     /* Disassemble the line */
398     switch (Style) {
399
400         case atDefault:
401             D->Handler (D);
402             PC += D->Size;
403             break;
404
405         case atCode:
406             /* Beware: If we don't have enough bytes left to disassemble the
407              * following insn, fall through to byte mode.
408              */
409             if (D->Size <= RemainingBytes) {
410                 /* Output labels within the next insn */
411                 ForwardLabels (D->Size);
412                 /* Output the insn */
413                 D->Handler (D);
414                 PC += D->Size;
415                 break;
416             }
417             /* FALLTHROUGH */
418
419         case atByteTab:
420             ByteTable ();
421             break;
422
423         case atDByteTab:
424             DByteTable ();
425             break;
426
427         case atWordTab:
428             WordTable ();
429             break;
430
431         case atDWordTab:
432             DWordTable ();
433             break;
434
435         case atAddrTab:
436             AddrTable ();
437             break;
438
439         case atRtsTab:
440             RtsTable ();
441             break;
442
443         case atTextTab:
444             TextTable ();
445             break;
446
447         case atSkip:
448             ++PC;
449             break;
450
451         default:
452             DataByteLine (1);
453             ++PC;
454             break;
455
456     }
457 }
458
459
460
461 static void OnePass (void)
462 /* Make one pass through the code */
463 {
464     unsigned Count;
465
466     /* Disassemble until nothing left */
467     while ((Count = GetRemainingBytes()) > 0) {
468         OneOpcode (Count);
469     }
470 }
471
472
473
474 static void Disassemble (void)
475 /* Disassemble the code */
476 {
477     /* Pass 1 */
478     Pass = 1;
479     OnePass ();
480
481     Output ("---------------------------");
482     LineFeed ();
483
484     /* Pass 2 */
485     Pass = 2;
486     ResetCode ();
487     OutputSettings ();
488     DefOutOfRangeLabels ();
489     OnePass ();
490 }
491
492
493
494 int main (int argc, char* argv [])
495 /* Assembler main program */
496 {
497     /* Program long options */
498     static const LongOpt OptTab[] = {
499         { "--argument-column",  1,      OptArgumentColumn       },
500         { "--bytes-per-line",   1,      OptBytesPerLine         },
501         { "--comment-column",   1,      OptCommentColumn        },
502         { "--comments",         1,      OptComments             },
503         { "--cpu",              1,      OptCPU                  },
504         { "--debug-info",       0,      OptDebugInfo            },
505         { "--formfeeds",        0,      OptFormFeeds            },
506         { "--help",             0,      OptHelp                 },
507         { "--hexoffs",          0,      OptHexOffs              },
508         { "--info",             1,      OptInfo                 },
509         { "--label-break",      1,      OptLabelBreak           },
510         { "--mnemonic-column",  1,      OptMnemonicColumn       },
511         { "--pagelength",       1,      OptPageLength           },
512         { "--start-addr",       1,      OptStartAddr            },
513         { "--text-column",      1,      OptTextColumn           },
514         { "--verbose",          0,      OptVerbose              },
515         { "--version",          0,      OptVersion              },
516     };
517
518     unsigned I;
519     time_t T;
520
521     /* Initialize the cmdline module */
522     InitCmdLine (&argc, &argv, "da65");
523
524     /* Check the parameters */
525     I = 1;
526     while (I < ArgCount) {
527
528         /* Get the argument */
529         const char* Arg = ArgVec[I];
530
531         /* Check for an option */
532         if (Arg [0] == '-') {
533             switch (Arg [1]) {
534
535                 case '-':
536                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
537                     break;
538
539                 case 'g':
540                     OptDebugInfo (Arg, 0);
541                     break;
542
543                 case 'h':
544                     OptHelp (Arg, 0);
545                     break;
546
547                 case 'i':
548                     OptInfo (Arg, GetArg (&I, 2));
549                     break;
550
551                 case 'o':
552                     OutFile = GetArg (&I, 2);
553                     break;
554
555                 case 'v':
556                     OptVerbose (Arg, 0);
557                     break;
558
559                 case 'S':
560                     OptStartAddr (Arg, GetArg (&I, 2));
561                     break;
562
563                 case 'V':
564                     OptVersion (Arg, 0);
565                     break;
566
567                 default:
568                     UnknownOption (Arg);
569                     break;
570
571             }
572         } else {
573             /* Filename. Check if we already had one */
574             if (InFile) {
575                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
576                          ProgName, Arg);
577                 exit (EXIT_FAILURE);
578             } else {
579                 InFile = Arg;
580             }
581         }
582
583         /* Next argument */
584         ++I;
585     }
586
587     /* Try to read the info file */
588     ReadInfoFile ();
589
590     /* Must have an input file */
591     if (InFile == 0) {
592         AbEnd ("No input file");
593     }
594
595     /* Check the formatting options for reasonable values. Note: We will not
596      * really check that they make sense, just that they aren't complete
597      * garbage.
598      */
599     if (MCol >= ACol) {
600         AbEnd ("mnemonic-column value must be smaller than argument-column value");
601     }
602     if (ACol >= CCol) {
603         AbEnd ("argument-column value must be smaller than comment-column value");
604     }
605     if (CCol >= TCol) {
606         AbEnd ("comment-column value must be smaller than text-column value");
607     }
608
609     /* If no CPU given, use the default CPU */
610     if (CPU == CPU_UNKNOWN) {
611         CPU = CPU_6502;
612     }
613
614     /* Get the current time and convert it to string so it can be used in
615      * the output page headers.
616      */
617     T = time (0);
618     strftime (Now, sizeof (Now), "%Y-%m-%d %H:%M:%S", localtime (&T));
619
620     /* Load the input file */
621     LoadCode ();
622
623     /* Open the output file */
624     OpenOutput (OutFile);
625
626     /* Disassemble the code */
627     Disassemble ();
628
629     /* Close the output file */
630     CloseOutput ();
631
632     /* Done */
633     return EXIT_SUCCESS;
634 }
635
636
637