* config/alpha/alpha.c (emit_insxl): Force the first operand of
[official-gcc.git] / libjava / defineclass.cc
blob12c6032862da0ab7ce72e7eab8838347b7cda717
1 // defineclass.cc - defining a class from .class format.
3 /* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 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/lang/reflect/Field.h>
43 #include <java/lang/reflect/Method.h>
44 #include <java/security/ProtectionDomain.h>
45 #include <java/io/DataOutputStream.h>
46 #include <java/io/ByteArrayOutputStream.h>
48 using namespace gcj;
50 #ifdef INTERPRETER
52 // these go in some separate functions, to avoid having _Jv_InitClass
53 // inserted all over the place.
54 static void throw_internal_error (const char *msg)
55 __attribute__ ((__noreturn__));
56 static void throw_no_class_def_found_error (jstring msg)
57 __attribute__ ((__noreturn__));
58 static void throw_no_class_def_found_error (const char *msg)
59 __attribute__ ((__noreturn__));
60 static void throw_class_format_error (jstring msg)
61 __attribute__ ((__noreturn__));
62 static void throw_incompatible_class_change_error (jstring msg)
63 __attribute__ ((__noreturn__));
64 static void throw_class_circularity_error (jstring msg)
65 __attribute__ ((__noreturn__));
67 /**
68 * We define class reading using a class. It is practical, since then
69 * the entire class-reader can be a friend of class Class (it needs to
70 * write all it's different structures); but also because this makes it
71 * easy to make class definition reentrant, and thus two threads can be
72 * defining classes at the same time. This class (_Jv_ClassReader) is
73 * never exposed outside this file, so we don't have to worry about
74 * public or private members here.
77 struct _Jv_ClassReader
80 // do verification? Currently, there is no option to disable this.
81 // This flag just controls the verificaiton done by the class loader;
82 // i.e., checking the integrity of the constant pool; and it is
83 // allways on. You always want this as far as I can see, but it also
84 // controls weither identifiers and type descriptors/signatures are
85 // verified as legal. This could be somewhat more expensive since it
86 // will call Character.isJavaIdentifier{Start,Part} for each character
87 // in any identifier (field name or method name) it comes by. Thus,
88 // it might be useful to turn off this verification for classes that
89 // come from a trusted source. However, for GCJ, trusted classes are
90 // most likely to be linked in.
92 bool verify;
94 // original input data.
95 jbyteArray input_data;
96 jint input_offset;
98 // input data.
99 unsigned char *bytes;
100 int len;
102 // current input position
103 int pos;
105 // the constant pool data
106 int pool_count;
107 unsigned char *tags;
108 unsigned int *offsets;
110 // the class to define (see java-interp.h)
111 jclass def;
113 // the classes associated interpreter data.
114 _Jv_InterpClass *def_interp;
116 // The name we found.
117 _Jv_Utf8Const **found_name;
119 // True if this is a 1.5 class file.
120 bool is_15;
122 // Buffer holding extra reflection data.
123 ::java::io::ByteArrayOutputStream *reflection_data;
124 ::java::io::DataOutputStream *data_stream;
127 /* check that the given number of input bytes are available */
128 inline void check (int num)
130 if (pos + num > len)
131 throw_class_format_error ("Premature end of data");
134 /* skip a given number of bytes in input */
135 inline void skip (int num)
137 check (num);
138 pos += num;
141 /* read an unsigned 1-byte unit */
142 inline static jint get1u (unsigned char* bytes)
144 return bytes[0];
147 /* read an unsigned 1-byte unit */
148 inline jint read1u ()
150 skip (1);
151 return get1u (bytes+pos-1);
154 /* read an unsigned 2-byte unit */
155 inline static jint get2u (unsigned char *bytes)
157 return (((jint)bytes[0]) << 8) | ((jint)bytes[1]);
160 /* read an unsigned 2-byte unit */
161 inline jint read2u ()
163 skip (2);
164 return get2u (bytes+pos-2);
167 /* read a 4-byte unit */
168 static jint get4 (unsigned char *bytes)
170 return (((jint)bytes[0]) << 24)
171 | (((jint)bytes[1]) << 16)
172 | (((jint)bytes[2]) << 8)
173 | (((jint)bytes[3]) << 0);
176 /* read a 4-byte unit, (we don't do that quite so often) */
177 inline jint read4 ()
179 skip (4);
180 return get4 (bytes+pos-4);
183 /* read a 8-byte unit */
184 static jlong get8 (unsigned char* bytes)
186 return (((jlong)bytes[0]) << 56)
187 | (((jlong)bytes[1]) << 48)
188 | (((jlong)bytes[2]) << 40)
189 | (((jlong)bytes[3]) << 32)
190 | (((jlong)bytes[4]) << 24)
191 | (((jlong)bytes[5]) << 16)
192 | (((jlong)bytes[6]) << 8)
193 | (((jlong)bytes[7]) << 0);
196 /* read a 8-byte unit */
197 inline jlong read8 ()
199 skip (8);
200 return get8 (bytes+pos-8);
203 inline void check_tag (int index, char expected_tag)
205 if (index < 0
206 || index > pool_count
207 || tags[index] != expected_tag)
208 throw_class_format_error ("erroneous constant pool tag");
211 inline void verify_identifier (_Jv_Utf8Const* name)
213 if (! _Jv_VerifyIdentifier (name))
214 throw_class_format_error ("erroneous identifier");
217 inline void verify_classname (unsigned char* ptr, _Jv_ushort length)
219 if (! _Jv_VerifyClassName (ptr, length))
220 throw_class_format_error ("erroneous class name");
223 inline void verify_classname (_Jv_Utf8Const *name)
225 if (! _Jv_VerifyClassName (name))
226 throw_class_format_error ("erroneous class name");
229 inline void verify_field_signature (_Jv_Utf8Const *sig)
231 if (! _Jv_VerifyFieldSignature (sig))
232 throw_class_format_error ("erroneous type descriptor");
235 inline void verify_method_signature (_Jv_Utf8Const *sig)
237 if (! _Jv_VerifyMethodSignature (sig))
238 throw_class_format_error ("erroneous type descriptor");
241 ::java::io::DataOutputStream *get_reflection_stream ()
243 if (reflection_data == NULL)
245 reflection_data = new ::java::io::ByteArrayOutputStream();
246 data_stream = new ::java::io::DataOutputStream(reflection_data);
248 return data_stream;
251 _Jv_ClassReader (jclass klass, jbyteArray data, jint offset, jint length,
252 java::security::ProtectionDomain *pd,
253 _Jv_Utf8Const **name_result)
255 if (klass == 0 || length < 0 || offset+length > data->length)
256 throw_internal_error ("arguments to _Jv_DefineClass");
258 verify = true;
259 input_data = data;
260 input_offset = offset;
261 bytes = (unsigned char*) (elements (data)+offset);
262 len = length;
263 pos = 0;
264 is_15 = false;
266 def = klass;
267 found_name = name_result;
268 reflection_data = NULL;
269 data_stream = NULL;
271 def->size_in_bytes = -1;
272 def->vtable_method_count = -1;
273 def->engine = &_Jv_soleInterpreterEngine;
274 def->protectionDomain = pd;
277 /** and here goes the parser members defined out-of-line */
278 void parse ();
279 void read_constpool ();
280 void prepare_pool_entry (int index, unsigned char tag,
281 bool rewrite = true);
282 void read_fields ();
283 void read_methods ();
284 void read_one_class_attribute ();
285 void read_one_method_attribute (int method);
286 void read_one_code_attribute (int method);
287 void read_one_field_attribute (int field, bool *);
288 void throw_class_format_error (const char *msg);
290 void handleEnclosingMethod(int);
291 void handleGenericSignature(jv_attr_type, unsigned short, int);
292 void handleAnnotationElement();
293 void handleAnnotation();
294 void handleAnnotations();
295 void handleMemberAnnotations(jv_attr_type, int, int);
296 void handleAnnotationDefault(int, int);
297 void handleParameterAnnotations(int, int);
298 void finish_reflection_data ();
300 /** check an utf8 entry, without creating a Utf8Const object */
301 bool is_attribute_name (int index, const char *name);
303 /** here goes the class-loader members defined out-of-line */
304 void handleConstantPool ();
305 void handleClassBegin (int, int, int);
306 void handleInterfacesBegin (int);
307 void handleInterface (int, int);
308 void handleFieldsBegin (int);
309 void handleField (int, int, int, int, int *);
310 void handleConstantValueAttribute (int, int, bool *);
311 void handleMethodsBegin (int);
312 void handleMethod (int, int, int, int);
313 void handleMethodsEnd ();
314 void handleCodeAttribute (int, int, int, int, int, int);
315 void handleExceptionTableEntry (int, int, int, int, int, int);
317 void checkExtends (jclass sub, jclass super);
318 void checkImplements (jclass sub, jclass super);
321 * FIXME: we should keep a hash table of utf8-strings, since many will
322 * be the same. It's a little tricky, however, because the hash table
323 * needs to interact gracefully with the garbage collector. Much
324 * memory is to be saved by this, however! perhaps the improvement
325 * could be implemented in prims.cc (_Jv_makeUtf8Const), since it
326 * computes the hash value anyway.
330 // Note that *NAME_RESULT will only be set if the class is registered
331 // with the class loader. This is how the caller can know whether
332 // unregistration is require.
333 void
334 _Jv_DefineClass (jclass klass, jbyteArray data, jint offset, jint length,
335 java::security::ProtectionDomain *pd,
336 _Jv_Utf8Const **name_result)
338 _Jv_ClassReader reader (klass, data, offset, length, pd, name_result);
339 reader.parse();
341 /* that's it! */
345 /** This section defines the parsing/scanning of the class data */
347 // Major and minor version numbers for various releases.
348 #define MAJOR_1_1 45
349 #define MINOR_1_1 3
350 #define MAJOR_1_2 46
351 #define MINOR_1_2 0
352 #define MAJOR_1_3 47
353 #define MINOR_1_3 0
354 #define MAJOR_1_4 48
355 #define MINOR_1_4 0
356 #define MAJOR_1_5 49
357 #define MINOR_1_5 0
359 void
360 _Jv_ClassReader::parse ()
362 int magic = read4 ();
363 if (magic != (int) 0xCAFEBABE)
364 throw_class_format_error ("bad magic number");
366 int minor_version = read2u ();
367 int major_version = read2u ();
368 if (major_version < MAJOR_1_1 || major_version > MAJOR_1_5
369 || (major_version == MAJOR_1_5 && minor_version > MINOR_1_5))
370 throw_class_format_error ("unrecognized class file version");
371 is_15 = (major_version == MAJOR_1_5);
373 pool_count = read2u ();
375 read_constpool ();
377 int access_flags = read2u ();
378 int this_class = read2u ();
379 int super_class = read2u ();
381 check_tag (this_class, JV_CONSTANT_Class);
382 if (super_class != 0)
383 check_tag (super_class, JV_CONSTANT_Class);
385 handleClassBegin (access_flags, this_class, super_class);
387 // Allocate our aux_info here, after the name is set, to fulfill our
388 // contract with the collector interface.
389 def->aux_info = (void *) _Jv_AllocRawObj (sizeof (_Jv_InterpClass));
390 def_interp = (_Jv_InterpClass *) def->aux_info;
392 int interfaces_count = read2u ();
394 handleInterfacesBegin (interfaces_count);
396 for (int i = 0; i < interfaces_count; i++)
398 int iface = read2u ();
399 check_tag (iface, JV_CONSTANT_Class);
400 handleInterface (i, iface);
403 read_fields ();
404 read_methods ();
406 int attributes_count = read2u ();
408 for (int i = 0; i < attributes_count; i++)
410 read_one_class_attribute ();
413 if (pos != len)
414 throw_class_format_error ("unused data before end of file");
416 finish_reflection_data ();
418 // Tell everyone we're done.
419 def->state = JV_STATE_READ;
420 if (gcj::verbose_class_flag)
421 _Jv_Linker::print_class_loaded (def);
422 ++gcj::loadedClasses;
423 def->notifyAll ();
426 void
427 _Jv_ClassReader::finish_reflection_data ()
429 if (data_stream == NULL)
430 return;
431 data_stream->writeByte(JV_DONE_ATTR);
432 data_stream->flush();
433 int nbytes = reflection_data->count;
434 unsigned char *new_bytes = (unsigned char *) _Jv_AllocBytes (nbytes);
435 memcpy (new_bytes, elements (reflection_data->buf), nbytes);
436 def->reflection_data = new_bytes;
439 void
440 _Jv_ClassReader::handleEnclosingMethod (int len)
442 if (len != 4)
443 throw_class_format_error ("invalid EnclosingMethod attribute");
444 // FIXME: only allow one...
446 int class_index = read2u();
447 check_tag (class_index, JV_CONSTANT_Class);
448 prepare_pool_entry (class_index, JV_CONSTANT_Class);
450 int method_index = read2u();
451 // Zero is ok and means no enclosing method.
452 if (method_index != 0)
454 check_tag (method_index, JV_CONSTANT_NameAndType);
455 prepare_pool_entry (method_index, JV_CONSTANT_NameAndType);
458 ::java::io::DataOutputStream *stream = get_reflection_stream ();
459 stream->writeByte(JV_CLASS_ATTR);
460 stream->writeInt(5);
461 stream->writeByte(JV_ENCLOSING_METHOD_KIND);
462 stream->writeShort(class_index);
463 stream->writeShort(method_index);
466 void
467 _Jv_ClassReader::handleGenericSignature (jv_attr_type type,
468 unsigned short index,
469 int len)
471 if (len != 2)
472 throw_class_format_error ("invalid Signature attribute");
474 int cpool_idx = read2u();
475 check_tag (cpool_idx, JV_CONSTANT_Utf8);
476 prepare_pool_entry (cpool_idx, JV_CONSTANT_Utf8, false);
478 ::java::io::DataOutputStream *stream = get_reflection_stream ();
479 stream->writeByte(type);
480 int attrlen = 3;
481 if (type != JV_CLASS_ATTR)
482 attrlen += 2;
483 stream->writeInt(attrlen);
484 if (type != JV_CLASS_ATTR)
485 stream->writeShort(index);
486 stream->writeByte(JV_SIGNATURE_KIND);
487 stream->writeShort(cpool_idx);
490 void
491 _Jv_ClassReader::handleAnnotationElement()
493 int tag = read1u();
494 switch (tag)
496 case 'B':
497 case 'C':
498 case 'S':
499 case 'Z':
500 case 'I':
502 int index = read2u();
503 check_tag (index, JV_CONSTANT_Integer);
504 prepare_pool_entry (index, JV_CONSTANT_Integer);
506 break;
507 case 'D':
509 int index = read2u();
510 check_tag (index, JV_CONSTANT_Double);
511 prepare_pool_entry (index, JV_CONSTANT_Double);
513 break;
514 case 'F':
516 int index = read2u();
517 check_tag (index, JV_CONSTANT_Float);
518 prepare_pool_entry (index, JV_CONSTANT_Float);
520 break;
521 case 'J':
523 int index = read2u();
524 check_tag (index, JV_CONSTANT_Long);
525 prepare_pool_entry (index, JV_CONSTANT_Long);
527 break;
528 case 's':
530 int index = read2u();
531 // Despite what the JVM spec says, compilers generate a Utf8
532 // constant here, not a String.
533 check_tag (index, JV_CONSTANT_Utf8);
534 prepare_pool_entry (index, JV_CONSTANT_Utf8, false);
536 break;
538 case 'e':
540 int type_name_index = read2u();
541 int const_name_index = read2u ();
542 check_tag (type_name_index, JV_CONSTANT_Utf8);
543 prepare_pool_entry (type_name_index, JV_CONSTANT_Utf8);
544 check_tag (const_name_index, JV_CONSTANT_Utf8);
545 prepare_pool_entry (const_name_index, JV_CONSTANT_Utf8, false);
547 break;
548 case 'c':
550 int index = read2u();
551 check_tag (index, JV_CONSTANT_Utf8);
552 prepare_pool_entry (index, JV_CONSTANT_Utf8);
554 break;
555 case '@':
556 handleAnnotation();
557 break;
558 case '[':
560 int n_array_elts = read2u ();
561 for (int i = 0; i < n_array_elts; ++i)
562 handleAnnotationElement();
564 break;
565 default:
566 throw_class_format_error ("invalid annotation element");
570 void
571 _Jv_ClassReader::handleAnnotation()
573 int type_index = read2u();
574 check_tag (type_index, JV_CONSTANT_Utf8);
575 prepare_pool_entry (type_index, JV_CONSTANT_Utf8);
577 int npairs = read2u();
578 for (int i = 0; i < npairs; ++i)
580 int name_index = read2u();
581 check_tag (name_index, JV_CONSTANT_Utf8);
582 prepare_pool_entry (name_index, JV_CONSTANT_Utf8, false);
583 handleAnnotationElement();
587 void
588 _Jv_ClassReader::handleAnnotations()
590 int num = read2u();
591 while (num--)
592 handleAnnotation();
595 void
596 _Jv_ClassReader::handleMemberAnnotations(jv_attr_type member_type,
597 int member_index,
598 int len)
600 // We're going to copy the bytes in verbatim. But first we want to
601 // make sure the attribute is well-formed, and we want to prepare
602 // the constant pool. So, we save our starting point.
603 int orig_pos = pos;
605 handleAnnotations();
606 // FIXME: check that we read all LEN bytes?
608 ::java::io::DataOutputStream *stream = get_reflection_stream ();
609 stream->writeByte(member_type);
610 int newLen = len + 1;
611 if (member_type != JV_CLASS_ATTR)
612 newLen += 2;
613 stream->writeInt(newLen);
614 stream->writeByte(JV_ANNOTATIONS_KIND);
615 if (member_type != JV_CLASS_ATTR)
616 stream->writeShort(member_index);
617 // Write the data as-is.
618 stream->write(input_data, input_offset + orig_pos, len);
621 void
622 _Jv_ClassReader::handleAnnotationDefault(int member_index, int len)
624 int orig_pos = pos;
625 handleAnnotationElement();
627 ::java::io::DataOutputStream *stream = get_reflection_stream ();
628 stream->writeByte(JV_METHOD_ATTR);
629 stream->writeInt(len + 3);
630 stream->writeByte(JV_ANNOTATION_DEFAULT_KIND);
631 stream->writeShort(member_index);
632 stream->write(input_data, input_offset + orig_pos, len);
635 void
636 _Jv_ClassReader::handleParameterAnnotations(int member_index, int len)
638 int orig_pos = pos;
640 int n_params = read1u();
641 for (int i = 0; i < n_params; ++i)
642 handleAnnotations();
644 ::java::io::DataOutputStream *stream = get_reflection_stream ();
645 stream->writeByte(JV_METHOD_ATTR);
646 stream->writeInt(len + 3);
647 stream->writeByte(JV_PARAMETER_ANNOTATIONS_KIND);
648 stream->writeShort(member_index);
649 stream->write(input_data, input_offset + orig_pos, len);
652 void _Jv_ClassReader::read_constpool ()
654 tags = (unsigned char*) _Jv_AllocBytes (pool_count);
655 offsets = (unsigned int *) _Jv_AllocBytes (sizeof (int) * pool_count) ;
657 /** first, we scan the constant pool, collecting tags and offsets */
658 tags[0] = JV_CONSTANT_Undefined;
659 offsets[0] = pos;
660 for (int c = 1; c < pool_count; c++)
662 tags[c] = read1u ();
663 offsets[c] = pos;
665 switch (tags[c])
667 case JV_CONSTANT_String:
668 case JV_CONSTANT_Class:
669 skip (2);
670 break;
672 case JV_CONSTANT_Fieldref:
673 case JV_CONSTANT_Methodref:
674 case JV_CONSTANT_InterfaceMethodref:
675 case JV_CONSTANT_NameAndType:
676 case JV_CONSTANT_Integer:
677 case JV_CONSTANT_Float:
678 skip (4);
679 break;
681 case JV_CONSTANT_Double:
682 case JV_CONSTANT_Long:
683 skip (8);
684 tags[++c] = JV_CONSTANT_Undefined;
685 break;
687 case JV_CONSTANT_Utf8:
689 int len = read2u ();
690 skip (len);
692 break;
694 case JV_CONSTANT_Unicode:
695 throw_class_format_error ("unicode not supported");
696 break;
698 default:
699 throw_class_format_error ("erroneous constant pool tag");
703 handleConstantPool ();
707 void _Jv_ClassReader::read_fields ()
709 int fields_count = read2u ();
710 handleFieldsBegin (fields_count);
712 // We want to sort the fields so that static fields come first,
713 // followed by instance fields. We do this before parsing the
714 // fields so that we can have the new indices available when
715 // creating the annotation data structures.
717 // Allocate this on the heap in case there are a large number of
718 // fields.
719 int *fieldmap = (int *) _Jv_AllocBytes (fields_count * sizeof (int));
720 int save_pos = pos;
721 int static_count = 0, instance_count = -1;
722 for (int i = 0; i < fields_count; ++i)
724 using namespace java::lang::reflect;
726 int access_flags = read2u ();
727 skip (4);
728 int attributes_count = read2u ();
730 if ((access_flags & Modifier::STATIC) != 0)
731 fieldmap[i] = static_count++;
732 else
733 fieldmap[i] = instance_count--;
735 for (int j = 0; j < attributes_count; ++j)
737 skip (2);
738 int length = read4 ();
739 skip (length);
742 pos = save_pos;
744 // In the loop above, instance fields are represented by negative
745 // numbers. Here we rewrite these to be proper offsets.
746 for (int i = 0; i < fields_count; ++i)
748 if (fieldmap[i] < 0)
749 fieldmap[i] = static_count - 1 - fieldmap[i];
751 def->static_field_count = static_count;
753 for (int i = 0; i < fields_count; i++)
755 int access_flags = read2u ();
756 int name_index = read2u ();
757 int descriptor_index = read2u ();
758 int attributes_count = read2u ();
760 check_tag (name_index, JV_CONSTANT_Utf8);
761 prepare_pool_entry (name_index, JV_CONSTANT_Utf8);
763 check_tag (descriptor_index, JV_CONSTANT_Utf8);
764 prepare_pool_entry (descriptor_index, JV_CONSTANT_Utf8);
766 handleField (i, access_flags, name_index, descriptor_index, fieldmap);
768 bool found_value = false;
769 for (int j = 0; j < attributes_count; j++)
771 read_one_field_attribute (fieldmap[i], &found_value);
776 bool
777 _Jv_ClassReader::is_attribute_name (int index, const char *name)
779 check_tag (index, JV_CONSTANT_Utf8);
780 int len = get2u (bytes+offsets[index]);
781 if (len != (int) strlen (name))
782 return false;
783 else
784 return !memcmp (bytes+offsets[index]+2, name, len);
787 void _Jv_ClassReader::read_one_field_attribute (int field_index,
788 bool *found_value)
790 int name = read2u ();
791 int length = read4 ();
793 if (is_attribute_name (name, "ConstantValue"))
795 int cv = read2u ();
797 if (cv < pool_count
798 && cv > 0
799 && (tags[cv] == JV_CONSTANT_Integer
800 || tags[cv] == JV_CONSTANT_Float
801 || tags[cv] == JV_CONSTANT_Long
802 || tags[cv] == JV_CONSTANT_Double
803 || tags[cv] == JV_CONSTANT_String))
805 handleConstantValueAttribute (field_index, cv, found_value);
807 else
809 throw_class_format_error ("erroneous ConstantValue attribute");
812 if (length != 2)
813 throw_class_format_error ("erroneous ConstantValue attribute");
815 else if (is_attribute_name (name, "Signature"))
816 handleGenericSignature(JV_FIELD_ATTR, field_index, length);
817 else if (is_attribute_name (name, "RuntimeVisibleAnnotations"))
818 handleMemberAnnotations(JV_FIELD_ATTR, field_index, length);
819 else
820 skip (length);
823 void _Jv_ClassReader::read_methods ()
825 int methods_count = read2u ();
827 handleMethodsBegin (methods_count);
829 for (int i = 0; i < methods_count; i++)
831 int access_flags = read2u ();
832 int name_index = read2u ();
833 int descriptor_index = read2u ();
834 int attributes_count = read2u ();
836 check_tag (name_index, JV_CONSTANT_Utf8);
837 prepare_pool_entry (name_index, JV_CONSTANT_Utf8);
839 check_tag (descriptor_index, JV_CONSTANT_Utf8);
840 prepare_pool_entry (descriptor_index, JV_CONSTANT_Utf8);
842 handleMethod (i, access_flags, name_index,
843 descriptor_index);
845 for (int j = 0; j < attributes_count; j++)
847 read_one_method_attribute (i);
851 handleMethodsEnd ();
854 void _Jv_ClassReader::read_one_method_attribute (int method_index)
856 int name = read2u ();
857 int length = read4 ();
859 if (is_attribute_name (name, "Exceptions"))
861 _Jv_Method *method = reinterpret_cast<_Jv_Method *>
862 (&def->methods[method_index]);
863 if (method->throws != NULL)
864 throw_class_format_error ("only one Exceptions attribute allowed per method");
866 int num_exceptions = read2u ();
867 _Jv_Utf8Const **exceptions =
868 (_Jv_Utf8Const **) _Jv_AllocBytes ((num_exceptions + 1)
869 * sizeof (_Jv_Utf8Const *));
871 int out = 0;
872 _Jv_word *pool_data = def->constants.data;
873 for (int i = 0; i < num_exceptions; ++i)
875 int ndx = read2u ();
876 // JLS 2nd Ed. 4.7.5 requires that the tag not be 0.
877 if (ndx != 0)
879 check_tag (ndx, JV_CONSTANT_Class);
880 exceptions[out++] = pool_data[ndx].utf8;
883 exceptions[out] = NULL;
884 method->throws = exceptions;
887 else if (is_attribute_name (name, "Code"))
889 int start_off = pos;
890 int max_stack = read2u ();
891 int max_locals = read2u ();
892 int code_length = read4 ();
894 int code_start = pos;
895 skip (code_length);
896 int exception_table_length = read2u ();
898 handleCodeAttribute (method_index,
899 max_stack, max_locals,
900 code_start, code_length,
901 exception_table_length);
904 for (int i = 0; i < exception_table_length; i++)
906 int start_pc = read2u ();
907 int end_pc = read2u ();
908 int handler_pc = read2u ();
909 int catch_type = read2u ();
911 if (start_pc > end_pc
912 || start_pc < 0
913 // END_PC can be equal to CODE_LENGTH.
914 // See JVM Spec 4.7.4.
915 || end_pc > code_length
916 || handler_pc >= code_length)
917 throw_class_format_error ("erroneous exception handler info");
919 if (! (tags[catch_type] == JV_CONSTANT_Class
920 || tags[catch_type] == 0))
922 throw_class_format_error ("erroneous exception handler info");
925 handleExceptionTableEntry (method_index,
927 start_pc,
928 end_pc,
929 handler_pc,
930 catch_type);
934 int attributes_count = read2u ();
936 for (int i = 0; i < attributes_count; i++)
938 read_one_code_attribute (method_index);
941 if ((pos - start_off) != length)
942 throw_class_format_error ("code attribute too short");
944 else if (is_attribute_name (name, "Signature"))
945 handleGenericSignature(JV_METHOD_ATTR, method_index, length);
946 else if (is_attribute_name (name, "RuntimeVisibleAnnotations"))
947 handleMemberAnnotations(JV_METHOD_ATTR, method_index, length);
948 else if (is_attribute_name (name, "RuntimeVisibleParameterAnnotations"))
949 handleParameterAnnotations(method_index, length);
950 else if (is_attribute_name (name, "AnnotationDefault"))
951 handleAnnotationDefault(method_index, length);
952 else
954 /* ignore unknown attributes */
955 skip (length);
959 void _Jv_ClassReader::read_one_code_attribute (int method_index)
961 int name = read2u ();
962 int length = read4 ();
963 if (is_attribute_name (name, "LineNumberTable"))
965 _Jv_InterpMethod *method = reinterpret_cast<_Jv_InterpMethod *>
966 (def_interp->interpreted_methods[method_index]);
967 if (method->line_table != NULL)
968 throw_class_format_error ("Method already has LineNumberTable");
970 int table_len = read2u ();
971 _Jv_LineTableEntry* table
972 = (_Jv_LineTableEntry *) _Jv_AllocBytes (table_len
973 * sizeof (_Jv_LineTableEntry));
974 for (int i = 0; i < table_len; i++)
976 table[i].bytecode_pc = read2u ();
977 table[i].line = read2u ();
979 method->line_table_len = table_len;
980 method->line_table = table;
982 else
984 /* ignore unknown code attributes */
985 skip (length);
989 void _Jv_ClassReader::read_one_class_attribute ()
991 int name = read2u ();
992 int length = read4 ();
993 if (is_attribute_name (name, "SourceFile"))
995 int source_index = read2u ();
996 check_tag (source_index, JV_CONSTANT_Utf8);
997 prepare_pool_entry (source_index, JV_CONSTANT_Utf8, false);
998 def_interp->source_file_name = _Jv_NewStringUtf8Const
999 (def->constants.data[source_index].utf8);
1001 else if (is_attribute_name (name, "Signature"))
1002 handleGenericSignature(JV_CLASS_ATTR, 0, length);
1003 else if (is_attribute_name (name, "EnclosingMethod"))
1004 handleEnclosingMethod(length);
1005 else if (is_attribute_name (name, "RuntimeVisibleAnnotations"))
1006 handleMemberAnnotations(JV_CLASS_ATTR, 0, length);
1007 else if (is_attribute_name (name, "InnerClasses"))
1009 ::java::io::DataOutputStream *stream = get_reflection_stream ();
1010 stream->writeByte(JV_CLASS_ATTR);
1011 stream->writeInt(length + 1);
1012 stream->writeByte(JV_INNER_CLASSES_KIND);
1013 stream->write(input_data, input_offset + pos, length);
1014 skip (length);
1016 else
1018 /* Currently, we ignore most class attributes. */
1019 skip (length);
1026 /* this section defines the semantic actions of the parser */
1028 void _Jv_ClassReader::handleConstantPool ()
1030 /** now, we actually define the class' constant pool */
1032 jbyte *pool_tags = (jbyte*) _Jv_AllocBytes (pool_count);
1033 _Jv_word *pool_data
1034 = (_Jv_word*) _Jv_AllocRawObj (pool_count * sizeof (_Jv_word));
1036 def->constants.tags = pool_tags;
1037 def->constants.data = pool_data;
1038 def->constants.size = pool_count;
1040 // Here we make a pass to collect the strings! We do this, because
1041 // internally in the GCJ runtime, classes are encoded with .'s not /'s.
1042 // Therefore, we first collect the strings, and then translate the rest
1043 // of the utf8-entries (thus not representing strings) from /-notation
1044 // to .-notation.
1045 for (int i = 1; i < pool_count; i++)
1047 if (tags[i] == JV_CONSTANT_String)
1049 unsigned char* str_data = bytes + offsets [i];
1050 int utf_index = get2u (str_data);
1051 check_tag (utf_index, JV_CONSTANT_Utf8);
1052 unsigned char *utf_data = bytes + offsets[utf_index];
1053 int len = get2u (utf_data);
1054 pool_data[i].utf8 = _Jv_makeUtf8Const ((char*)(utf_data+2), len);
1055 pool_tags[i] = JV_CONSTANT_String;
1057 else
1059 pool_tags[i] = JV_CONSTANT_Undefined;
1063 // and now, we scan everything else but strings & utf8-entries. This
1064 // leaves out those utf8-entries which are not used; which will be left
1065 // with a tag of JV_CONSTANT_Undefined in the class definition.
1066 for (int index = 1; index < pool_count; index++)
1068 switch (tags[index])
1070 case JV_CONSTANT_Undefined:
1071 case JV_CONSTANT_String:
1072 case JV_CONSTANT_Utf8:
1073 continue;
1075 default:
1076 prepare_pool_entry (index, tags[index]);
1082 /* this is a recursive procedure, which will prepare pool entries as needed.
1083 Which is how we avoid initializing those entries which go unused.
1085 REWRITE is true iff this pool entry is the Utf8 representation of a
1086 class name or a signature.
1089 void
1090 _Jv_ClassReader::prepare_pool_entry (int index, unsigned char this_tag,
1091 bool rewrite)
1093 /* these two, pool_data and pool_tags, point into the class
1094 structure we are currently defining */
1096 unsigned char *pool_tags = (unsigned char*) def->constants.tags;
1097 _Jv_word *pool_data = def->constants.data;
1099 /* this entry was already prepared */
1100 if (pool_tags[index] == this_tag)
1101 return;
1103 /* this_data points to the constant-pool information for the current
1104 constant-pool entry */
1106 unsigned char *this_data = bytes + offsets[index];
1108 switch (this_tag)
1110 case JV_CONSTANT_Utf8:
1112 int len = get2u (this_data);
1113 char *s = ((char*) this_data)+2;
1114 pool_tags[index] = JV_CONSTANT_Utf8;
1116 if (! rewrite)
1118 pool_data[index].utf8 = _Jv_makeUtf8Const (s, len);
1119 break;
1122 // If REWRITE is set, it is because some other tag needs this
1123 // utf8-entry for type information: it is a class or a
1124 // signature. Thus, we translate /'s to .'s in order to
1125 // accomondate gcj's internal representation.
1126 char *buffer = (char*) __builtin_alloca (len);
1127 for (int i = 0; i < len; i++)
1129 if (s[i] == '/')
1130 buffer[i] = '.';
1131 else
1132 buffer[i] = s[i];
1134 pool_data[index].utf8 = _Jv_makeUtf8Const (buffer, len);
1136 break;
1138 case JV_CONSTANT_Class:
1140 int utf_index = get2u (this_data);
1141 check_tag (utf_index, JV_CONSTANT_Utf8);
1142 prepare_pool_entry (utf_index, JV_CONSTANT_Utf8);
1144 if (verify)
1145 verify_classname (pool_data[utf_index].utf8);
1147 pool_data[index].utf8 = pool_data[utf_index].utf8;
1148 pool_tags[index] = JV_CONSTANT_Class;
1150 break;
1152 case JV_CONSTANT_String:
1153 // already handled before...
1154 break;
1156 case JV_CONSTANT_Fieldref:
1157 case JV_CONSTANT_Methodref:
1158 case JV_CONSTANT_InterfaceMethodref:
1160 int class_index = get2u (this_data);
1161 int nat_index = get2u (this_data+2);
1163 check_tag (class_index, JV_CONSTANT_Class);
1164 prepare_pool_entry (class_index, JV_CONSTANT_Class);
1166 check_tag (nat_index, JV_CONSTANT_NameAndType);
1167 prepare_pool_entry (nat_index, JV_CONSTANT_NameAndType);
1169 // here, verify the signature and identifier name
1170 if (verify)
1172 _Jv_ushort name_index, type_index;
1173 _Jv_loadIndexes (&pool_data[nat_index],
1174 name_index, type_index);
1176 if (this_tag == JV_CONSTANT_Fieldref)
1177 verify_field_signature (pool_data[type_index].utf8);
1178 else
1179 verify_method_signature (pool_data[type_index].utf8);
1181 _Jv_Utf8Const* name = pool_data[name_index].utf8;
1183 if (this_tag != JV_CONSTANT_Fieldref
1184 && ( _Jv_equalUtf8Consts (name, clinit_name)
1185 || _Jv_equalUtf8Consts (name, init_name)))
1186 /* ignore */;
1187 else
1188 verify_identifier (pool_data[name_index].utf8);
1191 _Jv_storeIndexes (&pool_data[index], class_index, nat_index);
1192 pool_tags[index] = this_tag;
1194 break;
1196 case JV_CONSTANT_NameAndType:
1198 _Jv_ushort name_index = get2u (this_data);
1199 _Jv_ushort type_index = get2u (this_data+2);
1201 check_tag (name_index, JV_CONSTANT_Utf8);
1202 prepare_pool_entry (name_index, JV_CONSTANT_Utf8, false);
1203 check_tag (type_index, JV_CONSTANT_Utf8);
1204 prepare_pool_entry (type_index, JV_CONSTANT_Utf8);
1206 _Jv_storeIndexes (&pool_data[index], name_index, type_index);
1207 pool_tags[index] = JV_CONSTANT_NameAndType;
1209 break;
1211 case JV_CONSTANT_Float:
1213 jfloat f = java::lang::Float::intBitsToFloat ((jint) get4 (this_data));
1214 _Jv_storeFloat (&pool_data[index], f);
1215 pool_tags[index] = JV_CONSTANT_Float;
1217 break;
1219 case JV_CONSTANT_Integer:
1221 int i = get4 (this_data);
1222 _Jv_storeInt (&pool_data[index], i);
1223 pool_tags[index] = JV_CONSTANT_Integer;
1225 break;
1227 case JV_CONSTANT_Double:
1229 jdouble d
1230 = java::lang::Double::longBitsToDouble ((jlong) get8 (this_data));
1231 _Jv_storeDouble (&pool_data[index], d);
1232 pool_tags[index] = JV_CONSTANT_Double;
1234 break;
1236 case JV_CONSTANT_Long:
1238 jlong i = get8 (this_data);
1239 _Jv_storeLong (&pool_data[index], i);
1240 pool_tags[index] = JV_CONSTANT_Long;
1242 break;
1244 default:
1245 throw_class_format_error ("erroneous constant pool tag");
1250 void
1251 _Jv_ClassReader::handleClassBegin (int access_flags, int this_class, int super_class)
1253 using namespace java::lang::reflect;
1255 unsigned char *pool_tags = (unsigned char*) def->constants.tags;
1256 _Jv_word *pool_data = def->constants.data;
1258 check_tag (this_class, JV_CONSTANT_Class);
1259 _Jv_Utf8Const *loadedName = pool_data[this_class].utf8;
1261 // was ClassLoader.defineClass called with an expected class name?
1262 if (def->name == 0)
1264 jclass orig = def->loader->findLoadedClass(loadedName->toString());
1266 if (orig == 0)
1268 def->name = loadedName;
1270 else
1272 jstring msg = JvNewStringUTF ("anonymous "
1273 "class data denotes "
1274 "existing class ");
1275 msg = msg->concat (orig->getName ());
1277 throw_no_class_def_found_error (msg);
1281 // assert that the loaded class has the expected name, 5.3.5
1282 else if (! _Jv_equalUtf8Consts (loadedName, def->name))
1284 jstring msg = JvNewStringUTF ("loaded class ");
1285 msg = msg->concat (def->getName ());
1286 msg = msg->concat (_Jv_NewStringUTF (" was in fact named "));
1287 jstring klass_name = loadedName->toString();
1288 msg = msg->concat (klass_name);
1290 throw_no_class_def_found_error (msg);
1293 def->accflags = access_flags | java::lang::reflect::Modifier::INTERPRETED;
1294 pool_data[this_class].clazz = def;
1295 pool_tags[this_class] = JV_CONSTANT_ResolvedClass;
1297 if (super_class == 0)
1299 // Note that this is ok if we are defining java.lang.Object.
1300 // But there is no way to have this class be interpreted.
1301 throw_class_format_error ("no superclass reference");
1304 def->state = JV_STATE_PRELOADING;
1306 // Register this class with its defining loader as well (despite the
1307 // name of the function we're calling), so that super class lookups
1308 // work properly. If there is an error, our caller will unregister
1309 // this class from the class loader. Also, we don't need to hold a
1310 // lock here, as our caller has acquired it.
1311 _Jv_RegisterInitiatingLoader (def, def->loader);
1313 // Note that we found a name so that unregistration can happen if
1314 // needed.
1315 *found_name = def->name;
1317 if (super_class != 0)
1319 // Load the superclass.
1320 check_tag (super_class, JV_CONSTANT_Class);
1321 _Jv_Utf8Const* super_name = pool_data[super_class].utf8;
1323 // Load the superclass using our defining loader.
1324 jclass the_super = _Jv_FindClass (super_name, def->loader);
1326 // This will establish that we are allowed to be a subclass,
1327 // and check for class circularity error.
1328 checkExtends (def, the_super);
1330 // Note: for an interface we will find Object as the
1331 // superclass. We still check it above to ensure class file
1332 // validity, but we simply assign `null' to the actual field in
1333 // this case.
1334 def->superclass = (((access_flags & Modifier::INTERFACE))
1335 ? NULL : the_super);
1336 pool_data[super_class].clazz = the_super;
1337 pool_tags[super_class] = JV_CONSTANT_ResolvedClass;
1340 // Now we've come past the circularity problem, we can
1341 // now say that we're loading.
1343 def->state = JV_STATE_LOADING;
1344 def->notifyAll ();
1347 ///// Implements the checks described in sect. 5.3.5.3
1348 void
1349 _Jv_ClassReader::checkExtends (jclass sub, jclass super)
1351 using namespace java::lang::reflect;
1353 _Jv_Linker::wait_for_state (super, JV_STATE_LOADING);
1355 // Having an interface or a final class as a superclass is no good.
1356 if ((super->accflags & (Modifier::INTERFACE | Modifier::FINAL)) != 0)
1358 throw_incompatible_class_change_error (sub->getName ());
1361 // If the super class is not public, we need to check some more.
1362 if ((super->accflags & Modifier::PUBLIC) == 0)
1364 // With package scope, the classes must have the same class
1365 // loader.
1366 if ( sub->loader != super->loader
1367 || !_Jv_ClassNameSamePackage (sub->name, super->name))
1369 throw_incompatible_class_change_error (sub->getName ());
1373 for (; super != 0; super = super->getSuperclass ())
1375 if (super == sub)
1376 throw_class_circularity_error (sub->getName ());
1382 void _Jv_ClassReader::handleInterfacesBegin (int count)
1384 def->interfaces = (jclass*) _Jv_AllocRawObj (count*sizeof (jclass));
1385 def->interface_count = count;
1388 void _Jv_ClassReader::handleInterface (int if_number, int offset)
1390 _Jv_word * pool_data = def->constants.data;
1391 unsigned char * pool_tags = (unsigned char*) def->constants.tags;
1393 jclass the_interface;
1395 if (pool_tags[offset] == JV_CONSTANT_Class)
1397 _Jv_Utf8Const* name = pool_data[offset].utf8;
1398 the_interface = _Jv_FindClass (name, def->loader);
1400 else if (pool_tags[offset] == JV_CONSTANT_ResolvedClass)
1402 the_interface = pool_data[offset].clazz;
1404 else
1406 throw_no_class_def_found_error ("erroneous constant pool tag");
1409 // checks the validity of the_interface, and that we are in fact
1410 // allowed to implement that interface.
1411 checkImplements (def, the_interface);
1413 pool_data[offset].clazz = the_interface;
1414 pool_tags[offset] = JV_CONSTANT_ResolvedClass;
1416 def->interfaces[if_number] = the_interface;
1419 void
1420 _Jv_ClassReader::checkImplements (jclass sub, jclass super)
1422 using namespace java::lang::reflect;
1424 // well, it *must* be an interface
1425 if ((super->accflags & Modifier::INTERFACE) == 0)
1427 throw_incompatible_class_change_error (sub->getName ());
1430 // if it has package scope, it must also be defined by the
1431 // same loader.
1432 if ((super->accflags & Modifier::PUBLIC) == 0)
1434 if ( sub->loader != super->loader
1435 || !_Jv_ClassNameSamePackage (sub->name, super->name))
1437 throw_incompatible_class_change_error (sub->getName ());
1441 // FIXME: add interface circularity check here
1442 if (sub == super)
1444 throw_class_circularity_error (sub->getName ());
1448 void _Jv_ClassReader::handleFieldsBegin (int count)
1450 def->fields = (_Jv_Field*) _Jv_AllocRawObj (count * sizeof (_Jv_Field));
1451 def->field_count = count;
1452 def_interp->field_initializers
1453 = (_Jv_ushort*) _Jv_AllocRawObj (count * sizeof (_Jv_ushort));
1454 for (int i = 0; i < count; i++)
1455 def_interp->field_initializers[i] = (_Jv_ushort) 0;
1458 void _Jv_ClassReader::handleField (int field_no,
1459 int flags,
1460 int name,
1461 int desc,
1462 int *fieldmap)
1464 using namespace java::lang::reflect;
1466 _Jv_word *pool_data = def->constants.data;
1468 _Jv_Field *field = &def->fields[fieldmap[field_no]];
1469 _Jv_Utf8Const *field_name = pool_data[name].utf8;
1471 field->name = field_name;
1473 // Ignore flags we don't know about.
1474 field->flags = flags & (Field::FIELD_MODIFIERS
1475 | Modifier::SYNTHETIC
1476 | Modifier::ENUM);
1478 _Jv_Utf8Const* sig = pool_data[desc].utf8;
1480 if (verify)
1482 verify_identifier (field_name);
1484 for (int i = 0; i < field_no; ++i)
1486 if (_Jv_equalUtf8Consts (field_name, def->fields[fieldmap[i]].name)
1487 && _Jv_equalUtf8Consts (sig,
1488 // We know the other fields are
1489 // unresolved.
1490 (_Jv_Utf8Const *) def->fields[i].type))
1491 throw_class_format_error ("duplicate field name");
1494 // At most one of PUBLIC, PRIVATE, or PROTECTED is allowed.
1495 if (1 < ( ((field->flags & Modifier::PUBLIC) ? 1 : 0)
1496 +((field->flags & Modifier::PRIVATE) ? 1 : 0)
1497 +((field->flags & Modifier::PROTECTED) ? 1 : 0)))
1498 throw_class_format_error ("erroneous field access flags");
1500 // FIXME: JVM spec S4.5: Verify ACC_FINAL and ACC_VOLATILE are not
1501 // both set. Verify modifiers for interface fields.
1505 if (verify)
1506 verify_field_signature (sig);
1508 // field->type is really a jclass, but while it is still
1509 // unresolved we keep an _Jv_Utf8Const* instead.
1510 field->type = (jclass) sig;
1511 field->flags |= _Jv_FIELD_UNRESOLVED_FLAG;
1512 field->u.boffset = 0;
1516 void _Jv_ClassReader::handleConstantValueAttribute (int field_index,
1517 int value,
1518 bool *found_value)
1520 using namespace java::lang::reflect;
1522 _Jv_Field *field = &def->fields[field_index];
1524 if ((field->flags & (Modifier::STATIC
1525 | Modifier::FINAL
1526 | Modifier::PRIVATE)) == 0)
1528 // Ignore, as per vmspec #4.7.2
1529 return;
1532 // do not allow multiple constant fields!
1533 if (*found_value)
1534 throw_class_format_error ("field has multiple ConstantValue attributes");
1536 *found_value = true;
1537 def_interp->field_initializers[field_index] = value;
1539 /* type check the initializer */
1541 if (value <= 0 || value >= pool_count)
1542 throw_class_format_error ("erroneous ConstantValue attribute");
1544 /* FIXME: do the rest */
1547 void
1548 _Jv_ClassReader::handleMethodsBegin (int count)
1550 def->methods = (_Jv_Method *) _Jv_AllocRawObj (sizeof (_Jv_Method) * count);
1552 def_interp->interpreted_methods
1553 = (_Jv_MethodBase **) _Jv_AllocRawObj (sizeof (_Jv_MethodBase *)
1554 * count);
1556 for (int i = 0; i < count; i++)
1558 def_interp->interpreted_methods[i] = 0;
1559 def->methods[i].index = (_Jv_ushort) -1;
1562 def->method_count = count;
1566 void _Jv_ClassReader::handleMethod
1567 (int mth_index, int accflags, int name, int desc)
1569 using namespace java::lang::reflect;
1571 _Jv_word *pool_data = def->constants.data;
1572 _Jv_Method *method = &def->methods[mth_index];
1574 check_tag (name, JV_CONSTANT_Utf8);
1575 prepare_pool_entry (name, JV_CONSTANT_Utf8, false);
1576 method->name = pool_data[name].utf8;
1578 check_tag (desc, JV_CONSTANT_Utf8);
1579 prepare_pool_entry (desc, JV_CONSTANT_Utf8);
1580 method->signature = pool_data[desc].utf8;
1582 // ignore unknown flags
1583 method->accflags = accflags & (Method::METHOD_MODIFIERS
1584 | Modifier::BRIDGE
1585 | Modifier::SYNTHETIC
1586 | Modifier::VARARGS);
1588 // Initialize...
1589 method->ncode = 0;
1590 method->throws = NULL;
1592 if (verify)
1594 if (_Jv_equalUtf8Consts (method->name, clinit_name)
1595 || _Jv_equalUtf8Consts (method->name, init_name))
1596 /* ignore */;
1597 else
1598 verify_identifier (method->name);
1600 verify_method_signature (method->signature);
1602 for (int i = 0; i < mth_index; ++i)
1604 if (_Jv_equalUtf8Consts (method->name, def->methods[i].name)
1605 && _Jv_equalUtf8Consts (method->signature,
1606 def->methods[i].signature))
1607 throw_class_format_error ("duplicate method");
1610 // At most one of PUBLIC, PRIVATE, or PROTECTED is allowed.
1611 if (1 < ( ((method->accflags & Modifier::PUBLIC) ? 1 : 0)
1612 +((method->accflags & Modifier::PRIVATE) ? 1 : 0)
1613 +((method->accflags & Modifier::PROTECTED) ? 1 : 0)))
1614 throw_class_format_error ("erroneous method access flags");
1616 // FIXME: JVM spec S4.6: if ABSTRACT modifier is set, verify other
1617 // flags are not set. Verify flags for interface methods. Verify
1618 // modifiers for initializers.
1622 void _Jv_ClassReader::handleCodeAttribute
1623 (int method_index, int max_stack, int max_locals,
1624 int code_start, int code_length, int exc_table_length)
1626 int size = _Jv_InterpMethod::size (exc_table_length, code_length);
1627 _Jv_InterpMethod *method =
1628 (_Jv_InterpMethod*) (_Jv_AllocRawObj (size));
1630 method->max_stack = max_stack;
1631 method->max_locals = max_locals;
1632 method->code_length = code_length;
1633 method->exc_count = exc_table_length;
1634 method->is_15 = is_15;
1635 method->defining_class = def;
1636 method->self = &def->methods[method_index];
1637 method->prepared = NULL;
1638 method->line_table_len = 0;
1639 method->line_table = NULL;
1642 // grab the byte code!
1643 memcpy ((void*) method->bytecode (),
1644 (void*) (bytes+code_start),
1645 code_length);
1647 def_interp->interpreted_methods[method_index] = method;
1649 if ((method->self->accflags & java::lang::reflect::Modifier::STATIC))
1651 // Precompute the ncode field for a static method. This lets us
1652 // call a static method of an interpreted class from precompiled
1653 // code without first resolving the class (that will happen
1654 // during class initialization instead).
1655 method->self->ncode = method->ncode ();
1659 void _Jv_ClassReader::handleExceptionTableEntry
1660 (int method_index, int exc_index,
1661 int start_pc, int end_pc, int handler_pc, int catch_type)
1663 _Jv_InterpMethod *method = reinterpret_cast<_Jv_InterpMethod *>
1664 (def_interp->interpreted_methods[method_index]);
1665 _Jv_InterpException *exc = method->exceptions ();
1667 exc[exc_index].start_pc.i = start_pc;
1668 exc[exc_index].end_pc.i = end_pc;
1669 exc[exc_index].handler_pc.i = handler_pc;
1670 exc[exc_index].handler_type.i = catch_type;
1673 void _Jv_ClassReader::handleMethodsEnd ()
1675 using namespace java::lang::reflect;
1677 for (int i = 0; i < def->method_count; i++)
1679 _Jv_Method *method = &def->methods[i];
1680 if ((method->accflags & Modifier::NATIVE) != 0)
1682 if (def_interp->interpreted_methods[i] != 0)
1683 throw_class_format_error ("code provided for native method");
1684 else
1686 _Jv_JNIMethod *m = (_Jv_JNIMethod *)
1687 _Jv_AllocRawObj (sizeof (_Jv_JNIMethod));
1688 m->defining_class = def;
1689 m->self = method;
1690 m->function = NULL;
1691 def_interp->interpreted_methods[i] = m;
1693 if ((method->accflags & Modifier::STATIC))
1695 // Precompute the ncode field for a static method.
1696 // This lets us call a static method of an
1697 // interpreted class from precompiled code without
1698 // first resolving the class (that will happen
1699 // during class initialization instead).
1700 method->ncode = m->ncode ();
1704 else if ((method->accflags & Modifier::ABSTRACT) != 0)
1706 if (def_interp->interpreted_methods[i] != 0)
1707 throw_class_format_error ("code provided for abstract method");
1708 method->ncode = (void *) &_Jv_ThrowAbstractMethodError;
1710 else
1712 if (def_interp->interpreted_methods[i] == 0)
1713 throw_class_format_error ("method with no code");
1718 void _Jv_ClassReader::throw_class_format_error (const char *msg)
1720 jstring str;
1721 if (def->name != NULL)
1723 jsize mlen = strlen (msg);
1724 unsigned char* data = (unsigned char*) def->name->chars();
1725 int ulen = def->name->len();
1726 unsigned char* limit = data + ulen;
1727 jsize nlen = _Jv_strLengthUtf8 ((char *) data, ulen);
1728 jsize len = nlen + mlen + 3;
1729 str = JvAllocString(len);
1730 jchar *chrs = JvGetStringChars(str);
1731 while (data < limit)
1732 *chrs++ = UTF8_GET(data, limit);
1733 *chrs++ = ' ';
1734 *chrs++ = '(';
1735 for (;;)
1737 char c = *msg++;
1738 if (c == 0)
1739 break;
1740 *chrs++ = c & 0xFFFF;
1742 *chrs++ = ')';
1744 else
1745 str = JvNewStringLatin1 (msg);
1746 ::throw_class_format_error (str);
1749 /** Here we define the exceptions that can be thrown */
1751 static void
1752 throw_no_class_def_found_error (jstring msg)
1754 throw (msg
1755 ? new java::lang::NoClassDefFoundError (msg)
1756 : new java::lang::NoClassDefFoundError);
1759 static void
1760 throw_no_class_def_found_error (const char *msg)
1762 throw_no_class_def_found_error (JvNewStringLatin1 (msg));
1765 static void
1766 throw_class_format_error (jstring msg)
1768 throw (msg
1769 ? new java::lang::ClassFormatError (msg)
1770 : new java::lang::ClassFormatError);
1773 static void
1774 throw_internal_error (const char *msg)
1776 throw new java::lang::InternalError (JvNewStringLatin1 (msg));
1779 static void
1780 throw_incompatible_class_change_error (jstring msg)
1782 throw new java::lang::IncompatibleClassChangeError (msg);
1785 static void
1786 throw_class_circularity_error (jstring msg)
1788 throw new java::lang::ClassCircularityError (msg);
1791 #endif /* INTERPRETER */
1795 /** This section takes care of verifying integrity of identifiers,
1796 signatures, field ddescriptors, and class names */
1798 #define UTF8_PEEK(PTR, LIMIT) \
1799 ({ unsigned char* xxkeep = (PTR); \
1800 int xxch = UTF8_GET(PTR,LIMIT); \
1801 PTR = xxkeep; xxch; })
1803 /* Verify one element of a type descriptor or signature. */
1804 static unsigned char*
1805 _Jv_VerifyOne (unsigned char* ptr, unsigned char* limit, bool void_ok)
1807 if (ptr >= limit)
1808 return 0;
1810 int ch = UTF8_GET (ptr, limit);
1812 switch (ch)
1814 case 'V':
1815 if (! void_ok)
1816 return 0;
1818 case 'S': case 'B': case 'I': case 'J':
1819 case 'Z': case 'C': case 'F': case 'D':
1820 break;
1822 case 'L':
1824 unsigned char *start = ptr, *end;
1827 if (ptr > limit)
1828 return 0;
1830 end = ptr;
1832 if ((ch = UTF8_GET (ptr, limit)) == -1)
1833 return 0;
1836 while (ch != ';');
1837 if (! _Jv_VerifyClassName (start, (unsigned short) (end-start)))
1838 return 0;
1840 break;
1842 case '[':
1843 return _Jv_VerifyOne (ptr, limit, false);
1844 break;
1846 default:
1847 return 0;
1850 return ptr;
1853 /* Verification and loading procedures. */
1854 bool
1855 _Jv_VerifyFieldSignature (_Jv_Utf8Const*sig)
1857 unsigned char* ptr = (unsigned char*) sig->chars();
1858 unsigned char* limit = ptr + sig->len();
1860 ptr = _Jv_VerifyOne (ptr, limit, false);
1862 return ptr == limit;
1865 bool
1866 _Jv_VerifyMethodSignature (_Jv_Utf8Const*sig)
1868 unsigned char* ptr = (unsigned char*) sig->chars();
1869 unsigned char* limit = ptr + sig->len();
1871 if (ptr == limit || UTF8_GET(ptr,limit) != '(')
1872 return false;
1874 while (ptr && UTF8_PEEK (ptr, limit) != ')')
1875 ptr = _Jv_VerifyOne (ptr, limit, false);
1877 if (! ptr || UTF8_GET (ptr, limit) != ')')
1878 return false;
1880 // get the return type
1881 ptr = _Jv_VerifyOne (ptr, limit, true);
1883 return ptr == limit;
1886 /* We try to avoid calling the Character methods all the time, in
1887 fact, they will only be called for non-standard things. */
1888 static __inline__ int
1889 is_identifier_start (int c)
1891 unsigned int ch = (unsigned)c;
1893 if ((ch - 0x41U) < 29U) /* A ... Z */
1894 return 1;
1895 if ((ch - 0x61U) < 29U) /* a ... z */
1896 return 1;
1897 if (ch == 0x5FU) /* _ */
1898 return 1;
1900 return java::lang::Character::isJavaIdentifierStart ((jchar) ch);
1903 static __inline__ int
1904 is_identifier_part (int c)
1906 unsigned int ch = (unsigned)c;
1908 if ((ch - 0x41U) < 29U) /* A ... Z */
1909 return 1;
1910 if ((ch - 0x61U) < 29U) /* a ... z */
1911 return 1;
1912 if ((ch - 0x30) < 10U) /* 0 .. 9 */
1913 return 1;
1914 if (ch == 0x5FU || ch == 0x24U) /* _ $ */
1915 return 1;
1917 return java::lang::Character::isJavaIdentifierStart ((jchar) ch);
1920 bool
1921 _Jv_VerifyIdentifier (_Jv_Utf8Const* name)
1923 unsigned char *ptr = (unsigned char*) name->chars();
1924 unsigned char *limit = (unsigned char*) name->limit();
1925 int ch;
1927 if ((ch = UTF8_GET (ptr, limit))==-1
1928 || ! is_identifier_start (ch))
1929 return false;
1931 while (ptr != limit)
1933 if ((ch = UTF8_GET (ptr, limit))==-1
1934 || ! is_identifier_part (ch))
1935 return false;
1937 return true;
1940 bool
1941 _Jv_VerifyClassName (unsigned char* ptr, _Jv_ushort length)
1943 unsigned char *limit = ptr+length;
1944 int ch;
1946 if ('[' == UTF8_PEEK (ptr, limit))
1948 unsigned char *end = _Jv_VerifyOne (++ptr, limit, false);
1949 // _Jv_VerifyOne must leave us looking at the terminating nul
1950 // byte.
1951 if (! end || *end)
1952 return false;
1953 else
1954 return true;
1957 next_level:
1958 for (;;) {
1959 if ((ch = UTF8_GET (ptr, limit))==-1)
1960 return false;
1961 if (! is_identifier_start (ch))
1962 return false;
1963 for (;;) {
1964 if (ptr == limit)
1965 return true;
1966 else if ((ch = UTF8_GET (ptr, limit))==-1)
1967 return false;
1968 else if (ch == '.')
1969 goto next_level;
1970 else if (! is_identifier_part (ch))
1971 return false;
1976 bool
1977 _Jv_VerifyClassName (_Jv_Utf8Const *name)
1979 return _Jv_VerifyClassName ((unsigned char*)name->chars(), name->len());
1982 /* Returns true, if NAME1 and NAME2 represent classes in the same
1983 package. Neither NAME2 nor NAME2 may name an array type. */
1984 bool
1985 _Jv_ClassNameSamePackage (_Jv_Utf8Const *name1, _Jv_Utf8Const *name2)
1987 unsigned char* ptr1 = (unsigned char*) name1->chars();
1988 unsigned char* limit1 = (unsigned char*) name1->limit();
1990 unsigned char* last1 = ptr1;
1992 // scan name1, and find the last occurrence of '.'
1993 while (ptr1 < limit1) {
1994 int ch1 = UTF8_GET (ptr1, limit1);
1996 if (ch1 == '.')
1997 last1 = ptr1;
1999 else if (ch1 == -1)
2000 return false;
2003 // Now the length of NAME1's package name is LEN.
2004 int len = last1 - (unsigned char*) name1->chars();
2006 // If this is longer than NAME2, then we're off.
2007 if (len > name2->len())
2008 return false;
2010 // Then compare the first len bytes for equality.
2011 if (memcmp ((void*) name1->chars(), (void*) name2->chars(), len) == 0)
2013 // Check that there are no .'s after position LEN in NAME2.
2015 unsigned char* ptr2 = (unsigned char*) name2->chars() + len;
2016 unsigned char* limit2 = (unsigned char*) name2->limit();
2018 while (ptr2 < limit2)
2020 int ch2 = UTF8_GET (ptr2, limit2);
2021 if (ch2 == -1 || ch2 == '.')
2022 return false;
2024 return true;
2026 return false;