0d389dc345c8dfc657a0d6809a6b5598c51ae04b
[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 # endif
302
303         if (!link_class(arrayclass_java_lang_Object))
304                 vm_abort("linker_init: linking failed");
305 #endif
306
307
308         /* create pseudo classes used by the typechecker */
309
310     /* pseudo class for Arraystubs (extends java.lang.Object) */
311
312         pseudo_class_Arraystub                   =
313                 class_create_classinfo(utf_new_char("$ARRAYSTUB$"));
314         pseudo_class_Arraystub->state           |= CLASS_LOADED;
315         pseudo_class_Arraystub->super            = class_java_lang_Object;
316
317 #if defined(ENABLE_JAVASE)
318
319         pseudo_class_Arraystub->interfacescount  = 2;
320         pseudo_class_Arraystub->interfaces       = MNEW(classinfo*, 2);
321         pseudo_class_Arraystub->interfaces[0]    = class_java_lang_Cloneable;
322         pseudo_class_Arraystub->interfaces[1]    = class_java_io_Serializable;
323
324 #elif defined(ENABLE_JAVAME_CLDC1_1)
325
326         pseudo_class_Arraystub->interfacescount    = 0;
327         pseudo_class_Arraystub->interfaces         = NULL;
328
329 #else
330 # error unknown Java configuration
331 #endif
332
333         if (!classcache_store_unique(pseudo_class_Arraystub))
334                 vm_abort("linker_init: could not cache pseudo_class_Arraystub");
335
336         if (!link_class(pseudo_class_Arraystub))
337                 vm_abort("linker_init: linking pseudo_class_Arraystub failed");
338
339         /* pseudo class representing the null type */
340
341         pseudo_class_Null         = class_create_classinfo(utf_new_char("$NULL$"));
342         pseudo_class_Null->state |= CLASS_LOADED;
343         pseudo_class_Null->super  = class_java_lang_Object;
344
345         if (!classcache_store_unique(pseudo_class_Null))
346                 vm_abort("linker_init: could not cache pseudo_class_Null");
347
348         if (!link_class(pseudo_class_Null))
349                 vm_abort("linker_init: linking failed");
350
351         /* pseudo class representing new uninitialized objects */
352     
353         pseudo_class_New         = class_create_classinfo(utf_new_char("$NEW$"));
354         pseudo_class_New->state |= CLASS_LOADED;
355         pseudo_class_New->state |= CLASS_LINKED; /* XXX is this allright? */
356         pseudo_class_New->super  = class_java_lang_Object;
357
358         if (!classcache_store_unique(pseudo_class_New))
359                 vm_abort("linker_init: could not cache pseudo_class_New");
360
361         /* Correct vftbl-entries (retarded loading and linking of class
362            java/lang/String). */
363
364         stringtable_update();
365 }
366
367
368 /* link_class ******************************************************************
369
370    Wrapper function for link_class_intern to ease monitor enter/exit
371    and exception handling.
372
373 *******************************************************************************/
374
375 classinfo *link_class(classinfo *c)
376 {
377         classinfo *r;
378 #if defined(ENABLE_RT_TIMING)
379         struct timespec time_start, time_end;
380 #endif
381
382         RT_TIMING_GET_TIME(time_start);
383
384         if (c == NULL) {
385                 exceptions_throw_nullpointerexception();
386                 return 0;
387         }
388
389         LOCK_MONITOR_ENTER(c);
390
391         /* Maybe the class is currently linking or is already linked.*/
392
393         if ((c->state & CLASS_LINKING) || (c->state & CLASS_LINKED)) {
394                 LOCK_MONITOR_EXIT(c);
395
396                 return c;
397         }
398
399 #if defined(ENABLE_STATISTICS)
400         /* measure time */
401
402         if (opt_getcompilingtime)
403                 compilingtime_stop();
404
405         if (opt_getloadingtime)
406                 loadingtime_start();
407 #endif
408
409         /* call the internal function */
410
411         r = link_class_intern(c);
412
413         /* If return value is NULL, we had a problem and the class is not
414            linked. */
415
416         if (r == NULL)
417                 c->state &= ~CLASS_LINKING;
418
419 #if defined(ENABLE_STATISTICS)
420         /* measure time */
421
422         if (opt_getloadingtime)
423                 loadingtime_stop();
424
425         if (opt_getcompilingtime)
426                 compilingtime_start();
427 #endif
428
429         LOCK_MONITOR_EXIT(c);
430
431         RT_TIMING_GET_TIME(time_end);
432
433         RT_TIMING_TIME_DIFF(time_start,time_end,RT_TIMING_LINK_TOTAL);
434
435         // Hook point just after a class was linked.
436         if (!Hook::class_linked(r))
437                 return 0;
438
439         return r;
440 }
441
442
443 /* linker_overwrite_method *****************************************************
444
445    Overwrite a method with another one, update method flags and check
446    assumptions.
447
448    IN:
449       mg................the general method being overwritten
450           ms................the overwriting (more specialized) method
451           wl................worklist where to add invalidated methods
452
453    RETURN VALUE:
454       true..............everything ok
455           false.............an exception has been thrown
456
457 *******************************************************************************/
458
459 static bool linker_overwrite_method(methodinfo *mg,
460                                                                         methodinfo *ms,
461                                                                         method_worklist **wl)
462 {
463         classinfo *cg;
464         classinfo *cs;
465
466         cg = mg->clazz;
467         cs = ms->clazz;
468
469         /* overriding a final method is illegal */
470
471         if (mg->flags & ACC_FINAL) {
472                 exceptions_throw_verifyerror(mg, "Overriding final method");
473                 return false;
474         }
475
476         /* method ms overwrites method mg */
477
478 #if defined(ENABLE_VERIFIER)
479         /* Add loading constraints (for the more general types of method mg). */
480         /* Not for <init>, as it is not invoked virtually.                    */
481
482         if ((ms->name != utf_init)
483                         && !classcache_add_constraints_for_params(
484                                 cs->classloader, cg->classloader, mg))
485         {
486                 return false;
487         }
488 #endif
489
490         /* inherit the vftbl index, and record the overwriting */
491
492         ms->vftblindex = mg->vftblindex;
493         ms->overwrites = mg;
494
495         /* update flags and check assumptions */
496         /* <init> methods are a special case, as they are never dispatched dynamically */
497
498         if ((ms->flags & ACC_METHOD_IMPLEMENTED) && ms->name != utf_init) {
499                 do {
500
501 #if defined(ENABLE_TLH)
502                         if (mg->flags & ACC_METHOD_MONOMORPHY_USED) {
503                                 printf("%s/%s is evil! the siner is %s/%s\n", mg->clazz->name->text, mg->name->text,
504                                         ms->clazz->name->text, ms->name->text);
505                                 ms->flags |= ACC_METHOD_PARENT_MONOMORPHY_USED;                                 
506                         }
507 #endif
508
509                         if (mg->flags & ACC_METHOD_IMPLEMENTED) {
510                                 /* this adds another implementation */
511
512                                 mg->flags &= ~ACC_METHOD_MONOMORPHIC;
513
514                                 INLINELOG( printf("becomes polymorphic: "); method_println(mg); );
515
516                                 method_break_assumption_monomorphic(mg, wl);
517                         }
518                         else {
519                                 /* this is the first implementation */
520
521                                 mg->flags |= ACC_METHOD_IMPLEMENTED;
522
523                                 INLINELOG( printf("becomes implemented: "); method_println(mg); );
524                         }
525
526                         ms = mg;
527                         mg = mg->overwrites;
528                 } while (mg != NULL);
529         }
530
531         return true;
532 }
533
534
535 #if USES_NEW_SUBTYPE
536 /* build_display ***************************************************************
537
538    Builds the entire display for a class. This entails filling the fixed part
539    as well as allocating and initializing the overflow part.
540
541    See Cliff Click and John Rose: Fast subtype checking in the Hotspot JVM.
542
543 *******************************************************************************/
544
545 static classinfo *build_display(classinfo *c)
546 {
547         int depth, i;
548         int depth_fixed;
549         classinfo *super;
550
551         do {
552                 /* Handle arrays. */
553                 if (c->vftbl->arraydesc) {
554                         arraydescriptor *a = c->vftbl->arraydesc;
555                         if (a->elementvftbl && a->elementvftbl->clazz->super) {
556                                 classinfo *cls = a->elementvftbl->clazz->super;
557                                 int n;
558                                 for (n=0; n<a->dimension; n++)
559                                         cls = class_array_of(cls, true);
560                                 super = cls;
561                                 break;
562                         }
563                         if (a->componentvftbl && a->elementvftbl) {
564                                 super = a->componentvftbl->clazz;
565                                 break;
566                         }
567                 }
568                 /* Normal classes. */
569                 super = c->super;
570         } while (false);
571         if (super) {
572                 if (!link_class(super))
573                         return NULL;
574                 depth = super->vftbl->subtype_depth + 1;
575         } else
576                 /* java.lang.Object doesn't have a super class. */
577                 depth = 0;
578
579         /* Now copy super's display, append c->vftbl and initialize the remaining fields. */
580         if (depth >= DISPLAY_SIZE) {
581                 c->vftbl->subtype_overflow = MNEW(vftbl_t *, depth - DISPLAY_SIZE + 1);
582 #if defined(ENABLE_STATISTICS)
583                 if (opt_stat)
584                         count_vftbl_len += sizeof(vftbl_t*) * (depth - DISPLAY_SIZE + 1);
585 #endif
586                 memcpy(c->vftbl->subtype_overflow, super->vftbl->subtype_overflow, sizeof(vftbl_t*) * (depth - DISPLAY_SIZE));
587                 c->vftbl->subtype_overflow[depth - DISPLAY_SIZE] = c->vftbl;
588                 depth_fixed = DISPLAY_SIZE;
589         }
590         else {
591                 depth_fixed = depth;
592                 c->vftbl->subtype_display[depth] = c->vftbl;
593         }
594
595         if (super)
596                 memcpy(c->vftbl->subtype_display, super->vftbl->subtype_display, sizeof(vftbl_t*) * depth_fixed);
597         for (i=depth_fixed+1; i<=DISPLAY_SIZE; i++)
598                 c->vftbl->subtype_display[i] = NULL;
599         c->vftbl->subtype_offset = OFFSET(vftbl_t, subtype_display[0]) + sizeof(vftbl_t*) * depth_fixed;
600         c->vftbl->subtype_depth = depth;
601
602         return c;
603 }
604 #endif
605
606 /* link_class_intern ***********************************************************
607
608    Tries to link a class. The function calculates the length in bytes
609    that an instance of this class requires as well as the VTBL for
610    methods and interface methods.
611         
612 *******************************************************************************/
613
614 static classinfo *link_class_intern(classinfo *c)
615 {
616         classinfo *super;             /* super class                              */
617         classinfo *tc;                /* temporary class variable                 */
618         s4 supervftbllength;          /* vftbllegnth of super class               */
619         s4 vftbllength;               /* vftbllength of current class             */
620         s4 interfacetablelength;      /* interface table length                   */
621         vftbl_t *v;                   /* vftbl of current class                   */
622         s4 i;                         /* interface/method/field counter           */
623         arraydescriptor *arraydesc;   /* descriptor for array classes             */
624         method_worklist *worklist;    /* worklist for recompilation               */
625 #if defined(ENABLE_RT_TIMING)
626         struct timespec time_start, time_resolving, time_compute_vftbl,
627                                         time_abstract, time_compute_iftbl, time_fill_vftbl,
628                                         time_offsets, time_fill_iftbl, time_finalizer,
629                                         time_subclasses;
630 #endif
631
632         RT_TIMING_GET_TIME(time_start);
633
634         TRACELINKCLASS(c);
635
636         /* the class must be loaded */
637
638         /* XXX should this be a specific exception? */
639         assert(c->state & CLASS_LOADED);
640
641         /* This is check in link_class. */
642
643         assert(!(c->state & CLASS_LINKED));
644
645         /* cache the self-reference of this class                          */
646         /* we do this for cases where the defining loader of the class     */
647         /* has not yet been recorded as an initiating loader for the class */
648         /* this is needed so subsequent code can assume that self-refs     */
649         /* will always resolve lazily                                      */
650         /* No need to do it for the bootloader - it is always registered   */
651         /* as initiating loader for the classes it loads.                  */
652         if (c->classloader)
653                 classcache_store(c->classloader,c,false);
654
655         /* this class is currently linking */
656
657         c->state |= CLASS_LINKING;
658
659         arraydesc = NULL;
660         worklist = NULL;
661
662         /* Link the super interfaces. */
663
664         for (i = 0; i < c->interfacescount; i++) {
665                 tc = c->interfaces[i];
666
667                 if (!(tc->state & CLASS_LINKED))
668                         if (!link_class(tc))
669                                 return NULL;
670         }
671         
672         /* check super class */
673
674         super = NULL;
675
676         /* Check for java/lang/Object. */
677
678         if (c->super == NULL) {
679                 c->index = 0;
680                 c->instancesize = sizeof(java_object_t);
681                 
682                 vftbllength = supervftbllength = 0;
683
684                 c->finalizer = NULL;
685         }
686         else {
687                 /* Get super class. */
688
689                 super = c->super;
690
691                 /* Link the super class if necessary. */
692                 
693                 if (!(super->state & CLASS_LINKED))
694                         if (!link_class(super))
695                                 return NULL;
696
697                 /* OR the ACC_CLASS_HAS_POINTERS and the ACC_CLASS_REFERENCE_*
698                    flags. */
699
700                 c->flags |= (super->flags &
701                                          (ACC_CLASS_HAS_POINTERS | ACC_CLASS_REFERENCE_MASK));
702
703                 /* handle array classes */
704
705                 if (c->name->text[0] == '[')
706                         if (!(arraydesc = link_array(c)))
707                                 return NULL;
708
709                 if (c->flags & ACC_INTERFACE)
710                         c->index = interfaceindex++;
711                 else
712                         c->index = super->index + 1;
713                 
714                 c->instancesize = super->instancesize;
715
716                 vftbllength = supervftbllength = super->vftbl->vftbllength;
717                 
718                 c->finalizer = super->finalizer;
719         }
720         RT_TIMING_GET_TIME(time_resolving);
721
722
723         /* compute vftbl length */
724
725         for (i = 0; i < c->methodscount; i++) {
726                 methodinfo *m = &(c->methods[i]);
727
728                 if (!(m->flags & ACC_STATIC)) { /* is instance method */
729                         tc = super;
730
731                         while (tc) {
732                                 s4 j;
733
734                                 for (j = 0; j < tc->methodscount; j++) {
735                                         if (method_canoverwrite(m, &(tc->methods[j]))) {
736                                                 if (tc->methods[j].flags & ACC_PRIVATE)
737                                                         goto notfoundvftblindex;
738
739                                                 /* package-private methods in other packages */
740                                                 /* must not be overridden                    */
741                                                 /* (see Java Language Specification 8.4.8.1) */
742                                                 if ( !(tc->methods[j].flags & (ACC_PUBLIC | ACC_PROTECTED)) 
743                                                          && !SAME_PACKAGE(c,tc) ) 
744                                                 {
745                                                     goto notfoundvftblindex;
746                                                 }
747
748                                                 if (!linker_overwrite_method(&(tc->methods[j]), m, &worklist))
749                                                         return NULL;
750
751                                                 goto foundvftblindex;
752                                         }
753                                 }
754
755                                 tc = tc->super;
756                         }
757
758                 notfoundvftblindex:
759                         m->vftblindex = (vftbllength++);
760                 foundvftblindex:
761                         ;
762                 }
763         }
764         RT_TIMING_GET_TIME(time_compute_vftbl);
765
766
767         /* Check all interfaces of an abstract class (maybe be an
768            interface too) for unimplemented methods.  Such methods are
769            called miranda-methods and are marked with the ACC_MIRANDA
770            flag.  VMClass.getDeclaredMethods does not return such
771            methods. */
772
773         if (c->flags & ACC_ABSTRACT) {
774                 classinfo  *ic;
775                 methodinfo *im;
776                 s4 abstractmethodscount;
777                 s4 j;
778                 s4 k;
779
780                 abstractmethodscount = 0;
781
782                 /* check all interfaces of the abstract class */
783
784                 for (i = 0; i < c->interfacescount; i++) {
785                         ic = c->interfaces[i];
786
787                         for (j = 0; j < ic->methodscount; j++) {
788                                 im = &(ic->methods[j]);
789
790                                 /* skip `<clinit>' and `<init>' */
791
792                                 if ((im->name == utf_clinit) || (im->name == utf_init))
793                                         continue;
794
795                                 for (tc = c; tc != NULL; tc = tc->super) {
796                                         for (k = 0; k < tc->methodscount; k++) {
797                                                 if (method_canoverwrite(im, &(tc->methods[k])))
798                                                         goto noabstractmethod;
799                                         }
800                                 }
801
802                                 abstractmethodscount++;
803
804                         noabstractmethod:
805                                 ;
806                         }
807                 }
808
809                 if (abstractmethodscount > 0) {
810                         methodinfo *am;
811
812                         /* reallocate methods memory */
813
814                         c->methods = (methodinfo*) MREALLOC(c->methods, methodinfo, c->methodscount,
815                                                                   c->methodscount + abstractmethodscount);
816
817                         for (i = 0; i < c->interfacescount; i++) {
818                                 ic = c->interfaces[i];
819
820                                 for (j = 0; j < ic->methodscount; j++) {
821                                         im = &(ic->methods[j]);
822
823                                         /* skip `<clinit>' and `<init>' */
824
825                                         if ((im->name == utf_clinit) || (im->name == utf_init))
826                                                 continue;
827
828                                         for (tc = c; tc != NULL; tc = tc->super) {
829                                                 for (k = 0; k < tc->methodscount; k++) {
830                                                         if (method_canoverwrite(im, &(tc->methods[k])))
831                                                                 goto noabstractmethod2;
832                                                 }
833                                         }
834
835                                         /* Copy the method found into the new c->methods
836                                            array and tag it as miranda-method. */
837
838                                         am = &(c->methods[c->methodscount]);
839                                         c->methodscount++;
840
841                                         MCOPY(am, im, methodinfo, 1);
842
843                                         am->vftblindex  = (vftbllength++);
844                                         am->clazz       = c;
845                                         am->flags      |= ACC_MIRANDA;
846
847                                 noabstractmethod2:
848                                         ;
849                                 }
850                         }
851                 }
852         }
853         RT_TIMING_GET_TIME(time_abstract);
854
855
856 #if defined(ENABLE_STATISTICS)
857         if (opt_stat)
858                 count_vftbl_len +=
859                         sizeof(vftbl_t) + (sizeof(methodptr) * (vftbllength - 1));
860 #endif
861
862         /* compute interfacetable length */
863
864         interfacetablelength = 0;
865
866         for (tc = c; tc != NULL; tc = tc->super) {
867                 for (i = 0; i < tc->interfacescount; i++) {
868                         s4 h = class_highestinterface(tc->interfaces[i]) + 1;
869
870                         if (h > interfacetablelength)
871                                 interfacetablelength = h;
872                 }
873         }
874         RT_TIMING_GET_TIME(time_compute_iftbl);
875
876         /* allocate virtual function table */
877
878         v = (vftbl_t *) mem_alloc(sizeof(vftbl_t) +
879                                                           sizeof(methodptr) * (vftbllength - 1) +
880                                                           sizeof(methodptr*) * (interfacetablelength - (interfacetablelength > 0)));
881         v = (vftbl_t *) (((methodptr *) v) +
882                                          (interfacetablelength - 1) * (interfacetablelength > 1));
883
884         c->vftbl                = v;
885         v->clazz                = c;
886         v->vftbllength          = vftbllength;
887         v->interfacetablelength = interfacetablelength;
888         v->arraydesc            = arraydesc;
889
890         /* store interface index in vftbl */
891
892         if (c->flags & ACC_INTERFACE)
893                 v->baseval = -(c->index);
894
895         /* copy virtual function table of super class */
896
897         for (i = 0; i < supervftbllength; i++) 
898                 v->table[i] = super->vftbl->table[i];
899
900         /* Fill the remaining vftbl slots with the AbstractMethodError
901            stub (all after the super class slots, because they are already
902            initialized). */
903
904         for (; i < vftbllength; i++) {
905 #if defined(ENABLE_JIT)
906 # if defined(ENABLE_INTRP)
907                 if (opt_intrp)
908                         v->table[i] = (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
909                 else
910 # endif
911                         v->table[i] = (methodptr) (ptrint) &asm_abstractmethoderror;
912 #else
913                 v->table[i] = (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
914 #endif
915         }
916
917         /* add method stubs into virtual function table */
918
919         for (i = 0; i < c->methodscount; i++) {
920                 methodinfo *m = &(c->methods[i]);
921
922                 assert(m->stubroutine == NULL);
923
924                 /* Don't create a compiler stub for abstract methods as they
925                    throw an AbstractMethodError with the default stub in the
926                    vftbl.  This entry is simply copied by sub-classes. */
927
928                 if (m->flags & ACC_ABSTRACT)
929                         continue;
930
931 #if defined(ENABLE_JIT)
932 # if defined(ENABLE_INTRP)
933                 if (opt_intrp)
934                         m->stubroutine = intrp_createcompilerstub(m);
935                 else
936 #endif
937                         m->stubroutine = (u1*) CompilerStub::generate(m);
938 #else
939                 m->stubroutine = intrp_createcompilerstub(m);
940 #endif
941
942                 /* static methods are not in the vftbl */
943
944                 if (m->flags & ACC_STATIC)
945                         continue;
946
947                 /* insert the stubroutine into the vftbl */
948
949                 v->table[m->vftblindex] = (methodptr) (ptrint) m->stubroutine;
950         }
951         RT_TIMING_GET_TIME(time_fill_vftbl);
952
953         /* compute instance size and offset of each field */
954         
955         for (i = 0; i < c->fieldscount; i++) {
956                 s4 dsize;
957                 fieldinfo *f = &(c->fields[i]);
958                 
959                 if (!(f->flags & ACC_STATIC)) {
960                         dsize = descriptor_typesize(f->parseddesc);
961                         c->instancesize = MEMORY_ALIGN(c->instancesize, dsize);
962                         f->offset = c->instancesize;
963                         c->instancesize += dsize;
964                 }
965         }
966         RT_TIMING_GET_TIME(time_offsets);
967
968         /* initialize interfacetable and interfacevftbllength */
969
970         v->interfacevftbllength = MNEW(s4, interfacetablelength);
971
972 #if defined(ENABLE_STATISTICS)
973         if (opt_stat)
974                 count_vftbl_len += (4 + sizeof(s4)) * v->interfacetablelength;
975 #endif
976
977         for (i = 0; i < interfacetablelength; i++) {
978                 v->interfacevftbllength[i] = 0;
979                 v->interfacetable[-i] = NULL;
980         }
981
982         /* add interfaces */
983
984         for (tc = c; tc != NULL; tc = tc->super)
985                 for (i = 0; i < tc->interfacescount; i++)
986                         if (!linker_addinterface(c, tc->interfaces[i]))
987                                 return NULL;
988
989         RT_TIMING_GET_TIME(time_fill_iftbl);
990
991         /* add finalizer method (not for java.lang.Object) */
992
993         if (super) {
994                 methodinfo *fi;
995
996                 fi = class_findmethod(c, utf_finalize, utf_void__void);
997
998                 if (fi)
999                         if (!(fi->flags & ACC_STATIC))
1000                                 c->finalizer = fi;
1001         }
1002         RT_TIMING_GET_TIME(time_finalizer);
1003
1004         /* final tasks */
1005
1006         linker_compute_subclasses(c);
1007
1008         /* FIXME: this is completely useless now */
1009         RT_TIMING_GET_TIME(time_subclasses);
1010
1011 #if USES_NEW_SUBTYPE
1012         if (!build_display(c))
1013                 return NULL;
1014 #endif
1015
1016         /* revert the linking state and class is linked */
1017
1018         c->state = (c->state & ~CLASS_LINKING) | CLASS_LINKED;
1019
1020         /* check worklist */
1021
1022         /* XXX must this also be done in case of exception? */
1023
1024         while (worklist != NULL) {
1025                 method_worklist *wi = worklist;
1026
1027                 worklist = worklist->next;
1028
1029                 INLINELOG( printf("MUST BE RECOMPILED: "); method_println(wi->m); );
1030                 jit_invalidate_code(wi->m);
1031
1032                 /* XXX put worklist into dump memory? */
1033                 FREE(wi, method_worklist);
1034         }
1035
1036         RT_TIMING_TIME_DIFF(time_start        ,time_resolving    ,RT_TIMING_LINK_RESOLVE);
1037         RT_TIMING_TIME_DIFF(time_resolving    ,time_compute_vftbl,RT_TIMING_LINK_C_VFTBL);
1038         RT_TIMING_TIME_DIFF(time_compute_vftbl,time_abstract     ,RT_TIMING_LINK_ABSTRACT);
1039         RT_TIMING_TIME_DIFF(time_abstract     ,time_compute_iftbl,RT_TIMING_LINK_C_IFTBL);
1040         RT_TIMING_TIME_DIFF(time_compute_iftbl,time_fill_vftbl   ,RT_TIMING_LINK_F_VFTBL);
1041         RT_TIMING_TIME_DIFF(time_fill_vftbl   ,time_offsets      ,RT_TIMING_LINK_OFFSETS);
1042         RT_TIMING_TIME_DIFF(time_offsets      ,time_fill_iftbl   ,RT_TIMING_LINK_F_IFTBL);
1043         RT_TIMING_TIME_DIFF(time_fill_iftbl   ,time_finalizer    ,RT_TIMING_LINK_FINALIZER);
1044         RT_TIMING_TIME_DIFF(time_finalizer    ,time_subclasses   ,RT_TIMING_LINK_SUBCLASS);
1045
1046         /* just return c to show that we didn't had a problem */
1047
1048         return c;
1049 }
1050
1051
1052 /* link_array ******************************************************************
1053
1054    This function is called by link_class to create the arraydescriptor
1055    for an array class.
1056
1057    This function returns NULL if the array cannot be linked because
1058    the component type has not been linked yet.
1059
1060 *******************************************************************************/
1061
1062 static arraydescriptor *link_array(classinfo *c)
1063 {
1064         classinfo       *comp;
1065         s4               namelen;
1066         arraydescriptor *desc;
1067         vftbl_t         *compvftbl;
1068         utf             *u;
1069
1070         comp = NULL;
1071         namelen = c->name->blength;
1072
1073         /* Check the component type */
1074
1075         switch (c->name->text[1]) {
1076         case '[':
1077                 /* c is an array of arrays. */
1078                 u = utf_new(c->name->text + 1, namelen - 1);
1079                 if (!(comp = load_class_from_classloader(u, c->classloader)))
1080                         return NULL;
1081                 break;
1082
1083         case 'L':
1084                 /* c is an array of objects. */
1085                 u = utf_new(c->name->text + 2, namelen - 3);
1086                 if (!(comp = load_class_from_classloader(u, c->classloader)))
1087                         return NULL;
1088                 break;
1089         }
1090
1091         /* If the component type has not been linked, link it now */
1092
1093         assert(!comp || (comp->state & CLASS_LOADED));
1094
1095         if (comp && !(comp->state & CLASS_LINKED))
1096                 if (!link_class(comp))
1097                         return NULL;
1098
1099         /* Allocate the arraydescriptor */
1100
1101         desc = NEW(arraydescriptor);
1102
1103         if (comp) {
1104                 /* c is an array of references */
1105                 desc->arraytype = ARRAYTYPE_OBJECT;
1106                 desc->componentsize = sizeof(void*);
1107                 desc->dataoffset = OFFSET(java_objectarray_t, data);
1108                 
1109                 compvftbl = comp->vftbl;
1110
1111                 if (!compvftbl) {
1112                         log_text("Component class has no vftbl");
1113                         assert(0);
1114                 }
1115
1116                 desc->componentvftbl = compvftbl;
1117                 
1118                 if (compvftbl->arraydesc) {
1119                         desc->elementvftbl = compvftbl->arraydesc->elementvftbl;
1120
1121                         if (compvftbl->arraydesc->dimension >= 255) {
1122                                 exceptions_throw_illegalargumentexception();
1123                                 return NULL;
1124                         }
1125
1126                         desc->dimension = compvftbl->arraydesc->dimension + 1;
1127                         desc->elementtype = compvftbl->arraydesc->elementtype;
1128
1129                 } else {
1130                         desc->elementvftbl = compvftbl;
1131                         desc->dimension = 1;
1132                         desc->elementtype = ARRAYTYPE_OBJECT;
1133                 }
1134
1135         } else {
1136                 /* c is an array of a primitive type */
1137                 switch (c->name->text[1]) {
1138                 case 'Z':
1139                         desc->arraytype = ARRAYTYPE_BOOLEAN;
1140                         desc->dataoffset = OFFSET(java_booleanarray_t,data);
1141                         desc->componentsize = sizeof(u1);
1142                         break;
1143
1144                 case 'B':
1145                         desc->arraytype = ARRAYTYPE_BYTE;
1146                         desc->dataoffset = OFFSET(java_bytearray_t,data);
1147                         desc->componentsize = sizeof(u1);
1148                         break;
1149
1150                 case 'C':
1151                         desc->arraytype = ARRAYTYPE_CHAR;
1152                         desc->dataoffset = OFFSET(java_chararray_t,data);
1153                         desc->componentsize = sizeof(u2);
1154                         break;
1155
1156                 case 'D':
1157                         desc->arraytype = ARRAYTYPE_DOUBLE;
1158                         desc->dataoffset = OFFSET(java_doublearray_t,data);
1159                         desc->componentsize = sizeof(double);
1160                         break;
1161
1162                 case 'F':
1163                         desc->arraytype = ARRAYTYPE_FLOAT;
1164                         desc->dataoffset = OFFSET(java_floatarray_t,data);
1165                         desc->componentsize = sizeof(float);
1166                         break;
1167
1168                 case 'I':
1169                         desc->arraytype = ARRAYTYPE_INT;
1170                         desc->dataoffset = OFFSET(java_intarray_t,data);
1171                         desc->componentsize = sizeof(s4);
1172                         break;
1173
1174                 case 'J':
1175                         desc->arraytype = ARRAYTYPE_LONG;
1176                         desc->dataoffset = OFFSET(java_longarray_t,data);
1177                         desc->componentsize = sizeof(s8);
1178                         break;
1179
1180                 case 'S':
1181                         desc->arraytype = ARRAYTYPE_SHORT;
1182                         desc->dataoffset = OFFSET(java_shortarray_t,data);
1183                         desc->componentsize = sizeof(s2);
1184                         break;
1185
1186                 default:
1187                         exceptions_throw_noclassdeffounderror(c->name);
1188                         return NULL;
1189                 }
1190                 
1191                 desc->componentvftbl = NULL;
1192                 desc->elementvftbl = NULL;
1193                 desc->dimension = 1;
1194                 desc->elementtype = desc->arraytype;
1195         }
1196
1197         return desc;
1198 }
1199
1200 /* linker_create_string_later **************************************************
1201
1202    A hack so we can initialize java.lang.String objects during initialization.
1203
1204 *******************************************************************************/
1205 void linker_create_string_later(java_object_t **a, utf *u)
1206 {
1207         deferred_strings.push_back(std::make_pair(a, u));
1208 }
1209
1210 void linker_initialize_deferred_strings()
1211 {
1212         deferred_strings_vec_t::const_iterator it = deferred_strings.begin();
1213         for (; it != deferred_strings.end(); ++it)
1214                 *it->first = literalstring_new(it->second);
1215         deferred_strings.clear();
1216 }
1217
1218
1219 /* linker_compute_subclasses ***************************************************
1220
1221    XXX
1222
1223    ATTENTION: DO NOT REMOVE ANY OF THE LOCKING MECHANISMS BELOW:
1224    This function needs to take the class renumber lock and stop the
1225    world during class renumbering. The lock is used in C code which
1226    is not that performance critical. Whereas JIT code uses critical
1227    sections to atomically access the class values.
1228
1229 *******************************************************************************/
1230
1231 static void linker_compute_subclasses(classinfo *c)
1232 {
1233
1234         LOCK_CLASSRENUMBER_LOCK;
1235
1236         if (!(c->flags & ACC_INTERFACE)) {
1237                 c->nextsub = NULL;
1238                 c->sub     = NULL;
1239 #if USES_NEW_SUBTYPE
1240                 c->vftbl->baseval = 1; /* so it does not look like an interface */
1241 #endif
1242         }
1243
1244         if (!(c->flags & ACC_INTERFACE) && (c->super != NULL)) {
1245                 c->nextsub    = c->super->sub;
1246                 c->super->sub = c;
1247         }
1248
1249         classvalue = 0;
1250
1251 #if !USES_NEW_SUBTYPE
1252         /* compute class values */
1253
1254         linker_compute_class_values(class_java_lang_Object);
1255 #endif
1256
1257         UNLOCK_CLASSRENUMBER_LOCK;
1258
1259 }
1260
1261
1262 /* linker_compute_class_values *************************************************
1263
1264    XXX
1265
1266 *******************************************************************************/
1267
1268 static void linker_compute_class_values(classinfo *c)
1269 {
1270         classinfo *subs;
1271
1272         c->vftbl->baseval = ++classvalue;
1273
1274         subs = c->sub;
1275
1276         while (subs) {
1277                 linker_compute_class_values(subs);
1278
1279                 subs = subs->nextsub;
1280         }
1281
1282         c->vftbl->diffval = classvalue - c->vftbl->baseval;
1283 }
1284
1285
1286 /* linker_addinterface *********************************************************
1287
1288    Is needed by link_class for adding a VTBL to a class. All
1289    interfaces implemented by ic are added as well.
1290
1291    RETURN VALUE:
1292       true.........everything ok
1293           false........an exception has been thrown
1294
1295 *******************************************************************************/
1296
1297 static bool linker_addinterface(classinfo *c, classinfo *ic)
1298 {
1299         s4          j, k;
1300         vftbl_t    *v;
1301         s4          i;
1302         classinfo  *sc;
1303         methodinfo *m;
1304
1305         v = c->vftbl;
1306         i = ic->index;
1307
1308         if (i >= v->interfacetablelength)
1309                 vm_abort("Internal error: interfacetable overflow");
1310
1311         /* if this interface has already been added, return immediately */
1312
1313         if (v->interfacetable[-i] != NULL)
1314                 return true;
1315
1316         if (ic->methodscount == 0) {  /* fake entry needed for subtype test */
1317                 v->interfacevftbllength[i] = 1;
1318                 v->interfacetable[-i]      = MNEW(methodptr, 1);
1319                 v->interfacetable[-i][0]   = NULL;
1320         }
1321         else {
1322                 v->interfacevftbllength[i] = ic->methodscount;
1323                 v->interfacetable[-i]      = MNEW(methodptr, ic->methodscount);
1324
1325 #if defined(ENABLE_STATISTICS)
1326                 if (opt_stat)
1327                         count_vftbl_len += sizeof(methodptr) *
1328                                 (ic->methodscount + (ic->methodscount == 0));
1329 #endif
1330
1331                 for (j = 0; j < ic->methodscount; j++) {
1332                         for (sc = c; sc != NULL; sc = sc->super) {
1333                                 for (k = 0; k < sc->methodscount; k++) {
1334                                         m = &(sc->methods[k]);
1335
1336                                         if (method_canoverwrite(m, &(ic->methods[j]))) {
1337                                                 /* method m overwrites the (abstract) method */
1338 #if defined(ENABLE_VERIFIER)
1339                                                 /* Add loading constraints (for the more
1340                                                    general types of the method
1341                                                    ic->methods[j]).  */
1342                                                 if (!classcache_add_constraints_for_params(
1343                                                                         c->classloader, ic->classloader,
1344                                                                         &(ic->methods[j])))
1345                                                 {
1346                                                         return false;
1347                                                 }
1348 #endif
1349
1350                                                 /* XXX taken from gcj */
1351                                                 /* check for ACC_STATIC: IncompatibleClassChangeError */
1352
1353                                                 /* check for !ACC_PUBLIC: IllegalAccessError */
1354
1355                                                 /* check for ACC_ABSTRACT: AbstracMethodError,
1356                                                    not sure about that one */
1357
1358                                                 v->interfacetable[-i][j] = v->table[m->vftblindex];
1359                                                 goto foundmethod;
1360                                         }
1361                                 }
1362                         }
1363
1364                         /* If no method was found, insert the AbstractMethodError
1365                            stub. */
1366
1367 #if defined(ENABLE_JIT)
1368 # if defined(ENABLE_INTRP)
1369                         if (opt_intrp)
1370                                 v->interfacetable[-i][j] =
1371                                         (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
1372                         else
1373 # endif
1374                                 v->interfacetable[-i][j] =
1375                                         (methodptr) (ptrint) &asm_abstractmethoderror;
1376 #else
1377                         v->interfacetable[-i][j] =
1378                                 (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
1379 #endif
1380
1381                 foundmethod:
1382                         ;
1383                 }
1384         }
1385
1386         /* add superinterfaces of this interface */
1387
1388         for (j = 0; j < ic->interfacescount; j++)
1389                 if (!linker_addinterface(c, ic->interfaces[j]))
1390                         return false;
1391
1392         /* everything ok */
1393
1394         return true;
1395 }
1396
1397
1398 /* class_highestinterface ******************************************************
1399
1400    Used by the function link_class to determine the amount of memory
1401    needed for the interface table.
1402
1403 *******************************************************************************/
1404
1405 static s4 class_highestinterface(classinfo *c)
1406 {
1407         s4 h;
1408         s4 h2;
1409         s4 i;
1410         
1411     /* check for ACC_INTERFACE bit already done in link_class_intern */
1412
1413     h = c->index;
1414
1415         for (i = 0; i < c->interfacescount; i++) {
1416                 h2 = class_highestinterface(c->interfaces[i]);
1417
1418                 if (h2 > h)
1419                         h = h2;
1420         }
1421
1422         return h;
1423 }
1424
1425 #if defined(__cplusplus)
1426 }
1427 #endif
1428
1429 /*
1430  * These are local overrides for various environment variables in Emacs.
1431  * Please do not remove this and leave it at the end of the file, where
1432  * Emacs will automagically detect them.
1433  * ---------------------------------------------------------------------
1434  * Local variables:
1435  * mode: c++
1436  * indent-tabs-mode: t
1437  * c-basic-offset: 4
1438  * tab-width: 4
1439  * End:
1440  * vim:noexpandtab:sw=4:ts=4:
1441  */