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