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