]> git.sur5r.net Git - cc65/blob - src/cc65/compile.c
Fixed a buffer overflow (report from Christian Groessler).
[cc65] / src / cc65 / compile.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 compile.c                                 */
4 /*                                                                           */
5 /*                       Top level compiler subroutine                       */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2002 Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
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 <stdlib.h>
37 #include <time.h>
38
39 /* common */
40 #include "version.h"
41 #include "xmalloc.h"
42 #include "xsprintf.h"
43
44 /* cc65 */
45 #include "asmlabel.h"
46 #include "asmstmt.h"
47 #include "codegen.h"
48 #include "declare.h"
49 #include "error.h"
50 #include "expr.h"
51 #include "function.h"
52 #include "global.h"
53 #include "incpath.h"
54 #include "input.h"
55 #include "litpool.h"
56 #include "macrotab.h"
57 #include "pragma.h"
58 #include "symtab.h"
59 #include "compile.h"
60
61
62
63 /*****************************************************************************/
64 /*                                   Code                                    */
65 /*****************************************************************************/
66
67
68
69 static void Parse (void)
70 /* Top level parser routine. */
71 {
72     int comma;
73     SymEntry* Entry;
74
75     /* Go... */
76     NextToken ();
77     NextToken ();
78
79     /* Parse until end of input */
80     while (CurTok.Tok != TOK_CEOF) {
81
82         DeclSpec        Spec;
83         Declaration     Decl;
84         int             NeedStorage;
85
86         /* Check for empty statements */
87         if (CurTok.Tok == TOK_SEMI) {
88             NextToken ();
89             continue;
90         }
91
92         /* Check for an ASM statement (which is allowed also on global level) */
93         if (CurTok.Tok == TOK_ASM) {
94             AsmStatement ();
95             ConsumeSemi ();
96             continue;
97         }
98
99         /* Check for a #pragma */
100         if (CurTok.Tok == TOK_PRAGMA) {
101             DoPragma ();
102             continue;
103         }
104
105         /* Read variable defs and functions */
106         ParseDeclSpec (&Spec, SC_EXTERN | SC_STATIC, T_INT);
107
108         /* Don't accept illegal storage classes */
109         if (Spec.StorageClass == SC_AUTO || Spec.StorageClass == SC_REGISTER) {
110             Error ("Illegal storage class");
111             Spec.StorageClass = SC_EXTERN | SC_STATIC;
112         }
113
114         /* Check if this is only a type declaration */
115         if (CurTok.Tok == TOK_SEMI) {
116             CheckEmptyDecl (&Spec);
117             NextToken ();
118             continue;
119         }
120
121         /* Check if we must reserve storage for the variable. We do
122          * this if we don't had a storage class given ("int i") or
123          * if the storage class is explicitly specified as static.
124          * This means that "extern int i" will not get storage
125          * allocated.
126          */
127         NeedStorage = (Spec.StorageClass & SC_TYPEDEF) == 0 &&
128                       ((Spec.Flags & DS_DEF_STORAGE) != 0  ||
129                       (Spec.StorageClass & (SC_STATIC | SC_EXTERN)) == SC_STATIC);
130
131         /* Read declarations for this type */
132         Entry = 0;
133         comma = 0;
134         while (1) {
135
136             unsigned SymFlags;
137
138             /* Read the next declaration */
139             ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
140             if (Decl.Ident[0] == '\0') {
141                 NextToken ();
142                 break;
143             }
144
145             /* Get the symbol flags */
146             SymFlags = Spec.StorageClass;
147             if (IsTypeFunc (Decl.Type)) {
148                 SymFlags |= SC_FUNC;
149             } else {
150                 if (NeedStorage) {
151                     /* We will allocate storage, variable is defined */
152                     SymFlags |= SC_STORAGE | SC_DEF;
153                 }
154             }
155
156             /* Add an entry to the symbol table */
157             Entry = AddGlobalSym (Decl.Ident, Decl.Type, SymFlags);
158
159             /* Reserve storage for the variable if we need to */
160             if (SymFlags & SC_STORAGE) {
161
162                 /* Get the size of the variable */
163                 unsigned Size = SizeOf (Decl.Type);
164
165                 /* Allow initialization */
166                 if (CurTok.Tok == TOK_ASSIGN) {
167
168                     /* We cannot initialize types of unknown size, or
169                      * void types in non ANSI mode.
170                      */
171                     if (Size == 0) {
172                         if (!IsTypeVoid (Decl.Type)) {
173                             if (!IsTypeArray (Decl.Type)) {
174                                 /* Size is unknown and not an array */
175                                 Error ("Variable `%s' has unknown size", Decl.Ident);
176                             }
177                         } else if (ANSI) {
178                             /* We cannot declare variables of type void */
179                             Error ("Illegal type for variable `%s'", Decl.Ident);
180                         }
181                     }
182
183                     /* Switch to the data or rodata segment */
184                     if (IsQualConst (Decl.Type)) {
185                         g_userodata ();
186                     } else {
187                         g_usedata ();
188                     }
189
190                     /* Define a label */
191                     g_defgloblabel (Entry->Name);
192
193                     /* Skip the '=' */
194                     NextToken ();
195
196                     /* Parse the initialization */
197                     ParseInit (Entry->Type);
198                 } else {
199
200                     if (IsTypeVoid (Decl.Type)) {
201                         /* We cannot declare variables of type void */
202                         Error ("Illegal type for variable `%s'", Decl.Ident);
203                     } else if (Size == 0) {
204                         /* Size is unknown */
205                         Error ("Variable `%s' has unknown size", Decl.Ident);
206                     }
207
208                     /* Switch to the BSS segment */
209                     g_usebss ();
210
211                     /* Define a label */
212                     g_defgloblabel (Entry->Name);
213
214                     /* Allocate space for uninitialized variable */
215                     g_res (SizeOf (Entry->Type));
216                 }
217
218             }
219
220             /* Check for end of declaration list */
221             if (CurTok.Tok == TOK_COMMA) {
222                 NextToken ();
223                 comma = 1;
224             } else {
225                 break;
226             }
227         }
228
229         /* Function declaration? */
230         if (Entry && IsTypeFunc (Entry->Type)) {
231
232             /* Function */
233             if (!comma) {
234
235                 if (CurTok.Tok == TOK_SEMI) {
236
237                     /* Prototype only */
238                     NextToken ();
239
240                 } else {
241                     if (Entry) {
242                         NewFunc (Entry);
243                     }
244                 }
245             }
246
247         } else {
248
249             /* Must be followed by a semicolon */
250             ConsumeSemi ();
251
252         }
253     }
254 }
255
256
257
258 void Compile (const char* FileName)
259 /* Top level compile routine. Will setup things and call the parser. */
260 {
261     char*       Path;
262     char        Buf[20];
263     char        DateStr[20];
264     char        TimeStr[20];
265     time_t      Time;
266     struct tm*  TM;
267
268     /* Since strftime is locale dependent, we need the abbreviated month names
269      * in english.
270      */
271     static const char MonthNames[12][4] = {
272         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
273         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
274     };
275
276     /* Add some standard paths to the include search path */
277     AddIncludePath ("", INC_USER);              /* Current directory */
278     AddIncludePath ("include", INC_SYS);
279 #ifdef CC65_INC
280     AddIncludePath (CC65_INC, INC_SYS);
281 #else
282     AddIncludePath ("/usr/lib/cc65/include", INC_SYS);
283 #endif
284     Path = getenv ("CC65_INC");
285     if (Path) {
286         AddIncludePath (Path, INC_SYS | INC_USER);
287     }
288
289     /* Add macros that are always defined */
290     DefineNumericMacro ("__CC65__", (VER_MAJOR * 0x100) + (VER_MINOR * 0x10) + VER_PATCH);
291
292     /* Strict ANSI macro */
293     if (ANSI) {
294         DefineNumericMacro ("__STRICT_ANSI__", 1);
295     }
296
297     /* Optimization macros */
298     if (Optimize) {
299         DefineNumericMacro ("__OPT__", 1);
300         if (FavourSize == 0) {
301             DefineNumericMacro ("__OPT_i__", 1);
302         }
303         if (EnableRegVars) {
304             DefineNumericMacro ("__OPT_r__", 1);
305         }
306         if (InlineStdFuncs) {
307             DefineNumericMacro ("__OPT_s__", 1);
308         }
309     }
310
311     /* __TIME__ and __DATE__ macros */
312     Time = time (0);
313     TM   = localtime (&Time);
314     strftime (Buf, sizeof (Buf), "%e %Y", TM);
315     xsprintf (DateStr, sizeof (DateStr), "\"%s %s\"", MonthNames[TM->tm_mon], Buf);
316     strftime (TimeStr, sizeof (TimeStr), "\"%H:%M:%S\"", TM);
317     DefineTextMacro ("__DATE__", DateStr);
318     DefineTextMacro ("__TIME__", TimeStr);
319
320     /* Initialize the literal pool */
321     InitLiteralPool ();
322
323     /* Create the base lexical level */
324     EnterGlobalLevel ();
325
326     /* Generate the code generator preamble */
327     g_preamble ();
328
329     /* Open the input file */
330     OpenMainFile (FileName);
331
332     /* Ok, start the ball rolling... */
333     Parse ();
334
335     /* Dump the literal pool. */
336     DumpLiteralPool ();
337
338     /* Write imported/exported symbols */
339     EmitExternals ();
340
341     if (Debug) {
342         PrintLiteralPoolStats (stdout);
343         PrintMacroStats (stdout);
344     }
345
346     /* Leave the main lexical level */
347     LeaveGlobalLevel ();
348
349     /* Print an error report */
350     ErrorReport ();
351 }
352
353
354