Update copyright.
[official-gcc.git] / libjava / defineclass.cc
blob001fa0131f025ac7879c7939d10c34cfeb29096b
1 // defineclass.cc - defining a class from .class format.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
11 /*
12 Author: Kresten Krab Thorup <krab@gnu.org>
14 Written using the online versions of Java Language Specification (1st
15 ed.) and The Java Virtual Machine Specification (2nd ed.).
17 Future work may include reading (and handling) attributes which are
18 currently being ignored ("InnerClasses", "LineNumber", etc...).
21 #include <config.h>
23 #include <java-interp.h>
25 #include <stdlib.h>
26 #include <java-cpool.h>
27 #include <gcj/cni.h>
29 #include <java/lang/Class.h>
30 #include <java/lang/Float.h>
31 #include <java/lang/Double.h>
32 #include <java/lang/Character.h>
33 #include <java/lang/LinkageError.h>
34 #include <java/lang/InternalError.h>
35 #include <java/lang/ClassFormatError.h>
36 #include <java/lang/NoClassDefFoundError.h>
37 #include <java/lang/ClassCircularityError.h>
38 #include <java/lang/IncompatibleClassChangeError.h>
39 #include <java/lang/reflect/Modifier.h>
41 using namespace gcj;
43 #ifdef INTERPRETER
45 // these go in some separate functions, to avoid having _Jv_InitClass
46 // inserted all over the place.
47 static void throw_internal_error (char *msg)
48 __attribute__ ((__noreturn__));
49 static void throw_no_class_def_found_error (jstring msg)
50 __attribute__ ((__noreturn__));
51 static void throw_no_class_def_found_error (char *msg)
52 __attribute__ ((__noreturn__));
53 static void throw_class_format_error (jstring msg)
54 __attribute__ ((__noreturn__));
55 static void throw_incompatible_class_change_error (jstring msg)
56 __attribute__ ((__noreturn__));
57 static void throw_class_circularity_error (jstring msg)
58 __attribute__ ((__noreturn__));
60 /**
61 * We define class reading using a class. It is practical, since then
62 * the entire class-reader can be a friend of class Class (it needs to
63 * write all it's different structures); but also because this makes it
64 * easy to make class definition reentrant, and thus two threads can be
65 * defining classes at the same time. This class (_Jv_ClassReader) is
66 * never exposed outside this file, so we don't have to worry about
67 * public or private members here.
70 struct _Jv_ClassReader {
72 // do verification? Currently, there is no option to disable this.
73 // This flag just controls the verificaiton done by the class loader;
74 // i.e., checking the integrity of the constant pool; and it is
75 // allways on. You always want this as far as I can see, but it also
76 // controls weither identifiers and type descriptors/signatures are
77 // verified as legal. This could be somewhat more expensive since it
78 // will call Characher.isJavaIdentifier{Start,Part} for each character
79 // in any identifier (field name or method name) it comes by. Thus,
80 // it might be useful to turn off this verification for classes that
81 // come from a trusted source. However, for GCJ, trusted classes are
82 // most likely to be linked in.
84 bool verify;
86 // input data.
87 unsigned char *bytes;
88 int len;
90 // current input position
91 int pos;
93 // the constant pool data
94 int pool_count;
95 unsigned char *tags;
96 unsigned int *offsets;
98 // the class to define (see java-interp.h)
99 _Jv_InterpClass *def;
101 /* check that the given number of input bytes are available */
102 inline void check (int num)
104 if (pos + num > len)
105 throw_class_format_error ("Premature end of data");
108 /* skip a given number of bytes in input */
109 inline void skip (int num)
111 check (num);
112 pos += num;
115 /* read an unsignend 1-byte unit */
116 inline static jint get1u (unsigned char* bytes)
118 return bytes[0];
121 /* read an unsigned 1-byte unit */
122 inline jint read1u ()
124 skip (1);
125 return get1u (bytes+pos-1);
128 /* read an unsigned 2-byte unit */
129 inline static jint get2u (unsigned char *bytes)
131 return (((jint)bytes[0]) << 8) | ((jint)bytes[1]);
134 /* read an unsigned 2-byte unit */
135 inline jint read2u ()
137 skip (2);
138 return get2u (bytes+pos-2);
141 /* read a 4-byte unit */
142 static jint get4 (unsigned char *bytes)
144 return (((jint)bytes[0]) << 24)
145 | (((jint)bytes[1]) << 16)
146 | (((jint)bytes[2]) << 8)
147 | (((jint)bytes[3]) << 0);
150 /* read a 4-byte unit, (we don't do that quite so often) */
151 inline jint read4 ()
153 skip (4);
154 return get4 (bytes+pos-4);
157 /* read a 8-byte unit */
158 static jlong get8 (unsigned char* bytes)
160 return (((jlong)bytes[0]) << 56)
161 | (((jlong)bytes[1]) << 48)
162 | (((jlong)bytes[2]) << 40)
163 | (((jlong)bytes[3]) << 32)
164 | (((jlong)bytes[4]) << 24)
165 | (((jlong)bytes[5]) << 16)
166 | (((jlong)bytes[6]) << 8)
167 | (((jlong)bytes[7]) << 0);
170 /* read a 8-byte unit */
171 inline jlong read8 ()
173 skip (8);
174 return get8 (bytes+pos-8);
177 inline void check_tag (int index, char expected_tag)
179 if (index < 0
180 || index > pool_count
181 || tags[index] != expected_tag)
182 throw_class_format_error ("erroneous constant pool tag");
185 inline void verify_identifier (_Jv_Utf8Const* name)
187 if (! _Jv_VerifyIdentifier (name))
188 throw_class_format_error ("erroneous identifier");
191 inline void verify_classname (unsigned char* ptr, _Jv_ushort length)
193 if (! _Jv_VerifyClassName (ptr, length))
194 throw_class_format_error ("erroneous class name");
197 inline void verify_classname (_Jv_Utf8Const *name)
199 if (! _Jv_VerifyClassName (name))
200 throw_class_format_error ("erroneous class name");
203 inline void verify_field_signature (_Jv_Utf8Const *sig)
205 if (! _Jv_VerifyFieldSignature (sig))
206 throw_class_format_error ("erroneous type descriptor");
209 inline void verify_method_signature (_Jv_Utf8Const *sig)
211 if (! _Jv_VerifyMethodSignature (sig))
212 throw_class_format_error ("erroneous type descriptor");
215 _Jv_ClassReader (jclass klass, jbyteArray data, jint offset, jint length)
217 if (klass == 0 || length < 0 || offset+length > data->length)
218 throw_internal_error ("arguments to _Jv_DefineClass");
220 verify = true;
221 bytes = (unsigned char*) (elements (data)+offset);
222 len = length;
223 pos = 0;
224 def = (_Jv_InterpClass*) klass;
227 /** and here goes the parser members defined out-of-line */
228 void parse ();
229 void read_constpool ();
230 void prepare_pool_entry (int index, unsigned char tag);
231 void read_fields ();
232 void read_methods ();
233 void read_one_class_attribute ();
234 void read_one_method_attribute (int method);
235 void read_one_code_attribute (int method);
236 void read_one_field_attribute (int field);
237 void throw_class_format_error (char *msg);
239 /** check an utf8 entry, without creating a Utf8Const object */
240 bool is_attribute_name (int index, char *name);
242 /** here goes the class-loader members defined out-of-line */
243 void handleConstantPool ();
244 void handleClassBegin (int, int, int);
245 void handleInterfacesBegin (int);
246 void handleInterface (int, int);
247 void handleFieldsBegin (int);
248 void handleField (int, int, int, int);
249 void handleFieldsEnd ();
250 void handleConstantValueAttribute (int,int);
251 void handleMethodsBegin (int);
252 void handleMethod (int, int, int, int);
253 void handleMethodsEnd ();
254 void handleCodeAttribute (int, int, int, int, int, int);
255 void handleExceptionTableEntry (int, int, int, int, int, int);
257 void checkExtends (jclass sub, jclass super);
258 void checkImplements (jclass sub, jclass super);
261 * FIXME: we should keep a hash table of utf8-strings, since many will
262 * be the same. It's a little tricky, however, because the hash table
263 * needs to interact gracefully with the garbage collector. Much
264 * memory is to be saved by this, however! perhaps the improvement
265 * could be implemented in prims.cc (_Jv_makeUtf8Const), since it
266 * computes the hash value anyway.
270 void
271 _Jv_DefineClass (jclass klass, jbyteArray data, jint offset, jint length)
273 _Jv_ClassReader reader (klass, data, offset, length);
274 reader.parse();
276 /* that's it! */
280 /** This section defines the parsing/scanning of the class data */
282 void
283 _Jv_ClassReader::parse ()
285 int magic = read4 ();
287 /* FIXME: Decide which range of version numbers to allow */
289 /* int minor_version = */ read2u ();
290 /* int major_verson = */ read2u ();
292 if (magic != (int) 0xCAFEBABE)
293 throw_class_format_error ("bad magic number");
295 pool_count = read2u ();
297 read_constpool ();
299 int access_flags = read2u ();
300 int this_class = read2u ();
301 int super_class = read2u ();
303 check_tag (this_class, JV_CONSTANT_Class);
304 if (super_class != 0)
305 check_tag (super_class, JV_CONSTANT_Class);
307 handleClassBegin (access_flags, this_class, super_class);
309 int interfaces_count = read2u ();
311 handleInterfacesBegin (interfaces_count);
313 for (int i = 0; i < interfaces_count; i++)
315 int iface = read2u ();
316 check_tag (iface, JV_CONSTANT_Class);
317 handleInterface (i, iface);
320 read_fields ();
321 read_methods ();
323 int attributes_count = read2u ();
325 for (int i = 0; i < attributes_count; i++)
327 read_one_class_attribute ();
330 if (pos != len)
331 throw_class_format_error ("unused data before end of file");
333 // tell everyone we're done.
334 def->state = JV_STATE_LOADED;
335 def->notifyAll ();
339 void _Jv_ClassReader::read_constpool ()
341 tags = (unsigned char*) _Jv_AllocBytes (pool_count);
342 offsets = (unsigned int *) _Jv_AllocBytes (sizeof (int)
343 * pool_count) ;
345 /** first, we scan the constant pool, collecting tags and offsets */
346 tags[0] = JV_CONSTANT_Undefined;
347 offsets[0] = pos;
348 for (int c = 1; c < pool_count; c++)
350 tags[c] = read1u ();
351 offsets[c] = pos;
353 switch (tags[c])
355 case JV_CONSTANT_String:
356 case JV_CONSTANT_Class:
357 skip (2);
358 break;
360 case JV_CONSTANT_Fieldref:
361 case JV_CONSTANT_Methodref:
362 case JV_CONSTANT_InterfaceMethodref:
363 case JV_CONSTANT_NameAndType:
364 case JV_CONSTANT_Integer:
365 case JV_CONSTANT_Float:
366 skip (4);
367 break;
369 case JV_CONSTANT_Double:
370 case JV_CONSTANT_Long:
371 skip (8);
372 tags[++c] = JV_CONSTANT_Undefined;
373 break;
375 case JV_CONSTANT_Utf8:
377 int len = read2u ();
378 skip (len);
380 break;
382 case JV_CONSTANT_Unicode:
383 throw_class_format_error ("unicode not supported");
384 break;
386 default:
387 throw_class_format_error ("erroneous constant pool tag");
391 handleConstantPool ();
395 void _Jv_ClassReader::read_fields ()
397 int fields_count = read2u ();
398 handleFieldsBegin (fields_count);
400 for (int i = 0; i < fields_count; i++)
402 int access_flags = read2u ();
403 int name_index = read2u ();
404 int descriptor_index = read2u ();
405 int attributes_count = read2u ();
407 check_tag (name_index, JV_CONSTANT_Utf8);
408 prepare_pool_entry (name_index, JV_CONSTANT_Utf8);
410 check_tag (descriptor_index, JV_CONSTANT_Utf8);
411 prepare_pool_entry (descriptor_index, JV_CONSTANT_Utf8);
413 handleField (i, access_flags, name_index, descriptor_index);
415 for (int j = 0; j < attributes_count; j++)
417 read_one_field_attribute (i);
421 handleFieldsEnd ();
424 bool
425 _Jv_ClassReader::is_attribute_name (int index, char *name)
427 check_tag (index, JV_CONSTANT_Utf8);
428 int len = get2u (bytes+offsets[index]);
429 if (len != (int) strlen (name))
430 return false;
431 else
432 return !memcmp (bytes+offsets[index]+2, name, len);
435 void _Jv_ClassReader::read_one_field_attribute (int field_index)
437 int name = read2u ();
438 int length = read4 ();
440 if (is_attribute_name (name, "ConstantValue"))
442 int cv = read2u ();
444 if (cv < pool_count
445 && cv > 0
446 && (tags[cv] == JV_CONSTANT_Integer
447 || tags[cv] == JV_CONSTANT_Float
448 || tags[cv] == JV_CONSTANT_Long
449 || tags[cv] == JV_CONSTANT_Double
450 || tags[cv] == JV_CONSTANT_String))
452 handleConstantValueAttribute (field_index, cv);
454 else
456 throw_class_format_error ("erroneous ConstantValue attribute");
459 if (length != 2)
460 throw_class_format_error ("erroneous ConstantValue attribute");
463 else
465 skip (length);
469 void _Jv_ClassReader::read_methods ()
471 int methods_count = read2u ();
473 handleMethodsBegin (methods_count);
475 for (int i = 0; i < methods_count; i++)
477 int access_flags = read2u ();
478 int name_index = read2u ();
479 int descriptor_index = read2u ();
480 int attributes_count = read2u ();
482 check_tag (name_index, JV_CONSTANT_Utf8);
483 prepare_pool_entry (descriptor_index, JV_CONSTANT_Utf8);
485 check_tag (name_index, JV_CONSTANT_Utf8);
486 prepare_pool_entry (descriptor_index, JV_CONSTANT_Utf8);
488 handleMethod (i, access_flags, name_index,
489 descriptor_index);
491 for (int j = 0; j < attributes_count; j++)
493 read_one_method_attribute (i);
497 handleMethodsEnd ();
500 void _Jv_ClassReader::read_one_method_attribute (int method_index)
502 int name = read2u ();
503 int length = read4 ();
505 if (is_attribute_name (name, "Exceptions"))
507 _Jv_Method *method = reinterpret_cast<_Jv_Method *>
508 (&def->methods[method_index]);
509 if (method->throws != NULL)
510 throw_class_format_error ("only one Exceptions attribute allowed per method");
512 int num_exceptions = read2u ();
513 // We use malloc here because the GC won't scan the method
514 // objects. FIXME this means a memory leak if we GC a class.
515 // (Currently we never do.)
516 _Jv_Utf8Const **exceptions =
517 (_Jv_Utf8Const **) _Jv_Malloc ((num_exceptions + 1) * sizeof (_Jv_Utf8Const *));
519 int out = 0;
520 _Jv_word *pool_data = def->constants.data;
521 for (int i = 0; i < num_exceptions; ++i)
525 int ndx = read2u ();
526 // JLS 2nd Ed. 4.7.5 requires that the tag not be 0.
527 if (ndx != 0)
529 check_tag (ndx, JV_CONSTANT_Class);
530 exceptions[out++] = pool_data[ndx].utf8;
533 catch (java::lang::Throwable *exc)
535 _Jv_Free (exceptions);
536 throw exc;
539 exceptions[out] = NULL;
540 method->throws = exceptions;
543 else if (is_attribute_name (name, "Code"))
545 int start_off = pos;
546 int max_stack = read2u ();
547 int max_locals = read2u ();
548 int code_length = read4 ();
550 int code_start = pos;
551 skip (code_length);
552 int exception_table_length = read2u ();
554 handleCodeAttribute (method_index,
555 max_stack, max_locals,
556 code_start, code_length,
557 exception_table_length);
560 for (int i = 0; i < exception_table_length; i++)
562 int start_pc = read2u ();
563 int end_pc = read2u ();
564 int handler_pc = read2u ();
565 int catch_type = read2u ();
567 if (start_pc > end_pc
568 || start_pc < 0
569 // END_PC can be equal to CODE_LENGTH.
570 // See JVM Spec 4.7.4.
571 || end_pc > code_length
572 || handler_pc >= code_length)
573 throw_class_format_error ("erroneous exception handler info");
575 if (! (tags[catch_type] == JV_CONSTANT_Class
576 || tags[catch_type] == 0))
578 throw_class_format_error ("erroneous exception handler info");
581 handleExceptionTableEntry (method_index,
583 start_pc,
584 end_pc,
585 handler_pc,
586 catch_type);
590 int attributes_count = read2u ();
592 for (int i = 0; i < attributes_count; i++)
594 read_one_code_attribute (method_index);
597 if ((pos - start_off) != length)
598 throw_class_format_error ("code attribute too short");
601 else
603 /* ignore unknown attributes */
604 skip (length);
608 void _Jv_ClassReader::read_one_code_attribute (int /*method*/)
610 /* ignore for now, ... later we may want to pick up
611 line number information, for debugging purposes;
612 in fact, the whole debugger issue is open! */
614 /* int name = */ read2u ();
615 int length = read4 ();
616 skip (length);
620 void _Jv_ClassReader::read_one_class_attribute ()
622 /* we also ignore the class attributes, ...
623 some day we'll add inner-classes support. */
625 /* int name = */ read2u ();
626 int length = read4 ();
627 skip (length);
633 /* this section defines the semantic actions of the parser */
635 void _Jv_ClassReader::handleConstantPool ()
637 /** now, we actually define the class' constant pool */
639 // the pool is scanned explicitly by the collector
640 jbyte *pool_tags = (jbyte*) _Jv_AllocBytes (pool_count);
641 _Jv_word *pool_data
642 = (_Jv_word*) _Jv_AllocBytes (pool_count * sizeof (_Jv_word));
644 def->constants.tags = pool_tags;
645 def->constants.data = pool_data;
646 def->constants.size = pool_count;
648 // Here we make a pass to collect the strings! We do this, because
649 // internally in the GCJ runtime, classes are encoded with .'s not /'s.
650 // Therefore, we first collect the strings, and then translate the rest
651 // of the utf8-entries (thus not representing strings) from /-notation
652 // to .-notation.
653 for (int i = 1; i < pool_count; i++)
655 if (tags[i] == JV_CONSTANT_String)
657 unsigned char* str_data = bytes + offsets [i];
658 int utf_index = get2u (str_data);
659 check_tag (utf_index, JV_CONSTANT_Utf8);
660 unsigned char *utf_data = bytes + offsets[utf_index];
661 int len = get2u (utf_data);
662 pool_data[i].utf8 = _Jv_makeUtf8Const ((char*)(utf_data+2), len);
663 pool_tags[i] = JV_CONSTANT_String;
665 else
667 pool_tags[i] = JV_CONSTANT_Undefined;
671 // and now, we scan everything else but strings & utf8-entries. This
672 // leaves out those utf8-entries which are not used; which will be left
673 // with a tag of JV_CONSTANT_Undefined in the class definition.
674 for (int index = 1; index < pool_count; index++)
676 switch (tags[index])
678 case JV_CONSTANT_Undefined:
679 case JV_CONSTANT_String:
680 case JV_CONSTANT_Utf8:
681 continue;
683 default:
684 prepare_pool_entry (index, tags[index]);
690 /* this is a recursive procedure, which will prepare pool entries as needed.
691 Which is how we avoid initializing those entries which go unused. */
692 void
693 _Jv_ClassReader::prepare_pool_entry (int index, unsigned char this_tag)
695 /* these two, pool_data and pool_tags, point into the class
696 structure we are currently defining */
698 unsigned char *pool_tags = (unsigned char*) def->constants.tags;
699 _Jv_word *pool_data = def->constants.data;
701 /* this entry was already prepared */
702 if (pool_tags[index] == this_tag)
703 return;
705 /* this_data points to the constant-pool information for the current
706 constant-pool entry */
708 unsigned char *this_data = bytes + offsets[index];
710 switch (this_tag)
712 case JV_CONSTANT_Utf8:
714 // If we came here, it is because some other tag needs this
715 // utf8-entry for type information! Thus, we translate /'s to .'s in
716 // order to accomondate gcj's internal representation.
718 int len = get2u (this_data);
719 char *buffer = (char*) __builtin_alloca (len);
720 char *s = ((char*) this_data)+2;
722 /* FIXME: avoid using a buffer here */
723 for (int i = 0; i < len; i++)
725 if (s[i] == '/')
726 buffer[i] = '.';
727 else
728 buffer[i] = (char) s[i];
731 pool_data[index].utf8 = _Jv_makeUtf8Const (buffer, len);
732 pool_tags[index] = JV_CONSTANT_Utf8;
734 break;
736 case JV_CONSTANT_Class:
738 int utf_index = get2u (this_data);
739 check_tag (utf_index, JV_CONSTANT_Utf8);
740 prepare_pool_entry (utf_index, JV_CONSTANT_Utf8);
742 if (verify)
743 verify_classname (pool_data[utf_index].utf8);
745 pool_data[index].utf8 = pool_data[utf_index].utf8;
746 pool_tags[index] = JV_CONSTANT_Class;
748 break;
750 case JV_CONSTANT_String:
751 // already handled before...
752 break;
754 case JV_CONSTANT_Fieldref:
755 case JV_CONSTANT_Methodref:
756 case JV_CONSTANT_InterfaceMethodref:
758 int class_index = get2u (this_data);
759 int nat_index = get2u (this_data+2);
761 check_tag (class_index, JV_CONSTANT_Class);
762 prepare_pool_entry (class_index, JV_CONSTANT_Class);
764 check_tag (nat_index, JV_CONSTANT_NameAndType);
765 prepare_pool_entry (nat_index, JV_CONSTANT_NameAndType);
767 // here, verify the signature and identifier name
768 if (verify)
770 _Jv_ushort name_index, type_index;
771 _Jv_loadIndexes (&pool_data[nat_index],
772 name_index, type_index);
774 if (this_tag == JV_CONSTANT_Fieldref)
775 _Jv_VerifyFieldSignature (pool_data[type_index].utf8);
776 else
777 _Jv_VerifyMethodSignature (pool_data[type_index].utf8);
779 _Jv_Utf8Const* name = pool_data[name_index].utf8;
781 if (this_tag != JV_CONSTANT_Fieldref
782 && ( _Jv_equalUtf8Consts (name, clinit_name)
783 || _Jv_equalUtf8Consts (name, init_name)))
784 /* ignore */;
785 else
786 verify_identifier (pool_data[name_index].utf8);
789 _Jv_storeIndexes (&pool_data[index], class_index, nat_index);
790 pool_tags[index] = this_tag;
792 break;
794 case JV_CONSTANT_NameAndType:
796 _Jv_ushort name_index = get2u (this_data);
797 _Jv_ushort type_index = get2u (this_data+2);
799 check_tag (name_index, JV_CONSTANT_Utf8);
800 prepare_pool_entry (name_index, JV_CONSTANT_Utf8);
802 check_tag (type_index, JV_CONSTANT_Utf8);
803 prepare_pool_entry (type_index, JV_CONSTANT_Utf8);
805 _Jv_storeIndexes (&pool_data[index], name_index, type_index);
806 pool_tags[index] = JV_CONSTANT_NameAndType;
808 break;
810 case JV_CONSTANT_Float:
812 jfloat f = java::lang::Float::intBitsToFloat ((jint) get4 (this_data));
813 _Jv_storeFloat (&pool_data[index], f);
814 pool_tags[index] = JV_CONSTANT_Float;
816 break;
818 case JV_CONSTANT_Integer:
820 int i = get4 (this_data);
821 _Jv_storeInt (&pool_data[index], i);
822 pool_tags[index] = JV_CONSTANT_Integer;
824 break;
826 case JV_CONSTANT_Double:
828 jdouble d
829 = java::lang::Double::longBitsToDouble ((jlong) get8 (this_data));
830 _Jv_storeDouble (&pool_data[index], d);
831 pool_tags[index] = JV_CONSTANT_Double;
833 break;
835 case JV_CONSTANT_Long:
837 jlong i = get8 (this_data);
838 _Jv_storeLong (&pool_data[index], i);
839 pool_tags[index] = JV_CONSTANT_Long;
841 break;
843 default:
844 throw_class_format_error ("erroneous constant pool tag");
849 void
850 _Jv_ClassReader::handleClassBegin
851 (int access_flags, int this_class, int super_class)
853 using namespace java::lang::reflect;
855 unsigned char *pool_tags = (unsigned char*) def->constants.tags;
856 _Jv_word *pool_data = def->constants.data;
858 check_tag (this_class, JV_CONSTANT_Class);
859 _Jv_Utf8Const *loadedName = pool_data[this_class].utf8;
861 // was ClassLoader.defineClass called with an expected class name?
862 if (def->name == 0)
864 jclass orig = _Jv_FindClassInCache (loadedName, def->loader);
866 if (orig == 0)
868 def->name = loadedName;
870 else
872 jstring msg = JvNewStringUTF ("anonymous "
873 "class data denotes "
874 "existing class ");
875 msg = msg->concat (orig->getName ());
877 throw_no_class_def_found_error (msg);
881 // assert that the loaded class has the expected name, 5.3.5
882 else if (! _Jv_equalUtf8Consts (loadedName, def->name))
884 jstring msg = JvNewStringUTF ("loaded class ");
885 msg = msg->concat (def->getName ());
886 msg = msg->concat (_Jv_NewStringUTF (" was in fact named "));
887 jstring klass_name = _Jv_NewStringUTF (loadedName->data);
888 msg = msg->concat (klass_name);
890 throw_no_class_def_found_error (msg);
893 def->accflags = access_flags | java::lang::reflect::Modifier::INTERPRETED;
894 pool_data[this_class].clazz = def;
895 pool_tags[this_class] = JV_CONSTANT_ResolvedClass;
897 if (super_class == 0 && ! (access_flags & Modifier::INTERFACE))
899 // FIXME: Consider this carefully!
900 if (! _Jv_equalUtf8Consts (def->name, java::lang::Object::class$.name))
901 throw_no_class_def_found_error ("loading java.lang.Object");
904 // In the pre-loading state, it can be looked up in the
905 // cache only by this thread! This allows the super-class
906 // to include references to this class.
908 def->state = JV_STATE_PRELOADING;
911 JvSynchronize sync (&java::lang::Class::class$);
912 _Jv_RegisterClass (def);
915 if (super_class != 0)
917 // Load the superclass.
918 check_tag (super_class, JV_CONSTANT_Class);
919 _Jv_Utf8Const* super_name = pool_data[super_class].utf8;
921 // Load the superclass using our defining loader.
922 jclass the_super = _Jv_FindClass (super_name,
923 def->loader);
925 // This will establish that we are allowed to be a subclass,
926 // and check for class circularity error.
927 checkExtends (def, the_super);
929 // Note: for an interface we will find Object as the
930 // superclass. We still check it above to ensure class file
931 // validity, but we simply assign `null' to the actual field in
932 // this case.
933 def->superclass = (((access_flags & Modifier::INTERFACE))
934 ? NULL : the_super);
935 pool_data[super_class].clazz = the_super;
936 pool_tags[super_class] = JV_CONSTANT_ResolvedClass;
939 // Now we've come past the circularity problem, we can
940 // now say that we're loading.
942 def->state = JV_STATE_LOADING;
943 def->notifyAll ();
946 ///// implements the checks described in sect. 5.3.5.3
947 void
948 _Jv_ClassReader::checkExtends (jclass sub, jclass super)
950 using namespace java::lang::reflect;
952 // having an interface or a final class as a superclass is no good
953 if ((super->accflags & (Modifier::INTERFACE | Modifier::FINAL)) != 0)
955 throw_incompatible_class_change_error (sub->getName ());
958 // if the super class is not public, we need to check some more
959 if ((super->accflags & Modifier::PUBLIC) == 0)
961 // With package scope, the classes must have the same
962 // class loader.
963 if ( sub->loader != super->loader
964 || !_Jv_ClassNameSamePackage (sub->name, super->name))
966 throw_incompatible_class_change_error (sub->getName ());
970 for (; super != 0; super = super->superclass)
972 if (super == sub)
973 throw_class_circularity_error (sub->getName ());
979 void _Jv_ClassReader::handleInterfacesBegin (int count)
981 def->interfaces = (jclass*) _Jv_AllocBytes (count*sizeof (jclass));
982 def->interface_count = count;
985 void _Jv_ClassReader::handleInterface (int if_number, int offset)
987 _Jv_word * pool_data = def->constants.data;
988 unsigned char * pool_tags = (unsigned char*) def->constants.tags;
990 jclass the_interface;
992 if (pool_tags[offset] == JV_CONSTANT_Class)
994 _Jv_Utf8Const* name = pool_data[offset].utf8;
995 the_interface = _Jv_FindClass (name, def->loader);
997 else if (pool_tags[offset] == JV_CONSTANT_ResolvedClass)
999 the_interface = pool_data[offset].clazz;
1001 else
1003 throw_no_class_def_found_error ("erroneous constant pool tag");
1006 // checks the validity of the_interface, and that we are in fact
1007 // allowed to implement that interface.
1008 checkImplements (def, the_interface);
1010 pool_data[offset].clazz = the_interface;
1011 pool_tags[offset] = JV_CONSTANT_ResolvedClass;
1013 def->interfaces[if_number] = the_interface;
1016 void
1017 _Jv_ClassReader::checkImplements (jclass sub, jclass super)
1019 using namespace java::lang::reflect;
1021 // well, it *must* be an interface
1022 if ((super->accflags & Modifier::INTERFACE) == 0)
1024 throw_incompatible_class_change_error (sub->getName ());
1027 // if it has package scope, it must also be defined by the
1028 // same loader.
1029 if ((super->accflags & Modifier::PUBLIC) == 0)
1031 if ( sub->loader != super->loader
1032 || !_Jv_ClassNameSamePackage (sub->name, super->name))
1034 throw_incompatible_class_change_error (sub->getName ());
1038 // FIXME: add interface circularity check here
1039 if (sub == super)
1041 throw_class_circularity_error (sub->getName ());
1045 void _Jv_ClassReader::handleFieldsBegin (int count)
1047 def->fields = (_Jv_Field*)
1048 _Jv_AllocBytes (count * sizeof (_Jv_Field));
1049 def->field_count = count;
1050 def->field_initializers = (_Jv_ushort*)
1051 _Jv_AllocBytes (count * sizeof (_Jv_ushort));
1052 for (int i = 0; i < count; i++)
1053 def->field_initializers[i] = (_Jv_ushort) 0;
1056 void _Jv_ClassReader::handleField (int field_no,
1057 int flags,
1058 int name,
1059 int desc)
1061 using namespace java::lang::reflect;
1063 _Jv_word *pool_data = def->constants.data;
1065 _Jv_Field *field = &def->fields[field_no];
1066 _Jv_Utf8Const *field_name = pool_data[name].utf8;
1068 #ifndef COMPACT_FIELDS
1069 field->name = field_name;
1070 #else
1071 field->nameIndex = name;
1072 #endif
1074 if (verify)
1075 verify_identifier (field_name);
1077 // ignore flags we don't know about.
1078 field->flags = flags & Modifier::ALL_FLAGS;
1080 if (verify)
1082 if (field->flags & (Modifier::SYNCHRONIZED
1083 | Modifier::NATIVE
1084 | Modifier::INTERFACE
1085 | Modifier::ABSTRACT))
1086 throw_class_format_error ("erroneous field access flags");
1088 if (1 < ( ((field->flags & Modifier::PUBLIC) ? 1 : 0)
1089 +((field->flags & Modifier::PRIVATE) ? 1 : 0)
1090 +((field->flags & Modifier::PROTECTED) ? 1 : 0)))
1091 throw_class_format_error ("erroneous field access flags");
1094 _Jv_Utf8Const* sig = pool_data[desc].utf8;
1096 if (verify)
1097 _Jv_VerifyFieldSignature (sig);
1099 // field->type is really a jclass, but while it is still
1100 // unresolved we keep an _Jv_Utf8Const* instead.
1101 field->type = (jclass) sig;
1102 field->flags |= _Jv_FIELD_UNRESOLVED_FLAG;
1103 field->u.boffset = 0;
1107 void _Jv_ClassReader::handleConstantValueAttribute (int field_index,
1108 int value)
1110 using namespace java::lang::reflect;
1112 _Jv_Field *field = &def->fields[field_index];
1114 if ((field->flags & (Modifier::STATIC
1115 | Modifier::FINAL
1116 | Modifier::PRIVATE)) == 0)
1118 // Ignore, as per vmspec #4.7.2
1119 return;
1122 // do not allow multiple constant fields!
1123 if (field->flags & _Jv_FIELD_CONSTANT_VALUE)
1124 throw_class_format_error ("field has multiple ConstantValue attributes");
1126 field->flags |= _Jv_FIELD_CONSTANT_VALUE;
1127 def->field_initializers[field_index] = value;
1129 /* type check the initializer */
1131 if (value <= 0 || value >= pool_count)
1132 throw_class_format_error ("erroneous ConstantValue attribute");
1134 /* FIXME: do the rest */
1137 void _Jv_ClassReader::handleFieldsEnd ()
1139 using namespace java::lang::reflect;
1141 // We need to reorganize the fields so that the static ones are first,
1142 // to conform to GCJ class layout.
1144 int low = 0;
1145 int high = def->field_count-1;
1146 _Jv_Field *fields = def->fields;
1147 _Jv_ushort *inits = def->field_initializers;
1149 // this is kind of a raw version of quicksort.
1150 while (low < high)
1152 // go forward on low, while it's a static
1153 while (low < high && (fields[low].flags & Modifier::STATIC) != 0)
1154 low++;
1156 // go backwards on high, while it's a non-static
1157 while (low < high && (fields[high].flags & Modifier::STATIC) == 0)
1158 high--;
1160 if (low==high)
1161 break;
1163 _Jv_Field tmp = fields[low];
1164 _Jv_ushort itmp = inits[low];
1166 fields[low] = fields[high];
1167 inits[low] = inits[high];
1169 fields[high] = tmp;
1170 inits[high] = itmp;
1172 high -= 1;
1173 low += 1;
1176 if ((fields[low].flags & Modifier::STATIC) != 0)
1177 low += 1;
1179 def->static_field_count = low;
1184 void
1185 _Jv_ClassReader::handleMethodsBegin (int count)
1187 def->methods = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method) * count);
1189 def->interpreted_methods
1190 = (_Jv_MethodBase **) _Jv_AllocBytes (sizeof (_Jv_MethodBase *)
1191 * count);
1193 for (int i = 0; i < count; i++)
1195 def->interpreted_methods[i] = 0;
1196 def->methods[i].index = (_Jv_ushort) -1;
1199 def->method_count = count;
1203 void _Jv_ClassReader::handleMethod
1204 (int mth_index, int accflags, int name, int desc)
1206 using namespace java::lang::reflect;
1208 _Jv_word *pool_data = def->constants.data;
1209 _Jv_Method *method = &def->methods[mth_index];
1211 check_tag (name, JV_CONSTANT_Utf8);
1212 prepare_pool_entry (name, JV_CONSTANT_Utf8);
1213 method->name = pool_data[name].utf8;
1215 check_tag (desc, JV_CONSTANT_Utf8);
1216 prepare_pool_entry (desc, JV_CONSTANT_Utf8);
1217 method->signature = pool_data[desc].utf8;
1219 // ignore unknown flags
1220 method->accflags = accflags & Modifier::ALL_FLAGS;
1222 // intialize...
1223 method->ncode = 0;
1224 method->throws = NULL;
1226 if (verify)
1228 if (_Jv_equalUtf8Consts (method->name, clinit_name)
1229 || _Jv_equalUtf8Consts (method->name, init_name))
1230 /* ignore */;
1231 else
1232 verify_identifier (method->name);
1234 _Jv_VerifyMethodSignature (method->signature);
1236 if (method->accflags & (Modifier::VOLATILE
1237 | Modifier::TRANSIENT
1238 | Modifier::INTERFACE))
1239 throw_class_format_error ("erroneous method access flags");
1241 if (1 < ( ((method->accflags & Modifier::PUBLIC) ? 1 : 0)
1242 +((method->accflags & Modifier::PRIVATE) ? 1 : 0)
1243 +((method->accflags & Modifier::PROTECTED) ? 1 : 0)))
1244 throw_class_format_error ("erroneous method access flags");
1248 void _Jv_ClassReader::handleCodeAttribute
1249 (int method_index, int max_stack, int max_locals,
1250 int code_start, int code_length, int exc_table_length)
1252 int size = _Jv_InterpMethod::size (exc_table_length, code_length);
1253 _Jv_InterpMethod *method =
1254 (_Jv_InterpMethod*) (_Jv_AllocBytes (size));
1256 method->max_stack = max_stack;
1257 method->max_locals = max_locals;
1258 method->code_length = code_length;
1259 method->exc_count = exc_table_length;
1260 method->defining_class = def;
1261 method->self = &def->methods[method_index];
1262 method->prepared = NULL;
1264 // grab the byte code!
1265 memcpy ((void*) method->bytecode (),
1266 (void*) (bytes+code_start),
1267 code_length);
1269 def->interpreted_methods[method_index] = method;
1271 if ((method->self->accflags & java::lang::reflect::Modifier::STATIC))
1273 // Precompute the ncode field for a static method. This lets us
1274 // call a static method of an interpreted class from precompiled
1275 // code without first resolving the class (that will happen
1276 // during class initialization instead).
1277 method->self->ncode = method->ncode ();
1281 void _Jv_ClassReader::handleExceptionTableEntry
1282 (int method_index, int exc_index,
1283 int start_pc, int end_pc, int handler_pc, int catch_type)
1285 _Jv_InterpMethod *method = reinterpret_cast<_Jv_InterpMethod *>
1286 (def->interpreted_methods[method_index]);
1287 _Jv_InterpException *exc = method->exceptions ();
1289 exc[exc_index].start_pc.i = start_pc;
1290 exc[exc_index].end_pc.i = end_pc;
1291 exc[exc_index].handler_pc.i = handler_pc;
1292 exc[exc_index].handler_type.i = catch_type;
1295 void _Jv_ClassReader::handleMethodsEnd ()
1297 using namespace java::lang::reflect;
1299 for (int i = 0; i < def->method_count; i++)
1301 _Jv_Method *method = &def->methods[i];
1302 if ((method->accflags & Modifier::NATIVE) != 0)
1304 if (def->interpreted_methods[i] != 0)
1305 throw_class_format_error ("code provided for native method");
1306 else
1308 _Jv_JNIMethod *m = (_Jv_JNIMethod *)
1309 _Jv_AllocBytes (sizeof (_Jv_JNIMethod));
1310 m->defining_class = def;
1311 m->self = method;
1312 m->function = NULL;
1313 def->interpreted_methods[i] = m;
1315 if ((method->accflags & Modifier::STATIC))
1317 // Precompute the ncode field for a static method.
1318 // This lets us call a static method of an
1319 // interpreted class from precompiled code without
1320 // first resolving the class (that will happen
1321 // during class initialization instead).
1322 method->ncode = m->ncode ();
1326 else if ((method->accflags & Modifier::ABSTRACT) != 0)
1328 if (def->interpreted_methods[i] != 0)
1329 throw_class_format_error ("code provided for abstract method");
1331 else
1333 if (def->interpreted_methods[i] == 0)
1334 throw_class_format_error ("method with no code");
1339 void _Jv_ClassReader::throw_class_format_error (char *msg)
1341 jstring str;
1342 if (def->name != NULL)
1344 jsize mlen = strlen (msg);
1345 unsigned char* data = (unsigned char*) def->name->data;
1346 int ulen = def->name->length;
1347 unsigned char* limit = data + ulen;
1348 jsize nlen = _Jv_strLengthUtf8 ((char *) data, ulen);
1349 jsize len = nlen + mlen + 3;
1350 str = JvAllocString(len);
1351 jchar *chrs = JvGetStringChars(str);
1352 while (data < limit)
1353 *chrs++ = UTF8_GET(data, limit);
1354 *chrs++ = ' ';
1355 *chrs++ = '(';
1356 for (;;)
1358 char c = *msg++;
1359 if (c == 0)
1360 break;
1361 *chrs++ = c & 0xFFFF;
1363 *chrs++ = ')';
1365 else
1366 str = JvNewStringLatin1 (msg);
1367 ::throw_class_format_error (str);
1370 /** Here we define the exceptions that can be thrown */
1372 static void
1373 throw_no_class_def_found_error (jstring msg)
1375 throw (msg
1376 ? new java::lang::NoClassDefFoundError (msg)
1377 : new java::lang::NoClassDefFoundError);
1380 static void
1381 throw_no_class_def_found_error (char *msg)
1383 throw_no_class_def_found_error (JvNewStringLatin1 (msg));
1386 static void
1387 throw_class_format_error (jstring msg)
1389 throw (msg
1390 ? new java::lang::ClassFormatError (msg)
1391 : new java::lang::ClassFormatError);
1394 static void
1395 throw_internal_error (char *msg)
1397 throw new java::lang::InternalError (JvNewStringLatin1 (msg));
1400 static void
1401 throw_incompatible_class_change_error (jstring msg)
1403 throw new java::lang::IncompatibleClassChangeError (msg);
1406 static void
1407 throw_class_circularity_error (jstring msg)
1409 throw new java::lang::ClassCircularityError (msg);
1412 #endif /* INTERPRETER */
1416 /** This section takes care of verifying integrity of identifiers,
1417 signatures, field ddescriptors, and class names */
1419 #define UTF8_PEEK(PTR, LIMIT) \
1420 ({ unsigned char* xxkeep = (PTR); \
1421 int xxch = UTF8_GET(PTR,LIMIT); \
1422 PTR = xxkeep; xxch; })
1424 /* Verify one element of a type descriptor or signature. */
1425 static unsigned char*
1426 _Jv_VerifyOne (unsigned char* ptr, unsigned char* limit, bool void_ok)
1428 if (ptr >= limit)
1429 return 0;
1431 int ch = UTF8_GET (ptr, limit);
1433 switch (ch)
1435 case 'V':
1436 if (! void_ok)
1437 return 0;
1439 case 'S': case 'B': case 'I': case 'J':
1440 case 'Z': case 'C': case 'F': case 'D':
1441 break;
1443 case 'L':
1445 unsigned char *start = ptr, *end;
1448 if (ptr > limit)
1449 return 0;
1451 end = ptr;
1453 if ((ch = UTF8_GET (ptr, limit)) == -1)
1454 return 0;
1457 while (ch != ';');
1458 if (! _Jv_VerifyClassName (start, (unsigned short) (end-start)))
1459 return 0;
1461 break;
1463 case '[':
1464 return _Jv_VerifyOne (ptr, limit, false);
1465 break;
1467 default:
1468 return 0;
1471 return ptr;
1474 /* Verification and loading procedures. */
1475 bool
1476 _Jv_VerifyFieldSignature (_Jv_Utf8Const*sig)
1478 unsigned char* ptr = (unsigned char*) sig->data;
1479 unsigned char* limit = ptr + sig->length;
1481 ptr = _Jv_VerifyOne (ptr, limit, false);
1483 return ptr == limit;
1486 bool
1487 _Jv_VerifyMethodSignature (_Jv_Utf8Const*sig)
1489 unsigned char* ptr = (unsigned char*) sig->data;
1490 unsigned char* limit = ptr + sig->length;
1492 if (ptr == limit || UTF8_GET(ptr,limit) != '(')
1493 return false;
1495 while (ptr && UTF8_PEEK (ptr, limit) != ')')
1496 ptr = _Jv_VerifyOne (ptr, limit, false);
1498 if (UTF8_GET (ptr, limit) != ')')
1499 return false;
1501 // get the return type
1502 ptr = _Jv_VerifyOne (ptr, limit, true);
1504 return ptr == limit;
1507 /* We try to avoid calling the Character methods all the time, in
1508 fact, they will only be called for non-standard things. */
1509 static __inline__ int
1510 is_identifier_start (int c)
1512 unsigned int ch = (unsigned)c;
1514 if ((ch - 0x41U) < 29U) /* A ... Z */
1515 return 1;
1516 if ((ch - 0x61U) < 29U) /* a ... z */
1517 return 1;
1518 if (ch == 0x5FU) /* _ */
1519 return 1;
1521 return java::lang::Character::isJavaIdentifierStart ((jchar) ch);
1524 static __inline__ int
1525 is_identifier_part (int c)
1527 unsigned int ch = (unsigned)c;
1529 if ((ch - 0x41U) < 29U) /* A ... Z */
1530 return 1;
1531 if ((ch - 0x61U) < 29U) /* a ... z */
1532 return 1;
1533 if ((ch - 0x30) < 10U) /* 0 .. 9 */
1534 return 1;
1535 if (ch == 0x5FU || ch == 0x24U) /* _ $ */
1536 return 1;
1538 return java::lang::Character::isJavaIdentifierStart ((jchar) ch);
1541 bool
1542 _Jv_VerifyIdentifier (_Jv_Utf8Const* name)
1544 unsigned char *ptr = (unsigned char*) name->data;
1545 unsigned char *limit = ptr + name->length;
1546 int ch;
1548 if ((ch = UTF8_GET (ptr, limit))==-1
1549 || ! is_identifier_start (ch))
1550 return false;
1552 while (ptr != limit)
1554 if ((ch = UTF8_GET (ptr, limit))==-1
1555 || ! is_identifier_part (ch))
1556 return false;
1558 return true;
1561 bool
1562 _Jv_VerifyClassName (unsigned char* ptr, _Jv_ushort length)
1564 unsigned char *limit = ptr+length;
1565 int ch;
1567 if ('[' == UTF8_PEEK (ptr, limit))
1569 unsigned char *end = _Jv_VerifyOne (++ptr, limit, false);
1570 // _Jv_VerifyOne must leave us looking at the terminating nul
1571 // byte.
1572 if (! end || *end)
1573 return false;
1574 else
1575 return true;
1578 next_level:
1579 for (;;) {
1580 if ((ch = UTF8_GET (ptr, limit))==-1)
1581 return false;
1582 if (! is_identifier_start (ch))
1583 return false;
1584 for (;;) {
1585 if (ptr == limit)
1586 return true;
1587 else if ((ch = UTF8_GET (ptr, limit))==-1)
1588 return false;
1589 else if (ch == '.')
1590 goto next_level;
1591 else if (! is_identifier_part (ch))
1592 return false;
1597 bool
1598 _Jv_VerifyClassName (_Jv_Utf8Const *name)
1600 return _Jv_VerifyClassName ((unsigned char*)&name->data[0],
1601 (_Jv_ushort) name->length);
1604 /* Returns true, if NAME1 and NAME2 represent classes in the same
1605 package. */
1606 bool
1607 _Jv_ClassNameSamePackage (_Jv_Utf8Const *name1, _Jv_Utf8Const *name2)
1609 unsigned char* ptr1 = (unsigned char*) name1->data;
1610 unsigned char* limit1 = ptr1 + name1->length;
1612 unsigned char* last1 = ptr1;
1614 // scan name1, and find the last occurrence of '.'
1615 while (ptr1 < limit1) {
1616 int ch1 = UTF8_GET (ptr1, limit1);
1618 if (ch1 == '.')
1619 last1 = ptr1;
1621 else if (ch1 == -1)
1622 return false;
1625 // Now the length of NAME1's package name is LEN.
1626 int len = last1 - (unsigned char*) name1->data;
1628 // If this is longer than NAME2, then we're off.
1629 if (len > name2->length)
1630 return false;
1632 // Then compare the first len bytes for equality.
1633 if (memcmp ((void*) name1->data, (void*) name2->data, len) == 0)
1635 // Check that there are no .'s after position LEN in NAME2.
1637 unsigned char* ptr2 = (unsigned char*) name2->data + len;
1638 unsigned char* limit2 =
1639 (unsigned char*) name2->data + name2->length;
1641 while (ptr2 < limit2)
1643 int ch2 = UTF8_GET (ptr2, limit2);
1644 if (ch2 == -1 || ch2 == '.')
1645 return false;
1647 return true;
1649 return false;