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