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