* configure.ac (AC_CHECK_ENABLE_ASSERTION): Added
[cacao.git] / src / vmcore / loader.c
1 /* src/vmcore/loader.c - class loader functions
2
3    Copyright (C) 1996-2005, 2006, 2007 R. Grafl, A. Krall, C. Kruegel,
4    C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,
5    E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,
6    J. Wenninger, Institut f. Computersprachen - TU Wien
7
8    This file is part of CACAO.
9
10    This program is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License as
12    published by the Free Software Foundation; either version 2, or (at
13    your option) any later version.
14
15    This program is distributed in the hope that it will be useful, but
16    WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23    02110-1301, USA.
24
25 */
26
27
28 #include "config.h"
29
30 #include <stdlib.h>
31 #include <string.h>
32 #include <assert.h>
33
34 #include "vm/types.h"
35
36 #include "mm/memory.h"
37
38 #include "native/llni.h"
39
40 #include "threads/lock-common.h"
41
42 #include "toolbox/hashtable.h"
43 #include "toolbox/logging.h"
44
45 #include "vm/builtin.h"
46 #include "vm/exceptions.h"
47 #include "vm/global.h"
48 #include "vm/package.h"
49 #include "vm/primitive.h"
50 #include "vm/resolve.h"
51 #include "vm/stringlocal.h"
52 #include "vm/vm.h"
53
54 #include "vm/jit_interface.h"
55
56 #if defined(ENABLE_JAVASE)
57 # include "vmcore/annotation.h"
58 # include "vmcore/stackmap.h"
59 #endif
60
61 #include "vmcore/classcache.h"
62 #include "vmcore/field.h"
63 #include "vmcore/linker.h"
64 #include "vmcore/loader.h"
65 #include "vmcore/method.h"
66 #include "vmcore/options.h"
67 #include "vmcore/rt-timing.h"
68
69 #if defined(ENABLE_STATISTICS)
70 # include "vmcore/statistics.h"
71 #endif
72
73 #include "vmcore/suck.h"
74
75 #if defined(ENABLE_ZLIB)
76 # include "vmcore/zip.h"
77 #endif
78
79 #if defined(ENABLE_JVMTI)
80 # include "native/jvmti/cacaodbg.h"
81 #endif
82
83
84 /* global variables ***********************************************************/
85
86 static hashtable *hashtable_classloader;
87
88
89 /* loader_preinit **************************************************************
90
91    Initializes the classpath list and loads classes required for the
92    primitive table.
93
94    NOTE: Exceptions thrown during VM initialization are caught in the
95          exception functions themselves.
96
97 *******************************************************************************/
98  
99 void loader_preinit(void)
100 {
101 #if defined(ENABLE_THREADS)
102         list_classpath_entry *lce;
103
104         /* Initialize the monitor pointer for zip/jar file locking. */
105
106         for (lce = list_first(list_classpath_entries); lce != NULL;
107                  lce = list_next(list_classpath_entries, lce)) {
108                 if (lce->type == CLASSPATH_ARCHIVE)
109                         LOCK_INIT_OBJECT_LOCK(lce);
110         }
111 #endif
112
113         /* initialize classloader hashtable, 10 entries should be enough */
114
115         hashtable_classloader = NEW(hashtable);
116         hashtable_create(hashtable_classloader, 10);
117
118         /* Load the most basic classes. */
119
120         assert(vm_initializing == true);
121
122         class_java_lang_Object     = load_class_bootstrap(utf_java_lang_Object);
123
124 #if defined(ENABLE_JAVASE)
125         class_java_lang_Cloneable  = load_class_bootstrap(utf_java_lang_Cloneable);
126         class_java_io_Serializable = load_class_bootstrap(utf_java_io_Serializable);
127 #endif
128 }
129
130
131 /* loader_init *****************************************************************
132
133    Loads all classes required in the VM.
134
135    NOTE: Exceptions thrown during VM initialization are caught in the
136          exception functions themselves.
137
138 *******************************************************************************/
139  
140 void loader_init(void)
141 {
142         /* Load primitive-type wrapping classes. */
143
144         assert(vm_initializing == true);
145
146 #if defined(ENABLE_JAVASE)
147         class_java_lang_Void       = load_class_bootstrap(utf_java_lang_Void);
148 #endif
149
150         class_java_lang_Boolean    = load_class_bootstrap(utf_java_lang_Boolean);
151         class_java_lang_Byte       = load_class_bootstrap(utf_java_lang_Byte);
152         class_java_lang_Character  = load_class_bootstrap(utf_java_lang_Character);
153         class_java_lang_Short      = load_class_bootstrap(utf_java_lang_Short);
154         class_java_lang_Integer    = load_class_bootstrap(utf_java_lang_Integer);
155         class_java_lang_Long       = load_class_bootstrap(utf_java_lang_Long);
156         class_java_lang_Float      = load_class_bootstrap(utf_java_lang_Float);
157         class_java_lang_Double     = load_class_bootstrap(utf_java_lang_Double);
158
159         /* Load important system classes. */
160
161         class_java_lang_Class      = load_class_bootstrap(utf_java_lang_Class);
162         class_java_lang_String     = load_class_bootstrap(utf_java_lang_String);
163
164 #if defined(ENABLE_JAVASE)
165         class_java_lang_ClassLoader =
166                 load_class_bootstrap(utf_java_lang_ClassLoader);
167
168         class_java_lang_SecurityManager =
169                 load_class_bootstrap(utf_java_lang_SecurityManager);
170 #endif
171
172         class_java_lang_System     =
173                 load_class_bootstrap(utf_new_char("java/lang/System"));
174
175         class_java_lang_Thread     =
176                 load_class_bootstrap(utf_new_char("java/lang/Thread"));
177
178 #if defined(ENABLE_JAVASE)
179         class_java_lang_ThreadGroup =
180                 load_class_bootstrap(utf_java_lang_ThreadGroup);
181 #endif
182
183         class_java_lang_Throwable  = load_class_bootstrap(utf_java_lang_Throwable);
184
185 #if defined(WITH_CLASSPATH_GNU)
186         class_java_lang_VMSystem   =
187                 load_class_bootstrap(utf_new_char("java/lang/VMSystem"));
188
189         class_java_lang_VMThread   =
190                 load_class_bootstrap(utf_new_char("java/lang/VMThread"));
191
192         class_java_lang_VMThrowable =
193                 load_class_bootstrap(utf_new_char("java/lang/VMThrowable"));
194 #endif
195
196         /* Some classes which may be used often. */
197
198 #if defined(ENABLE_JAVASE)
199         class_java_lang_StackTraceElement =
200                 load_class_bootstrap(utf_java_lang_StackTraceElement);
201
202         class_java_lang_reflect_Constructor =
203                 load_class_bootstrap(utf_java_lang_reflect_Constructor);
204
205         class_java_lang_reflect_Field =
206                 load_class_bootstrap(utf_java_lang_reflect_Field);
207
208         class_java_lang_reflect_Method =
209                 load_class_bootstrap(utf_java_lang_reflect_Method);
210
211         class_java_security_PrivilegedAction =
212                 load_class_bootstrap(utf_new_char("java/security/PrivilegedAction"));
213
214         class_java_util_HashMap = 
215                 load_class_bootstrap(utf_new_char("java/util/HashMap"));
216
217         class_java_util_Vector     = load_class_bootstrap(utf_java_util_Vector);
218
219 # if defined(WITH_CLASSPATH_SUN)
220         class_sun_reflect_MagicAccessorImpl =
221                 load_class_bootstrap(utf_new_char("sun/reflect/MagicAccessorImpl"));
222 # endif
223
224         arrayclass_java_lang_Object =
225                 load_class_bootstrap(utf_new_char("[Ljava/lang/Object;"));
226
227 # if defined(ENABLE_ANNOTATIONS)
228         /* needed by annotation support */
229         class_sun_reflect_ConstantPool =
230                 load_class_bootstrap(utf_new_char("sun/reflect/ConstantPool"));
231
232 #  if defined(WITH_CLASSPATH_GNU)
233         /* needed by GNU Classpaths annotation support */
234         class_sun_reflect_annotation_AnnotationParser =
235                 load_class_bootstrap(utf_new_char("sun/reflect/annotation/AnnotationParser"));
236 #  endif
237 # endif
238 #endif
239 }
240
241
242 /* loader_hashtable_classloader_add ********************************************
243
244    Adds an entry to the classloader hashtable.
245
246    REMEMBER: Also use this to register native loaders!
247
248 *******************************************************************************/
249
250 classloader *loader_hashtable_classloader_add(java_handle_t *cl)
251 {
252         hashtable_classloader_entry *cle;
253         u4   key;
254         u4   slot;
255
256         if (cl == NULL)
257                 return NULL;
258
259         LOCK_MONITOR_ENTER(hashtable_classloader->header);
260
261         LLNI_CRITICAL_START;
262
263         /* key for entry is the hashcode of the classloader;
264            aligned to 16-byte boundaries */
265
266         key  = heap_hashcode(LLNI_DIRECT(cl)) >> 4;
267         slot = key & (hashtable_classloader->size - 1);
268         cle  = hashtable_classloader->ptr[slot];
269
270         /* search hashchain for existing entry */
271
272         while (cle) {
273                 if (cle->object == LLNI_DIRECT(cl))
274                         break;
275
276                 cle = cle->hashlink;
277         }
278
279         LLNI_CRITICAL_END;
280
281         /* if no classloader was found, we create a new entry here */
282
283         if (cle == NULL) {
284                 cle = NEW(hashtable_classloader_entry);
285
286 #if defined(ENABLE_GC_CACAO)
287                 /* register the classloader object with the GC */
288
289                 gc_reference_register(&(cle->object), GC_REFTYPE_CLASSLOADER);
290 #endif
291
292                 LLNI_CRITICAL_START;
293
294                 cle->object = LLNI_DIRECT(cl);
295
296                 LLNI_CRITICAL_END;
297
298 /*#define LOADER_DEBUG_CLASSLOADER*/
299 #ifdef LOADER_DEBUG_CLASSLOADER
300                 printf("CLASSLOADER: adding new classloader entry %p for %p: ", cle, cl);
301                 class_print(LLNI_vftbl_direct(cl)->class);
302                 printf("\n");
303                 fflush(stdout);
304 #endif
305
306                 /* insert entry into hashtable */
307
308                 cle->hashlink = hashtable_classloader->ptr[slot];
309                 hashtable_classloader->ptr[slot] = cle;
310
311                 /* update number of entries */
312
313                 hashtable_classloader->entries++;
314         }
315
316
317         LOCK_MONITOR_EXIT(hashtable_classloader->header);
318
319 #if defined(ENABLE_HANDLES)
320         return cle;
321 #else
322         return cl;
323 #endif
324 }
325
326
327 /* loader_hashtable_classloader_find *******************************************
328
329    Find an entry in the classloader hashtable.
330
331 *******************************************************************************/
332
333 classloader *loader_hashtable_classloader_find(java_handle_t *cl)
334 {
335         hashtable_classloader_entry *cle;
336         u4   key;
337         u4   slot;
338
339         if (cl == NULL)
340                 return NULL;
341
342         LLNI_CRITICAL_START;
343
344         /* key for entry is the hashcode of the classloader;
345            aligned to 16-byte boundaries */
346
347         key  = heap_hashcode(LLNI_DIRECT(cl)) >> 4;
348         slot = key & (hashtable_classloader->size - 1);
349         cle  = hashtable_classloader->ptr[slot];
350
351         /* search hashchain for existing entry */
352
353         while (cle) {
354                 if (cle->object == LLNI_DIRECT(cl))
355                         break;
356
357                 cle = cle->hashlink;
358         }
359
360 #ifdef LOADER_DEBUG_CLASSLOADER
361         if (cle == NULL) {
362                 printf("CLASSLOADER: unable to find classloader entry for %p: ", cl);
363                 class_print(LLNI_vftbl_direct(cl)->class);
364                 printf("\n");
365                 fflush(stdout);
366         }
367 #endif
368
369         LLNI_CRITICAL_END;
370
371 #if defined(ENABLE_HANDLES)
372         return cle;
373 #else
374         return cl;
375 #endif
376 }
377
378
379 /* loader_load_all_classes *****************************************************
380
381    Loads all classes specified in the BOOTCLASSPATH.
382
383 *******************************************************************************/
384
385 void loader_load_all_classes(void)
386 {
387         list_classpath_entry    *lce;
388 #if defined(ENABLE_ZLIB)
389         hashtable               *ht;
390         s4                       slot;
391         hashtable_zipfile_entry *htzfe;
392         utf                     *u;
393 #endif
394
395         for (lce = list_first(list_classpath_entries); lce != NULL;
396                  lce = list_next(list_classpath_entries, lce)) {
397 #if defined(ENABLE_ZLIB)
398                 if (lce->type == CLASSPATH_ARCHIVE) {
399                         /* get the classes hashtable */
400
401                         ht = lce->htclasses;
402
403                         for (slot = 0; slot < ht->size; slot++) {
404                                 htzfe = (hashtable_zipfile_entry *) ht->ptr[slot];
405
406                                 for (; htzfe; htzfe = htzfe->hashlink) {
407                                         u = htzfe->filename;
408
409                                         /* skip all entries in META-INF and .properties,
410                        .png files */
411
412                                         if (!strncmp(u->text, "META-INF", strlen("META-INF")) ||
413                                                 strstr(u->text, ".properties") ||
414                                                 strstr(u->text, ".png"))
415                                                 continue;
416
417                                         /* load class from bootstrap classloader */
418
419                                         if (!load_class_bootstrap(u)) {
420                                                 fprintf(stderr, "Error loading: ");
421                                                 utf_fprint_printable_ascii_classname(stderr, u);
422                                                 fprintf(stderr, "\n");
423
424 #if !defined(NDEBUG)
425                                                 /* print out exception and cause */
426
427                                                 exceptions_print_current_exception();
428 #endif
429                                         }
430                                 }
431                         }
432
433                 } else {
434 #endif
435 #if defined(ENABLE_ZLIB)
436                 }
437 #endif
438         }
439 }
440
441
442 /* loader_skip_attribute_body **************************************************
443
444    Skips an attribute the attribute_name_index has already been read.
445         
446    attribute_info {
447        u2 attribute_name_index;
448        u4 attribute_length;
449        u1 info[attribute_length];
450    }
451
452 *******************************************************************************/
453
454 bool loader_skip_attribute_body(classbuffer *cb)
455 {
456         u4 attribute_length;
457
458         if (!suck_check_classbuffer_size(cb, 4))
459                 return false;
460
461         attribute_length = suck_u4(cb);
462
463         if (!suck_check_classbuffer_size(cb, attribute_length))
464                 return false;
465
466         suck_skip_nbytes(cb, attribute_length);
467
468         return true;
469 }
470
471
472 /* load_constantpool ***********************************************************
473
474    Loads the constantpool of a class, the entries are transformed into
475    a simpler format by resolving references (a detailed overview of
476    the compact structures can be found in global.h).
477
478 *******************************************************************************/
479
480 static bool load_constantpool(classbuffer *cb, descriptor_pool *descpool)
481 {
482
483         /* The following structures are used to save information which cannot be 
484            processed during the first pass. After the complete constantpool has 
485            been traversed the references can be resolved. 
486            (only in specific order)                                                */
487         
488         /* CONSTANT_Class entries */
489         typedef struct forward_class {
490                 struct forward_class *next;
491                 u2 thisindex;
492                 u2 name_index;
493         } forward_class;
494
495         /* CONSTANT_String */
496         typedef struct forward_string {
497                 struct forward_string *next;
498                 u2 thisindex;
499                 u2 string_index;
500         } forward_string;
501
502         /* CONSTANT_NameAndType */
503         typedef struct forward_nameandtype {
504                 struct forward_nameandtype *next;
505                 u2 thisindex;
506                 u2 name_index;
507                 u2 sig_index;
508         } forward_nameandtype;
509
510         /* CONSTANT_Fieldref, CONSTANT_Methodref or CONSTANT_InterfaceMethodref */
511         typedef struct forward_fieldmethint {
512                 struct forward_fieldmethint *next;
513                 u2 thisindex;
514                 u1 tag;
515                 u2 class_index;
516                 u2 nameandtype_index;
517         } forward_fieldmethint;
518
519
520         classinfo *c;
521         u4 idx;
522
523         forward_class *forward_classes = NULL;
524         forward_string *forward_strings = NULL;
525         forward_nameandtype *forward_nameandtypes = NULL;
526         forward_fieldmethint *forward_fieldmethints = NULL;
527
528         forward_class *nfc;
529         forward_string *nfs;
530         forward_nameandtype *nfn;
531         forward_fieldmethint *nff;
532
533         u4 cpcount;
534         u1 *cptags;
535         voidptr *cpinfos;
536
537         c = cb->class;
538
539         /* number of entries in the constant_pool table plus one */
540         if (!suck_check_classbuffer_size(cb, 2))
541                 return false;
542
543         cpcount = c->cpcount = suck_u2(cb);
544
545         /* allocate memory */
546         cptags  = c->cptags  = MNEW(u1, cpcount);
547         cpinfos = c->cpinfos = MNEW(voidptr, cpcount);
548
549         if (cpcount < 1) {
550                 exceptions_throw_classformaterror(c, "Illegal constant pool size");
551                 return false;
552         }
553         
554 #if defined(ENABLE_STATISTICS)
555         if (opt_stat)
556                 count_const_pool_len += (sizeof(u1) + sizeof(voidptr)) * cpcount;
557 #endif
558         
559         /* initialize constantpool */
560         for (idx = 0; idx < cpcount; idx++) {
561                 cptags[idx] = CONSTANT_UNUSED;
562                 cpinfos[idx] = NULL;
563         }
564
565                         
566         /******* first pass *******/
567         /* entries which cannot be resolved now are written into 
568            temporary structures and traversed again later        */
569                    
570         idx = 1;
571         while (idx < cpcount) {
572                 u4 t;
573
574                 /* get constant type */
575                 if (!suck_check_classbuffer_size(cb, 1))
576                         return false;
577
578                 t = suck_u1(cb);
579
580                 switch (t) {
581                 case CONSTANT_Class:
582                         nfc = DNEW(forward_class);
583
584                         nfc->next = forward_classes;
585                         forward_classes = nfc;
586
587                         nfc->thisindex = idx;
588                         /* reference to CONSTANT_NameAndType */
589                         if (!suck_check_classbuffer_size(cb, 2))
590                                 return false;
591
592                         nfc->name_index = suck_u2(cb);
593
594                         idx++;
595                         break;
596                         
597                 case CONSTANT_String:
598                         nfs = DNEW(forward_string);
599                                 
600                         nfs->next = forward_strings;
601                         forward_strings = nfs;
602                                 
603                         nfs->thisindex = idx;
604
605                         /* reference to CONSTANT_Utf8_info with string characters */
606                         if (!suck_check_classbuffer_size(cb, 2))
607                                 return false;
608
609                         nfs->string_index = suck_u2(cb);
610                                 
611                         idx++;
612                         break;
613
614                 case CONSTANT_NameAndType:
615                         nfn = DNEW(forward_nameandtype);
616                                 
617                         nfn->next = forward_nameandtypes;
618                         forward_nameandtypes = nfn;
619                                 
620                         nfn->thisindex = idx;
621
622                         if (!suck_check_classbuffer_size(cb, 2 + 2))
623                                 return false;
624
625                         /* reference to CONSTANT_Utf8_info containing simple name */
626                         nfn->name_index = suck_u2(cb);
627
628                         /* reference to CONSTANT_Utf8_info containing field or method
629                            descriptor */
630                         nfn->sig_index = suck_u2(cb);
631                                 
632                         idx++;
633                         break;
634
635                 case CONSTANT_Fieldref:
636                 case CONSTANT_Methodref:
637                 case CONSTANT_InterfaceMethodref:
638                         nff = DNEW(forward_fieldmethint);
639                         
640                         nff->next = forward_fieldmethints;
641                         forward_fieldmethints = nff;
642
643                         nff->thisindex = idx;
644                         /* constant type */
645                         nff->tag = t;
646
647                         if (!suck_check_classbuffer_size(cb, 2 + 2))
648                                 return false;
649
650                         /* class or interface type that contains the declaration of the
651                            field or method */
652                         nff->class_index = suck_u2(cb);
653
654                         /* name and descriptor of the field or method */
655                         nff->nameandtype_index = suck_u2(cb);
656
657                         idx++;
658                         break;
659                                 
660                 case CONSTANT_Integer: {
661                         constant_integer *ci = NEW(constant_integer);
662
663 #if defined(ENABLE_STATISTICS)
664                         if (opt_stat)
665                                 count_const_pool_len += sizeof(constant_integer);
666 #endif
667
668                         if (!suck_check_classbuffer_size(cb, 4))
669                                 return false;
670
671                         ci->value = suck_s4(cb);
672                         cptags[idx] = CONSTANT_Integer;
673                         cpinfos[idx] = ci;
674
675                         idx++;
676                         break;
677                 }
678                                 
679                 case CONSTANT_Float: {
680                         constant_float *cf = NEW(constant_float);
681
682 #if defined(ENABLE_STATISTICS)
683                         if (opt_stat)
684                                 count_const_pool_len += sizeof(constant_float);
685 #endif
686
687                         if (!suck_check_classbuffer_size(cb, 4))
688                                 return false;
689
690                         cf->value = suck_float(cb);
691                         cptags[idx] = CONSTANT_Float;
692                         cpinfos[idx] = cf;
693
694                         idx++;
695                         break;
696                 }
697                                 
698                 case CONSTANT_Long: {
699                         constant_long *cl = NEW(constant_long);
700                                         
701 #if defined(ENABLE_STATISTICS)
702                         if (opt_stat)
703                                 count_const_pool_len += sizeof(constant_long);
704 #endif
705
706                         if (!suck_check_classbuffer_size(cb, 8))
707                                 return false;
708
709                         cl->value = suck_s8(cb);
710                         cptags[idx] = CONSTANT_Long;
711                         cpinfos[idx] = cl;
712                         idx += 2;
713                         if (idx > cpcount) {
714                                 exceptions_throw_classformaterror(c, "Invalid constant pool entry");
715                                 return false;
716                         }
717                         break;
718                 }
719                         
720                 case CONSTANT_Double: {
721                         constant_double *cd = NEW(constant_double);
722                                 
723 #if defined(ENABLE_STATISTICS)
724                         if (opt_stat)
725                                 count_const_pool_len += sizeof(constant_double);
726 #endif
727
728                         if (!suck_check_classbuffer_size(cb, 8))
729                                 return false;
730
731                         cd->value = suck_double(cb);
732                         cptags[idx] = CONSTANT_Double;
733                         cpinfos[idx] = cd;
734                         idx += 2;
735                         if (idx > cpcount) {
736                                 exceptions_throw_classformaterror(c, "Invalid constant pool entry");
737                                 return false;
738                         }
739                         break;
740                 }
741                                 
742                 case CONSTANT_Utf8: { 
743                         u4 length;
744
745                         /* number of bytes in the bytes array (not string-length) */
746                         if (!suck_check_classbuffer_size(cb, 2))
747                                 return false;
748
749                         length = suck_u2(cb);
750                         cptags[idx] = CONSTANT_Utf8;
751
752                         /* validate the string */
753                         if (!suck_check_classbuffer_size(cb, length))
754                                 return false;
755
756 #ifdef ENABLE_VERIFIER
757                         if (opt_verify &&
758                                 !is_valid_utf((char *) cb->pos, (char *) (cb->pos + length))) 
759                         {
760                                 exceptions_throw_classformaterror(c, "Invalid UTF-8 string");
761                                 return false;
762                         }
763 #endif /* ENABLE_VERIFIER */
764                         /* insert utf-string into the utf-symboltable */
765                         cpinfos[idx] = utf_new((char *) cb->pos, length);
766
767                         /* skip bytes of the string (buffer size check above) */
768                         suck_skip_nbytes(cb, length);
769                         idx++;
770                         break;
771                 }
772                                                                                 
773                 default:
774                         exceptions_throw_classformaterror(c, "Illegal constant pool type");
775                         return false;
776                 }  /* end switch */
777         } /* end while */
778
779
780         /* resolve entries in temporary structures */
781
782         while (forward_classes) {
783                 utf *name =
784                         class_getconstant(c, forward_classes->name_index, CONSTANT_Utf8);
785                 if (!name)
786                         return false;
787
788 #ifdef ENABLE_VERIFIER
789                 if (opt_verify && !is_valid_name_utf(name)) {
790                         exceptions_throw_classformaterror(c, "Class reference with invalid name");
791                         return false;
792                 }
793 #endif /* ENABLE_VERIFIER */
794
795                 /* add all class references to the descriptor_pool */
796
797                 if (!descriptor_pool_add_class(descpool, name))
798                         return false;
799
800                 cptags[forward_classes->thisindex] = CONSTANT_Class;
801
802                 /* the classref is created later */
803                 cpinfos[forward_classes->thisindex] = name;
804
805                 nfc = forward_classes;
806                 forward_classes = forward_classes->next;
807         }
808
809         while (forward_strings) {
810                 utf *text =
811                         class_getconstant(c, forward_strings->string_index, CONSTANT_Utf8);
812                 if (!text)
813                         return false;
814
815                 /* resolve utf-string */
816                 cptags[forward_strings->thisindex] = CONSTANT_String;
817                 cpinfos[forward_strings->thisindex] = text;
818                 
819                 nfs = forward_strings;
820                 forward_strings = forward_strings->next;
821         }
822
823         while (forward_nameandtypes) {
824                 constant_nameandtype *cn = NEW(constant_nameandtype);   
825
826 #if defined(ENABLE_STATISTICS)
827                 if (opt_stat)
828                         count_const_pool_len += sizeof(constant_nameandtype);
829 #endif
830
831                 /* resolve simple name and descriptor */
832                 cn->name = class_getconstant(c,
833                                                                          forward_nameandtypes->name_index,
834                                                                          CONSTANT_Utf8);
835                 if (!cn->name)
836                         return false;
837
838                 cn->descriptor = class_getconstant(c,
839                                                                                    forward_nameandtypes->sig_index,
840                                                                                    CONSTANT_Utf8);
841                 if (!cn->descriptor)
842                         return false;
843
844 #ifdef ENABLE_VERIFIER
845                 if (opt_verify) {
846                         /* check name */
847                         if (!is_valid_name_utf(cn->name)) {
848                                 exceptions_throw_classformaterror(c,
849                                                                                                   "Illegal Field name \"%s\"",
850                                                                                                   cn->name->text);
851
852                                 return false;
853                         }
854
855                         /* disallow referencing <clinit> among others */
856                         if (cn->name->text[0] == '<' && cn->name != utf_init) {
857                                 exceptions_throw_classformaterror(c, "Illegal reference to special method");
858                                 return false;
859                         }
860                 }
861 #endif /* ENABLE_VERIFIER */
862
863                 cptags[forward_nameandtypes->thisindex] = CONSTANT_NameAndType;
864                 cpinfos[forward_nameandtypes->thisindex] = cn;
865
866                 nfn = forward_nameandtypes;
867                 forward_nameandtypes = forward_nameandtypes->next;
868         }
869
870         while (forward_fieldmethints) {
871                 constant_nameandtype *nat;
872                 constant_FMIref *fmi = NEW(constant_FMIref);
873
874 #if defined(ENABLE_STATISTICS)
875                 if (opt_stat)
876                         count_const_pool_len += sizeof(constant_FMIref);
877 #endif
878                 /* resolve simple name and descriptor */
879
880                 nat = class_getconstant(c,
881                                                                 forward_fieldmethints->nameandtype_index,
882                                                                 CONSTANT_NameAndType);
883                 if (!nat)
884                         return false;
885
886                 /* add all descriptors in {Field,Method}ref to the descriptor_pool */
887
888                 if (!descriptor_pool_add(descpool, nat->descriptor, NULL))
889                         return false;
890
891                 /* the classref is created later */
892
893                 fmi->p.index = forward_fieldmethints->class_index;
894                 fmi->name = nat->name;
895                 fmi->descriptor = nat->descriptor;
896
897                 cptags[forward_fieldmethints->thisindex] = forward_fieldmethints->tag;
898                 cpinfos[forward_fieldmethints->thisindex] = fmi;
899         
900                 nff = forward_fieldmethints;
901                 forward_fieldmethints = forward_fieldmethints->next;
902         }
903
904         /* everything was ok */
905
906         return true;
907 }
908
909
910 /* loader_load_attribute_signature *********************************************
911
912    Signature_attribute {
913        u2 attribute_name_index;
914            u4 atrribute_length;
915            u2 signature_index;
916    }
917
918 *******************************************************************************/
919
920 #if defined(ENABLE_JAVASE)
921 bool loader_load_attribute_signature(classbuffer *cb, utf **signature)
922 {
923         classinfo *c;
924         u4         attribute_length;
925         u2         signature_index;
926
927         /* get classinfo */
928
929         c = cb->class;
930
931         /* check remaining bytecode */
932
933         if (!suck_check_classbuffer_size(cb, 4 + 2))
934                 return false;
935
936         /* check attribute length */
937
938         attribute_length = suck_u4(cb);
939
940         if (attribute_length != 2) {
941                 exceptions_throw_classformaterror(c, "Wrong size for VALUE attribute");
942                 return false;
943         }
944
945         if (*signature != NULL) {
946                 exceptions_throw_classformaterror(c, "Multiple Signature attributes");
947                 return false;
948         }
949
950         /* get signature */
951
952         signature_index = suck_u2(cb);
953
954         if (!(*signature = class_getconstant(c, signature_index, CONSTANT_Utf8)))
955                 return false;
956
957         return true;
958 }
959 #endif /* defined(ENABLE_JAVASE) */
960
961
962 /* load_class_from_sysloader ***************************************************
963
964    Load the class with the given name using the system class loader
965
966    IN:
967        name.............the classname
968
969    RETURN VALUE:
970        the loaded class, or
971            NULL if an exception has been thrown
972
973 *******************************************************************************/
974
975 classinfo *load_class_from_sysloader(utf *name)
976 {
977         methodinfo    *m;
978         java_handle_t *clo;
979         classloader   *cl;
980         classinfo     *c;
981
982         assert(class_java_lang_Object);
983         assert(class_java_lang_ClassLoader);
984         assert(class_java_lang_ClassLoader->state & CLASS_LINKED);
985         
986         m = class_resolveclassmethod(class_java_lang_ClassLoader,
987                                                                  utf_getSystemClassLoader,
988                                                                  utf_void__java_lang_ClassLoader,
989                                                                  class_java_lang_Object,
990                                                                  false);
991
992         if (!m)
993                 return false;
994
995         clo = vm_call_method(m, NULL);
996
997         if (!clo)
998                 return false;
999
1000         cl = loader_hashtable_classloader_add(clo);
1001
1002         c = load_class_from_classloader(name, cl);
1003
1004         return c;
1005 }
1006
1007
1008 /* load_class_from_classloader *************************************************
1009
1010    Load the class with the given name using the given user-defined class loader.
1011
1012    IN:
1013        name.............the classname
1014            cl...............user-defined class loader
1015            
1016    RETURN VALUE:
1017        the loaded class, or
1018            NULL if an exception has been thrown
1019
1020 *******************************************************************************/
1021
1022 classinfo *load_class_from_classloader(utf *name, classloader *cl)
1023 {
1024         java_handle_t *o;
1025         classinfo     *c;
1026         classinfo     *tmpc;
1027         java_handle_t *string;
1028 #if defined(ENABLE_RT_TIMING)
1029         struct timespec time_start, time_lookup, time_prepare, time_java, 
1030                                         time_cache;
1031 #endif
1032
1033         RT_TIMING_GET_TIME(time_start);
1034
1035         assert(name);
1036
1037         /* lookup if this class has already been loaded */
1038
1039         c = classcache_lookup(cl, name);
1040
1041         RT_TIMING_GET_TIME(time_lookup);
1042         RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_CL_LOOKUP);
1043
1044         if (c != NULL)
1045                 return c;
1046
1047         /* if other class loader than bootstrap, call it */
1048
1049         if (cl != NULL) {
1050                 methodinfo *lc;
1051                 char       *text;
1052                 s4          namelen;
1053
1054                 text = name->text;
1055                 namelen = name->blength;
1056
1057                 /* handle array classes */
1058                 if (text[0] == '[') {
1059                         classinfo *comp;
1060                         utf       *u;
1061
1062                         switch (text[1]) {
1063                         case 'L':
1064                                 /* check for cases like `[L;' or `[L[I;' or `[Ljava.lang.Object' */
1065                                 if (namelen < 4 || text[2] == '[' || text[namelen - 1] != ';') {
1066                                         exceptions_throw_classnotfoundexception(name);
1067                                         return false;
1068                                 }
1069
1070                                 u = utf_new(text + 2, namelen - 3);
1071
1072                                 if (!(comp = load_class_from_classloader(u, cl)))
1073                                         return false;
1074
1075                                 /* create the array class */
1076
1077                                 c = class_array_of(comp, false);
1078
1079                                 tmpc = classcache_store(cl, c, true);
1080
1081                                 if (tmpc == NULL) {
1082                                         /* exception, free the loaded class */
1083                                         c->state &= ~CLASS_LOADING;
1084                                         class_free(c);
1085                                 }
1086
1087                                 return tmpc;
1088
1089                         case '[':
1090                                 /* load the component class */
1091
1092                                 u = utf_new(text + 1, namelen - 1);
1093
1094                                 if (!(comp = load_class_from_classloader(u, cl)))
1095                                         return false;
1096
1097                                 /* create the array class */
1098
1099                                 c = class_array_of(comp, false);
1100
1101                                 tmpc = classcache_store(cl, c, true);
1102
1103                                 if (tmpc == NULL) {
1104                                         /* exception, free the loaded class */
1105                                         c->state &= ~CLASS_LOADING;
1106                                         class_free(c);
1107                                 }
1108
1109                                 return tmpc;
1110
1111                         default:
1112                                 /* primitive array classes are loaded by the bootstrap loader */
1113
1114                                 c = load_class_bootstrap(name);
1115
1116                                 return c;
1117                         }
1118                 }
1119
1120                 LLNI_class_get(cl, c);
1121
1122 #if defined(WITH_CLASSPATH_SUN)
1123                 /* OpenJDK uses this internal function because it's
1124                    synchronized. */
1125
1126                 lc = class_resolveclassmethod(c,
1127                                                                           utf_loadClassInternal,
1128                                                                           utf_java_lang_String__java_lang_Class,
1129                                                                           NULL,
1130                                                                           true);
1131 #else
1132                 lc = class_resolveclassmethod(c,
1133                                                                           utf_loadClass,
1134                                                                           utf_java_lang_String__java_lang_Class,
1135                                                                           NULL,
1136                                                                           true);
1137 #endif
1138
1139                 if (lc == NULL)
1140                         return false; /* exception */
1141
1142                 /* move return value into `o' and cast it afterwards to a classinfo* */
1143
1144                 string = javastring_new_slash_to_dot(name);
1145
1146                 RT_TIMING_GET_TIME(time_prepare);
1147
1148                 o = vm_call_method(lc, (java_handle_t *) cl, string);
1149
1150                 RT_TIMING_GET_TIME(time_java);
1151
1152                 c = LLNI_classinfo_unwrap(o);
1153
1154                 if (c != NULL) {
1155                         /* Store this class in the loaded class cache. If another
1156                            class with the same (initloader,name) pair has been
1157                            stored earlier it will be returned by classcache_store
1158                            In this case classcache_store may not free the class
1159                            because it has already been exposed to Java code which
1160                            may have kept references to that class. */
1161
1162                     tmpc = classcache_store(cl, c, false);
1163
1164                         if (tmpc == NULL) {
1165                                 /* exception, free the loaded class */
1166                                 c->state &= ~CLASS_LOADING;
1167                                 class_free(c);
1168                         }
1169
1170                         c = tmpc;
1171                 }
1172
1173                 RT_TIMING_GET_TIME(time_cache);
1174
1175                 RT_TIMING_TIME_DIFF(time_lookup , time_prepare, RT_TIMING_LOAD_CL_PREPARE);
1176                 RT_TIMING_TIME_DIFF(time_prepare, time_java   , RT_TIMING_LOAD_CL_JAVA);
1177                 RT_TIMING_TIME_DIFF(time_java   , time_cache  , RT_TIMING_LOAD_CL_CACHE);
1178
1179                 /* SUN compatible -verbose:class output */
1180
1181                 if (opt_verboseclass && (c != NULL) && (c->classloader == cl)) {
1182                         printf("[Loaded ");
1183                         utf_display_printable_ascii_classname(name);
1184                         printf("]\n");
1185                 }
1186
1187 #if defined(ENABLE_JVMTI)
1188                 /* fire Class Load JVMTI event */
1189                 if (jvmti) jvmti_ClassLoadPrepare(false, c);
1190 #endif
1191
1192
1193                 return c;
1194         } 
1195
1196         c = load_class_bootstrap(name);
1197
1198         return c;
1199 }
1200
1201
1202 /* load_class_bootstrap ********************************************************
1203         
1204    Load the class with the given name using the bootstrap class loader.
1205
1206    IN:
1207        name.............the classname
1208
1209    RETURN VALUE:
1210        loaded classinfo, or
1211            NULL if an exception has been thrown
1212
1213    SYNCHRONIZATION:
1214        load_class_bootstrap is synchronized. It can be treated as an
1215            atomic operation.
1216
1217 *******************************************************************************/
1218
1219 classinfo *load_class_bootstrap(utf *name)
1220 {
1221         classbuffer *cb;
1222         classinfo   *c;
1223         classinfo   *r;
1224 #if defined(ENABLE_RT_TIMING)
1225         struct timespec time_start, time_lookup, time_array, time_suck, 
1226                                         time_load, time_cache;
1227 #endif
1228
1229         RT_TIMING_GET_TIME(time_start);
1230
1231         /* for debugging */
1232
1233         assert(name);
1234
1235         /* lookup if this class has already been loaded */
1236
1237         r = classcache_lookup(NULL, name);
1238
1239         if (r != NULL) {
1240                 RT_TIMING_GET_TIME(time_lookup);
1241                 RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_BOOT_LOOKUP);
1242                 
1243                 return r;
1244         }
1245
1246         RT_TIMING_GET_TIME(time_lookup);
1247         RT_TIMING_TIME_DIFF(time_start,time_lookup,RT_TIMING_LOAD_BOOT_LOOKUP);
1248                 
1249         /* create the classinfo */
1250
1251         c = class_create_classinfo(name);
1252
1253         /* handle array classes */
1254
1255         if (name->text[0] == '[') {
1256                 c = load_newly_created_array(c, NULL);
1257
1258                 if (c == NULL)
1259                         return NULL;
1260
1261                 assert(c->state & CLASS_LOADED);
1262
1263                 RT_TIMING_GET_TIME(time_array);
1264                 RT_TIMING_TIME_DIFF(time_start,time_array,RT_TIMING_LOAD_BOOT_ARRAY);
1265                 
1266                 return c;
1267         }
1268
1269 #if defined(ENABLE_STATISTICS)
1270         /* measure time */
1271
1272         if (opt_getcompilingtime)
1273                 compilingtime_stop();
1274
1275         if (opt_getloadingtime)
1276                 loadingtime_start();
1277 #endif
1278
1279         /* load classdata, throw exception on error */
1280
1281         cb = suck_start(c);
1282
1283         if (cb == NULL) {
1284                 exceptions_throw_classnotfoundexception(name);
1285                 return NULL;
1286         }
1287
1288         RT_TIMING_GET_TIME(time_suck);
1289         
1290         /* load the class from the buffer */
1291
1292         r = load_class_from_classbuffer(cb);
1293
1294         RT_TIMING_GET_TIME(time_load);
1295         
1296         if (r == NULL) {
1297                 /* the class could not be loaded, free the classinfo struct */
1298
1299                 class_free(c);
1300         }
1301         else {
1302                 /* Store this class in the loaded class cache this step also
1303                    checks the loading constraints. If the class has been
1304                    loaded before, the earlier loaded class is returned. */
1305
1306                 classinfo *res = classcache_store(NULL, c, true);
1307
1308                 if (res == NULL) {
1309                         /* exception */
1310                         class_free(c);
1311                 }
1312                 else {
1313                         /* Add the package name to the boot packages. */
1314
1315                         package_add(c->packagename);
1316                 }
1317
1318                 r = res;
1319         }
1320
1321         RT_TIMING_GET_TIME(time_cache);
1322         
1323         /* SUN compatible -verbose:class output */
1324
1325         if (opt_verboseclass && r) {
1326                 printf("[Loaded ");
1327                 utf_display_printable_ascii_classname(name);
1328                 printf(" from %s]\n", cb->path);
1329         }
1330
1331         /* free memory */
1332
1333         suck_stop(cb);
1334
1335 #if defined(ENABLE_STATISTICS)
1336         /* measure time */
1337
1338         if (opt_getloadingtime)
1339                 loadingtime_stop();
1340
1341         if (opt_getcompilingtime)
1342                 compilingtime_start();
1343 #endif
1344
1345         RT_TIMING_TIME_DIFF(time_lookup, time_suck , RT_TIMING_LOAD_BOOT_SUCK);
1346         RT_TIMING_TIME_DIFF(time_suck  , time_load , RT_TIMING_LOAD_BOOT_LOAD);
1347         RT_TIMING_TIME_DIFF(time_load  , time_cache, RT_TIMING_LOAD_BOOT_CACHE);
1348         RT_TIMING_TIME_DIFF(time_lookup, time_cache, RT_TIMING_LOAD_BOOT_TOTAL);
1349
1350         return r;
1351 }
1352
1353
1354 /* load_class_from_classbuffer_intern ******************************************
1355         
1356    Loads a class from a classbuffer into a given classinfo structure.
1357    Super-classes are also loaded at this point and some verfication
1358    checks are done.
1359
1360    SYNCHRONIZATION:
1361        This function is NOT synchronized!
1362    
1363 *******************************************************************************/
1364
1365 static bool load_class_from_classbuffer_intern(classbuffer *cb)
1366 {
1367         classinfo          *c;
1368         classinfo          *tc;
1369         utf                *name;
1370         utf                *supername;
1371         utf               **interfacesnames;
1372         utf                *u;
1373         constant_classref  *cr;
1374         int16_t             index;
1375
1376         u4 i,j;
1377         u4 ma, mi;
1378         descriptor_pool *descpool;
1379 #if defined(ENABLE_STATISTICS)
1380         u4 classrefsize;
1381         u4 descsize;
1382 #endif
1383 #if defined(ENABLE_RT_TIMING)
1384         struct timespec time_start, time_checks, time_ndpool, time_cpool,
1385                                         time_setup, time_fields, time_methods, time_classrefs,
1386                                         time_descs,     time_setrefs, time_parsefds, time_parsemds,
1387                                         time_parsecpool, time_verify, time_attrs;
1388 #endif
1389
1390         RT_TIMING_GET_TIME(time_start);
1391
1392         /* Get the classbuffer's class. */
1393
1394         c = cb->class;
1395
1396         if (!suck_check_classbuffer_size(cb, 4 + 2 + 2))
1397                 return false;
1398
1399         /* check signature */
1400
1401         if (suck_u4(cb) != MAGIC) {
1402                 exceptions_throw_classformaterror(c, "Bad magic number");
1403                 return false;
1404         }
1405
1406         /* check version */
1407
1408         mi = suck_u2(cb);
1409         ma = suck_u2(cb);
1410
1411         if (!(ma < MAJOR_VERSION || (ma == MAJOR_VERSION && mi <= MINOR_VERSION))) {
1412                 exceptions_throw_unsupportedclassversionerror(c, ma, mi);
1413                 return false;
1414         }
1415
1416         RT_TIMING_GET_TIME(time_checks);
1417
1418         /* create a new descriptor pool */
1419
1420         descpool = descriptor_pool_new(c);
1421
1422         RT_TIMING_GET_TIME(time_ndpool);
1423
1424         /* load the constant pool */
1425
1426         if (!load_constantpool(cb, descpool))
1427                 return false;
1428
1429         RT_TIMING_GET_TIME(time_cpool);
1430
1431         /* ACC flags */
1432
1433         if (!suck_check_classbuffer_size(cb, 2))
1434                 return false;
1435
1436         /* We OR the flags here, as we set already some flags in
1437            class_create_classinfo. */
1438
1439         c->flags |= suck_u2(cb);
1440
1441         /* check ACC flags consistency */
1442
1443         if (c->flags & ACC_INTERFACE) {
1444                 if (!(c->flags & ACC_ABSTRACT)) {
1445                         /* We work around this because interfaces in JDK 1.1 are
1446                          * not declared abstract. */
1447
1448                         c->flags |= ACC_ABSTRACT;
1449                 }
1450
1451                 if (c->flags & ACC_FINAL) {
1452                         exceptions_throw_classformaterror(c,
1453                                                                                           "Illegal class modifiers: 0x%X",
1454                                                                                           c->flags);
1455                         return false;
1456                 }
1457
1458                 if (c->flags & ACC_SUPER) {
1459                         c->flags &= ~ACC_SUPER; /* kjc seems to set this on interfaces */
1460                 }
1461         }
1462
1463         if ((c->flags & (ACC_ABSTRACT | ACC_FINAL)) == (ACC_ABSTRACT | ACC_FINAL)) {
1464                 exceptions_throw_classformaterror(c,
1465                                                                                   "Illegal class modifiers: 0x%X",
1466                                                                                   c->flags);
1467                 return false;
1468         }
1469
1470         if (!suck_check_classbuffer_size(cb, 2 + 2))
1471                 return false;
1472
1473         /* This class. */
1474
1475         index = suck_u2(cb);
1476
1477         name = (utf *) class_getconstant(c, index, CONSTANT_Class);
1478
1479         if (name == NULL)
1480                 return false;
1481
1482         if (c->name == utf_not_named_yet) {
1483                 /* we finally have a name for this class */
1484                 c->name = name;
1485                 class_set_packagename(c);
1486         }
1487         else if (name != c->name) {
1488                 exceptions_throw_noclassdeffounderror_wrong_name(c, name);
1489                 return false;
1490         }
1491
1492         /* Retrieve superclass. */
1493
1494         c->super = NULL;
1495
1496         index = suck_u2(cb);
1497
1498         if (index == 0) {
1499                 supername = NULL;
1500
1501                 /* This is only allowed for java.lang.Object. */
1502
1503                 if (c->name != utf_java_lang_Object) {
1504                         exceptions_throw_classformaterror(c, "Bad superclass index");
1505                         return false;
1506                 }
1507         }
1508         else {
1509                 supername = (utf *) class_getconstant(c, index, CONSTANT_Class);
1510
1511                 if (supername == NULL)
1512                         return false;
1513
1514                 /* java.lang.Object may not have a super class. */
1515
1516                 if (c->name == utf_java_lang_Object) {
1517                         exceptions_throw_classformaterror(NULL, "java.lang.Object with superclass");
1518                         return false;
1519                 }
1520
1521                 /* Detect circularity. */
1522
1523                 if (supername == c->name) {
1524                         exceptions_throw_classcircularityerror(c);
1525                         return false;
1526                 }
1527
1528                 /* Interfaces must have java.lang.Object as super class. */
1529
1530                 if ((c->flags & ACC_INTERFACE) && (supername != utf_java_lang_Object)) {
1531                         exceptions_throw_classformaterror(c, "Interfaces must have java.lang.Object as superclass");
1532                         return false;
1533                 }
1534         }
1535
1536         /* Parse the super interfaces. */
1537
1538         if (!suck_check_classbuffer_size(cb, 2))
1539                 return false;
1540
1541         c->interfacescount = suck_u2(cb);
1542
1543         if (!suck_check_classbuffer_size(cb, 2 * c->interfacescount))
1544                 return false;
1545
1546         c->interfaces = MNEW(classinfo*, c->interfacescount);
1547
1548         /* Get the names of the super interfaces. */
1549
1550         interfacesnames = DMNEW(utf*, c->interfacescount);
1551
1552         for (i = 0; i < c->interfacescount; i++) {
1553                 index = suck_u2(cb);
1554
1555                 u = (utf *) class_getconstant(c, index, CONSTANT_Class);
1556
1557                 if (u == NULL)
1558                         return false;
1559
1560                 interfacesnames[i] = u;
1561         }
1562
1563         RT_TIMING_GET_TIME(time_setup);
1564
1565         /* Parse fields. */
1566
1567         if (!suck_check_classbuffer_size(cb, 2))
1568                 return false;
1569
1570         c->fieldscount = suck_u2(cb);
1571         c->fields      = MNEW(fieldinfo, c->fieldscount);
1572
1573         MZERO(c->fields, fieldinfo, c->fieldscount);
1574
1575         for (i = 0; i < c->fieldscount; i++) {
1576                 if (!field_load(cb, &(c->fields[i]), descpool))
1577                         return false;
1578         }
1579
1580         RT_TIMING_GET_TIME(time_fields);
1581
1582         /* Parse methods. */
1583
1584         if (!suck_check_classbuffer_size(cb, 2))
1585                 return false;
1586
1587         c->methodscount = suck_u2(cb);
1588         c->methods      = MNEW(methodinfo, c->methodscount);
1589
1590         MZERO(c->methods, methodinfo, c->methodscount);
1591         
1592         for (i = 0; i < c->methodscount; i++) {
1593                 if (!method_load(cb, &(c->methods[i]), descpool))
1594                         return false;
1595         }
1596
1597         RT_TIMING_GET_TIME(time_methods);
1598
1599         /* create the class reference table */
1600
1601         c->classrefs =
1602                 descriptor_pool_create_classrefs(descpool, &(c->classrefcount));
1603
1604         RT_TIMING_GET_TIME(time_classrefs);
1605
1606         /* allocate space for the parsed descriptors */
1607
1608         descriptor_pool_alloc_parsed_descriptors(descpool);
1609         c->parseddescs =
1610                 descriptor_pool_get_parsed_descriptors(descpool, &(c->parseddescsize));
1611
1612 #if defined(ENABLE_STATISTICS)
1613         if (opt_stat) {
1614                 descriptor_pool_get_sizes(descpool, &classrefsize, &descsize);
1615                 count_classref_len += classrefsize;
1616                 count_parsed_desc_len += descsize;
1617         }
1618 #endif
1619
1620         RT_TIMING_GET_TIME(time_descs);
1621
1622         /* put the classrefs in the constant pool */
1623
1624         for (i = 0; i < c->cpcount; i++) {
1625                 if (c->cptags[i] == CONSTANT_Class) {
1626                         utf *name = (utf *) c->cpinfos[i];
1627                         c->cpinfos[i] = descriptor_pool_lookup_classref(descpool, name);
1628                 }
1629         }
1630
1631         /* Resolve the super class. */
1632
1633         if (supername != NULL) {
1634                 cr = descriptor_pool_lookup_classref(descpool, supername);
1635
1636                 if (cr == NULL)
1637                         return false;
1638
1639                 /* XXX This should be done better. */
1640                 tc = resolve_classref_or_classinfo_eager(CLASSREF_OR_CLASSINFO(cr), false);
1641
1642                 if (tc == NULL)
1643                         return false;
1644
1645                 /* Interfaces are not allowed as super classes. */
1646
1647                 if (tc->flags & ACC_INTERFACE) {
1648                         exceptions_throw_incompatibleclasschangeerror(c, "class %s has interface %s as super class");
1649                         return false;
1650                 }
1651
1652                 /* Don't allow extending final classes */
1653
1654                 if (tc->flags & ACC_FINAL) {
1655                         exceptions_throw_verifyerror(NULL,
1656                                                                                  "Cannot inherit from final class");
1657                         return false;
1658                 }
1659
1660                 /* Store the super class. */
1661
1662                 c->super = tc;
1663         }
1664
1665         /* Resolve the super interfaces. */
1666
1667         for (i = 0; i < c->interfacescount; i++) {
1668                 u  = interfacesnames[i];
1669                 cr = descriptor_pool_lookup_classref(descpool, u);
1670
1671                 if (cr == NULL)
1672                         return false;
1673
1674                 /* XXX This should be done better. */
1675                 tc = resolve_classref_or_classinfo_eager(CLASSREF_OR_CLASSINFO(cr), false);
1676
1677                 if (tc == NULL)
1678                         return false;
1679
1680                 /* Detect circularity. */
1681
1682                 if (tc == c) {
1683                         exceptions_throw_classcircularityerror(c);
1684                         return false;
1685                 }
1686
1687                 if (!(tc->flags & ACC_INTERFACE)) {
1688                         exceptions_throw_incompatibleclasschangeerror(tc,
1689                                                                                                                   "Implementing class");
1690                         return false;
1691                 }
1692
1693                 /* Store the super interface. */
1694
1695                 c->interfaces[i] = tc;
1696         }
1697
1698         RT_TIMING_GET_TIME(time_setrefs);
1699
1700         /* Parse the field descriptors. */
1701
1702         for (i = 0; i < c->fieldscount; i++) {
1703                 c->fields[i].parseddesc =
1704                         descriptor_pool_parse_field_descriptor(descpool,
1705                                                                                                    c->fields[i].descriptor);
1706                 if (!c->fields[i].parseddesc)
1707                         return false;
1708         }
1709
1710         RT_TIMING_GET_TIME(time_parsefds);
1711
1712         /* parse method descriptors */
1713
1714         for (i = 0; i < c->methodscount; i++) {
1715                 methodinfo *m = &c->methods[i];
1716                 m->parseddesc =
1717                         descriptor_pool_parse_method_descriptor(descpool, m->descriptor,
1718                                                                                                         m->flags, class_get_self_classref(m->class));
1719                 if (!m->parseddesc)
1720                         return false;
1721
1722                 for (j = 0; j < m->rawexceptiontablelength; j++) {
1723                         if (!m->rawexceptiontable[j].catchtype.any)
1724                                 continue;
1725
1726                         if ((m->rawexceptiontable[j].catchtype.ref =
1727                                  descriptor_pool_lookup_classref(descpool,
1728                                                 (utf *) m->rawexceptiontable[j].catchtype.any)) == NULL)
1729                                 return false;
1730                 }
1731
1732                 for (j = 0; j < m->thrownexceptionscount; j++) {
1733                         if (!m->thrownexceptions[j].any)
1734                                 continue;
1735
1736                         if ((m->thrownexceptions[j].ref = descriptor_pool_lookup_classref(descpool,
1737                                                 (utf *) m->thrownexceptions[j].any)) == NULL)
1738                                 return false;
1739                 }
1740         }
1741
1742         RT_TIMING_GET_TIME(time_parsemds);
1743
1744         /* parse the loaded descriptors */
1745
1746         for (i = 0; i < c->cpcount; i++) {
1747                 constant_FMIref *fmi;
1748                 s4               index;
1749
1750                 switch (c->cptags[i]) {
1751                 case CONSTANT_Fieldref:
1752                         fmi = (constant_FMIref *) c->cpinfos[i];
1753                         fmi->parseddesc.fd =
1754                                 descriptor_pool_parse_field_descriptor(descpool,
1755                                                                                                            fmi->descriptor);
1756                         if (!fmi->parseddesc.fd)
1757                                 return false;
1758
1759                         index = fmi->p.index;
1760                         fmi->p.classref =
1761                                 (constant_classref *) class_getconstant(c, index,
1762                                                                                                                 CONSTANT_Class);
1763                         if (!fmi->p.classref)
1764                                 return false;
1765                         break;
1766                 case CONSTANT_Methodref:
1767                 case CONSTANT_InterfaceMethodref:
1768                         fmi = (constant_FMIref *) c->cpinfos[i];
1769                         index = fmi->p.index;
1770                         fmi->p.classref =
1771                                 (constant_classref *) class_getconstant(c, index,
1772                                                                                                                 CONSTANT_Class);
1773                         if (!fmi->p.classref)
1774                                 return false;
1775                         fmi->parseddesc.md =
1776                                 descriptor_pool_parse_method_descriptor(descpool,
1777                                                                                                                 fmi->descriptor,
1778                                                                                                                 ACC_UNDEF,
1779                                                                                                                 fmi->p.classref);
1780                         if (!fmi->parseddesc.md)
1781                                 return false;
1782                         break;
1783                 }
1784         }
1785
1786         RT_TIMING_GET_TIME(time_parsecpool);
1787
1788 #ifdef ENABLE_VERIFIER
1789         /* Check if all fields and methods can be uniquely
1790          * identified by (name,descriptor). */
1791
1792         if (opt_verify) {
1793                 /* We use a hash table here to avoid making the
1794                  * average case quadratic in # of methods, fields.
1795                  */
1796                 static int shift = 0;
1797                 u2 *hashtab;
1798                 u2 *next; /* for chaining colliding hash entries */
1799                 size_t len;
1800                 size_t hashlen;
1801                 u2 index;
1802                 u2 old;
1803
1804                 /* Allocate hashtable */
1805                 len = c->methodscount;
1806                 if (len < c->fieldscount) len = c->fieldscount;
1807                 hashlen = 5 * len;
1808                 hashtab = MNEW(u2,(hashlen + len));
1809                 next = hashtab + hashlen;
1810
1811                 /* Determine bitshift (to get good hash values) */
1812                 if (!shift) {
1813                         len = sizeof(utf);
1814                         while (len) {
1815                                 len >>= 1;
1816                                 shift++;
1817                         }
1818                 }
1819
1820                 /* Check fields */
1821                 memset(hashtab, 0, sizeof(u2) * (hashlen + len));
1822
1823                 for (i = 0; i < c->fieldscount; ++i) {
1824                         fieldinfo *fi = c->fields + i;
1825
1826                         /* It's ok if we lose bits here */
1827                         index = ((((size_t) fi->name) +
1828                                           ((size_t) fi->descriptor)) >> shift) % hashlen;
1829
1830                         if ((old = hashtab[index])) {
1831                                 old--;
1832                                 next[i] = old;
1833                                 do {
1834                                         if (c->fields[old].name == fi->name &&
1835                                                 c->fields[old].descriptor == fi->descriptor) {
1836                                                 exceptions_throw_classformaterror(c, "Repetitive field name/signature");
1837                                                 return false;
1838                                         }
1839                                 } while ((old = next[old]));
1840                         }
1841                         hashtab[index] = i + 1;
1842                 }
1843
1844                 /* Check methods */
1845                 memset(hashtab, 0, sizeof(u2) * (hashlen + hashlen/5));
1846
1847                 for (i = 0; i < c->methodscount; ++i) {
1848                         methodinfo *mi = c->methods + i;
1849
1850                         /* It's ok if we lose bits here */
1851                         index = ((((size_t) mi->name) +
1852                                           ((size_t) mi->descriptor)) >> shift) % hashlen;
1853
1854                         if ((old = hashtab[index])) {
1855                                 old--;
1856                                 next[i] = old;
1857                                 do {
1858                                         if (c->methods[old].name == mi->name &&
1859                                                 c->methods[old].descriptor == mi->descriptor) {
1860                                                 exceptions_throw_classformaterror(c, "Repetitive method name/signature");
1861                                                 return false;
1862                                         }
1863                                 } while ((old = next[old]));
1864                         }
1865                         hashtab[index] = i + 1;
1866                 }
1867
1868                 MFREE(hashtab, u2, (hashlen + len));
1869         }
1870 #endif /* ENABLE_VERIFIER */
1871
1872         RT_TIMING_GET_TIME(time_verify);
1873
1874 #if defined(ENABLE_STATISTICS)
1875         if (opt_stat) {
1876                 size_classinfo  += sizeof(classinfo*) * c->interfacescount;
1877                 size_fieldinfo  += sizeof(fieldinfo)  * c->fieldscount;
1878                 size_methodinfo += sizeof(methodinfo) * c->methodscount;
1879         }
1880 #endif
1881
1882         /* load attribute structures */
1883
1884         if (!class_load_attributes(cb))
1885                 return false;
1886
1887         /* Pre Java 1.5 version don't check this. This implementation is
1888            like Java 1.5 do it: for class file version 45.3 we don't check
1889            it, older versions are checked. */
1890
1891         if (((ma == 45) && (mi > 3)) || (ma > 45)) {
1892                 /* check if all data has been read */
1893                 s4 classdata_left = ((cb->data + cb->size) - cb->pos);
1894
1895                 if (classdata_left > 0) {
1896                         exceptions_throw_classformaterror(c, "Extra bytes at the end of class file");
1897                         return false;
1898                 }
1899         }
1900
1901         RT_TIMING_GET_TIME(time_attrs);
1902
1903         RT_TIMING_TIME_DIFF(time_start     , time_checks    , RT_TIMING_LOAD_CHECKS);
1904         RT_TIMING_TIME_DIFF(time_checks    , time_ndpool    , RT_TIMING_LOAD_NDPOOL);
1905         RT_TIMING_TIME_DIFF(time_ndpool    , time_cpool     , RT_TIMING_LOAD_CPOOL);
1906         RT_TIMING_TIME_DIFF(time_cpool     , time_setup     , RT_TIMING_LOAD_SETUP);
1907         RT_TIMING_TIME_DIFF(time_setup     , time_fields    , RT_TIMING_LOAD_FIELDS);
1908         RT_TIMING_TIME_DIFF(time_fields    , time_methods   , RT_TIMING_LOAD_METHODS);
1909         RT_TIMING_TIME_DIFF(time_methods   , time_classrefs , RT_TIMING_LOAD_CLASSREFS);
1910         RT_TIMING_TIME_DIFF(time_classrefs , time_descs     , RT_TIMING_LOAD_DESCS);
1911         RT_TIMING_TIME_DIFF(time_descs     , time_setrefs   , RT_TIMING_LOAD_SETREFS);
1912         RT_TIMING_TIME_DIFF(time_setrefs   , time_parsefds  , RT_TIMING_LOAD_PARSEFDS);
1913         RT_TIMING_TIME_DIFF(time_parsefds  , time_parsemds  , RT_TIMING_LOAD_PARSEMDS);
1914         RT_TIMING_TIME_DIFF(time_parsemds  , time_parsecpool, RT_TIMING_LOAD_PARSECP);
1915         RT_TIMING_TIME_DIFF(time_parsecpool, time_verify    , RT_TIMING_LOAD_VERIFY);
1916         RT_TIMING_TIME_DIFF(time_verify    , time_attrs     , RT_TIMING_LOAD_ATTRS);
1917         RT_TIMING_TIME_DIFF(time_start     , time_attrs     , RT_TIMING_LOAD_TOTAL);
1918
1919         return true;
1920 }
1921
1922
1923 /* load_class_from_classbuffer *************************************************
1924
1925    Convenience wrapper for load_class_from_classbuffer.
1926
1927    SYNCHRONIZATION:
1928        This function is NOT synchronized!
1929    
1930 *******************************************************************************/
1931
1932 classinfo *load_class_from_classbuffer(classbuffer *cb)
1933 {
1934         classinfo *c;
1935         int32_t    dumpsize;
1936         bool       result;
1937
1938         /* Get the classbuffer's class. */
1939
1940         c = cb->class;
1941
1942         /* Check if the class is already loaded. */
1943
1944         if (c->state & CLASS_LOADED)
1945                 return c;
1946
1947 #if defined(ENABLE_STATISTICS)
1948         if (opt_stat)
1949                 count_class_loads++;
1950 #endif
1951
1952 #if !defined(NDEBUG)
1953         if (loadverbose)
1954                 log_message_class("Loading class: ", c);
1955 #endif
1956
1957         /* Mark start of dump memory area. */
1958
1959         dumpsize = dump_size();
1960
1961         /* Class is currently loading. */
1962
1963         c->state |= CLASS_LOADING;
1964
1965         /* Parse the classbuffer. */
1966
1967         result = load_class_from_classbuffer_intern(cb);
1968
1969         /* Release dump area. */
1970
1971         dump_release(dumpsize);
1972
1973         /* An error occurred. */
1974
1975         if (result == false) {
1976                 /* Revert loading state. */
1977
1978                 c->state = (c->state & ~CLASS_LOADING);
1979
1980                 return NULL;
1981         }
1982
1983         /* Revert loading state and set loaded. */
1984
1985         c->state = (c->state & ~CLASS_LOADING) | CLASS_LOADED;
1986
1987 #if defined(ENABLE_JVMTI)
1988         /* fire Class Prepare JVMTI event */
1989
1990         if (jvmti)
1991                 jvmti_ClassLoadPrepare(true, c);
1992 #endif
1993
1994 #if !defined(NDEBUG)
1995         if (loadverbose)
1996                 log_message_class("Loading done class: ", c);
1997 #endif
1998
1999         return c;
2000 }
2001
2002
2003 /* load_newly_created_array ****************************************************
2004
2005    Load a newly created array class.
2006
2007         RETURN VALUE:
2008             c....................the array class C has been loaded
2009                 other classinfo......the array class was found in the class cache, 
2010                                      C has been freed
2011             NULL.................an exception has been thrown
2012
2013         Note:
2014                 This is an internal function. Do not use it unless you know exactly
2015                 what you are doing!
2016
2017                 Use one of the load_class_... functions for general array class loading.
2018
2019 *******************************************************************************/
2020
2021 classinfo *load_newly_created_array(classinfo *c, classloader *loader)
2022 {
2023         classinfo         *comp = NULL;
2024         methodinfo        *clone;
2025         methoddesc        *clonedesc;
2026         constant_classref *classrefs;
2027         char              *text;
2028         s4                 namelen;
2029         utf               *u;
2030
2031         text    = c->name->text;
2032         namelen = c->name->blength;
2033
2034         /* Check array class name */
2035
2036         if ((namelen < 2) || (text[0] != '[')) {
2037                 exceptions_throw_classnotfoundexception(c->name);
2038                 return NULL;
2039         }
2040
2041         /* Check the element type */
2042
2043         switch (text[1]) {
2044         case '[':
2045                 /* c is an array of arrays. We have to create the component class. */
2046
2047                 u = utf_new(text + 1, namelen - 1);
2048
2049                 comp = load_class_from_classloader(u, loader);
2050
2051                 if (comp == NULL)
2052                         return NULL;
2053
2054                 assert(comp->state & CLASS_LOADED);
2055
2056                 /* the array's flags are that of the component class */
2057                 c->flags = (comp->flags & ~ACC_INTERFACE) | ACC_FINAL | ACC_ABSTRACT;
2058                 c->classloader = comp->classloader;
2059                 break;
2060
2061         case 'L':
2062                 /* c is an array of objects. */
2063
2064                 /* check for cases like `[L;' or `[L[I;' or `[Ljava.lang.Object' */
2065                 if ((namelen < 4) || (text[2] == '[') || (text[namelen - 1] != ';')) {
2066                         exceptions_throw_classnotfoundexception(c->name);
2067                         return NULL;
2068                 }
2069
2070                 u = utf_new(text + 2, namelen - 3);
2071
2072                 if (!(comp = load_class_from_classloader(u, loader)))
2073                         return NULL;
2074
2075                 assert(comp->state & CLASS_LOADED);
2076
2077                 /* the array's flags are that of the component class */
2078                 c->flags = (comp->flags & ~ACC_INTERFACE) | ACC_FINAL | ACC_ABSTRACT;
2079                 c->classloader = comp->classloader;
2080                 break;
2081
2082         default:
2083                 /* c is an array of a primitive type */
2084
2085                 /* check for cases like `[II' and whether the character is a
2086                    valid primitive type */
2087
2088                 if ((namelen > 2) || (primitive_class_get_by_char(text[1]) == NULL)) {
2089                         exceptions_throw_classnotfoundexception(c->name);
2090                         return NULL;
2091                 }
2092
2093                 /* the accessibility of the array class is public (VM Spec 5.3.3) */
2094                 c->flags = ACC_PUBLIC | ACC_FINAL | ACC_ABSTRACT;
2095                 c->classloader = NULL;
2096         }
2097
2098         assert(class_java_lang_Object);
2099 #if defined(ENABLE_JAVASE)
2100         assert(class_java_lang_Cloneable);
2101         assert(class_java_io_Serializable);
2102 #endif
2103
2104         /* Setup the array class. */
2105
2106         c->super = class_java_lang_Object;
2107
2108 #if defined(ENABLE_JAVASE)
2109
2110         c->interfacescount = 2;
2111     c->interfaces      = MNEW(classinfo*, 2);
2112         c->interfaces[0]   = class_java_lang_Cloneable;
2113         c->interfaces[1]   = class_java_io_Serializable;
2114
2115 #elif defined(ENABLE_JAVAME_CLDC1_1)
2116
2117         c->interfacescount = 0;
2118         c->interfaces      = NULL;
2119
2120 #else
2121 # error unknow Java configuration
2122 #endif
2123
2124         c->methodscount = 1;
2125         c->methods      = MNEW(methodinfo, c->methodscount);
2126
2127         MZERO(c->methods, methodinfo, c->methodscount);
2128
2129         classrefs = MNEW(constant_classref, 2);
2130
2131         CLASSREF_INIT(classrefs[0], c, c->name);
2132         CLASSREF_INIT(classrefs[1], c, utf_java_lang_Object);
2133
2134         /* create descriptor for clone method */
2135         /* we need one paramslot which is reserved for the 'this' parameter */
2136         clonedesc = NEW(methoddesc);
2137         clonedesc->returntype.type = TYPE_ADR;
2138         clonedesc->returntype.classref = classrefs + 1;
2139         clonedesc->returntype.arraydim = 0;
2140         /* initialize params to "empty", add real params below in
2141            descriptor_params_from_paramtypes */
2142         clonedesc->paramcount = 0;
2143         clonedesc->paramslots = 0;
2144         clonedesc->paramtypes[0].classref = classrefs + 0;
2145         clonedesc->params = NULL;
2146
2147         /* create methodinfo */
2148
2149         clone = c->methods;
2150         MSET(clone, 0, methodinfo, 1);
2151
2152 #if defined(ENABLE_THREADS)
2153         lock_init_object_lock(&clone->header);
2154 #endif
2155
2156         /* ATTENTION: if you delete the ACC_NATIVE below, set
2157            clone->maxlocals=1 (interpreter related) */
2158
2159         clone->flags      = ACC_PUBLIC | ACC_NATIVE;
2160         clone->name       = utf_clone;
2161         clone->descriptor = utf_void__java_lang_Object;
2162         clone->parseddesc = clonedesc;
2163         clone->class      = c;
2164
2165         /* parse the descriptor to get the register allocation */
2166
2167         if (!descriptor_params_from_paramtypes(clonedesc, clone->flags))
2168                 return false;
2169
2170         clone->code = codegen_generate_stub_native(clone, BUILTIN_clone);
2171
2172         /* XXX: field: length? */
2173
2174         /* array classes are not loaded from class files */
2175
2176         c->state          |= CLASS_LOADED;
2177         c->parseddescs    = (u1 *) clonedesc;
2178         c->parseddescsize = sizeof(methodinfo);
2179         c->classrefs      = classrefs;
2180         c->classrefcount  = 1;
2181
2182         /* insert class into the loaded class cache */
2183         /* XXX free classinfo if NULL returned? */
2184
2185         return classcache_store(loader, c, true);
2186 }
2187
2188
2189 /* loader_close ****************************************************************
2190
2191    Frees all resources.
2192         
2193 *******************************************************************************/
2194
2195 void loader_close(void)
2196 {
2197         /* empty */
2198 }
2199
2200
2201 /*
2202  * These are local overrides for various environment variables in Emacs.
2203  * Please do not remove this and leave it at the end of the file, where
2204  * Emacs will automagically detect them.
2205  * ---------------------------------------------------------------------
2206  * Local variables:
2207  * mode: c
2208  * indent-tabs-mode: t
2209  * c-basic-offset: 4
2210  * tab-width: 4
2211  * End:
2212  * vim:noexpandtab:sw=4:ts=4:
2213  */