Merged new changes from default (manually: src/vm/jit/i386/codegen.c).
[cacao.git] / src / vm / class.cpp
1 /* src/vm/class.cpp - class related 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 <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32
33 #include "vm/types.h"
34
35 #include "arch.h"
36
37 #include "mm/memory.h"
38
39 #include "native/llni.h"
40
41 #include "threads/lock.hpp"
42 #include "threads/mutex.hpp"
43
44 #include "toolbox/logging.h"
45
46 #include "vm/array.hpp"
47 #include "vm/jit/builtin.hpp"
48 #include "vm/class.hpp"
49 #include "vm/classcache.h"
50 #include "vm/exceptions.hpp"
51 #include "vm/global.h"
52 #include "vm/globals.hpp"
53 #include "vm/javaobjects.hpp"
54 #include "vm/jit/jitcache.hpp"
55 #include "vm/linker.h"
56 #include "vm/loader.hpp"
57 #include "vm/options.h"
58 #include "vm/resolve.hpp"
59
60 #if defined(ENABLE_STATISTICS)
61 # include "vm/statistics.h"
62 #endif
63
64 #include "vm/suck.hpp"
65 #include "vm/utf8.h"
66
67 #include "vm/jit/asmpart.h"
68
69
70 /* class_set_packagename *******************************************************
71
72    Derive the package name from the class name and store it in the
73    struct.
74
75    An internal package name consists of the package name plus the
76    trailing '/', e.g. "java/lang/".
77
78    For classes in the unnamed package, the package name is set to
79    NULL.
80
81 *******************************************************************************/
82
83 void class_set_packagename(classinfo *c)
84 {
85         char *p;
86         char *start;
87
88         p     = UTF_END(c->name) - 1;
89         start = c->name->text;
90
91         if (c->name->text[0] == '[') {
92                 /* Set packagename of arrays to the element's package. */
93
94                 for (; *start == '['; start++);
95
96                 /* Skip the 'L' in arrays of references. */
97
98                 if (*start == 'L')
99                         start++;
100         }
101
102         /* Search for last '/'. */
103
104         for (; (p > start) && (*p != '/'); --p);
105
106         /* If we found a '/' we set the package name plus the trailing
107            '/'.  Otherwise we set the packagename to NULL. */
108
109         if (p > start)
110                 c->packagename = utf_new(start, p - start + 1);
111         else
112                 c->packagename = NULL;
113 }
114
115
116 /* class_create_classinfo ******************************************************
117
118    Create a new classinfo struct. The class name is set to the given utf *,
119    most other fields are initialized to zero.
120
121    Note: classname may be NULL. In this case a not-yet-named classinfo is
122          created. The name must be filled in later and class_set_packagename
123                  must be called after that.
124
125 *******************************************************************************/
126
127 classinfo *class_create_classinfo(utf *classname)
128 {
129         classinfo *c;
130
131 #if defined(ENABLE_STATISTICS)
132         if (opt_stat)
133                 size_classinfo += sizeof(classinfo);
134 #endif
135
136         /* we use a safe name for temporarily unnamed classes */
137
138         if (classname == NULL)
139                 classname = utf_not_named_yet;
140
141 #if !defined(NDEBUG)
142         if (initverbose)
143                 log_message_utf("Creating class: ", classname);
144 #endif
145
146 #if !defined(ENABLE_GC_BOEHM)
147         c = (classinfo *) heap_alloc_uncollectable(sizeof(classinfo));
148         /*c = NEW(classinfo);
149         MZERO(c, classinfo, 1);*/
150 #else
151         c = GCNEW_UNCOLLECTABLE(classinfo, 1);
152         /* GCNEW_UNCOLLECTABLE clears the allocated memory */
153 #endif
154
155         c->name = classname;
156
157         /* Set the header.vftbl of all loaded classes to the one of
158        java.lang.Class, so Java code can use a class as object. */
159
160         if (class_java_lang_Class != NULL)
161                 if (class_java_lang_Class->vftbl != NULL)
162                         c->object.header.vftbl = class_java_lang_Class->vftbl;
163
164 #if defined(ENABLE_JAVASE)
165         /* check if the class is a reference class and flag it */
166
167         if (classname == utf_java_lang_ref_SoftReference) {
168                 c->flags |= ACC_CLASS_REFERENCE_SOFT;
169         }
170         else if (classname == utf_java_lang_ref_WeakReference) {
171                 c->flags |= ACC_CLASS_REFERENCE_WEAK;
172         }
173         else if (classname == utf_java_lang_ref_PhantomReference) {
174                 c->flags |= ACC_CLASS_REFERENCE_PHANTOM;
175         }
176 #endif
177
178         if (classname != utf_not_named_yet)
179                 class_set_packagename(c);
180 #if defined (ENABLE_JITCACHE)
181     c->cache_file_fd = 0;
182 #endif
183
184         c->object.header.lockword.init();
185
186         return c;
187 }
188
189
190 /* class_postset_header_vftbl **************************************************
191
192    Set the header.vftbl of all classes created before java.lang.Class
193    was linked.  This is necessary that Java code can use a class as
194    object.
195
196 *******************************************************************************/
197
198 void class_postset_header_vftbl(void)
199 {
200         classinfo *c;
201         u4 slot;
202         classcache_name_entry *nmen;
203         classcache_class_entry *clsen;
204
205         assert(class_java_lang_Class);
206
207         for (slot = 0; slot < hashtable_classcache.size; slot++) {
208                 nmen = (classcache_name_entry *) hashtable_classcache.ptr[slot];
209
210                 for (; nmen; nmen = nmen->hashlink) {
211                         /* iterate over all class entries */
212
213                         for (clsen = nmen->classes; clsen; clsen = clsen->next) {
214                                 c = clsen->classobj;
215
216                                 /* now set the the vftbl */
217
218                                 if (c->object.header.vftbl == NULL)
219                                         c->object.header.vftbl = class_java_lang_Class->vftbl;
220                         }
221                 }
222         }
223 }
224
225 /* class_define ****************************************************************
226
227    Calls the loader and defines a class in the VM.
228
229 *******************************************************************************/
230
231 classinfo *class_define(utf *name, classloader_t *cl, int32_t length, uint8_t *data, java_handle_t *pd)
232 {
233         classinfo   *c;
234         classinfo   *r;
235         classbuffer *cb;
236
237         if (name != NULL) {
238                 /* check if this class has already been defined */
239
240                 c = classcache_lookup_defined_or_initiated(cl, name);
241
242                 if (c != NULL) {
243                         exceptions_throw_linkageerror("duplicate class definition: ", c);
244                         return NULL;
245                 }
246         } 
247
248         /* create a new classinfo struct */
249
250         c = class_create_classinfo(name);
251
252 #if defined(ENABLE_STATISTICS)
253         /* measure time */
254
255         if (opt_getloadingtime)
256                 loadingtime_start();
257 #endif
258
259         /* build a classbuffer with the given data */
260
261         cb = NEW(classbuffer);
262
263         cb->clazz = c;
264         cb->size  = length;
265         cb->data  = data;
266         cb->pos   = cb->data;
267
268         /* preset the defining classloader */
269
270         c->classloader = cl;
271
272         /* load the class from this buffer */
273
274         r = load_class_from_classbuffer(cb);
275
276         /* free memory */
277
278         FREE(cb, classbuffer);
279
280 #if defined(ENABLE_STATISTICS)
281         /* measure time */
282
283         if (opt_getloadingtime)
284                 loadingtime_stop();
285 #endif
286
287         if (r == NULL) {
288                 /* If return value is NULL, we had a problem and the class is
289                    not loaded.  Now free the allocated memory, otherwise we
290                    could run into a DOS. */
291
292                 class_free(c);
293
294                 return NULL;
295         }
296
297 #if defined(ENABLE_JAVASE)
298 # if defined(WITH_JAVA_RUNTIME_LIBRARY_OPENJDK)
299         /* Store the protection domain. */
300
301         c->protectiondomain = pd;
302 # endif
303 #endif
304
305         /* Store the newly defined class in the class cache. This call
306            also checks whether a class of the same name has already been
307            defined by the same defining loader, and if so, replaces the
308            newly created class by the one defined earlier. */
309
310         /* Important: The classinfo given to classcache_store must be
311                       fully prepared because another thread may return
312                       this pointer after the lookup at to top of this
313                       function directly after the class cache lock has
314                       been released. */
315
316         c = classcache_store(cl, c, true);
317
318         return c;
319 }
320
321
322 /* class_load_attribute_sourcefile *********************************************
323
324    SourceFile_attribute {
325        u2 attribute_name_index;
326        u4 attribute_length;
327            u2 sourcefile_index;
328    }
329
330 *******************************************************************************/
331
332 static bool class_load_attribute_sourcefile(classbuffer *cb)
333 {
334         classinfo *c;
335         u4         attribute_length;
336         u2         sourcefile_index;
337         utf       *sourcefile;
338
339         /* get classinfo */
340
341         c = cb->clazz;
342
343         /* check buffer size */
344
345         if (!suck_check_classbuffer_size(cb, 4 + 2))
346                 return false;
347
348         /* check attribute length */
349
350         attribute_length = suck_u4(cb);
351
352         if (attribute_length != 2) {
353                 exceptions_throw_classformaterror(c, "Wrong size for VALUE attribute");
354                 return false;
355         }
356
357         /* there can be no more than one SourceFile attribute */
358
359         if (c->sourcefile != NULL) {
360                 exceptions_throw_classformaterror(c, "Multiple SourceFile attributes");
361                 return false;
362         }
363
364         /* get sourcefile */
365
366         sourcefile_index = suck_u2(cb);
367         sourcefile = (utf*) class_getconstant(c, sourcefile_index, CONSTANT_Utf8);
368
369         if (sourcefile == NULL)
370                 return false;
371
372         /* store sourcefile */
373
374         c->sourcefile = sourcefile;
375
376         return true;
377 }
378
379
380 /* class_load_attribute_enclosingmethod ****************************************
381
382    EnclosingMethod_attribute {
383        u2 attribute_name_index;
384        u4 attribute_length;
385            u2 class_index;
386            u2 method_index;
387    }
388
389 *******************************************************************************/
390
391 #if defined(ENABLE_JAVASE)
392 static bool class_load_attribute_enclosingmethod(classbuffer *cb)
393 {
394         classinfo             *c;
395         u4                     attribute_length;
396         u2                     class_index;
397         u2                     method_index;
398         classref_or_classinfo  cr;
399         constant_nameandtype  *cn;
400
401         /* get classinfo */
402
403         c = cb->clazz;
404
405         /* check buffer size */
406
407         if (!suck_check_classbuffer_size(cb, 4 + 2 + 2))
408                 return false;
409
410         /* check attribute length */
411
412         attribute_length = suck_u4(cb);
413
414         if (attribute_length != 4) {
415                 exceptions_throw_classformaterror(c, "Wrong size for VALUE attribute");
416                 return false;
417         }
418
419         /* there can be no more than one EnclosingMethod attribute */
420
421         if (c->enclosingmethod != NULL) {
422                 exceptions_throw_classformaterror(c, "Multiple EnclosingMethod attributes");
423                 return false;
424         }
425
426         /* get class index */
427
428         class_index = suck_u2(cb);
429         cr.ref = (constant_classref*) innerclass_getconstant(c, class_index, CONSTANT_Class);
430
431         /* get method index */
432
433         method_index = suck_u2(cb);
434         cn = (constant_nameandtype*) innerclass_getconstant(c, method_index, CONSTANT_NameAndType);
435
436         /* store info in classinfo */
437
438         c->enclosingclass.any = cr.any;
439         c->enclosingmethod    = cn;
440
441         return true;
442 }
443 #endif /* defined(ENABLE_JAVASE) */
444
445
446 /* class_load_attributes *******************************************************
447
448    Read attributes from ClassFile.
449
450    attribute_info {
451        u2 attribute_name_index;
452        u4 attribute_length;
453        u1 info[attribute_length];
454    }
455
456    InnerClasses_attribute {
457        u2 attribute_name_index;
458        u4 attribute_length;
459    }
460
461 *******************************************************************************/
462
463 bool class_load_attributes(classbuffer *cb)
464 {
465         classinfo             *c;
466         uint16_t               attributes_count;
467         uint16_t               attribute_name_index;
468         utf                   *attribute_name;
469         innerclassinfo        *info;
470         classref_or_classinfo  inner;
471         classref_or_classinfo  outer;
472         utf                   *name;
473         uint16_t               flags;
474         int                    i, j;
475
476         c = cb->clazz;
477
478         /* get attributes count */
479
480         if (!suck_check_classbuffer_size(cb, 2))
481                 return false;
482
483         attributes_count = suck_u2(cb);
484
485         for (i = 0; i < attributes_count; i++) {
486                 /* get attribute name */
487
488                 if (!suck_check_classbuffer_size(cb, 2))
489                         return false;
490
491                 attribute_name_index = suck_u2(cb);
492                 attribute_name =
493                         (utf*) class_getconstant(c, attribute_name_index, CONSTANT_Utf8);
494
495                 if (attribute_name == NULL)
496                         return false;
497
498                 if (attribute_name == utf_InnerClasses) {
499                         /* InnerClasses */
500
501                         if (c->innerclass != NULL) {
502                                 exceptions_throw_classformaterror(c, "Multiple InnerClasses attributes");
503                                 return false;
504                         }
505                                 
506                         if (!suck_check_classbuffer_size(cb, 4 + 2))
507                                 return false;
508
509                         /* skip attribute length */
510                         suck_u4(cb);
511
512                         /* number of records */
513                         c->innerclasscount = suck_u2(cb);
514
515                         if (!suck_check_classbuffer_size(cb, (2 + 2 + 2 + 2) * c->innerclasscount))
516                                 return false;
517
518                         /* allocate memory for innerclass structure */
519                         c->innerclass = MNEW(innerclassinfo, c->innerclasscount);
520
521                         for (j = 0; j < c->innerclasscount; j++) {
522                                 /* The innerclass structure contains a class with an encoded
523                                    name, its defining scope, its simple name and a bitmask of
524                                    the access flags. */
525                                                                 
526                                 info = c->innerclass + j;
527
528                                 inner.ref = (constant_classref*) innerclass_getconstant(c, suck_u2(cb), CONSTANT_Class);
529                                 outer.ref = (constant_classref*) innerclass_getconstant(c, suck_u2(cb), CONSTANT_Class);
530                                 name      = (utf*) innerclass_getconstant(c, suck_u2(cb), CONSTANT_Utf8);
531                                 flags     = suck_u2(cb);
532
533                                 /* If the current inner-class is the currently loaded
534                                    class check for some special flags. */
535
536                                 if (inner.ref->name == c->name) {
537                                         /* If an inner-class is not a member, its
538                                            outer-class is NULL. */
539
540                                         if (outer.ref != NULL) {
541                                                 c->flags |= ACC_CLASS_MEMBER;
542
543                                                 /* A member class doesn't have an
544                                                    EnclosingMethod attribute, so set the
545                                                    enclosing-class to be the same as the
546                                                    declaring-class. */
547
548                                                 c->declaringclass = outer;
549                                                 c->enclosingclass = outer;
550                                         }
551
552                                         /* If an inner-class is anonymous, its name is
553                                            NULL. */
554
555                                         if (name == NULL)
556                                                 c->flags |= ACC_CLASS_ANONYMOUS;
557                                 }
558
559                                 info->inner_class = inner;
560                                 info->outer_class = outer;
561                                 info->name        = name;
562                                 info->flags       = flags;
563                         }
564                 }
565                 else if (attribute_name == utf_SourceFile) {
566                         /* SourceFile */
567
568                         if (!class_load_attribute_sourcefile(cb))
569                                 return false;
570                 }
571 #if defined(ENABLE_JAVASE)
572                 else if (attribute_name == utf_EnclosingMethod) {
573                         /* EnclosingMethod */
574
575                         if (!class_load_attribute_enclosingmethod(cb))
576                                 return false;
577                 }
578                 else if (attribute_name == utf_Signature) {
579                         /* Signature */
580
581                         if (!loader_load_attribute_signature(cb, &(c->signature)))
582                                 return false;
583                 }
584 #endif
585
586 #if defined(ENABLE_ANNOTATIONS)
587                 else if (attribute_name == utf_RuntimeVisibleAnnotations) {
588                         /* RuntimeVisibleAnnotations */
589                         if (!annotation_load_class_attribute_runtimevisibleannotations(cb))
590                                 return false;
591                 }
592                 else if (attribute_name == utf_RuntimeInvisibleAnnotations) {
593                         /* RuntimeInvisibleAnnotations */
594                         if (!annotation_load_class_attribute_runtimeinvisibleannotations(cb))
595                                 return false;
596                 }
597 #endif
598
599                 else {
600                         /* unknown attribute */
601
602                         if (!loader_skip_attribute_body(cb))
603                                 return false;
604                 }
605         }
606
607         return true;
608 }
609
610
611 /* class_freepool **************************************************************
612
613         Frees all resources used by this classes Constant Pool.
614
615 *******************************************************************************/
616
617 static void class_freecpool(classinfo *c)
618 {
619         u4 idx;
620         u4 tag;
621         void* info;
622         
623         if (c->cptags && c->cpinfos) {
624                 for (idx = 0; idx < c->cpcount; idx++) {
625                         tag = c->cptags[idx];
626                         info = c->cpinfos[idx];
627                 
628                         if (info != NULL) {
629                                 switch (tag) {
630                                 case CONSTANT_Fieldref:
631                                 case CONSTANT_Methodref:
632                                 case CONSTANT_InterfaceMethodref:
633                                         FREE(info, constant_FMIref);
634                                         break;
635                                 case CONSTANT_Integer:
636                                         FREE(info, constant_integer);
637                                         break;
638                                 case CONSTANT_Float:
639                                         FREE(info, constant_float);
640                                         break;
641                                 case CONSTANT_Long:
642                                         FREE(info, constant_long);
643                                         break;
644                                 case CONSTANT_Double:
645                                         FREE(info, constant_double);
646                                         break;
647                                 case CONSTANT_NameAndType:
648                                         FREE(info, constant_nameandtype);
649                                         break;
650                                 }
651                         }
652                 }
653         }
654
655         if (c->cptags)
656                 MFREE(c->cptags, u1, c->cpcount);
657
658         if (c->cpinfos)
659                 MFREE(c->cpinfos, void*, c->cpcount);
660 }
661
662
663 /* class_getconstant ***********************************************************
664
665    Retrieves the value at position 'pos' of the constantpool of a
666    class. If the type of the value is other than 'ctype', an error is
667    thrown.
668
669 *******************************************************************************/
670
671 void* class_getconstant(classinfo *c, u4 pos, u4 ctype)
672 {
673         /* check index and type of constantpool entry */
674         /* (pos == 0 is caught by type comparison) */
675
676         if ((pos >= c->cpcount) || (c->cptags[pos] != ctype)) {
677                 exceptions_throw_classformaterror(c, "Illegal constant pool index");
678                 return NULL;
679         }
680
681         return c->cpinfos[pos];
682 }
683
684
685 /* innerclass_getconstant ******************************************************
686
687    Like class_getconstant, but if cptags is ZERO, null is returned.
688         
689 *******************************************************************************/
690
691 void* innerclass_getconstant(classinfo *c, u4 pos, u4 ctype)
692 {
693         /* invalid position in constantpool */
694
695         if (pos >= c->cpcount) {
696                 exceptions_throw_classformaterror(c, "Illegal constant pool index");
697                 return NULL;
698         }
699
700         /* constantpool entry of type 0 */      
701
702         if (c->cptags[pos] == 0)
703                 return NULL;
704
705         /* check type of constantpool entry */
706
707         if (c->cptags[pos] != ctype) {
708                 exceptions_throw_classformaterror(c, "Illegal constant pool index");
709                 return NULL;
710         }
711                 
712         return c->cpinfos[pos];
713 }
714
715
716 /* class_free ******************************************************************
717
718    Frees all resources used by the class.
719
720 *******************************************************************************/
721
722 void class_free(classinfo *c)
723 {
724         s4 i;
725         vftbl_t *v;
726
727 #if defined(ENABLE_JITCACHE)
728 /* TODO: Find a way around the linker problem */
729 /*    jitcache_freeclass(c);*/
730 #endif
731
732         class_freecpool(c);
733
734         if (c->interfaces != NULL)
735                 MFREE(c->interfaces, classinfo*, c->interfacescount);
736
737         if (c->fields) {
738                 for (i = 0; i < c->fieldscount; i++)
739                         field_free(&(c->fields[i]));
740                 MFREE(c->fields, fieldinfo, c->fieldscount);
741         }
742         
743         if (c->methods) {
744                 for (i = 0; i < c->methodscount; i++)
745                         method_free(&(c->methods[i]));
746                 MFREE(c->methods, methodinfo, c->methodscount);
747         }
748
749         if ((v = c->vftbl) != NULL) {
750                 if (v->arraydesc)
751                         mem_free(v->arraydesc,sizeof(arraydescriptor));
752                 
753                 for (i = 0; i < v->interfacetablelength; i++) {
754                         MFREE(v->interfacetable[-i], methodptr, v->interfacevftbllength[i]);
755                 }
756                 MFREE(v->interfacevftbllength, s4, v->interfacetablelength);
757
758                 i = sizeof(vftbl_t) + sizeof(methodptr) * (v->vftbllength - 1) +
759                     sizeof(methodptr*) * (v->interfacetablelength -
760                                          (v->interfacetablelength > 0));
761                 v = (vftbl_t*) (((methodptr*) v) -
762                                                 (v->interfacetablelength - 1) * (v->interfacetablelength > 1));
763                 mem_free(v, i);
764         }
765
766         if (c->innerclass)
767                 MFREE(c->innerclass, innerclassinfo, c->innerclasscount);
768
769         /*      if (c->classvftbl)
770                 mem_free(c->header.vftbl, sizeof(vftbl) + sizeof(methodptr)*(c->vftbl->vftbllength-1)); */
771         
772 /*      GCFREE(c); */
773 }
774
775
776 /* get_array_class *************************************************************
777
778    Returns the array class with the given name for the given
779    classloader, or NULL if an exception occurred.
780
781    Note: This function does eager loading. 
782
783 *******************************************************************************/
784
785 static classinfo *get_array_class(utf *name,classloader_t *initloader,
786                                                                                         classloader_t *defloader,bool link)
787 {
788         classinfo *c;
789         
790         /* lookup this class in the classcache */
791         c = classcache_lookup(initloader,name);
792         if (!c)
793                 c = classcache_lookup_defined(defloader,name);
794
795         if (!c) {
796                 /* we have to create it */
797                 c = class_create_classinfo(name);
798                 c = load_newly_created_array(c,initloader);
799                 if (c == NULL)
800                         return NULL;
801         }
802
803         assert(c);
804         assert(c->state & CLASS_LOADED);
805         assert(c->classloader == defloader);
806
807         if (link && !(c->state & CLASS_LINKED))
808                 if (!link_class(c))
809                         return NULL;
810
811         assert(!link || (c->state & CLASS_LINKED));
812
813         return c;
814 }
815
816
817 /* class_array_of **************************************************************
818
819    Returns an array class with the given component class. The array
820    class is dynamically created if neccessary.
821
822 *******************************************************************************/
823
824 classinfo *class_array_of(classinfo *component, bool link)
825 {
826         classloader_t     *cl;
827     s4                 namelen;
828     char              *namebuf;
829         utf               *u;
830         classinfo         *c;
831
832         cl = component->classloader;
833
834     /* Assemble the array class name */
835     namelen = component->name->blength;
836     
837     if (component->name->text[0] == '[') {
838         /* the component is itself an array */
839         namebuf = MNEW(char, namelen + 1);
840         namebuf[0] = '[';
841         MCOPY(namebuf + 1, component->name->text, char, namelen);
842         namelen++;
843     }
844         else {
845         /* the component is a non-array class */
846         namebuf = MNEW(char, namelen + 3);
847         namebuf[0] = '[';
848         namebuf[1] = 'L';
849         MCOPY(namebuf + 2, component->name->text, char, namelen);
850         namebuf[2 + namelen] = ';';
851         namelen += 3;
852     }
853
854         u = utf_new(namebuf, namelen);
855
856         MFREE(namebuf, char, namelen);
857
858         c = get_array_class(u, cl, cl, link);
859
860         return c;
861 }
862
863
864 /* class_multiarray_of *********************************************************
865
866    Returns an array class with the given dimension and element class.
867    The array class is dynamically created if neccessary.
868
869 *******************************************************************************/
870
871 classinfo *class_multiarray_of(s4 dim, classinfo *element, bool link)
872 {
873     s4 namelen;
874     char *namebuf;
875         classinfo *c;
876
877         if (dim < 1) {
878                 log_text("Invalid array dimension requested");
879                 assert(0);
880         }
881
882     /* Assemble the array class name */
883     namelen = element->name->blength;
884     
885     if (element->name->text[0] == '[') {
886         /* the element is itself an array */
887         namebuf = MNEW(char, namelen + dim);
888         memcpy(namebuf + dim, element->name->text, namelen);
889         namelen += dim;
890     }
891     else {
892         /* the element is a non-array class */
893         namebuf = MNEW(char, namelen + 2 + dim);
894         namebuf[dim] = 'L';
895         memcpy(namebuf + dim + 1, element->name->text, namelen);
896         namelen += (2 + dim);
897         namebuf[namelen - 1] = ';';
898     }
899         memset(namebuf, '[', dim);
900
901         utf* u = utf_new(namebuf, namelen);
902
903         MFREE(namebuf, char, namelen);
904
905         c = get_array_class(u,
906                                                 element->classloader,
907                                                 element->classloader,
908                                                 link);
909
910         return c;
911 }
912
913
914 /* class_lookup_classref *******************************************************
915
916    Looks up the constant_classref for a given classname in the classref
917    tables of a class.
918
919    IN:
920        cls..............the class containing the reference
921            name.............the name of the class refered to
922
923     RETURN VALUE:
924            a pointer to a constant_classref, or 
925            NULL if the reference was not found
926    
927 *******************************************************************************/
928
929 constant_classref *class_lookup_classref(classinfo *cls, utf *name)
930 {
931         constant_classref *ref;
932         extra_classref *xref;
933         int count;
934
935         assert(cls);
936         assert(name);
937         assert(!cls->classrefcount || cls->classrefs);
938         
939         /* first search the main classref table */
940         count = cls->classrefcount;
941         ref = cls->classrefs;
942         for (; count; --count, ++ref)
943                 if (ref->name == name)
944                         return ref;
945
946         /* next try the list of extra classrefs */
947         for (xref = cls->extclassrefs; xref; xref = xref->next) {
948                 if (xref->classref.name == name)
949                         return &(xref->classref);
950         }
951
952         /* not found */
953         return NULL;
954 }
955
956
957 /* class_get_classref **********************************************************
958
959    Returns the constant_classref for a given classname.
960
961    IN:
962        cls..............the class containing the reference
963            name.............the name of the class refered to
964
965    RETURN VALUE:
966        a pointer to a constant_classref (never NULL)
967
968    NOTE:
969        The given name is not checked for validity!
970    
971 *******************************************************************************/
972
973 constant_classref *class_get_classref(classinfo *cls, utf *name)
974 {
975         constant_classref *ref;
976         extra_classref *xref;
977
978         assert(cls);
979         assert(name);
980
981         ref = class_lookup_classref(cls,name);
982         if (ref)
983                 return ref;
984
985         xref = NEW(extra_classref);
986         CLASSREF_INIT(xref->classref,cls,name);
987
988         xref->next = cls->extclassrefs;
989         cls->extclassrefs = xref;
990
991         return &(xref->classref);
992 }
993
994
995 /* class_get_self_classref *****************************************************
996
997    Returns the constant_classref to the class itself.
998
999    IN:
1000        cls..............the class containing the reference
1001
1002    RETURN VALUE:
1003        a pointer to a constant_classref (never NULL)
1004
1005 *******************************************************************************/
1006
1007 constant_classref *class_get_self_classref(classinfo *cls)
1008 {
1009         /* XXX this should be done in a faster way. Maybe always make */
1010         /* the classref of index 0 a self reference.                  */
1011         return class_get_classref(cls,cls->name);
1012 }
1013
1014 /* class_get_classref_multiarray_of ********************************************
1015
1016    Returns an array type reference with the given dimension and element class
1017    reference.
1018
1019    IN:
1020        dim..............the requested dimension
1021                             dim must be in [1;255]. This is NOT checked!
1022            ref..............the component class reference
1023
1024    RETURN VALUE:
1025        a pointer to the class reference for the array type
1026
1027    NOTE:
1028        The referer of `ref` is used as the referer for the new classref.
1029
1030 *******************************************************************************/
1031
1032 constant_classref *class_get_classref_multiarray_of(s4 dim, constant_classref *ref)
1033 {
1034     s4 namelen;
1035     char *namebuf;
1036         constant_classref *cr;
1037
1038         assert(ref);
1039         assert(dim >= 1 && dim <= 255);
1040
1041     /* Assemble the array class name */
1042     namelen = ref->name->blength;
1043     
1044     if (ref->name->text[0] == '[') {
1045         /* the element is itself an array */
1046         namebuf = MNEW(char, namelen + dim);
1047         memcpy(namebuf + dim, ref->name->text, namelen);
1048         namelen += dim;
1049     }
1050     else {
1051         /* the element is a non-array class */
1052         namebuf = MNEW(char, namelen + 2 + dim);
1053         namebuf[dim] = 'L';
1054         memcpy(namebuf + dim + 1, ref->name->text, namelen);
1055         namelen += (2 + dim);
1056         namebuf[namelen - 1] = ';';
1057     }
1058         memset(namebuf, '[', dim);
1059
1060         utf* u = utf_new(namebuf, namelen);
1061
1062         MFREE(namebuf, char, namelen);
1063
1064     cr = class_get_classref(ref->referer, u);
1065
1066         return cr;
1067 }
1068
1069
1070 /* class_get_classref_component_of *********************************************
1071
1072    Returns the component classref of a given array type reference
1073
1074    IN:
1075        ref..............the array type reference
1076
1077    RETURN VALUE:
1078        a reference to the component class, or
1079            NULL if `ref` is not an object array type reference
1080
1081    NOTE:
1082        The referer of `ref` is used as the referer for the new classref.
1083
1084 *******************************************************************************/
1085
1086 constant_classref *class_get_classref_component_of(constant_classref *ref)
1087 {
1088         s4 namelen;
1089         char *name;
1090         
1091         assert(ref);
1092
1093         name = ref->name->text;
1094         if (*name++ != '[')
1095                 return NULL;
1096         
1097         namelen = ref->name->blength - 1;
1098         if (*name == 'L') {
1099                 name++;
1100                 namelen -= 2;
1101         }
1102         else if (*name != '[') {
1103                 return NULL;
1104         }
1105
1106     return class_get_classref(ref->referer, utf_new(name, namelen));
1107 }
1108
1109
1110 /* class_findmethod ************************************************************
1111         
1112    Searches a 'classinfo' structure for a method having the given name
1113    and descriptor. If descriptor is NULL, it is ignored.
1114
1115 *******************************************************************************/
1116
1117 methodinfo *class_findmethod(classinfo *c, utf *name, utf *desc)
1118 {
1119         methodinfo *m;
1120         s4          i;
1121
1122         for (i = 0; i < c->methodscount; i++) {
1123                 m = &(c->methods[i]);
1124
1125                 if ((m->name == name) && ((desc == NULL) || (m->descriptor == desc)))
1126                         return m;
1127         }
1128
1129         return NULL;
1130 }
1131
1132
1133 /* class_resolvemethod *********************************************************
1134         
1135    Searches a class and it's super classes for a method.
1136
1137    Superinterfaces are *not* searched.
1138
1139 *******************************************************************************/
1140
1141 methodinfo *class_resolvemethod(classinfo *c, utf *name, utf *desc)
1142 {
1143         methodinfo *m;
1144
1145         while (c) {
1146                 m = class_findmethod(c, name, desc);
1147
1148                 if (m)
1149                         return m;
1150
1151                 /* JVM Specification bug: 
1152
1153                    It is important NOT to resolve special <init> and <clinit>
1154                    methods to super classes or interfaces; yet, this is not
1155                    explicited in the specification.  Section 5.4.3.3 should be
1156                    updated appropriately.  */
1157
1158                 if (name == utf_init || name == utf_clinit)
1159                         return NULL;
1160
1161                 c = c->super;
1162         }
1163
1164         return NULL;
1165 }
1166
1167
1168 /* class_resolveinterfacemethod_intern *****************************************
1169
1170    Internally used helper function. Do not use this directly.
1171
1172 *******************************************************************************/
1173
1174 static methodinfo *class_resolveinterfacemethod_intern(classinfo *c,
1175                                                                                                            utf *name, utf *desc)
1176 {
1177         methodinfo *m;
1178         s4          i;
1179
1180         /* try to find the method in the class */
1181
1182         m = class_findmethod(c, name, desc);
1183
1184         if (m != NULL)
1185                 return m;
1186
1187         /* No method found?  Try the super interfaces. */
1188
1189         for (i = 0; i < c->interfacescount; i++) {
1190                 m = class_resolveinterfacemethod_intern(c->interfaces[i], name, desc);
1191
1192                 if (m != NULL)
1193                         return m;
1194         }
1195
1196         /* no method found */
1197
1198         return NULL;
1199 }
1200
1201
1202 /* class_resolveclassmethod ****************************************************
1203         
1204    Resolves a reference from REFERER to a method with NAME and DESC in
1205    class C.
1206
1207    If the method cannot be resolved the return value is NULL. If
1208    EXCEPT is true *exceptionptr is set, too.
1209
1210 *******************************************************************************/
1211
1212 methodinfo *class_resolveclassmethod(classinfo *c, utf *name, utf *desc,
1213                                                                          classinfo *referer, bool throwexception)
1214 {
1215         classinfo  *cls;
1216         methodinfo *m;
1217         s4          i;
1218
1219 /*      if (c->flags & ACC_INTERFACE) { */
1220 /*              if (throwexception) */
1221 /*                      *exceptionptr = */
1222 /*                              new_exception(string_java_lang_IncompatibleClassChangeError); */
1223 /*              return NULL; */
1224 /*      } */
1225
1226         /* try class c and its superclasses */
1227
1228         cls = c;
1229
1230         m = class_resolvemethod(cls, name, desc);
1231
1232         if (m != NULL)
1233                 goto found;
1234
1235         /* Try the super interfaces. */
1236
1237         for (i = 0; i < c->interfacescount; i++) {
1238                 m = class_resolveinterfacemethod_intern(c->interfaces[i], name, desc);
1239
1240                 if (m != NULL)
1241                         goto found;
1242         }
1243         
1244         if (throwexception)
1245                 exceptions_throw_nosuchmethoderror(c, name, desc);
1246
1247         return NULL;
1248
1249  found:
1250         if ((m->flags & ACC_ABSTRACT) && !(c->flags & ACC_ABSTRACT)) {
1251                 if (throwexception)
1252                         exceptions_throw_abstractmethoderror();
1253
1254                 return NULL;
1255         }
1256
1257         /* XXX check access rights */
1258
1259         return m;
1260 }
1261
1262
1263 /* class_resolveinterfacemethod ************************************************
1264
1265    Resolves a reference from REFERER to a method with NAME and DESC in
1266    interface C.
1267
1268    If the method cannot be resolved the return value is NULL. If
1269    EXCEPT is true *exceptionptr is set, too.
1270
1271 *******************************************************************************/
1272
1273 methodinfo *class_resolveinterfacemethod(classinfo *c, utf *name, utf *desc,
1274                                                                                  classinfo *referer, bool throwexception)
1275 {
1276         methodinfo *mi;
1277
1278         if (!(c->flags & ACC_INTERFACE)) {
1279                 if (throwexception)
1280                         exceptions_throw_incompatibleclasschangeerror(c, "Not an interface");
1281
1282                 return NULL;
1283         }
1284
1285         mi = class_resolveinterfacemethod_intern(c, name, desc);
1286
1287         if (mi != NULL)
1288                 return mi;
1289
1290         /* try class java.lang.Object */
1291
1292         mi = class_findmethod(class_java_lang_Object, name, desc);
1293
1294         if (mi != NULL)
1295                 return mi;
1296
1297         if (throwexception)
1298                 exceptions_throw_nosuchmethoderror(c, name, desc);
1299
1300         return NULL;
1301 }
1302
1303
1304 /* class_findfield *************************************************************
1305         
1306    Searches for field with specified name and type in a classinfo
1307    structure. If no such field is found NULL is returned.
1308
1309 *******************************************************************************/
1310
1311 fieldinfo *class_findfield(classinfo *c, utf *name, utf *desc)
1312 {
1313         s4 i;
1314
1315         for (i = 0; i < c->fieldscount; i++)
1316                 if ((c->fields[i].name == name) && (c->fields[i].descriptor == desc))
1317                         return &(c->fields[i]);
1318
1319         if (c->super != NULL)
1320                 return class_findfield(c->super, name, desc);
1321
1322         return NULL;
1323 }
1324
1325
1326 /* class_findfield_approx ******************************************************
1327         
1328    Searches in 'classinfo'-structure for a field with the specified
1329    name.
1330
1331 *******************************************************************************/
1332  
1333 fieldinfo *class_findfield_by_name(classinfo* c, utf* name)
1334 {
1335         for (int32_t i = 0; i < c->fieldscount; i++) {
1336                 fieldinfo* f = &(c->fields[i]);
1337
1338                 if (f->name == name)
1339                         return f;
1340         }
1341
1342         // Field not found.
1343         exceptions_throw_nosuchfielderror(c, name);
1344         return NULL;
1345 }
1346
1347
1348 /****************** Function: class_resolvefield_int ***************************
1349
1350     This is an internally used helper function. Do not use this directly.
1351
1352         Tries to resolve a field having the given name and type.
1353     If the field cannot be resolved, NULL is returned.
1354
1355 *******************************************************************************/
1356
1357 static fieldinfo *class_resolvefield_int(classinfo *c, utf *name, utf *desc)
1358 {
1359         fieldinfo *fi;
1360         s4         i;
1361
1362         /* search for field in class c */
1363
1364         for (i = 0; i < c->fieldscount; i++) { 
1365                 if ((c->fields[i].name == name) && (c->fields[i].descriptor == desc)) {
1366                         return &(c->fields[i]);
1367                 }
1368     }
1369
1370         /* Try super interfaces recursively. */
1371
1372         for (i = 0; i < c->interfacescount; i++) {
1373                 fi = class_resolvefield_int(c->interfaces[i], name, desc);
1374
1375                 if (fi != NULL)
1376                         return fi;
1377         }
1378
1379         /* Try super class. */
1380
1381         if (c->super != NULL)
1382                 return class_resolvefield_int(c->super, name, desc);
1383
1384         /* not found */
1385
1386         return NULL;
1387 }
1388
1389
1390 /********************* Function: class_resolvefield ***************************
1391         
1392         Resolves a reference from REFERER to a field with NAME and DESC in class C.
1393
1394     If the field cannot be resolved, an exception is thrown and the
1395     return value is NULL.
1396
1397 *******************************************************************************/
1398
1399 fieldinfo *class_resolvefield(classinfo *c, utf *name, utf *desc, classinfo *referer)
1400 {
1401         fieldinfo *fi;
1402
1403         fi = class_resolvefield_int(c, name, desc);
1404
1405         if (!fi) {
1406                 exceptions_throw_nosuchfielderror(c, name);
1407                 return NULL;
1408         }
1409
1410         /* XXX check access rights */
1411
1412         return fi;
1413 }
1414
1415
1416 /* class_issubclass ************************************************************
1417
1418    Checks if sub is a descendant of super.
1419         
1420 *******************************************************************************/
1421
1422 bool class_issubclass(classinfo *sub, classinfo *super)
1423 {
1424         classinfo *c;
1425
1426         c = sub;
1427
1428         for (;;) {
1429                 /* We reached java/lang/Object and did not find the requested
1430                    super class. */
1431
1432                 if (c == NULL)
1433                         return false;
1434
1435                 /* We found the requested super class. */
1436
1437                 if (c == super)
1438                         return true;
1439
1440                 c = c->super;
1441         }
1442 }
1443
1444
1445 /* class_isanysubclass *********************************************************
1446
1447    Checks a subclass relation between two classes. Implemented
1448    interfaces are interpreted as super classes.
1449
1450    Return value: 1 ... sub is subclass of super
1451                  0 ... otherwise
1452
1453 *******************************************************************************/
1454
1455 bool class_isanysubclass(classinfo *sub, classinfo *super)
1456 {
1457         uint32_t diffval;
1458         bool     result;
1459
1460         /* This is the trivial case. */
1461
1462         if (sub == super)
1463                 return true;
1464
1465         /* Primitive classes are only subclasses of themselves. */
1466
1467         if (class_is_primitive(sub) || class_is_primitive(super))
1468                 return false;
1469
1470         /* Check for interfaces. */
1471
1472         if (super->flags & ACC_INTERFACE) {
1473                 result = (sub->vftbl->interfacetablelength > super->index) &&
1474                         (sub->vftbl->interfacetable[-super->index] != NULL);
1475         }
1476         else {
1477                 /* java.lang.Object is the only super class of any
1478                    interface. */
1479
1480                 if (sub->flags & ACC_INTERFACE)
1481                         return (super == class_java_lang_Object);
1482
1483                 result = fast_subtype_check(sub->vftbl, super->vftbl);
1484         }
1485
1486         return result;
1487 }
1488
1489
1490 /* class_is_assignable_from ****************************************************
1491
1492    Return whether an instance of the "from" class parameter would be
1493    an instance of this class "to" as well.
1494
1495    ARGUMENTS:
1496        to ..... class
1497            from ... class
1498
1499    RETURN:
1500        true .... is assignable
1501            false ... is not assignable
1502
1503 *******************************************************************************/
1504
1505 bool class_is_assignable_from(classinfo *to, classinfo *from)
1506 {
1507         if (!(to->state & CLASS_LINKED))
1508                 if (!link_class(to))
1509                         return false;
1510
1511         if (!(from->state & CLASS_LINKED))
1512                 if (!link_class(from))
1513                         return false;
1514
1515         return class_isanysubclass(from, to);
1516 }
1517
1518
1519 /* class_is_instance ***********************************************************
1520
1521    Return if the given Java object is an instance of the given class.
1522
1523    ARGUMENTS:
1524        c ... class
1525            h ... Java object
1526
1527    RETURN:
1528        true .... is instance
1529            false ... is not instance
1530
1531 *******************************************************************************/
1532
1533 bool class_is_instance(classinfo *c, java_handle_t *h)
1534 {
1535         if (!(c->state & CLASS_LINKED))
1536                 if (!link_class(c))
1537                         return false;
1538
1539         return builtin_instanceof(h, c);
1540 }
1541
1542
1543 /* class_get_componenttype *****************************************************
1544
1545    Return the component class of the given class.  If the given class
1546    is not an array, return NULL.
1547
1548 *******************************************************************************/
1549
1550 classinfo *class_get_componenttype(classinfo *c)
1551 {
1552         classinfo       *component;
1553         arraydescriptor *ad;
1554         
1555         /* XXX maybe we could find a way to do this without linking. */
1556         /* This way should be safe and easy, however.                */
1557
1558         if (!(c->state & CLASS_LINKED))
1559                 if (!link_class(c))
1560                         return NULL;
1561
1562         ad = c->vftbl->arraydesc;
1563         
1564         if (ad == NULL)
1565                 return NULL;
1566         
1567         if (ad->arraytype == ARRAYTYPE_OBJECT)
1568                 component = ad->componentvftbl->clazz;
1569         else
1570                 component = Primitive::get_class_by_type(ad->arraytype);
1571                 
1572         return component;
1573 }
1574
1575
1576 /* class_get_declaredclasses ***************************************************
1577
1578    Return an array of declared classes of the given class.
1579
1580 *******************************************************************************/
1581
1582 java_handle_objectarray_t *class_get_declaredclasses(classinfo *c, bool publicOnly)
1583 {
1584         classref_or_classinfo  inner;
1585         classref_or_classinfo  outer;
1586         utf                   *outername;
1587         int                    declaredclasscount;  /* number of declared classes */
1588         int                    pos;                     /* current declared class */
1589         java_handle_objectarray_t *oa;               /* array of declared classes */
1590         int                    i;
1591         classinfo             *ic;
1592
1593         declaredclasscount = 0;
1594
1595         if (!class_is_primitive(c) && !class_is_array(c)) {
1596                 /* Determine number of declared classes. */
1597
1598                 for (i = 0; i < c->innerclasscount; i++) {
1599                         /* Get outer-class.  If the inner-class is not a member
1600                            class, the outer-class is NULL. */
1601
1602                         outer = c->innerclass[i].outer_class;
1603
1604                         if (outer.any == NULL)
1605                                 continue;
1606
1607                         /* Check if outer-class is a classref or a real class and
1608                get the class name from the structure. */
1609
1610                         outername = IS_CLASSREF(outer) ? outer.ref->name : outer.cls->name;
1611
1612                         /* Outer class is this class. */
1613
1614                         if ((outername == c->name) &&
1615                                 ((publicOnly == 0) || (c->innerclass[i].flags & ACC_PUBLIC)))
1616                                 declaredclasscount++;
1617                 }
1618         }
1619
1620         /* Allocate Class[] and check for OOM. */
1621
1622         oa = builtin_anewarray(declaredclasscount, class_java_lang_Class);
1623
1624         if (oa == NULL)
1625                 return NULL;
1626
1627         for (i = 0, pos = 0; i < c->innerclasscount; i++) {
1628                 inner = c->innerclass[i].inner_class;
1629                 outer = c->innerclass[i].outer_class;
1630
1631                 /* Get outer-class.  If the inner-class is not a member class,
1632                    the outer-class is NULL. */
1633
1634                 if (outer.any == NULL)
1635                         continue;
1636
1637                 /* Check if outer_class is a classref or a real class and get
1638                    the class name from the structure. */
1639
1640                 outername = IS_CLASSREF(outer) ? outer.ref->name : outer.cls->name;
1641
1642                 /* Outer class is this class. */
1643
1644                 if ((outername == c->name) &&
1645                         ((publicOnly == 0) || (c->innerclass[i].flags & ACC_PUBLIC))) {
1646
1647                         ic = resolve_classref_or_classinfo_eager(inner, false);
1648
1649                         if (ic == NULL)
1650                                 return NULL;
1651
1652                         if (!(ic->state & CLASS_LINKED))
1653                                 if (!link_class(ic))
1654                                         return NULL;
1655
1656                         LLNI_array_direct(oa, pos++) = (java_object_t *) ic;
1657                 }
1658         }
1659
1660         return oa;
1661 }
1662
1663
1664 /**
1665  * Return an array of declared constructors of the given class.
1666  *
1667  * @param c          class to get the constructors of
1668  * @param publicOnly show only public fields
1669  *
1670  * @return array of java.lang.reflect.Constructor
1671  */
1672 #if defined(ENABLE_JAVASE)
1673 java_handle_objectarray_t *class_get_declaredconstructors(classinfo *c, bool publicOnly)
1674 {
1675         methodinfo*                m;
1676         java_handle_objectarray_t* oa;
1677         int                        count;
1678         int                        index;
1679         int                        i;
1680
1681         /* Determine number of constructors. */
1682
1683         count = 0;
1684
1685         for (i = 0; i < c->methodscount; i++) {
1686                 m = &(c->methods[i]);
1687
1688                 if (((m->flags & ACC_PUBLIC) || (publicOnly == 0)) &&
1689                         (m->name == utf_init))
1690                         count++;
1691         }
1692
1693         /* Create array of constructors. */
1694
1695         oa = builtin_anewarray(count, class_java_lang_reflect_Constructor);
1696
1697         if (oa == NULL)
1698                 return NULL;
1699
1700         /* Get the constructors and store them in the array. */
1701
1702         for (i = 0, index = 0; i < c->methodscount; i++) {
1703                 m = &(c->methods[i]);
1704
1705                 if (((m->flags & ACC_PUBLIC) || (publicOnly == 0)) &&
1706                         (m->name == utf_init)) {
1707                         // Create a java.lang.reflect.Constructor object.
1708
1709                         java_lang_reflect_Constructor rc(m);
1710
1711                         /* Store object into array. */
1712
1713                         array_objectarray_element_set(oa, index, rc.get_handle());
1714                         index++;
1715                 }
1716         }
1717
1718         return oa;
1719 }
1720 #endif
1721
1722
1723 /* class_get_declaredfields ****************************************************
1724
1725    Return an array of declared fields of the given class.
1726
1727    ARGUMENTS:
1728        c ............ class to get the fields of
1729            publicOnly ... show only public fields
1730
1731    RETURN:
1732        array of java.lang.reflect.Field
1733
1734 *******************************************************************************/
1735
1736 #if defined(ENABLE_JAVASE)
1737 java_handle_objectarray_t *class_get_declaredfields(classinfo *c, bool publicOnly)
1738 {
1739         java_handle_objectarray_t *oa;
1740         fieldinfo                 *f;
1741         int                        count;
1742         int                        index;
1743         int                        i;
1744
1745         /* Determine number of fields. */
1746
1747         count = 0;
1748
1749         for (i = 0; i < c->fieldscount; i++)
1750                 if ((c->fields[i].flags & ACC_PUBLIC) || (publicOnly == 0))
1751                         count++;
1752
1753         /* Create array of fields. */
1754
1755         oa = builtin_anewarray(count, class_java_lang_reflect_Field);
1756
1757         if (oa == NULL)
1758                 return NULL;
1759
1760         /* Get the fields and store them in the array. */
1761
1762         for (i = 0, index = 0; i < c->fieldscount; i++) {
1763                 f = &(c->fields[i]);
1764
1765                 if ((f->flags & ACC_PUBLIC) || (publicOnly == 0)) {
1766                         // Create a java.lang.reflect.Field object.
1767
1768                         java_lang_reflect_Field rf(f);
1769
1770                         /* Store object into array. */
1771
1772                         array_objectarray_element_set(oa, index, rf.get_handle());
1773                         index++;
1774                 }
1775         }
1776
1777         return oa;
1778 }
1779 #endif
1780
1781
1782 /* class_get_declaredmethods ***************************************************
1783
1784    Return an array of declared methods of the given class.
1785
1786    ARGUMENTS:
1787        c ............ class to get the methods of
1788            publicOnly ... show only public methods
1789
1790    RETURN:
1791        array of java.lang.reflect.Method
1792
1793 *******************************************************************************/
1794
1795 #if defined(ENABLE_JAVASE)
1796 java_handle_objectarray_t *class_get_declaredmethods(classinfo *c, bool publicOnly)
1797 {
1798         java_handle_objectarray_t *oa;         /* result: array of Method-objects */
1799         methodinfo                *m;     /* the current method to be represented */
1800         int                        count;
1801         int                        index;
1802         int                        i;
1803
1804         /* JOWENN: array classes do not declare methods according to mauve
1805            test.  It should be considered, if we should return to my old
1806            clone method overriding instead of declaring it as a member
1807            function. */
1808
1809         if (class_is_array(c))
1810                 return builtin_anewarray(0, class_java_lang_reflect_Method);
1811
1812         /* Determine number of methods. */
1813
1814         count = 0;
1815
1816         for (i = 0; i < c->methodscount; i++) {
1817                 m = &(c->methods[i]);
1818
1819                 if (((m->flags & ACC_PUBLIC) || (publicOnly == false)) &&
1820                         ((m->name != utf_init) && (m->name != utf_clinit)) &&
1821                         !(m->flags & ACC_MIRANDA))
1822                         count++;
1823         }
1824
1825         /* Create array of methods. */
1826
1827         oa = builtin_anewarray(count, class_java_lang_reflect_Method);
1828
1829         if (oa == NULL)
1830                 return NULL;
1831
1832         /* Get the methods and store them in the array. */
1833
1834         for (i = 0, index = 0; i < c->methodscount; i++) {
1835                 m = &(c->methods[i]);
1836
1837                 if (((m->flags & ACC_PUBLIC) || (publicOnly == false)) && 
1838                         ((m->name != utf_init) && (m->name != utf_clinit)) &&
1839                         !(m->flags & ACC_MIRANDA)) {
1840                         // Create java.lang.reflect.Method object.
1841
1842                         java_lang_reflect_Method rm(m);
1843
1844                         /* Store object into array. */
1845
1846                         array_objectarray_element_set(oa, index, rm.get_handle());
1847                         index++;
1848                 }
1849         }
1850
1851         return oa;
1852 }
1853 #endif
1854
1855
1856 /* class_get_declaringclass ****************************************************
1857
1858    If the class or interface given is a member of another class,
1859    return the declaring class.  For array and primitive classes return
1860    NULL.
1861
1862 *******************************************************************************/
1863
1864 classinfo *class_get_declaringclass(classinfo *c)
1865 {
1866         classref_or_classinfo  cr;
1867         classinfo             *dc;
1868
1869         /* Get declaring class. */
1870
1871         cr = c->declaringclass;
1872
1873         if (cr.any == NULL)
1874                 return NULL;
1875
1876         /* Resolve the class if necessary. */
1877
1878         if (IS_CLASSREF(cr)) {
1879 /*              dc = resolve_classref_eager(cr.ref); */
1880                 dc = resolve_classref_or_classinfo_eager(cr, true);
1881
1882                 if (dc == NULL)
1883                         return NULL;
1884
1885                 /* Store the resolved class in the class structure. */
1886
1887                 cr.cls = dc;
1888         }
1889
1890         dc = cr.cls;
1891
1892         return dc;
1893 }
1894
1895
1896 /* class_get_enclosingclass ****************************************************
1897
1898    Return the enclosing class for the given class.
1899
1900 *******************************************************************************/
1901
1902 classinfo *class_get_enclosingclass(classinfo *c)
1903 {
1904         classref_or_classinfo  cr;
1905         classinfo             *ec;
1906
1907         /* Get enclosing class. */
1908
1909         cr = c->enclosingclass;
1910
1911         if (cr.any == NULL)
1912                 return NULL;
1913
1914         /* Resolve the class if necessary. */
1915
1916         if (IS_CLASSREF(cr)) {
1917 /*              ec = resolve_classref_eager(cr.ref); */
1918                 ec = resolve_classref_or_classinfo_eager(cr, true);
1919
1920                 if (ec == NULL)
1921                         return NULL;
1922
1923                 /* Store the resolved class in the class structure. */
1924
1925                 cr.cls = ec;
1926         }
1927
1928         ec = cr.cls;
1929
1930         return ec;
1931 }
1932
1933
1934 /**
1935  * Return the enclosing constructor as java.lang.reflect.Constructor
1936  * object for the given class.
1937  *
1938  * @param c class to return the enclosing constructor for
1939  *
1940  * @return java.lang.reflect.Constructor object of the enclosing
1941  * constructor
1942  */
1943 #if defined(ENABLE_JAVASE)
1944 java_handle_t* class_get_enclosingconstructor(classinfo *c)
1945 {
1946         methodinfo*    m;
1947
1948         m = class_get_enclosingmethod_raw(c);
1949
1950         if (m == NULL)
1951                 return NULL;
1952
1953         /* Check for <init>. */
1954
1955         if (m->name != utf_init)
1956                 return NULL;
1957
1958         // Create a java.lang.reflect.Constructor object.
1959
1960         java_lang_reflect_Constructor rc(m);
1961
1962         return rc.get_handle();
1963 }
1964 #endif
1965
1966
1967 /* class_get_enclosingmethod ***************************************************
1968
1969    Return the enclosing method for the given class.
1970
1971    IN:
1972        c ... class to return the enclosing method for
1973
1974    RETURN:
1975        methodinfo of the enclosing method
1976
1977 *******************************************************************************/
1978
1979 methodinfo *class_get_enclosingmethod_raw(classinfo *c)
1980 {
1981         constant_nameandtype *cn;
1982         classinfo            *ec;
1983         methodinfo           *m;
1984
1985         /* get enclosing class and method */
1986
1987         ec = class_get_enclosingclass(c);
1988         cn = c->enclosingmethod;
1989
1990         /* check for enclosing class and method */
1991
1992         if (ec == NULL)
1993                 return NULL;
1994
1995         if (cn == NULL)
1996                 return NULL;
1997
1998         /* find method in enclosing class */
1999
2000         m = class_findmethod(ec, cn->name, cn->descriptor);
2001
2002         if (m == NULL) {
2003                 exceptions_throw_internalerror("Enclosing method doesn't exist");
2004                 return NULL;
2005         }
2006
2007         return m;
2008 }
2009
2010
2011 /**
2012  * Return the enclosing method as java.lang.reflect.Method object for
2013  * the given class.
2014  *
2015  * @param c class to return the enclosing method for
2016  *
2017  * @return java.lang.reflect.Method object of the enclosing method
2018  */
2019 #if defined(ENABLE_JAVASE)
2020 java_handle_t* class_get_enclosingmethod(classinfo *c)
2021 {
2022         methodinfo*    m;
2023
2024         m = class_get_enclosingmethod_raw(c);
2025
2026         if (m == NULL)
2027                 return NULL;
2028
2029         /* check for <init> */
2030
2031         if (m->name == utf_init)
2032                 return NULL;
2033
2034         // Create a java.lang.reflect.Method object.
2035
2036         java_lang_reflect_Method rm(m);
2037
2038         return rm.get_handle();
2039 }
2040 #endif
2041
2042
2043 /* class_get_interfaces ********************************************************
2044
2045    Return an array of interfaces of the given class.
2046
2047 *******************************************************************************/
2048
2049 java_handle_objectarray_t *class_get_interfaces(classinfo *c)
2050 {
2051         classinfo                 *ic;
2052         java_handle_objectarray_t *oa;
2053         u4                         i;
2054
2055         if (!(c->state & CLASS_LINKED))
2056                 if (!link_class(c))
2057                         return NULL;
2058
2059         oa = builtin_anewarray(c->interfacescount, class_java_lang_Class);
2060
2061         if (oa == NULL)
2062                 return NULL;
2063
2064         for (i = 0; i < c->interfacescount; i++) {
2065                 ic = c->interfaces[i];
2066
2067                 LLNI_array_direct(oa, i) = (java_object_t *) ic;
2068         }
2069
2070         return oa;
2071 }
2072
2073
2074 /* class_get_annotations *******************************************************
2075
2076    Get the unparsed declared annotations in a byte array
2077    of the given class.
2078
2079    IN:
2080        c........the class of which the annotations should be returned
2081
2082    RETURN VALUE:
2083        The unparsed declared annotations in a byte array
2084        (or NULL if there aren't any).
2085
2086 *******************************************************************************/
2087
2088 java_handle_bytearray_t *class_get_annotations(classinfo *c)
2089 {
2090 #if defined(ENABLE_ANNOTATIONS)
2091         java_handle_t *annotations; /* unparsed annotations */
2092
2093         LLNI_classinfo_field_get(c, annotations, annotations);
2094
2095         return (java_handle_bytearray_t*)annotations;
2096 #else
2097         return NULL;
2098 #endif
2099 }
2100
2101
2102 /* class_get_modifiers *********************************************************
2103
2104    Get the modifier flags of the given class.
2105
2106    IN:
2107        c....the class of which the modifier flags should be returned
2108            ignoreInnerClassesAttrib
2109    RETURN VALUE:
2110        modifier flags
2111
2112 *******************************************************************************/
2113
2114 int32_t class_get_modifiers(classinfo *c, bool ignoreInnerClassesAttrib)
2115 {
2116         classref_or_classinfo  inner;
2117         classref_or_classinfo  outer;
2118         utf                   *innername;
2119         int                    i;
2120
2121         if (!ignoreInnerClassesAttrib && (c->innerclasscount != 0)) {
2122                 /* search for passed class as inner class */
2123
2124                 for (i = 0; i < c->innerclasscount; i++) {
2125                         inner = c->innerclass[i].inner_class;
2126                         outer = c->innerclass[i].outer_class;
2127
2128                         /* Check if inner is a classref or a real class and get
2129                the name of the structure */
2130
2131                         innername = IS_CLASSREF(inner) ? inner.ref->name : inner.cls->name;
2132
2133                         /* innerclass is this class */
2134
2135                         if (innername == c->name) {
2136                                 /* has the class actually an outer class? */
2137
2138                                 if (outer.any)
2139                                         /* return flags got from the outer class file */
2140                                         return c->innerclass[i].flags & ACC_CLASS_REFLECT_MASK;
2141                                 else
2142                                         return c->flags & ACC_CLASS_REFLECT_MASK;
2143                         }
2144                 }
2145         }
2146
2147         /* passed class is no inner class or it was not requested */
2148
2149         return c->flags & ACC_CLASS_REFLECT_MASK;
2150 }
2151
2152
2153 /* class_get_signature *********************************************************
2154
2155    Return the signature of the given class.  For array and primitive
2156    classes return NULL.
2157
2158 *******************************************************************************/
2159
2160 #if defined(ENABLE_JAVASE)
2161 utf *class_get_signature(classinfo *c)
2162 {
2163         /* For array and primitive classes return NULL. */
2164
2165         if (class_is_array(c) || class_is_primitive(c))
2166                 return NULL;
2167
2168         return c->signature;
2169 }
2170 #endif
2171
2172
2173 /* class_printflags ************************************************************
2174
2175    Prints flags of a class.
2176
2177 *******************************************************************************/
2178
2179 #if !defined(NDEBUG)
2180 void class_printflags(classinfo *c)
2181 {
2182         if (c == NULL) {
2183                 printf("NULL");
2184                 return;
2185         }
2186
2187         if (c->flags & ACC_PUBLIC)       printf(" PUBLIC");
2188         if (c->flags & ACC_PRIVATE)      printf(" PRIVATE");
2189         if (c->flags & ACC_PROTECTED)    printf(" PROTECTED");
2190         if (c->flags & ACC_STATIC)       printf(" STATIC");
2191         if (c->flags & ACC_FINAL)        printf(" FINAL");
2192         if (c->flags & ACC_SYNCHRONIZED) printf(" SYNCHRONIZED");
2193         if (c->flags & ACC_VOLATILE)     printf(" VOLATILE");
2194         if (c->flags & ACC_TRANSIENT)    printf(" TRANSIENT");
2195         if (c->flags & ACC_NATIVE)       printf(" NATIVE");
2196         if (c->flags & ACC_INTERFACE)    printf(" INTERFACE");
2197         if (c->flags & ACC_ABSTRACT)     printf(" ABSTRACT");
2198 }
2199 #endif
2200
2201
2202 /* class_print *****************************************************************
2203
2204    Prints classname plus flags.
2205
2206 *******************************************************************************/
2207
2208 #if !defined(NDEBUG)
2209 void class_print(classinfo *c)
2210 {
2211         if (c == NULL) {
2212                 printf("NULL");
2213                 return;
2214         }
2215
2216         utf_display_printable_ascii(c->name);
2217         class_printflags(c);
2218 }
2219 #endif
2220
2221
2222 /* class_classref_print ********************************************************
2223
2224    Prints classname plus referer class.
2225
2226 *******************************************************************************/
2227
2228 #if !defined(NDEBUG)
2229 void class_classref_print(constant_classref *cr)
2230 {
2231         if (cr == NULL) {
2232                 printf("NULL");
2233                 return;
2234         }
2235
2236         utf_display_printable_ascii(cr->name);
2237         printf("(ref.by ");
2238         if (cr->referer)
2239                 class_print(cr->referer);
2240         else
2241                 printf("NULL");
2242         printf(")");
2243 }
2244 #endif
2245
2246
2247 /* class_println ***************************************************************
2248
2249    Prints classname plus flags and new line.
2250
2251 *******************************************************************************/
2252
2253 #if !defined(NDEBUG)
2254 void class_println(classinfo *c)
2255 {
2256         class_print(c);
2257         printf("\n");
2258 }
2259 #endif
2260
2261
2262 /* class_classref_println ******************************************************
2263
2264    Prints classname plus referer class and new line.
2265
2266 *******************************************************************************/
2267
2268 #if !defined(NDEBUG)
2269 void class_classref_println(constant_classref *cr)
2270 {
2271         class_classref_print(cr);
2272         printf("\n");
2273 }
2274 #endif
2275
2276
2277 /* class_classref_or_classinfo_print *******************************************
2278
2279    Prints classname plus referer class.
2280
2281 *******************************************************************************/
2282
2283 #if !defined(NDEBUG)
2284 void class_classref_or_classinfo_print(classref_or_classinfo c)
2285 {
2286         if (c.any == NULL) {
2287                 printf("(classref_or_classinfo) NULL");
2288                 return;
2289         }
2290         if (IS_CLASSREF(c))
2291                 class_classref_print(c.ref);
2292         else
2293                 class_print(c.cls);
2294 }
2295 #endif
2296
2297
2298 /* class_classref_or_classinfo_println *****************************************
2299
2300    Prints classname plus referer class and a newline.
2301
2302 *******************************************************************************/
2303
2304 #if !defined(NDEBUG)
2305 void class_classref_or_classinfo_println(classref_or_classinfo c)
2306 {
2307         class_classref_or_classinfo_print(c);
2308         printf("\n");
2309 }
2310 #endif
2311
2312
2313 /* class_showconstantpool ******************************************************
2314
2315    Dump the constant pool of the given class to stdout.
2316
2317 *******************************************************************************/
2318
2319 #if !defined(NDEBUG)
2320 void class_showconstantpool (classinfo *c) 
2321 {
2322         u4 i;
2323         void* e;
2324
2325         printf ("---- dump of constant pool ----\n");
2326
2327         for (i=0; i<c->cpcount; i++) {
2328                 printf ("#%d:  ", (int) i);
2329                 
2330                 e = c -> cpinfos [i];
2331                 if (e) {
2332                         
2333                         switch (c -> cptags [i]) {
2334                         case CONSTANT_Class:
2335                                 printf ("Classreference -> ");
2336                                 utf_display_printable_ascii ( ((constant_classref*)e) -> name );
2337                                 break;
2338                         case CONSTANT_Fieldref:
2339                                 printf ("Fieldref -> ");
2340                                 field_fieldref_print((constant_FMIref *) e);
2341                                 break;
2342                         case CONSTANT_Methodref:
2343                                 printf ("Methodref -> ");
2344                                 method_methodref_print((constant_FMIref *) e);
2345                                 break;
2346                         case CONSTANT_InterfaceMethodref:
2347                                 printf ("InterfaceMethod -> ");
2348                                 method_methodref_print((constant_FMIref *) e);
2349                                 break;
2350                         case CONSTANT_String:
2351                                 printf ("String -> ");
2352                                 utf_display_printable_ascii ((utf*) e);
2353                                 break;
2354                         case CONSTANT_Integer:
2355                                 printf ("Integer -> %d", (int) ( ((constant_integer*)e) -> value) );
2356                                 break;
2357                         case CONSTANT_Float:
2358                                 printf ("Float -> %f", ((constant_float*)e) -> value);
2359                                 break;
2360                         case CONSTANT_Double:
2361                                 printf ("Double -> %f", ((constant_double*)e) -> value);
2362                                 break;
2363                         case CONSTANT_Long:
2364                                 printf ("Long -> %ld", (long int) ((constant_long*)e) -> value);
2365                                 break;
2366                         case CONSTANT_NameAndType:
2367                                 {
2368                                         constant_nameandtype *cnt = (constant_nameandtype *) e;
2369                                         printf ("NameAndType: ");
2370                                         utf_display_printable_ascii (cnt->name);
2371                                         printf (" ");
2372                                         utf_display_printable_ascii (cnt->descriptor);
2373                                 }
2374                                 break;
2375                         case CONSTANT_Utf8:
2376                                 printf ("Utf8 -> ");
2377                                 utf_display_printable_ascii ((utf*) e);
2378                                 break;
2379                         default: 
2380                                 log_text("Invalid type of ConstantPool-Entry");
2381                                 assert(0);
2382                         }
2383                 }
2384
2385                 printf ("\n");
2386         }
2387 }
2388 #endif /* !defined(NDEBUG) */
2389
2390
2391 /* class_showmethods ***********************************************************
2392
2393    Dump info about the fields and methods of the given class to stdout.
2394
2395 *******************************************************************************/
2396
2397 #if !defined(NDEBUG)
2398 void class_showmethods (classinfo *c)
2399 {
2400         s4 i;
2401         
2402         printf("--------- Fields and Methods ----------------\n");
2403         printf("Flags: ");
2404         class_printflags(c);
2405         printf("\n");
2406
2407         printf("This: ");
2408         utf_display_printable_ascii(c->name);
2409         printf("\n");
2410
2411         if (c->super) {
2412                 printf("Super: ");
2413                 utf_display_printable_ascii(c->super->name);
2414                 printf ("\n");
2415         }
2416
2417         printf("Index: %d\n", c->index);
2418         
2419         printf("Interfaces:\n");        
2420         for (i = 0; i < c->interfacescount; i++) {
2421                 printf("   ");
2422                 utf_display_printable_ascii(c->interfaces[i]->name);
2423                 printf (" (%d)\n", c->interfaces[i]->index);
2424         }
2425
2426         printf("Fields:\n");
2427         for (i = 0; i < c->fieldscount; i++)
2428                 field_println(&(c->fields[i]));
2429
2430         printf("Methods:\n");
2431         for (i = 0; i < c->methodscount; i++) {
2432                 methodinfo *m = &(c->methods[i]);
2433
2434                 if (!(m->flags & ACC_STATIC))
2435                         printf("vftblindex: %d   ", m->vftblindex);
2436
2437                 method_println(m);
2438         }
2439
2440         printf ("Virtual function table:\n");
2441         for (i = 0; i < c->vftbl->vftbllength; i++)
2442                 printf ("entry: %d,  %ld\n", i, (long int) (c->vftbl->table[i]));
2443 }
2444 #endif /* !defined(NDEBUG) */
2445
2446
2447 /*
2448  * These are local overrides for various environment variables in Emacs.
2449  * Please do not remove this and leave it at the end of the file, where
2450  * Emacs will automagically detect them.
2451  * ---------------------------------------------------------------------
2452  * Local variables:
2453  * mode: c
2454  * indent-tabs-mode: t
2455  * c-basic-offset: 4
2456  * tab-width: 4
2457  * End:
2458  * vim:noexpandtab:sw=4:ts=4:
2459  */