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