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