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