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