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