OSDN Git Service

* config/i386/i386.c (override_options): Define c3-2 as a 686 with SSE.
[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_LANGINFO_CODESET
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           /* Parsing might change the class, in which case we have to
520              put it back where we found it.  */
521           if (current_class != class && icv != NULL_TREE)
522             TREE_TYPE (icv) = current_class;
523           class = current_class;
524           java_pop_parser_context (0);
525           java_parser_context_restore_global ();
526         }
527       layout_class (class);
528       load_inner_classes (class);
529     }
530
531   current_class = save_current_class;
532   input_filename = save_input_filename;
533   current_jcf = save_current_jcf;
534   return 1;
535 }
536
537 /* Load CLASS_OR_NAME. CLASS_OR_NAME can be a mere identifier if
538    called from the parser, otherwise it's a RECORD_TYPE node. If
539    VERBOSE is 1, print error message on failure to load a class. */
540
541 /* Replace calls to load_class by having callers call read_class directly
542    - and then perhaps rename read_class to load_class.  FIXME */
543
544 void
545 load_class (tree class_or_name, int verbose)
546 {
547   tree name, saved;
548   int class_loaded;
549
550   /* class_or_name can be the name of the class we want to load */
551   if (TREE_CODE (class_or_name) == IDENTIFIER_NODE)
552     name = class_or_name;
553   /* In some cases, it's a dependency that we process earlier that
554      we though */
555   else if (TREE_CODE (class_or_name) == TREE_LIST)
556     name = TYPE_NAME (TREE_PURPOSE (class_or_name));
557   /* Or it's a type in the making */
558   else
559     name = DECL_NAME (TYPE_NAME (class_or_name));
560
561   saved = name;
562   while (1)
563     {
564       char *separator;
565
566       if ((class_loaded = read_class (name)))
567         break;
568
569       /* We failed loading name. Now consider that we might be looking
570          for a inner class. */
571       if ((separator = strrchr (IDENTIFIER_POINTER (name), '$'))
572           || (separator = strrchr (IDENTIFIER_POINTER (name), '.')))
573         {
574           int c = *separator;
575           *separator = '\0';
576           name = get_identifier (IDENTIFIER_POINTER (name));
577           *separator = c;
578         }
579       /* Otherwise, we failed, we bail. */
580       else
581         break;
582     }
583
584   if (!class_loaded && verbose)
585     error ("cannot find file for class %s", IDENTIFIER_POINTER (saved));
586 }
587
588 /* Parse the .class file JCF. */
589
590 void
591 jcf_parse (JCF* jcf)
592 {
593   int i, code;
594
595   if (jcf_parse_preamble (jcf) != 0)
596     fatal_error ("not a valid Java .class file");
597   code = jcf_parse_constant_pool (jcf);
598   if (code != 0)
599     fatal_error ("error while parsing constant pool");
600   code = verify_constant_pool (jcf);
601   if (code > 0)
602     fatal_error ("error in constant pool entry #%d\n", code);
603
604   jcf_parse_class (jcf);
605   if (main_class == NULL_TREE)
606     main_class = current_class;
607   if (! quiet_flag && TYPE_NAME (current_class))
608     fprintf (stderr, " %s %s",
609              (jcf->access_flags & ACC_INTERFACE) ? "interface" : "class", 
610              IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (current_class))));
611   if (CLASS_PARSED_P (current_class))
612     {
613       /* FIXME - where was first time */
614       fatal_error ("reading class %s for the second time from %s",
615                    IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (current_class))),
616                    jcf->filename);
617     }
618   CLASS_PARSED_P (current_class) = 1;
619
620   for (i = 1; i < JPOOL_SIZE(jcf); i++)
621     {
622       switch (JPOOL_TAG (jcf, i))
623         {
624         case CONSTANT_Class:
625           get_class_constant (jcf, i);
626           break;
627         }
628     }
629   
630   code = jcf_parse_fields (jcf);
631   if (code != 0)
632     fatal_error ("error while parsing fields");
633   code = jcf_parse_methods (jcf);
634   if (code != 0)
635     fatal_error ("error while parsing methods");
636   code = jcf_parse_final_attributes (jcf);
637   if (code != 0)
638     fatal_error ("error while parsing final attributes");
639
640   /* The fields of class_type_node are already in correct order. */
641   if (current_class != class_type_node && current_class != object_type_node)
642     TYPE_FIELDS (current_class) = nreverse (TYPE_FIELDS (current_class));
643
644   if (current_class == object_type_node)
645     {
646       layout_class_methods (object_type_node);
647       /* If we don't have the right archive, emit a verbose warning.
648          If we're generating bytecode, emit the warning only if
649          -fforce-classes-archive-check was specified. */
650       if (!jcf->right_zip
651           && (!flag_emit_class_files || flag_force_classes_archive_check))
652         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);
653     }
654   else
655     all_class_list = tree_cons (NULL_TREE,
656                                 TYPE_NAME (current_class), all_class_list );
657 }
658
659 /* If we came across inner classes, load them now. */
660 static void
661 load_inner_classes (tree cur_class)
662 {
663   tree current;
664   for (current = DECL_INNER_CLASS_LIST (TYPE_NAME (cur_class)); current;
665        current = TREE_CHAIN (current))
666     {
667       tree name = DECL_NAME (TREE_PURPOSE (current));
668       tree decl = IDENTIFIER_GLOBAL_VALUE (name);
669       if (decl && ! CLASS_LOADED_P (TREE_TYPE (decl))
670           && !CLASS_BEING_LAIDOUT (TREE_TYPE (decl)))
671         load_class (name, 1);
672     }
673 }
674
675 void
676 init_outgoing_cpool (void)
677 {
678   outgoing_cpool = ggc_alloc_cleared (sizeof (struct CPool));
679 }
680
681 static void
682 parse_class_file (void)
683 {
684   tree method, field;
685   const char *save_input_filename = input_filename;
686   int save_lineno = lineno;
687
688   java_layout_seen_class_methods ();
689
690   input_filename = DECL_SOURCE_FILE (TYPE_NAME (current_class));
691   lineno = 0;
692   (*debug_hooks->start_source_file) (lineno, input_filename);
693   init_outgoing_cpool ();
694
695   /* Currently we always have to emit calls to _Jv_InitClass when
696      compiling from class files.  */
697   always_initialize_class_p = 1;
698
699   for (field = TYPE_FIELDS (current_class);
700        field != NULL_TREE; field = TREE_CHAIN (field))
701     if (FIELD_STATIC (field))
702       DECL_EXTERNAL (field) = 0;
703
704   for (method = TYPE_METHODS (current_class);
705        method != NULL_TREE; method = TREE_CHAIN (method))
706     {
707       JCF *jcf = current_jcf;
708
709       if (METHOD_ABSTRACT (method))
710         continue;
711
712       if (METHOD_NATIVE (method))
713         {
714           tree arg;
715           int  decl_max_locals;
716
717           if (! flag_jni)
718             continue;
719           /* We need to compute the DECL_MAX_LOCALS. We need to take
720              the wide types into account too. */
721           for (arg = TYPE_ARG_TYPES (TREE_TYPE (method)), decl_max_locals = 0; 
722                arg != end_params_node;
723                arg = TREE_CHAIN (arg), decl_max_locals += 1)
724             {
725               if (TREE_VALUE (arg) && TYPE_IS_WIDE (TREE_VALUE (arg)))
726                 decl_max_locals += 1;
727             }
728           DECL_MAX_LOCALS (method) = decl_max_locals;
729           start_java_method (method);
730           give_name_to_locals (jcf);
731           expand_expr_stmt (build_jni_stub (method));
732           end_java_method ();
733           continue;
734         }
735
736       if (DECL_CODE_OFFSET (method) == 0)
737         {
738           current_function_decl = method;
739           error ("missing Code attribute");
740           continue;
741         }
742
743       lineno = 0;
744       if (DECL_LINENUMBERS_OFFSET (method))
745         {
746           register int i;
747           register unsigned char *ptr;
748           JCF_SEEK (jcf, DECL_LINENUMBERS_OFFSET (method));
749           linenumber_count = i = JCF_readu2 (jcf);
750           linenumber_table = ptr = jcf->read_ptr;
751
752           for (ptr += 2; --i >= 0; ptr += 4)
753             {
754               int line = GET_u2 (ptr);
755               /* Set initial lineno lineno to smallest linenumber.
756                * Needs to be set before init_function_start. */
757               if (lineno == 0 || line < lineno)
758                 lineno = line;
759             }  
760         }
761       else
762         {
763           linenumber_table = NULL;
764           linenumber_count = 0;
765         }
766
767       start_java_method (method);
768
769       note_instructions (jcf, method);
770
771       give_name_to_locals (jcf);
772
773       /* Actually generate code. */
774       expand_byte_code (jcf, method);
775
776       end_java_method ();
777     }
778
779   if (flag_emit_class_files)
780     write_classfile (current_class);
781
782   finish_class ();
783
784   (*debug_hooks->end_source_file) (save_lineno);
785   input_filename = save_input_filename;
786   lineno = save_lineno;
787 }
788
789 /* Parse a source file, as pointed by the current value of INPUT_FILENAME. */
790
791 static void
792 parse_source_file_1 (tree file, FILE *finput)
793 {
794   int save_error_count = java_error_count;
795   /* Mark the file as parsed */
796   HAS_BEEN_ALREADY_PARSED_P (file) = 1;
797
798   jcf_dependency_add_file (input_filename, 0);
799
800   lang_init_source (1);             /* Error msgs have no method prototypes */
801
802   /* There's no point in trying to find the current encoding unless we
803      are going to do something intelligent with it -- hence the test
804      for iconv.  */
805 #if defined (HAVE_LOCALE_H) && defined (HAVE_ICONV) && defined (HAVE_LANGINFO_CODESET)
806   setlocale (LC_CTYPE, "");
807   if (current_encoding == NULL)
808     current_encoding = nl_langinfo (CODESET);
809 #endif 
810   if (current_encoding == NULL || *current_encoding == '\0')
811     current_encoding = DEFAULT_ENCODING;
812
813   /* Initialize the parser */
814   java_init_lex (finput, current_encoding);
815   java_parse_abort_on_error ();
816
817   java_parse ();                    /* Parse and build partial tree nodes. */
818   java_parse_abort_on_error ();
819 }
820
821 /* Process a parsed source file, resolving names etc. */
822
823 static void
824 parse_source_file_2 (void)
825 {
826   int save_error_count = java_error_count;
827   java_complete_class ();           /* Parse unsatisfied class decl. */
828   java_parse_abort_on_error ();
829 }
830
831 static void
832 parse_source_file_3 (void)
833 {
834   int save_error_count = java_error_count;
835   java_check_circular_reference (); /* Check on circular references */
836   java_parse_abort_on_error ();
837   java_fix_constructors ();         /* Fix the constructors */
838   java_parse_abort_on_error ();
839   java_reorder_fields ();           /* Reorder the fields */
840 }
841
842 void
843 add_predefined_file (tree name)
844 {
845   predef_filenames = tree_cons (NULL_TREE, name, predef_filenames);
846 }
847
848 int
849 predefined_filename_p (tree node)
850 {
851   tree iter;
852
853   for (iter = predef_filenames; iter != NULL_TREE; iter = TREE_CHAIN (iter))
854     {
855       if (TREE_VALUE (iter) == node)
856         return 1;
857     }
858   return 0;
859 }
860
861 void
862 java_parse_file (int set_yydebug ATTRIBUTE_UNUSED)
863 {
864   int filename_count = 0;
865   char *list, *next;
866   tree node;
867   FILE *finput = NULL;
868
869   if (flag_filelist_file)
870     {
871       int avail = 2000;
872       finput = fopen (input_filename, "r");
873       if (finput == NULL)
874         fatal_io_error ("can't open %s", input_filename);
875       list = xmalloc(avail);
876       next = list;
877       for (;;)
878         {
879           int count;
880           if (avail < 500)
881             {
882               count = next - list;
883               avail = 2 * (count + avail);
884               list = xrealloc (list, avail);
885               next = list + count;
886               avail = avail - count;
887             }
888           /* Subtract to to guarantee space for final '\0'. */
889           count = fread (next, 1, avail - 1, finput);
890           if (count == 0)
891             {
892               if (! feof (finput))
893                 fatal_io_error ("error closing %s", input_filename);
894               *next = '\0';
895               break;
896             }
897           avail -= count;
898           next += count;
899         }
900       fclose (finput);
901       finput = NULL;
902     }
903   else
904     list = xstrdup (input_filename);
905
906   do 
907     {
908       for (next = list; ; )
909         {
910           char ch = *next;
911           if (ch == '\n' || ch == '\r' || ch == '\t' || ch == ' '
912               || ch == '&' /* FIXME */)
913             {
914               if (next == list)
915                 {
916                   next++;
917                   list = next;
918                   continue;
919                 }
920               else
921                 {
922                   *next++ = '\0';
923                   break;
924                 }
925             }
926           if (ch == '\0')
927             {
928               next = NULL;
929               break;
930             }
931           next++;
932         }
933
934       if (list[0]) 
935         {
936           char *value;
937           tree id;
938           int twice = 0;
939
940           int len = strlen (list);
941
942           obstack_grow0 (&temporary_obstack, list, len);
943           value = obstack_finish (&temporary_obstack);
944
945           filename_count++;
946
947           /* Exclude file that we see twice on the command line. For
948              all files except {Class,Error,Object,RuntimeException,String,
949              Throwable}.java we can rely on maybe_get_identifier. For
950              these files, we need to do a linear search of
951              current_file_list. This search happens only for these
952              files, presumably only when we're recompiling libgcj. */
953              
954           if ((id = maybe_get_identifier (value)))
955             {
956               if (predefined_filename_p (id))
957                 {
958                   tree c;
959                   for (c = current_file_list; c; c = TREE_CHAIN (c))
960                     if (TREE_VALUE (c) == id)
961                       twice = 1;
962                 }
963               else
964                 twice = 1;
965             }
966
967           if (twice)
968             {
969               const char *saved_input_filename = input_filename;
970               input_filename = value;
971               warning ("source file seen twice on command line and will be compiled only once");
972               input_filename = saved_input_filename;
973             }
974           else
975             {
976               BUILD_FILENAME_IDENTIFIER_NODE (node, value);
977               IS_A_COMMAND_LINE_FILENAME_P (node) = 1;
978               current_file_list = tree_cons (NULL_TREE, node, 
979                                              current_file_list);
980             }
981         }
982       list = next;
983     }
984   while (next);
985
986   if (filename_count == 0)
987     warning ("no input file specified");
988
989   if (resource_name)
990     {
991       const char *resource_filename;
992       
993       /* Only one resource file may be compiled at a time.  */
994       assert (TREE_CHAIN (current_file_list) == NULL);
995
996       resource_filename = IDENTIFIER_POINTER (TREE_VALUE (current_file_list));
997       compile_resource_file (resource_name, resource_filename);
998
999       return;
1000     }
1001
1002   current_jcf = main_jcf;
1003   current_file_list = nreverse (current_file_list);
1004   for (node = current_file_list; node; node = TREE_CHAIN (node))
1005     {
1006       unsigned char magic_string[4];
1007       uint32 magic = 0;
1008       tree name = TREE_VALUE (node);
1009
1010       /* Skip already parsed files */
1011       if (HAS_BEEN_ALREADY_PARSED_P (name))
1012         continue;
1013       
1014       /* Close previous descriptor, if any */
1015       if (finput && fclose (finput))
1016         fatal_io_error ("can't close input file %s", main_input_filename);
1017       
1018       finput = fopen (IDENTIFIER_POINTER (name), "rb");
1019       if (finput == NULL)
1020         fatal_io_error ("can't open %s", IDENTIFIER_POINTER (name));
1021
1022 #ifdef IO_BUFFER_SIZE
1023       setvbuf (finput, xmalloc (IO_BUFFER_SIZE),
1024                _IOFBF, IO_BUFFER_SIZE);
1025 #endif
1026       input_filename = IDENTIFIER_POINTER (name);
1027
1028       /* Figure what kind of file we're dealing with */
1029       if (fread (magic_string, 1, 4, finput) == 4)
1030         {
1031           fseek (finput, 0L, SEEK_SET);
1032           magic = GET_u4 (magic_string);
1033         }
1034       if (magic == 0xcafebabe)
1035         {
1036           CLASS_FILE_P (node) = 1;
1037           current_jcf = ggc_alloc (sizeof (JCF));
1038           JCF_ZERO (current_jcf);
1039           current_jcf->read_state = finput;
1040           current_jcf->filbuf = jcf_filbuf_from_stdio;
1041           jcf_parse (current_jcf);
1042           TYPE_JCF (current_class) = current_jcf;
1043           CLASS_FROM_CURRENTLY_COMPILED_P (current_class) = 1;
1044           TREE_PURPOSE (node) = current_class;
1045         }
1046       else if (magic == (JCF_u4)ZIPMAGIC)
1047         {
1048           ZIP_FILE_P (node) = 1;
1049           main_jcf = ggc_alloc (sizeof (JCF));
1050           JCF_ZERO (main_jcf);
1051           main_jcf->read_state = finput;
1052           main_jcf->filbuf = jcf_filbuf_from_stdio;
1053           if (open_in_zip (main_jcf, input_filename, NULL, 0) <  0)
1054             fatal_error ("bad zip/jar file %s", IDENTIFIER_POINTER (name));
1055           localToFile = SeenZipFiles;
1056           /* Register all the classes defined there.  */
1057           process_zip_dir (main_jcf->read_state);
1058           parse_zip_file_entries ();
1059           /*
1060           for (each entry)
1061             CLASS_FROM_CURRENTLY_COMPILED_P (current_class) = 1;
1062           */
1063         }
1064       else
1065         {
1066           JAVA_FILE_P (node) = 1;
1067           java_push_parser_context ();
1068           java_parser_context_save_global ();
1069           parse_source_file_1 (name, finput);
1070           java_parser_context_restore_global ();
1071           java_pop_parser_context (1);
1072         }
1073     }
1074
1075   for (ctxp = ctxp_for_generation;  ctxp;  ctxp = ctxp->next)
1076     {
1077       input_filename = ctxp->filename;
1078       parse_source_file_2 ();
1079     }
1080
1081   for (ctxp = ctxp_for_generation; ctxp; ctxp = ctxp->next)
1082     {
1083       input_filename = ctxp->filename;
1084       parse_source_file_3 ();
1085     }
1086
1087   for (node = current_file_list; node; node = TREE_CHAIN (node))
1088     {
1089       input_filename = IDENTIFIER_POINTER (TREE_VALUE (node));
1090       if (CLASS_FILE_P (node))
1091         {
1092           current_class = TREE_PURPOSE (node);
1093           current_jcf = TYPE_JCF (current_class);
1094           layout_class (current_class);
1095           load_inner_classes (current_class);
1096           parse_class_file ();
1097           JCF_FINISH (current_jcf);
1098         }
1099     }
1100   input_filename = main_input_filename;
1101
1102   java_expand_classes ();
1103   if (!java_report_errors () && !flag_syntax_only)
1104     {
1105       emit_register_classes ();
1106       if (flag_indirect_dispatch)
1107         emit_offset_symbol_table ();
1108     }
1109
1110   write_resource_constructor ();
1111 }
1112
1113 /* Return the name of the class corresponding to the name of the file
1114    in this zip entry.  The result is newly allocated using ALLOC.  */
1115 static char *
1116 compute_class_name (struct ZipDirectory *zdir)
1117 {
1118   char *class_name_in_zip_dir = ZIPDIR_FILENAME (zdir);
1119   char *class_name;
1120   int j;
1121
1122   class_name = ALLOC (zdir->filename_length + 1 - 6);
1123   strncpy (class_name, class_name_in_zip_dir, zdir->filename_length - 6);
1124   class_name [zdir->filename_length - 6] = '\0';
1125   for (j = 0; class_name[j]; ++j)
1126     class_name[j] = class_name[j] == '/' ? '.' : class_name[j];
1127   return class_name;
1128 }
1129
1130 /* Return 0 if we should skip this entry, 1 if it is a .class file, 2
1131    if it is a property file of some sort.  */
1132 static int
1133 classify_zip_file (struct ZipDirectory *zdir)
1134 {
1135   char *class_name_in_zip_dir = ZIPDIR_FILENAME (zdir);
1136
1137   if (zdir->filename_length > 6
1138       && !strncmp (&class_name_in_zip_dir[zdir->filename_length - 6],
1139                    ".class", 6))
1140     return 1;
1141
1142   /* For now we drop the manifest and other information.  Maybe it
1143      would make more sense to compile it in?  */
1144   if (zdir->filename_length > 8
1145       && !strncmp (class_name_in_zip_dir, "META-INF/", 9))
1146     return 0;
1147
1148   /* Drop directory entries.  */
1149   if (zdir->filename_length > 0
1150       && class_name_in_zip_dir[zdir->filename_length - 1] == '/')
1151     return 0;
1152
1153   return 2;
1154 }
1155
1156 /* Process all class entries found in the zip file.  */
1157 static void
1158 parse_zip_file_entries (void)
1159 {
1160   struct ZipDirectory *zdir;
1161   int i;
1162
1163   for (i = 0, zdir = (ZipDirectory *)localToFile->central_directory;
1164        i < localToFile->count; i++, zdir = ZIPDIR_NEXT (zdir))
1165     {
1166       tree class;
1167
1168       switch (classify_zip_file (zdir))
1169         {
1170         case 0:
1171           continue;
1172
1173         case 1:
1174           {
1175             char *class_name = compute_class_name (zdir);
1176             class = lookup_class (get_identifier (class_name));
1177             FREE (class_name);
1178             current_jcf = TYPE_JCF (class);
1179             current_class = class;
1180
1181             if (! CLASS_LOADED_P (class))
1182               {
1183                 if (! CLASS_PARSED_P (class))
1184                   {
1185                     read_zip_member (current_jcf, zdir, localToFile);
1186                     jcf_parse (current_jcf);
1187                   }
1188                 layout_class (current_class);
1189                 load_inner_classes (current_class);
1190               }
1191
1192             if (TYPE_SIZE (current_class) != error_mark_node)
1193               {
1194                 input_filename = current_jcf->filename;
1195                 parse_class_file ();
1196                 FREE (current_jcf->buffer); /* No longer necessary */
1197                 /* Note: there is a way to free this buffer right after a
1198                    class seen in a zip file has been parsed. The idea is the
1199                    set its jcf in such a way that buffer will be reallocated
1200                    the time the code for the class will be generated. FIXME. */
1201               }
1202           }
1203           break;
1204
1205         case 2:
1206           {
1207             char *file_name, *class_name_in_zip_dir, *buffer;
1208             JCF *jcf;
1209             file_name = ALLOC (zdir->filename_length + 1);
1210             class_name_in_zip_dir = ZIPDIR_FILENAME (zdir);
1211             strncpy (file_name, class_name_in_zip_dir, zdir->filename_length);
1212             file_name[zdir->filename_length] = '\0';
1213             jcf = ALLOC (sizeof (JCF));
1214             JCF_ZERO (jcf);
1215             jcf->read_state  = finput;
1216             jcf->filbuf      = jcf_filbuf_from_stdio;
1217             jcf->java_source = 0;
1218             jcf->classname   = NULL;
1219             jcf->filename    = file_name;
1220             jcf->zipd        = zdir;
1221
1222             if (read_zip_member (jcf, zdir, localToFile) < 0)
1223               fatal_error ("error while reading %s from zip file", file_name);
1224
1225             buffer = ALLOC (zdir->filename_length + 1 +
1226                             (jcf->buffer_end - jcf->buffer));
1227             strcpy (buffer, file_name);
1228             /* This is not a typo: we overwrite the trailing \0 of the
1229                file name; this is just how the data is laid out.  */
1230             memcpy (buffer + zdir->filename_length,
1231                     jcf->buffer, jcf->buffer_end - jcf->buffer);
1232
1233             compile_resource_data (file_name, buffer,
1234                                    jcf->buffer_end - jcf->buffer);
1235             JCF_FINISH (jcf);
1236             FREE (jcf);
1237             FREE (buffer);
1238           }
1239           break;
1240
1241         default:
1242           abort ();
1243         }
1244     }
1245 }
1246
1247 /* Read all the entries of the zip file, creates a class and a JCF. Sets the
1248    jcf up for further processing and link it to the created class.  */
1249
1250 static void
1251 process_zip_dir (FILE *finput)
1252 {
1253   int i;
1254   ZipDirectory *zdir;
1255
1256   for (i = 0, zdir = (ZipDirectory *)localToFile->central_directory;
1257        i < localToFile->count; i++, zdir = ZIPDIR_NEXT (zdir))
1258     {
1259       char *class_name, *file_name, *class_name_in_zip_dir;
1260       tree class;
1261       JCF  *jcf;
1262
1263       class_name_in_zip_dir = ZIPDIR_FILENAME (zdir);
1264
1265       /* Here we skip non-class files; we handle them later.  */
1266       if (classify_zip_file (zdir) != 1)
1267         continue;
1268
1269       class_name = compute_class_name (zdir);
1270       file_name  = ALLOC (zdir->filename_length+1);
1271       jcf = ggc_alloc (sizeof (JCF));
1272       JCF_ZERO (jcf);
1273
1274       strncpy (file_name, class_name_in_zip_dir, zdir->filename_length);
1275       file_name [zdir->filename_length] = '\0';
1276
1277       class = lookup_class (get_identifier (class_name));
1278
1279       jcf->read_state  = finput;
1280       jcf->filbuf      = jcf_filbuf_from_stdio;
1281       jcf->java_source = 0;
1282       jcf->classname   = class_name;
1283       jcf->filename    = file_name;
1284       jcf->zipd        = zdir;
1285
1286       TYPE_JCF (class) = jcf;
1287     }
1288 }
1289
1290 /* Initialization.  */
1291
1292 void
1293 init_jcf_parse (void)
1294 {
1295   init_src_parse ();
1296 }
1297
1298 #include "gt-java-jcf-parse.h"