OSDN Git Service

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