OSDN Git Service

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