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