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