PR149: Used wrong class loader.
[cacao.git] / src / vm / linker.cpp
1 /* src/vm/linker.cpp - class linker functions
2
3    Copyright (C) 1996, 2011
4    CACAOVM - Verein zur Foerderung der freien virtuellen Maschine CACAO
5
6    This file is part of CACAO.
7
8    This program is free software; you can redistribute it and/or
9    modify it under the terms of the GNU General Public License as
10    published by the Free Software Foundation; either version 2, or (at
11    your option) any later version.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23 */
24
25
26 #include "config.h"
27
28 #include <assert.h>
29 #include <stdint.h>
30
31 #include "vm/types.h"
32
33 #include "mm/memory.hpp"
34
35 #include "native/native.hpp"
36
37 #include "threads/lock.hpp"
38 #include "threads/mutex.hpp"
39
40 #include "toolbox/logging.hpp"
41
42 #include "vm/access.hpp"
43 #include "vm/array.hpp"
44 #include "vm/class.hpp"
45 #include "vm/classcache.hpp"
46 #include "vm/exceptions.hpp"
47 #include "vm/globals.hpp"
48 #include "vm/hook.hpp"
49 #include "vm/loader.hpp"
50 #include "vm/options.h"
51 #include "vm/primitive.hpp"
52 #include "vm/rt-timing.h"
53 #include "vm/string.hpp"
54 #include "vm/vm.hpp"
55
56 #include "vm/jit/asmpart.h"
57 #include "vm/jit/stubs.hpp"
58
59 #include <vector>
60 #include <utility>
61
62
63 /* debugging macros ***********************************************************/
64
65 #if !defined(NDEBUG)
66 # define TRACELINKCLASS(c) \
67     do { \
68         if (opt_TraceLinkClass) { \
69             log_start(); \
70             log_print("[Linking "); \
71             class_print((c)); \
72             log_print("]"); \
73             log_finish(); \
74         } \
75     } while (0)
76 #else
77 # define TRACELINKCLASS(c)
78 #endif
79
80
81 /* #include "vm/resolve.hpp" */
82 /* copied prototype to avoid bootstrapping problem: */
83 classinfo *resolve_classref_or_classinfo_eager(classref_or_classinfo cls, bool checkaccess);
84
85 #if defined(ENABLE_STATISTICS)
86 # include "vm/statistics.h"
87 #endif
88
89 #if !defined(NDEBUG) && defined(ENABLE_INLINING)
90 #define INLINELOG(code)  do { if (opt_TraceInlining) { code } } while (0)
91 #else
92 #define INLINELOG(code)
93 #endif
94
95
96 /* global variables ***********************************************************/
97
98 static s4 interfaceindex;       /* sequential numbering of interfaces         */
99 static s4 classvalue;
100
101 #if !USES_NEW_SUBTYPE
102 Mutex *linker_classrenumber_lock;
103 #endif
104
105 #if defined(__cplusplus)
106 extern "C" {
107 #endif
108
109 /* private functions **********************************************************/
110
111 static classinfo *link_class_intern(classinfo *c);
112 static arraydescriptor *link_array(classinfo *c);
113 static void linker_compute_class_values(classinfo *c);
114 static void linker_compute_subclasses(classinfo *c);
115 static bool linker_addinterface(classinfo *c, classinfo *ic);
116 static s4 class_highestinterface(classinfo *c);
117
118
119 typedef std::vector<std::pair<java_object_t**, utf*> > deferred_strings_vec_t;
120 static deferred_strings_vec_t deferred_strings;
121
122 /* linker_init *****************************************************************
123
124    Initializes the linker subsystem and links classes required for the
125    primitive table.
126
127 *******************************************************************************/
128
129 void linker_preinit(void)
130 {
131         TRACESUBSYSTEMINITIALIZATION("linker_preinit");
132
133         /* Reset interface index. */
134
135         interfaceindex = 0;
136
137 #if defined(ENABLE_THREADS) && !USES_NEW_SUBTYPE
138         /* create the global mutex */
139
140         linker_classrenumber_lock = new Mutex();
141 #endif
142
143         /* Link the most basic classes. */
144
145         if (!link_class(class_java_lang_Object))
146                 vm_abort("linker_preinit: linking java/lang/Object failed");
147
148 #if defined(ENABLE_JAVASE)
149         if (!link_class(class_java_lang_Cloneable))
150                 vm_abort("linker_preinit: linking java/lang/Cloneable failed");
151
152         if (!link_class(class_java_io_Serializable))
153                 vm_abort("linker_preinit: linking java/io/Serializable failed");
154 #endif
155 }
156
157
158 /* linker_init *****************************************************************
159
160    Links all classes required in the VM.
161
162 *******************************************************************************/
163
164 void linker_init(void)
165 {
166         TRACESUBSYSTEMINITIALIZATION("linker_init");
167
168         /* Link java.lang.Class as first class of the system, because we
169        need it's vftbl for all other classes so we can use a class as
170        object. */
171
172         if (!link_class(class_java_lang_Class))
173                 vm_abort("linker_init: linking java/lang/Class failed");
174
175         /* Now set the header.vftbl of all classes which were created
176        before java.lang.Class was linked. */
177
178         class_postset_header_vftbl();
179
180         /* Link primitive-type wrapping classes. */
181
182 #if defined(ENABLE_JAVASE)
183         if (!link_class(class_java_lang_Void))
184                 vm_abort("linker_init: linking failed");
185 #endif
186
187         if (!link_class(class_java_lang_Boolean))
188                 vm_abort("linker_init: linking failed");
189
190         if (!link_class(class_java_lang_Byte))
191                 vm_abort("linker_init: linking failed");
192
193         if (!link_class(class_java_lang_Character))
194                 vm_abort("linker_init: linking failed");
195
196         if (!link_class(class_java_lang_Short))
197                 vm_abort("linker_init: linking failed");
198
199         if (!link_class(class_java_lang_Integer))
200                 vm_abort("linker_init: linking failed");
201
202         if (!link_class(class_java_lang_Long))
203                 vm_abort("linker_init: linking failed");
204
205         if (!link_class(class_java_lang_Float))
206                 vm_abort("linker_init: linking failed");
207
208         if (!link_class(class_java_lang_Double))
209                 vm_abort("linker_init: linking failed");
210
211         /* Link important system classes. */
212
213         if (!link_class(class_java_lang_String))
214                 vm_abort("linker_init: linking java/lang/String failed");
215
216 #if defined(ENABLE_JAVASE)
217         if (!link_class(class_java_lang_ClassLoader))
218                 vm_abort("linker_init: linking failed");
219
220         if (!link_class(class_java_lang_SecurityManager))
221                 vm_abort("linker_init: linking failed");
222 #endif
223
224         if (!link_class(class_java_lang_System))
225                 vm_abort("linker_init: linking failed");
226
227         if (!link_class(class_java_lang_Thread))
228                 vm_abort("linker_init: linking failed");
229
230 #if defined(ENABLE_JAVASE)
231         if (!link_class(class_java_lang_ThreadGroup))
232                 vm_abort("linker_init: linking failed");
233 #endif
234
235         if (!link_class(class_java_lang_Throwable))
236                 vm_abort("linker_init: linking failed");
237
238 #if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
239         if (!link_class(class_java_lang_VMSystem))
240                 vm_abort("linker_init: linking failed");
241
242         if (!link_class(class_java_lang_VMThread))
243                 vm_abort("linker_init: linking failed");
244
245         if (!link_class(class_java_lang_VMThrowable))
246                 vm_abort("linker_init: linking failed");
247 #endif
248
249         /* Important system exceptions. */
250
251         if (!link_class(class_java_lang_Exception))
252                 vm_abort("linker_init: linking failed");
253
254         if (!link_class(class_java_lang_ClassNotFoundException))
255                 vm_abort("linker_init: linking failed");
256
257         if (!link_class(class_java_lang_RuntimeException))
258                 vm_abort("linker_init: linking failed");
259
260         /* some classes which may be used more often */
261
262 #if defined(ENABLE_JAVASE)
263         if (!link_class(class_java_lang_StackTraceElement))
264                 vm_abort("linker_init: linking failed");
265
266         if (!link_class(class_java_lang_reflect_Constructor))
267                 vm_abort("linker_init: linking failed");
268
269         if (!link_class(class_java_lang_reflect_Field))
270                 vm_abort("linker_init: linking failed");
271
272         if (!link_class(class_java_lang_reflect_Method))
273                 vm_abort("linker_init: linking failed");
274
275 # if defined(WITH_JAVA_RUNTIME_LIBRARY_GNU_CLASSPATH)
276         if (!link_class(class_java_lang_reflect_VMConstructor))
277                 vm_abort("linker_init: linking failed");
278
279         if (!link_class(class_java_lang_reflect_VMField))
280                 vm_abort("linker_init: linking failed");
281
282         if (!link_class(class_java_lang_reflect_VMMethod))
283                 vm_abort("linker_init: linking failed");
284 # endif
285
286         if (!link_class(class_java_security_PrivilegedAction))
287                 vm_abort("linker_init: linking failed");
288
289         if (!link_class(class_java_util_Vector))
290                 vm_abort("linker_init: linking failed");
291
292         if (!link_class(class_java_util_HashMap))
293                 vm_abort("linker_init: linking failed");
294
295 # if defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
296         if (!link_class(class_sun_misc_Signal))
297                 vm_abort("linker_init: linking failed");
298
299         if (!link_class(class_sun_reflect_MagicAccessorImpl))
300                 vm_abort("linker_init: linking failed");
301
302         if (!link_class(class_sun_reflect_MethodAccessorImpl))
303                 vm_abort("linker_init: linking failed");
304
305         if (!link_class(class_sun_reflect_ConstructorAccessorImpl))
306                 vm_abort("linker_init: linking failed");
307 # endif
308
309         if (!link_class(arrayclass_java_lang_Object))
310                 vm_abort("linker_init: linking failed");
311 #endif
312
313
314         /* create pseudo classes used by the typechecker */
315
316     /* pseudo class for Arraystubs (extends java.lang.Object) */
317
318         pseudo_class_Arraystub                   =
319                 class_create_classinfo(utf_new_char("$ARRAYSTUB$"));
320         pseudo_class_Arraystub->state           |= CLASS_LOADED;
321         pseudo_class_Arraystub->super            = class_java_lang_Object;
322
323 #if defined(ENABLE_JAVASE)
324
325         pseudo_class_Arraystub->interfacescount  = 2;
326         pseudo_class_Arraystub->interfaces       = MNEW(classinfo*, 2);
327         pseudo_class_Arraystub->interfaces[0]    = class_java_lang_Cloneable;
328         pseudo_class_Arraystub->interfaces[1]    = class_java_io_Serializable;
329
330 #elif defined(ENABLE_JAVAME_CLDC1_1)
331
332         pseudo_class_Arraystub->interfacescount    = 0;
333         pseudo_class_Arraystub->interfaces         = NULL;
334
335 #else
336 # error unknown Java configuration
337 #endif
338
339         if (!classcache_store_unique(pseudo_class_Arraystub))
340                 vm_abort("linker_init: could not cache pseudo_class_Arraystub");
341
342         if (!link_class(pseudo_class_Arraystub))
343                 vm_abort("linker_init: linking pseudo_class_Arraystub failed");
344
345         /* pseudo class representing the null type */
346
347         pseudo_class_Null         = class_create_classinfo(utf_new_char("$NULL$"));
348         pseudo_class_Null->state |= CLASS_LOADED;
349         pseudo_class_Null->super  = class_java_lang_Object;
350
351         if (!classcache_store_unique(pseudo_class_Null))
352                 vm_abort("linker_init: could not cache pseudo_class_Null");
353
354         if (!link_class(pseudo_class_Null))
355                 vm_abort("linker_init: linking failed");
356
357         /* pseudo class representing new uninitialized objects */
358     
359         pseudo_class_New         = class_create_classinfo(utf_new_char("$NEW$"));
360         pseudo_class_New->state |= CLASS_LOADED;
361         pseudo_class_New->state |= CLASS_LINKED; /* XXX is this allright? */
362         pseudo_class_New->super  = class_java_lang_Object;
363
364         if (!classcache_store_unique(pseudo_class_New))
365                 vm_abort("linker_init: could not cache pseudo_class_New");
366
367         /* Correct vftbl-entries (retarded loading and linking of class
368            java/lang/String). */
369
370         stringtable_update();
371 }
372
373
374 /* link_class ******************************************************************
375
376    Wrapper function for link_class_intern to ease monitor enter/exit
377    and exception handling.
378
379 *******************************************************************************/
380
381 classinfo *link_class(classinfo *c)
382 {
383         classinfo *r;
384 #if defined(ENABLE_RT_TIMING)
385         struct timespec time_start, time_end;
386 #endif
387
388         RT_TIMING_GET_TIME(time_start);
389
390         if (c == NULL) {
391                 exceptions_throw_nullpointerexception();
392                 return 0;
393         }
394
395         LOCK_MONITOR_ENTER(c);
396
397         /* Maybe the class is currently linking or is already linked.*/
398
399         if ((c->state & CLASS_LINKING) || (c->state & CLASS_LINKED)) {
400                 LOCK_MONITOR_EXIT(c);
401
402                 return c;
403         }
404
405 #if defined(ENABLE_STATISTICS)
406         /* measure time */
407
408         if (opt_getcompilingtime)
409                 compilingtime_stop();
410
411         if (opt_getloadingtime)
412                 loadingtime_start();
413 #endif
414
415         /* call the internal function */
416
417         r = link_class_intern(c);
418
419         /* If return value is NULL, we had a problem and the class is not
420            linked. */
421
422         if (r == NULL)
423                 c->state &= ~CLASS_LINKING;
424
425 #if defined(ENABLE_STATISTICS)
426         /* measure time */
427
428         if (opt_getloadingtime)
429                 loadingtime_stop();
430
431         if (opt_getcompilingtime)
432                 compilingtime_start();
433 #endif
434
435         LOCK_MONITOR_EXIT(c);
436
437         RT_TIMING_GET_TIME(time_end);
438
439         RT_TIMING_TIME_DIFF(time_start,time_end,RT_TIMING_LINK_TOTAL);
440
441         // Hook point just after a class was linked.
442         if (!Hook::class_linked(r))
443                 return 0;
444
445         return r;
446 }
447
448
449 /* linker_overwrite_method *****************************************************
450
451    Overwrite a method with another one, update method flags and check
452    assumptions.
453
454    IN:
455       mg................the general method being overwritten
456           ms................the overwriting (more specialized) method
457           wl................worklist where to add invalidated methods
458
459    RETURN VALUE:
460       true..............everything ok
461           false.............an exception has been thrown
462
463 *******************************************************************************/
464
465 static bool linker_overwrite_method(methodinfo *mg,
466                                                                         methodinfo *ms,
467                                                                         method_worklist **wl)
468 {
469         classinfo *cg;
470         classinfo *cs;
471
472         cg = mg->clazz;
473         cs = ms->clazz;
474
475         /* overriding a final method is illegal */
476
477         if (mg->flags & ACC_FINAL) {
478                 exceptions_throw_verifyerror(mg, "Overriding final method");
479                 return false;
480         }
481
482         /* method ms overwrites method mg */
483
484 #if defined(ENABLE_VERIFIER)
485         /* Add loading constraints (for the more general types of method mg). */
486         /* Not for <init>, as it is not invoked virtually.                    */
487
488         if ((ms->name != utf_init)
489                         && !classcache_add_constraints_for_params(
490                                 cs->classloader, cg->classloader, mg))
491         {
492                 return false;
493         }
494 #endif
495
496         /* inherit the vftbl index, and record the overwriting */
497
498         ms->vftblindex = mg->vftblindex;
499         ms->overwrites = mg;
500
501         /* update flags and check assumptions */
502         /* <init> methods are a special case, as they are never dispatched dynamically */
503
504         if ((ms->flags & ACC_METHOD_IMPLEMENTED) && ms->name != utf_init) {
505                 do {
506
507 #if defined(ENABLE_TLH)
508                         if (mg->flags & ACC_METHOD_MONOMORPHY_USED) {
509                                 printf("%s/%s is evil! the siner is %s/%s\n", mg->clazz->name->text, mg->name->text,
510                                         ms->clazz->name->text, ms->name->text);
511                                 ms->flags |= ACC_METHOD_PARENT_MONOMORPHY_USED;                                 
512                         }
513 #endif
514
515                         if (mg->flags & ACC_METHOD_IMPLEMENTED) {
516                                 /* this adds another implementation */
517
518                                 mg->flags &= ~ACC_METHOD_MONOMORPHIC;
519
520                                 INLINELOG( printf("becomes polymorphic: "); method_println(mg); );
521
522                                 method_break_assumption_monomorphic(mg, wl);
523                         }
524                         else {
525                                 /* this is the first implementation */
526
527                                 mg->flags |= ACC_METHOD_IMPLEMENTED;
528
529                                 INLINELOG( printf("becomes implemented: "); method_println(mg); );
530                         }
531
532                         ms = mg;
533                         mg = mg->overwrites;
534                 } while (mg != NULL);
535         }
536
537         return true;
538 }
539
540
541 #if USES_NEW_SUBTYPE
542 /* build_display ***************************************************************
543
544    Builds the entire display for a class. This entails filling the fixed part
545    as well as allocating and initializing the overflow part.
546
547    See Cliff Click and John Rose: Fast subtype checking in the Hotspot JVM.
548
549 *******************************************************************************/
550
551 static classinfo *build_display(classinfo *c)
552 {
553         int depth, i;
554         int depth_fixed;
555         classinfo *super;
556
557         do {
558                 /* Handle arrays. */
559                 if (c->vftbl->arraydesc) {
560                         arraydescriptor *a = c->vftbl->arraydesc;
561                         if (a->elementvftbl && a->elementvftbl->clazz->super) {
562                                 classinfo *cls = a->elementvftbl->clazz->super;
563                                 int n;
564                                 for (n=0; n<a->dimension; n++)
565                                         cls = class_array_of(cls, true);
566                                 super = cls;
567                                 break;
568                         }
569                         if (a->componentvftbl && a->elementvftbl) {
570                                 super = a->componentvftbl->clazz;
571                                 break;
572                         }
573                 }
574                 /* Normal classes. */
575                 super = c->super;
576         } while (false);
577         if (super) {
578                 if (!link_class(super))
579                         return NULL;
580                 depth = super->vftbl->subtype_depth + 1;
581         } else
582                 /* java.lang.Object doesn't have a super class. */
583                 depth = 0;
584
585         /* Now copy super's display, append c->vftbl and initialize the remaining fields. */
586         if (depth >= DISPLAY_SIZE) {
587                 c->vftbl->subtype_overflow = MNEW(vftbl_t *, depth - DISPLAY_SIZE + 1);
588 #if defined(ENABLE_STATISTICS)
589                 if (opt_stat)
590                         count_vftbl_len += sizeof(vftbl_t*) * (depth - DISPLAY_SIZE + 1);
591 #endif
592                 memcpy(c->vftbl->subtype_overflow, super->vftbl->subtype_overflow, sizeof(vftbl_t*) * (depth - DISPLAY_SIZE));
593                 c->vftbl->subtype_overflow[depth - DISPLAY_SIZE] = c->vftbl;
594                 depth_fixed = DISPLAY_SIZE;
595         }
596         else {
597                 depth_fixed = depth;
598                 c->vftbl->subtype_display[depth] = c->vftbl;
599         }
600
601         if (super)
602                 memcpy(c->vftbl->subtype_display, super->vftbl->subtype_display, sizeof(vftbl_t*) * depth_fixed);
603         for (i=depth_fixed+1; i<=DISPLAY_SIZE; i++)
604                 c->vftbl->subtype_display[i] = NULL;
605         c->vftbl->subtype_offset = OFFSET(vftbl_t, subtype_display[0]) + sizeof(vftbl_t*) * depth_fixed;
606         c->vftbl->subtype_depth = depth;
607
608         return c;
609 }
610 #endif
611
612 /* link_class_intern ***********************************************************
613
614    Tries to link a class. The function calculates the length in bytes
615    that an instance of this class requires as well as the VTBL for
616    methods and interface methods.
617         
618 *******************************************************************************/
619
620 static classinfo *link_class_intern(classinfo *c)
621 {
622         classinfo *super;             /* super class                              */
623         classinfo *tc;                /* temporary class variable                 */
624         s4 supervftbllength;          /* vftbllegnth of super class               */
625         s4 vftbllength;               /* vftbllength of current class             */
626         s4 interfacetablelength;      /* interface table length                   */
627         vftbl_t *v;                   /* vftbl of current class                   */
628         s4 i;                         /* interface/method/field counter           */
629         arraydescriptor *arraydesc;   /* descriptor for array classes             */
630         method_worklist *worklist;    /* worklist for recompilation               */
631 #if defined(ENABLE_RT_TIMING)
632         struct timespec time_start, time_resolving, time_compute_vftbl,
633                                         time_abstract, time_compute_iftbl, time_fill_vftbl,
634                                         time_offsets, time_fill_iftbl, time_finalizer,
635                                         time_subclasses;
636 #endif
637
638         RT_TIMING_GET_TIME(time_start);
639
640         TRACELINKCLASS(c);
641
642         /* the class must be loaded */
643
644         /* XXX should this be a specific exception? */
645         assert(c->state & CLASS_LOADED);
646
647         /* This is check in link_class. */
648
649         assert(!(c->state & CLASS_LINKED));
650
651         /* cache the self-reference of this class                          */
652         /* we do this for cases where the defining loader of the class     */
653         /* has not yet been recorded as an initiating loader for the class */
654         /* this is needed so subsequent code can assume that self-refs     */
655         /* will always resolve lazily                                      */
656         /* No need to do it for the bootloader - it is always registered   */
657         /* as initiating loader for the classes it loads.                  */
658         if (c->classloader)
659                 classcache_store(c->classloader,c,false);
660
661         /* this class is currently linking */
662
663         c->state |= CLASS_LINKING;
664
665         arraydesc = NULL;
666         worklist = NULL;
667
668         /* Link the super interfaces. */
669
670         for (i = 0; i < c->interfacescount; i++) {
671                 tc = c->interfaces[i];
672
673                 if (!(tc->state & CLASS_LINKED))
674                         if (!link_class(tc))
675                                 return NULL;
676         }
677         
678         /* check super class */
679
680         super = NULL;
681
682         /* Check for java/lang/Object. */
683
684         if (c->super == NULL) {
685                 c->index = 0;
686                 c->instancesize = sizeof(java_object_t);
687                 
688                 vftbllength = supervftbllength = 0;
689
690                 c->finalizer = NULL;
691         }
692         else {
693                 /* Get super class. */
694
695                 super = c->super;
696
697                 /* Link the super class if necessary. */
698                 
699                 if (!(super->state & CLASS_LINKED))
700                         if (!link_class(super))
701                                 return NULL;
702
703                 /* OR the ACC_CLASS_HAS_POINTERS and the ACC_CLASS_REFERENCE_*
704                    flags. */
705
706                 c->flags |= (super->flags &
707                                          (ACC_CLASS_HAS_POINTERS | ACC_CLASS_REFERENCE_MASK));
708
709                 /* handle array classes */
710
711                 if (c->name->text[0] == '[')
712                         if (!(arraydesc = link_array(c)))
713                                 return NULL;
714
715                 if (c->flags & ACC_INTERFACE)
716                         c->index = interfaceindex++;
717                 else
718                         c->index = super->index + 1;
719                 
720                 c->instancesize = super->instancesize;
721
722                 vftbllength = supervftbllength = super->vftbl->vftbllength;
723                 
724                 c->finalizer = super->finalizer;
725         }
726         RT_TIMING_GET_TIME(time_resolving);
727
728
729         /* compute vftbl length */
730
731         for (i = 0; i < c->methodscount; i++) {
732                 methodinfo *m = &(c->methods[i]);
733
734                 if (!(m->flags & ACC_STATIC)) { /* is instance method */
735                         tc = super;
736
737                         while (tc) {
738                                 s4 j;
739
740                                 for (j = 0; j < tc->methodscount; j++) {
741                                         if (method_canoverwrite(m, &(tc->methods[j]))) {
742                                                 if (tc->methods[j].flags & ACC_PRIVATE)
743                                                         goto notfoundvftblindex;
744
745                                                 /* package-private methods in other packages */
746                                                 /* must not be overridden                    */
747                                                 /* (see Java Language Specification 8.4.8.1) */
748                                                 if ( !(tc->methods[j].flags & (ACC_PUBLIC | ACC_PROTECTED)) 
749                                                          && !SAME_PACKAGE(c,tc) ) 
750                                                 {
751                                                     goto notfoundvftblindex;
752                                                 }
753
754                                                 if (!linker_overwrite_method(&(tc->methods[j]), m, &worklist))
755                                                         return NULL;
756
757                                                 goto foundvftblindex;
758                                         }
759                                 }
760
761                                 tc = tc->super;
762                         }
763
764                 notfoundvftblindex:
765                         m->vftblindex = (vftbllength++);
766                 foundvftblindex:
767                         ;
768                 }
769         }
770         RT_TIMING_GET_TIME(time_compute_vftbl);
771
772
773         /* Check all interfaces of an abstract class (maybe be an
774            interface too) for unimplemented methods.  Such methods are
775            called miranda-methods and are marked with the ACC_MIRANDA
776            flag.  VMClass.getDeclaredMethods does not return such
777            methods. */
778
779         if (c->flags & ACC_ABSTRACT) {
780                 classinfo  *ic;
781                 methodinfo *im;
782                 s4 abstractmethodscount;
783                 s4 j;
784                 s4 k;
785
786                 abstractmethodscount = 0;
787
788                 /* check all interfaces of the abstract class */
789
790                 for (i = 0; i < c->interfacescount; i++) {
791                         ic = c->interfaces[i];
792
793                         for (j = 0; j < ic->methodscount; j++) {
794                                 im = &(ic->methods[j]);
795
796                                 /* skip `<clinit>' and `<init>' */
797
798                                 if ((im->name == utf_clinit) || (im->name == utf_init))
799                                         continue;
800
801                                 for (tc = c; tc != NULL; tc = tc->super) {
802                                         for (k = 0; k < tc->methodscount; k++) {
803                                                 if (method_canoverwrite(im, &(tc->methods[k])))
804                                                         goto noabstractmethod;
805                                         }
806                                 }
807
808                                 abstractmethodscount++;
809
810                         noabstractmethod:
811                                 ;
812                         }
813                 }
814
815                 if (abstractmethodscount > 0) {
816                         methodinfo *am;
817
818                         /* reallocate methods memory */
819
820                         c->methods = (methodinfo*) MREALLOC(c->methods, methodinfo, c->methodscount,
821                                                                   c->methodscount + abstractmethodscount);
822
823                         for (i = 0; i < c->interfacescount; i++) {
824                                 ic = c->interfaces[i];
825
826                                 for (j = 0; j < ic->methodscount; j++) {
827                                         im = &(ic->methods[j]);
828
829                                         /* skip `<clinit>' and `<init>' */
830
831                                         if ((im->name == utf_clinit) || (im->name == utf_init))
832                                                 continue;
833
834                                         for (tc = c; tc != NULL; tc = tc->super) {
835                                                 for (k = 0; k < tc->methodscount; k++) {
836                                                         if (method_canoverwrite(im, &(tc->methods[k])))
837                                                                 goto noabstractmethod2;
838                                                 }
839                                         }
840
841                                         /* Copy the method found into the new c->methods
842                                            array and tag it as miranda-method. */
843
844                                         am = &(c->methods[c->methodscount]);
845                                         c->methodscount++;
846
847                                         MCOPY(am, im, methodinfo, 1);
848
849                                         am->vftblindex  = (vftbllength++);
850                                         am->clazz       = c;
851                                         am->flags      |= ACC_MIRANDA;
852
853                                 noabstractmethod2:
854                                         ;
855                                 }
856                         }
857                 }
858         }
859         RT_TIMING_GET_TIME(time_abstract);
860
861
862 #if defined(ENABLE_STATISTICS)
863         if (opt_stat)
864                 count_vftbl_len +=
865                         sizeof(vftbl_t) + (sizeof(methodptr) * (vftbllength - 1));
866 #endif
867
868         /* compute interfacetable length */
869
870         interfacetablelength = 0;
871
872         for (tc = c; tc != NULL; tc = tc->super) {
873                 for (i = 0; i < tc->interfacescount; i++) {
874                         s4 h = class_highestinterface(tc->interfaces[i]) + 1;
875
876                         if (h > interfacetablelength)
877                                 interfacetablelength = h;
878                 }
879         }
880         RT_TIMING_GET_TIME(time_compute_iftbl);
881
882         /* allocate virtual function table */
883
884         v = (vftbl_t *) mem_alloc(sizeof(vftbl_t) +
885                                                           sizeof(methodptr) * (vftbllength - 1) +
886                                                           sizeof(methodptr*) * (interfacetablelength - (interfacetablelength > 0)));
887         v = (vftbl_t *) (((methodptr *) v) +
888                                          (interfacetablelength - 1) * (interfacetablelength > 1));
889
890         c->vftbl                = v;
891         v->clazz                = c;
892         v->vftbllength          = vftbllength;
893         v->interfacetablelength = interfacetablelength;
894         v->arraydesc            = arraydesc;
895
896         /* store interface index in vftbl */
897
898         if (c->flags & ACC_INTERFACE)
899                 v->baseval = -(c->index);
900
901         /* copy virtual function table of super class */
902
903         for (i = 0; i < supervftbllength; i++) 
904                 v->table[i] = super->vftbl->table[i];
905
906         /* Fill the remaining vftbl slots with the AbstractMethodError
907            stub (all after the super class slots, because they are already
908            initialized). */
909
910         for (; i < vftbllength; i++) {
911 #if defined(ENABLE_JIT)
912 # if defined(ENABLE_INTRP)
913                 if (opt_intrp)
914                         v->table[i] = (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
915                 else
916 # endif
917                         v->table[i] = (methodptr) (ptrint) &asm_abstractmethoderror;
918 #else
919                 v->table[i] = (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
920 #endif
921         }
922
923         /* add method stubs into virtual function table */
924
925         for (i = 0; i < c->methodscount; i++) {
926                 methodinfo *m = &(c->methods[i]);
927
928                 assert(m->stubroutine == NULL);
929
930                 /* Don't create a compiler stub for abstract methods as they
931                    throw an AbstractMethodError with the default stub in the
932                    vftbl.  This entry is simply copied by sub-classes. */
933
934                 if (m->flags & ACC_ABSTRACT)
935                         continue;
936
937 #if defined(ENABLE_JIT)
938 # if defined(ENABLE_INTRP)
939                 if (opt_intrp)
940                         m->stubroutine = intrp_createcompilerstub(m);
941                 else
942 #endif
943                         m->stubroutine = (u1*) CompilerStub::generate(m);
944 #else
945                 m->stubroutine = intrp_createcompilerstub(m);
946 #endif
947
948                 /* static methods are not in the vftbl */
949
950                 if (m->flags & ACC_STATIC)
951                         continue;
952
953                 /* insert the stubroutine into the vftbl */
954
955                 v->table[m->vftblindex] = (methodptr) (ptrint) m->stubroutine;
956         }
957         RT_TIMING_GET_TIME(time_fill_vftbl);
958
959         /* compute instance size and offset of each field */
960         
961         for (i = 0; i < c->fieldscount; i++) {
962                 s4 dsize;
963                 fieldinfo *f = &(c->fields[i]);
964                 
965                 if (!(f->flags & ACC_STATIC)) {
966                         dsize = descriptor_typesize(f->parseddesc);
967                         c->instancesize = MEMORY_ALIGN(c->instancesize, dsize);
968                         f->offset = c->instancesize;
969                         c->instancesize += dsize;
970                 }
971         }
972         RT_TIMING_GET_TIME(time_offsets);
973
974         /* initialize interfacetable and interfacevftbllength */
975
976         v->interfacevftbllength = MNEW(s4, interfacetablelength);
977
978 #if defined(ENABLE_STATISTICS)
979         if (opt_stat)
980                 count_vftbl_len += (4 + sizeof(s4)) * v->interfacetablelength;
981 #endif
982
983         for (i = 0; i < interfacetablelength; i++) {
984                 v->interfacevftbllength[i] = 0;
985                 v->interfacetable[-i] = NULL;
986         }
987
988         /* add interfaces */
989
990         for (tc = c; tc != NULL; tc = tc->super)
991                 for (i = 0; i < tc->interfacescount; i++)
992                         if (!linker_addinterface(c, tc->interfaces[i]))
993                                 return NULL;
994
995         RT_TIMING_GET_TIME(time_fill_iftbl);
996
997         /* add finalizer method (not for java.lang.Object) */
998
999         if (super) {
1000                 methodinfo *fi;
1001
1002                 fi = class_findmethod(c, utf_finalize, utf_void__void);
1003
1004                 if (fi)
1005                         if (!(fi->flags & ACC_STATIC))
1006                                 c->finalizer = fi;
1007         }
1008         RT_TIMING_GET_TIME(time_finalizer);
1009
1010         /* final tasks */
1011
1012         linker_compute_subclasses(c);
1013
1014         /* FIXME: this is completely useless now */
1015         RT_TIMING_GET_TIME(time_subclasses);
1016
1017 #if USES_NEW_SUBTYPE
1018         if (!build_display(c))
1019                 return NULL;
1020 #endif
1021
1022         /* revert the linking state and class is linked */
1023
1024         c->state = (c->state & ~CLASS_LINKING) | CLASS_LINKED;
1025
1026         /* check worklist */
1027
1028         /* XXX must this also be done in case of exception? */
1029
1030         while (worklist != NULL) {
1031                 method_worklist *wi = worklist;
1032
1033                 worklist = worklist->next;
1034
1035                 INLINELOG( printf("MUST BE RECOMPILED: "); method_println(wi->m); );
1036                 jit_invalidate_code(wi->m);
1037
1038                 /* XXX put worklist into dump memory? */
1039                 FREE(wi, method_worklist);
1040         }
1041
1042         RT_TIMING_TIME_DIFF(time_start        ,time_resolving    ,RT_TIMING_LINK_RESOLVE);
1043         RT_TIMING_TIME_DIFF(time_resolving    ,time_compute_vftbl,RT_TIMING_LINK_C_VFTBL);
1044         RT_TIMING_TIME_DIFF(time_compute_vftbl,time_abstract     ,RT_TIMING_LINK_ABSTRACT);
1045         RT_TIMING_TIME_DIFF(time_abstract     ,time_compute_iftbl,RT_TIMING_LINK_C_IFTBL);
1046         RT_TIMING_TIME_DIFF(time_compute_iftbl,time_fill_vftbl   ,RT_TIMING_LINK_F_VFTBL);
1047         RT_TIMING_TIME_DIFF(time_fill_vftbl   ,time_offsets      ,RT_TIMING_LINK_OFFSETS);
1048         RT_TIMING_TIME_DIFF(time_offsets      ,time_fill_iftbl   ,RT_TIMING_LINK_F_IFTBL);
1049         RT_TIMING_TIME_DIFF(time_fill_iftbl   ,time_finalizer    ,RT_TIMING_LINK_FINALIZER);
1050         RT_TIMING_TIME_DIFF(time_finalizer    ,time_subclasses   ,RT_TIMING_LINK_SUBCLASS);
1051
1052         /* just return c to show that we didn't had a problem */
1053
1054         return c;
1055 }
1056
1057
1058 /* link_array ******************************************************************
1059
1060    This function is called by link_class to create the arraydescriptor
1061    for an array class.
1062
1063    This function returns NULL if the array cannot be linked because
1064    the component type has not been linked yet.
1065
1066 *******************************************************************************/
1067
1068 static arraydescriptor *link_array(classinfo *c)
1069 {
1070         classinfo       *comp;
1071         s4               namelen;
1072         arraydescriptor *desc;
1073         vftbl_t         *compvftbl;
1074         utf             *u;
1075
1076         comp = NULL;
1077         namelen = c->name->blength;
1078
1079         /* Check the component type */
1080
1081         switch (c->name->text[1]) {
1082         case '[':
1083                 /* c is an array of arrays. */
1084                 u = utf_new(c->name->text + 1, namelen - 1);
1085                 if (!(comp = load_class_from_classloader(u, c->classloader)))
1086                         return NULL;
1087                 break;
1088
1089         case 'L':
1090                 /* c is an array of objects. */
1091                 u = utf_new(c->name->text + 2, namelen - 3);
1092                 if (!(comp = load_class_from_classloader(u, c->classloader)))
1093                         return NULL;
1094                 break;
1095         }
1096
1097         /* If the component type has not been linked, link it now */
1098
1099         assert(!comp || (comp->state & CLASS_LOADED));
1100
1101         if (comp && !(comp->state & CLASS_LINKED))
1102                 if (!link_class(comp))
1103                         return NULL;
1104
1105         /* Allocate the arraydescriptor */
1106
1107         desc = NEW(arraydescriptor);
1108
1109         if (comp) {
1110                 /* c is an array of references */
1111                 desc->arraytype = ARRAYTYPE_OBJECT;
1112                 desc->componentsize = sizeof(void*);
1113                 desc->dataoffset = OFFSET(java_objectarray_t, data);
1114                 
1115                 compvftbl = comp->vftbl;
1116
1117                 if (!compvftbl) {
1118                         log_text("Component class has no vftbl");
1119                         assert(0);
1120                 }
1121
1122                 desc->componentvftbl = compvftbl;
1123                 
1124                 if (compvftbl->arraydesc) {
1125                         desc->elementvftbl = compvftbl->arraydesc->elementvftbl;
1126
1127                         if (compvftbl->arraydesc->dimension >= 255) {
1128                                 exceptions_throw_illegalargumentexception();
1129                                 return NULL;
1130                         }
1131
1132                         desc->dimension = compvftbl->arraydesc->dimension + 1;
1133                         desc->elementtype = compvftbl->arraydesc->elementtype;
1134
1135                 } else {
1136                         desc->elementvftbl = compvftbl;
1137                         desc->dimension = 1;
1138                         desc->elementtype = ARRAYTYPE_OBJECT;
1139                 }
1140
1141         } else {
1142                 /* c is an array of a primitive type */
1143                 switch (c->name->text[1]) {
1144                 case 'Z':
1145                         desc->arraytype = ARRAYTYPE_BOOLEAN;
1146                         desc->dataoffset = OFFSET(java_booleanarray_t,data);
1147                         desc->componentsize = sizeof(u1);
1148                         break;
1149
1150                 case 'B':
1151                         desc->arraytype = ARRAYTYPE_BYTE;
1152                         desc->dataoffset = OFFSET(java_bytearray_t,data);
1153                         desc->componentsize = sizeof(u1);
1154                         break;
1155
1156                 case 'C':
1157                         desc->arraytype = ARRAYTYPE_CHAR;
1158                         desc->dataoffset = OFFSET(java_chararray_t,data);
1159                         desc->componentsize = sizeof(u2);
1160                         break;
1161
1162                 case 'D':
1163                         desc->arraytype = ARRAYTYPE_DOUBLE;
1164                         desc->dataoffset = OFFSET(java_doublearray_t,data);
1165                         desc->componentsize = sizeof(double);
1166                         break;
1167
1168                 case 'F':
1169                         desc->arraytype = ARRAYTYPE_FLOAT;
1170                         desc->dataoffset = OFFSET(java_floatarray_t,data);
1171                         desc->componentsize = sizeof(float);
1172                         break;
1173
1174                 case 'I':
1175                         desc->arraytype = ARRAYTYPE_INT;
1176                         desc->dataoffset = OFFSET(java_intarray_t,data);
1177                         desc->componentsize = sizeof(s4);
1178                         break;
1179
1180                 case 'J':
1181                         desc->arraytype = ARRAYTYPE_LONG;
1182                         desc->dataoffset = OFFSET(java_longarray_t,data);
1183                         desc->componentsize = sizeof(s8);
1184                         break;
1185
1186                 case 'S':
1187                         desc->arraytype = ARRAYTYPE_SHORT;
1188                         desc->dataoffset = OFFSET(java_shortarray_t,data);
1189                         desc->componentsize = sizeof(s2);
1190                         break;
1191
1192                 default:
1193                         exceptions_throw_noclassdeffounderror(c->name);
1194                         return NULL;
1195                 }
1196                 
1197                 desc->componentvftbl = NULL;
1198                 desc->elementvftbl = NULL;
1199                 desc->dimension = 1;
1200                 desc->elementtype = desc->arraytype;
1201         }
1202
1203         return desc;
1204 }
1205
1206 /* linker_create_string_later **************************************************
1207
1208    A hack so we can initialize java.lang.String objects during initialization.
1209
1210 *******************************************************************************/
1211 void linker_create_string_later(java_object_t **a, utf *u)
1212 {
1213         deferred_strings.push_back(std::make_pair(a, u));
1214 }
1215
1216 void linker_initialize_deferred_strings()
1217 {
1218         deferred_strings_vec_t::const_iterator it = deferred_strings.begin();
1219         for (; it != deferred_strings.end(); ++it)
1220                 *it->first = literalstring_new(it->second);
1221         deferred_strings.clear();
1222 }
1223
1224
1225 /* linker_compute_subclasses ***************************************************
1226
1227    XXX
1228
1229    ATTENTION: DO NOT REMOVE ANY OF THE LOCKING MECHANISMS BELOW:
1230    This function needs to take the class renumber lock and stop the
1231    world during class renumbering. The lock is used in C code which
1232    is not that performance critical. Whereas JIT code uses critical
1233    sections to atomically access the class values.
1234
1235 *******************************************************************************/
1236
1237 static void linker_compute_subclasses(classinfo *c)
1238 {
1239
1240         LOCK_CLASSRENUMBER_LOCK;
1241
1242         if (!(c->flags & ACC_INTERFACE)) {
1243                 c->nextsub = NULL;
1244                 c->sub     = NULL;
1245 #if USES_NEW_SUBTYPE
1246                 c->vftbl->baseval = 1; /* so it does not look like an interface */
1247 #endif
1248         }
1249
1250         if (!(c->flags & ACC_INTERFACE) && (c->super != NULL)) {
1251                 c->nextsub    = c->super->sub;
1252                 c->super->sub = c;
1253         }
1254
1255         classvalue = 0;
1256
1257 #if !USES_NEW_SUBTYPE
1258         /* compute class values */
1259
1260         linker_compute_class_values(class_java_lang_Object);
1261 #endif
1262
1263         UNLOCK_CLASSRENUMBER_LOCK;
1264
1265 }
1266
1267
1268 /* linker_compute_class_values *************************************************
1269
1270    XXX
1271
1272 *******************************************************************************/
1273
1274 static void linker_compute_class_values(classinfo *c)
1275 {
1276         classinfo *subs;
1277
1278         c->vftbl->baseval = ++classvalue;
1279
1280         subs = c->sub;
1281
1282         while (subs) {
1283                 linker_compute_class_values(subs);
1284
1285                 subs = subs->nextsub;
1286         }
1287
1288         c->vftbl->diffval = classvalue - c->vftbl->baseval;
1289 }
1290
1291
1292 /* linker_addinterface *********************************************************
1293
1294    Is needed by link_class for adding a VTBL to a class. All
1295    interfaces implemented by ic are added as well.
1296
1297    RETURN VALUE:
1298       true.........everything ok
1299           false........an exception has been thrown
1300
1301 *******************************************************************************/
1302
1303 static bool linker_addinterface(classinfo *c, classinfo *ic)
1304 {
1305         s4          j, k;
1306         vftbl_t    *v;
1307         s4          i;
1308         classinfo  *sc;
1309         methodinfo *m;
1310
1311         v = c->vftbl;
1312         i = ic->index;
1313
1314         if (i >= v->interfacetablelength)
1315                 vm_abort("Internal error: interfacetable overflow");
1316
1317         /* if this interface has already been added, return immediately */
1318
1319         if (v->interfacetable[-i] != NULL)
1320                 return true;
1321
1322         if (ic->methodscount == 0) {  /* fake entry needed for subtype test */
1323                 v->interfacevftbllength[i] = 1;
1324                 v->interfacetable[-i]      = MNEW(methodptr, 1);
1325                 v->interfacetable[-i][0]   = NULL;
1326         }
1327         else {
1328                 v->interfacevftbllength[i] = ic->methodscount;
1329                 v->interfacetable[-i]      = MNEW(methodptr, ic->methodscount);
1330
1331 #if defined(ENABLE_STATISTICS)
1332                 if (opt_stat)
1333                         count_vftbl_len += sizeof(methodptr) *
1334                                 (ic->methodscount + (ic->methodscount == 0));
1335 #endif
1336
1337                 for (j = 0; j < ic->methodscount; j++) {
1338                         for (sc = c; sc != NULL; sc = sc->super) {
1339                                 for (k = 0; k < sc->methodscount; k++) {
1340                                         m = &(sc->methods[k]);
1341
1342                                         if (method_canoverwrite(m, &(ic->methods[j]))) {
1343                                                 /* method m overwrites the (abstract) method */
1344 #if defined(ENABLE_VERIFIER)
1345                                                 /* Add loading constraints (for the more
1346                                                    general types of the method
1347                                                    ic->methods[j]).  */
1348                                                 if (!classcache_add_constraints_for_params(
1349                                                                         c->classloader, ic->classloader,
1350                                                                         &(ic->methods[j])))
1351                                                 {
1352                                                         return false;
1353                                                 }
1354 #endif
1355
1356                                                 /* XXX taken from gcj */
1357                                                 /* check for ACC_STATIC: IncompatibleClassChangeError */
1358
1359                                                 /* check for !ACC_PUBLIC: IllegalAccessError */
1360
1361                                                 /* check for ACC_ABSTRACT: AbstracMethodError,
1362                                                    not sure about that one */
1363
1364                                                 v->interfacetable[-i][j] = v->table[m->vftblindex];
1365                                                 goto foundmethod;
1366                                         }
1367                                 }
1368                         }
1369
1370                         /* If no method was found, insert the AbstractMethodError
1371                            stub. */
1372
1373 #if defined(ENABLE_JIT)
1374 # if defined(ENABLE_INTRP)
1375                         if (opt_intrp)
1376                                 v->interfacetable[-i][j] =
1377                                         (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
1378                         else
1379 # endif
1380                                 v->interfacetable[-i][j] =
1381                                         (methodptr) (ptrint) &asm_abstractmethoderror;
1382 #else
1383                         v->interfacetable[-i][j] =
1384                                 (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
1385 #endif
1386
1387                 foundmethod:
1388                         ;
1389                 }
1390         }
1391
1392         /* add superinterfaces of this interface */
1393
1394         for (j = 0; j < ic->interfacescount; j++)
1395                 if (!linker_addinterface(c, ic->interfaces[j]))
1396                         return false;
1397
1398         /* everything ok */
1399
1400         return true;
1401 }
1402
1403
1404 /* class_highestinterface ******************************************************
1405
1406    Used by the function link_class to determine the amount of memory
1407    needed for the interface table.
1408
1409 *******************************************************************************/
1410
1411 static s4 class_highestinterface(classinfo *c)
1412 {
1413         s4 h;
1414         s4 h2;
1415         s4 i;
1416         
1417     /* check for ACC_INTERFACE bit already done in link_class_intern */
1418
1419     h = c->index;
1420
1421         for (i = 0; i < c->interfacescount; i++) {
1422                 h2 = class_highestinterface(c->interfaces[i]);
1423
1424                 if (h2 > h)
1425                         h = h2;
1426         }
1427
1428         return h;
1429 }
1430
1431 #if defined(__cplusplus)
1432 }
1433 #endif
1434
1435 /*
1436  * These are local overrides for various environment variables in Emacs.
1437  * Please do not remove this and leave it at the end of the file, where
1438  * Emacs will automagically detect them.
1439  * ---------------------------------------------------------------------
1440  * Local variables:
1441  * mode: c++
1442  * indent-tabs-mode: t
1443  * c-basic-offset: 4
1444  * tab-width: 4
1445  * End:
1446  * vim:noexpandtab:sw=4:ts=4:
1447  */