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