* src/vm/utf8.c (utf_java_lang_AbstractMethodError): 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 5053 2006-06-28 19:11:20Z 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 #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                 /* Methods in ABSTRACT classes from interfaces maybe already
811                    have a stubroutine. */
812
813                 if (m->stubroutine == NULL) {
814 #if defined(ENABLE_JIT)
815 # if defined(ENABLE_INTRP)
816                         if (opt_intrp)
817                                 m->stubroutine = intrp_createcompilerstub(m);
818                         else
819 #endif
820                                 m->stubroutine = createcompilerstub(m);
821 #else
822                         m->stubroutine = intrp_createcompilerstub(m);
823 #endif
824                 }
825
826                 if (!(m->flags & ACC_STATIC))
827                         v->table[m->vftblindex] = (methodptr) (ptrint) m->stubroutine;
828         }
829         RT_TIMING_GET_TIME(time_fill_vftbl);
830
831         /* compute instance size and offset of each field */
832         
833         for (i = 0; i < c->fieldscount; i++) {
834                 s4 dsize;
835                 fieldinfo *f = &(c->fields[i]);
836                 
837                 if (!(f->flags & ACC_STATIC)) {
838                         dsize = descriptor_typesize(f->parseddesc);
839
840                         /* On i386 we only align to 4 bytes even for double and s8.    */
841                         /* This matches what gcc does for struct members. We must      */
842                         /* do the same as gcc here because the offsets in native       */
843                         /* header structs like java_lang_Double must match the offsets */
844                         /* of the Java fields (eg. java.lang.Double.value).            */
845 #if defined(__I386__)
846                         c->instancesize = ALIGN(c->instancesize, 4);
847 #else
848                         c->instancesize = ALIGN(c->instancesize, dsize);
849 #endif
850
851                         f->offset = c->instancesize;
852                         c->instancesize += dsize;
853                 }
854         }
855         RT_TIMING_GET_TIME(time_offsets);
856
857         /* initialize interfacetable and interfacevftbllength */
858
859         v->interfacevftbllength = MNEW(s4, interfacetablelength);
860
861 #if defined(ENABLE_STATISTICS)
862         if (opt_stat)
863                 count_vftbl_len += (4 + sizeof(s4)) * v->interfacetablelength;
864 #endif
865
866         for (i = 0; i < interfacetablelength; i++) {
867                 v->interfacevftbllength[i] = 0;
868                 v->interfacetable[-i] = NULL;
869         }
870
871         /* add interfaces */
872
873         for (tc = c; tc != NULL; tc = tc->super.cls)
874                 for (i = 0; i < tc->interfacescount; i++)
875                         if (!linker_addinterface(c, tc->interfaces[i].cls))
876                                 return NULL;
877
878         RT_TIMING_GET_TIME(time_fill_iftbl);
879
880         /* add finalizer method (not for java.lang.Object) */
881
882         if (super) {
883                 methodinfo *fi;
884
885                 fi = class_findmethod(c, utf_finalize, utf_void__void);
886
887                 if (fi)
888                         if (!(fi->flags & ACC_STATIC))
889                                 c->finalizer = fi;
890         }
891         RT_TIMING_GET_TIME(time_finalizer);
892
893         /* resolve exception class references */
894
895         for (i = 0; i < c->methodscount; i++) {
896                 methodinfo *m = &(c->methods[i]);
897
898                 for (j = 0; j < m->exceptiontablelength; j++) {
899                         if (!m->exceptiontable[j].catchtype.any)
900                                 continue;
901                         if (!resolve_classref_or_classinfo(NULL,
902                                                                                            m->exceptiontable[j].catchtype,
903                                                                                            resolveEager, true, false,
904                                                                                            &(m->exceptiontable[j].catchtype.cls)))
905                                 return NULL;
906                 }
907         }
908         RT_TIMING_GET_TIME(time_exceptions);
909         
910         /* final tasks */
911
912         linker_compute_subclasses(c);
913
914         RT_TIMING_GET_TIME(time_subclasses);
915
916         /* revert the linking state and class is linked */
917
918         c->state = (c->state & ~CLASS_LINKING) | CLASS_LINKED;
919
920 #if !defined(NDEBUG)
921         if (linkverbose)
922                 log_message_class("Linking done class: ", c);
923 #endif
924
925         RT_TIMING_TIME_DIFF(time_start        ,time_resolving    ,RT_TIMING_LINK_RESOLVE);
926         RT_TIMING_TIME_DIFF(time_resolving    ,time_compute_vftbl,RT_TIMING_LINK_C_VFTBL);
927         RT_TIMING_TIME_DIFF(time_compute_vftbl,time_abstract     ,RT_TIMING_LINK_ABSTRACT);
928         RT_TIMING_TIME_DIFF(time_abstract     ,time_compute_iftbl,RT_TIMING_LINK_C_IFTBL);
929         RT_TIMING_TIME_DIFF(time_compute_iftbl,time_fill_vftbl   ,RT_TIMING_LINK_F_VFTBL);
930         RT_TIMING_TIME_DIFF(time_fill_vftbl   ,time_offsets      ,RT_TIMING_LINK_OFFSETS);
931         RT_TIMING_TIME_DIFF(time_offsets      ,time_fill_iftbl   ,RT_TIMING_LINK_F_IFTBL);
932         RT_TIMING_TIME_DIFF(time_fill_iftbl   ,time_finalizer    ,RT_TIMING_LINK_FINALIZER);
933         RT_TIMING_TIME_DIFF(time_finalizer    ,time_exceptions   ,RT_TIMING_LINK_EXCEPTS);
934         RT_TIMING_TIME_DIFF(time_exceptions   ,time_subclasses   ,RT_TIMING_LINK_SUBCLASS);
935
936         /* just return c to show that we didn't had a problem */
937
938         return c;
939 }
940
941
942 /* link_array ******************************************************************
943
944    This function is called by link_class to create the arraydescriptor
945    for an array class.
946
947    This function returns NULL if the array cannot be linked because
948    the component type has not been linked yet.
949
950 *******************************************************************************/
951
952 static arraydescriptor *link_array(classinfo *c)
953 {
954         classinfo       *comp;
955         s4               namelen;
956         arraydescriptor *desc;
957         vftbl_t         *compvftbl;
958         utf             *u;
959
960         comp = NULL;
961         namelen = c->name->blength;
962
963         /* Check the component type */
964
965         switch (c->name->text[1]) {
966         case '[':
967                 /* c is an array of arrays. */
968                 u = utf_new(c->name->text + 1, namelen - 1);
969                 if (!(comp = load_class_from_classloader(u, c->classloader)))
970                         return NULL;
971                 break;
972
973         case 'L':
974                 /* c is an array of objects. */
975                 u = utf_new(c->name->text + 2, namelen - 3);
976                 if (!(comp = load_class_from_classloader(u, c->classloader)))
977                         return NULL;
978                 break;
979         }
980
981         /* If the component type has not been linked, link it now */
982
983         assert(!comp || (comp->state & CLASS_LOADED));
984
985         if (comp && !(comp->state & CLASS_LINKED))
986                 if (!link_class(comp))
987                         return NULL;
988
989         /* Allocate the arraydescriptor */
990
991         desc = NEW(arraydescriptor);
992
993         if (comp) {
994                 /* c is an array of references */
995                 desc->arraytype = ARRAYTYPE_OBJECT;
996                 desc->componentsize = sizeof(void*);
997                 desc->dataoffset = OFFSET(java_objectarray, data);
998                 
999                 compvftbl = comp->vftbl;
1000
1001                 if (!compvftbl) {
1002                         log_text("Component class has no vftbl");
1003                         assert(0);
1004                 }
1005
1006                 desc->componentvftbl = compvftbl;
1007                 
1008                 if (compvftbl->arraydesc) {
1009                         desc->elementvftbl = compvftbl->arraydesc->elementvftbl;
1010
1011                         if (compvftbl->arraydesc->dimension >= 255) {
1012                                 log_text("Creating array of dimension >255");
1013                                 assert(0);
1014                         }
1015
1016                         desc->dimension = compvftbl->arraydesc->dimension + 1;
1017                         desc->elementtype = compvftbl->arraydesc->elementtype;
1018
1019                 } else {
1020                         desc->elementvftbl = compvftbl;
1021                         desc->dimension = 1;
1022                         desc->elementtype = ARRAYTYPE_OBJECT;
1023                 }
1024
1025         } else {
1026                 /* c is an array of a primitive type */
1027                 switch (c->name->text[1]) {
1028                 case 'Z':
1029                         desc->arraytype = ARRAYTYPE_BOOLEAN;
1030                         desc->dataoffset = OFFSET(java_booleanarray,data);
1031                         desc->componentsize = sizeof(u1);
1032                         break;
1033
1034                 case 'B':
1035                         desc->arraytype = ARRAYTYPE_BYTE;
1036                         desc->dataoffset = OFFSET(java_bytearray,data);
1037                         desc->componentsize = sizeof(u1);
1038                         break;
1039
1040                 case 'C':
1041                         desc->arraytype = ARRAYTYPE_CHAR;
1042                         desc->dataoffset = OFFSET(java_chararray,data);
1043                         desc->componentsize = sizeof(u2);
1044                         break;
1045
1046                 case 'D':
1047                         desc->arraytype = ARRAYTYPE_DOUBLE;
1048                         desc->dataoffset = OFFSET(java_doublearray,data);
1049                         desc->componentsize = sizeof(double);
1050                         break;
1051
1052                 case 'F':
1053                         desc->arraytype = ARRAYTYPE_FLOAT;
1054                         desc->dataoffset = OFFSET(java_floatarray,data);
1055                         desc->componentsize = sizeof(float);
1056                         break;
1057
1058                 case 'I':
1059                         desc->arraytype = ARRAYTYPE_INT;
1060                         desc->dataoffset = OFFSET(java_intarray,data);
1061                         desc->componentsize = sizeof(s4);
1062                         break;
1063
1064                 case 'J':
1065                         desc->arraytype = ARRAYTYPE_LONG;
1066                         desc->dataoffset = OFFSET(java_longarray,data);
1067                         desc->componentsize = sizeof(s8);
1068                         break;
1069
1070                 case 'S':
1071                         desc->arraytype = ARRAYTYPE_SHORT;
1072                         desc->dataoffset = OFFSET(java_shortarray,data);
1073                         desc->componentsize = sizeof(s2);
1074                         break;
1075
1076                 default:
1077                         *exceptionptr = new_noclassdeffounderror(c->name);
1078                         return NULL;
1079                 }
1080                 
1081                 desc->componentvftbl = NULL;
1082                 desc->elementvftbl = NULL;
1083                 desc->dimension = 1;
1084                 desc->elementtype = desc->arraytype;
1085         }
1086
1087         return desc;
1088 }
1089
1090
1091 /* linker_compute_subclasses ***************************************************
1092
1093    XXX
1094
1095 *******************************************************************************/
1096
1097 static void linker_compute_subclasses(classinfo *c)
1098 {
1099 #if defined(ENABLE_THREADS)
1100         compiler_lock();
1101 #endif
1102
1103         if (!(c->flags & ACC_INTERFACE)) {
1104                 c->nextsub = 0;
1105                 c->sub = 0;
1106         }
1107
1108         if (!(c->flags & ACC_INTERFACE) && (c->super.any != NULL)) {
1109                 c->nextsub = c->super.cls->sub;
1110                 c->super.cls->sub = c;
1111         }
1112
1113         classvalue = 0;
1114
1115         /* compute class values */
1116
1117         linker_compute_class_values(class_java_lang_Object);
1118
1119 #if defined(ENABLE_THREADS)
1120         compiler_unlock();
1121 #endif
1122 }
1123
1124
1125 /* linker_compute_class_values *************************************************
1126
1127    XXX
1128
1129 *******************************************************************************/
1130
1131 static void linker_compute_class_values(classinfo *c)
1132 {
1133         classinfo *subs;
1134
1135         c->vftbl->baseval = ++classvalue;
1136
1137         subs = c->sub;
1138
1139         while (subs) {
1140                 linker_compute_class_values(subs);
1141
1142                 subs = subs->nextsub;
1143         }
1144
1145         c->vftbl->diffval = classvalue - c->vftbl->baseval;
1146 }
1147
1148
1149 /* linker_addinterface *********************************************************
1150
1151    Is needed by link_class for adding a VTBL to a class. All
1152    interfaces implemented by ic are added as well.
1153
1154    RETURN VALUE:
1155       true.........everything ok
1156           false........an exception has been thrown
1157
1158 *******************************************************************************/
1159
1160 static bool linker_addinterface(classinfo *c, classinfo *ic)
1161 {
1162         s4          j, k;
1163         vftbl_t    *v;
1164         s4          i;
1165         classinfo  *sc;
1166         methodinfo *m;
1167
1168         v = c->vftbl;
1169         i = ic->index;
1170
1171         if (i >= v->interfacetablelength)
1172                 vm_abort("Internal error: interfacetable overflow");
1173
1174         /* if this interface has already been added, return immediately */
1175
1176         if (v->interfacetable[-i] != NULL)
1177                 return true;
1178
1179         if (ic->methodscount == 0) {  /* fake entry needed for subtype test */
1180                 v->interfacevftbllength[i] = 1;
1181                 v->interfacetable[-i]      = MNEW(methodptr, 1);
1182                 v->interfacetable[-i][0]   = NULL;
1183         }
1184         else {
1185                 v->interfacevftbllength[i] = ic->methodscount;
1186                 v->interfacetable[-i]      = MNEW(methodptr, ic->methodscount);
1187
1188 #if defined(ENABLE_STATISTICS)
1189                 if (opt_stat)
1190                         count_vftbl_len += sizeof(methodptr) *
1191                                 (ic->methodscount + (ic->methodscount == 0));
1192 #endif
1193
1194                 for (j = 0; j < ic->methodscount; j++) {
1195                         for (sc = c; sc != NULL; sc = sc->super.cls) {
1196                                 for (k = 0; k < sc->methodscount; k++) {
1197                                         m = &(sc->methods[k]);
1198
1199                                         if (method_canoverwrite(m, &(ic->methods[j]))) {
1200                                                 /* method m overwrites the (abstract) method */
1201 #if defined(ENABLE_VERIFIER)
1202                                                 /* Add loading constraints (for the more
1203                                                    general types of the method
1204                                                    ic->methods[j]).  */
1205                                                 if (!classcache_add_constraints_for_params(
1206                                                                         c->classloader, ic->classloader,
1207                                                                         &(ic->methods[j])))
1208                                                 {
1209                                                         return false;
1210                                                 }
1211 #endif
1212
1213                                                 /* XXX taken from gcj */
1214                                                 /* check for ACC_STATIC: IncompatibleClassChangeError */
1215
1216                                                 /* check for !ACC_PUBLIC: IllegalAccessError */
1217
1218                                                 /* check for ACC_ABSTRACT: AbstracMethodError,
1219                                                    not sure about that one */
1220
1221                                                 v->interfacetable[-i][j] = v->table[m->vftblindex];
1222                                                 goto foundmethod;
1223                                         }
1224                                 }
1225                         }
1226
1227                         /* If no method was found, insert the AbstractMethodError
1228                            stub. */
1229
1230                         v->interfacetable[-i][j] = &asm_abstractmethoderror;
1231
1232                 foundmethod:
1233                         ;
1234                 }
1235         }
1236
1237         /* add superinterfaces of this interface */
1238
1239         for (j = 0; j < ic->interfacescount; j++)
1240                 if (!linker_addinterface(c, ic->interfaces[j].cls))
1241                         return false;
1242
1243         /* everything ok */
1244
1245         return true;
1246 }
1247
1248
1249 /* class_highestinterface ******************************************************
1250
1251    Used by the function link_class to determine the amount of memory
1252    needed for the interface table.
1253
1254 *******************************************************************************/
1255
1256 static s4 class_highestinterface(classinfo *c)
1257 {
1258         s4 h;
1259         s4 h2;
1260         s4 i;
1261         
1262     /* check for ACC_INTERFACE bit already done in link_class_intern */
1263
1264     h = c->index;
1265
1266         for (i = 0; i < c->interfacescount; i++) {
1267                 h2 = class_highestinterface(c->interfaces[i].cls);
1268
1269                 if (h2 > h)
1270                         h = h2;
1271         }
1272
1273         return h;
1274 }
1275
1276
1277 /*
1278  * These are local overrides for various environment variables in Emacs.
1279  * Please do not remove this and leave it at the end of the file, where
1280  * Emacs will automagically detect them.
1281  * ---------------------------------------------------------------------
1282  * Local variables:
1283  * mode: c
1284  * indent-tabs-mode: t
1285  * c-basic-offset: 4
1286  * tab-width: 4
1287  * End:
1288  * vim:noexpandtab:sw=4:ts=4:
1289  */