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