]> git.sur5r.net Git - cc65/blob - src/da65/main.c
Merge branch 'master' into kbrepeat
[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
354     /* Get the opcode from the current address */
355     unsigned char OPC = GetCodeByte (PC);
356
357     /* Get the opcode description for the opcode byte */
358     const OpcDesc* D = &OpcTable[OPC];
359
360     /* Get the output style for the current PC */
361     attr_t Style = GetStyleAttr (PC);
362
363     /* If a segment begins here, then name that segment.
364     ** Note that the segment is named even if its code is being skipped,
365     ** because some of its later code might not be skipped.
366     */
367     if (IsSegmentStart (PC)) {
368         StartSegment (GetSegmentStartName (PC), GetSegmentAddrSize (PC));
369     }
370
371     /* If we have a label at this address, output the label and an attached
372     ** comment, provided that we aren't in a skip area.
373     */
374     if (Style != atSkip && MustDefLabel (PC)) {
375         const char* Comment = GetComment (PC);
376         if (Comment) {
377             UserComment (Comment);
378         }
379         DefLabel (GetLabelName (PC));
380     }
381
382     /* Check...
383     **   - ...if we have enough bytes remaining for the code at this address.
384     **   - ...if the current instruction is valid for the given CPU.
385     **   - ...if there is no label somewhere between the instruction bytes.
386     **   - ...if there is no segment change between the instruction bytes.
387     ** If any one of those conditions is false, switch to data mode.
388     */
389     if (Style == atDefault) {
390         if (D->Size > RemainingBytes) {
391             Style = atIllegal;
392             MarkAddr (PC, Style);
393         } else if (D->Flags & flIllegal) {
394             Style = atIllegal;
395             MarkAddr (PC, Style);
396         } else {
397             for (I = PC + D->Size; --I > PC; ) {
398                 if (HaveLabel (I) || IsSegmentStart (I)) {
399                     Style = atIllegal;
400                     MarkAddr (PC, Style);
401                     break;
402                 }
403             }
404             for (I = 0; I < D->Size - 1u; ++I) {
405                 if (IsSegmentEnd (PC + I)) {
406                     Style = atIllegal;
407                     MarkAddr (PC, Style);
408                     break;
409                 }
410             }
411         }
412     }
413
414     /* Disassemble the line */
415     switch (Style) {
416
417         case atDefault:
418             D->Handler (D);
419             PC += D->Size;
420             break;
421
422         case atCode:
423             /* Beware: If we don't have enough bytes left to disassemble the
424             ** following insn, fall through to byte mode.
425             */
426             if (D->Size <= RemainingBytes) {
427                 /* Output labels within the next insn */
428                 for (I = 1; I < D->Size; ++I) {
429                     ForwardLabel (I);
430                 }
431                 /* Output the insn */
432                 D->Handler (D);
433                 PC += D->Size;
434                 break;
435             }
436             /* FALLTHROUGH */
437
438         case atByteTab:
439             ByteTable ();
440             break;
441
442         case atDByteTab:
443             DByteTable ();
444             break;
445
446         case atWordTab:
447             WordTable ();
448             break;
449
450         case atDWordTab:
451             DWordTable ();
452             break;
453
454         case atAddrTab:
455             AddrTable ();
456             break;
457
458         case atRtsTab:
459             RtsTable ();
460             break;
461
462         case atTextTab:
463             TextTable ();
464             break;
465
466         case atSkip:
467             ++PC;
468             break;
469
470         default:
471             DataByteLine (1);
472             ++PC;
473             break;
474     }
475
476     /* Change back to the default CODE segment if
477     ** a named segment stops at the current address.
478     */
479     for (I = D->Size; I >= 1; --I) {
480         if (IsSegmentEnd (PC - I)) {
481             EndSegment ();
482             break;
483         }
484     }
485 }
486
487
488
489 static void OnePass (void)
490 /* Make one pass through the code */
491 {
492     unsigned Count;
493
494     /* Disassemble until nothing left */
495     while ((Count = GetRemainingBytes()) > 0) {
496         OneOpcode (Count);
497     }
498 }
499
500
501
502 static void Disassemble (void)
503 /* Disassemble the code */
504 {
505     /* Pass 1 */
506     Pass = 1;
507     OnePass ();
508
509     Output ("---------------------------");
510     LineFeed ();
511
512     /* Pass 2 */
513     Pass = 2;
514     ResetCode ();
515     OutputSettings ();
516     DefOutOfRangeLabels ();
517     OnePass ();
518 }
519
520
521
522 int main (int argc, char* argv [])
523 /* Assembler main program */
524 {
525     /* Program long options */
526     static const LongOpt OptTab[] = {
527         { "--argument-column",  1,      OptArgumentColumn       },
528         { "--bytes-per-line",   1,      OptBytesPerLine         },
529         { "--comment-column",   1,      OptCommentColumn        },
530         { "--comments",         1,      OptComments             },
531         { "--cpu",              1,      OptCPU                  },
532         { "--debug-info",       0,      OptDebugInfo            },
533         { "--formfeeds",        0,      OptFormFeeds            },
534         { "--help",             0,      OptHelp                 },
535         { "--hexoffs",          0,      OptHexOffs              },
536         { "--info",             1,      OptInfo                 },
537         { "--label-break",      1,      OptLabelBreak           },
538         { "--mnemonic-column",  1,      OptMnemonicColumn       },
539         { "--pagelength",       1,      OptPageLength           },
540         { "--start-addr",       1,      OptStartAddr            },
541         { "--text-column",      1,      OptTextColumn           },
542         { "--verbose",          0,      OptVerbose              },
543         { "--version",          0,      OptVersion              },
544     };
545
546     unsigned I;
547     time_t T;
548
549     /* Initialize the cmdline module */
550     InitCmdLine (&argc, &argv, "da65");
551
552     /* Check the parameters */
553     I = 1;
554     while (I < ArgCount) {
555
556         /* Get the argument */
557         const char* Arg = ArgVec[I];
558
559         /* Check for an option */
560         if (Arg [0] == '-') {
561             switch (Arg [1]) {
562
563                 case '-':
564                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
565                     break;
566
567                 case 'g':
568                     OptDebugInfo (Arg, 0);
569                     break;
570
571                 case 'h':
572                     OptHelp (Arg, 0);
573                     break;
574
575                 case 'i':
576                     OptInfo (Arg, GetArg (&I, 2));
577                     break;
578
579                 case 'o':
580                     OutFile = GetArg (&I, 2);
581                     break;
582
583                 case 'v':
584                     OptVerbose (Arg, 0);
585                     break;
586
587                 case 'S':
588                     OptStartAddr (Arg, GetArg (&I, 2));
589                     break;
590
591                 case 'V':
592                     OptVersion (Arg, 0);
593                     break;
594
595                 default:
596                     UnknownOption (Arg);
597                     break;
598
599             }
600         } else {
601             /* Filename. Check if we already had one */
602             if (InFile) {
603                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
604                          ProgName, Arg);
605                 exit (EXIT_FAILURE);
606             } else {
607                 InFile = Arg;
608             }
609         }
610
611         /* Next argument */
612         ++I;
613     }
614
615     /* Try to read the info file */
616     ReadInfoFile ();
617
618     /* Must have an input file */
619     if (InFile == 0) {
620         AbEnd ("No input file");
621     }
622
623     /* Check the formatting options for reasonable values. Note: We will not
624     ** really check that they make sense, just that they aren't complete
625     ** garbage.
626     */
627     if (MCol >= ACol) {
628         AbEnd ("mnemonic-column value must be smaller than argument-column value");
629     }
630     if (ACol >= CCol) {
631         AbEnd ("argument-column value must be smaller than comment-column value");
632     }
633     if (CCol >= TCol) {
634         AbEnd ("comment-column value must be smaller than text-column value");
635     }
636
637     /* If no CPU given, use the default CPU */
638     if (CPU == CPU_UNKNOWN) {
639         CPU = CPU_6502;
640     }
641
642     /* Get the current time and convert it to string so it can be used in
643     ** the output page headers.
644     */
645     T = time (0);
646     strftime (Now, sizeof (Now), "%Y-%m-%d %H:%M:%S", localtime (&T));
647
648     /* Load the input file */
649     LoadCode ();
650
651     /* Open the output file */
652     OpenOutput (OutFile);
653
654     /* Disassemble the code */
655     Disassemble ();
656
657     /* Close the output file */
658     CloseOutput ();
659
660     /* Done */
661     return EXIT_SUCCESS;
662 }