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