OSDN Git Service

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