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