OSDN Git Service

* Makefile.in (c-lex.o): Wrap long lines. Depend on debug.h.
[pf3gnuchains/gcc-fork.git] / gcc / java / jcf-parse.c
1 /* Parser for Java(TM) .class files.
2    Copyright (C) 1996, 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
3
4 This file is part of GNU CC.
5
6 GNU CC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU CC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU CC; see the file COPYING.  If not, write to
18 the Free Software Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.
20
21 Java and all Java-based marks are trademarks or registered trademarks
22 of Sun Microsystems, Inc. in the United States and other countries.
23 The Free Software Foundation is independent of Sun Microsystems, Inc.  */
24
25 /* Written by Per Bothner <bothner@cygnus.com> */
26
27 #include "config.h"
28 #include "system.h"
29 #include "tree.h"
30 #include "obstack.h"
31 #include "flags.h"
32 #include "java-except.h"
33 #include "input.h"
34 #include "java-tree.h"
35 #include "toplev.h"
36 #include "parse.h"
37 #include "ggc.h"
38 #include "debug.h"
39
40 #ifdef HAVE_LOCALE_H
41 #include <locale.h>
42 #endif
43
44 #ifdef HAVE_NL_LANGINFO
45 #include <langinfo.h>
46 #endif
47
48 /* A CONSTANT_Utf8 element is converted to an IDENTIFIER_NODE at parse time. */
49 #define JPOOL_UTF(JCF, INDEX) CPOOL_UTF(&(JCF)->cpool, INDEX)
50 #define JPOOL_UTF_LENGTH(JCF, INDEX) IDENTIFIER_LENGTH (JPOOL_UTF (JCF, INDEX))
51 #define JPOOL_UTF_DATA(JCF, INDEX) \
52   ((const unsigned char *) IDENTIFIER_POINTER (JPOOL_UTF (JCF, INDEX)))
53 #define HANDLE_CONSTANT_Utf8(JCF, INDEX, LENGTH) \
54   do { \
55     unsigned char save;  unsigned char *text; \
56     JCF_FILL (JCF, (LENGTH)+1); /* Make sure we read 1 byte beyond string. */ \
57     text = (JCF)->read_ptr; \
58     save = text[LENGTH]; \
59     text[LENGTH] = 0; \
60     (JCF)->cpool.data[INDEX] = (jword) get_identifier (text); \
61     text[LENGTH] = save; \
62     JCF_SKIP (JCF, LENGTH); } while (0)
63
64 #include "jcf.h"
65
66 extern struct obstack *saveable_obstack;
67 extern struct obstack temporary_obstack;
68 extern struct obstack permanent_obstack;
69
70 /* Set to non-zero value in order to emit class initilization code
71    before static field references.  */
72 extern int always_initialize_class_p;
73
74 static tree parse_roots[3] = { NULL_TREE, NULL_TREE, NULL_TREE };
75
76 /* The FIELD_DECL for the current field.  */
77 #define current_field parse_roots[0]
78
79 /* The METHOD_DECL for the current method.  */
80 #define current_method parse_roots[1]
81
82 /* A list of file names.  */
83 #define current_file_list parse_roots[2]
84
85 /* The Java archive that provides main_class;  the main input file. */
86 static struct JCF main_jcf[1];
87
88 static struct ZipFile *localToFile;
89
90 /* Declarations of some functions used here.  */
91 static void handle_innerclass_attribute PARAMS ((int count, JCF *));
92 static tree give_name_to_class PARAMS ((JCF *jcf, int index));
93 static void parse_zip_file_entries PARAMS ((void));
94 static void process_zip_dir PARAMS ((FILE *));
95 static void parse_source_file_1 PARAMS ((tree, FILE *));
96 static void parse_source_file_2 PARAMS ((void));
97 static void parse_class_file PARAMS ((void));
98 static void set_source_filename PARAMS ((JCF *, int));
99 static int predefined_filename_p PARAMS ((tree));
100 static void ggc_mark_jcf PARAMS ((void**));
101 static void jcf_parse PARAMS ((struct JCF*));
102 static void load_inner_classes PARAMS ((tree));
103
104 /* Mark (for garbage collection) all the tree nodes that are
105    referenced from JCF's constant pool table. Do that only if the JCF
106    hasn't been marked finished.  */
107
108 static void
109 ggc_mark_jcf (elt)
110      void **elt;
111 {
112   JCF *jcf = *(JCF**) elt;
113   if (jcf != NULL && !jcf->finished)
114     {
115       CPool *cpool = &jcf->cpool;
116       int size = CPOOL_COUNT(cpool);
117       int index;
118       for (index = 1; index < size;  index++)
119         {
120           int tag = JPOOL_TAG (jcf, index);
121           if ((tag & CONSTANT_ResolvedFlag) || tag == CONSTANT_Utf8)
122             ggc_mark_tree ((tree) cpool->data[index]);
123         }
124     }
125 }
126
127 /* Handle "SourceFile" attribute. */
128
129 static void
130 set_source_filename (jcf, index)
131      JCF *jcf;
132      int index;
133 {
134   tree sfname_id = get_name_constant (jcf, index);
135   const char *sfname = IDENTIFIER_POINTER (sfname_id);
136   if (input_filename != NULL)
137     {
138       int old_len = strlen (input_filename);
139       int new_len = IDENTIFIER_LENGTH (sfname_id);
140       /* Use the current input_filename (derived from the class name)
141          if it has a directory prefix, but otherwise matches sfname. */
142       if (old_len > new_len
143           && strcmp (sfname, input_filename + old_len - new_len) == 0
144           && (input_filename[old_len - new_len - 1] == '/'
145               || input_filename[old_len - new_len - 1] == '\\'))
146         return;
147     }
148   input_filename = sfname;
149   DECL_SOURCE_FILE (TYPE_NAME (current_class)) = sfname;
150   if (current_class == main_class) main_input_filename = input_filename;
151 }
152
153 #define HANDLE_SOURCEFILE(INDEX) set_source_filename (jcf, INDEX)
154
155 #define HANDLE_CLASS_INFO(ACCESS_FLAGS, THIS, SUPER, INTERFACES_COUNT) \
156 { tree super_class = SUPER==0 ? NULL_TREE : get_class_constant (jcf, SUPER); \
157   current_class = give_name_to_class (jcf, THIS); \
158   set_super_info (ACCESS_FLAGS, current_class, super_class, INTERFACES_COUNT);}
159
160 #define HANDLE_CLASS_INTERFACE(INDEX) \
161   add_interface (current_class, get_class_constant (jcf, INDEX))
162
163 #define HANDLE_START_FIELD(ACCESS_FLAGS, NAME, SIGNATURE, ATTRIBUTE_COUNT) \
164 { int sig_index = SIGNATURE; \
165   current_field = add_field (current_class, get_name_constant (jcf, NAME), \
166                              parse_signature (jcf, sig_index), ACCESS_FLAGS); \
167  set_java_signature (TREE_TYPE (current_field), JPOOL_UTF (jcf, sig_index)); \
168  if ((ACCESS_FLAGS) & ACC_FINAL) \
169    MAYBE_CREATE_VAR_LANG_DECL_SPECIFIC (current_field); \
170 }
171
172 #define HANDLE_END_FIELDS() \
173   (current_field = NULL_TREE)
174
175 #define HANDLE_CONSTANTVALUE(INDEX) \
176 { tree constant;  int index = INDEX; \
177   if (! flag_emit_class_files && JPOOL_TAG (jcf, index) == CONSTANT_String) { \
178     tree name = get_name_constant (jcf, JPOOL_USHORT1 (jcf, index)); \
179     constant = build_utf8_ref (name); \
180   } \
181   else \
182     constant = get_constant (jcf, index); \
183   set_constant_value (current_field, constant); }
184
185 #define HANDLE_METHOD(ACCESS_FLAGS, NAME, SIGNATURE, ATTRIBUTE_COUNT) \
186  (current_method = add_method (current_class, ACCESS_FLAGS, \
187                                get_name_constant (jcf, NAME), \
188                                get_name_constant (jcf, SIGNATURE)), \
189   DECL_LOCALVARIABLES_OFFSET (current_method) = 0, \
190   DECL_LINENUMBERS_OFFSET (current_method) = 0)
191
192 #define HANDLE_END_METHODS() \
193 { tree handle_type = CLASS_TO_HANDLE_TYPE (current_class); \
194   if (handle_type != current_class) layout_type (handle_type); \
195   current_method = NULL_TREE; }
196
197 #define HANDLE_CODE_ATTRIBUTE(MAX_STACK, MAX_LOCALS, CODE_LENGTH) \
198 { DECL_MAX_STACK (current_method) = (MAX_STACK); \
199   DECL_MAX_LOCALS (current_method) = (MAX_LOCALS); \
200   DECL_CODE_LENGTH (current_method) = (CODE_LENGTH); \
201   DECL_CODE_OFFSET (current_method) = JCF_TELL (jcf); }
202
203 #define HANDLE_LOCALVARIABLETABLE_ATTRIBUTE(COUNT) \
204 { int n = (COUNT); \
205   DECL_LOCALVARIABLES_OFFSET (current_method) = JCF_TELL (jcf) - 2; \
206   JCF_SKIP (jcf, n * 10); }
207
208 #define HANDLE_LINENUMBERTABLE_ATTRIBUTE(COUNT) \
209 { int n = (COUNT); \
210   DECL_LINENUMBERS_OFFSET (current_method) = JCF_TELL (jcf) - 2; \
211   JCF_SKIP (jcf, n * 4); }
212
213 #define HANDLE_EXCEPTIONS_ATTRIBUTE(COUNT) \
214 { \
215   int n = COUNT; \
216   tree list = DECL_FUNCTION_THROWS (current_method); \
217   while (--n >= 0) \
218     { \
219       tree thrown_class = get_class_constant (jcf, JCF_readu2 (jcf)); \
220       list = tree_cons (NULL_TREE, thrown_class, list); \
221     } \
222   DECL_FUNCTION_THROWS (current_method) = nreverse (list); \
223 }
224
225 /* Link seen inner classes to their outer context and register the
226    inner class to its outer context. They will be later loaded.  */
227 #define HANDLE_INNERCLASSES_ATTRIBUTE(COUNT) \
228   handle_innerclass_attribute (COUNT, jcf)
229
230 #define HANDLE_SYNTHETIC_ATTRIBUTE()                                    \
231 {                                                                       \
232   /* Irrelevant decls should have been nullified by the END macros.     \
233      We only handle the `Synthetic' attribute on method DECLs.          \
234      DECL_ARTIFICIAL on fields is used for something else (See          \
235      PUSH_FIELD in java-tree.h) */                                      \
236   if (current_method)                                                   \
237     DECL_ARTIFICIAL (current_method) = 1;                               \
238 }
239
240 #define HANDLE_GCJCOMPILED_ATTRIBUTE()          \
241 {                                               \
242   if (current_class == object_type_node)        \
243     jcf->right_zip = 1;                         \
244 }
245
246 #include "jcf-reader.c"
247
248 static int yydebug;
249
250 tree
251 parse_signature (jcf, sig_index)
252      JCF *jcf;
253      int sig_index;
254 {
255   if (sig_index <= 0 || sig_index >= JPOOL_SIZE (jcf)
256       || JPOOL_TAG (jcf, sig_index) != CONSTANT_Utf8)
257     abort ();
258   else
259     return parse_signature_string (JPOOL_UTF_DATA (jcf, sig_index),
260                                    JPOOL_UTF_LENGTH (jcf, sig_index));
261 }
262
263 void
264 init_lex ()
265 {
266   /* Make identifier nodes long enough for the language-specific slots.  */
267   set_identifier_size (sizeof (struct lang_identifier));
268 }
269
270 void
271 set_yydebug (value)
272      int value;
273 {
274   yydebug = value;
275 }
276
277 tree
278 get_constant (jcf, index)
279   JCF *jcf;
280   int index;
281 {
282   tree value;
283   int tag;
284   if (index <= 0 || index >= JPOOL_SIZE(jcf))
285     goto bad;
286   tag = JPOOL_TAG (jcf, index);
287   if ((tag & CONSTANT_ResolvedFlag) || tag == CONSTANT_Utf8)
288     return (tree) jcf->cpool.data[index];
289   switch (tag)
290     {
291     case CONSTANT_Integer:
292       {
293         jint num = JPOOL_INT(jcf, index);
294         value = build_int_2 (num, num < 0 ? -1 : 0);
295         TREE_TYPE (value) = int_type_node;
296         break;
297       }
298     case CONSTANT_Long:
299       {
300         jint num = JPOOL_INT (jcf, index);
301         HOST_WIDE_INT lo, hi;
302         lshift_double (num, 0, 32, 64, &lo, &hi, 0);
303         num = JPOOL_INT (jcf, index+1) & 0xffffffff;
304         add_double (lo, hi, num, 0, &lo, &hi);
305         value = build_int_2 (lo, hi);
306         TREE_TYPE (value) = long_type_node;
307         force_fit_type (value, 0);
308         break;
309       }
310 #if TARGET_FLOAT_FORMAT == IEEE_FLOAT_FORMAT
311     case CONSTANT_Float:
312       {
313         jint num = JPOOL_INT(jcf, index);
314         REAL_VALUE_TYPE d;
315 #ifdef REAL_ARITHMETIC
316         d = REAL_VALUE_FROM_TARGET_SINGLE (num);
317 #else
318         union { float f;  jint i; } u;
319         u.i = num;
320         d = u.f;
321 #endif
322         value = build_real (float_type_node, d);
323         break;
324       }
325     case CONSTANT_Double:
326       {
327         HOST_WIDE_INT num[2];
328         REAL_VALUE_TYPE d;
329         HOST_WIDE_INT lo, hi;
330         num[0] = JPOOL_INT (jcf, index);
331         lshift_double (num[0], 0, 32, 64, &lo, &hi, 0);
332         num[0] = JPOOL_INT (jcf, index+1);
333         add_double (lo, hi, num[0], 0, &lo, &hi);
334         if (FLOAT_WORDS_BIG_ENDIAN)
335           {
336             num[0] = hi;
337             num[1] = lo;
338           }
339         else
340           {
341             num[0] = lo;
342             num[1] = hi;
343           }
344 #ifdef REAL_ARITHMETIC
345         d = REAL_VALUE_FROM_TARGET_DOUBLE (num);
346 #else
347         {
348           union { double d;  jint i[2]; } u;
349           u.i[0] = (jint) num[0];
350           u.i[1] = (jint) num[1];
351           d = u.d;
352         }
353 #endif
354         value = build_real (double_type_node, d);
355         break;
356       }
357 #endif /* TARGET_FLOAT_FORMAT == IEEE_FLOAT_FORMAT */
358     case CONSTANT_String:
359       {
360         tree name = get_name_constant (jcf, JPOOL_USHORT1 (jcf, index));
361         const char *utf8_ptr = IDENTIFIER_POINTER (name);
362         int utf8_len = IDENTIFIER_LENGTH (name);
363         unsigned char *str_ptr;
364         unsigned char *str;
365         const unsigned char *utf8;
366         int i, str_len;
367
368         /* Count the number of Unicode characters in the string,
369            while checking for a malformed Utf8 string. */
370         utf8 = (const unsigned char *) utf8_ptr;
371         i = utf8_len;
372         str_len = 0;
373         while (i > 0)
374           {
375             int char_len = UT8_CHAR_LENGTH (*utf8);
376             if (char_len < 0 || char_len > 3 || char_len > i)
377               fatal_error ("bad string constant");
378
379             utf8 += char_len;
380             i -= char_len;
381             str_len++;
382           }
383
384         /* Allocate a scratch buffer, convert the string to UCS2, and copy it
385            into the new space.  */
386         str_ptr = (unsigned char *) alloca (2 * str_len);
387         str = str_ptr;
388         utf8 = (const unsigned char *)utf8_ptr;
389
390         for (i = 0; i < str_len; i++)
391           {
392             int char_value;
393             int char_len = UT8_CHAR_LENGTH (*utf8);
394             switch (char_len)
395               {
396               case 1:
397                 char_value = *utf8++;
398                 break;
399               case 2:
400                 char_value = *utf8++ & 0x1F;
401                 char_value = (char_value << 6) | (*utf8++ & 0x3F);
402                 break;
403               case 3:
404                 char_value = *utf8++ & 0x0F;
405                 char_value = (char_value << 6) | (*utf8++ & 0x3F);
406                 char_value = (char_value << 6) | (*utf8++ & 0x3F);
407                 break;
408               default:
409                 goto bad;
410               }
411             if (BYTES_BIG_ENDIAN)
412               {
413                 *str++ = char_value >> 8;
414                 *str++ = char_value & 0xFF;
415               }
416             else
417               {
418                 *str++ = char_value & 0xFF;
419                 *str++ = char_value >> 8;
420               }
421           }
422         value = build_string (str - str_ptr, str_ptr);
423         TREE_TYPE (value) = build_pointer_type (string_type_node);
424       }
425       break;
426     default:
427       goto bad;
428     }
429   JPOOL_TAG (jcf, index) = tag | CONSTANT_ResolvedFlag;
430   jcf->cpool.data [index] = (jword) value;
431   return value;
432  bad:
433   internal_error ("bad value constant type %d, index %d", 
434                   JPOOL_TAG (jcf, index), index);
435 }
436
437 tree
438 get_name_constant (jcf, index)
439   JCF *jcf;
440   int index;
441 {
442   tree name = get_constant (jcf, index);
443
444   if (TREE_CODE (name) != IDENTIFIER_NODE)
445     abort ();
446
447   return name;
448 }
449
450 /* Handle reading innerclass attributes. If a non zero entry (denoting
451    a non anonymous entry) is found, We augment the inner class list of
452    the outer context with the newly resolved innerclass.  */
453
454 static void
455 handle_innerclass_attribute (count, jcf)
456      int count;
457      JCF *jcf;
458 {
459   int c = (count);
460   while (c--)
461     {
462       /* Read inner_class_info_index. This may be 0 */
463       int icii = JCF_readu2 (jcf);
464       /* Read outer_class_info_index. If the innerclasses attribute
465          entry isn't a member (like an inner class) the value is 0. */
466       int ocii = JCF_readu2 (jcf);
467       /* Read inner_name_index. If the class we're dealing with is
468          an annonymous class, it must be 0. */
469       int ini = JCF_readu2 (jcf);
470       /* Read the access flag. */
471       int acc = JCF_readu2 (jcf);
472       /* If icii is 0, don't try to read the class. */
473       if (icii >= 0)
474         {
475           tree class = get_class_constant (jcf, icii);
476           tree decl = TYPE_NAME (class);
477           /* Skip reading further if ocii is null */
478           if (DECL_P (decl) && !CLASS_COMPLETE_P (decl) && ocii)
479             {
480               tree outer = TYPE_NAME (get_class_constant (jcf, ocii));
481               tree alias = (ini ? get_name_constant (jcf, ini) : NULL_TREE);
482               set_class_decl_access_flags (acc, decl);
483               DECL_CONTEXT (decl) = outer;
484               DECL_INNER_CLASS_LIST (outer) =
485                 tree_cons (decl, alias, DECL_INNER_CLASS_LIST (outer));
486               CLASS_COMPLETE_P (decl) = 1;
487             }
488         }
489     }
490 }
491
492 static tree
493 give_name_to_class (jcf, i)
494      JCF *jcf;
495      int i;
496 {
497   if (i <= 0 || i >= JPOOL_SIZE (jcf)
498       || JPOOL_TAG (jcf, i) != CONSTANT_Class)
499     abort ();
500   else
501     {
502       tree this_class;
503       int j = JPOOL_USHORT1 (jcf, i);
504       /* verify_constant_pool confirmed that j is a CONSTANT_Utf8. */
505       tree class_name = unmangle_classname (JPOOL_UTF_DATA (jcf, j),
506                                             JPOOL_UTF_LENGTH (jcf, j));
507       this_class = lookup_class (class_name);
508       input_filename = DECL_SOURCE_FILE (TYPE_NAME (this_class));
509       lineno = 0;
510       if (main_input_filename == NULL && jcf == main_jcf)
511         main_input_filename = input_filename;
512
513       jcf->cpool.data[i] = (jword) this_class;
514       JPOOL_TAG (jcf, i) = CONSTANT_ResolvedClass;
515       return this_class;
516     }
517 }
518
519 /* Get the class of the CONSTANT_Class whose constant pool index is I. */
520
521 tree
522 get_class_constant (JCF *jcf , int i)
523 {
524   tree type;
525   if (i <= 0 || i >= JPOOL_SIZE (jcf)
526       || (JPOOL_TAG (jcf, i) & ~CONSTANT_ResolvedFlag) != CONSTANT_Class)
527     abort ();
528
529   if (JPOOL_TAG (jcf, i) != CONSTANT_ResolvedClass)
530     {
531       int name_index = JPOOL_USHORT1 (jcf, i);
532       /* verify_constant_pool confirmed that name_index is a CONSTANT_Utf8. */
533       const char *name = JPOOL_UTF_DATA (jcf, name_index);
534       int nlength = JPOOL_UTF_LENGTH (jcf, name_index);
535
536       if (name[0] == '[')  /* Handle array "classes". */
537           type = TREE_TYPE (parse_signature_string (name, nlength));
538       else
539         { 
540           tree cname = unmangle_classname (name, nlength);
541           type = lookup_class (cname);
542         }
543       jcf->cpool.data[i] = (jword) type;
544       JPOOL_TAG (jcf, i) = CONSTANT_ResolvedClass;
545     }
546   else
547     type = (tree) jcf->cpool.data[i];
548   return type;
549 }
550
551 /* Read a class with the fully qualified-name NAME.
552    Return 1 iff we read the requested file.
553    (It is still possible we failed if the file did not
554    define the class it is supposed to.) */
555
556 int
557 read_class (name)
558      tree name;
559 {
560   JCF this_jcf, *jcf;
561   tree icv, class = NULL_TREE;
562   tree save_current_class = current_class;
563   const char *save_input_filename = input_filename;
564   JCF *save_current_jcf = current_jcf;
565
566   if ((icv = IDENTIFIER_CLASS_VALUE (name)) != NULL_TREE)
567     {
568       class = TREE_TYPE (icv);
569       jcf = TYPE_JCF (class);
570     }
571   else
572     jcf = NULL;
573
574   if (jcf == NULL)
575     {
576       this_jcf.zipd = NULL;
577       jcf = &this_jcf;
578       if (find_class (IDENTIFIER_POINTER (name), IDENTIFIER_LENGTH (name),
579                       &this_jcf, 1) == 0)
580         return 0;
581     }
582
583   current_jcf = jcf;
584
585   if (current_jcf->java_source)
586     {
587       const char *filename = current_jcf->filename;
588       tree file;
589       FILE *finput;
590       int generate;
591
592       java_parser_context_save_global ();
593       java_push_parser_context ();
594       BUILD_FILENAME_IDENTIFIER_NODE (file, filename);
595       generate = IS_A_COMMAND_LINE_FILENAME_P (file);
596       if (wfl_operator == NULL_TREE)
597         wfl_operator = build_expr_wfl (NULL_TREE, NULL, 0, 0);
598       EXPR_WFL_FILENAME_NODE (wfl_operator) = file;
599       input_filename = ggc_strdup (filename);
600       current_class = NULL_TREE;
601       current_function_decl = NULL_TREE;
602       if (!HAS_BEEN_ALREADY_PARSED_P (file))
603         {
604           if (!(finput = fopen (input_filename, "r")))
605             fatal_io_error ("can't reopen %s", input_filename);
606           parse_source_file_1 (file, finput);
607           parse_source_file_2 ();
608           if (fclose (finput))
609             fatal_io_error ("can't close %s", input_filename);
610         }
611       JCF_FINISH (current_jcf);
612       java_pop_parser_context (generate);
613       java_parser_context_restore_global ();
614     }
615   else
616     {
617       if (class == NULL_TREE || ! CLASS_PARSED_P (class))
618         {
619           java_parser_context_save_global ();
620           java_push_parser_context ();
621           current_class = class;
622           input_filename = current_jcf->filename;
623           if (JCF_SEEN_IN_ZIP (current_jcf))
624             read_zip_member(current_jcf,
625                             current_jcf->zipd, current_jcf->zipd->zipf);
626           jcf_parse (current_jcf);
627           class = current_class;
628           java_pop_parser_context (0);
629           java_parser_context_restore_global ();
630         }
631       layout_class (class);
632       load_inner_classes (class);
633     }
634
635   current_class = save_current_class;
636   input_filename = save_input_filename;
637   current_jcf = save_current_jcf;
638   return 1;
639 }
640
641 /* Load CLASS_OR_NAME. CLASS_OR_NAME can be a mere identifier if
642    called from the parser, otherwise it's a RECORD_TYPE node. If
643    VERBOSE is 1, print error message on failure to load a class. */
644
645 /* Replace calls to load_class by having callers call read_class directly
646    - and then perhaps rename read_class to load_class.  FIXME */
647
648 void
649 load_class (class_or_name, verbose)
650      tree class_or_name;
651      int verbose;
652 {
653   tree name;
654
655   /* class_or_name can be the name of the class we want to load */
656   if (TREE_CODE (class_or_name) == IDENTIFIER_NODE)
657     name = class_or_name;
658   /* In some cases, it's a dependency that we process earlier that
659      we though */
660   else if (TREE_CODE (class_or_name) == TREE_LIST)
661     name = TYPE_NAME (TREE_PURPOSE (class_or_name));
662   /* Or it's a type in the making */
663   else
664     name = DECL_NAME (TYPE_NAME (class_or_name));
665
666   if (read_class (name) == 0 && verbose)
667     error ("Cannot find file for class %s.", IDENTIFIER_POINTER (name));
668 }
669
670 /* Parse the .class file JCF. */
671
672 void
673 jcf_parse (jcf)
674      JCF* jcf;
675 {
676   int i, code;
677
678   if (jcf_parse_preamble (jcf) != 0)
679     fatal_error ("not a valid Java .class file");
680   code = jcf_parse_constant_pool (jcf);
681   if (code != 0)
682     fatal_error ("error while parsing constant pool");
683   code = verify_constant_pool (jcf);
684   if (code > 0)
685     fatal_error ("error in constant pool entry #%d\n", code);
686
687   jcf_parse_class (jcf);
688   if (main_class == NULL_TREE)
689     main_class = current_class;
690   if (! quiet_flag && TYPE_NAME (current_class))
691     fprintf (stderr, " %s %s",
692              (jcf->access_flags & ACC_INTERFACE) ? "interface" : "class", 
693              IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (current_class))));
694   if (CLASS_PARSED_P (current_class))
695     {
696       /* FIXME - where was first time */
697       fatal_error ("reading class %s for the second time from %s",
698                    IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (current_class))),
699                    jcf->filename);
700     }
701   CLASS_PARSED_P (current_class) = 1;
702
703   for (i = 1; i < JPOOL_SIZE(jcf); i++)
704     {
705       switch (JPOOL_TAG (jcf, i))
706         {
707         case CONSTANT_Class:
708           get_class_constant (jcf, i);
709           break;
710         }
711     }
712   
713   code = jcf_parse_fields (jcf);
714   if (code != 0)
715     fatal_error ("error while parsing fields");
716   code = jcf_parse_methods (jcf);
717   if (code != 0)
718     fatal_error ("error while parsing methods");
719   code = jcf_parse_final_attributes (jcf);
720   if (code != 0)
721     fatal_error ("error while parsing final attributes");
722
723   /* The fields of class_type_node are already in correct order. */
724   if (current_class != class_type_node && current_class != object_type_node)
725     TYPE_FIELDS (current_class) = nreverse (TYPE_FIELDS (current_class));
726
727   if (current_class == object_type_node)
728     {
729       layout_class_methods (object_type_node);
730       /* If we don't have the right archive, emit a verbose warning.
731          If we're generating bytecode, emit the warning only if
732          -fforce-classes-archive-check was specified. */
733       if (!jcf->right_zip
734           && (!flag_emit_class_files || flag_force_classes_archive_check))
735         fatal_error ("The `java.lang.Object' that was found in `%s' didn't have the special zero-length `gnu.gcj.gcj-compiled' attribute. This generally means that your classpath is incorrect set. Use `info gcj \"Input Options\"' to see the info page describing how to set the classpath.", jcf->filename);
736     }
737   else
738     all_class_list = tree_cons (NULL_TREE,
739                                 TYPE_NAME (current_class), all_class_list );
740 }
741
742 /* If we came across inner classes, load them now. */
743 static void
744 load_inner_classes (cur_class)
745      tree cur_class;
746 {
747   tree current;
748   for (current = DECL_INNER_CLASS_LIST (TYPE_NAME (cur_class)); current;
749        current = TREE_CHAIN (current))
750     {
751       tree name = DECL_NAME (TREE_PURPOSE (current));
752       tree decl = IDENTIFIER_GLOBAL_VALUE (name);
753       if (decl && ! CLASS_LOADED_P (TREE_TYPE (decl))
754           && !CLASS_BEING_LAIDOUT (TREE_TYPE (decl)))
755         load_class (name, 1);
756     }
757 }
758
759 void
760 init_outgoing_cpool ()
761 {
762   current_constant_pool_data_ref = NULL_TREE;
763   outgoing_cpool = (struct CPool *)xmalloc (sizeof (struct CPool));
764   memset (outgoing_cpool, 0, sizeof (struct CPool));
765 }
766
767 static void
768 parse_class_file ()
769 {
770   tree method;
771   const char *save_input_filename = input_filename;
772   int save_lineno = lineno;
773
774   java_layout_seen_class_methods ();
775
776   input_filename = DECL_SOURCE_FILE (TYPE_NAME (current_class));
777   lineno = 0;
778   (*debug_hooks->start_source_file) (lineno, input_filename);
779   init_outgoing_cpool ();
780
781   /* Currently we always have to emit calls to _Jv_InitClass when
782      compiling from class files.  */
783   always_initialize_class_p = 1;
784
785   for ( method = TYPE_METHODS (CLASS_TO_HANDLE_TYPE (current_class));
786         method != NULL_TREE; method = TREE_CHAIN (method))
787     {
788       JCF *jcf = current_jcf;
789
790       if (METHOD_ABSTRACT (method))
791         continue;
792
793       if (METHOD_NATIVE (method))
794         {
795           tree arg;
796           int  decl_max_locals;
797
798           if (! flag_jni)
799             continue;
800           /* We need to compute the DECL_MAX_LOCALS. We need to take
801              the wide types into account too. */
802           for (arg = TYPE_ARG_TYPES (TREE_TYPE (method)), decl_max_locals = 0; 
803                arg != end_params_node;
804                arg = TREE_CHAIN (arg), decl_max_locals += 1)
805             {
806               if (TREE_VALUE (arg) && TYPE_IS_WIDE (TREE_VALUE (arg)))
807                 decl_max_locals += 1;
808             }
809           DECL_MAX_LOCALS (method) = decl_max_locals;
810           start_java_method (method);
811           give_name_to_locals (jcf);
812           expand_expr_stmt (build_jni_stub (method));
813           end_java_method ();
814           continue;
815         }
816
817       if (DECL_CODE_OFFSET (method) == 0)
818         {
819           error ("missing Code attribute");
820           continue;
821         }
822
823       lineno = 0;
824       if (DECL_LINENUMBERS_OFFSET (method))
825         {
826           register int i;
827           register unsigned char *ptr;
828           JCF_SEEK (jcf, DECL_LINENUMBERS_OFFSET (method));
829           linenumber_count = i = JCF_readu2 (jcf);
830           linenumber_table = ptr = jcf->read_ptr;
831
832           for (ptr += 2; --i >= 0; ptr += 4)
833             {
834               int line = GET_u2 (ptr);
835               /* Set initial lineno lineno to smallest linenumber.
836                * Needs to be set before init_function_start. */
837               if (lineno == 0 || line < lineno)
838                 lineno = line;
839             }  
840         }
841       else
842         {
843           linenumber_table = NULL;
844           linenumber_count = 0;
845         }
846
847       start_java_method (method);
848
849       note_instructions (jcf, method);
850
851       give_name_to_locals (jcf);
852
853       /* Actually generate code. */
854       expand_byte_code (jcf, method);
855
856       end_java_method ();
857     }
858
859   if (flag_emit_class_files)
860     write_classfile (current_class);
861
862   finish_class ();
863
864   (*debug_hooks->end_source_file) (save_lineno);
865   input_filename = save_input_filename;
866   lineno = save_lineno;
867 }
868
869 /* Parse a source file, as pointed by the current value of INPUT_FILENAME. */
870
871 static void
872 parse_source_file_1 (file, finput)
873      tree file;
874      FILE *finput;
875 {
876   int save_error_count = java_error_count;
877   /* Mark the file as parsed */
878   HAS_BEEN_ALREADY_PARSED_P (file) = 1;
879
880   jcf_dependency_add_file (input_filename, 0);
881
882   lang_init_source (1);             /* Error msgs have no method prototypes */
883
884   /* There's no point in trying to find the current encoding unless we
885      are going to do something intelligent with it -- hence the test
886      for iconv.  */
887 #ifdef HAVE_ICONV
888 #ifdef HAVE_NL_LANGINFO
889   setlocale (LC_CTYPE, "");
890   if (current_encoding == NULL)
891     current_encoding = nl_langinfo (CODESET);
892 #endif /* HAVE_NL_LANGINFO */
893 #endif /* HAVE_ICONV */
894   if (current_encoding == NULL || *current_encoding == '\0')
895     current_encoding = DEFAULT_ENCODING;
896
897   /* Initialize the parser */
898   java_init_lex (finput, current_encoding);
899   java_parse_abort_on_error ();
900
901   java_parse ();                    /* Parse and build partial tree nodes. */
902   java_parse_abort_on_error ();
903 }
904
905 /* Process a parsed source file, resolving names etc. */
906
907 static void
908 parse_source_file_2 ()
909 {
910   int save_error_count = java_error_count;
911   java_complete_class ();           /* Parse unsatisfied class decl. */
912   java_parse_abort_on_error ();
913   java_check_circular_reference (); /* Check on circular references */
914   java_parse_abort_on_error ();
915   java_fix_constructors ();         /* Fix the constructors */
916   java_parse_abort_on_error ();
917   java_reorder_fields ();           /* Reorder the fields */
918 }
919
920 static int
921 predefined_filename_p (node)
922      tree node;
923 {
924   int i;
925   for (i = 0; i < PREDEF_FILENAMES_SIZE; i++)
926     if (predef_filenames [i] == node)
927       return 1;
928   return 0;
929 }
930
931 int
932 yyparse ()
933 {
934   int filename_count = 0;
935   char *list, *next;
936   tree node;
937   FILE *finput = NULL;
938
939   if (flag_filelist_file)
940     {
941       int avail = 2000;
942       finput = fopen (input_filename, "r");
943       if (finput == NULL)
944         fatal_io_error ("can't open %s", input_filename);
945       list = xmalloc(avail);
946       next = list;
947       for (;;)
948         {
949           int count;
950           if (avail < 500)
951             {
952               count = next - list;
953               avail = 2 * (count + avail);
954               list = xrealloc (list, avail);
955               next = list + count;
956               avail = avail - count;
957             }
958           /* Subtract to to guarantee space for final '\0'. */
959           count = fread (next, 1, avail - 1, finput);
960           if (count == 0)
961             {
962               if (! feof (finput))
963                 fatal_io_error ("error closing %s", input_filename);
964               *next = '\0';
965               break;
966             }
967           avail -= count;
968           next += count;
969         }
970       fclose (finput);
971       finput = NULL;
972     }
973   else
974     list = xstrdup (input_filename);
975
976   do 
977     {
978       for (next = list; ; )
979         {
980           char ch = *next;
981           if (ch == '\n' || ch == '\r' || ch == '\t' || ch == ' '
982               || ch == '&' /* FIXME */)
983             {
984               if (next == list)
985                 {
986                   next++;
987                   list = next;
988                   continue;
989                 }
990               else
991                 {
992                   *next++ = '\0';
993                   break;
994                 }
995             }
996           if (ch == '\0')
997             {
998               next = NULL;
999               break;
1000             }
1001           next++;
1002         }
1003
1004       if (list[0]) 
1005         {
1006           char *value;
1007           tree id;
1008           int twice = 0;
1009
1010           int len = strlen (list);
1011
1012           if (*list != '/' && filename_count > 0)
1013             obstack_grow (&temporary_obstack, "./", 2);
1014
1015           obstack_grow0 (&temporary_obstack, list, len);
1016           value = obstack_finish (&temporary_obstack);
1017
1018           filename_count++;
1019
1020           /* Exclude file that we see twice on the command line. For
1021              all files except {Class,Error,Object,RuntimeException,String,
1022              Throwable}.java we can rely on maybe_get_identifier. For
1023              these files, we need to do a linear search of
1024              current_file_list. This search happens only for these
1025              files, presumably only when we're recompiling libgcj. */
1026              
1027           if ((id = maybe_get_identifier (value)))
1028             {
1029               if (predefined_filename_p (id))
1030                 {
1031                   tree c;
1032                   for (c = current_file_list; c; c = TREE_CHAIN (c))
1033                     if (TREE_VALUE (c) == id)
1034                       twice = 1;
1035                 }
1036               else
1037                 twice = 1;
1038             }
1039
1040           if (twice)
1041             {
1042               const char *saved_input_filename = input_filename;
1043               input_filename = value;
1044               warning ("source file seen twice on command line and will be compiled only once.");
1045               input_filename = saved_input_filename;
1046             }
1047           else
1048             {
1049               BUILD_FILENAME_IDENTIFIER_NODE (node, value);
1050               IS_A_COMMAND_LINE_FILENAME_P (node) = 1;
1051               current_file_list = tree_cons (NULL_TREE, node, 
1052                                              current_file_list);
1053             }
1054         }
1055       list = next;
1056     }
1057   while (next);
1058
1059   if (filename_count == 0)
1060     warning ("no input file specified");
1061
1062   current_jcf = main_jcf;
1063   current_file_list = nreverse (current_file_list);
1064   for (node = current_file_list; node; node = TREE_CHAIN (node))
1065     {
1066       unsigned char magic_string[4];
1067       uint32 magic;
1068       tree name = TREE_VALUE (node);
1069
1070       /* Skip already parsed files */
1071       if (HAS_BEEN_ALREADY_PARSED_P (name))
1072         continue;
1073       
1074       /* Close previous descriptor, if any */
1075       if (finput && fclose (finput))
1076         fatal_io_error ("can't close input file %s", main_input_filename);
1077       
1078       finput = fopen (IDENTIFIER_POINTER (name), "rb");
1079       if (finput == NULL)
1080         fatal_io_error ("can't open %s", IDENTIFIER_POINTER (name));
1081       
1082 #ifdef IO_BUFFER_SIZE
1083       setvbuf (finput, (char *) xmalloc (IO_BUFFER_SIZE),
1084                _IOFBF, IO_BUFFER_SIZE);
1085 #endif
1086       input_filename = IDENTIFIER_POINTER (name);
1087
1088       /* Figure what kind of file we're dealing with */
1089       if (fread (magic_string, 1, 4, finput) != 4)
1090         fatal_io_error ("Premature end of input file %s", 
1091                         IDENTIFIER_POINTER (name));
1092       fseek (finput, 0L, SEEK_SET);
1093       magic = GET_u4 (magic_string);
1094       if (magic == 0xcafebabe)
1095         {
1096           CLASS_FILE_P (node) = 1;
1097           current_jcf = ALLOC (sizeof (JCF));
1098           JCF_ZERO (current_jcf);
1099           current_jcf->read_state = finput;
1100           current_jcf->filbuf = jcf_filbuf_from_stdio;
1101           jcf_parse (current_jcf);
1102           TYPE_JCF (current_class) = current_jcf;
1103           CLASS_FROM_CURRENTLY_COMPILED_P (current_class) = 1;
1104           TREE_PURPOSE (node) = current_class;
1105         }
1106       else if (magic == (JCF_u4)ZIPMAGIC)
1107         {
1108           ZIP_FILE_P (node) = 1;
1109           JCF_ZERO (main_jcf);
1110           main_jcf->read_state = finput;
1111           main_jcf->filbuf = jcf_filbuf_from_stdio;
1112           if (open_in_zip (main_jcf, input_filename, NULL, 0) <  0)
1113             fatal_error ("bad zip/jar file %s", IDENTIFIER_POINTER (name));
1114           localToFile = SeenZipFiles;
1115           /* Register all the class defined there.  */
1116           process_zip_dir (main_jcf->read_state);
1117           parse_zip_file_entries ();
1118           /*
1119           for (each entry)
1120             CLASS_FROM_CURRENTLY_COMPILED_P (current_class) = 1;
1121           */
1122         }
1123       else
1124         {
1125           JAVA_FILE_P (node) = 1;
1126           java_push_parser_context ();
1127           java_parser_context_save_global ();
1128           parse_source_file_1 (name, finput);
1129           java_parser_context_restore_global ();
1130           java_pop_parser_context (1);
1131         }
1132     }
1133
1134   for (ctxp = ctxp_for_generation;  ctxp;  ctxp = ctxp->next)
1135     {
1136       input_filename = ctxp->filename;
1137       parse_source_file_2 ();
1138     }
1139   for (node = current_file_list; node; node = TREE_CHAIN (node))
1140     {
1141       input_filename = IDENTIFIER_POINTER (TREE_VALUE (node));
1142       if (CLASS_FILE_P (node))
1143         {
1144           current_class = TREE_PURPOSE (node);
1145           current_jcf = TYPE_JCF (current_class);
1146           layout_class (current_class);
1147           load_inner_classes (current_class);
1148           parse_class_file ();
1149           JCF_FINISH (current_jcf);
1150         }
1151     }
1152   input_filename = main_input_filename;
1153
1154   java_expand_classes ();
1155   if (!java_report_errors () && !flag_syntax_only)
1156     emit_register_classes ();
1157   return 0;
1158 }
1159
1160 /* Process all class entries found in the zip file.  */
1161 static void
1162 parse_zip_file_entries (void)
1163 {
1164   struct ZipDirectory *zdir;
1165   int i;
1166
1167   for (i = 0, zdir = (ZipDirectory *)localToFile->central_directory;
1168        i < localToFile->count; i++, zdir = ZIPDIR_NEXT (zdir))
1169     {
1170       tree class;
1171       
1172       /* We don't need to consider those files.  */
1173       if (!zdir->size || !zdir->filename_offset)
1174         continue;
1175
1176       class = lookup_class (get_identifier (ZIPDIR_FILENAME (zdir)));
1177       current_jcf = TYPE_JCF (class);
1178       current_class = class;
1179
1180       if ( !CLASS_LOADED_P (class))
1181         {
1182           if (! CLASS_PARSED_P (class))
1183             {
1184               read_zip_member(current_jcf, zdir, localToFile);
1185               jcf_parse (current_jcf);
1186             }
1187           layout_class (current_class);
1188           load_inner_classes (current_class);
1189         }
1190
1191       if (TYPE_SIZE (current_class) != error_mark_node)
1192         {
1193           input_filename = current_jcf->filename;
1194           parse_class_file ();
1195           FREE (current_jcf->buffer); /* No longer necessary */
1196           /* Note: there is a way to free this buffer right after a
1197              class seen in a zip file has been parsed. The idea is the
1198              set its jcf in such a way that buffer will be reallocated
1199              the time the code for the class will be generated. FIXME. */
1200         }
1201     }
1202 }
1203
1204 /* Read all the entries of the zip file, creates a class and a JCF. Sets the
1205    jcf up for further processing and link it to the created class.  */
1206
1207 static void
1208 process_zip_dir (FILE *finput)
1209 {
1210   int i;
1211   ZipDirectory *zdir;
1212
1213   for (i = 0, zdir = (ZipDirectory *)localToFile->central_directory;
1214        i < localToFile->count; i++, zdir = ZIPDIR_NEXT (zdir))
1215     {
1216       char *class_name, *file_name, *class_name_in_zip_dir;
1217       tree class;
1218       JCF  *jcf;
1219       int   j;
1220
1221       class_name_in_zip_dir = ZIPDIR_FILENAME (zdir);
1222
1223       /* We choose to not to process entries with a zero size or entries
1224          not bearing the .class extention.  */
1225       if (!zdir->size || !zdir->filename_offset ||
1226           strncmp (&class_name_in_zip_dir[zdir->filename_length-6], 
1227                    ".class", 6))
1228         {
1229           /* So it will be skipped in parse_zip_file_entries  */
1230           zdir->size = 0;  
1231           continue;
1232         }
1233
1234       class_name = ALLOC (zdir->filename_length+1-6);
1235       file_name  = ALLOC (zdir->filename_length+1);
1236       jcf = ALLOC (sizeof (JCF));
1237       JCF_ZERO (jcf);
1238
1239       strncpy (class_name, class_name_in_zip_dir, zdir->filename_length-6);
1240       class_name [zdir->filename_length-6] = '\0';
1241       strncpy (file_name, class_name_in_zip_dir, zdir->filename_length);
1242       file_name [zdir->filename_length] = '\0';
1243
1244       for (j=0; class_name[j]; j++)
1245         class_name [j] = (class_name [j] == '/' ? '.' : class_name [j]);
1246
1247       /* Yes, we write back the true class name into the zip directory.  */
1248       strcpy (class_name_in_zip_dir, class_name);
1249       zdir->filename_length = j;
1250       class = lookup_class (get_identifier (class_name));
1251
1252       jcf->read_state  = finput;
1253       jcf->filbuf      = jcf_filbuf_from_stdio;
1254       jcf->java_source = 0;
1255       jcf->classname   = class_name;
1256       jcf->filename    = file_name;
1257       jcf->zipd        = zdir;
1258
1259       TYPE_JCF (class) = jcf;
1260     }
1261 }
1262
1263 /* Initialization.  */
1264
1265 void
1266 init_jcf_parse ()
1267 {
1268   /* Register roots with the garbage collector.  */
1269   ggc_add_tree_root (parse_roots, sizeof (parse_roots) / sizeof(tree));
1270
1271   ggc_add_root (&current_jcf, 1, sizeof (JCF), (void (*)(void *))ggc_mark_jcf);
1272
1273   init_src_parse ();
1274 }