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