]> git.sur5r.net Git - cc65/blob - src/da65/main.c
34b48f4bb51a333ac14dab0ec8868886e9947a2f
[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             "  --comments n\t\tSet the comment level for the output\n"
88             "  --cpu type\t\tSet cpu type\n"
89             "  --debug-info\t\tAdd debug info to object file\n"
90             "  --formfeeds\t\tAdd formfeeds to the output\n"
91             "  --help\t\tHelp (this text)\n"
92             "  --hexoffs\t\tUse hexadecimal label offsets\n"
93             "  --info name\t\tSpecify an info file\n"
94             "  --label-break n\tAdd newline if label exceeds length n\n"
95             "  --pagelength n\tSet the page length for the listing\n"
96             "  --start-addr addr\tSet the start/load address\n"
97             "  --verbose\t\tIncrease verbosity\n"
98             "  --version\t\tPrint the disassembler version\n",
99             ProgName);
100 }
101
102
103
104 static unsigned long CvtNumber (const char* Arg, const char* Number)
105 /* Convert a number from a string. Allow '$' and '0x' prefixes for hex
106  * numbers.
107  */
108 {
109     unsigned long Val;
110     int           Converted;
111     char          BoundsCheck;
112
113     /* Convert */
114     if (*Number == '$') {
115         ++Number;
116         Converted = sscanf (Number, "%lx%c", &Val, &BoundsCheck);
117     } else {
118         Converted = sscanf (Number, "%li%c", (long*)&Val, &BoundsCheck);
119     }
120
121     /* Check if we do really have a number */
122     if (Converted != 1) {
123         Error ("Invalid number given in argument: %s\n", Arg);
124     }
125
126     /* Return the result */
127     return Val;
128 }
129
130
131
132 static void OptComments (const char* Opt, const char* Arg)
133 /* Handle the --comments option */
134 {
135     /* Convert the argument to a number */
136     unsigned long Val = CvtNumber (Opt, Arg);
137
138     /* Check for a valid range */
139     if (Val > MAX_COMMENTS) {
140         Error ("Argument for %s outside valid range (%d-%d)",
141                Opt, MIN_COMMENTS, MAX_COMMENTS);
142     }
143
144     /* Use the value */
145     Comments = (unsigned char) Val;
146 }
147
148
149
150 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
151 /* Handle the --cpu option */
152 {
153     /* Find the CPU from the given name */
154     CPU = FindCPU (Arg);
155     SetOpcTable (CPU);
156 }
157
158
159
160 static void OptDebugInfo (const char* Opt attribute ((unused)),
161                           const char* Arg attribute ((unused)))
162 /* Add debug info to the object file */
163 {
164     DebugInfo = 1;
165 }
166
167
168
169 static void OptFormFeeds (const char* Opt attribute ((unused)),
170                           const char* Arg attribute ((unused)))
171 /* Add form feeds to the output */
172 {
173     FormFeeds = 1;
174 }
175
176
177
178 static void OptHelp (const char* Opt attribute ((unused)),
179                      const char* Arg attribute ((unused)))
180 /* Print usage information and exit */
181 {
182     Usage ();
183     exit (EXIT_SUCCESS);
184 }
185
186
187
188 static void OptHexOffs (const char* Opt attribute ((unused)),
189                         const char* Arg attribute ((unused)))
190 /* Handle the --hexoffs option */
191 {
192     UseHexOffs = 1;
193 }
194
195
196
197 static void OptInfo (const char* Opt attribute ((unused)), const char* Arg)
198 /* Handle the --info option */
199 {
200     InfoSetName (Arg);
201 }
202
203
204
205 static void OptLabelBreak (const char* Opt, const char* Arg)
206 /* Handle the --label-break option */
207 {
208     /* Convert the argument to a number */
209     unsigned long Val = CvtNumber (Opt, Arg);
210
211     /* Check for a valid range */
212     if (Val >= UCHAR_MAX) {
213         Error ("Argument for %s out of valid range (%d)",
214                Opt, UCHAR_MAX);
215     }
216
217     /* Use the value */
218     LBreak = (unsigned char) Val;
219 }
220
221
222
223 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
224 /* Handle the --pagelength option */
225 {
226     int Len = atoi (Arg);
227     if (Len != 0 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
228         AbEnd ("Invalid page length: %d", Len);
229     }
230     PageLength = Len;
231 }
232
233
234
235 static void OptStartAddr (const char* Opt, const char* Arg)
236 /* Set the default start address */
237 {
238     StartAddr = CvtNumber (Opt, Arg);
239 }
240
241
242
243 static void OptVerbose (const char* Opt attribute ((unused)),
244                         const char* Arg attribute ((unused)))
245 /* Increase verbosity */
246 {
247     ++Verbosity;
248 }
249
250
251
252 static void OptVersion (const char* Opt attribute ((unused)),
253                         const char* Arg attribute ((unused)))
254 /* Print the disassembler version */
255 {
256     fprintf (stderr,
257              "da65 V%u.%u.%u - (C) Copyright 2000-2006, Ullrich von Bassewitz\n",
258              VER_MAJOR, VER_MINOR, VER_PATCH);
259 }
260
261
262
263 static void OneOpcode (unsigned RemainingBytes)
264 /* Disassemble one opcode */
265 {
266     /* Get the opcode from the current address */
267     unsigned char OPC = GetCodeByte (PC);
268
269     /* Get the opcode description for the opcode byte */
270     const OpcDesc* D = &OpcTable[OPC];
271
272     /* Get the output style for the current PC */
273     attr_t Style = GetStyleAttr (PC);
274
275     /* If we have a label at this address, output the label and an attached
276      * comment, provided that we aren't in a skip area.
277      */
278     if (Style != atSkip && MustDefLabel (PC)) {
279         const char* Comment = GetComment (PC);
280         if (Comment) {
281             UserComment (Comment);
282         }
283         DefLabel (GetLabelName (PC));
284     }
285
286     /* Check...
287      *   - ...if we have enough bytes remaining for the code at this address.
288      *   - ...if the current instruction is valid for the given CPU.
289      *   - ...if there is no label somewhere between the instruction bytes.
290      * If any of these conditions is false, switch to data mode.
291      */
292     if (Style == atDefault) {
293         if (D->Size > RemainingBytes) {
294             Style = atIllegal;
295             MarkAddr (PC, Style);
296         } else if (D->Flags & flIllegal) {
297             Style = atIllegal;
298             MarkAddr (PC, Style);
299         } else {
300             unsigned I;
301             for (I = 1; I < D->Size; ++I) {
302                 if (HaveLabel (PC+I)) {
303                     Style = atIllegal;
304                     MarkAddr (PC, Style);
305                     break;
306                 }
307             }
308         }
309     }
310
311     /* Disassemble the line */
312     switch (Style) {
313
314         case atDefault:
315             D->Handler (D);
316             PC += D->Size;
317             break;
318
319         case atCode:
320             /* Beware: If we don't have enough bytes left to disassemble the
321              * following insn, fall through to byte mode.
322              */
323             if (D->Size <= RemainingBytes) {
324                 /* Output labels within the next insn */
325                 unsigned I;
326                 for (I = 1; I < D->Size; ++I) {
327                     ForwardLabel (I);
328                 }
329                 D->Handler (D);
330                 PC += D->Size;
331                 break;
332             }
333             /* FALLTHROUGH */
334
335         case atByteTab:
336             ByteTable ();
337             break;
338
339         case atDByteTab:
340             DByteTable ();
341             break;
342
343         case atWordTab:
344             WordTable ();
345             break;
346
347         case atDWordTab:
348             DWordTable ();
349             break;
350
351         case atAddrTab:
352             AddrTable ();
353             break;
354
355         case atRtsTab:
356             RtsTable ();
357             break;
358
359         case atTextTab:
360             TextTable ();
361             break;
362
363         case atSkip:
364             ++PC;
365             break;
366
367         default:
368             DataByteLine (1);
369             ++PC;
370             break;
371
372     }
373 }
374
375
376
377 static void OnePass (void)
378 /* Make one pass through the code */
379 {
380     unsigned Count;
381
382     /* Disassemble until nothing left */
383     while ((Count = GetRemainingBytes()) > 0) {
384         OneOpcode (Count);
385     }
386 }
387
388
389
390 static void Disassemble (void)
391 /* Disassemble the code */
392 {
393     /* Pass 1 */
394     Pass = 1;
395     OnePass ();
396
397     Output ("---------------------------");
398     LineFeed ();
399
400     /* Pass 2 */
401     Pass = 2;
402     ResetCode ();
403     OutputSettings ();
404     DefOutOfRangeLabels ();
405     OnePass ();
406 }
407
408
409
410 int main (int argc, char* argv [])
411 /* Assembler main program */
412 {
413     /* Program long options */
414     static const LongOpt OptTab[] = {
415         { "--comments",         1,      OptComments             },
416         { "--cpu",              1,      OptCPU                  },
417         { "--debug-info",       0,      OptDebugInfo            },
418         { "--formfeeds",        0,      OptFormFeeds            },
419         { "--help",             0,      OptHelp                 },
420         { "--hexoffs",          0,      OptHexOffs              },
421         { "--info",             1,      OptInfo                 },
422         { "--label-break",      1,      OptLabelBreak           },
423         { "--pagelength",       1,      OptPageLength           },
424         { "--start-addr",       1,      OptStartAddr            },
425         { "--verbose",          0,      OptVerbose              },
426         { "--version",          0,      OptVersion              },
427     };
428
429     unsigned I;
430     time_t T;
431
432     /* Initialize the cmdline module */
433     InitCmdLine (&argc, &argv, "da65");
434
435     /* Check the parameters */
436     I = 1;
437     while (I < ArgCount) {
438
439         /* Get the argument */
440         const char* Arg = ArgVec[I];
441
442         /* Check for an option */
443         if (Arg [0] == '-') {
444             switch (Arg [1]) {
445
446                 case '-':
447                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
448                     break;
449
450                 case 'g':
451                     OptDebugInfo (Arg, 0);
452                     break;
453
454                 case 'h':
455                     OptHelp (Arg, 0);
456                     break;
457
458                 case 'i':
459                     OptInfo (Arg, GetArg (&I, 2));
460                     break;
461
462                 case 'o':
463                     OutFile = GetArg (&I, 2);
464                     break;
465
466                 case 'v':
467                     OptVerbose (Arg, 0);
468                     break;
469
470                 case 'S':
471                     OptStartAddr (Arg, GetArg (&I, 2));
472                     break;
473
474                 case 'V':
475                     OptVersion (Arg, 0);
476                     break;
477
478                 default:
479                     UnknownOption (Arg);
480                     break;
481
482             }
483         } else {
484             /* Filename. Check if we already had one */
485             if (InFile) {
486                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
487                          ProgName, Arg);
488                 exit (EXIT_FAILURE);
489             } else {
490                 InFile = Arg;
491             }
492         }
493
494         /* Next argument */
495         ++I;
496     }
497
498     /* Try to read the info file */
499     ReadInfoFile ();
500
501     /* Must have an input file */
502     if (InFile == 0) {
503         AbEnd ("No input file");
504     }
505
506     /* If no CPU given, use the default CPU */
507     if (CPU == CPU_UNKNOWN) {
508         CPU = CPU_6502;
509     }
510
511     /* Get the current time and convert it to string so it can be used in
512      * the output page headers.
513      */
514     T = time (0);
515     strftime (Now, sizeof (Now), "%Y-%m-%d %H:%M:%S", localtime (&T));
516
517     /* Load the input file */
518     LoadCode ();
519
520     /* Open the output file */
521     OpenOutput (OutFile);
522
523     /* Disassemble the code */
524     Disassemble ();
525
526     /* Close the output file */
527     CloseOutput ();
528
529     /* Done */
530     return EXIT_SUCCESS;
531 }
532
533
534