* config/xtensa/xtensa.h (STARTFILE_SPEC): Add crt0.
[official-gcc.git] / libjava / defineclass.cc
blob1a0c4e4da603988e22e36e072070c2b964872429
1 // defineclass.cc - defining a class from .class format.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 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 <stdio.h>
27 #include <java-cpool.h>
28 #include <gcj/cni.h>
29 #include <execution.h>
31 #include <java/lang/Class.h>
32 #include <java/lang/Float.h>
33 #include <java/lang/Double.h>
34 #include <java/lang/Character.h>
35 #include <java/lang/LinkageError.h>
36 #include <java/lang/InternalError.h>
37 #include <java/lang/ClassFormatError.h>
38 #include <java/lang/NoClassDefFoundError.h>
39 #include <java/lang/ClassCircularityError.h>
40 #include <java/lang/IncompatibleClassChangeError.h>
41 #include <java/lang/reflect/Modifier.h>
42 #include <java/security/ProtectionDomain.h>
44 using namespace gcj;
46 #ifdef INTERPRETER
48 // these go in some separate functions, to avoid having _Jv_InitClass
49 // inserted all over the place.
50 static void throw_internal_error (char *msg)
51 __attribute__ ((__noreturn__));
52 static void throw_no_class_def_found_error (jstring msg)
53 __attribute__ ((__noreturn__));
54 static void throw_no_class_def_found_error (char *msg)
55 __attribute__ ((__noreturn__));
56 static void throw_class_format_error (jstring msg)
57 __attribute__ ((__noreturn__));
58 static void throw_incompatible_class_change_error (jstring msg)
59 __attribute__ ((__noreturn__));
60 static void throw_class_circularity_error (jstring msg)
61 __attribute__ ((__noreturn__));
63 /**
64 * We define class reading using a class. It is practical, since then
65 * the entire class-reader can be a friend of class Class (it needs to
66 * write all it's different structures); but also because this makes it
67 * easy to make class definition reentrant, and thus two threads can be
68 * defining classes at the same time. This class (_Jv_ClassReader) is
69 * never exposed outside this file, so we don't have to worry about
70 * public or private members here.
73 struct _Jv_ClassReader {
75 // do verification? Currently, there is no option to disable this.
76 // This flag just controls the verificaiton done by the class loader;
77 // i.e., checking the integrity of the constant pool; and it is
78 // allways on. You always want this as far as I can see, but it also
79 // controls weither identifiers and type descriptors/signatures are
80 // verified as legal. This could be somewhat more expensive since it
81 // will call Character.isJavaIdentifier{Start,Part} for each character
82 // in any identifier (field name or method name) it comes by. Thus,
83 // it might be useful to turn off this verification for classes that
84 // come from a trusted source. However, for GCJ, trusted classes are
85 // most likely to be linked in.
87 bool verify;
89 // input data.
90 unsigned char *bytes;
91 int len;
93 // current input position
94 int pos;
96 // the constant pool data
97 int pool_count;
98 unsigned char *tags;
99 unsigned int *offsets;
101 // the class to define (see java-interp.h)
102 jclass def;
104 // the classes associated interpreter data.
105 _Jv_InterpClass *def_interp;
107 /* check that the given number of input bytes are available */
108 inline void check (int num)
110 if (pos + num > len)
111 throw_class_format_error ("Premature end of data");
114 /* skip a given number of bytes in input */
115 inline void skip (int num)
117 check (num);
118 pos += num;
121 /* read an unsignend 1-byte unit */
122 inline static jint get1u (unsigned char* bytes)
124 return bytes[0];
127 /* read an unsigned 1-byte unit */
128 inline jint read1u ()
130 skip (1);
131 return get1u (bytes+pos-1);
134 /* read an unsigned 2-byte unit */
135 inline static jint get2u (unsigned char *bytes)
137 return (((jint)bytes[0]) << 8) | ((jint)bytes[1]);
140 /* read an unsigned 2-byte unit */
141 inline jint read2u ()
143 skip (2);
144 return get2u (bytes+pos-2);
147 /* read a 4-byte unit */
148 static jint get4 (unsigned char *bytes)
150 return (((jint)bytes[0]) << 24)
151 | (((jint)bytes[1]) << 16)
152 | (((jint)bytes[2]) << 8)
153 | (((jint)bytes[3]) << 0);
156 /* read a 4-byte unit, (we don't do that quite so often) */
157 inline jint read4 ()
159 skip (4);
160 return get4 (bytes+pos-4);
163 /* read a 8-byte unit */
164 static jlong get8 (unsigned char* bytes)
166 return (((jlong)bytes[0]) << 56)
167 | (((jlong)bytes[1]) << 48)
168 | (((jlong)bytes[2]) << 40)
169 | (((jlong)bytes[3]) << 32)
170 | (((jlong)bytes[4]) << 24)
171 | (((jlong)bytes[5]) << 16)
172 | (((jlong)bytes[6]) << 8)
173 | (((jlong)bytes[7]) << 0);
176 /* read a 8-byte unit */
177 inline jlong read8 ()
179 skip (8);
180 return get8 (bytes+pos-8);
183 inline void check_tag (int index, char expected_tag)
185 if (index < 0
186 || index > pool_count
187 || tags[index] != expected_tag)
188 throw_class_format_error ("erroneous constant pool tag");
191 inline void verify_identifier (_Jv_Utf8Const* name)
193 if (! _Jv_VerifyIdentifier (name))
194 throw_class_format_error ("erroneous identifier");
197 inline void verify_classname (unsigned char* ptr, _Jv_ushort length)
199 if (! _Jv_VerifyClassName (ptr, length))
200 throw_class_format_error ("erroneous class name");
203 inline void verify_classname (_Jv_Utf8Const *name)
205 if (! _Jv_VerifyClassName (name))
206 throw_class_format_error ("erroneous class name");
209 inline void verify_field_signature (_Jv_Utf8Const *sig)
211 if (! _Jv_VerifyFieldSignature (sig))
212 throw_class_format_error ("erroneous type descriptor");
215 inline void verify_method_signature (_Jv_Utf8Const *sig)
217 if (! _Jv_VerifyMethodSignature (sig))
218 throw_class_format_error ("erroneous type descriptor");
221 _Jv_ClassReader (jclass klass, jbyteArray data, jint offset, jint length,
222 java::security::ProtectionDomain *pd)
224 if (klass == 0 || length < 0 || offset+length > data->length)
225 throw_internal_error ("arguments to _Jv_DefineClass");
227 verify = true;
228 bytes = (unsigned char*) (elements (data)+offset);
229 len = length;
230 pos = 0;
231 def = klass;
232 def->size_in_bytes = -1;
233 def->vtable_method_count = -1;
234 def->engine = &_Jv_soleInterpreterEngine;
235 def->protectionDomain = pd;
238 /** and here goes the parser members defined out-of-line */
239 void parse ();
240 void read_constpool ();
241 void prepare_pool_entry (int index, unsigned char tag);
242 void read_fields ();
243 void read_methods ();
244 void read_one_class_attribute ();
245 void read_one_method_attribute (int method);
246 void read_one_code_attribute (int method);
247 void read_one_field_attribute (int field);
248 void throw_class_format_error (char *msg);
250 /** check an utf8 entry, without creating a Utf8Const object */
251 bool is_attribute_name (int index, char *name);
253 /** here goes the class-loader members defined out-of-line */
254 void handleConstantPool ();
255 void handleClassBegin (int, int, int);
256 void handleInterfacesBegin (int);
257 void handleInterface (int, int);
258 void handleFieldsBegin (int);
259 void handleField (int, int, int, int);
260 void handleFieldsEnd ();
261 void handleConstantValueAttribute (int,int);
262 void handleMethodsBegin (int);
263 void handleMethod (int, int, int, int);
264 void handleMethodsEnd ();
265 void handleCodeAttribute (int, int, int, int, int, int);
266 void handleExceptionTableEntry (int, int, int, int, int, int);
268 void checkExtends (jclass sub, jclass super);
269 void checkImplements (jclass sub, jclass super);
272 * FIXME: we should keep a hash table of utf8-strings, since many will
273 * be the same. It's a little tricky, however, because the hash table
274 * needs to interact gracefully with the garbage collector. Much
275 * memory is to be saved by this, however! perhaps the improvement
276 * could be implemented in prims.cc (_Jv_makeUtf8Const), since it
277 * computes the hash value anyway.
281 void
282 _Jv_DefineClass (jclass klass, jbyteArray data, jint offset, jint length,
283 java::security::ProtectionDomain *pd)
285 _Jv_ClassReader reader (klass, data, offset, length, pd);
286 reader.parse();
288 /* that's it! */
292 /** This section defines the parsing/scanning of the class data */
294 void
295 _Jv_ClassReader::parse ()
297 int magic = read4 ();
299 /* FIXME: Decide which range of version numbers to allow */
301 /* int minor_version = */ read2u ();
302 /* int major_verson = */ read2u ();
304 if (magic != (int) 0xCAFEBABE)
305 throw_class_format_error ("bad magic number");
307 pool_count = read2u ();
309 read_constpool ();
311 int access_flags = read2u ();
312 int this_class = read2u ();
313 int super_class = read2u ();
315 check_tag (this_class, JV_CONSTANT_Class);
316 if (super_class != 0)
317 check_tag (super_class, JV_CONSTANT_Class);
319 handleClassBegin (access_flags, this_class, super_class);
321 // Allocate our aux_info here, after the name is set, to fulfill our
322 // contract with the collector interface.
323 def->aux_info = (void *) _Jv_AllocBytes (sizeof (_Jv_InterpClass));
324 def_interp = (_Jv_InterpClass *) def->aux_info;
326 int interfaces_count = read2u ();
328 handleInterfacesBegin (interfaces_count);
330 for (int i = 0; i < interfaces_count; i++)
332 int iface = read2u ();
333 check_tag (iface, JV_CONSTANT_Class);
334 handleInterface (i, iface);
337 read_fields ();
338 read_methods ();
340 int attributes_count = read2u ();
342 for (int i = 0; i < attributes_count; i++)
344 read_one_class_attribute ();
347 if (pos != len)
348 throw_class_format_error ("unused data before end of file");
350 // Tell everyone we're done.
351 def->state = JV_STATE_READ;
352 if (gcj::verbose_class_flag)
353 _Jv_Linker::print_class_loaded (def);
354 def->notifyAll ();
357 void _Jv_ClassReader::read_constpool ()
359 tags = (unsigned char*) _Jv_AllocBytes (pool_count);
360 offsets = (unsigned int *) _Jv_AllocBytes (sizeof (int)
361 * pool_count) ;
363 /** first, we scan the constant pool, collecting tags and offsets */
364 tags[0] = JV_CONSTANT_Undefined;
365 offsets[0] = pos;
366 for (int c = 1; c < pool_count; c++)
368 tags[c] = read1u ();
369 offsets[c] = pos;
371 switch (tags[c])
373 case JV_CONSTANT_String:
374 case JV_CONSTANT_Class:
375 skip (2);
376 break;
378 case JV_CONSTANT_Fieldref:
379 case JV_CONSTANT_Methodref:
380 case JV_CONSTANT_InterfaceMethodref:
381 case JV_CONSTANT_NameAndType:
382 case JV_CONSTANT_Integer:
383 case JV_CONSTANT_Float:
384 skip (4);
385 break;
387 case JV_CONSTANT_Double:
388 case JV_CONSTANT_Long:
389 skip (8);
390 tags[++c] = JV_CONSTANT_Undefined;
391 break;
393 case JV_CONSTANT_Utf8:
395 int len = read2u ();
396 skip (len);
398 break;
400 case JV_CONSTANT_Unicode:
401 throw_class_format_error ("unicode not supported");
402 break;
404 default:
405 throw_class_format_error ("erroneous constant pool tag");
409 handleConstantPool ();
413 void _Jv_ClassReader::read_fields ()
415 int fields_count = read2u ();
416 handleFieldsBegin (fields_count);
418 for (int i = 0; i < fields_count; i++)
420 int access_flags = read2u ();
421 int name_index = read2u ();
422 int descriptor_index = read2u ();
423 int attributes_count = read2u ();
425 check_tag (name_index, JV_CONSTANT_Utf8);
426 prepare_pool_entry (name_index, JV_CONSTANT_Utf8);
428 check_tag (descriptor_index, JV_CONSTANT_Utf8);
429 prepare_pool_entry (descriptor_index, JV_CONSTANT_Utf8);
431 handleField (i, access_flags, name_index, descriptor_index);
433 for (int j = 0; j < attributes_count; j++)
435 read_one_field_attribute (i);
439 handleFieldsEnd ();
442 bool
443 _Jv_ClassReader::is_attribute_name (int index, char *name)
445 check_tag (index, JV_CONSTANT_Utf8);
446 int len = get2u (bytes+offsets[index]);
447 if (len != (int) strlen (name))
448 return false;
449 else
450 return !memcmp (bytes+offsets[index]+2, name, len);
453 void _Jv_ClassReader::read_one_field_attribute (int field_index)
455 int name = read2u ();
456 int length = read4 ();
458 if (is_attribute_name (name, "ConstantValue"))
460 int cv = read2u ();
462 if (cv < pool_count
463 && cv > 0
464 && (tags[cv] == JV_CONSTANT_Integer
465 || tags[cv] == JV_CONSTANT_Float
466 || tags[cv] == JV_CONSTANT_Long
467 || tags[cv] == JV_CONSTANT_Double
468 || tags[cv] == JV_CONSTANT_String))
470 handleConstantValueAttribute (field_index, cv);
472 else
474 throw_class_format_error ("erroneous ConstantValue attribute");
477 if (length != 2)
478 throw_class_format_error ("erroneous ConstantValue attribute");
481 else
483 skip (length);
487 void _Jv_ClassReader::read_methods ()
489 int methods_count = read2u ();
491 handleMethodsBegin (methods_count);
493 for (int i = 0; i < methods_count; i++)
495 int access_flags = read2u ();
496 int name_index = read2u ();
497 int descriptor_index = read2u ();
498 int attributes_count = read2u ();
500 check_tag (name_index, JV_CONSTANT_Utf8);
501 prepare_pool_entry (descriptor_index, JV_CONSTANT_Utf8);
503 check_tag (name_index, JV_CONSTANT_Utf8);
504 prepare_pool_entry (descriptor_index, JV_CONSTANT_Utf8);
506 handleMethod (i, access_flags, name_index,
507 descriptor_index);
509 for (int j = 0; j < attributes_count; j++)
511 read_one_method_attribute (i);
515 handleMethodsEnd ();
518 void _Jv_ClassReader::read_one_method_attribute (int method_index)
520 int name = read2u ();
521 int length = read4 ();
523 if (is_attribute_name (name, "Exceptions"))
525 _Jv_Method *method = reinterpret_cast<_Jv_Method *>
526 (&def->methods[method_index]);
527 if (method->throws != NULL)
528 throw_class_format_error ("only one Exceptions attribute allowed per method");
530 int num_exceptions = read2u ();
531 _Jv_Utf8Const **exceptions =
532 (_Jv_Utf8Const **) _Jv_AllocBytes ((num_exceptions + 1)
533 * sizeof (_Jv_Utf8Const *));
535 int out = 0;
536 _Jv_word *pool_data = def->constants.data;
537 for (int i = 0; i < num_exceptions; ++i)
539 int ndx = read2u ();
540 // JLS 2nd Ed. 4.7.5 requires that the tag not be 0.
541 if (ndx != 0)
543 check_tag (ndx, JV_CONSTANT_Class);
544 exceptions[out++] = pool_data[ndx].utf8;
547 exceptions[out] = NULL;
548 method->throws = exceptions;
551 else if (is_attribute_name (name, "Code"))
553 int start_off = pos;
554 int max_stack = read2u ();
555 int max_locals = read2u ();
556 int code_length = read4 ();
558 int code_start = pos;
559 skip (code_length);
560 int exception_table_length = read2u ();
562 handleCodeAttribute (method_index,
563 max_stack, max_locals,
564 code_start, code_length,
565 exception_table_length);
568 for (int i = 0; i < exception_table_length; i++)
570 int start_pc = read2u ();
571 int end_pc = read2u ();
572 int handler_pc = read2u ();
573 int catch_type = read2u ();
575 if (start_pc > end_pc
576 || start_pc < 0
577 // END_PC can be equal to CODE_LENGTH.
578 // See JVM Spec 4.7.4.
579 || end_pc > code_length
580 || handler_pc >= code_length)
581 throw_class_format_error ("erroneous exception handler info");
583 if (! (tags[catch_type] == JV_CONSTANT_Class
584 || tags[catch_type] == 0))
586 throw_class_format_error ("erroneous exception handler info");
589 handleExceptionTableEntry (method_index,
591 start_pc,
592 end_pc,
593 handler_pc,
594 catch_type);
598 int attributes_count = read2u ();
600 for (int i = 0; i < attributes_count; i++)
602 read_one_code_attribute (method_index);
605 if ((pos - start_off) != length)
606 throw_class_format_error ("code attribute too short");
609 else
611 /* ignore unknown attributes */
612 skip (length);
616 void _Jv_ClassReader::read_one_code_attribute (int /*method*/)
618 /* ignore for now, ... later we may want to pick up
619 line number information, for debugging purposes;
620 in fact, the whole debugger issue is open! */
622 /* int name = */ read2u ();
623 int length = read4 ();
624 skip (length);
628 void _Jv_ClassReader::read_one_class_attribute ()
630 /* we also ignore the class attributes, ...
631 some day we'll add inner-classes support. */
633 /* int name = */ read2u ();
634 int length = read4 ();
635 skip (length);
641 /* this section defines the semantic actions of the parser */
643 void _Jv_ClassReader::handleConstantPool ()
645 /** now, we actually define the class' constant pool */
647 // the pool is scanned explicitly by the collector
648 jbyte *pool_tags = (jbyte*) _Jv_AllocBytes (pool_count);
649 _Jv_word *pool_data
650 = (_Jv_word*) _Jv_AllocBytes (pool_count * sizeof (_Jv_word));
652 def->constants.tags = pool_tags;
653 def->constants.data = pool_data;
654 def->constants.size = pool_count;
656 // Here we make a pass to collect the strings! We do this, because
657 // internally in the GCJ runtime, classes are encoded with .'s not /'s.
658 // Therefore, we first collect the strings, and then translate the rest
659 // of the utf8-entries (thus not representing strings) from /-notation
660 // to .-notation.
661 for (int i = 1; i < pool_count; i++)
663 if (tags[i] == JV_CONSTANT_String)
665 unsigned char* str_data = bytes + offsets [i];
666 int utf_index = get2u (str_data);
667 check_tag (utf_index, JV_CONSTANT_Utf8);
668 unsigned char *utf_data = bytes + offsets[utf_index];
669 int len = get2u (utf_data);
670 pool_data[i].utf8 = _Jv_makeUtf8Const ((char*)(utf_data+2), len);
671 pool_tags[i] = JV_CONSTANT_String;
673 else
675 pool_tags[i] = JV_CONSTANT_Undefined;
679 // and now, we scan everything else but strings & utf8-entries. This
680 // leaves out those utf8-entries which are not used; which will be left
681 // with a tag of JV_CONSTANT_Undefined in the class definition.
682 for (int index = 1; index < pool_count; index++)
684 switch (tags[index])
686 case JV_CONSTANT_Undefined:
687 case JV_CONSTANT_String:
688 case JV_CONSTANT_Utf8:
689 continue;
691 default:
692 prepare_pool_entry (index, tags[index]);
698 /* this is a recursive procedure, which will prepare pool entries as needed.
699 Which is how we avoid initializing those entries which go unused. */
700 void
701 _Jv_ClassReader::prepare_pool_entry (int index, unsigned char this_tag)
703 /* these two, pool_data and pool_tags, point into the class
704 structure we are currently defining */
706 unsigned char *pool_tags = (unsigned char*) def->constants.tags;
707 _Jv_word *pool_data = def->constants.data;
709 /* this entry was already prepared */
710 if (pool_tags[index] == this_tag)
711 return;
713 /* this_data points to the constant-pool information for the current
714 constant-pool entry */
716 unsigned char *this_data = bytes + offsets[index];
718 switch (this_tag)
720 case JV_CONSTANT_Utf8:
722 // If we came here, it is because some other tag needs this
723 // utf8-entry for type information! Thus, we translate /'s to .'s in
724 // order to accomondate gcj's internal representation.
726 int len = get2u (this_data);
727 char *buffer = (char*) __builtin_alloca (len);
728 char *s = ((char*) this_data)+2;
730 /* FIXME: avoid using a buffer here */
731 for (int i = 0; i < len; i++)
733 if (s[i] == '/')
734 buffer[i] = '.';
735 else
736 buffer[i] = (char) s[i];
739 pool_data[index].utf8 = _Jv_makeUtf8Const (buffer, len);
740 pool_tags[index] = JV_CONSTANT_Utf8;
742 break;
744 case JV_CONSTANT_Class:
746 int utf_index = get2u (this_data);
747 check_tag (utf_index, JV_CONSTANT_Utf8);
748 prepare_pool_entry (utf_index, JV_CONSTANT_Utf8);
750 if (verify)
751 verify_classname (pool_data[utf_index].utf8);
753 pool_data[index].utf8 = pool_data[utf_index].utf8;
754 pool_tags[index] = JV_CONSTANT_Class;
756 break;
758 case JV_CONSTANT_String:
759 // already handled before...
760 break;
762 case JV_CONSTANT_Fieldref:
763 case JV_CONSTANT_Methodref:
764 case JV_CONSTANT_InterfaceMethodref:
766 int class_index = get2u (this_data);
767 int nat_index = get2u (this_data+2);
769 check_tag (class_index, JV_CONSTANT_Class);
770 prepare_pool_entry (class_index, JV_CONSTANT_Class);
772 check_tag (nat_index, JV_CONSTANT_NameAndType);
773 prepare_pool_entry (nat_index, JV_CONSTANT_NameAndType);
775 // here, verify the signature and identifier name
776 if (verify)
778 _Jv_ushort name_index, type_index;
779 _Jv_loadIndexes (&pool_data[nat_index],
780 name_index, type_index);
782 if (this_tag == JV_CONSTANT_Fieldref)
783 verify_field_signature (pool_data[type_index].utf8);
784 else
785 verify_method_signature (pool_data[type_index].utf8);
787 _Jv_Utf8Const* name = pool_data[name_index].utf8;
789 if (this_tag != JV_CONSTANT_Fieldref
790 && ( _Jv_equalUtf8Consts (name, clinit_name)
791 || _Jv_equalUtf8Consts (name, init_name)))
792 /* ignore */;
793 else
794 verify_identifier (pool_data[name_index].utf8);
797 _Jv_storeIndexes (&pool_data[index], class_index, nat_index);
798 pool_tags[index] = this_tag;
800 break;
802 case JV_CONSTANT_NameAndType:
804 _Jv_ushort name_index = get2u (this_data);
805 _Jv_ushort type_index = get2u (this_data+2);
807 check_tag (name_index, JV_CONSTANT_Utf8);
808 prepare_pool_entry (name_index, JV_CONSTANT_Utf8);
810 check_tag (type_index, JV_CONSTANT_Utf8);
811 prepare_pool_entry (type_index, JV_CONSTANT_Utf8);
813 _Jv_storeIndexes (&pool_data[index], name_index, type_index);
814 pool_tags[index] = JV_CONSTANT_NameAndType;
816 break;
818 case JV_CONSTANT_Float:
820 jfloat f = java::lang::Float::intBitsToFloat ((jint) get4 (this_data));
821 _Jv_storeFloat (&pool_data[index], f);
822 pool_tags[index] = JV_CONSTANT_Float;
824 break;
826 case JV_CONSTANT_Integer:
828 int i = get4 (this_data);
829 _Jv_storeInt (&pool_data[index], i);
830 pool_tags[index] = JV_CONSTANT_Integer;
832 break;
834 case JV_CONSTANT_Double:
836 jdouble d
837 = java::lang::Double::longBitsToDouble ((jlong) get8 (this_data));
838 _Jv_storeDouble (&pool_data[index], d);
839 pool_tags[index] = JV_CONSTANT_Double;
841 break;
843 case JV_CONSTANT_Long:
845 jlong i = get8 (this_data);
846 _Jv_storeLong (&pool_data[index], i);
847 pool_tags[index] = JV_CONSTANT_Long;
849 break;
851 default:
852 throw_class_format_error ("erroneous constant pool tag");
857 void
858 _Jv_ClassReader::handleClassBegin (int access_flags, int this_class, int super_class)
860 using namespace java::lang::reflect;
862 unsigned char *pool_tags = (unsigned char*) def->constants.tags;
863 _Jv_word *pool_data = def->constants.data;
865 check_tag (this_class, JV_CONSTANT_Class);
866 _Jv_Utf8Const *loadedName = pool_data[this_class].utf8;
868 // was ClassLoader.defineClass called with an expected class name?
869 if (def->name == 0)
871 jclass orig = _Jv_FindClassInCache (loadedName, def->loader);
873 if (orig == 0)
875 def->name = loadedName;
877 else
879 jstring msg = JvNewStringUTF ("anonymous "
880 "class data denotes "
881 "existing class ");
882 msg = msg->concat (orig->getName ());
884 throw_no_class_def_found_error (msg);
888 // assert that the loaded class has the expected name, 5.3.5
889 else if (! _Jv_equalUtf8Consts (loadedName, def->name))
891 jstring msg = JvNewStringUTF ("loaded class ");
892 msg = msg->concat (def->getName ());
893 msg = msg->concat (_Jv_NewStringUTF (" was in fact named "));
894 jstring klass_name = loadedName->toString();
895 msg = msg->concat (klass_name);
897 throw_no_class_def_found_error (msg);
900 def->accflags = access_flags | java::lang::reflect::Modifier::INTERPRETED;
901 pool_data[this_class].clazz = def;
902 pool_tags[this_class] = JV_CONSTANT_ResolvedClass;
904 if (super_class == 0 && ! (access_flags & Modifier::INTERFACE))
906 // FIXME: Consider this carefully!
907 if (! _Jv_equalUtf8Consts (def->name, java::lang::Object::class$.name))
908 throw_no_class_def_found_error ("loading java.lang.Object");
911 // In the pre-loading state, it can be looked up in the
912 // cache only by this thread! This allows the super-class
913 // to include references to this class.
915 def->state = JV_STATE_PRELOADING;
918 JvSynchronize sync (&java::lang::Class::class$);
919 _Jv_RegisterClass (def);
922 if (super_class != 0)
924 // Load the superclass.
925 check_tag (super_class, JV_CONSTANT_Class);
926 _Jv_Utf8Const* super_name = pool_data[super_class].utf8;
928 // Load the superclass using our defining loader.
929 jclass the_super = _Jv_FindClass (super_name,
930 def->loader);
932 // This will establish that we are allowed to be a subclass,
933 // and check for class circularity error.
934 checkExtends (def, the_super);
936 // Note: for an interface we will find Object as the
937 // superclass. We still check it above to ensure class file
938 // validity, but we simply assign `null' to the actual field in
939 // this case.
940 def->superclass = (((access_flags & Modifier::INTERFACE))
941 ? NULL : the_super);
942 pool_data[super_class].clazz = the_super;
943 pool_tags[super_class] = JV_CONSTANT_ResolvedClass;
946 // Now we've come past the circularity problem, we can
947 // now say that we're loading.
949 def->state = JV_STATE_LOADING;
950 def->notifyAll ();
953 ///// Implements the checks described in sect. 5.3.5.3
954 void
955 _Jv_ClassReader::checkExtends (jclass sub, jclass super)
957 using namespace java::lang::reflect;
959 _Jv_Linker::wait_for_state (super, JV_STATE_LOADING);
961 // Having an interface or a final class as a superclass is no good.
962 if ((super->accflags & (Modifier::INTERFACE | Modifier::FINAL)) != 0)
964 throw_incompatible_class_change_error (sub->getName ());
967 // If the super class is not public, we need to check some more.
968 if ((super->accflags & Modifier::PUBLIC) == 0)
970 // With package scope, the classes must have the same class
971 // loader.
972 if ( sub->loader != super->loader
973 || !_Jv_ClassNameSamePackage (sub->name, super->name))
975 throw_incompatible_class_change_error (sub->getName ());
979 for (; super != 0; super = super->getSuperclass ())
981 if (super == sub)
982 throw_class_circularity_error (sub->getName ());
988 void _Jv_ClassReader::handleInterfacesBegin (int count)
990 def->interfaces = (jclass*) _Jv_AllocBytes (count*sizeof (jclass));
991 def->interface_count = count;
994 void _Jv_ClassReader::handleInterface (int if_number, int offset)
996 _Jv_word * pool_data = def->constants.data;
997 unsigned char * pool_tags = (unsigned char*) def->constants.tags;
999 jclass the_interface;
1001 if (pool_tags[offset] == JV_CONSTANT_Class)
1003 _Jv_Utf8Const* name = pool_data[offset].utf8;
1004 the_interface = _Jv_FindClass (name, def->loader);
1006 else if (pool_tags[offset] == JV_CONSTANT_ResolvedClass)
1008 the_interface = pool_data[offset].clazz;
1010 else
1012 throw_no_class_def_found_error ("erroneous constant pool tag");
1015 // checks the validity of the_interface, and that we are in fact
1016 // allowed to implement that interface.
1017 checkImplements (def, the_interface);
1019 pool_data[offset].clazz = the_interface;
1020 pool_tags[offset] = JV_CONSTANT_ResolvedClass;
1022 def->interfaces[if_number] = the_interface;
1025 void
1026 _Jv_ClassReader::checkImplements (jclass sub, jclass super)
1028 using namespace java::lang::reflect;
1030 // well, it *must* be an interface
1031 if ((super->accflags & Modifier::INTERFACE) == 0)
1033 throw_incompatible_class_change_error (sub->getName ());
1036 // if it has package scope, it must also be defined by the
1037 // same loader.
1038 if ((super->accflags & Modifier::PUBLIC) == 0)
1040 if ( sub->loader != super->loader
1041 || !_Jv_ClassNameSamePackage (sub->name, super->name))
1043 throw_incompatible_class_change_error (sub->getName ());
1047 // FIXME: add interface circularity check here
1048 if (sub == super)
1050 throw_class_circularity_error (sub->getName ());
1054 void _Jv_ClassReader::handleFieldsBegin (int count)
1056 def->fields = (_Jv_Field*)
1057 _Jv_AllocBytes (count * sizeof (_Jv_Field));
1058 def->field_count = count;
1059 def_interp->field_initializers = (_Jv_ushort*)
1060 _Jv_AllocBytes (count * sizeof (_Jv_ushort));
1061 for (int i = 0; i < count; i++)
1062 def_interp->field_initializers[i] = (_Jv_ushort) 0;
1065 void _Jv_ClassReader::handleField (int field_no,
1066 int flags,
1067 int name,
1068 int desc)
1070 using namespace java::lang::reflect;
1072 _Jv_word *pool_data = def->constants.data;
1074 _Jv_Field *field = &def->fields[field_no];
1075 _Jv_Utf8Const *field_name = pool_data[name].utf8;
1077 field->name = field_name;
1079 // Ignore flags we don't know about.
1080 field->flags = flags & Modifier::ALL_FLAGS;
1082 _Jv_Utf8Const* sig = pool_data[desc].utf8;
1084 if (verify)
1086 verify_identifier (field_name);
1088 for (int i = 0; i < field_no; ++i)
1090 if (_Jv_equalUtf8Consts (field_name, def->fields[i].name)
1091 && _Jv_equalUtf8Consts (sig,
1092 // We know the other fields are
1093 // unresolved.
1094 (_Jv_Utf8Const *) def->fields[i].type))
1095 throw_class_format_error ("duplicate field name");
1098 // At most one of PUBLIC, PRIVATE, or PROTECTED is allowed.
1099 if (1 < ( ((field->flags & Modifier::PUBLIC) ? 1 : 0)
1100 +((field->flags & Modifier::PRIVATE) ? 1 : 0)
1101 +((field->flags & Modifier::PROTECTED) ? 1 : 0)))
1102 throw_class_format_error ("erroneous field access flags");
1104 // FIXME: JVM spec S4.5: Verify ACC_FINAL and ACC_VOLATILE are not
1105 // both set. Verify modifiers for interface fields.
1109 if (verify)
1110 verify_field_signature (sig);
1112 // field->type is really a jclass, but while it is still
1113 // unresolved we keep an _Jv_Utf8Const* instead.
1114 field->type = (jclass) sig;
1115 field->flags |= _Jv_FIELD_UNRESOLVED_FLAG;
1116 field->u.boffset = 0;
1120 void _Jv_ClassReader::handleConstantValueAttribute (int field_index,
1121 int value)
1123 using namespace java::lang::reflect;
1125 _Jv_Field *field = &def->fields[field_index];
1127 if ((field->flags & (Modifier::STATIC
1128 | Modifier::FINAL
1129 | Modifier::PRIVATE)) == 0)
1131 // Ignore, as per vmspec #4.7.2
1132 return;
1135 // do not allow multiple constant fields!
1136 if (field->flags & _Jv_FIELD_CONSTANT_VALUE)
1137 throw_class_format_error ("field has multiple ConstantValue attributes");
1139 field->flags |= _Jv_FIELD_CONSTANT_VALUE;
1140 def_interp->field_initializers[field_index] = value;
1142 /* type check the initializer */
1144 if (value <= 0 || value >= pool_count)
1145 throw_class_format_error ("erroneous ConstantValue attribute");
1147 /* FIXME: do the rest */
1150 void _Jv_ClassReader::handleFieldsEnd ()
1152 using namespace java::lang::reflect;
1154 // We need to reorganize the fields so that the static ones are first,
1155 // to conform to GCJ class layout.
1157 int low = 0;
1158 int high = def->field_count-1;
1159 _Jv_Field *fields = def->fields;
1160 _Jv_ushort *inits = def_interp->field_initializers;
1162 // this is kind of a raw version of quicksort.
1163 while (low < high)
1165 // go forward on low, while it's a static
1166 while (low < high && (fields[low].flags & Modifier::STATIC) != 0)
1167 low++;
1169 // go backwards on high, while it's a non-static
1170 while (low < high && (fields[high].flags & Modifier::STATIC) == 0)
1171 high--;
1173 if (low==high)
1174 break;
1176 _Jv_Field tmp = fields[low];
1177 _Jv_ushort itmp = inits[low];
1179 fields[low] = fields[high];
1180 inits[low] = inits[high];
1182 fields[high] = tmp;
1183 inits[high] = itmp;
1185 high -= 1;
1186 low += 1;
1189 if ((fields[low].flags & Modifier::STATIC) != 0)
1190 low += 1;
1192 def->static_field_count = low;
1197 void
1198 _Jv_ClassReader::handleMethodsBegin (int count)
1200 def->methods = (_Jv_Method *) _Jv_AllocBytes (sizeof (_Jv_Method) * count);
1202 def_interp->interpreted_methods
1203 = (_Jv_MethodBase **) _Jv_AllocBytes (sizeof (_Jv_MethodBase *)
1204 * count);
1206 for (int i = 0; i < count; i++)
1208 def_interp->interpreted_methods[i] = 0;
1209 def->methods[i].index = (_Jv_ushort) -1;
1212 def->method_count = count;
1216 void _Jv_ClassReader::handleMethod
1217 (int mth_index, int accflags, int name, int desc)
1219 using namespace java::lang::reflect;
1221 _Jv_word *pool_data = def->constants.data;
1222 _Jv_Method *method = &def->methods[mth_index];
1224 check_tag (name, JV_CONSTANT_Utf8);
1225 prepare_pool_entry (name, JV_CONSTANT_Utf8);
1226 method->name = pool_data[name].utf8;
1228 check_tag (desc, JV_CONSTANT_Utf8);
1229 prepare_pool_entry (desc, JV_CONSTANT_Utf8);
1230 method->signature = pool_data[desc].utf8;
1232 // ignore unknown flags
1233 method->accflags = accflags & Modifier::ALL_FLAGS;
1235 // Initialize...
1236 method->ncode = 0;
1237 method->throws = NULL;
1239 if (verify)
1241 if (_Jv_equalUtf8Consts (method->name, clinit_name)
1242 || _Jv_equalUtf8Consts (method->name, init_name))
1243 /* ignore */;
1244 else
1245 verify_identifier (method->name);
1247 verify_method_signature (method->signature);
1249 for (int i = 0; i < mth_index; ++i)
1251 if (_Jv_equalUtf8Consts (method->name, def->methods[i].name)
1252 && _Jv_equalUtf8Consts (method->signature,
1253 def->methods[i].signature))
1254 throw_class_format_error ("duplicate method");
1257 // At most one of PUBLIC, PRIVATE, or PROTECTED is allowed.
1258 if (1 < ( ((method->accflags & Modifier::PUBLIC) ? 1 : 0)
1259 +((method->accflags & Modifier::PRIVATE) ? 1 : 0)
1260 +((method->accflags & Modifier::PROTECTED) ? 1 : 0)))
1261 throw_class_format_error ("erroneous method access flags");
1263 // FIXME: JVM spec S4.6: if ABSTRACT modifier is set, verify other
1264 // flags are not set. Verify flags for interface methods. Verifiy
1265 // modifiers for initializers.
1269 void _Jv_ClassReader::handleCodeAttribute
1270 (int method_index, int max_stack, int max_locals,
1271 int code_start, int code_length, int exc_table_length)
1273 int size = _Jv_InterpMethod::size (exc_table_length, code_length);
1274 _Jv_InterpMethod *method =
1275 (_Jv_InterpMethod*) (_Jv_AllocBytes (size));
1277 method->max_stack = max_stack;
1278 method->max_locals = max_locals;
1279 method->code_length = code_length;
1280 method->exc_count = exc_table_length;
1281 method->defining_class = def;
1282 method->self = &def->methods[method_index];
1283 method->prepared = NULL;
1285 // grab the byte code!
1286 memcpy ((void*) method->bytecode (),
1287 (void*) (bytes+code_start),
1288 code_length);
1290 def_interp->interpreted_methods[method_index] = method;
1292 if ((method->self->accflags & java::lang::reflect::Modifier::STATIC))
1294 // Precompute the ncode field for a static method. This lets us
1295 // call a static method of an interpreted class from precompiled
1296 // code without first resolving the class (that will happen
1297 // during class initialization instead).
1298 method->self->ncode = method->ncode ();
1302 void _Jv_ClassReader::handleExceptionTableEntry
1303 (int method_index, int exc_index,
1304 int start_pc, int end_pc, int handler_pc, int catch_type)
1306 _Jv_InterpMethod *method = reinterpret_cast<_Jv_InterpMethod *>
1307 (def_interp->interpreted_methods[method_index]);
1308 _Jv_InterpException *exc = method->exceptions ();
1310 exc[exc_index].start_pc.i = start_pc;
1311 exc[exc_index].end_pc.i = end_pc;
1312 exc[exc_index].handler_pc.i = handler_pc;
1313 exc[exc_index].handler_type.i = catch_type;
1316 void _Jv_ClassReader::handleMethodsEnd ()
1318 using namespace java::lang::reflect;
1320 for (int i = 0; i < def->method_count; i++)
1322 _Jv_Method *method = &def->methods[i];
1323 if ((method->accflags & Modifier::NATIVE) != 0)
1325 if (def_interp->interpreted_methods[i] != 0)
1326 throw_class_format_error ("code provided for native method");
1327 else
1329 _Jv_JNIMethod *m = (_Jv_JNIMethod *)
1330 _Jv_AllocBytes (sizeof (_Jv_JNIMethod));
1331 m->defining_class = def;
1332 m->self = method;
1333 m->function = NULL;
1334 def_interp->interpreted_methods[i] = m;
1336 if ((method->accflags & Modifier::STATIC))
1338 // Precompute the ncode field for a static method.
1339 // This lets us call a static method of an
1340 // interpreted class from precompiled code without
1341 // first resolving the class (that will happen
1342 // during class initialization instead).
1343 method->ncode = m->ncode ();
1347 else if ((method->accflags & Modifier::ABSTRACT) != 0)
1349 if (def_interp->interpreted_methods[i] != 0)
1350 throw_class_format_error ("code provided for abstract method");
1352 else
1354 if (def_interp->interpreted_methods[i] == 0)
1355 throw_class_format_error ("method with no code");
1360 void _Jv_ClassReader::throw_class_format_error (char *msg)
1362 jstring str;
1363 if (def->name != NULL)
1365 jsize mlen = strlen (msg);
1366 unsigned char* data = (unsigned char*) def->name->chars();
1367 int ulen = def->name->len();
1368 unsigned char* limit = data + ulen;
1369 jsize nlen = _Jv_strLengthUtf8 ((char *) data, ulen);
1370 jsize len = nlen + mlen + 3;
1371 str = JvAllocString(len);
1372 jchar *chrs = JvGetStringChars(str);
1373 while (data < limit)
1374 *chrs++ = UTF8_GET(data, limit);
1375 *chrs++ = ' ';
1376 *chrs++ = '(';
1377 for (;;)
1379 char c = *msg++;
1380 if (c == 0)
1381 break;
1382 *chrs++ = c & 0xFFFF;
1384 *chrs++ = ')';
1386 else
1387 str = JvNewStringLatin1 (msg);
1388 ::throw_class_format_error (str);
1391 /** Here we define the exceptions that can be thrown */
1393 static void
1394 throw_no_class_def_found_error (jstring msg)
1396 throw (msg
1397 ? new java::lang::NoClassDefFoundError (msg)
1398 : new java::lang::NoClassDefFoundError);
1401 static void
1402 throw_no_class_def_found_error (char *msg)
1404 throw_no_class_def_found_error (JvNewStringLatin1 (msg));
1407 static void
1408 throw_class_format_error (jstring msg)
1410 throw (msg
1411 ? new java::lang::ClassFormatError (msg)
1412 : new java::lang::ClassFormatError);
1415 static void
1416 throw_internal_error (char *msg)
1418 throw new java::lang::InternalError (JvNewStringLatin1 (msg));
1421 static void
1422 throw_incompatible_class_change_error (jstring msg)
1424 throw new java::lang::IncompatibleClassChangeError (msg);
1427 static void
1428 throw_class_circularity_error (jstring msg)
1430 throw new java::lang::ClassCircularityError (msg);
1433 #endif /* INTERPRETER */
1437 /** This section takes care of verifying integrity of identifiers,
1438 signatures, field ddescriptors, and class names */
1440 #define UTF8_PEEK(PTR, LIMIT) \
1441 ({ unsigned char* xxkeep = (PTR); \
1442 int xxch = UTF8_GET(PTR,LIMIT); \
1443 PTR = xxkeep; xxch; })
1445 /* Verify one element of a type descriptor or signature. */
1446 static unsigned char*
1447 _Jv_VerifyOne (unsigned char* ptr, unsigned char* limit, bool void_ok)
1449 if (ptr >= limit)
1450 return 0;
1452 int ch = UTF8_GET (ptr, limit);
1454 switch (ch)
1456 case 'V':
1457 if (! void_ok)
1458 return 0;
1460 case 'S': case 'B': case 'I': case 'J':
1461 case 'Z': case 'C': case 'F': case 'D':
1462 break;
1464 case 'L':
1466 unsigned char *start = ptr, *end;
1469 if (ptr > limit)
1470 return 0;
1472 end = ptr;
1474 if ((ch = UTF8_GET (ptr, limit)) == -1)
1475 return 0;
1478 while (ch != ';');
1479 if (! _Jv_VerifyClassName (start, (unsigned short) (end-start)))
1480 return 0;
1482 break;
1484 case '[':
1485 return _Jv_VerifyOne (ptr, limit, false);
1486 break;
1488 default:
1489 return 0;
1492 return ptr;
1495 /* Verification and loading procedures. */
1496 bool
1497 _Jv_VerifyFieldSignature (_Jv_Utf8Const*sig)
1499 unsigned char* ptr = (unsigned char*) sig->chars();
1500 unsigned char* limit = ptr + sig->len();
1502 ptr = _Jv_VerifyOne (ptr, limit, false);
1504 return ptr == limit;
1507 bool
1508 _Jv_VerifyMethodSignature (_Jv_Utf8Const*sig)
1510 unsigned char* ptr = (unsigned char*) sig->chars();
1511 unsigned char* limit = ptr + sig->len();
1513 if (ptr == limit || UTF8_GET(ptr,limit) != '(')
1514 return false;
1516 while (ptr && UTF8_PEEK (ptr, limit) != ')')
1517 ptr = _Jv_VerifyOne (ptr, limit, false);
1519 if (UTF8_GET (ptr, limit) != ')')
1520 return false;
1522 // get the return type
1523 ptr = _Jv_VerifyOne (ptr, limit, true);
1525 return ptr == limit;
1528 /* We try to avoid calling the Character methods all the time, in
1529 fact, they will only be called for non-standard things. */
1530 static __inline__ int
1531 is_identifier_start (int c)
1533 unsigned int ch = (unsigned)c;
1535 if ((ch - 0x41U) < 29U) /* A ... Z */
1536 return 1;
1537 if ((ch - 0x61U) < 29U) /* a ... z */
1538 return 1;
1539 if (ch == 0x5FU) /* _ */
1540 return 1;
1542 return java::lang::Character::isJavaIdentifierStart ((jchar) ch);
1545 static __inline__ int
1546 is_identifier_part (int c)
1548 unsigned int ch = (unsigned)c;
1550 if ((ch - 0x41U) < 29U) /* A ... Z */
1551 return 1;
1552 if ((ch - 0x61U) < 29U) /* a ... z */
1553 return 1;
1554 if ((ch - 0x30) < 10U) /* 0 .. 9 */
1555 return 1;
1556 if (ch == 0x5FU || ch == 0x24U) /* _ $ */
1557 return 1;
1559 return java::lang::Character::isJavaIdentifierStart ((jchar) ch);
1562 bool
1563 _Jv_VerifyIdentifier (_Jv_Utf8Const* name)
1565 unsigned char *ptr = (unsigned char*) name->chars();
1566 unsigned char *limit = (unsigned char*) name->limit();
1567 int ch;
1569 if ((ch = UTF8_GET (ptr, limit))==-1
1570 || ! is_identifier_start (ch))
1571 return false;
1573 while (ptr != limit)
1575 if ((ch = UTF8_GET (ptr, limit))==-1
1576 || ! is_identifier_part (ch))
1577 return false;
1579 return true;
1582 bool
1583 _Jv_VerifyClassName (unsigned char* ptr, _Jv_ushort length)
1585 unsigned char *limit = ptr+length;
1586 int ch;
1588 if ('[' == UTF8_PEEK (ptr, limit))
1590 unsigned char *end = _Jv_VerifyOne (++ptr, limit, false);
1591 // _Jv_VerifyOne must leave us looking at the terminating nul
1592 // byte.
1593 if (! end || *end)
1594 return false;
1595 else
1596 return true;
1599 next_level:
1600 for (;;) {
1601 if ((ch = UTF8_GET (ptr, limit))==-1)
1602 return false;
1603 if (! is_identifier_start (ch))
1604 return false;
1605 for (;;) {
1606 if (ptr == limit)
1607 return true;
1608 else if ((ch = UTF8_GET (ptr, limit))==-1)
1609 return false;
1610 else if (ch == '.')
1611 goto next_level;
1612 else if (! is_identifier_part (ch))
1613 return false;
1618 bool
1619 _Jv_VerifyClassName (_Jv_Utf8Const *name)
1621 return _Jv_VerifyClassName ((unsigned char*)name->chars(), name->len());
1624 /* Returns true, if NAME1 and NAME2 represent classes in the same
1625 package. Neither NAME2 nor NAME2 may name an array type. */
1626 bool
1627 _Jv_ClassNameSamePackage (_Jv_Utf8Const *name1, _Jv_Utf8Const *name2)
1629 unsigned char* ptr1 = (unsigned char*) name1->chars();
1630 unsigned char* limit1 = (unsigned char*) name1->limit();
1632 unsigned char* last1 = ptr1;
1634 // scan name1, and find the last occurrence of '.'
1635 while (ptr1 < limit1) {
1636 int ch1 = UTF8_GET (ptr1, limit1);
1638 if (ch1 == '.')
1639 last1 = ptr1;
1641 else if (ch1 == -1)
1642 return false;
1645 // Now the length of NAME1's package name is LEN.
1646 int len = last1 - (unsigned char*) name1->chars();
1648 // If this is longer than NAME2, then we're off.
1649 if (len > name2->len())
1650 return false;
1652 // Then compare the first len bytes for equality.
1653 if (memcmp ((void*) name1->chars(), (void*) name2->chars(), len) == 0)
1655 // Check that there are no .'s after position LEN in NAME2.
1657 unsigned char* ptr2 = (unsigned char*) name2->chars() + len;
1658 unsigned char* limit2 = (unsigned char*) name2->limit();
1660 while (ptr2 < limit2)
1662 int ch2 = UTF8_GET (ptr2, limit2);
1663 if (ch2 == -1 || ch2 == '.')
1664 return false;
1666 return true;
1668 return false;