defineclass.cc 55.6 KB
Newer Older
Anthony Green committed
1 2
// defineclass.cc - defining a class from .class format.

3
/* Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2012
4
   Free Software Foundation
Anthony Green committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

   This file is part of libgcj.

This software is copyrighted work licensed under the terms of the
Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
details.  */

/* 
   Author: Kresten Krab Thorup <krab@gnu.org> 

   Written using the online versions of Java Language Specification (1st
   ed.) and The Java Virtual Machine Specification (2nd ed.). 

   Future work may include reading (and handling) attributes which are
   currently being ignored ("InnerClasses", "LineNumber", etc...).  
*/

Tom Tromey committed
22 23
#include <config.h>

Anthony Green committed
24 25
#include <java-interp.h>

Tom Tromey committed
26
#include <stdlib.h>
27
#include <stdio.h>
Anthony Green committed
28
#include <java-cpool.h>
Tom Tromey committed
29
#include <gcj/cni.h>
30
#include <execution.h>
Anthony Green committed
31 32 33 34 35 36 37 38 39 40 41

#include <java/lang/Class.h>
#include <java/lang/Float.h>
#include <java/lang/Double.h>
#include <java/lang/Character.h>
#include <java/lang/LinkageError.h>
#include <java/lang/InternalError.h>
#include <java/lang/ClassFormatError.h>
#include <java/lang/NoClassDefFoundError.h>
#include <java/lang/ClassCircularityError.h>
#include <java/lang/IncompatibleClassChangeError.h>
42
#include <java/lang/reflect/Modifier.h>
43 44
#include <java/lang/reflect/Field.h>
#include <java/lang/reflect/Method.h>
45
#include <java/security/ProtectionDomain.h>
46 47
#include <java/io/DataOutputStream.h>
#include <java/io/ByteArrayOutputStream.h>
Anthony Green committed
48

49
using namespace gcj;
Anthony Green committed
50

51 52
#ifdef INTERPRETER

53
// these go in some separate functions, to avoid having _Jv_InitClass
Anthony Green committed
54
// inserted all over the place.
55
static void throw_internal_error (const char *msg)
Anthony Green committed
56 57 58
	__attribute__ ((__noreturn__));
static void throw_no_class_def_found_error (jstring msg)
	__attribute__ ((__noreturn__));
59
static void throw_no_class_def_found_error (const char *msg)
Anthony Green committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
	__attribute__ ((__noreturn__));
static void throw_class_format_error (jstring msg)
	__attribute__ ((__noreturn__));
static void throw_incompatible_class_change_error (jstring msg)
	__attribute__ ((__noreturn__));
static void throw_class_circularity_error (jstring msg)
	__attribute__ ((__noreturn__));

/**
 * We define class reading using a class.  It is practical, since then
 * the entire class-reader can be a friend of class Class (it needs to
 * write all it's different structures); but also because this makes it
 * easy to make class definition reentrant, and thus two threads can be
 * defining classes at the same time.   This class (_Jv_ClassReader) is
 * never exposed outside this file, so we don't have to worry about
 * public or private members here.
 */

78 79
struct _Jv_ClassReader
{
Anthony Green committed
80 81 82 83 84 85 86

  // do verification?  Currently, there is no option to disable this.
  // This flag just controls the verificaiton done by the class loader;
  // i.e., checking the integrity of the constant pool; and it is
  // allways on.  You always want this as far as I can see, but it also
  // controls weither identifiers and type descriptors/signatures are
  // verified as legal.  This could be somewhat more expensive since it
87
  // will call Character.isJavaIdentifier{Start,Part} for each character
Anthony Green committed
88 89 90 91 92 93 94
  // in any identifier (field name or method name) it comes by.  Thus,
  // it might be useful to turn off this verification for classes that
  // come from a trusted source.  However, for GCJ, trusted classes are
  // most likely to be linked in.

  bool verify;

95 96 97 98
  // original input data.
  jbyteArray input_data;
  jint input_offset;

Anthony Green committed
99 100 101 102 103 104 105 106 107 108 109 110 111
  // input data.
  unsigned char     *bytes;
  int                len;

  // current input position
  int                pos;

  // the constant pool data
  int pool_count;
  unsigned char     *tags;
  unsigned int      *offsets;

  // the class to define (see java-interp.h)
112
  jclass	   def;
113

114 115
  // the classes associated interpreter data.
  _Jv_InterpClass  *def_interp;
Anthony Green committed
116

117 118 119
  // The name we found.
  _Jv_Utf8Const **found_name;

120 121 122
  // True if this is a 1.5 class file.
  bool             is_15;

123 124 125 126
  // Buffer holding extra reflection data.
  ::java::io::ByteArrayOutputStream *reflection_data;
  ::java::io::DataOutputStream *data_stream;

127

Anthony Green committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141
  /* check that the given number of input bytes are available */
  inline void check (int num)
  {
    if (pos + num > len)
      throw_class_format_error ("Premature end of data");
  }

  /* skip a given number of bytes in input */
  inline void skip (int num)
  {
    check (num);
    pos += num;
  }
  
142
  /* read an unsigned 1-byte unit */
Anthony Green committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
  inline static jint get1u (unsigned char* bytes)
  {
    return bytes[0];
  }
  
  /* read an unsigned 1-byte unit */
  inline jint read1u ()
  {
    skip (1);
    return get1u (bytes+pos-1);
  }
  
  /* read an unsigned 2-byte unit */
  inline static jint get2u (unsigned char *bytes)
  {
    return (((jint)bytes[0]) << 8) | ((jint)bytes[1]);
  }
  
  /* read an unsigned 2-byte unit */
  inline jint read2u ()
  {
    skip (2);  
    return get2u (bytes+pos-2);
  }
  
  /* read a 4-byte unit */
  static jint get4 (unsigned char *bytes)
  {
    return (((jint)bytes[0]) << 24)
         | (((jint)bytes[1]) << 16)
         | (((jint)bytes[2]) << 8)
         | (((jint)bytes[3]) << 0);
  }

  /* read a 4-byte unit, (we don't do that quite so often) */
  inline jint read4 ()
  {
    skip (4);  
    return get4 (bytes+pos-4);
  }

  /* read a 8-byte unit */
  static jlong get8 (unsigned char* bytes)
  {
    return (((jlong)bytes[0]) << 56)
         | (((jlong)bytes[1]) << 48)
         | (((jlong)bytes[2]) << 40)
         | (((jlong)bytes[3]) << 32) 
         | (((jlong)bytes[4]) << 24)
         | (((jlong)bytes[5]) << 16)
         | (((jlong)bytes[6]) << 8)
         | (((jlong)bytes[7]) << 0);
  }

  /* read a 8-byte unit */
  inline jlong read8 ()
  {
    skip (8);  
    return get8 (bytes+pos-8);
  }

  inline void check_tag (int index, char expected_tag)
  {
    if (index < 0
	|| index > pool_count
	|| tags[index] != expected_tag)
      throw_class_format_error ("erroneous constant pool tag");
  }

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
  inline void verify_identifier (_Jv_Utf8Const* name)
  {
    if (! _Jv_VerifyIdentifier (name))
      throw_class_format_error ("erroneous identifier");
  }

  inline void verify_classname (unsigned char* ptr, _Jv_ushort length)
  {
    if (! _Jv_VerifyClassName (ptr, length))
      throw_class_format_error ("erroneous class name");
  }

  inline void verify_classname (_Jv_Utf8Const *name)
  {
    if (! _Jv_VerifyClassName (name))
      throw_class_format_error ("erroneous class name");
  }

  inline void verify_field_signature (_Jv_Utf8Const *sig)
  {
    if (! _Jv_VerifyFieldSignature (sig))
      throw_class_format_error ("erroneous type descriptor");
  }

  inline void verify_method_signature (_Jv_Utf8Const *sig)
  {
    if (! _Jv_VerifyMethodSignature (sig))
      throw_class_format_error ("erroneous type descriptor");
  }

242 243 244 245 246 247 248 249 250 251
  ::java::io::DataOutputStream *get_reflection_stream ()
  {
    if (reflection_data == NULL)
      {
	reflection_data = new ::java::io::ByteArrayOutputStream();
	data_stream = new ::java::io::DataOutputStream(reflection_data);
      }
    return data_stream;
  }

252
  _Jv_ClassReader (jclass klass, jbyteArray data, jint offset, jint length,
253 254
		   java::security::ProtectionDomain *pd,
		   _Jv_Utf8Const **name_result)
Anthony Green committed
255 256 257 258 259
  {
    if (klass == 0 || length < 0 || offset+length > data->length)
      throw_internal_error ("arguments to _Jv_DefineClass");

    verify = true;
260 261
    input_data = data;
    input_offset = offset;
Anthony Green committed
262 263 264
    bytes  = (unsigned char*) (elements (data)+offset);
    len    = length;
    pos    = 0;
265 266
    is_15  = false;

267
    def    = klass;
268
    found_name = name_result;
269 270
    reflection_data = NULL;
    data_stream = NULL;
271

272 273 274 275
    def->size_in_bytes = -1;
    def->vtable_method_count = -1;
    def->engine = &_Jv_soleInterpreterEngine;
    def->protectionDomain = pd;
Anthony Green committed
276 277 278 279 280
  }

  /** and here goes the parser members defined out-of-line */
  void parse ();
  void read_constpool ();
281 282
  void prepare_pool_entry (int index, unsigned char tag,
			   bool rewrite = true);
Anthony Green committed
283 284 285 286 287
  void read_fields ();
  void read_methods ();
  void read_one_class_attribute ();
  void read_one_method_attribute (int method);
  void read_one_code_attribute (int method);
288
  void read_one_field_attribute (int field, bool *);
289
  void throw_class_format_error (const char *msg);
Anthony Green committed
290

291 292 293 294 295 296 297 298 299 300
  void handleEnclosingMethod(int);
  void handleGenericSignature(jv_attr_type, unsigned short, int);
  void handleAnnotationElement();
  void handleAnnotation();
  void handleAnnotations();
  void handleMemberAnnotations(jv_attr_type, int, int);
  void handleAnnotationDefault(int, int);
  void handleParameterAnnotations(int, int);
  void finish_reflection_data ();

Anthony Green committed
301
  /** check an utf8 entry, without creating a Utf8Const object */
302
  bool is_attribute_name (int index, const char *name);
303 304 305
  
  /** return the value of a utf8 entry in the passed array */
  int pool_Utf8_to_char_arr (int index, char **entry);
Anthony Green committed
306 307 308 309 310 311 312

  /** here goes the class-loader members defined out-of-line */
  void handleConstantPool ();
  void handleClassBegin (int, int, int);
  void handleInterfacesBegin (int);
  void handleInterface (int, int);
  void handleFieldsBegin (int);
313 314
  void handleField (int, int, int, int, int *);
  void handleConstantValueAttribute (int, int, bool *);
Anthony Green committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
  void handleMethodsBegin (int);
  void handleMethod (int, int, int, int);
  void handleMethodsEnd ();
  void handleCodeAttribute (int, int, int, int, int, int);
  void handleExceptionTableEntry (int, int, int, int, int, int);

  void checkExtends (jclass sub, jclass super);
  void checkImplements (jclass sub, jclass super);

  /*
   * FIXME: we should keep a hash table of utf8-strings, since many will
   * be the same.  It's a little tricky, however, because the hash table
   * needs to interact gracefully with the garbage collector.  Much
   * memory is to be saved by this, however!  perhaps the improvement
   * could be implemented in prims.cc (_Jv_makeUtf8Const), since it
   * computes the hash value anyway.
   */
};

334 335 336
// Note that *NAME_RESULT will only be set if the class is registered
// with the class loader.  This is how the caller can know whether
// unregistration is require.
Anthony Green committed
337
void
338
_Jv_DefineClass (jclass klass, jbyteArray data, jint offset, jint length,
339 340
		 java::security::ProtectionDomain *pd,
		 _Jv_Utf8Const **name_result)
Anthony Green committed
341
{
342
  _Jv_ClassReader reader (klass, data, offset, length, pd, name_result);
Anthony Green committed
343 344 345 346 347 348 349 350
  reader.parse();

  /* that's it! */
}


/** This section defines the parsing/scanning of the class data */

351 352 353 354 355 356 357 358 359 360 361
// Major and minor version numbers for various releases.
#define MAJOR_1_1 45
#define MINOR_1_1  3
#define MAJOR_1_2 46
#define MINOR_1_2  0
#define MAJOR_1_3 47
#define MINOR_1_3  0
#define MAJOR_1_4 48
#define MINOR_1_4  0
#define MAJOR_1_5 49
#define MINOR_1_5  0
362 363
#define MAJOR_1_6 50
#define MINOR_1_6  0
364 365
#define MAJOR_1_7 51
#define MINOR_1_7  0
366

Anthony Green committed
367 368 369 370 371 372 373
void
_Jv_ClassReader::parse ()
{
  int magic = read4 ();
  if (magic != (int) 0xCAFEBABE)
    throw_class_format_error ("bad magic number");

374 375
  int minor_version = read2u ();
  int major_version = read2u ();
376 377
  if (major_version < MAJOR_1_1 || major_version > MAJOR_1_7
      || (major_version == MAJOR_1_7 && minor_version > MINOR_1_7))
378
    throw_class_format_error ("unrecognized class file version");
379
  is_15 = (major_version >= MAJOR_1_5);
380

Anthony Green committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394
  pool_count = read2u ();

  read_constpool ();

  int access_flags = read2u ();
  int this_class = read2u ();
  int super_class = read2u ();

  check_tag (this_class, JV_CONSTANT_Class);
  if (super_class != 0) 
    check_tag (super_class, JV_CONSTANT_Class);

  handleClassBegin (access_flags, this_class, super_class);

395 396
  // Allocate our aux_info here, after the name is set, to fulfill our
  // contract with the collector interface.
397
  def->aux_info = (void *) _Jv_AllocRawObj (sizeof (_Jv_InterpClass));
398 399
  def_interp = (_Jv_InterpClass *) def->aux_info;

Anthony Green committed
400
  int interfaces_count = read2u (); 
401

Anthony Green committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
  handleInterfacesBegin (interfaces_count);

  for (int i = 0; i < interfaces_count; i++)
    {
      int iface = read2u ();
      check_tag (iface, JV_CONSTANT_Class);
      handleInterface (i, iface);
    }
  
  read_fields ();
  read_methods ();
  
  int attributes_count = read2u ();
  
  for (int i = 0; i < attributes_count; i++)
    {
      read_one_class_attribute ();
    }

  if (pos != len)
    throw_class_format_error ("unused data before end of file");

424 425
  finish_reflection_data ();

426 427
  // Tell everyone we're done.
  def->state = JV_STATE_READ;
428
  if (gcj::verbose_class_flag)
429
    _Jv_Linker::print_class_loaded (def);
430
  ++gcj::loadedClasses;
Anthony Green committed
431 432 433
  def->notifyAll ();
}

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
void
_Jv_ClassReader::finish_reflection_data ()
{
  if (data_stream == NULL)
    return;
  data_stream->writeByte(JV_DONE_ATTR);
  data_stream->flush();
  int nbytes = reflection_data->count;
  unsigned char *new_bytes = (unsigned char *) _Jv_AllocBytes (nbytes);
  memcpy (new_bytes, elements (reflection_data->buf), nbytes);
  def->reflection_data = new_bytes;
}

void
_Jv_ClassReader::handleEnclosingMethod (int len)
{
  if (len != 4)
    throw_class_format_error ("invalid EnclosingMethod attribute");
  // FIXME: only allow one...

  int class_index = read2u();
  check_tag (class_index, JV_CONSTANT_Class);
  prepare_pool_entry (class_index, JV_CONSTANT_Class);

  int method_index = read2u();
  // Zero is ok and means no enclosing method.
  if (method_index != 0)
    {
      check_tag (method_index, JV_CONSTANT_NameAndType);
      prepare_pool_entry (method_index, JV_CONSTANT_NameAndType);
    }

  ::java::io::DataOutputStream *stream = get_reflection_stream ();
  stream->writeByte(JV_CLASS_ATTR);
  stream->writeInt(5);
  stream->writeByte(JV_ENCLOSING_METHOD_KIND);
  stream->writeShort(class_index);
  stream->writeShort(method_index);
}

void
_Jv_ClassReader::handleGenericSignature (jv_attr_type type,
					 unsigned short index,
					 int len)
{
  if (len != 2)
    throw_class_format_error ("invalid Signature attribute");

  int cpool_idx = read2u();
  check_tag (cpool_idx, JV_CONSTANT_Utf8);
  prepare_pool_entry (cpool_idx, JV_CONSTANT_Utf8, false);

  ::java::io::DataOutputStream *stream = get_reflection_stream ();
  stream->writeByte(type);
  int attrlen = 3;
  if (type != JV_CLASS_ATTR)
    attrlen += 2;
  stream->writeInt(attrlen);
  if (type != JV_CLASS_ATTR)
    stream->writeShort(index);
  stream->writeByte(JV_SIGNATURE_KIND);
  stream->writeShort(cpool_idx);
}

void
_Jv_ClassReader::handleAnnotationElement()
{
  int tag = read1u();
  switch (tag)
    {
    case 'B':
    case 'C':
    case 'S':
    case 'Z':
    case 'I':
      {
	int index = read2u();
	check_tag (index, JV_CONSTANT_Integer);
	prepare_pool_entry (index, JV_CONSTANT_Integer);
      }
      break;
    case 'D':
      {
	int index = read2u();
	check_tag (index, JV_CONSTANT_Double);
	prepare_pool_entry (index, JV_CONSTANT_Double);
      }
      break;
    case 'F':
      {
	int index = read2u();
	check_tag (index, JV_CONSTANT_Float);
	prepare_pool_entry (index, JV_CONSTANT_Float);
      }
      break;
    case 'J':
      {
	int index = read2u();
	check_tag (index, JV_CONSTANT_Long);
	prepare_pool_entry (index, JV_CONSTANT_Long);
      }
      break;
    case 's':
      {
	int index = read2u();
	// Despite what the JVM spec says, compilers generate a Utf8
	// constant here, not a String.
	check_tag (index, JV_CONSTANT_Utf8);
	prepare_pool_entry (index, JV_CONSTANT_Utf8, false);
      }
      break;

    case 'e':
      {
	int type_name_index = read2u();
	int const_name_index = read2u ();
	check_tag (type_name_index, JV_CONSTANT_Utf8);
	prepare_pool_entry (type_name_index, JV_CONSTANT_Utf8);
	check_tag (const_name_index, JV_CONSTANT_Utf8);
	prepare_pool_entry (const_name_index, JV_CONSTANT_Utf8, false);
      }
      break;
    case 'c':
      {
	int index = read2u();
	check_tag (index, JV_CONSTANT_Utf8);
	prepare_pool_entry (index, JV_CONSTANT_Utf8);
      }
      break;
    case '@':
      handleAnnotation();
      break;
    case '[':
      {
	int n_array_elts = read2u ();
	for (int i = 0; i < n_array_elts; ++i)
	  handleAnnotationElement();
      }
      break;
    default:
      throw_class_format_error ("invalid annotation element");
    }
}

void
_Jv_ClassReader::handleAnnotation()
{
  int type_index = read2u();
  check_tag (type_index, JV_CONSTANT_Utf8);
  prepare_pool_entry (type_index, JV_CONSTANT_Utf8);

  int npairs = read2u();
  for (int i = 0; i < npairs; ++i)
    {
      int name_index = read2u();
      check_tag (name_index, JV_CONSTANT_Utf8);
      prepare_pool_entry (name_index, JV_CONSTANT_Utf8, false);
      handleAnnotationElement();
    }
}

void
_Jv_ClassReader::handleAnnotations()
{
  int num = read2u();
  while (num--)
    handleAnnotation();
}

void
_Jv_ClassReader::handleMemberAnnotations(jv_attr_type member_type,
					 int member_index,
					 int len)
{
  // We're going to copy the bytes in verbatim.  But first we want to
  // make sure the attribute is well-formed, and we want to prepare
  // the constant pool.  So, we save our starting point.
  int orig_pos = pos;

  handleAnnotations();
  // FIXME: check that we read all LEN bytes?

  ::java::io::DataOutputStream *stream = get_reflection_stream ();
  stream->writeByte(member_type);
  int newLen = len + 1;
  if (member_type != JV_CLASS_ATTR)
    newLen += 2;
  stream->writeInt(newLen);
  stream->writeByte(JV_ANNOTATIONS_KIND);
  if (member_type != JV_CLASS_ATTR)
    stream->writeShort(member_index);
  // Write the data as-is.
  stream->write(input_data, input_offset + orig_pos, len);
}

void
_Jv_ClassReader::handleAnnotationDefault(int member_index, int len)
{
  int orig_pos = pos;
  handleAnnotationElement();

  ::java::io::DataOutputStream *stream = get_reflection_stream ();
  stream->writeByte(JV_METHOD_ATTR);
  stream->writeInt(len + 3);
  stream->writeByte(JV_ANNOTATION_DEFAULT_KIND);
  stream->writeShort(member_index);
  stream->write(input_data, input_offset + orig_pos, len);
}

void
_Jv_ClassReader::handleParameterAnnotations(int member_index, int len)
{
  int orig_pos = pos;

  int n_params = read1u();
  for (int i = 0; i < n_params; ++i)
    handleAnnotations();

  ::java::io::DataOutputStream *stream = get_reflection_stream ();
  stream->writeByte(JV_METHOD_ATTR);
  stream->writeInt(len + 3);
  stream->writeByte(JV_PARAMETER_ANNOTATIONS_KIND);
  stream->writeShort(member_index);
  stream->write(input_data, input_offset + orig_pos, len);
}

Anthony Green committed
660 661
void _Jv_ClassReader::read_constpool ()
{
Tom Tromey committed
662
  tags    = (unsigned char*) _Jv_AllocBytes (pool_count);
663
  offsets = (unsigned int *) _Jv_AllocBytes (sizeof (int) * pool_count) ;
Anthony Green committed
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719

  /** first, we scan the constant pool, collecting tags and offsets */
  tags[0]   = JV_CONSTANT_Undefined;
  offsets[0] = pos;
  for (int c = 1; c < pool_count; c++)
    {
      tags[c]    = read1u ();
      offsets[c] = pos;

      switch (tags[c])
	{
	case JV_CONSTANT_String:
	case JV_CONSTANT_Class:
	  skip (2);
	  break;

	case JV_CONSTANT_Fieldref:
	case JV_CONSTANT_Methodref:
	case JV_CONSTANT_InterfaceMethodref:
	case JV_CONSTANT_NameAndType:
	case JV_CONSTANT_Integer:
	case JV_CONSTANT_Float:
	  skip (4);
	  break;

	case JV_CONSTANT_Double:
	case JV_CONSTANT_Long:
	  skip (8);
	  tags[++c] = JV_CONSTANT_Undefined;
	  break;
	    
	case JV_CONSTANT_Utf8:
	  {		    
	    int len = read2u ();
	    skip (len);
	  }
	  break;

	case JV_CONSTANT_Unicode:
	  throw_class_format_error ("unicode not supported");
	  break;

	default:
	  throw_class_format_error ("erroneous constant pool tag");
	}
    }

  handleConstantPool ();
}


void _Jv_ClassReader::read_fields ()
{
  int fields_count = read2u ();
  handleFieldsBegin (fields_count);

720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
  // We want to sort the fields so that static fields come first,
  // followed by instance fields.  We do this before parsing the
  // fields so that we can have the new indices available when
  // creating the annotation data structures.

  // Allocate this on the heap in case there are a large number of
  // fields.
  int *fieldmap = (int *) _Jv_AllocBytes (fields_count * sizeof (int));
  int save_pos = pos;
  int static_count = 0, instance_count = -1;
  for (int i = 0; i < fields_count; ++i)
    {
      using namespace java::lang::reflect;

      int access_flags = read2u ();
      skip (4);
      int attributes_count = read2u ();

      if ((access_flags & Modifier::STATIC) != 0) 
	fieldmap[i] = static_count++;
      else
	fieldmap[i] = instance_count--;

      for (int j = 0; j < attributes_count; ++j)
	{
	  skip (2);
	  int length = read4 ();
	  skip (length);
	}
    }
  pos = save_pos;

  // In the loop above, instance fields are represented by negative
  // numbers.  Here we rewrite these to be proper offsets.
  for (int i = 0; i < fields_count; ++i)
    {
      if (fieldmap[i] < 0)
	fieldmap[i] = static_count - 1 - fieldmap[i];
    }
  def->static_field_count = static_count;

Anthony Green committed
761 762 763 764 765 766
  for (int i = 0; i < fields_count; i++)
    {
      int access_flags     = read2u ();
      int name_index       = read2u ();
      int descriptor_index = read2u ();
      int attributes_count = read2u ();
767

Anthony Green committed
768 769 770 771 772
      check_tag (name_index, JV_CONSTANT_Utf8);
      prepare_pool_entry (name_index, JV_CONSTANT_Utf8);

      check_tag (descriptor_index, JV_CONSTANT_Utf8);
      prepare_pool_entry (descriptor_index, JV_CONSTANT_Utf8);
773

774
      handleField (i, access_flags, name_index, descriptor_index, fieldmap);
775

776
      bool found_value = false;
Anthony Green committed
777 778
      for (int j = 0; j < attributes_count; j++)
	{
779
	  read_one_field_attribute (fieldmap[i], &found_value);
Anthony Green committed
780 781 782 783 784
	}
    }
}

bool
785
_Jv_ClassReader::is_attribute_name (int index, const char *name)
Anthony Green committed
786 787 788 789 790 791 792 793 794
{
  check_tag (index, JV_CONSTANT_Utf8);
  int len = get2u (bytes+offsets[index]);
  if (len != (int) strlen (name))
    return false;
  else
    return !memcmp (bytes+offsets[index]+2, name, len);
}

795 796 797 798 799 800 801 802 803 804 805 806
// Get a UTF8 value from the constant pool and turn it into a garbage
// collected char array.
int _Jv_ClassReader::pool_Utf8_to_char_arr (int index, char** entry)
{
  check_tag (index, JV_CONSTANT_Utf8);
  int len = get2u (bytes + offsets[index]);
  *entry = reinterpret_cast<char *> (_Jv_AllocBytes (len + 1));
  (*entry)[len] = '\0';
  memcpy (*entry, bytes + offsets[index] + 2, len);
  return len + 1;
}

807 808
void _Jv_ClassReader::read_one_field_attribute (int field_index,
						bool *found_value)
Anthony Green committed
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
{
  int name = read2u ();
  int length = read4 ();

  if (is_attribute_name (name, "ConstantValue"))
    {
      int cv = read2u ();

      if (cv < pool_count 
	  && cv > 0
	  && (tags[cv] == JV_CONSTANT_Integer
	      || tags[cv] == JV_CONSTANT_Float
	      || tags[cv] == JV_CONSTANT_Long
	      || tags[cv] == JV_CONSTANT_Double
	      || tags[cv] == JV_CONSTANT_String))
824 825 826 827 828
	{
	  handleConstantValueAttribute (field_index, cv, found_value);
	}
      else
	{
Anthony Green committed
829
	  throw_class_format_error ("erroneous ConstantValue attribute");
830
	}
Anthony Green committed
831

832 833 834 835 836 837 838 839 840
      if (length != 2) 
	throw_class_format_error ("erroneous ConstantValue attribute");
    }
  else if (is_attribute_name (name, "Signature"))
    handleGenericSignature(JV_FIELD_ATTR, field_index, length);
  else if (is_attribute_name (name, "RuntimeVisibleAnnotations"))
    handleMemberAnnotations(JV_FIELD_ATTR, field_index, length);
  else
    skip (length);
Anthony Green committed
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
}

void _Jv_ClassReader::read_methods ()
{
  int methods_count = read2u ();
  
  handleMethodsBegin (methods_count);
  
  for (int i = 0; i < methods_count; i++)
    {
      int access_flags     = read2u ();
      int name_index       = read2u ();
      int descriptor_index = read2u ();
      int attributes_count = read2u ();
      
      check_tag (name_index, JV_CONSTANT_Utf8);
857
      prepare_pool_entry (name_index, JV_CONSTANT_Utf8);
Anthony Green committed
858

859
      check_tag (descriptor_index, JV_CONSTANT_Utf8);
Anthony Green committed
860
      prepare_pool_entry (descriptor_index, JV_CONSTANT_Utf8);
861

Anthony Green committed
862 863
      handleMethod (i, access_flags, name_index,
		    descriptor_index);
864

Anthony Green committed
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
      for (int j = 0; j < attributes_count; j++)
	{
	  read_one_method_attribute (i);
	}
    }
  
  handleMethodsEnd ();
}

void _Jv_ClassReader::read_one_method_attribute (int method_index) 
{
  int name = read2u ();
  int length = read4 ();

  if (is_attribute_name (name, "Exceptions"))
    {
881 882 883 884 885 886 887
      _Jv_Method *method = reinterpret_cast<_Jv_Method *>
	(&def->methods[method_index]);
      if (method->throws != NULL)
	throw_class_format_error ("only one Exceptions attribute allowed per method");

      int num_exceptions = read2u ();
      _Jv_Utf8Const **exceptions =
888 889
	(_Jv_Utf8Const **) _Jv_AllocBytes ((num_exceptions + 1)
					   * sizeof (_Jv_Utf8Const *));
890 891 892 893 894

      int out = 0;
      _Jv_word *pool_data = def->constants.data;
      for (int i = 0; i < num_exceptions; ++i)
	{
895 896 897
	  int ndx = read2u ();
	  // JLS 2nd Ed. 4.7.5 requires that the tag not be 0.
	  if (ndx != 0)
898
	    {
899 900
	      check_tag (ndx, JV_CONSTANT_Class);
	      exceptions[out++] = pool_data[ndx].utf8; 
901 902 903 904
	    }
	}
      exceptions[out] = NULL;
      method->throws = exceptions;
Anthony Green committed
905
    }
906

Anthony Green committed
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
  else if (is_attribute_name (name, "Code"))
    {
      int start_off = pos;
      int max_stack = read2u ();
      int max_locals = read2u ();
      int code_length = read4 ();

      int code_start = pos;
      skip (code_length);
      int exception_table_length = read2u ();

      handleCodeAttribute (method_index, 
			   max_stack, max_locals,
			   code_start, code_length,
			   exception_table_length);
      

      for (int i = 0; i < exception_table_length; i++)
	{
	  int start_pc   = read2u ();
	  int end_pc     = read2u ();
	  int handler_pc = read2u ();
	  int catch_type = read2u ();

	  if (start_pc > end_pc
	      || start_pc < 0
933 934 935
	      // END_PC can be equal to CODE_LENGTH.
	      // See JVM Spec 4.7.4.
	      || end_pc > code_length
Anthony Green committed
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
	      || handler_pc >= code_length)
	    throw_class_format_error ("erroneous exception handler info");

	  if (! (tags[catch_type] == JV_CONSTANT_Class
		 || tags[catch_type] == 0))
	    {
	      throw_class_format_error ("erroneous exception handler info");
	    }

	  handleExceptionTableEntry (method_index,
				     i,
				     start_pc,
				     end_pc,
				     handler_pc, 
				     catch_type);

	}

      int attributes_count = read2u ();

      for (int i = 0; i < attributes_count; i++)
	{
	  read_one_code_attribute (method_index);
	}

      if ((pos - start_off) != length)
	throw_class_format_error ("code attribute too short");
    }
964 965 966 967 968 969 970 971
  else if (is_attribute_name (name, "Signature"))
    handleGenericSignature(JV_METHOD_ATTR, method_index, length);
  else if (is_attribute_name (name, "RuntimeVisibleAnnotations"))
    handleMemberAnnotations(JV_METHOD_ATTR, method_index, length);
  else if (is_attribute_name (name, "RuntimeVisibleParameterAnnotations"))
    handleParameterAnnotations(method_index, length);
  else if (is_attribute_name (name, "AnnotationDefault"))
    handleAnnotationDefault(method_index, length);
Anthony Green committed
972 973 974 975 976 977 978
  else
    {
      /* ignore unknown attributes */
      skip (length);
    }
}

979
void _Jv_ClassReader::read_one_code_attribute (int method_index) 
Anthony Green committed
980
{
981
  int name = read2u ();
Anthony Green committed
982
  int length = read4 ();
983 984 985 986 987 988 989 990 991
  if (is_attribute_name (name, "LineNumberTable"))
    {
      _Jv_InterpMethod *method = reinterpret_cast<_Jv_InterpMethod *>
	(def_interp->interpreted_methods[method_index]);
      if (method->line_table != NULL)
	throw_class_format_error ("Method already has LineNumberTable");

      int table_len = read2u ();
      _Jv_LineTableEntry* table
992 993
	= (_Jv_LineTableEntry *) _Jv_AllocBytes (table_len
						 * sizeof (_Jv_LineTableEntry));
994 995 996 997 998 999 1000 1001
      for (int i = 0; i < table_len; i++)
       {
	 table[i].bytecode_pc = read2u ();
	 table[i].line = read2u ();
       }
      method->line_table_len = table_len;
      method->line_table = table;
    }
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
  else if (is_attribute_name (name, "LocalVariableTable"))
    {
      _Jv_InterpMethod *method = reinterpret_cast<_Jv_InterpMethod *>
	                       (def_interp->interpreted_methods[method_index]);
      if (method->local_var_table != NULL)
        throw_class_format_error ("Method already has LocalVariableTable");
	
      int table_len = read2u ();
      _Jv_LocalVarTableEntry *table 
        = reinterpret_cast<_Jv_LocalVarTableEntry *>
            (_Jv_AllocRawObj (table_len * sizeof (_Jv_LocalVarTableEntry)));
                               
      for (int i = 0; i < table_len; i++)
        {
1016
          table[i].bytecode_pc = read2u ();
1017
          table[i].length = read2u ();
1018 1019
          pool_Utf8_to_char_arr (read2u (), &table[i].name);
          pool_Utf8_to_char_arr (read2u (), &table[i].descriptor);
1020 1021 1022 1023 1024 1025 1026 1027 1028
          table[i].slot = read2u ();
          
          if (table[i].slot > method->max_locals || table[i].slot < 0)
            throw_class_format_error ("Malformed Local Variable Table: Invalid Slot");
        }
	    
      method->local_var_table_len = table_len;
      method->local_var_table = table;
    }
1029 1030 1031 1032 1033
  else
    {
      /* ignore unknown code attributes */
      skip (length);
    }
Anthony Green committed
1034 1035 1036 1037
}

void _Jv_ClassReader::read_one_class_attribute () 
{
1038
  int name = read2u ();
Anthony Green committed
1039
  int length = read4 ();
1040 1041 1042 1043
  if (is_attribute_name (name, "SourceFile"))
    {
      int source_index = read2u ();
      check_tag (source_index, JV_CONSTANT_Utf8);
1044
      prepare_pool_entry (source_index, JV_CONSTANT_Utf8, false);
1045 1046 1047
      def_interp->source_file_name = _Jv_NewStringUtf8Const
	(def->constants.data[source_index].utf8);
    }
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
  else if (is_attribute_name (name, "Signature"))
    handleGenericSignature(JV_CLASS_ATTR, 0, length);
  else if (is_attribute_name (name, "EnclosingMethod"))
    handleEnclosingMethod(length);
  else if (is_attribute_name (name, "RuntimeVisibleAnnotations"))
    handleMemberAnnotations(JV_CLASS_ATTR, 0, length);
  else if (is_attribute_name (name, "InnerClasses"))
    {
      ::java::io::DataOutputStream *stream = get_reflection_stream ();
      stream->writeByte(JV_CLASS_ATTR);
      stream->writeInt(length + 1);
      stream->writeByte(JV_INNER_CLASSES_KIND);
      stream->write(input_data, input_offset + pos, length);
      skip (length);
    }
1063 1064
  else
    {
1065
      /* Currently, we ignore most class attributes. */
1066 1067
     skip (length);
    }
Anthony Green committed
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
}




/* this section defines the semantic actions of the parser */

void _Jv_ClassReader::handleConstantPool ()
{
  /** now, we actually define the class' constant pool */

Tom Tromey committed
1079
  jbyte *pool_tags = (jbyte*) _Jv_AllocBytes (pool_count);
Anthony Green committed
1080
  _Jv_word *pool_data
1081 1082
    = (_Jv_word*) _Jv_AllocRawObj (pool_count * sizeof (_Jv_word));

Anthony Green committed
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
  def->constants.tags = pool_tags;
  def->constants.data = pool_data;
  def->constants.size = pool_count;

  // Here we make a pass to collect the strings!   We do this, because
  // internally in the GCJ runtime, classes are encoded with .'s not /'s. 
  // Therefore, we first collect the strings, and then translate the rest
  // of the utf8-entries (thus not representing strings) from /-notation
  // to .-notation.
  for (int i = 1; i < pool_count; i++)
    {
      if (tags[i] == JV_CONSTANT_String)
	{
	  unsigned char* str_data = bytes + offsets [i];
	  int utf_index = get2u (str_data);
	  check_tag (utf_index, JV_CONSTANT_Utf8);
	  unsigned char *utf_data = bytes + offsets[utf_index];
	  int len = get2u (utf_data);
Anthony Green committed
1101
	  pool_data[i].utf8 = _Jv_makeUtf8Const ((char*)(utf_data+2), len);
Anthony Green committed
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
	  pool_tags[i] = JV_CONSTANT_String;
	}
      else
	{
	  pool_tags[i] = JV_CONSTANT_Undefined;
	}
    }

  // and now, we scan everything else but strings & utf8-entries.  This
  // leaves out those utf8-entries which are not used; which will be left
  // with a tag of JV_CONSTANT_Undefined in the class definition.
  for (int index = 1; index < pool_count; index++)
    {
      switch (tags[index])
	{
	case JV_CONSTANT_Undefined:
	case JV_CONSTANT_String:
	case JV_CONSTANT_Utf8:
	  continue;
	  
	default:
	  prepare_pool_entry (index, tags[index]);
	}
    }  
  
}

/* this is a recursive procedure, which will prepare pool entries as needed.
1130 1131 1132 1133 1134 1135
   Which is how we avoid initializing those entries which go unused. 
   
   REWRITE is true iff this pool entry is the Utf8 representation of a
   class name or a signature.
*/

Anthony Green committed
1136
void
1137 1138
_Jv_ClassReader::prepare_pool_entry (int index, unsigned char this_tag,
				     bool rewrite)
Anthony Green committed
1139 1140 1141 1142 1143
{
  /* these two, pool_data and pool_tags, point into the class
     structure we are currently defining */

  unsigned char *pool_tags = (unsigned char*) def->constants.tags;
Anthony Green committed
1144
  _Jv_word      *pool_data = def->constants.data;
Anthony Green committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

  /* this entry was already prepared */
  if (pool_tags[index] == this_tag)
    return;

  /* this_data points to the constant-pool information for the current
     constant-pool entry */

  unsigned char *this_data = bytes + offsets[index];

  switch (this_tag)
    {
    case JV_CONSTANT_Utf8: 
      {
	int len = get2u (this_data);
	char *s = ((char*) this_data)+2;
1161 1162 1163 1164 1165 1166 1167
	pool_tags[index] = JV_CONSTANT_Utf8;

	if (! rewrite)
	  {
	    pool_data[index].utf8 = _Jv_makeUtf8Const (s, len);
	    break;
	  }
Anthony Green committed
1168

1169 1170 1171 1172 1173
	// If REWRITE is set, it is because some other tag needs this
	// utf8-entry for type information: it is a class or a
	// signature.  Thus, we translate /'s to .'s in order to
	// accomondate gcj's internal representation.
	char *buffer = (char*) __builtin_alloca (len);
Anthony Green committed
1174 1175 1176 1177 1178
	for (int i = 0; i < len; i++)
	  {
	    if (s[i] == '/')
	      buffer[i] = '.';
	    else
1179
	      buffer[i] = s[i];
Anthony Green committed
1180
	  }
Anthony Green committed
1181
	pool_data[index].utf8 = _Jv_makeUtf8Const (buffer, len);
Anthony Green committed
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
      }
      break;
	    
    case JV_CONSTANT_Class:      
      {
	int utf_index = get2u (this_data);
	check_tag (utf_index, JV_CONSTANT_Utf8);
	prepare_pool_entry (utf_index, JV_CONSTANT_Utf8);

	if (verify)
1192
	  verify_classname (pool_data[utf_index].utf8);
Anthony Green committed
1193
		
Anthony Green committed
1194
	pool_data[index].utf8 = pool_data[utf_index].utf8;
Anthony Green committed
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
	pool_tags[index] = JV_CONSTANT_Class;
      }
      break;
	    
    case JV_CONSTANT_String:
      // already handled before... 
      break;
	    
    case JV_CONSTANT_Fieldref:
    case JV_CONSTANT_Methodref:
    case JV_CONSTANT_InterfaceMethodref:
      {
	int class_index = get2u (this_data);
	int nat_index = get2u (this_data+2);

	check_tag (class_index, JV_CONSTANT_Class);
	prepare_pool_entry (class_index, JV_CONSTANT_Class);	    

	check_tag (nat_index, JV_CONSTANT_NameAndType);
	prepare_pool_entry (nat_index, JV_CONSTANT_NameAndType);

	// here, verify the signature and identifier name
	if (verify)
	{
	  _Jv_ushort name_index, type_index;
Anthony Green committed
1220
	  _Jv_loadIndexes (&pool_data[nat_index],
Anthony Green committed
1221 1222 1223
			   name_index, type_index);

	  if (this_tag == JV_CONSTANT_Fieldref)
1224
	    verify_field_signature (pool_data[type_index].utf8);
Anthony Green committed
1225
	  else
1226
	    verify_method_signature (pool_data[type_index].utf8);
Anthony Green committed
1227

Anthony Green committed
1228
	  _Jv_Utf8Const* name = pool_data[name_index].utf8;
Anthony Green committed
1229 1230 1231 1232 1233 1234

	  if (this_tag != JV_CONSTANT_Fieldref
	      && (   _Jv_equalUtf8Consts (name, clinit_name)
		  || _Jv_equalUtf8Consts (name, init_name)))
	    /* ignore */;
	  else
1235
	    verify_identifier (pool_data[name_index].utf8);
Anthony Green committed
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
	}
	    
	_Jv_storeIndexes (&pool_data[index], class_index, nat_index);
	pool_tags[index] = this_tag;
      }
      break;
	    
    case JV_CONSTANT_NameAndType:
      {
	_Jv_ushort name_index = get2u (this_data);
	_Jv_ushort type_index = get2u (this_data+2);

	check_tag (name_index, JV_CONSTANT_Utf8);
1249
	prepare_pool_entry (name_index, JV_CONSTANT_Utf8, false);
Anthony Green committed
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
	check_tag (type_index, JV_CONSTANT_Utf8);
	prepare_pool_entry (type_index, JV_CONSTANT_Utf8);

	_Jv_storeIndexes (&pool_data[index], name_index, type_index);
	pool_tags[index] = JV_CONSTANT_NameAndType;
      }
      break;
	    
    case JV_CONSTANT_Float:
      {
1260
	jfloat f = java::lang::Float::intBitsToFloat ((jint) get4 (this_data));
Anthony Green committed
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
	_Jv_storeFloat (&pool_data[index], f);
	pool_tags[index] = JV_CONSTANT_Float;
      }
      break;
	    
    case JV_CONSTANT_Integer:
      {
	int i = get4 (this_data);
	_Jv_storeInt (&pool_data[index], i);
	pool_tags[index] = JV_CONSTANT_Integer;
      }
      break;
	    
    case JV_CONSTANT_Double:
      {
1276 1277
	jdouble d
	  = java::lang::Double::longBitsToDouble ((jlong) get8 (this_data));
Anthony Green committed
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
	_Jv_storeDouble (&pool_data[index], d);
	pool_tags[index] = JV_CONSTANT_Double;
      }
      break;
	    
    case JV_CONSTANT_Long:
      {
	jlong i = get8 (this_data);
	_Jv_storeLong (&pool_data[index], i);
	pool_tags[index] = JV_CONSTANT_Long;
      }
      break;
	    
    default:
      throw_class_format_error ("erroneous constant pool tag");
    }
}


void
1298
_Jv_ClassReader::handleClassBegin (int access_flags, int this_class, int super_class)
Anthony Green committed
1299
{
1300 1301
  using namespace java::lang::reflect;

Anthony Green committed
1302
  unsigned char *pool_tags = (unsigned char*) def->constants.tags;
Anthony Green committed
1303
  _Jv_word      *pool_data = def->constants.data;
Anthony Green committed
1304 1305

  check_tag (this_class, JV_CONSTANT_Class);
Anthony Green committed
1306
  _Jv_Utf8Const *loadedName = pool_data[this_class].utf8;
Anthony Green committed
1307 1308 1309 1310

  // was ClassLoader.defineClass called with an expected class name?
  if (def->name == 0)
    {
1311
      jclass orig = def->loader->findLoadedClass(loadedName->toString());
Anthony Green committed
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333

      if (orig == 0)
	{
	  def->name = loadedName;
	}
      else
	{
	  jstring msg = JvNewStringUTF ("anonymous "
					"class data denotes "
					"existing class ");
	  msg = msg->concat (orig->getName ());

	  throw_no_class_def_found_error (msg);
	}
    }

  // assert that the loaded class has the expected name, 5.3.5
  else if (! _Jv_equalUtf8Consts (loadedName, def->name))
    {
      jstring msg = JvNewStringUTF ("loaded class ");
      msg = msg->concat (def->getName ());
      msg = msg->concat (_Jv_NewStringUTF (" was in fact named "));
1334
      jstring klass_name = loadedName->toString();
Anthony Green committed
1335 1336 1337 1338 1339
      msg = msg->concat (klass_name);

      throw_no_class_def_found_error (msg);
    }

1340
  def->accflags = access_flags | java::lang::reflect::Modifier::INTERPRETED;
Anthony Green committed
1341
  pool_data[this_class].clazz = def;
Anthony Green committed
1342 1343
  pool_tags[this_class] = JV_CONSTANT_ResolvedClass;

1344
  if (super_class == 0)
Anthony Green committed
1345
    {
1346 1347 1348
      // Note that this is ok if we are defining java.lang.Object.
      // But there is no way to have this class be interpreted.
      throw_class_format_error ("no superclass reference");
Anthony Green committed
1349 1350 1351
    }

  def->state = JV_STATE_PRELOADING;
1352

1353 1354 1355 1356 1357 1358
  // Register this class with its defining loader as well (despite the
  // name of the function we're calling), so that super class lookups
  // work properly.  If there is an error, our caller will unregister
  // this class from the class loader.  Also, we don't need to hold a
  // lock here, as our caller has acquired it.
  _Jv_RegisterInitiatingLoader (def, def->loader);
Anthony Green committed
1359

1360 1361 1362 1363
  // Note that we found a name so that unregistration can happen if
  // needed.
  *found_name = def->name;

Anthony Green committed
1364 1365
  if (super_class != 0)
    {
Tom Tromey committed
1366
      // Load the superclass.
Anthony Green committed
1367
      check_tag (super_class, JV_CONSTANT_Class);
Anthony Green committed
1368
      _Jv_Utf8Const* super_name = pool_data[super_class].utf8; 
Anthony Green committed
1369

Tom Tromey committed
1370
      // Load the superclass using our defining loader.
1371
      jclass the_super = _Jv_FindClass (super_name, def->loader);
Anthony Green committed
1372 1373

      // This will establish that we are allowed to be a subclass,
Tom Tromey committed
1374
      // and check for class circularity error.
Anthony Green committed
1375 1376
      checkExtends (def, the_super);

Tom Tromey committed
1377 1378 1379 1380 1381 1382
      // Note: for an interface we will find Object as the
      // superclass.  We still check it above to ensure class file
      // validity, but we simply assign `null' to the actual field in
      // this case.
      def->superclass = (((access_flags & Modifier::INTERFACE))
			 ? NULL : the_super);
Anthony Green committed
1383
      pool_data[super_class].clazz = the_super;
Anthony Green committed
1384 1385
      pool_tags[super_class] = JV_CONSTANT_ResolvedClass;
    }
1386

Tom Tromey committed
1387 1388
  // Now we've come past the circularity problem, we can 
  // now say that we're loading.
Anthony Green committed
1389 1390 1391 1392 1393

  def->state = JV_STATE_LOADING;
  def->notifyAll ();
}

1394
///// Implements the checks described in sect. 5.3.5.3
Anthony Green committed
1395 1396 1397
void
_Jv_ClassReader::checkExtends (jclass sub, jclass super)
{
1398 1399
  using namespace java::lang::reflect;

1400 1401 1402
  _Jv_Linker::wait_for_state (super, JV_STATE_LOADING);

  // Having an interface or a final class as a superclass is no good.
1403
  if ((super->accflags & (Modifier::INTERFACE | Modifier::FINAL)) != 0)
Anthony Green committed
1404 1405 1406 1407
    {
      throw_incompatible_class_change_error (sub->getName ());
    }

1408
  // If the super class is not public, we need to check some more.
1409
  if ((super->accflags & Modifier::PUBLIC) == 0)
Anthony Green committed
1410
    {
1411 1412
      // With package scope, the classes must have the same class
      // loader.
Anthony Green committed
1413 1414 1415 1416 1417 1418 1419
      if (   sub->loader != super->loader
	  || !_Jv_ClassNameSamePackage (sub->name, super->name))
	{
	  throw_incompatible_class_change_error (sub->getName ());
	}
    } 

1420
  for (; super != 0; super = super->getSuperclass ())
Anthony Green committed
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
    {
      if (super == sub)
	throw_class_circularity_error (sub->getName ());
    }
}



void _Jv_ClassReader::handleInterfacesBegin (int count)
{
1431
  def->interfaces = (jclass*) _Jv_AllocRawObj (count*sizeof (jclass));
Anthony Green committed
1432 1433 1434 1435 1436
  def->interface_count = count;
}

void _Jv_ClassReader::handleInterface (int if_number, int offset)
{
Anthony Green committed
1437
  _Jv_word       * pool_data = def->constants.data;
Anthony Green committed
1438 1439 1440 1441 1442 1443
  unsigned char  * pool_tags = (unsigned char*) def->constants.tags;

  jclass the_interface;

  if (pool_tags[offset] == JV_CONSTANT_Class)
    {
Anthony Green committed
1444
      _Jv_Utf8Const* name = pool_data[offset].utf8;
Anthony Green committed
1445 1446 1447 1448
      the_interface =  _Jv_FindClass (name, def->loader);
    }
  else if (pool_tags[offset] == JV_CONSTANT_ResolvedClass)
    {
Anthony Green committed
1449
      the_interface = pool_data[offset].clazz;
Anthony Green committed
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
    }
  else
    {
      throw_no_class_def_found_error ("erroneous constant pool tag");
    }

  // checks the validity of the_interface, and that we are in fact
  // allowed to implement that interface.
  checkImplements (def, the_interface);
  
Anthony Green committed
1460
  pool_data[offset].clazz = the_interface;
Anthony Green committed
1461 1462 1463 1464 1465 1466 1467 1468
  pool_tags[offset] = JV_CONSTANT_ResolvedClass;
  
  def->interfaces[if_number] = the_interface;
}

void
_Jv_ClassReader::checkImplements (jclass sub, jclass super)
{
1469 1470
  using namespace java::lang::reflect;

Anthony Green committed
1471
  // well, it *must* be an interface
1472
  if ((super->accflags & Modifier::INTERFACE) == 0)
Anthony Green committed
1473 1474 1475 1476 1477 1478
    {
      throw_incompatible_class_change_error (sub->getName ());
    }

  // if it has package scope, it must also be defined by the 
  // same loader.
1479
  if ((super->accflags & Modifier::PUBLIC) == 0)
Anthony Green committed
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
    {
      if (    sub->loader != super->loader
	  || !_Jv_ClassNameSamePackage (sub->name, super->name))
	{
	  throw_incompatible_class_change_error (sub->getName ());
	}
    } 

  // FIXME: add interface circularity check here
  if (sub == super)
    {
      throw_class_circularity_error (sub->getName ());
    }		
}

void _Jv_ClassReader::handleFieldsBegin (int count)
{
1497
  def->fields = (_Jv_Field*) _Jv_AllocRawObj (count * sizeof (_Jv_Field));
Anthony Green committed
1498
  def->field_count = count;
1499 1500
  def_interp->field_initializers
    = (_Jv_ushort*) _Jv_AllocRawObj (count * sizeof (_Jv_ushort));
Anthony Green committed
1501
  for (int i = 0; i < count; i++)
1502
    def_interp->field_initializers[i] = (_Jv_ushort) 0;
Anthony Green committed
1503 1504 1505 1506 1507
}

void _Jv_ClassReader::handleField (int field_no,
				   int flags,
				   int name,
1508 1509
				   int desc,
				   int *fieldmap)
Anthony Green committed
1510
{
1511 1512
  using namespace java::lang::reflect;

Anthony Green committed
1513
  _Jv_word *pool_data = def->constants.data;
Anthony Green committed
1514

1515
  _Jv_Field *field = &def->fields[fieldmap[field_no]];
Anthony Green committed
1516
  _Jv_Utf8Const *field_name = pool_data[name].utf8;
Anthony Green committed
1517 1518 1519

  field->name      = field_name;

1520
  // Ignore flags we don't know about.  
1521 1522 1523
  field->flags = flags & (Field::FIELD_MODIFIERS
			  | Modifier::SYNTHETIC
			  | Modifier::ENUM);
Anthony Green committed
1524

1525 1526
  _Jv_Utf8Const* sig = pool_data[desc].utf8;

Anthony Green committed
1527 1528
  if (verify)
    {
1529 1530 1531 1532
      verify_identifier (field_name);

      for (int i = 0; i < field_no; ++i)
	{
1533
	  if (_Jv_equalUtf8Consts (field_name, def->fields[fieldmap[i]].name)
1534 1535 1536 1537 1538 1539 1540
	      && _Jv_equalUtf8Consts (sig,
				      // We know the other fields are
				      // unresolved.
				      (_Jv_Utf8Const *) def->fields[i].type))
	    throw_class_format_error ("duplicate field name");
	}

1541
      // At most one of PUBLIC, PRIVATE, or PROTECTED is allowed.
1542 1543 1544
      if (1 < ( ((field->flags & Modifier::PUBLIC) ? 1 : 0)
		+((field->flags & Modifier::PRIVATE) ? 1 : 0)
		+((field->flags & Modifier::PROTECTED) ? 1 : 0)))
Anthony Green committed
1545
	throw_class_format_error ("erroneous field access flags");
1546 1547 1548 1549

      // FIXME: JVM spec S4.5: Verify ACC_FINAL and ACC_VOLATILE are not 
      // both set. Verify modifiers for interface fields.
      
Anthony Green committed
1550 1551 1552
    }

  if (verify)
1553
    verify_field_signature (sig);
Anthony Green committed
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563

  // field->type is really a jclass, but while it is still
  // unresolved we keep an _Jv_Utf8Const* instead.
  field->type       = (jclass) sig;
  field->flags     |= _Jv_FIELD_UNRESOLVED_FLAG;
  field->u.boffset  = 0;
}


void _Jv_ClassReader::handleConstantValueAttribute (int field_index, 
1564 1565
						    int value,
						    bool *found_value)
Anthony Green committed
1566
{
1567 1568
  using namespace java::lang::reflect;

Anthony Green committed
1569 1570
  _Jv_Field *field = &def->fields[field_index];

1571 1572 1573
  if ((field->flags & (Modifier::STATIC
		       | Modifier::FINAL
		       | Modifier::PRIVATE)) == 0)
Anthony Green committed
1574 1575 1576 1577 1578 1579
    {
      // Ignore, as per vmspec #4.7.2
      return;
    }

  // do not allow multiple constant fields!
1580
  if (*found_value)
Anthony Green committed
1581 1582
    throw_class_format_error ("field has multiple ConstantValue attributes");

1583
  *found_value = true;
1584
  def_interp->field_initializers[field_index] = value;
Anthony Green committed
1585 1586 1587 1588 1589 1590 1591 1592 1593

  /* type check the initializer */
  
  if (value <= 0 || value >= pool_count)
    throw_class_format_error ("erroneous ConstantValue attribute");

  /* FIXME: do the rest */
}

1594 1595
void
_Jv_ClassReader::handleMethodsBegin (int count)
Anthony Green committed
1596
{
1597
  def->methods = (_Jv_Method *) _Jv_AllocRawObj (sizeof (_Jv_Method) * count);
Anthony Green committed
1598

1599
  def_interp->interpreted_methods
1600 1601
    = (_Jv_MethodBase **) _Jv_AllocRawObj (sizeof (_Jv_MethodBase *)
					   * count);
Anthony Green committed
1602 1603

  for (int i = 0; i < count; i++)
1604
    {
1605
      def_interp->interpreted_methods[i] = 0;
1606 1607
      def->methods[i].index = (_Jv_ushort) -1;
    }
Anthony Green committed
1608 1609 1610 1611 1612 1613 1614 1615

  def->method_count = count;
}


void _Jv_ClassReader::handleMethod 
    (int mth_index, int accflags, int name, int desc)
{ 
1616 1617
  using namespace java::lang::reflect;

Anthony Green committed
1618
  _Jv_word *pool_data = def->constants.data;
Anthony Green committed
1619 1620 1621
  _Jv_Method *method = &def->methods[mth_index];

  check_tag (name, JV_CONSTANT_Utf8);
1622
  prepare_pool_entry (name, JV_CONSTANT_Utf8, false);
Anthony Green committed
1623
  method->name = pool_data[name].utf8;
Anthony Green committed
1624 1625 1626

  check_tag (desc, JV_CONSTANT_Utf8);
  prepare_pool_entry (desc, JV_CONSTANT_Utf8);
Anthony Green committed
1627
  method->signature = pool_data[desc].utf8;
Anthony Green committed
1628 1629

  // ignore unknown flags
1630 1631 1632 1633
  method->accflags = accflags & (Method::METHOD_MODIFIERS
				 | Modifier::BRIDGE
				 | Modifier::SYNTHETIC
				 | Modifier::VARARGS);
Anthony Green committed
1634

1635
  // Initialize...
Anthony Green committed
1636
  method->ncode = 0;
1637
  method->throws = NULL;
Anthony Green committed
1638 1639 1640 1641 1642 1643 1644
  
  if (verify)
    {
      if (_Jv_equalUtf8Consts (method->name, clinit_name)
	  || _Jv_equalUtf8Consts (method->name, init_name))
	/* ignore */;
      else
1645
	verify_identifier (method->name);
Anthony Green committed
1646

1647
      verify_method_signature (method->signature);
Anthony Green committed
1648

1649 1650 1651 1652 1653 1654 1655 1656
      for (int i = 0; i < mth_index; ++i)
	{
	  if (_Jv_equalUtf8Consts (method->name, def->methods[i].name)
	      && _Jv_equalUtf8Consts (method->signature,
				      def->methods[i].signature))
	    throw_class_format_error ("duplicate method");
	}

1657
      // At most one of PUBLIC, PRIVATE, or PROTECTED is allowed.
1658 1659 1660
      if (1 < ( ((method->accflags & Modifier::PUBLIC) ? 1 : 0)
		+((method->accflags & Modifier::PRIVATE) ? 1 : 0)
		+((method->accflags & Modifier::PROTECTED) ? 1 : 0)))
Anthony Green committed
1661
	throw_class_format_error ("erroneous method access flags");
1662 1663

      // FIXME: JVM spec S4.6: if ABSTRACT modifier is set, verify other 
1664
      // flags are not set. Verify flags for interface methods.  Verify
1665
      // modifiers for initializers. 
Anthony Green committed
1666 1667 1668 1669 1670 1671 1672 1673 1674
    }
}

void _Jv_ClassReader::handleCodeAttribute
  (int method_index, int max_stack, int max_locals, 
   int code_start, int code_length, int exc_table_length)
{
  int size = _Jv_InterpMethod::size (exc_table_length, code_length);
  _Jv_InterpMethod *method = 
1675
    (_Jv_InterpMethod*) (_Jv_AllocRawObj (size));
Anthony Green committed
1676 1677 1678 1679 1680

  method->max_stack      = max_stack;
  method->max_locals     = max_locals;
  method->code_length    = code_length;
  method->exc_count      = exc_table_length;
1681
  method->is_15          = is_15;
Anthony Green committed
1682 1683
  method->defining_class = def;
  method->self           = &def->methods[method_index];
1684
  method->prepared       = NULL;
1685 1686
  method->line_table_len = 0;
  method->line_table     = NULL;
1687 1688 1689
#ifdef DIRECT_THREADED
  method->thread_count   = 0;
#endif
Anthony Green committed
1690 1691 1692 1693 1694

  // grab the byte code!
  memcpy ((void*) method->bytecode (),
	  (void*) (bytes+code_start),
	  code_length);
1695

1696
  def_interp->interpreted_methods[method_index] = method;
1697 1698 1699 1700 1701 1702 1703

  if ((method->self->accflags & java::lang::reflect::Modifier::STATIC))
    {
      // Precompute the ncode field for a static method.  This lets us
      // call a static method of an interpreted class from precompiled
      // code without first resolving the class (that will happen
      // during class initialization instead).
1704
      method->self->ncode = method->ncode (def);
1705
    }
Anthony Green committed
1706 1707
}

1708
void _Jv_ClassReader::handleExceptionTableEntry
Anthony Green committed
1709 1710 1711
  (int method_index, int exc_index, 
   int start_pc, int end_pc, int handler_pc, int catch_type)
{
1712
  _Jv_InterpMethod *method = reinterpret_cast<_Jv_InterpMethod *>
1713
    (def_interp->interpreted_methods[method_index]);
Anthony Green committed
1714 1715
  _Jv_InterpException *exc = method->exceptions ();

1716 1717 1718 1719
  exc[exc_index].start_pc.i     = start_pc;
  exc[exc_index].end_pc.i       = end_pc;
  exc[exc_index].handler_pc.i   = handler_pc;
  exc[exc_index].handler_type.i = catch_type;
Anthony Green committed
1720 1721 1722 1723
}

void _Jv_ClassReader::handleMethodsEnd ()
{
1724 1725
  using namespace java::lang::reflect;

Anthony Green committed
1726 1727 1728
  for (int i = 0; i < def->method_count; i++)
    {
      _Jv_Method *method = &def->methods[i];
1729 1730
      if ((method->accflags & Modifier::NATIVE) != 0)
	{
1731
	  if (def_interp->interpreted_methods[i] != 0)
1732 1733 1734 1735
	    throw_class_format_error ("code provided for native method");
	  else
	    {
	      _Jv_JNIMethod *m = (_Jv_JNIMethod *)
1736
		_Jv_AllocRawObj (sizeof (_Jv_JNIMethod));
1737 1738 1739
	      m->defining_class = def;
	      m->self = method;
	      m->function = NULL;
1740
	      def_interp->interpreted_methods[i] = m;
1741 1742 1743 1744 1745 1746 1747 1748

	      if ((method->accflags & Modifier::STATIC))
		{
		  // Precompute the ncode field for a static method.
		  // This lets us call a static method of an
		  // interpreted class from precompiled code without
		  // first resolving the class (that will happen
		  // during class initialization instead).
1749
		  method->ncode = m->ncode (def);
1750
		}
1751 1752 1753
	    }
	}
      else if ((method->accflags & Modifier::ABSTRACT) != 0)
Anthony Green committed
1754
	{
1755
	  if (def_interp->interpreted_methods[i] != 0)
1756
	    throw_class_format_error ("code provided for abstract method");
1757
	  method->ncode = (void *) &_Jv_ThrowAbstractMethodError;
Anthony Green committed
1758 1759 1760
	}
      else
	{
1761
	  if (def_interp->interpreted_methods[i] == 0)
1762
	    throw_class_format_error ("method with no code");
Anthony Green committed
1763 1764 1765 1766
	}
    }
}

1767
void _Jv_ClassReader::throw_class_format_error (const char *msg)
1768 1769 1770 1771 1772
{
  jstring str;
  if (def->name != NULL)
    {
      jsize mlen = strlen (msg);
1773 1774
      unsigned char* data = (unsigned char*) def->name->chars();
      int ulen = def->name->len();
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
      unsigned char* limit = data + ulen;
      jsize nlen = _Jv_strLengthUtf8 ((char *) data, ulen);
      jsize len = nlen + mlen + 3;
      str = JvAllocString(len);
      jchar *chrs = JvGetStringChars(str);
      while (data < limit)
	*chrs++ = UTF8_GET(data, limit);
      *chrs++ = ' ';
      *chrs++ = '(';
      for (;;)
	{
	  char c = *msg++;
	  if (c == 0)
	    break;
	  *chrs++ = c & 0xFFFF;
	}
      *chrs++ = ')';
    }
  else
    str = JvNewStringLatin1 (msg);
  ::throw_class_format_error (str);
}
Anthony Green committed
1797

1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
/** Here we define the exceptions that can be thrown */

static void
throw_no_class_def_found_error (jstring msg)
{
  throw (msg
	 ? new java::lang::NoClassDefFoundError (msg)
	 : new java::lang::NoClassDefFoundError);
}

static void
1809
throw_no_class_def_found_error (const char *msg)
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
{
  throw_no_class_def_found_error (JvNewStringLatin1 (msg));
}

static void
throw_class_format_error (jstring msg)
{
  throw (msg
	 ? new java::lang::ClassFormatError (msg)
	 : new java::lang::ClassFormatError);
}

static void
1823
throw_internal_error (const char *msg)
1824 1825 1826 1827
{
  throw new java::lang::InternalError (JvNewStringLatin1 (msg));
}

1828 1829
static void
throw_incompatible_class_change_error (jstring msg)
1830 1831 1832 1833
{
  throw new java::lang::IncompatibleClassChangeError (msg);
}

1834 1835
static void
throw_class_circularity_error (jstring msg)
1836 1837 1838 1839 1840 1841 1842 1843
{
  throw new java::lang::ClassCircularityError (msg);
}

#endif /* INTERPRETER */



Anthony Green committed
1844 1845 1846 1847 1848 1849 1850 1851
/** This section takes care of verifying integrity of identifiers,
    signatures, field ddescriptors, and class names */

#define UTF8_PEEK(PTR, LIMIT) \
  ({ unsigned char* xxkeep = (PTR); \
     int xxch = UTF8_GET(PTR,LIMIT); \
     PTR = xxkeep; xxch; })

1852
/* Verify one element of a type descriptor or signature.  */
Anthony Green committed
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
static unsigned char*
_Jv_VerifyOne (unsigned char* ptr, unsigned char* limit, bool void_ok)
{
  if (ptr >= limit)
    return 0;

  int ch = UTF8_GET (ptr, limit);

  switch (ch)
    {
    case 'V':
1864 1865
      if (! void_ok)
	return 0;
Anthony Green committed
1866 1867 1868 1869 1870 1871 1872 1873

    case 'S': case 'B': case 'I': case 'J':
    case 'Z': case 'C': case 'F': case 'D': 
      break;

    case 'L':
      {
	unsigned char *start = ptr, *end;
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
	do
	  {
	    if (ptr > limit)
	      return 0;

	    end = ptr;

	    if ((ch = UTF8_GET (ptr, limit)) == -1)
	      return 0;

	  }
	while (ch != ';');
1886 1887
	if (! _Jv_VerifyClassName (start, (unsigned short) (end-start)))
	  return 0;
Anthony Green committed
1888 1889 1890 1891 1892 1893
      }
      break;

    case '[':
      return _Jv_VerifyOne (ptr, limit, false);
      break;
1894

Anthony Green committed
1895 1896 1897 1898 1899 1900 1901
    default:
      return 0;
    }

  return ptr;
}

1902
/* Verification and loading procedures.  */
1903
bool
Anthony Green committed
1904 1905
_Jv_VerifyFieldSignature (_Jv_Utf8Const*sig)
{
1906 1907
  unsigned char* ptr = (unsigned char*) sig->chars();
  unsigned char* limit = ptr + sig->len();
Anthony Green committed
1908 1909 1910

  ptr = _Jv_VerifyOne (ptr, limit, false);

1911
  return ptr == limit;
Anthony Green committed
1912 1913
}

1914
bool
Anthony Green committed
1915 1916
_Jv_VerifyMethodSignature (_Jv_Utf8Const*sig)
{
1917 1918
  unsigned char* ptr = (unsigned char*) sig->chars();
  unsigned char* limit = ptr + sig->len();
Anthony Green committed
1919

1920 1921
  if (ptr == limit || UTF8_GET(ptr,limit) != '(')
    return false;
Anthony Green committed
1922 1923 1924

  while (ptr && UTF8_PEEK (ptr, limit) != ')')
    ptr = _Jv_VerifyOne (ptr, limit, false);
1925

1926
  if (! ptr || UTF8_GET (ptr, limit) != ')')
1927
    return false;
Anthony Green committed
1928 1929 1930 1931

  // get the return type
  ptr = _Jv_VerifyOne (ptr, limit, true);

1932
  return ptr == limit;
Anthony Green committed
1933 1934
}

1935 1936
/* We try to avoid calling the Character methods all the time, in
   fact, they will only be called for non-standard things. */
Anthony Green committed
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
static __inline__ int 
is_identifier_start (int c)
{
  unsigned int ch = (unsigned)c;

  if ((ch - 0x41U) < 29U) 		/* A ... Z */
    return 1;
  if ((ch - 0x61U) < 29U) 		/* a ... z */
    return 1;
  if (ch == 0x5FU)       		/* _ */
    return 1;

1949
  return java::lang::Character::isJavaIdentifierStart ((jchar) ch);
Anthony Green committed
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
}

static __inline__ int 
is_identifier_part (int c)
{
  unsigned int ch = (unsigned)c;

  if ((ch - 0x41U) < 29U) 		/* A ... Z */
    return 1;
  if ((ch - 0x61U) < 29U) 		/* a ... z */
    return 1;
  if ((ch - 0x30) < 10U)       		/* 0 .. 9 */
    return 1;
  if (ch == 0x5FU || ch == 0x24U)       /* _ $ */
    return 1;

1966
  return java::lang::Character::isJavaIdentifierStart ((jchar) ch);
Anthony Green committed
1967 1968
}

1969
bool
Anthony Green committed
1970 1971
_Jv_VerifyIdentifier (_Jv_Utf8Const* name)
{
1972 1973
  unsigned char *ptr   = (unsigned char*) name->chars();
  unsigned char *limit = (unsigned char*) name->limit();
Anthony Green committed
1974 1975 1976 1977
  int ch;

  if ((ch = UTF8_GET (ptr, limit))==-1
      || ! is_identifier_start (ch))
1978
    return false;
Anthony Green committed
1979 1980 1981 1982 1983

  while (ptr != limit)
    {
      if ((ch = UTF8_GET (ptr, limit))==-1
	  || ! is_identifier_part (ch))
1984
	return false;
Anthony Green committed
1985
    }
1986
  return true;
Anthony Green committed
1987 1988
}

1989
bool
Anthony Green committed
1990 1991 1992 1993 1994
_Jv_VerifyClassName (unsigned char* ptr, _Jv_ushort length)
{
  unsigned char *limit = ptr+length;
  int ch;

1995 1996
  if ('[' == UTF8_PEEK (ptr, limit))
    {
1997 1998 1999 2000
      unsigned char *end = _Jv_VerifyOne (++ptr, limit, false);
      // _Jv_VerifyOne must leave us looking at the terminating nul
      // byte.
      if (! end || *end)
2001
	return false;
2002
      else
2003
        return true;
2004 2005
    }

Anthony Green committed
2006
 next_level:
2007
  for (;;) {
Anthony Green committed
2008
    if ((ch = UTF8_GET (ptr, limit))==-1)
2009
      return false;
Anthony Green committed
2010
    if (! is_identifier_start (ch))
2011 2012
      return false;
    for (;;) {
Anthony Green committed
2013
      if (ptr == limit)
2014
	return true;
Anthony Green committed
2015
      else if ((ch = UTF8_GET (ptr, limit))==-1)
2016
	return false;
Anthony Green committed
2017 2018 2019
      else if (ch == '.')
	goto next_level;
      else if (! is_identifier_part (ch))
2020 2021 2022
	return false;
    }
  }
Anthony Green committed
2023 2024
}

2025
bool
Anthony Green committed
2026 2027
_Jv_VerifyClassName (_Jv_Utf8Const *name)
{
2028
  return _Jv_VerifyClassName ((unsigned char*)name->chars(), name->len());
Anthony Green committed
2029 2030
}

2031
/* Returns true, if NAME1 and NAME2 represent classes in the same
2032
   package.  Neither NAME2 nor NAME2 may name an array type.  */
Anthony Green committed
2033 2034 2035
bool
_Jv_ClassNameSamePackage (_Jv_Utf8Const *name1, _Jv_Utf8Const *name2)
{
2036 2037
  unsigned char* ptr1 = (unsigned char*) name1->chars();
  unsigned char* limit1 = (unsigned char*) name1->limit();
Anthony Green committed
2038 2039 2040 2041 2042 2043 2044 2045 2046

  unsigned char* last1 = ptr1;

  // scan name1, and find the last occurrence of '.'
  while (ptr1 < limit1) {
    int ch1 = UTF8_GET (ptr1, limit1);

    if (ch1 == '.')
      last1 = ptr1;
2047

Anthony Green committed
2048 2049 2050 2051
    else if (ch1 == -1)
      return false;
  }

2052
  // Now the length of NAME1's package name is LEN.
2053
  int len = last1 - (unsigned char*) name1->chars();
Anthony Green committed
2054

2055
  // If this is longer than NAME2, then we're off.
2056
  if (len > name2->len())
Anthony Green committed
2057 2058
    return false;

2059
  // Then compare the first len bytes for equality.
2060
  if (memcmp ((void*) name1->chars(), (void*) name2->chars(), len) == 0)
Anthony Green committed
2061
    {
2062
      // Check that there are no .'s after position LEN in NAME2.
Anthony Green committed
2063

2064 2065
      unsigned char* ptr2 = (unsigned char*) name2->chars() + len;
      unsigned char* limit2 = (unsigned char*) name2->limit();
Anthony Green committed
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076

      while (ptr2 < limit2)
	{
	  int ch2 = UTF8_GET (ptr2, limit2);
	  if (ch2 == -1 || ch2 == '.')
	    return false;
	}
      return true;
    }
  return false;
}