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