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