* src/vmcore/options.h, src/vmcore/options.c, src/vmcore/method.c,
[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 7450 2007-03-04 19:13:29Z 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 (!resolve_classref_or_classinfo(NULL, c->interfaces[i], resolveEager,
602                                                                                    true, false, &tc))
603                         return NULL;
604
605                 c->interfaces[i].cls = tc;
606                 
607                 /* detect circularity */
608
609                 if (tc == c) {
610                         exceptions_throw_classcircularityerror(c);
611                         return NULL;
612                 }
613
614                 assert(tc->state & CLASS_LOADED);
615
616                 if (!(tc->flags & ACC_INTERFACE)) {
617                         exceptions_throw_incompatibleclasschangeerror(tc,
618                                                                                                                   "Implementing class");
619                         return NULL;
620                 }
621
622                 if (!(tc->state & CLASS_LINKED))
623                         if (!link_class(tc))
624                                 return NULL;
625         }
626         
627         /* check super class */
628
629         super = NULL;
630
631         if (c->super.any == NULL) {                     /* class java.lang.Object */
632                 c->index = 0;
633                 c->instancesize = sizeof(java_objectheader);
634                 
635                 vftbllength = supervftbllength = 0;
636
637                 c->finalizer = NULL;
638
639         } else {
640                 /* resolve super class */
641
642                 if (!resolve_classref_or_classinfo(NULL, c->super, resolveEager, true, false,
643                                                                                    &super))
644                         return NULL;
645                 c->super.cls = super;
646                 
647                 /* detect circularity */
648
649                 if (super == c) {
650                         exceptions_throw_classcircularityerror(c);
651                         return NULL;
652                 }
653
654                 assert(super->state & CLASS_LOADED);
655
656                 if (super->flags & ACC_INTERFACE) {
657                         /* java.lang.IncompatibleClassChangeError: class a has interface java.lang.Cloneable as super class */
658                         log_text("Interface specified as super class");
659                         assert(0);
660                 }
661
662                 /* Don't allow extending final classes */
663
664                 if (super->flags & ACC_FINAL) {
665                         exceptions_throw_verifyerror(NULL,
666                                                                                  "Cannot inherit from final class");
667                         return NULL;
668                 }
669
670                 /* link the superclass if necessary */
671                 
672                 if (!(super->state & CLASS_LINKED))
673                         if (!link_class(super))
674                                 return NULL;
675
676                 /* OR the ACC_CLASS_HAS_POINTERS flag */
677
678                 c->flags |= (super->flags & ACC_CLASS_HAS_POINTERS);
679
680                 /* handle array classes */
681
682                 if (c->name->text[0] == '[')
683                         if (!(arraydesc = link_array(c)))
684                                 return NULL;
685
686                 if (c->flags & ACC_INTERFACE)
687                         c->index = interfaceindex++;
688                 else
689                         c->index = super->index + 1;
690                 
691                 c->instancesize = super->instancesize;
692
693                 vftbllength = supervftbllength = super->vftbl->vftbllength;
694                 
695                 c->finalizer = super->finalizer;
696         }
697         RT_TIMING_GET_TIME(time_resolving);
698
699
700         /* compute vftbl length */
701
702         for (i = 0; i < c->methodscount; i++) {
703                 methodinfo *m = &(c->methods[i]);
704
705                 if (!(m->flags & ACC_STATIC)) { /* is instance method */
706                         tc = super;
707
708                         while (tc) {
709                                 s4 j;
710
711                                 for (j = 0; j < tc->methodscount; j++) {
712                                         if (method_canoverwrite(m, &(tc->methods[j]))) {
713                                                 if (tc->methods[j].flags & ACC_PRIVATE)
714                                                         goto notfoundvftblindex;
715
716                                                 /* package-private methods in other packages */
717                                                 /* must not be overridden                    */
718                                                 /* (see Java Language Specification 8.4.8.1) */
719                                                 if ( !(tc->methods[j].flags & (ACC_PUBLIC | ACC_PROTECTED)) 
720                                                          && !SAME_PACKAGE(c,tc) ) 
721                                                 {
722                                                     goto notfoundvftblindex;
723                                                 }
724
725                                                 if (!linker_overwrite_method(&(tc->methods[j]), m, &worklist))
726                                                         return NULL;
727
728                                                 goto foundvftblindex;
729                                         }
730                                 }
731
732                                 tc = tc->super.cls;
733                         }
734
735                 notfoundvftblindex:
736                         m->vftblindex = (vftbllength++);
737                 foundvftblindex:
738                         ;
739                 }
740         }
741         RT_TIMING_GET_TIME(time_compute_vftbl);
742
743
744         /* Check all interfaces of an abstract class (maybe be an
745            interface too) for unimplemented methods.  Such methods are
746            called miranda-methods and are marked with the ACC_MIRANDA
747            flag.  VMClass.getDeclaredMethods does not return such
748            methods. */
749
750         if (c->flags & ACC_ABSTRACT) {
751                 classinfo  *ic;
752                 methodinfo *im;
753                 s4 abstractmethodscount;
754                 s4 j;
755                 s4 k;
756
757                 abstractmethodscount = 0;
758
759                 /* check all interfaces of the abstract class */
760
761                 for (i = 0; i < c->interfacescount; i++) {
762                         ic = c->interfaces[i].cls;
763
764                         for (j = 0; j < ic->methodscount; j++) {
765                                 im = &(ic->methods[j]);
766
767                                 /* skip `<clinit>' and `<init>' */
768
769                                 if ((im->name == utf_clinit) || (im->name == utf_init))
770                                         continue;
771
772                                 for (tc = c; tc != NULL; tc = tc->super.cls) {
773                                         for (k = 0; k < tc->methodscount; k++) {
774                                                 if (method_canoverwrite(im, &(tc->methods[k])))
775                                                         goto noabstractmethod;
776                                         }
777                                 }
778
779                                 abstractmethodscount++;
780
781                         noabstractmethod:
782                                 ;
783                         }
784                 }
785
786                 if (abstractmethodscount > 0) {
787                         methodinfo *am;
788
789                         /* reallocate methods memory */
790
791                         c->methods = MREALLOC(c->methods, methodinfo, c->methodscount,
792                                                                   c->methodscount + abstractmethodscount);
793
794                         for (i = 0; i < c->interfacescount; i++) {
795                                 ic = c->interfaces[i].cls;
796
797                                 for (j = 0; j < ic->methodscount; j++) {
798                                         im = &(ic->methods[j]);
799
800                                         /* skip `<clinit>' and `<init>' */
801
802                                         if ((im->name == utf_clinit) || (im->name == utf_init))
803                                                 continue;
804
805                                         for (tc = c; tc != NULL; tc = tc->super.cls) {
806                                                 for (k = 0; k < tc->methodscount; k++) {
807                                                         if (method_canoverwrite(im, &(tc->methods[k])))
808                                                                 goto noabstractmethod2;
809                                                 }
810                                         }
811
812                                         /* Copy the method found into the new c->methods
813                                            array and tag it as miranda-method. */
814
815                                         am = &(c->methods[c->methodscount]);
816                                         c->methodscount++;
817
818                                         MCOPY(am, im, methodinfo, 1);
819
820                                         am->vftblindex  = (vftbllength++);
821                                         am->class       = c;
822                                         am->flags      |= ACC_MIRANDA;
823
824                                 noabstractmethod2:
825                                         ;
826                                 }
827                         }
828                 }
829         }
830         RT_TIMING_GET_TIME(time_abstract);
831
832
833 #if defined(ENABLE_STATISTICS)
834         if (opt_stat)
835                 count_vftbl_len +=
836                         sizeof(vftbl_t) + (sizeof(methodptr) * (vftbllength - 1));
837 #endif
838
839         /* compute interfacetable length */
840
841         interfacetablelength = 0;
842
843         for (tc = c; tc != NULL; tc = tc->super.cls) {
844                 for (i = 0; i < tc->interfacescount; i++) {
845                         s4 h = class_highestinterface(tc->interfaces[i].cls) + 1;
846
847                         if (h > interfacetablelength)
848                                 interfacetablelength = h;
849                 }
850         }
851         RT_TIMING_GET_TIME(time_compute_iftbl);
852
853         /* allocate virtual function table */
854
855         v = (vftbl_t *) mem_alloc(sizeof(vftbl_t) +
856                                                           sizeof(methodptr) * (vftbllength - 1) +
857                                                           sizeof(methodptr*) * (interfacetablelength - (interfacetablelength > 0)));
858         v = (vftbl_t *) (((methodptr *) v) +
859                                          (interfacetablelength - 1) * (interfacetablelength > 1));
860
861         c->vftbl                = v;
862         v->class                = c;
863         v->vftbllength          = vftbllength;
864         v->interfacetablelength = interfacetablelength;
865         v->arraydesc            = arraydesc;
866
867         /* store interface index in vftbl */
868
869         if (c->flags & ACC_INTERFACE)
870                 v->baseval = -(c->index);
871
872         /* copy virtual function table of super class */
873
874         for (i = 0; i < supervftbllength; i++) 
875                 v->table[i] = super->vftbl->table[i];
876
877         /* Fill the remaining vftbl slots with the AbstractMethodError
878            stub (all after the super class slots, because they are already
879            initialized). */
880
881         for (; i < vftbllength; i++) {
882 #if defined(ENABLE_JIT)
883 # if defined(ENABLE_INTRP)
884                 if (opt_intrp)
885                         v->table[i] = (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
886                 else
887 # endif
888                         v->table[i] = (methodptr) (ptrint) &asm_abstractmethoderror;
889 #else
890                 v->table[i] = (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
891 #endif
892         }
893
894         /* add method stubs into virtual function table */
895
896         for (i = 0; i < c->methodscount; i++) {
897                 methodinfo *m = &(c->methods[i]);
898
899                 assert(m->stubroutine == NULL);
900
901                 /* Don't create a compiler stub for abstract methods as they
902                    throw an AbstractMethodError with the default stub in the
903                    vftbl.  This entry is simply copied by sub-classes. */
904
905                 if (m->flags & ACC_ABSTRACT)
906                         continue;
907
908 #if defined(ENABLE_JIT)
909 # if defined(ENABLE_INTRP)
910                 if (opt_intrp)
911                         m->stubroutine = intrp_createcompilerstub(m);
912                 else
913 #endif
914                         m->stubroutine = createcompilerstub(m);
915 #else
916                 m->stubroutine = intrp_createcompilerstub(m);
917 #endif
918
919                 /* static methods are not in the vftbl */
920
921                 if (m->flags & ACC_STATIC)
922                         continue;
923
924                 /* insert the stubroutine into the vftbl */
925
926                 v->table[m->vftblindex] = (methodptr) (ptrint) m->stubroutine;
927         }
928         RT_TIMING_GET_TIME(time_fill_vftbl);
929
930         /* compute instance size and offset of each field */
931         
932         for (i = 0; i < c->fieldscount; i++) {
933                 s4 dsize;
934                 fieldinfo *f = &(c->fields[i]);
935                 
936                 if (!(f->flags & ACC_STATIC)) {
937                         dsize = descriptor_typesize(f->parseddesc);
938
939 #if defined(__I386__) || defined(__ARM__)
940                         /* On i386 and ARM we align double and s8 fields to
941                            4-bytes.  This matches what GCC does for struct
942                            members. We must do the same as gcc here because the
943                            offsets in native header structs like java_lang_Double
944                            must match the offsets of the Java fields
945                            (eg. java.lang.Double.value).  */
946
947                         c->instancesize = MEMORY_ALIGN(c->instancesize, 4);
948 #else
949                         c->instancesize = MEMORY_ALIGN(c->instancesize, dsize);
950 #endif
951
952                         f->offset = c->instancesize;
953                         c->instancesize += dsize;
954                 }
955         }
956         RT_TIMING_GET_TIME(time_offsets);
957
958         /* initialize interfacetable and interfacevftbllength */
959
960         v->interfacevftbllength = MNEW(s4, interfacetablelength);
961
962 #if defined(ENABLE_STATISTICS)
963         if (opt_stat)
964                 count_vftbl_len += (4 + sizeof(s4)) * v->interfacetablelength;
965 #endif
966
967         for (i = 0; i < interfacetablelength; i++) {
968                 v->interfacevftbllength[i] = 0;
969                 v->interfacetable[-i] = NULL;
970         }
971
972         /* add interfaces */
973
974         for (tc = c; tc != NULL; tc = tc->super.cls)
975                 for (i = 0; i < tc->interfacescount; i++)
976                         if (!linker_addinterface(c, tc->interfaces[i].cls))
977                                 return NULL;
978
979         RT_TIMING_GET_TIME(time_fill_iftbl);
980
981         /* add finalizer method (not for java.lang.Object) */
982
983         if (super) {
984                 methodinfo *fi;
985
986                 fi = class_findmethod(c, utf_finalize, utf_void__void);
987
988                 if (fi)
989                         if (!(fi->flags & ACC_STATIC))
990                                 c->finalizer = fi;
991         }
992         RT_TIMING_GET_TIME(time_finalizer);
993
994         /* final tasks */
995
996         linker_compute_subclasses(c);
997
998         RT_TIMING_GET_TIME(time_subclasses);
999
1000         /* revert the linking state and class is linked */
1001
1002         c->state = (c->state & ~CLASS_LINKING) | CLASS_LINKED;
1003
1004         /* check worklist */
1005
1006         /* XXX must this also be done in case of exception? */
1007
1008         while (worklist != NULL) {
1009                 method_worklist *wi = worklist;
1010
1011                 worklist = worklist->next;
1012
1013                 INLINELOG( printf("MUST BE RECOMPILED: "); method_println(wi->m); );
1014                 jit_invalidate_code(wi->m);
1015
1016                 /* XXX put worklist into dump memory? */
1017                 FREE(wi, method_worklist);
1018         }
1019
1020 #if !defined(NDEBUG)
1021         if (linkverbose)
1022                 log_message_class("Linking done class: ", c);
1023 #endif
1024
1025         RT_TIMING_TIME_DIFF(time_start        ,time_resolving    ,RT_TIMING_LINK_RESOLVE);
1026         RT_TIMING_TIME_DIFF(time_resolving    ,time_compute_vftbl,RT_TIMING_LINK_C_VFTBL);
1027         RT_TIMING_TIME_DIFF(time_compute_vftbl,time_abstract     ,RT_TIMING_LINK_ABSTRACT);
1028         RT_TIMING_TIME_DIFF(time_abstract     ,time_compute_iftbl,RT_TIMING_LINK_C_IFTBL);
1029         RT_TIMING_TIME_DIFF(time_compute_iftbl,time_fill_vftbl   ,RT_TIMING_LINK_F_VFTBL);
1030         RT_TIMING_TIME_DIFF(time_fill_vftbl   ,time_offsets      ,RT_TIMING_LINK_OFFSETS);
1031         RT_TIMING_TIME_DIFF(time_offsets      ,time_fill_iftbl   ,RT_TIMING_LINK_F_IFTBL);
1032         RT_TIMING_TIME_DIFF(time_fill_iftbl   ,time_finalizer    ,RT_TIMING_LINK_FINALIZER);
1033         RT_TIMING_TIME_DIFF(time_finalizer    ,time_subclasses   ,RT_TIMING_LINK_SUBCLASS);
1034
1035         /* just return c to show that we didn't had a problem */
1036
1037         return c;
1038 }
1039
1040
1041 /* link_array ******************************************************************
1042
1043    This function is called by link_class to create the arraydescriptor
1044    for an array class.
1045
1046    This function returns NULL if the array cannot be linked because
1047    the component type has not been linked yet.
1048
1049 *******************************************************************************/
1050
1051 static arraydescriptor *link_array(classinfo *c)
1052 {
1053         classinfo       *comp;
1054         s4               namelen;
1055         arraydescriptor *desc;
1056         vftbl_t         *compvftbl;
1057         utf             *u;
1058
1059         comp = NULL;
1060         namelen = c->name->blength;
1061
1062         /* Check the component type */
1063
1064         switch (c->name->text[1]) {
1065         case '[':
1066                 /* c is an array of arrays. */
1067                 u = utf_new(c->name->text + 1, namelen - 1);
1068                 if (!(comp = load_class_from_classloader(u, c->classloader)))
1069                         return NULL;
1070                 break;
1071
1072         case 'L':
1073                 /* c is an array of objects. */
1074                 u = utf_new(c->name->text + 2, namelen - 3);
1075                 if (!(comp = load_class_from_classloader(u, c->classloader)))
1076                         return NULL;
1077                 break;
1078         }
1079
1080         /* If the component type has not been linked, link it now */
1081
1082         assert(!comp || (comp->state & CLASS_LOADED));
1083
1084         if (comp && !(comp->state & CLASS_LINKED))
1085                 if (!link_class(comp))
1086                         return NULL;
1087
1088         /* Allocate the arraydescriptor */
1089
1090         desc = NEW(arraydescriptor);
1091
1092         if (comp) {
1093                 /* c is an array of references */
1094                 desc->arraytype = ARRAYTYPE_OBJECT;
1095                 desc->componentsize = sizeof(void*);
1096                 desc->dataoffset = OFFSET(java_objectarray, data);
1097                 
1098                 compvftbl = comp->vftbl;
1099
1100                 if (!compvftbl) {
1101                         log_text("Component class has no vftbl");
1102                         assert(0);
1103                 }
1104
1105                 desc->componentvftbl = compvftbl;
1106                 
1107                 if (compvftbl->arraydesc) {
1108                         desc->elementvftbl = compvftbl->arraydesc->elementvftbl;
1109
1110                         if (compvftbl->arraydesc->dimension >= 255) {
1111                                 log_text("Creating array of dimension >255");
1112                                 assert(0);
1113                         }
1114
1115                         desc->dimension = compvftbl->arraydesc->dimension + 1;
1116                         desc->elementtype = compvftbl->arraydesc->elementtype;
1117
1118                 } else {
1119                         desc->elementvftbl = compvftbl;
1120                         desc->dimension = 1;
1121                         desc->elementtype = ARRAYTYPE_OBJECT;
1122                 }
1123
1124         } else {
1125                 /* c is an array of a primitive type */
1126                 switch (c->name->text[1]) {
1127                 case 'Z':
1128                         desc->arraytype = ARRAYTYPE_BOOLEAN;
1129                         desc->dataoffset = OFFSET(java_booleanarray,data);
1130                         desc->componentsize = sizeof(u1);
1131                         break;
1132
1133                 case 'B':
1134                         desc->arraytype = ARRAYTYPE_BYTE;
1135                         desc->dataoffset = OFFSET(java_bytearray,data);
1136                         desc->componentsize = sizeof(u1);
1137                         break;
1138
1139                 case 'C':
1140                         desc->arraytype = ARRAYTYPE_CHAR;
1141                         desc->dataoffset = OFFSET(java_chararray,data);
1142                         desc->componentsize = sizeof(u2);
1143                         break;
1144
1145                 case 'D':
1146                         desc->arraytype = ARRAYTYPE_DOUBLE;
1147                         desc->dataoffset = OFFSET(java_doublearray,data);
1148                         desc->componentsize = sizeof(double);
1149                         break;
1150
1151                 case 'F':
1152                         desc->arraytype = ARRAYTYPE_FLOAT;
1153                         desc->dataoffset = OFFSET(java_floatarray,data);
1154                         desc->componentsize = sizeof(float);
1155                         break;
1156
1157                 case 'I':
1158                         desc->arraytype = ARRAYTYPE_INT;
1159                         desc->dataoffset = OFFSET(java_intarray,data);
1160                         desc->componentsize = sizeof(s4);
1161                         break;
1162
1163                 case 'J':
1164                         desc->arraytype = ARRAYTYPE_LONG;
1165                         desc->dataoffset = OFFSET(java_longarray,data);
1166                         desc->componentsize = sizeof(s8);
1167                         break;
1168
1169                 case 'S':
1170                         desc->arraytype = ARRAYTYPE_SHORT;
1171                         desc->dataoffset = OFFSET(java_shortarray,data);
1172                         desc->componentsize = sizeof(s2);
1173                         break;
1174
1175                 default:
1176                         exceptions_throw_noclassdeffounderror(c->name);
1177                         return NULL;
1178                 }
1179                 
1180                 desc->componentvftbl = NULL;
1181                 desc->elementvftbl = NULL;
1182                 desc->dimension = 1;
1183                 desc->elementtype = desc->arraytype;
1184         }
1185
1186         return desc;
1187 }
1188
1189
1190 /* linker_compute_subclasses ***************************************************
1191
1192    XXX
1193
1194 *******************************************************************************/
1195
1196 static void linker_compute_subclasses(classinfo *c)
1197 {
1198 #if defined(ENABLE_THREADS)
1199         compiler_lock();
1200 #endif
1201
1202         if (!(c->flags & ACC_INTERFACE)) {
1203                 c->nextsub = 0;
1204                 c->sub = 0;
1205         }
1206
1207         if (!(c->flags & ACC_INTERFACE) && (c->super.any != NULL)) {
1208                 c->nextsub = c->super.cls->sub;
1209                 c->super.cls->sub = c;
1210         }
1211
1212         classvalue = 0;
1213
1214         /* compute class values */
1215
1216         linker_compute_class_values(class_java_lang_Object);
1217
1218 #if defined(ENABLE_THREADS)
1219         compiler_unlock();
1220 #endif
1221 }
1222
1223
1224 /* linker_compute_class_values *************************************************
1225
1226    XXX
1227
1228 *******************************************************************************/
1229
1230 static void linker_compute_class_values(classinfo *c)
1231 {
1232         classinfo *subs;
1233
1234         c->vftbl->baseval = ++classvalue;
1235
1236         subs = c->sub;
1237
1238         while (subs) {
1239                 linker_compute_class_values(subs);
1240
1241                 subs = subs->nextsub;
1242         }
1243
1244         c->vftbl->diffval = classvalue - c->vftbl->baseval;
1245 }
1246
1247
1248 /* linker_addinterface *********************************************************
1249
1250    Is needed by link_class for adding a VTBL to a class. All
1251    interfaces implemented by ic are added as well.
1252
1253    RETURN VALUE:
1254       true.........everything ok
1255           false........an exception has been thrown
1256
1257 *******************************************************************************/
1258
1259 static bool linker_addinterface(classinfo *c, classinfo *ic)
1260 {
1261         s4          j, k;
1262         vftbl_t    *v;
1263         s4          i;
1264         classinfo  *sc;
1265         methodinfo *m;
1266
1267         v = c->vftbl;
1268         i = ic->index;
1269
1270         if (i >= v->interfacetablelength)
1271                 vm_abort("Internal error: interfacetable overflow");
1272
1273         /* if this interface has already been added, return immediately */
1274
1275         if (v->interfacetable[-i] != NULL)
1276                 return true;
1277
1278         if (ic->methodscount == 0) {  /* fake entry needed for subtype test */
1279                 v->interfacevftbllength[i] = 1;
1280                 v->interfacetable[-i]      = MNEW(methodptr, 1);
1281                 v->interfacetable[-i][0]   = NULL;
1282         }
1283         else {
1284                 v->interfacevftbllength[i] = ic->methodscount;
1285                 v->interfacetable[-i]      = MNEW(methodptr, ic->methodscount);
1286
1287 #if defined(ENABLE_STATISTICS)
1288                 if (opt_stat)
1289                         count_vftbl_len += sizeof(methodptr) *
1290                                 (ic->methodscount + (ic->methodscount == 0));
1291 #endif
1292
1293                 for (j = 0; j < ic->methodscount; j++) {
1294                         for (sc = c; sc != NULL; sc = sc->super.cls) {
1295                                 for (k = 0; k < sc->methodscount; k++) {
1296                                         m = &(sc->methods[k]);
1297
1298                                         if (method_canoverwrite(m, &(ic->methods[j]))) {
1299                                                 /* method m overwrites the (abstract) method */
1300 #if defined(ENABLE_VERIFIER)
1301                                                 /* Add loading constraints (for the more
1302                                                    general types of the method
1303                                                    ic->methods[j]).  */
1304                                                 if (!classcache_add_constraints_for_params(
1305                                                                         c->classloader, ic->classloader,
1306                                                                         &(ic->methods[j])))
1307                                                 {
1308                                                         return false;
1309                                                 }
1310 #endif
1311
1312                                                 /* XXX taken from gcj */
1313                                                 /* check for ACC_STATIC: IncompatibleClassChangeError */
1314
1315                                                 /* check for !ACC_PUBLIC: IllegalAccessError */
1316
1317                                                 /* check for ACC_ABSTRACT: AbstracMethodError,
1318                                                    not sure about that one */
1319
1320                                                 v->interfacetable[-i][j] = v->table[m->vftblindex];
1321                                                 goto foundmethod;
1322                                         }
1323                                 }
1324                         }
1325
1326                         /* If no method was found, insert the AbstractMethodError
1327                            stub. */
1328
1329 #if defined(ENABLE_JIT)
1330 # if defined(ENABLE_INTRP)
1331                         if (opt_intrp)
1332                                 v->interfacetable[-i][j] =
1333                                         (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
1334                         else
1335 # endif
1336                                 v->interfacetable[-i][j] =
1337                                         (methodptr) (ptrint) &asm_abstractmethoderror;
1338 #else
1339                         v->interfacetable[-i][j] =
1340                                 (methodptr) (ptrint) &intrp_asm_abstractmethoderror;
1341 #endif
1342
1343                 foundmethod:
1344                         ;
1345                 }
1346         }
1347
1348         /* add superinterfaces of this interface */
1349
1350         for (j = 0; j < ic->interfacescount; j++)
1351                 if (!linker_addinterface(c, ic->interfaces[j].cls))
1352                         return false;
1353
1354         /* everything ok */
1355
1356         return true;
1357 }
1358
1359
1360 /* class_highestinterface ******************************************************
1361
1362    Used by the function link_class to determine the amount of memory
1363    needed for the interface table.
1364
1365 *******************************************************************************/
1366
1367 static s4 class_highestinterface(classinfo *c)
1368 {
1369         s4 h;
1370         s4 h2;
1371         s4 i;
1372         
1373     /* check for ACC_INTERFACE bit already done in link_class_intern */
1374
1375     h = c->index;
1376
1377         for (i = 0; i < c->interfacescount; i++) {
1378                 h2 = class_highestinterface(c->interfaces[i].cls);
1379
1380                 if (h2 > h)
1381                         h = h2;
1382         }
1383
1384         return h;
1385 }
1386
1387
1388 /*
1389  * These are local overrides for various environment variables in Emacs.
1390  * Please do not remove this and leave it at the end of the file, where
1391  * Emacs will automagically detect them.
1392  * ---------------------------------------------------------------------
1393  * Local variables:
1394  * mode: c
1395  * indent-tabs-mode: t
1396  * c-basic-offset: 4
1397  * tab-width: 4
1398  * End:
1399  * vim:noexpandtab:sw=4:ts=4:
1400  */