1 /* 2 * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "oops/inlineKlass.hpp" 26 #include "cds/cdsConfig.hpp" 27 #include "classfile/classFileParser.hpp" 28 #include "classfile/classFileStream.hpp" 29 #include "classfile/classLoader.hpp" 30 #include "classfile/classLoaderData.inline.hpp" 31 #include "classfile/classLoadInfo.hpp" 32 #include "classfile/defaultMethods.hpp" 33 #include "classfile/fieldLayoutBuilder.hpp" 34 #include "classfile/javaClasses.inline.hpp" 35 #include "classfile/moduleEntry.hpp" 36 #include "classfile/packageEntry.hpp" 37 #include "classfile/symbolTable.hpp" 38 #include "classfile/systemDictionary.hpp" 39 #include "classfile/verificationType.hpp" 40 #include "classfile/verifier.hpp" 41 #include "classfile/vmClasses.hpp" 42 #include "classfile/vmSymbols.hpp" 43 #include "jvm.h" 44 #include "logging/log.hpp" 45 #include "logging/logStream.hpp" 46 #include "memory/allocation.hpp" 47 #include "memory/metadataFactory.hpp" 48 #include "memory/oopFactory.hpp" 49 #include "memory/resourceArea.hpp" 50 #include "memory/universe.hpp" 51 #include "oops/annotations.hpp" 52 #include "oops/constantPool.inline.hpp" 53 #include "oops/fieldInfo.hpp" 54 #include "oops/fieldStreams.inline.hpp" 55 #include "oops/inlineKlass.inline.hpp" 56 #include "oops/instanceKlass.inline.hpp" 57 #include "oops/instanceMirrorKlass.hpp" 58 #include "oops/klass.inline.hpp" 59 #include "oops/klassVtable.hpp" 60 #include "oops/metadata.hpp" 61 #include "oops/method.inline.hpp" 62 #include "oops/oop.inline.hpp" 63 #include "oops/recordComponent.hpp" 64 #include "oops/symbol.hpp" 65 #include "prims/jvmtiExport.hpp" 66 #include "prims/jvmtiThreadState.hpp" 67 #include "runtime/arguments.hpp" 68 #include "runtime/fieldDescriptor.inline.hpp" 69 #include "runtime/handles.inline.hpp" 70 #include "runtime/javaCalls.hpp" 71 #include "runtime/os.hpp" 72 #include "runtime/perfData.hpp" 73 #include "runtime/reflection.hpp" 74 #include "runtime/safepointVerifiers.hpp" 75 #include "runtime/signature.hpp" 76 #include "runtime/timer.hpp" 77 #include "services/classLoadingService.hpp" 78 #include "services/threadService.hpp" 79 #include "utilities/align.hpp" 80 #include "utilities/bitMap.inline.hpp" 81 #include "utilities/checkedCast.hpp" 82 #include "utilities/copy.hpp" 83 #include "utilities/formatBuffer.hpp" 84 #include "utilities/exceptions.hpp" 85 #include "utilities/globalDefinitions.hpp" 86 #include "utilities/growableArray.hpp" 87 #include "utilities/macros.hpp" 88 #include "utilities/ostream.hpp" 89 #include "utilities/resourceHash.hpp" 90 #include "utilities/stringUtils.hpp" 91 #include "utilities/utf8.hpp" 92 #if INCLUDE_CDS 93 #include "classfile/systemDictionaryShared.hpp" 94 #endif 95 #if INCLUDE_JFR 96 #include "jfr/support/jfrTraceIdExtension.hpp" 97 #endif 98 99 // We generally try to create the oops directly when parsing, rather than 100 // allocating temporary data structures and copying the bytes twice. A 101 // temporary area is only needed when parsing utf8 entries in the constant 102 // pool and when parsing line number tables. 103 104 // We add assert in debug mode when class format is not checked. 105 106 #define JAVA_CLASSFILE_MAGIC 0xCAFEBABE 107 #define JAVA_MIN_SUPPORTED_VERSION 45 108 #define JAVA_PREVIEW_MINOR_VERSION 65535 109 110 // Used for two backward compatibility reasons: 111 // - to check for new additions to the class file format in JDK1.5 112 // - to check for bug fixes in the format checker in JDK1.5 113 #define JAVA_1_5_VERSION 49 114 115 // Used for backward compatibility reasons: 116 // - to check for javac bug fixes that happened after 1.5 117 // - also used as the max version when running in jdk6 118 #define JAVA_6_VERSION 50 119 120 // Used for backward compatibility reasons: 121 // - to disallow argument and require ACC_STATIC for <clinit> methods 122 #define JAVA_7_VERSION 51 123 124 // Extension method support. 125 #define JAVA_8_VERSION 52 126 127 #define JAVA_9_VERSION 53 128 129 #define JAVA_10_VERSION 54 130 131 #define JAVA_11_VERSION 55 132 133 #define JAVA_12_VERSION 56 134 135 #define JAVA_13_VERSION 57 136 137 #define JAVA_14_VERSION 58 138 139 #define JAVA_15_VERSION 59 140 141 #define JAVA_16_VERSION 60 142 143 #define JAVA_17_VERSION 61 144 145 #define JAVA_18_VERSION 62 146 147 #define JAVA_19_VERSION 63 148 149 #define JAVA_20_VERSION 64 150 151 #define JAVA_21_VERSION 65 152 153 #define JAVA_22_VERSION 66 154 155 #define JAVA_23_VERSION 67 156 157 #define CONSTANT_CLASS_DESCRIPTORS 69 158 159 #define JAVA_24_VERSION 68 160 161 #define JAVA_25_VERSION 69 162 163 void ClassFileParser::set_class_bad_constant_seen(short bad_constant) { 164 assert((bad_constant == JVM_CONSTANT_Module || 165 bad_constant == JVM_CONSTANT_Package) && _major_version >= JAVA_9_VERSION, 166 "Unexpected bad constant pool entry"); 167 if (_bad_constant_seen == 0) _bad_constant_seen = bad_constant; 168 } 169 170 void ClassFileParser::parse_constant_pool_entries(const ClassFileStream* const stream, 171 ConstantPool* cp, 172 const int length, 173 TRAPS) { 174 assert(stream != nullptr, "invariant"); 175 assert(cp != nullptr, "invariant"); 176 177 // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize 178 // this function (_current can be allocated in a register, with scalar 179 // replacement of aggregates). The _current pointer is copied back to 180 // stream() when this function returns. DON'T call another method within 181 // this method that uses stream(). 182 const ClassFileStream cfs1 = *stream; 183 const ClassFileStream* const cfs = &cfs1; 184 185 debug_only(const u1* const old_current = stream->current();) 186 187 // Used for batching symbol allocations. 188 const char* names[SymbolTable::symbol_alloc_batch_size]; 189 int lengths[SymbolTable::symbol_alloc_batch_size]; 190 int indices[SymbolTable::symbol_alloc_batch_size]; 191 unsigned int hashValues[SymbolTable::symbol_alloc_batch_size]; 192 int names_count = 0; 193 194 // parsing Index 0 is unused 195 for (int index = 1; index < length; index++) { 196 // Each of the following case guarantees one more byte in the stream 197 // for the following tag or the access_flags following constant pool, 198 // so we don't need bounds-check for reading tag. 199 const u1 tag = cfs->get_u1_fast(); 200 switch (tag) { 201 case JVM_CONSTANT_Class: { 202 cfs->guarantee_more(3, CHECK); // name_index, tag/access_flags 203 const u2 name_index = cfs->get_u2_fast(); 204 cp->klass_index_at_put(index, name_index); 205 break; 206 } 207 case JVM_CONSTANT_Fieldref: { 208 cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags 209 const u2 class_index = cfs->get_u2_fast(); 210 const u2 name_and_type_index = cfs->get_u2_fast(); 211 cp->field_at_put(index, class_index, name_and_type_index); 212 break; 213 } 214 case JVM_CONSTANT_Methodref: { 215 cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags 216 const u2 class_index = cfs->get_u2_fast(); 217 const u2 name_and_type_index = cfs->get_u2_fast(); 218 cp->method_at_put(index, class_index, name_and_type_index); 219 break; 220 } 221 case JVM_CONSTANT_InterfaceMethodref: { 222 cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags 223 const u2 class_index = cfs->get_u2_fast(); 224 const u2 name_and_type_index = cfs->get_u2_fast(); 225 cp->interface_method_at_put(index, class_index, name_and_type_index); 226 break; 227 } 228 case JVM_CONSTANT_String : { 229 cfs->guarantee_more(3, CHECK); // string_index, tag/access_flags 230 const u2 string_index = cfs->get_u2_fast(); 231 cp->string_index_at_put(index, string_index); 232 break; 233 } 234 case JVM_CONSTANT_MethodHandle : 235 case JVM_CONSTANT_MethodType: { 236 if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) { 237 classfile_parse_error( 238 "Class file version does not support constant tag %u in class file %s", 239 tag, THREAD); 240 return; 241 } 242 if (tag == JVM_CONSTANT_MethodHandle) { 243 cfs->guarantee_more(4, CHECK); // ref_kind, method_index, tag/access_flags 244 const u1 ref_kind = cfs->get_u1_fast(); 245 const u2 method_index = cfs->get_u2_fast(); 246 cp->method_handle_index_at_put(index, ref_kind, method_index); 247 } 248 else if (tag == JVM_CONSTANT_MethodType) { 249 cfs->guarantee_more(3, CHECK); // signature_index, tag/access_flags 250 const u2 signature_index = cfs->get_u2_fast(); 251 cp->method_type_index_at_put(index, signature_index); 252 } 253 else { 254 ShouldNotReachHere(); 255 } 256 break; 257 } 258 case JVM_CONSTANT_Dynamic : { 259 if (_major_version < Verifier::DYNAMICCONSTANT_MAJOR_VERSION) { 260 classfile_parse_error( 261 "Class file version does not support constant tag %u in class file %s", 262 tag, THREAD); 263 return; 264 } 265 cfs->guarantee_more(5, CHECK); // bsm_index, nt, tag/access_flags 266 const u2 bootstrap_specifier_index = cfs->get_u2_fast(); 267 const u2 name_and_type_index = cfs->get_u2_fast(); 268 if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index) { 269 _max_bootstrap_specifier_index = (int) bootstrap_specifier_index; // collect for later 270 } 271 cp->dynamic_constant_at_put(index, bootstrap_specifier_index, name_and_type_index); 272 break; 273 } 274 case JVM_CONSTANT_InvokeDynamic : { 275 if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) { 276 classfile_parse_error( 277 "Class file version does not support constant tag %u in class file %s", 278 tag, THREAD); 279 return; 280 } 281 cfs->guarantee_more(5, CHECK); // bsm_index, nt, tag/access_flags 282 const u2 bootstrap_specifier_index = cfs->get_u2_fast(); 283 const u2 name_and_type_index = cfs->get_u2_fast(); 284 if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index) { 285 _max_bootstrap_specifier_index = (int) bootstrap_specifier_index; // collect for later 286 } 287 cp->invoke_dynamic_at_put(index, bootstrap_specifier_index, name_and_type_index); 288 break; 289 } 290 case JVM_CONSTANT_Integer: { 291 cfs->guarantee_more(5, CHECK); // bytes, tag/access_flags 292 const u4 bytes = cfs->get_u4_fast(); 293 cp->int_at_put(index, (jint)bytes); 294 break; 295 } 296 case JVM_CONSTANT_Float: { 297 cfs->guarantee_more(5, CHECK); // bytes, tag/access_flags 298 const u4 bytes = cfs->get_u4_fast(); 299 cp->float_at_put(index, *(jfloat*)&bytes); 300 break; 301 } 302 case JVM_CONSTANT_Long: { 303 // A mangled type might cause you to overrun allocated memory 304 guarantee_property(index + 1 < length, 305 "Invalid constant pool entry %u in class file %s", 306 index, 307 CHECK); 308 cfs->guarantee_more(9, CHECK); // bytes, tag/access_flags 309 const u8 bytes = cfs->get_u8_fast(); 310 cp->long_at_put(index, bytes); 311 index++; // Skip entry following eigth-byte constant, see JVM book p. 98 312 break; 313 } 314 case JVM_CONSTANT_Double: { 315 // A mangled type might cause you to overrun allocated memory 316 guarantee_property(index+1 < length, 317 "Invalid constant pool entry %u in class file %s", 318 index, 319 CHECK); 320 cfs->guarantee_more(9, CHECK); // bytes, tag/access_flags 321 const u8 bytes = cfs->get_u8_fast(); 322 cp->double_at_put(index, *(jdouble*)&bytes); 323 index++; // Skip entry following eigth-byte constant, see JVM book p. 98 324 break; 325 } 326 case JVM_CONSTANT_NameAndType: { 327 cfs->guarantee_more(5, CHECK); // name_index, signature_index, tag/access_flags 328 const u2 name_index = cfs->get_u2_fast(); 329 const u2 signature_index = cfs->get_u2_fast(); 330 cp->name_and_type_at_put(index, name_index, signature_index); 331 break; 332 } 333 case JVM_CONSTANT_Utf8 : { 334 cfs->guarantee_more(2, CHECK); // utf8_length 335 u2 utf8_length = cfs->get_u2_fast(); 336 const u1* utf8_buffer = cfs->current(); 337 assert(utf8_buffer != nullptr, "null utf8 buffer"); 338 // Got utf8 string, guarantee utf8_length+1 bytes, set stream position forward. 339 cfs->guarantee_more(utf8_length+1, CHECK); // utf8 string, tag/access_flags 340 cfs->skip_u1_fast(utf8_length); 341 342 // Before storing the symbol, make sure it's legal 343 if (_need_verify) { 344 verify_legal_utf8(utf8_buffer, utf8_length, CHECK); 345 } 346 347 unsigned int hash; 348 Symbol* const result = SymbolTable::lookup_only((const char*)utf8_buffer, 349 utf8_length, 350 hash); 351 if (result == nullptr) { 352 names[names_count] = (const char*)utf8_buffer; 353 lengths[names_count] = utf8_length; 354 indices[names_count] = index; 355 hashValues[names_count++] = hash; 356 if (names_count == SymbolTable::symbol_alloc_batch_size) { 357 SymbolTable::new_symbols(_loader_data, 358 constantPoolHandle(THREAD, cp), 359 names_count, 360 names, 361 lengths, 362 indices, 363 hashValues); 364 names_count = 0; 365 } 366 } else { 367 cp->symbol_at_put(index, result); 368 } 369 break; 370 } 371 case JVM_CONSTANT_Module: 372 case JVM_CONSTANT_Package: { 373 // Record that an error occurred in these two cases but keep parsing so 374 // that ACC_Module can be checked for in the access_flags. Need to 375 // throw NoClassDefFoundError in that case. 376 if (_major_version >= JAVA_9_VERSION) { 377 cfs->guarantee_more(3, CHECK); 378 cfs->get_u2_fast(); 379 set_class_bad_constant_seen(tag); 380 break; 381 } 382 } 383 default: { 384 classfile_parse_error("Unknown constant tag %u in class file %s", 385 tag, 386 THREAD); 387 return; 388 } 389 } // end of switch(tag) 390 } // end of for 391 392 // Allocate the remaining symbols 393 if (names_count > 0) { 394 SymbolTable::new_symbols(_loader_data, 395 constantPoolHandle(THREAD, cp), 396 names_count, 397 names, 398 lengths, 399 indices, 400 hashValues); 401 } 402 403 // Copy _current pointer of local copy back to stream. 404 assert(stream->current() == old_current, "non-exclusive use of stream"); 405 stream->set_current(cfs1.current()); 406 407 } 408 409 static inline bool valid_cp_range(int index, int length) { 410 return (index > 0 && index < length); 411 } 412 413 static inline Symbol* check_symbol_at(const ConstantPool* cp, int index) { 414 assert(cp != nullptr, "invariant"); 415 if (valid_cp_range(index, cp->length()) && cp->tag_at(index).is_utf8()) { 416 return cp->symbol_at(index); 417 } 418 return nullptr; 419 } 420 421 void ClassFileParser::parse_constant_pool(const ClassFileStream* const stream, 422 ConstantPool* const cp, 423 const int length, 424 TRAPS) { 425 assert(cp != nullptr, "invariant"); 426 assert(stream != nullptr, "invariant"); 427 428 // parsing constant pool entries 429 parse_constant_pool_entries(stream, cp, length, CHECK); 430 if (class_bad_constant_seen() != 0) { 431 // a bad CP entry has been detected previously so stop parsing and just return. 432 return; 433 } 434 435 int index = 1; // declared outside of loops for portability 436 int num_klasses = 0; 437 438 // first verification pass - validate cross references 439 // and fixup class and string constants 440 for (index = 1; index < length; index++) { // Index 0 is unused 441 const jbyte tag = cp->tag_at(index).value(); 442 switch (tag) { 443 case JVM_CONSTANT_Class: { 444 ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present 445 break; 446 } 447 case JVM_CONSTANT_Fieldref: 448 // fall through 449 case JVM_CONSTANT_Methodref: 450 // fall through 451 case JVM_CONSTANT_InterfaceMethodref: { 452 if (!_need_verify) break; 453 const int klass_ref_index = cp->uncached_klass_ref_index_at(index); 454 const int name_and_type_ref_index = cp->uncached_name_and_type_ref_index_at(index); 455 guarantee_property(valid_klass_reference_at(klass_ref_index), 456 "Invalid constant pool index %u in class file %s", 457 klass_ref_index, CHECK); 458 guarantee_property(valid_cp_range(name_and_type_ref_index, length) && 459 cp->tag_at(name_and_type_ref_index).is_name_and_type(), 460 "Invalid constant pool index %u in class file %s", 461 name_and_type_ref_index, CHECK); 462 break; 463 } 464 case JVM_CONSTANT_String: { 465 ShouldNotReachHere(); // Only JVM_CONSTANT_StringIndex should be present 466 break; 467 } 468 case JVM_CONSTANT_Integer: 469 break; 470 case JVM_CONSTANT_Float: 471 break; 472 case JVM_CONSTANT_Long: 473 case JVM_CONSTANT_Double: { 474 index++; 475 guarantee_property( 476 (index < length && cp->tag_at(index).is_invalid()), 477 "Improper constant pool long/double index %u in class file %s", 478 index, CHECK); 479 break; 480 } 481 case JVM_CONSTANT_NameAndType: { 482 if (!_need_verify) break; 483 const int name_ref_index = cp->name_ref_index_at(index); 484 const int signature_ref_index = cp->signature_ref_index_at(index); 485 guarantee_property(valid_symbol_at(name_ref_index), 486 "Invalid constant pool index %u in class file %s", 487 name_ref_index, CHECK); 488 guarantee_property(valid_symbol_at(signature_ref_index), 489 "Invalid constant pool index %u in class file %s", 490 signature_ref_index, CHECK); 491 break; 492 } 493 case JVM_CONSTANT_Utf8: 494 break; 495 case JVM_CONSTANT_UnresolvedClass: // fall-through 496 case JVM_CONSTANT_UnresolvedClassInError: { 497 ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present 498 break; 499 } 500 case JVM_CONSTANT_ClassIndex: { 501 const int class_index = cp->klass_index_at(index); 502 guarantee_property(valid_symbol_at(class_index), 503 "Invalid constant pool index %u in class file %s", 504 class_index, CHECK); 505 506 Symbol* const name = cp->symbol_at(class_index); 507 const unsigned int name_len = name->utf8_length(); 508 cp->unresolved_klass_at_put(index, class_index, num_klasses++); 509 break; 510 } 511 case JVM_CONSTANT_StringIndex: { 512 const int string_index = cp->string_index_at(index); 513 guarantee_property(valid_symbol_at(string_index), 514 "Invalid constant pool index %u in class file %s", 515 string_index, CHECK); 516 Symbol* const sym = cp->symbol_at(string_index); 517 cp->unresolved_string_at_put(index, sym); 518 break; 519 } 520 case JVM_CONSTANT_MethodHandle: { 521 const int ref_index = cp->method_handle_index_at(index); 522 guarantee_property(valid_cp_range(ref_index, length), 523 "Invalid constant pool index %u in class file %s", 524 ref_index, CHECK); 525 const constantTag tag = cp->tag_at(ref_index); 526 const int ref_kind = cp->method_handle_ref_kind_at(index); 527 528 switch (ref_kind) { 529 case JVM_REF_getField: 530 case JVM_REF_getStatic: 531 case JVM_REF_putField: 532 case JVM_REF_putStatic: { 533 guarantee_property( 534 tag.is_field(), 535 "Invalid constant pool index %u in class file %s (not a field)", 536 ref_index, CHECK); 537 break; 538 } 539 case JVM_REF_invokeVirtual: 540 case JVM_REF_newInvokeSpecial: { 541 guarantee_property( 542 tag.is_method(), 543 "Invalid constant pool index %u in class file %s (not a method)", 544 ref_index, CHECK); 545 break; 546 } 547 case JVM_REF_invokeStatic: 548 case JVM_REF_invokeSpecial: { 549 guarantee_property( 550 tag.is_method() || 551 ((_major_version >= JAVA_8_VERSION) && tag.is_interface_method()), 552 "Invalid constant pool index %u in class file %s (not a method)", 553 ref_index, CHECK); 554 break; 555 } 556 case JVM_REF_invokeInterface: { 557 guarantee_property( 558 tag.is_interface_method(), 559 "Invalid constant pool index %u in class file %s (not an interface method)", 560 ref_index, CHECK); 561 break; 562 } 563 default: { 564 classfile_parse_error( 565 "Bad method handle kind at constant pool index %u in class file %s", 566 index, THREAD); 567 return; 568 } 569 } // switch(refkind) 570 // Keep the ref_index unchanged. It will be indirected at link-time. 571 break; 572 } // case MethodHandle 573 case JVM_CONSTANT_MethodType: { 574 const int ref_index = cp->method_type_index_at(index); 575 guarantee_property(valid_symbol_at(ref_index), 576 "Invalid constant pool index %u in class file %s", 577 ref_index, CHECK); 578 break; 579 } 580 case JVM_CONSTANT_Dynamic: { 581 const int name_and_type_ref_index = 582 cp->bootstrap_name_and_type_ref_index_at(index); 583 584 guarantee_property(valid_cp_range(name_and_type_ref_index, length) && 585 cp->tag_at(name_and_type_ref_index).is_name_and_type(), 586 "Invalid constant pool index %u in class file %s", 587 name_and_type_ref_index, CHECK); 588 // bootstrap specifier index must be checked later, 589 // when BootstrapMethods attr is available 590 591 // Mark the constant pool as having a CONSTANT_Dynamic_info structure 592 cp->set_has_dynamic_constant(); 593 break; 594 } 595 case JVM_CONSTANT_InvokeDynamic: { 596 const int name_and_type_ref_index = 597 cp->bootstrap_name_and_type_ref_index_at(index); 598 599 guarantee_property(valid_cp_range(name_and_type_ref_index, length) && 600 cp->tag_at(name_and_type_ref_index).is_name_and_type(), 601 "Invalid constant pool index %u in class file %s", 602 name_and_type_ref_index, CHECK); 603 // bootstrap specifier index must be checked later, 604 // when BootstrapMethods attr is available 605 break; 606 } 607 default: { 608 fatal("bad constant pool tag value %u", cp->tag_at(index).value()); 609 ShouldNotReachHere(); 610 break; 611 } 612 } // switch(tag) 613 } // end of for 614 615 cp->allocate_resolved_klasses(_loader_data, num_klasses, CHECK); 616 617 if (!_need_verify) { 618 return; 619 } 620 621 // second verification pass - checks the strings are of the right format. 622 // but not yet to the other entries 623 for (index = 1; index < length; index++) { 624 const jbyte tag = cp->tag_at(index).value(); 625 switch (tag) { 626 case JVM_CONSTANT_UnresolvedClass: { 627 const Symbol* const class_name = cp->klass_name_at(index); 628 // check the name 629 verify_legal_class_name(class_name, CHECK); 630 break; 631 } 632 case JVM_CONSTANT_NameAndType: { 633 if (_need_verify) { 634 const int sig_index = cp->signature_ref_index_at(index); 635 const int name_index = cp->name_ref_index_at(index); 636 const Symbol* const name = cp->symbol_at(name_index); 637 const Symbol* const sig = cp->symbol_at(sig_index); 638 guarantee_property(sig->utf8_length() != 0, 639 "Illegal zero length constant pool entry at %d in class %s", 640 sig_index, CHECK); 641 guarantee_property(name->utf8_length() != 0, 642 "Illegal zero length constant pool entry at %d in class %s", 643 name_index, CHECK); 644 645 if (Signature::is_method(sig)) { 646 // Format check method name and signature 647 verify_legal_method_name(name, CHECK); 648 verify_legal_method_signature(name, sig, CHECK); 649 } else { 650 // Format check field name and signature 651 verify_legal_field_name(name, CHECK); 652 verify_legal_field_signature(name, sig, CHECK); 653 } 654 } 655 break; 656 } 657 case JVM_CONSTANT_Dynamic: { 658 const int name_and_type_ref_index = 659 cp->uncached_name_and_type_ref_index_at(index); 660 // already verified to be utf8 661 const int name_ref_index = 662 cp->name_ref_index_at(name_and_type_ref_index); 663 // already verified to be utf8 664 const int signature_ref_index = 665 cp->signature_ref_index_at(name_and_type_ref_index); 666 const Symbol* const name = cp->symbol_at(name_ref_index); 667 const Symbol* const signature = cp->symbol_at(signature_ref_index); 668 if (_need_verify) { 669 // CONSTANT_Dynamic's name and signature are verified above, when iterating NameAndType_info. 670 // Need only to be sure signature is the right type. 671 if (Signature::is_method(signature)) { 672 throwIllegalSignature("CONSTANT_Dynamic", name, signature, CHECK); 673 } 674 } 675 break; 676 } 677 case JVM_CONSTANT_InvokeDynamic: 678 case JVM_CONSTANT_Fieldref: 679 case JVM_CONSTANT_Methodref: 680 case JVM_CONSTANT_InterfaceMethodref: { 681 const int name_and_type_ref_index = 682 cp->uncached_name_and_type_ref_index_at(index); 683 // already verified to be utf8 684 const int name_ref_index = 685 cp->name_ref_index_at(name_and_type_ref_index); 686 // already verified to be utf8 687 const int signature_ref_index = 688 cp->signature_ref_index_at(name_and_type_ref_index); 689 const Symbol* const name = cp->symbol_at(name_ref_index); 690 const Symbol* const signature = cp->symbol_at(signature_ref_index); 691 if (tag == JVM_CONSTANT_Fieldref) { 692 if (_need_verify) { 693 // Field name and signature are verified above, when iterating NameAndType_info. 694 // Need only to be sure signature is non-zero length and the right type. 695 if (Signature::is_method(signature)) { 696 throwIllegalSignature("Field", name, signature, CHECK); 697 } 698 } 699 } else { 700 if (_need_verify) { 701 // Method name and signature are individually verified above, when iterating 702 // NameAndType_info. Need to check here that signature is non-zero length and 703 // the right type. 704 if (!Signature::is_method(signature)) { 705 throwIllegalSignature("Method", name, signature, CHECK); 706 } 707 } 708 // If a class method name begins with '<', it must be "<init>" and have void signature. 709 const unsigned int name_len = name->utf8_length(); 710 if (tag == JVM_CONSTANT_Methodref && name_len != 0 && 711 name->char_at(0) == JVM_SIGNATURE_SPECIAL) { 712 if (name != vmSymbols::object_initializer_name()) { 713 classfile_parse_error( 714 "Bad method name at constant pool index %u in class file %s", 715 name_ref_index, THREAD); 716 return; 717 } else if (!Signature::is_void_method(signature)) { // must have void signature. 718 throwIllegalSignature("Method", name, signature, CHECK); 719 } 720 } 721 } 722 break; 723 } 724 case JVM_CONSTANT_MethodHandle: { 725 const int ref_index = cp->method_handle_index_at(index); 726 const int ref_kind = cp->method_handle_ref_kind_at(index); 727 switch (ref_kind) { 728 case JVM_REF_invokeVirtual: 729 case JVM_REF_invokeStatic: 730 case JVM_REF_invokeSpecial: 731 case JVM_REF_newInvokeSpecial: { 732 const int name_and_type_ref_index = 733 cp->uncached_name_and_type_ref_index_at(ref_index); 734 const int name_ref_index = 735 cp->name_ref_index_at(name_and_type_ref_index); 736 const Symbol* const name = cp->symbol_at(name_ref_index); 737 738 if (name != vmSymbols::object_initializer_name()) { // !<init> 739 if (ref_kind == JVM_REF_newInvokeSpecial) { 740 classfile_parse_error( 741 "Bad constructor name at constant pool index %u in class file %s", 742 name_ref_index, THREAD); 743 return; 744 } 745 } else { // <init> 746 // The allowed invocation mode of <init> depends on its signature. 747 // This test corresponds to verify_invoke_instructions in the verifier. 748 const int signature_ref_index = 749 cp->signature_ref_index_at(name_and_type_ref_index); 750 const Symbol* const signature = cp->symbol_at(signature_ref_index); 751 if (signature->is_void_method_signature() 752 && ref_kind == JVM_REF_newInvokeSpecial) { 753 // OK, could be a constructor call 754 } else { 755 classfile_parse_error( 756 "Bad method name at constant pool index %u in class file %s", 757 name_ref_index, THREAD); 758 return; 759 } 760 } 761 break; 762 } 763 // Other ref_kinds are already fully checked in previous pass. 764 } // switch(ref_kind) 765 break; 766 } 767 case JVM_CONSTANT_MethodType: { 768 const Symbol* const no_name = vmSymbols::type_name(); // place holder 769 const Symbol* const signature = cp->method_type_signature_at(index); 770 verify_legal_method_signature(no_name, signature, CHECK); 771 break; 772 } 773 case JVM_CONSTANT_Utf8: { 774 assert(cp->symbol_at(index)->refcount() != 0, "count corrupted"); 775 } 776 } // switch(tag) 777 } // end of for 778 } 779 780 class NameSigHash: public ResourceObj { 781 public: 782 const Symbol* _name; // name 783 const Symbol* _sig; // signature 784 785 static const int HASH_ROW_SIZE = 256; 786 787 NameSigHash(Symbol* name, Symbol* sig) : 788 _name(name), 789 _sig(sig) {} 790 791 static unsigned int hash(NameSigHash const& namesig) { 792 return namesig._name->identity_hash() ^ namesig._sig->identity_hash(); 793 } 794 795 static bool equals(NameSigHash const& e0, NameSigHash const& e1) { 796 return (e0._name == e1._name) && 797 (e0._sig == e1._sig); 798 } 799 }; 800 801 using NameSigHashtable = ResourceHashtable<NameSigHash, int, 802 NameSigHash::HASH_ROW_SIZE, 803 AnyObj::RESOURCE_AREA, mtInternal, 804 &NameSigHash::hash, &NameSigHash::equals>; 805 806 static void check_identity_and_value_modifiers(ClassFileParser* current, const InstanceKlass* super_type, TRAPS) { 807 assert(super_type != nullptr,"Method doesn't support null super type"); 808 if (super_type->access_flags().is_identity_class() && !current->access_flags().is_identity_class() 809 && super_type->name() != vmSymbols::java_lang_Object()) { 810 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), 811 err_msg("Value type %s has an identity type as supertype", 812 current->class_name()->as_klass_external_name())); 813 } 814 } 815 816 void ClassFileParser::parse_interfaces(const ClassFileStream* stream, 817 int itfs_len, 818 ConstantPool* cp, 819 bool* const has_nonstatic_concrete_methods, 820 // FIXME: lots of these functions 821 // declare their parameters as const, 822 // which adds only noise to the code. 823 // Remove the spurious const modifiers. 824 // Many are of the form "const int x" 825 // or "T* const x". 826 TRAPS) { 827 assert(stream != nullptr, "invariant"); 828 assert(cp != nullptr, "invariant"); 829 assert(has_nonstatic_concrete_methods != nullptr, "invariant"); 830 831 if (itfs_len == 0) { 832 _local_interfaces = Universe::the_empty_instance_klass_array(); 833 834 } else { 835 assert(itfs_len > 0, "only called for len>0"); 836 _local_interface_indexes = new GrowableArray<u2>(itfs_len); 837 int index = 0; 838 for (index = 0; index < itfs_len; index++) { 839 const u2 interface_index = stream->get_u2(CHECK); 840 guarantee_property( 841 valid_klass_reference_at(interface_index), 842 "Interface name has bad constant pool index %u in class file %s", 843 interface_index, CHECK); 844 _local_interface_indexes->at_put_grow(index, interface_index); 845 } 846 847 if (!_need_verify || itfs_len <= 1) { 848 return; 849 } 850 851 // Check if there's any duplicates in interfaces 852 ResourceMark rm(THREAD); 853 // Set containing interface names 854 ResourceHashtable<Symbol*, int>* interface_names = new ResourceHashtable<Symbol*, int>(); 855 for (index = 0; index < itfs_len; index++) { 856 Symbol* interface_name = cp->klass_name_at(_local_interface_indexes->at(index)); 857 // If no duplicates, add (name, nullptr) in hashtable interface_names. 858 if (!interface_names->put(interface_name, 0)) { 859 classfile_parse_error("Duplicate interface name \"%s\" in class file %s", 860 interface_name->as_C_string(), THREAD); 861 return; 862 } 863 } 864 } 865 } 866 867 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp, 868 int constantvalue_index, 869 int signature_index, 870 TRAPS) const { 871 // Make sure the constant pool entry is of a type appropriate to this field 872 guarantee_property( 873 (constantvalue_index > 0 && 874 constantvalue_index < cp->length()), 875 "Bad initial value index %u in ConstantValue attribute in class file %s", 876 constantvalue_index, CHECK); 877 878 const constantTag value_type = cp->tag_at(constantvalue_index); 879 switch(cp->basic_type_for_signature_at(signature_index)) { 880 case T_LONG: { 881 guarantee_property(value_type.is_long(), 882 "Inconsistent constant value type in class file %s", 883 CHECK); 884 break; 885 } 886 case T_FLOAT: { 887 guarantee_property(value_type.is_float(), 888 "Inconsistent constant value type in class file %s", 889 CHECK); 890 break; 891 } 892 case T_DOUBLE: { 893 guarantee_property(value_type.is_double(), 894 "Inconsistent constant value type in class file %s", 895 CHECK); 896 break; 897 } 898 case T_BYTE: 899 case T_CHAR: 900 case T_SHORT: 901 case T_BOOLEAN: 902 case T_INT: { 903 guarantee_property(value_type.is_int(), 904 "Inconsistent constant value type in class file %s", 905 CHECK); 906 break; 907 } 908 case T_OBJECT: { 909 guarantee_property((cp->symbol_at(signature_index)->equals("Ljava/lang/String;") 910 && value_type.is_string()), 911 "Bad string initial value in class file %s", 912 CHECK); 913 break; 914 } 915 default: { 916 classfile_parse_error("Unable to set initial value %u in class file %s", 917 constantvalue_index, 918 THREAD); 919 } 920 } 921 } 922 923 class AnnotationCollector : public ResourceObj{ 924 public: 925 enum Location { _in_field, _in_method, _in_class }; 926 enum ID { 927 _unknown = 0, 928 _method_CallerSensitive, 929 _method_ForceInline, 930 _method_DontInline, 931 _method_ChangesCurrentThread, 932 _method_JvmtiHideEvents, 933 _method_JvmtiMountTransition, 934 _method_InjectedProfile, 935 _method_LambdaForm_Compiled, 936 _method_Hidden, 937 _method_Scoped, 938 _method_IntrinsicCandidate, 939 _jdk_internal_vm_annotation_Contended, 940 _field_Stable, 941 _jdk_internal_vm_annotation_ReservedStackAccess, 942 _jdk_internal_ValueBased, 943 _jdk_internal_ImplicitlyConstructible, 944 _jdk_internal_LooselyConsistentValue, 945 _jdk_internal_NullRestricted, 946 _java_lang_Deprecated, 947 _java_lang_Deprecated_for_removal, 948 _annotation_LIMIT 949 }; 950 const Location _location; 951 int _annotations_present; 952 u2 _contended_group; 953 954 AnnotationCollector(Location location) 955 : _location(location), _annotations_present(0), _contended_group(0) 956 { 957 assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, ""); 958 } 959 // If this annotation name has an ID, report it (or _none). 960 ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name, bool can_access_vm_annotations); 961 // Set the annotation name: 962 void set_annotation(ID id) { 963 assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob"); 964 _annotations_present |= (int)nth_bit((int)id); 965 } 966 967 void remove_annotation(ID id) { 968 assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob"); 969 _annotations_present &= (int)~nth_bit((int)id); 970 } 971 972 // Report if the annotation is present. 973 bool has_any_annotations() const { return _annotations_present != 0; } 974 bool has_annotation(ID id) const { return (nth_bit((int)id) & _annotations_present) != 0; } 975 976 void set_contended_group(u2 group) { _contended_group = group; } 977 u2 contended_group() const { return _contended_group; } 978 979 bool is_contended() const { return has_annotation(_jdk_internal_vm_annotation_Contended); } 980 981 void set_stable(bool stable) { set_annotation(_field_Stable); } 982 bool is_stable() const { return has_annotation(_field_Stable); } 983 }; 984 985 // This class also doubles as a holder for metadata cleanup. 986 class ClassFileParser::FieldAnnotationCollector : public AnnotationCollector { 987 private: 988 ClassLoaderData* _loader_data; 989 AnnotationArray* _field_annotations; 990 AnnotationArray* _field_type_annotations; 991 public: 992 FieldAnnotationCollector(ClassLoaderData* loader_data) : 993 AnnotationCollector(_in_field), 994 _loader_data(loader_data), 995 _field_annotations(nullptr), 996 _field_type_annotations(nullptr) {} 997 ~FieldAnnotationCollector(); 998 void apply_to(FieldInfo* f); 999 AnnotationArray* field_annotations() { return _field_annotations; } 1000 AnnotationArray* field_type_annotations() { return _field_type_annotations; } 1001 1002 void set_field_annotations(AnnotationArray* a) { _field_annotations = a; } 1003 void set_field_type_annotations(AnnotationArray* a) { _field_type_annotations = a; } 1004 }; 1005 1006 class MethodAnnotationCollector : public AnnotationCollector{ 1007 public: 1008 MethodAnnotationCollector() : AnnotationCollector(_in_method) { } 1009 void apply_to(const methodHandle& m); 1010 }; 1011 1012 class ClassFileParser::ClassAnnotationCollector : public AnnotationCollector{ 1013 public: 1014 ClassAnnotationCollector() : AnnotationCollector(_in_class) { } 1015 void apply_to(InstanceKlass* ik); 1016 }; 1017 1018 1019 static int skip_annotation_value(const u1*, int, int); // fwd decl 1020 1021 // Safely increment index by val if does not pass limit 1022 #define SAFE_ADD(index, limit, val) \ 1023 if (index >= limit - val) return limit; \ 1024 index += val; 1025 1026 // Skip an annotation. Return >=limit if there is any problem. 1027 static int skip_annotation(const u1* buffer, int limit, int index) { 1028 assert(buffer != nullptr, "invariant"); 1029 // annotation := atype:u2 do(nmem:u2) {member:u2 value} 1030 // value := switch (tag:u1) { ... } 1031 SAFE_ADD(index, limit, 4); // skip atype and read nmem 1032 int nmem = Bytes::get_Java_u2((address)buffer + index - 2); 1033 while (--nmem >= 0 && index < limit) { 1034 SAFE_ADD(index, limit, 2); // skip member 1035 index = skip_annotation_value(buffer, limit, index); 1036 } 1037 return index; 1038 } 1039 1040 // Skip an annotation value. Return >=limit if there is any problem. 1041 static int skip_annotation_value(const u1* buffer, int limit, int index) { 1042 assert(buffer != nullptr, "invariant"); 1043 1044 // value := switch (tag:u1) { 1045 // case B, C, I, S, Z, D, F, J, c: con:u2; 1046 // case e: e_class:u2 e_name:u2; 1047 // case s: s_con:u2; 1048 // case [: do(nval:u2) {value}; 1049 // case @: annotation; 1050 // case s: s_con:u2; 1051 // } 1052 SAFE_ADD(index, limit, 1); // read tag 1053 const u1 tag = buffer[index - 1]; 1054 switch (tag) { 1055 case 'B': 1056 case 'C': 1057 case 'I': 1058 case 'S': 1059 case 'Z': 1060 case 'D': 1061 case 'F': 1062 case 'J': 1063 case 'c': 1064 case 's': 1065 SAFE_ADD(index, limit, 2); // skip con or s_con 1066 break; 1067 case 'e': 1068 SAFE_ADD(index, limit, 4); // skip e_class, e_name 1069 break; 1070 case '[': 1071 { 1072 SAFE_ADD(index, limit, 2); // read nval 1073 int nval = Bytes::get_Java_u2((address)buffer + index - 2); 1074 while (--nval >= 0 && index < limit) { 1075 index = skip_annotation_value(buffer, limit, index); 1076 } 1077 } 1078 break; 1079 case '@': 1080 index = skip_annotation(buffer, limit, index); 1081 break; 1082 default: 1083 return limit; // bad tag byte 1084 } 1085 return index; 1086 } 1087 1088 // Sift through annotations, looking for those significant to the VM: 1089 static void parse_annotations(const ConstantPool* const cp, 1090 const u1* buffer, int limit, 1091 AnnotationCollector* coll, 1092 ClassLoaderData* loader_data, 1093 const bool can_access_vm_annotations) { 1094 1095 assert(cp != nullptr, "invariant"); 1096 assert(buffer != nullptr, "invariant"); 1097 assert(coll != nullptr, "invariant"); 1098 assert(loader_data != nullptr, "invariant"); 1099 1100 // annotations := do(nann:u2) {annotation} 1101 int index = 2; // read nann 1102 if (index >= limit) return; 1103 int nann = Bytes::get_Java_u2((address)buffer + index - 2); 1104 enum { // initial annotation layout 1105 atype_off = 0, // utf8 such as 'Ljava/lang/annotation/Retention;' 1106 count_off = 2, // u2 such as 1 (one value) 1107 member_off = 4, // utf8 such as 'value' 1108 tag_off = 6, // u1 such as 'c' (type) or 'e' (enum) 1109 e_tag_val = 'e', 1110 e_type_off = 7, // utf8 such as 'Ljava/lang/annotation/RetentionPolicy;' 1111 e_con_off = 9, // utf8 payload, such as 'SOURCE', 'CLASS', 'RUNTIME' 1112 e_size = 11, // end of 'e' annotation 1113 c_tag_val = 'c', // payload is type 1114 c_con_off = 7, // utf8 payload, such as 'I' 1115 c_size = 9, // end of 'c' annotation 1116 s_tag_val = 's', // payload is String 1117 s_con_off = 7, // utf8 payload, such as 'Ljava/lang/String;' 1118 s_size = 9, 1119 b_tag_val = 'Z', // payload is boolean 1120 min_size = 6 // smallest possible size (zero members) 1121 }; 1122 // Cannot add min_size to index in case of overflow MAX_INT 1123 while ((--nann) >= 0 && (index - 2 <= limit - min_size)) { 1124 int index0 = index; 1125 index = skip_annotation(buffer, limit, index); 1126 const u1* const abase = buffer + index0; 1127 const int atype = Bytes::get_Java_u2((address)abase + atype_off); 1128 const int count = Bytes::get_Java_u2((address)abase + count_off); 1129 const Symbol* const aname = check_symbol_at(cp, atype); 1130 if (aname == nullptr) break; // invalid annotation name 1131 const Symbol* member = nullptr; 1132 if (count >= 1) { 1133 const int member_index = Bytes::get_Java_u2((address)abase + member_off); 1134 member = check_symbol_at(cp, member_index); 1135 if (member == nullptr) break; // invalid member name 1136 } 1137 1138 // Here is where parsing particular annotations will take place. 1139 AnnotationCollector::ID id = coll->annotation_index(loader_data, aname, can_access_vm_annotations); 1140 if (AnnotationCollector::_unknown == id) continue; 1141 coll->set_annotation(id); 1142 if (AnnotationCollector::_java_lang_Deprecated == id) { 1143 // @Deprecated can specify forRemoval=true, which we need 1144 // to record for JFR to use. If the annotation is not well-formed 1145 // then we may not be able to determine that. 1146 const u1* offset = abase + member_off; 1147 // There are only 2 members in @Deprecated. 1148 int n_members = MIN2(count, 2); 1149 for (int i = 0; i < n_members; ++i) { 1150 int member_index = Bytes::get_Java_u2((address)offset); 1151 offset += 2; 1152 member = check_symbol_at(cp, member_index); 1153 if (member == vmSymbols::since() && 1154 (*((address)offset) == s_tag_val)) { 1155 // Found `since` first so skip over it 1156 offset += 3; 1157 } 1158 else if (member == vmSymbols::for_removal() && 1159 (*((address)offset) == b_tag_val)) { 1160 const u2 boolean_value_index = Bytes::get_Java_u2((address)offset + 1); 1161 // No guarantee the entry is valid so check it refers to an int in the CP. 1162 if (cp->is_within_bounds(boolean_value_index) && 1163 cp->tag_at(boolean_value_index).is_int() && 1164 cp->int_at(boolean_value_index) == 1) { 1165 // forRemoval == true 1166 coll->set_annotation(AnnotationCollector::_java_lang_Deprecated_for_removal); 1167 } 1168 break; // no need to check further 1169 } 1170 else { 1171 // This @Deprecated annotation is malformed so we don't try to 1172 // determine whether forRemoval is set. 1173 break; 1174 } 1175 } 1176 continue; // proceed to next annotation 1177 } 1178 1179 if (AnnotationCollector::_jdk_internal_vm_annotation_Contended == id) { 1180 // @Contended can optionally specify the contention group. 1181 // 1182 // Contended group defines the equivalence class over the fields: 1183 // the fields within the same contended group are not treated distinct. 1184 // The only exception is default group, which does not incur the 1185 // equivalence. Naturally, contention group for classes is meaningless. 1186 // 1187 // While the contention group is specified as String, annotation 1188 // values are already interned, and we might as well use the constant 1189 // pool index as the group tag. 1190 // 1191 u2 group_index = 0; // default contended group 1192 if (count == 1 1193 && s_size == (index - index0) // match size 1194 && s_tag_val == *(abase + tag_off) 1195 && member == vmSymbols::value_name()) { 1196 group_index = Bytes::get_Java_u2((address)abase + s_con_off); 1197 // No guarantee the group_index is valid so check it refers to a 1198 // symbol in the CP. 1199 if (cp->is_within_bounds(group_index) && 1200 cp->tag_at(group_index).is_utf8()) { 1201 // Seems valid, so check for empty string and reset 1202 if (cp->symbol_at(group_index)->utf8_length() == 0) { 1203 group_index = 0; // default contended group 1204 } 1205 } else { 1206 // Not valid so use the default 1207 group_index = 0; 1208 } 1209 } 1210 coll->set_contended_group(group_index); 1211 continue; // proceed to next annotation 1212 } 1213 } 1214 } 1215 1216 1217 // Parse attributes for a field. 1218 void ClassFileParser::parse_field_attributes(const ClassFileStream* const cfs, 1219 u2 attributes_count, 1220 bool is_static, u2 signature_index, 1221 u2* const constantvalue_index_addr, 1222 bool* const is_synthetic_addr, 1223 u2* const generic_signature_index_addr, 1224 ClassFileParser::FieldAnnotationCollector* parsed_annotations, 1225 TRAPS) { 1226 assert(cfs != nullptr, "invariant"); 1227 assert(constantvalue_index_addr != nullptr, "invariant"); 1228 assert(is_synthetic_addr != nullptr, "invariant"); 1229 assert(generic_signature_index_addr != nullptr, "invariant"); 1230 assert(parsed_annotations != nullptr, "invariant"); 1231 assert(attributes_count > 0, "attributes_count should be greater than 0"); 1232 1233 u2 constantvalue_index = 0; 1234 u2 generic_signature_index = 0; 1235 bool is_synthetic = false; 1236 const u1* runtime_visible_annotations = nullptr; 1237 int runtime_visible_annotations_length = 0; 1238 const u1* runtime_visible_type_annotations = nullptr; 1239 int runtime_visible_type_annotations_length = 0; 1240 bool runtime_invisible_annotations_exists = false; 1241 bool runtime_invisible_type_annotations_exists = false; 1242 const ConstantPool* const cp = _cp; 1243 1244 while (attributes_count--) { 1245 cfs->guarantee_more(6, CHECK); // attribute_name_index, attribute_length 1246 const u2 attribute_name_index = cfs->get_u2_fast(); 1247 const u4 attribute_length = cfs->get_u4_fast(); 1248 guarantee_property(valid_symbol_at(attribute_name_index), 1249 "Invalid field attribute index %u in class file %s", 1250 attribute_name_index, 1251 CHECK); 1252 1253 const Symbol* const attribute_name = cp->symbol_at(attribute_name_index); 1254 if (is_static && attribute_name == vmSymbols::tag_constant_value()) { 1255 // ignore if non-static 1256 if (constantvalue_index != 0) { 1257 classfile_parse_error("Duplicate ConstantValue attribute in class file %s", THREAD); 1258 return; 1259 } 1260 guarantee_property( 1261 attribute_length == 2, 1262 "Invalid ConstantValue field attribute length %u in class file %s", 1263 attribute_length, CHECK); 1264 1265 constantvalue_index = cfs->get_u2(CHECK); 1266 if (_need_verify) { 1267 verify_constantvalue(cp, constantvalue_index, signature_index, CHECK); 1268 } 1269 } else if (attribute_name == vmSymbols::tag_synthetic()) { 1270 if (attribute_length != 0) { 1271 classfile_parse_error( 1272 "Invalid Synthetic field attribute length %u in class file %s", 1273 attribute_length, THREAD); 1274 return; 1275 } 1276 is_synthetic = true; 1277 } else if (attribute_name == vmSymbols::tag_deprecated()) { // 4276120 1278 if (attribute_length != 0) { 1279 classfile_parse_error( 1280 "Invalid Deprecated field attribute length %u in class file %s", 1281 attribute_length, THREAD); 1282 return; 1283 } 1284 } else if (_major_version >= JAVA_1_5_VERSION) { 1285 if (attribute_name == vmSymbols::tag_signature()) { 1286 if (generic_signature_index != 0) { 1287 classfile_parse_error( 1288 "Multiple Signature attributes for field in class file %s", THREAD); 1289 return; 1290 } 1291 if (attribute_length != 2) { 1292 classfile_parse_error( 1293 "Wrong size %u for field's Signature attribute in class file %s", 1294 attribute_length, THREAD); 1295 return; 1296 } 1297 generic_signature_index = parse_generic_signature_attribute(cfs, CHECK); 1298 } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) { 1299 if (runtime_visible_annotations != nullptr) { 1300 classfile_parse_error( 1301 "Multiple RuntimeVisibleAnnotations attributes for field in class file %s", THREAD); 1302 return; 1303 } 1304 runtime_visible_annotations_length = attribute_length; 1305 runtime_visible_annotations = cfs->current(); 1306 assert(runtime_visible_annotations != nullptr, "null visible annotations"); 1307 cfs->guarantee_more(runtime_visible_annotations_length, CHECK); 1308 parse_annotations(cp, 1309 runtime_visible_annotations, 1310 runtime_visible_annotations_length, 1311 parsed_annotations, 1312 _loader_data, 1313 _can_access_vm_annotations); 1314 cfs->skip_u1_fast(runtime_visible_annotations_length); 1315 } else if (attribute_name == vmSymbols::tag_runtime_invisible_annotations()) { 1316 if (runtime_invisible_annotations_exists) { 1317 classfile_parse_error( 1318 "Multiple RuntimeInvisibleAnnotations attributes for field in class file %s", THREAD); 1319 return; 1320 } 1321 runtime_invisible_annotations_exists = true; 1322 cfs->skip_u1(attribute_length, CHECK); 1323 } else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) { 1324 if (runtime_visible_type_annotations != nullptr) { 1325 classfile_parse_error( 1326 "Multiple RuntimeVisibleTypeAnnotations attributes for field in class file %s", THREAD); 1327 return; 1328 } 1329 runtime_visible_type_annotations_length = attribute_length; 1330 runtime_visible_type_annotations = cfs->current(); 1331 assert(runtime_visible_type_annotations != nullptr, "null visible type annotations"); 1332 cfs->skip_u1(runtime_visible_type_annotations_length, CHECK); 1333 } else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) { 1334 if (runtime_invisible_type_annotations_exists) { 1335 classfile_parse_error( 1336 "Multiple RuntimeInvisibleTypeAnnotations attributes for field in class file %s", THREAD); 1337 return; 1338 } else { 1339 runtime_invisible_type_annotations_exists = true; 1340 } 1341 cfs->skip_u1(attribute_length, CHECK); 1342 } else { 1343 cfs->skip_u1(attribute_length, CHECK); // Skip unknown attributes 1344 } 1345 } else { 1346 cfs->skip_u1(attribute_length, CHECK); // Skip unknown attributes 1347 } 1348 } 1349 1350 *constantvalue_index_addr = constantvalue_index; 1351 *is_synthetic_addr = is_synthetic; 1352 *generic_signature_index_addr = generic_signature_index; 1353 AnnotationArray* a = allocate_annotations(runtime_visible_annotations, 1354 runtime_visible_annotations_length, 1355 CHECK); 1356 parsed_annotations->set_field_annotations(a); 1357 a = allocate_annotations(runtime_visible_type_annotations, 1358 runtime_visible_type_annotations_length, 1359 CHECK); 1360 parsed_annotations->set_field_type_annotations(a); 1361 return; 1362 } 1363 1364 1365 // Side-effects: populates the _fields, _fields_annotations, 1366 // _fields_type_annotations fields 1367 void ClassFileParser::parse_fields(const ClassFileStream* const cfs, 1368 AccessFlags class_access_flags, 1369 ConstantPool* cp, 1370 const int cp_size, 1371 u2* const java_fields_count_ptr, 1372 TRAPS) { 1373 1374 assert(cfs != nullptr, "invariant"); 1375 assert(cp != nullptr, "invariant"); 1376 assert(java_fields_count_ptr != nullptr, "invariant"); 1377 1378 assert(nullptr == _fields_annotations, "invariant"); 1379 assert(nullptr == _fields_type_annotations, "invariant"); 1380 1381 bool is_inline_type = !class_access_flags.is_identity_class() && !class_access_flags.is_abstract(); 1382 cfs->guarantee_more(2, CHECK); // length 1383 const u2 length = cfs->get_u2_fast(); 1384 *java_fields_count_ptr = length; 1385 1386 int num_injected = 0; 1387 const InjectedField* const injected = JavaClasses::get_injected(_class_name, 1388 &num_injected); 1389 1390 // two more slots are required for inline classes: 1391 // one for the static field with a reference to the pre-allocated default value 1392 // one for the field the JVM injects when detecting an empty inline class 1393 const int total_fields = length + num_injected + (is_inline_type ? 2 : 0); 1394 1395 // Allocate a temporary resource array to collect field data. 1396 // After parsing all fields, data are stored in a UNSIGNED5 compressed stream. 1397 _temp_field_info = new GrowableArray<FieldInfo>(total_fields); 1398 1399 int instance_fields_count = 0; 1400 ResourceMark rm(THREAD); 1401 for (int n = 0; n < length; n++) { 1402 // access_flags, name_index, descriptor_index, attributes_count 1403 cfs->guarantee_more(8, CHECK); 1404 1405 jint recognized_modifiers = JVM_RECOGNIZED_FIELD_MODIFIERS; 1406 if (!supports_inline_types()) { 1407 recognized_modifiers &= ~JVM_ACC_STRICT; 1408 } 1409 1410 const jint flags = cfs->get_u2_fast() & recognized_modifiers; 1411 verify_legal_field_modifiers(flags, class_access_flags, CHECK); 1412 AccessFlags access_flags; 1413 access_flags.set_flags(flags); 1414 FieldInfo::FieldFlags fieldFlags(0); 1415 1416 const u2 name_index = cfs->get_u2_fast(); 1417 guarantee_property(valid_symbol_at(name_index), 1418 "Invalid constant pool index %u for field name in class file %s", 1419 name_index, CHECK); 1420 const Symbol* const name = cp->symbol_at(name_index); 1421 verify_legal_field_name(name, CHECK); 1422 1423 const u2 signature_index = cfs->get_u2_fast(); 1424 guarantee_property(valid_symbol_at(signature_index), 1425 "Invalid constant pool index %u for field signature in class file %s", 1426 signature_index, CHECK); 1427 const Symbol* const sig = cp->symbol_at(signature_index); 1428 verify_legal_field_signature(name, sig, CHECK); 1429 if (!access_flags.is_static()) instance_fields_count++; 1430 1431 u2 constantvalue_index = 0; 1432 bool is_synthetic = false; 1433 u2 generic_signature_index = 0; 1434 const bool is_static = access_flags.is_static(); 1435 FieldAnnotationCollector parsed_annotations(_loader_data); 1436 1437 bool is_null_restricted = false; 1438 1439 const u2 attributes_count = cfs->get_u2_fast(); 1440 if (attributes_count > 0) { 1441 parse_field_attributes(cfs, 1442 attributes_count, 1443 is_static, 1444 signature_index, 1445 &constantvalue_index, 1446 &is_synthetic, 1447 &generic_signature_index, 1448 &parsed_annotations, 1449 CHECK); 1450 1451 if (parsed_annotations.field_annotations() != nullptr) { 1452 if (_fields_annotations == nullptr) { 1453 _fields_annotations = MetadataFactory::new_array<AnnotationArray*>( 1454 _loader_data, length, nullptr, 1455 CHECK); 1456 } 1457 _fields_annotations->at_put(n, parsed_annotations.field_annotations()); 1458 if (parsed_annotations.has_annotation(AnnotationCollector::_jdk_internal_NullRestricted)) { 1459 if (!Signature::has_envelope(sig)) { 1460 Exceptions::fthrow( 1461 THREAD_AND_LOCATION, 1462 vmSymbols::java_lang_ClassFormatError(), 1463 "Illegal use of @jdk.internal.vm.annotation.NullRestricted annotation on field %s with signature %s (primitive types can never be null)", 1464 name->as_C_string(), sig->as_C_string()); 1465 } 1466 is_null_restricted = true; 1467 } 1468 parsed_annotations.set_field_annotations(nullptr); 1469 } 1470 if (parsed_annotations.field_type_annotations() != nullptr) { 1471 if (_fields_type_annotations == nullptr) { 1472 _fields_type_annotations = 1473 MetadataFactory::new_array<AnnotationArray*>(_loader_data, 1474 length, 1475 nullptr, 1476 CHECK); 1477 } 1478 _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations()); 1479 parsed_annotations.set_field_type_annotations(nullptr); 1480 } 1481 1482 if (is_synthetic) { 1483 access_flags.set_is_synthetic(); 1484 } 1485 if (generic_signature_index != 0) { 1486 fieldFlags.update_generic(true); 1487 } 1488 } 1489 1490 if (is_null_restricted) { 1491 fieldFlags.update_null_free_inline_type(true); 1492 } 1493 1494 const BasicType type = cp->basic_type_for_signature_at(signature_index); 1495 1496 // Update number of static oop fields. 1497 if (is_static && is_reference_type(type)) { 1498 _static_oop_count++; 1499 } 1500 1501 FieldInfo fi(access_flags, name_index, signature_index, constantvalue_index, fieldFlags); 1502 fi.set_index(n); 1503 if (fieldFlags.is_generic()) { 1504 fi.set_generic_signature_index(generic_signature_index); 1505 } 1506 parsed_annotations.apply_to(&fi); 1507 if (fi.field_flags().is_contended()) { 1508 _has_contended_fields = true; 1509 } 1510 _temp_field_info->append(fi); 1511 } 1512 assert(_temp_field_info->length() == length, "Must be"); 1513 1514 if (num_injected != 0) { 1515 for (int n = 0; n < num_injected; n++) { 1516 // Check for duplicates 1517 if (injected[n].may_be_java) { 1518 const Symbol* const name = injected[n].name(); 1519 const Symbol* const signature = injected[n].signature(); 1520 bool duplicate = false; 1521 for (int i = 0; i < length; i++) { 1522 const FieldInfo* const f = _temp_field_info->adr_at(i); 1523 if (name == cp->symbol_at(f->name_index()) && 1524 signature == cp->symbol_at(f->signature_index())) { 1525 // Symbol is desclared in Java so skip this one 1526 duplicate = true; 1527 break; 1528 } 1529 } 1530 if (duplicate) { 1531 // These will be removed from the field array at the end 1532 continue; 1533 } 1534 } 1535 1536 // Injected field 1537 FieldInfo::FieldFlags fflags(0); 1538 fflags.update_injected(true); 1539 AccessFlags aflags; 1540 FieldInfo fi(aflags, (u2)(injected[n].name_index), (u2)(injected[n].signature_index), 0, fflags); 1541 int idx = _temp_field_info->append(fi); 1542 _temp_field_info->adr_at(idx)->set_index(idx); 1543 } 1544 } 1545 1546 if (is_inline_type) { 1547 // Inject static ".default" field 1548 FieldInfo::FieldFlags fflags(0); 1549 fflags.update_injected(true); 1550 AccessFlags aflags(JVM_ACC_STATIC); 1551 FieldInfo fi(aflags, 1552 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(default_value_name)), 1553 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)), 1554 0, 1555 fflags); 1556 int idx = _temp_field_info->append(fi); 1557 _temp_field_info->adr_at(idx)->set_index(idx); 1558 _static_oop_count++; 1559 // Inject static ".null_reset" field. This is the same as the .default field but will never have its null-channel set to non-zero. 1560 FieldInfo::FieldFlags fflags2(0); 1561 fflags2.update_injected(true); 1562 AccessFlags aflags2(JVM_ACC_STATIC); 1563 FieldInfo fi2(aflags2, 1564 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(null_reset_value_name)), 1565 (u2)vmSymbols::as_int(VM_SYMBOL_ENUM_NAME(object_signature)), 1566 0, 1567 fflags2); 1568 int idx2 = _temp_field_info->append(fi2); 1569 _temp_field_info->adr_at(idx2)->set_index(idx2); 1570 _static_oop_count++; 1571 } 1572 1573 if (_need_verify && length > 1) { 1574 // Check duplicated fields 1575 ResourceMark rm(THREAD); 1576 // Set containing name-signature pairs 1577 NameSigHashtable* names_and_sigs = new NameSigHashtable(); 1578 for (int i = 0; i < _temp_field_info->length(); i++) { 1579 NameSigHash name_and_sig(_temp_field_info->adr_at(i)->name(_cp), 1580 _temp_field_info->adr_at(i)->signature(_cp)); 1581 // If no duplicates, add name/signature in hashtable names_and_sigs. 1582 if(!names_and_sigs->put(name_and_sig, 0)) { 1583 classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s", 1584 name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD); 1585 return; 1586 } 1587 } 1588 } 1589 } 1590 1591 1592 const ClassFileParser::unsafe_u2* ClassFileParser::parse_exception_table(const ClassFileStream* const cfs, 1593 u4 code_length, 1594 u4 exception_table_length, 1595 TRAPS) { 1596 assert(cfs != nullptr, "invariant"); 1597 1598 const unsafe_u2* const exception_table_start = cfs->current(); 1599 assert(exception_table_start != nullptr, "null exception table"); 1600 1601 cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc, 1602 // end_pc, 1603 // handler_pc, 1604 // catch_type_index 1605 1606 // Will check legal target after parsing code array in verifier. 1607 if (_need_verify) { 1608 for (unsigned int i = 0; i < exception_table_length; i++) { 1609 const u2 start_pc = cfs->get_u2_fast(); 1610 const u2 end_pc = cfs->get_u2_fast(); 1611 const u2 handler_pc = cfs->get_u2_fast(); 1612 const u2 catch_type_index = cfs->get_u2_fast(); 1613 guarantee_property((start_pc < end_pc) && (end_pc <= code_length), 1614 "Illegal exception table range in class file %s", 1615 CHECK_NULL); 1616 guarantee_property(handler_pc < code_length, 1617 "Illegal exception table handler in class file %s", 1618 CHECK_NULL); 1619 if (catch_type_index != 0) { 1620 guarantee_property(valid_klass_reference_at(catch_type_index), 1621 "Catch type in exception table has bad constant type in class file %s", CHECK_NULL); 1622 } 1623 } 1624 } else { 1625 cfs->skip_u2_fast(exception_table_length * 4); 1626 } 1627 return exception_table_start; 1628 } 1629 1630 void ClassFileParser::parse_linenumber_table(u4 code_attribute_length, 1631 u4 code_length, 1632 CompressedLineNumberWriteStream**const write_stream, 1633 TRAPS) { 1634 1635 const ClassFileStream* const cfs = _stream; 1636 unsigned int num_entries = cfs->get_u2(CHECK); 1637 1638 // Each entry is a u2 start_pc, and a u2 line_number 1639 const unsigned int length_in_bytes = num_entries * (sizeof(u2) * 2); 1640 1641 // Verify line number attribute and table length 1642 guarantee_property( 1643 code_attribute_length == sizeof(u2) + length_in_bytes, 1644 "LineNumberTable attribute has wrong length in class file %s", CHECK); 1645 1646 cfs->guarantee_more(length_in_bytes, CHECK); 1647 1648 if ((*write_stream) == nullptr) { 1649 if (length_in_bytes > fixed_buffer_size) { 1650 (*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes); 1651 } else { 1652 (*write_stream) = new CompressedLineNumberWriteStream( 1653 _linenumbertable_buffer, fixed_buffer_size); 1654 } 1655 } 1656 1657 while (num_entries-- > 0) { 1658 const u2 bci = cfs->get_u2_fast(); // start_pc 1659 const u2 line = cfs->get_u2_fast(); // line_number 1660 guarantee_property(bci < code_length, 1661 "Invalid pc in LineNumberTable in class file %s", CHECK); 1662 (*write_stream)->write_pair(bci, line); 1663 } 1664 } 1665 1666 1667 class LVT_Hash : public AllStatic { 1668 public: 1669 1670 static bool equals(LocalVariableTableElement const& e0, LocalVariableTableElement const& e1) { 1671 /* 1672 * 3-tuple start_bci/length/slot has to be unique key, 1673 * so the following comparison seems to be redundant: 1674 * && elem->name_cp_index == entry->_elem->name_cp_index 1675 */ 1676 return (e0.start_bci == e1.start_bci && 1677 e0.length == e1.length && 1678 e0.name_cp_index == e1.name_cp_index && 1679 e0.slot == e1.slot); 1680 } 1681 1682 static unsigned int hash(LocalVariableTableElement const& e0) { 1683 unsigned int raw_hash = e0.start_bci; 1684 1685 raw_hash = e0.length + raw_hash * 37; 1686 raw_hash = e0.name_cp_index + raw_hash * 37; 1687 raw_hash = e0.slot + raw_hash * 37; 1688 1689 return raw_hash; 1690 } 1691 }; 1692 1693 1694 // Class file LocalVariableTable elements. 1695 class Classfile_LVT_Element { 1696 public: 1697 u2 start_bci; 1698 u2 length; 1699 u2 name_cp_index; 1700 u2 descriptor_cp_index; 1701 u2 slot; 1702 }; 1703 1704 static void copy_lvt_element(const Classfile_LVT_Element* const src, 1705 LocalVariableTableElement* const lvt) { 1706 lvt->start_bci = Bytes::get_Java_u2((u1*) &src->start_bci); 1707 lvt->length = Bytes::get_Java_u2((u1*) &src->length); 1708 lvt->name_cp_index = Bytes::get_Java_u2((u1*) &src->name_cp_index); 1709 lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index); 1710 lvt->signature_cp_index = 0; 1711 lvt->slot = Bytes::get_Java_u2((u1*) &src->slot); 1712 } 1713 1714 // Function is used to parse both attributes: 1715 // LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT) 1716 const ClassFileParser::unsafe_u2* ClassFileParser::parse_localvariable_table(const ClassFileStream* cfs, 1717 u4 code_length, 1718 u2 max_locals, 1719 u4 code_attribute_length, 1720 u2* const localvariable_table_length, 1721 bool isLVTT, 1722 TRAPS) { 1723 const char* const tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable"; 1724 *localvariable_table_length = cfs->get_u2(CHECK_NULL); 1725 const unsigned int size = checked_cast<unsigned>( 1726 (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2)); 1727 1728 const ConstantPool* const cp = _cp; 1729 1730 // Verify local variable table attribute has right length 1731 if (_need_verify) { 1732 guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)), 1733 "%s has wrong length in class file %s", tbl_name, CHECK_NULL); 1734 } 1735 1736 const unsafe_u2* const localvariable_table_start = cfs->current(); 1737 assert(localvariable_table_start != nullptr, "null local variable table"); 1738 if (!_need_verify) { 1739 cfs->skip_u2_fast(size); 1740 } else { 1741 cfs->guarantee_more(size * 2, CHECK_NULL); 1742 for(int i = 0; i < (*localvariable_table_length); i++) { 1743 const u2 start_pc = cfs->get_u2_fast(); 1744 const u2 length = cfs->get_u2_fast(); 1745 const u2 name_index = cfs->get_u2_fast(); 1746 const u2 descriptor_index = cfs->get_u2_fast(); 1747 const u2 index = cfs->get_u2_fast(); 1748 // Assign to a u4 to avoid overflow 1749 const u4 end_pc = (u4)start_pc + (u4)length; 1750 1751 if (start_pc >= code_length) { 1752 classfile_parse_error( 1753 "Invalid start_pc %u in %s in class file %s", 1754 start_pc, tbl_name, THREAD); 1755 return nullptr; 1756 } 1757 if (end_pc > code_length) { 1758 classfile_parse_error( 1759 "Invalid length %u in %s in class file %s", 1760 length, tbl_name, THREAD); 1761 return nullptr; 1762 } 1763 const int cp_size = cp->length(); 1764 guarantee_property(valid_symbol_at(name_index), 1765 "Name index %u in %s has bad constant type in class file %s", 1766 name_index, tbl_name, CHECK_NULL); 1767 guarantee_property(valid_symbol_at(descriptor_index), 1768 "Signature index %u in %s has bad constant type in class file %s", 1769 descriptor_index, tbl_name, CHECK_NULL); 1770 1771 const Symbol* const name = cp->symbol_at(name_index); 1772 const Symbol* const sig = cp->symbol_at(descriptor_index); 1773 verify_legal_field_name(name, CHECK_NULL); 1774 u2 extra_slot = 0; 1775 if (!isLVTT) { 1776 verify_legal_field_signature(name, sig, CHECK_NULL); 1777 1778 // 4894874: check special cases for double and long local variables 1779 if (sig == vmSymbols::type_signature(T_DOUBLE) || 1780 sig == vmSymbols::type_signature(T_LONG)) { 1781 extra_slot = 1; 1782 } 1783 } 1784 guarantee_property((index + extra_slot) < max_locals, 1785 "Invalid index %u in %s in class file %s", 1786 index, tbl_name, CHECK_NULL); 1787 } 1788 } 1789 return localvariable_table_start; 1790 } 1791 1792 static const u1* parse_stackmap_table(const ClassFileStream* const cfs, 1793 u4 code_attribute_length, 1794 TRAPS) { 1795 assert(cfs != nullptr, "invariant"); 1796 1797 if (0 == code_attribute_length) { 1798 return nullptr; 1799 } 1800 1801 const u1* const stackmap_table_start = cfs->current(); 1802 assert(stackmap_table_start != nullptr, "null stackmap table"); 1803 1804 // check code_attribute_length 1805 cfs->skip_u1(code_attribute_length, CHECK_NULL); 1806 1807 return stackmap_table_start; 1808 } 1809 1810 const ClassFileParser::unsafe_u2* ClassFileParser::parse_checked_exceptions(const ClassFileStream* const cfs, 1811 u2* const checked_exceptions_length, 1812 u4 method_attribute_length, 1813 TRAPS) { 1814 assert(cfs != nullptr, "invariant"); 1815 assert(checked_exceptions_length != nullptr, "invariant"); 1816 1817 cfs->guarantee_more(2, CHECK_NULL); // checked_exceptions_length 1818 *checked_exceptions_length = cfs->get_u2_fast(); 1819 const unsigned int size = 1820 (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2); 1821 const unsafe_u2* const checked_exceptions_start = cfs->current(); 1822 assert(checked_exceptions_start != nullptr, "null checked exceptions"); 1823 if (!_need_verify) { 1824 cfs->skip_u2_fast(size); 1825 } else { 1826 // Verify each value in the checked exception table 1827 u2 checked_exception; 1828 const u2 len = *checked_exceptions_length; 1829 cfs->guarantee_more(2 * len, CHECK_NULL); 1830 for (int i = 0; i < len; i++) { 1831 checked_exception = cfs->get_u2_fast(); 1832 guarantee_property( 1833 valid_klass_reference_at(checked_exception), 1834 "Exception name has bad type at constant pool %u in class file %s", 1835 checked_exception, CHECK_NULL); 1836 } 1837 } 1838 // check exceptions attribute length 1839 if (_need_verify) { 1840 guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) + 1841 sizeof(u2) * size), 1842 "Exceptions attribute has wrong length in class file %s", CHECK_NULL); 1843 } 1844 return checked_exceptions_start; 1845 } 1846 1847 void ClassFileParser::throwIllegalSignature(const char* type, 1848 const Symbol* name, 1849 const Symbol* sig, 1850 TRAPS) const { 1851 assert(name != nullptr, "invariant"); 1852 assert(sig != nullptr, "invariant"); 1853 1854 ResourceMark rm(THREAD); 1855 // Names are all known to be < 64k so we know this formatted message is not excessively large. 1856 Exceptions::fthrow(THREAD_AND_LOCATION, 1857 vmSymbols::java_lang_ClassFormatError(), 1858 "%s \"%s\" in class %s has illegal signature \"%s\"", type, 1859 name->as_C_string(), _class_name->as_C_string(), sig->as_C_string()); 1860 } 1861 1862 AnnotationCollector::ID 1863 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data, 1864 const Symbol* name, 1865 const bool can_access_vm_annotations) { 1866 const vmSymbolID sid = vmSymbols::find_sid(name); 1867 // Privileged code can use all annotations. Other code silently drops some. 1868 const bool privileged = loader_data->is_boot_class_loader_data() || 1869 loader_data->is_platform_class_loader_data() || 1870 can_access_vm_annotations; 1871 switch (sid) { 1872 case VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): { 1873 if (_location != _in_method) break; // only allow for methods 1874 if (!privileged) break; // only allow in privileged code 1875 return _method_CallerSensitive; 1876 } 1877 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): { 1878 if (_location != _in_method) break; // only allow for methods 1879 if (!privileged) break; // only allow in privileged code 1880 return _method_ForceInline; 1881 } 1882 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_DontInline_signature): { 1883 if (_location != _in_method) break; // only allow for methods 1884 if (!privileged) break; // only allow in privileged code 1885 return _method_DontInline; 1886 } 1887 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ChangesCurrentThread_signature): { 1888 if (_location != _in_method) break; // only allow for methods 1889 if (!privileged) break; // only allow in privileged code 1890 return _method_ChangesCurrentThread; 1891 } 1892 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_JvmtiHideEvents_signature): { 1893 if (_location != _in_method) break; // only allow for methods 1894 if (!privileged) break; // only allow in privileged code 1895 return _method_JvmtiHideEvents; 1896 } 1897 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_JvmtiMountTransition_signature): { 1898 if (_location != _in_method) break; // only allow for methods 1899 if (!privileged) break; // only allow in privileged code 1900 return _method_JvmtiMountTransition; 1901 } 1902 case VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature): { 1903 if (_location != _in_method) break; // only allow for methods 1904 if (!privileged) break; // only allow in privileged code 1905 return _method_InjectedProfile; 1906 } 1907 case VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature): { 1908 if (_location != _in_method) break; // only allow for methods 1909 if (!privileged) break; // only allow in privileged code 1910 return _method_LambdaForm_Compiled; 1911 } 1912 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Hidden_signature): { 1913 if (_location != _in_method) break; // only allow for methods 1914 if (!privileged) break; // only allow in privileged code 1915 return _method_Hidden; 1916 } 1917 case VM_SYMBOL_ENUM_NAME(jdk_internal_misc_Scoped_signature): { 1918 if (_location != _in_method) break; // only allow for methods 1919 if (!privileged) break; // only allow in privileged code 1920 return _method_Scoped; 1921 } 1922 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_IntrinsicCandidate_signature): { 1923 if (_location != _in_method) break; // only allow for methods 1924 if (!privileged) break; // only allow in privileged code 1925 return _method_IntrinsicCandidate; 1926 } 1927 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Stable_signature): { 1928 if (_location != _in_field) break; // only allow for fields 1929 if (!privileged) break; // only allow in privileged code 1930 return _field_Stable; 1931 } 1932 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): { 1933 if (_location != _in_field && _location != _in_class) { 1934 break; // only allow for fields and classes 1935 } 1936 if (!EnableContended || (RestrictContended && !privileged)) { 1937 break; // honor privileges 1938 } 1939 return _jdk_internal_vm_annotation_Contended; 1940 } 1941 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): { 1942 if (_location != _in_method) break; // only allow for methods 1943 if (RestrictReservedStack && !privileged) break; // honor privileges 1944 return _jdk_internal_vm_annotation_ReservedStackAccess; 1945 } 1946 case VM_SYMBOL_ENUM_NAME(jdk_internal_ValueBased_signature): { 1947 if (_location != _in_class) break; // only allow for classes 1948 if (!privileged) break; // only allow in privileged code 1949 return _jdk_internal_ValueBased; 1950 } 1951 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ImplicitlyConstructible_signature): { 1952 if (_location != _in_class) break; // only allow for classes 1953 return _jdk_internal_ImplicitlyConstructible; 1954 } 1955 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_LooselyConsistentValue_signature): { 1956 if (_location != _in_class) break; // only allow for classes 1957 return _jdk_internal_LooselyConsistentValue; 1958 } 1959 case VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_NullRestricted_signature): { 1960 if (_location != _in_field) break; // only allow for fields 1961 return _jdk_internal_NullRestricted; 1962 } 1963 case VM_SYMBOL_ENUM_NAME(java_lang_Deprecated): { 1964 return _java_lang_Deprecated; 1965 } 1966 default: { 1967 break; 1968 } 1969 } 1970 return AnnotationCollector::_unknown; 1971 } 1972 1973 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) { 1974 if (is_contended()) 1975 // Setting the contended group also sets the contended bit in field flags 1976 f->set_contended_group(contended_group()); 1977 if (is_stable()) 1978 (f->field_flags_addr())->update_stable(true); 1979 } 1980 1981 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() { 1982 // If there's an error deallocate metadata for field annotations 1983 MetadataFactory::free_array<u1>(_loader_data, _field_annotations); 1984 MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations); 1985 } 1986 1987 void MethodAnnotationCollector::apply_to(const methodHandle& m) { 1988 if (has_annotation(_method_CallerSensitive)) 1989 m->set_caller_sensitive(); 1990 if (has_annotation(_method_ForceInline)) 1991 m->set_force_inline(); 1992 if (has_annotation(_method_DontInline)) 1993 m->set_dont_inline(); 1994 if (has_annotation(_method_ChangesCurrentThread)) 1995 m->set_changes_current_thread(); 1996 if (has_annotation(_method_JvmtiHideEvents)) 1997 m->set_jvmti_hide_events(); 1998 if (has_annotation(_method_JvmtiMountTransition)) 1999 m->set_jvmti_mount_transition(); 2000 if (has_annotation(_method_InjectedProfile)) 2001 m->set_has_injected_profile(); 2002 if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none) 2003 m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm); 2004 if (has_annotation(_method_Hidden)) 2005 m->set_is_hidden(); 2006 if (has_annotation(_method_Scoped)) 2007 m->set_scoped(); 2008 if (has_annotation(_method_IntrinsicCandidate) && !m->is_synthetic()) 2009 m->set_intrinsic_candidate(); 2010 if (has_annotation(_jdk_internal_vm_annotation_ReservedStackAccess)) 2011 m->set_has_reserved_stack_access(); 2012 if (has_annotation(_java_lang_Deprecated)) 2013 m->set_deprecated(); 2014 if (has_annotation(_java_lang_Deprecated_for_removal)) 2015 m->set_deprecated_for_removal(); 2016 } 2017 2018 void ClassFileParser::ClassAnnotationCollector::apply_to(InstanceKlass* ik) { 2019 assert(ik != nullptr, "invariant"); 2020 if (has_annotation(_jdk_internal_vm_annotation_Contended)) { 2021 ik->set_is_contended(is_contended()); 2022 } 2023 if (has_annotation(_jdk_internal_ValueBased)) { 2024 ik->set_has_value_based_class_annotation(); 2025 if (DiagnoseSyncOnValueBasedClasses) { 2026 ik->set_is_value_based(); 2027 } 2028 } 2029 if (has_annotation(_java_lang_Deprecated)) { 2030 Array<Method*>* methods = ik->methods(); 2031 int length = ik->methods()->length(); 2032 for (int i = 0; i < length; i++) { 2033 Method* m = methods->at(i); 2034 m->set_deprecated(); 2035 } 2036 } 2037 if (has_annotation(_java_lang_Deprecated_for_removal)) { 2038 Array<Method*>* methods = ik->methods(); 2039 int length = ik->methods()->length(); 2040 for (int i = 0; i < length; i++) { 2041 Method* m = methods->at(i); 2042 m->set_deprecated_for_removal(); 2043 } 2044 } 2045 } 2046 2047 #define MAX_ARGS_SIZE 255 2048 #define MAX_CODE_SIZE 65535 2049 #define INITIAL_MAX_LVT_NUMBER 256 2050 2051 /* Copy class file LVT's/LVTT's into the HotSpot internal LVT. 2052 * 2053 * Rules for LVT's and LVTT's are: 2054 * - There can be any number of LVT's and LVTT's. 2055 * - If there are n LVT's, it is the same as if there was just 2056 * one LVT containing all the entries from the n LVT's. 2057 * - There may be no more than one LVT entry per local variable. 2058 * Two LVT entries are 'equal' if these fields are the same: 2059 * start_pc, length, name, slot 2060 * - There may be no more than one LVTT entry per each LVT entry. 2061 * Each LVTT entry has to match some LVT entry. 2062 * - HotSpot internal LVT keeps natural ordering of class file LVT entries. 2063 */ 2064 void ClassFileParser::copy_localvariable_table(const ConstMethod* cm, 2065 int lvt_cnt, 2066 u2* const localvariable_table_length, 2067 const unsafe_u2** const localvariable_table_start, 2068 int lvtt_cnt, 2069 u2* const localvariable_type_table_length, 2070 const unsafe_u2** const localvariable_type_table_start, 2071 TRAPS) { 2072 2073 ResourceMark rm(THREAD); 2074 2075 typedef ResourceHashtable<LocalVariableTableElement, LocalVariableTableElement*, 2076 256, AnyObj::RESOURCE_AREA, mtInternal, 2077 &LVT_Hash::hash, &LVT_Hash::equals> LVT_HashTable; 2078 2079 LVT_HashTable* const table = new LVT_HashTable(); 2080 2081 // To fill LocalVariableTable in 2082 const Classfile_LVT_Element* cf_lvt; 2083 LocalVariableTableElement* lvt = cm->localvariable_table_start(); 2084 2085 for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) { 2086 cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no]; 2087 for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) { 2088 copy_lvt_element(&cf_lvt[idx], lvt); 2089 // If no duplicates, add LVT elem in hashtable. 2090 if (table->put(*lvt, lvt) == false 2091 && _need_verify 2092 && _major_version >= JAVA_1_5_VERSION) { 2093 classfile_parse_error("Duplicated LocalVariableTable attribute " 2094 "entry for '%s' in class file %s", 2095 _cp->symbol_at(lvt->name_cp_index)->as_utf8(), 2096 THREAD); 2097 return; 2098 } 2099 } 2100 } 2101 2102 // To merge LocalVariableTable and LocalVariableTypeTable 2103 const Classfile_LVT_Element* cf_lvtt; 2104 LocalVariableTableElement lvtt_elem; 2105 2106 for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) { 2107 cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no]; 2108 for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) { 2109 copy_lvt_element(&cf_lvtt[idx], &lvtt_elem); 2110 LocalVariableTableElement** entry = table->get(lvtt_elem); 2111 if (entry == nullptr) { 2112 if (_need_verify) { 2113 classfile_parse_error("LVTT entry for '%s' in class file %s " 2114 "does not match any LVT entry", 2115 _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(), 2116 THREAD); 2117 return; 2118 } 2119 } else if ((*entry)->signature_cp_index != 0 && _need_verify) { 2120 classfile_parse_error("Duplicated LocalVariableTypeTable attribute " 2121 "entry for '%s' in class file %s", 2122 _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(), 2123 THREAD); 2124 return; 2125 } else { 2126 // to add generic signatures into LocalVariableTable 2127 (*entry)->signature_cp_index = lvtt_elem.descriptor_cp_index; 2128 } 2129 } 2130 } 2131 } 2132 2133 2134 void ClassFileParser::copy_method_annotations(ConstMethod* cm, 2135 const u1* runtime_visible_annotations, 2136 int runtime_visible_annotations_length, 2137 const u1* runtime_visible_parameter_annotations, 2138 int runtime_visible_parameter_annotations_length, 2139 const u1* runtime_visible_type_annotations, 2140 int runtime_visible_type_annotations_length, 2141 const u1* annotation_default, 2142 int annotation_default_length, 2143 TRAPS) { 2144 2145 AnnotationArray* a; 2146 2147 if (runtime_visible_annotations_length > 0) { 2148 a = allocate_annotations(runtime_visible_annotations, 2149 runtime_visible_annotations_length, 2150 CHECK); 2151 cm->set_method_annotations(a); 2152 } 2153 2154 if (runtime_visible_parameter_annotations_length > 0) { 2155 a = allocate_annotations(runtime_visible_parameter_annotations, 2156 runtime_visible_parameter_annotations_length, 2157 CHECK); 2158 cm->set_parameter_annotations(a); 2159 } 2160 2161 if (annotation_default_length > 0) { 2162 a = allocate_annotations(annotation_default, 2163 annotation_default_length, 2164 CHECK); 2165 cm->set_default_annotations(a); 2166 } 2167 2168 if (runtime_visible_type_annotations_length > 0) { 2169 a = allocate_annotations(runtime_visible_type_annotations, 2170 runtime_visible_type_annotations_length, 2171 CHECK); 2172 cm->set_type_annotations(a); 2173 } 2174 } 2175 2176 2177 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions 2178 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the 2179 // Method* to save footprint, so we only know the size of the resulting Method* when the 2180 // entire method attribute is parsed. 2181 // 2182 // The has_localvariable_table parameter is used to pass up the value to InstanceKlass. 2183 2184 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs, 2185 bool is_interface, 2186 bool is_value_class, 2187 bool is_abstract_class, 2188 const ConstantPool* cp, 2189 bool* const has_localvariable_table, 2190 TRAPS) { 2191 assert(cfs != nullptr, "invariant"); 2192 assert(cp != nullptr, "invariant"); 2193 assert(has_localvariable_table != nullptr, "invariant"); 2194 2195 ResourceMark rm(THREAD); 2196 // Parse fixed parts: 2197 // access_flags, name_index, descriptor_index, attributes_count 2198 cfs->guarantee_more(8, CHECK_NULL); 2199 2200 u2 flags = cfs->get_u2_fast(); 2201 const u2 name_index = cfs->get_u2_fast(); 2202 const int cp_size = cp->length(); 2203 guarantee_property( 2204 valid_symbol_at(name_index), 2205 "Illegal constant pool index %u for method name in class file %s", 2206 name_index, CHECK_NULL); 2207 const Symbol* const name = cp->symbol_at(name_index); 2208 verify_legal_method_name(name, CHECK_NULL); 2209 2210 const u2 signature_index = cfs->get_u2_fast(); 2211 guarantee_property( 2212 valid_symbol_at(signature_index), 2213 "Illegal constant pool index %u for method signature in class file %s", 2214 signature_index, CHECK_NULL); 2215 const Symbol* const signature = cp->symbol_at(signature_index); 2216 2217 if (name == vmSymbols::class_initializer_name()) { 2218 // We ignore the other access flags for a valid class initializer. 2219 // (JVM Spec 2nd ed., chapter 4.6) 2220 if (_major_version < 51) { // backward compatibility 2221 flags = JVM_ACC_STATIC; 2222 } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) { 2223 flags &= JVM_ACC_STATIC | (_major_version <= JAVA_16_VERSION ? JVM_ACC_STRICT : 0); 2224 } else { 2225 classfile_parse_error("Method <clinit> is not static in class file %s", THREAD); 2226 return nullptr; 2227 } 2228 } else { 2229 verify_legal_method_modifiers(flags, access_flags() , name, CHECK_NULL); 2230 } 2231 2232 if (name == vmSymbols::object_initializer_name() && is_interface) { 2233 classfile_parse_error("Interface cannot have a method named <init>, class file %s", THREAD); 2234 return nullptr; 2235 } 2236 2237 if (EnableValhalla) { 2238 if (((flags & JVM_ACC_SYNCHRONIZED) == JVM_ACC_SYNCHRONIZED) 2239 && ((flags & JVM_ACC_STATIC) == 0 ) 2240 && !_access_flags.is_identity_class()) { 2241 classfile_parse_error("Invalid synchronized method in non-identity class %s", THREAD); 2242 return nullptr; 2243 } 2244 } 2245 2246 int args_size = -1; // only used when _need_verify is true 2247 if (_need_verify) { 2248 verify_legal_name_with_signature(name, signature, CHECK_NULL); 2249 args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) + 2250 verify_legal_method_signature(name, signature, CHECK_NULL); 2251 if (args_size > MAX_ARGS_SIZE) { 2252 classfile_parse_error("Too many arguments in method signature in class file %s", THREAD); 2253 return nullptr; 2254 } 2255 } 2256 2257 AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS); 2258 2259 // Default values for code and exceptions attribute elements 2260 u2 max_stack = 0; 2261 u2 max_locals = 0; 2262 u4 code_length = 0; 2263 const u1* code_start = nullptr; 2264 u2 exception_table_length = 0; 2265 const unsafe_u2* exception_table_start = nullptr; // (potentially unaligned) pointer to array of u2 elements 2266 Array<int>* exception_handlers = Universe::the_empty_int_array(); 2267 u2 checked_exceptions_length = 0; 2268 const unsafe_u2* checked_exceptions_start = nullptr; // (potentially unaligned) pointer to array of u2 elements 2269 CompressedLineNumberWriteStream* linenumber_table = nullptr; 2270 int linenumber_table_length = 0; 2271 int total_lvt_length = 0; 2272 u2 lvt_cnt = 0; 2273 u2 lvtt_cnt = 0; 2274 bool lvt_allocated = false; 2275 u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER; 2276 u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER; 2277 u2* localvariable_table_length = nullptr; 2278 const unsafe_u2** localvariable_table_start = nullptr; // (potentially unaligned) pointer to array of LVT attributes 2279 u2* localvariable_type_table_length = nullptr; 2280 const unsafe_u2** localvariable_type_table_start = nullptr; // (potentially unaligned) pointer to LVTT attributes 2281 int method_parameters_length = -1; 2282 const u1* method_parameters_data = nullptr; 2283 bool method_parameters_seen = false; 2284 bool parsed_code_attribute = false; 2285 bool parsed_checked_exceptions_attribute = false; 2286 bool parsed_stackmap_attribute = false; 2287 // stackmap attribute - JDK1.5 2288 const u1* stackmap_data = nullptr; 2289 int stackmap_data_length = 0; 2290 u2 generic_signature_index = 0; 2291 MethodAnnotationCollector parsed_annotations; 2292 const u1* runtime_visible_annotations = nullptr; 2293 int runtime_visible_annotations_length = 0; 2294 const u1* runtime_visible_parameter_annotations = nullptr; 2295 int runtime_visible_parameter_annotations_length = 0; 2296 const u1* runtime_visible_type_annotations = nullptr; 2297 int runtime_visible_type_annotations_length = 0; 2298 bool runtime_invisible_annotations_exists = false; 2299 bool runtime_invisible_type_annotations_exists = false; 2300 bool runtime_invisible_parameter_annotations_exists = false; 2301 const u1* annotation_default = nullptr; 2302 int annotation_default_length = 0; 2303 2304 // Parse code and exceptions attribute 2305 u2 method_attributes_count = cfs->get_u2_fast(); 2306 while (method_attributes_count--) { 2307 cfs->guarantee_more(6, CHECK_NULL); // method_attribute_name_index, method_attribute_length 2308 const u2 method_attribute_name_index = cfs->get_u2_fast(); 2309 const u4 method_attribute_length = cfs->get_u4_fast(); 2310 guarantee_property( 2311 valid_symbol_at(method_attribute_name_index), 2312 "Invalid method attribute name index %u in class file %s", 2313 method_attribute_name_index, CHECK_NULL); 2314 2315 const Symbol* const method_attribute_name = cp->symbol_at(method_attribute_name_index); 2316 if (method_attribute_name == vmSymbols::tag_code()) { 2317 // Parse Code attribute 2318 if (_need_verify) { 2319 guarantee_property( 2320 !access_flags.is_native() && !access_flags.is_abstract(), 2321 "Code attribute in native or abstract methods in class file %s", 2322 CHECK_NULL); 2323 } 2324 if (parsed_code_attribute) { 2325 classfile_parse_error("Multiple Code attributes in class file %s", 2326 THREAD); 2327 return nullptr; 2328 } 2329 parsed_code_attribute = true; 2330 2331 // Stack size, locals size, and code size 2332 cfs->guarantee_more(8, CHECK_NULL); 2333 max_stack = cfs->get_u2_fast(); 2334 max_locals = cfs->get_u2_fast(); 2335 code_length = cfs->get_u4_fast(); 2336 if (_need_verify) { 2337 guarantee_property(args_size <= max_locals, 2338 "Arguments can't fit into locals in class file %s", 2339 CHECK_NULL); 2340 guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE, 2341 "Invalid method Code length %u in class file %s", 2342 code_length, CHECK_NULL); 2343 } 2344 // Code pointer 2345 code_start = cfs->current(); 2346 assert(code_start != nullptr, "null code start"); 2347 cfs->guarantee_more(code_length, CHECK_NULL); 2348 cfs->skip_u1_fast(code_length); 2349 2350 // Exception handler table 2351 cfs->guarantee_more(2, CHECK_NULL); // exception_table_length 2352 exception_table_length = cfs->get_u2_fast(); 2353 if (exception_table_length > 0) { 2354 exception_table_start = parse_exception_table(cfs, 2355 code_length, 2356 exception_table_length, 2357 CHECK_NULL); 2358 } 2359 2360 // Parse additional attributes in code attribute 2361 cfs->guarantee_more(2, CHECK_NULL); // code_attributes_count 2362 u2 code_attributes_count = cfs->get_u2_fast(); 2363 2364 unsigned int calculated_attribute_length = 0; 2365 2366 calculated_attribute_length = 2367 sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length); 2368 calculated_attribute_length += checked_cast<unsigned int>( 2369 code_length + 2370 sizeof(exception_table_length) + 2371 sizeof(code_attributes_count) + 2372 exception_table_length * 2373 ( sizeof(u2) + // start_pc 2374 sizeof(u2) + // end_pc 2375 sizeof(u2) + // handler_pc 2376 sizeof(u2) )); // catch_type_index 2377 2378 while (code_attributes_count--) { 2379 cfs->guarantee_more(6, CHECK_NULL); // code_attribute_name_index, code_attribute_length 2380 const u2 code_attribute_name_index = cfs->get_u2_fast(); 2381 const u4 code_attribute_length = cfs->get_u4_fast(); 2382 calculated_attribute_length += code_attribute_length + 2383 (unsigned)sizeof(code_attribute_name_index) + 2384 (unsigned)sizeof(code_attribute_length); 2385 guarantee_property(valid_symbol_at(code_attribute_name_index), 2386 "Invalid code attribute name index %u in class file %s", 2387 code_attribute_name_index, 2388 CHECK_NULL); 2389 if (LoadLineNumberTables && 2390 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) { 2391 // Parse and compress line number table 2392 parse_linenumber_table(code_attribute_length, 2393 code_length, 2394 &linenumber_table, 2395 CHECK_NULL); 2396 2397 } else if (LoadLocalVariableTables && 2398 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) { 2399 // Parse local variable table 2400 if (!lvt_allocated) { 2401 localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD( 2402 THREAD, u2, INITIAL_MAX_LVT_NUMBER); 2403 localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD( 2404 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER); 2405 localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD( 2406 THREAD, u2, INITIAL_MAX_LVT_NUMBER); 2407 localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD( 2408 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER); 2409 lvt_allocated = true; 2410 } 2411 if (lvt_cnt == max_lvt_cnt) { 2412 max_lvt_cnt <<= 1; 2413 localvariable_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt); 2414 localvariable_table_start = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt); 2415 } 2416 localvariable_table_start[lvt_cnt] = 2417 parse_localvariable_table(cfs, 2418 code_length, 2419 max_locals, 2420 code_attribute_length, 2421 &localvariable_table_length[lvt_cnt], 2422 false, // is not LVTT 2423 CHECK_NULL); 2424 total_lvt_length += localvariable_table_length[lvt_cnt]; 2425 lvt_cnt++; 2426 } else if (LoadLocalVariableTypeTables && 2427 _major_version >= JAVA_1_5_VERSION && 2428 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) { 2429 if (!lvt_allocated) { 2430 localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD( 2431 THREAD, u2, INITIAL_MAX_LVT_NUMBER); 2432 localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD( 2433 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER); 2434 localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD( 2435 THREAD, u2, INITIAL_MAX_LVT_NUMBER); 2436 localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD( 2437 THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER); 2438 lvt_allocated = true; 2439 } 2440 // Parse local variable type table 2441 if (lvtt_cnt == max_lvtt_cnt) { 2442 max_lvtt_cnt <<= 1; 2443 localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt); 2444 localvariable_type_table_start = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt); 2445 } 2446 localvariable_type_table_start[lvtt_cnt] = 2447 parse_localvariable_table(cfs, 2448 code_length, 2449 max_locals, 2450 code_attribute_length, 2451 &localvariable_type_table_length[lvtt_cnt], 2452 true, // is LVTT 2453 CHECK_NULL); 2454 lvtt_cnt++; 2455 } else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION && 2456 cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) { 2457 // Stack map is only needed by the new verifier in JDK1.5. 2458 if (parsed_stackmap_attribute) { 2459 classfile_parse_error("Multiple StackMapTable attributes in class file %s", THREAD); 2460 return nullptr; 2461 } 2462 stackmap_data = parse_stackmap_table(cfs, code_attribute_length, CHECK_NULL); 2463 stackmap_data_length = code_attribute_length; 2464 parsed_stackmap_attribute = true; 2465 } else { 2466 // Skip unknown attributes 2467 cfs->skip_u1(code_attribute_length, CHECK_NULL); 2468 } 2469 } 2470 // check method attribute length 2471 if (_need_verify) { 2472 guarantee_property(method_attribute_length == calculated_attribute_length, 2473 "Code segment has wrong length in class file %s", 2474 CHECK_NULL); 2475 } 2476 } else if (method_attribute_name == vmSymbols::tag_exceptions()) { 2477 // Parse Exceptions attribute 2478 if (parsed_checked_exceptions_attribute) { 2479 classfile_parse_error("Multiple Exceptions attributes in class file %s", 2480 THREAD); 2481 return nullptr; 2482 } 2483 parsed_checked_exceptions_attribute = true; 2484 checked_exceptions_start = 2485 parse_checked_exceptions(cfs, 2486 &checked_exceptions_length, 2487 method_attribute_length, 2488 CHECK_NULL); 2489 } else if (method_attribute_name == vmSymbols::tag_method_parameters()) { 2490 // reject multiple method parameters 2491 if (method_parameters_seen) { 2492 classfile_parse_error("Multiple MethodParameters attributes in class file %s", 2493 THREAD); 2494 return nullptr; 2495 } 2496 method_parameters_seen = true; 2497 method_parameters_length = cfs->get_u1_fast(); 2498 const u4 real_length = (method_parameters_length * 4u) + 1u; 2499 if (method_attribute_length != real_length) { 2500 classfile_parse_error( 2501 "Invalid MethodParameters method attribute length %u in class file", 2502 method_attribute_length, THREAD); 2503 return nullptr; 2504 } 2505 method_parameters_data = cfs->current(); 2506 cfs->skip_u2_fast(method_parameters_length); 2507 cfs->skip_u2_fast(method_parameters_length); 2508 // ignore this attribute if it cannot be reflected 2509 if (!vmClasses::Parameter_klass_loaded()) 2510 method_parameters_length = -1; 2511 } else if (method_attribute_name == vmSymbols::tag_synthetic()) { 2512 if (method_attribute_length != 0) { 2513 classfile_parse_error( 2514 "Invalid Synthetic method attribute length %u in class file %s", 2515 method_attribute_length, THREAD); 2516 return nullptr; 2517 } 2518 // Should we check that there hasn't already been a synthetic attribute? 2519 access_flags.set_is_synthetic(); 2520 } else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120 2521 if (method_attribute_length != 0) { 2522 classfile_parse_error( 2523 "Invalid Deprecated method attribute length %u in class file %s", 2524 method_attribute_length, THREAD); 2525 return nullptr; 2526 } 2527 } else if (_major_version >= JAVA_1_5_VERSION) { 2528 if (method_attribute_name == vmSymbols::tag_signature()) { 2529 if (generic_signature_index != 0) { 2530 classfile_parse_error( 2531 "Multiple Signature attributes for method in class file %s", 2532 THREAD); 2533 return nullptr; 2534 } 2535 if (method_attribute_length != 2) { 2536 classfile_parse_error( 2537 "Invalid Signature attribute length %u in class file %s", 2538 method_attribute_length, THREAD); 2539 return nullptr; 2540 } 2541 generic_signature_index = parse_generic_signature_attribute(cfs, CHECK_NULL); 2542 } else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) { 2543 if (runtime_visible_annotations != nullptr) { 2544 classfile_parse_error( 2545 "Multiple RuntimeVisibleAnnotations attributes for method in class file %s", 2546 THREAD); 2547 return nullptr; 2548 } 2549 runtime_visible_annotations_length = method_attribute_length; 2550 runtime_visible_annotations = cfs->current(); 2551 assert(runtime_visible_annotations != nullptr, "null visible annotations"); 2552 cfs->guarantee_more(runtime_visible_annotations_length, CHECK_NULL); 2553 parse_annotations(cp, 2554 runtime_visible_annotations, 2555 runtime_visible_annotations_length, 2556 &parsed_annotations, 2557 _loader_data, 2558 _can_access_vm_annotations); 2559 cfs->skip_u1_fast(runtime_visible_annotations_length); 2560 } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) { 2561 if (runtime_invisible_annotations_exists) { 2562 classfile_parse_error( 2563 "Multiple RuntimeInvisibleAnnotations attributes for method in class file %s", 2564 THREAD); 2565 return nullptr; 2566 } 2567 runtime_invisible_annotations_exists = true; 2568 cfs->skip_u1(method_attribute_length, CHECK_NULL); 2569 } else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) { 2570 if (runtime_visible_parameter_annotations != nullptr) { 2571 classfile_parse_error( 2572 "Multiple RuntimeVisibleParameterAnnotations attributes for method in class file %s", 2573 THREAD); 2574 return nullptr; 2575 } 2576 runtime_visible_parameter_annotations_length = method_attribute_length; 2577 runtime_visible_parameter_annotations = cfs->current(); 2578 assert(runtime_visible_parameter_annotations != nullptr, "null visible parameter annotations"); 2579 cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_NULL); 2580 } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) { 2581 if (runtime_invisible_parameter_annotations_exists) { 2582 classfile_parse_error( 2583 "Multiple RuntimeInvisibleParameterAnnotations attributes for method in class file %s", 2584 THREAD); 2585 return nullptr; 2586 } 2587 runtime_invisible_parameter_annotations_exists = true; 2588 cfs->skip_u1(method_attribute_length, CHECK_NULL); 2589 } else if (method_attribute_name == vmSymbols::tag_annotation_default()) { 2590 if (annotation_default != nullptr) { 2591 classfile_parse_error( 2592 "Multiple AnnotationDefault attributes for method in class file %s", 2593 THREAD); 2594 return nullptr; 2595 } 2596 annotation_default_length = method_attribute_length; 2597 annotation_default = cfs->current(); 2598 assert(annotation_default != nullptr, "null annotation default"); 2599 cfs->skip_u1(annotation_default_length, CHECK_NULL); 2600 } else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) { 2601 if (runtime_visible_type_annotations != nullptr) { 2602 classfile_parse_error( 2603 "Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s", 2604 THREAD); 2605 return nullptr; 2606 } 2607 runtime_visible_type_annotations_length = method_attribute_length; 2608 runtime_visible_type_annotations = cfs->current(); 2609 assert(runtime_visible_type_annotations != nullptr, "null visible type annotations"); 2610 // No need for the VM to parse Type annotations 2611 cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_NULL); 2612 } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) { 2613 if (runtime_invisible_type_annotations_exists) { 2614 classfile_parse_error( 2615 "Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s", 2616 THREAD); 2617 return nullptr; 2618 } 2619 runtime_invisible_type_annotations_exists = true; 2620 cfs->skip_u1(method_attribute_length, CHECK_NULL); 2621 } else { 2622 // Skip unknown attributes 2623 cfs->skip_u1(method_attribute_length, CHECK_NULL); 2624 } 2625 } else { 2626 // Skip unknown attributes 2627 cfs->skip_u1(method_attribute_length, CHECK_NULL); 2628 } 2629 } 2630 2631 if (linenumber_table != nullptr) { 2632 linenumber_table->write_terminator(); 2633 linenumber_table_length = linenumber_table->position(); 2634 } 2635 2636 // Make sure there's at least one Code attribute in non-native/non-abstract method 2637 if (_need_verify) { 2638 guarantee_property(access_flags.is_native() || 2639 access_flags.is_abstract() || 2640 parsed_code_attribute, 2641 "Absent Code attribute in method that is not native or abstract in class file %s", 2642 CHECK_NULL); 2643 } 2644 2645 // All sizing information for a Method* is finally available, now create it 2646 InlineTableSizes sizes( 2647 total_lvt_length, 2648 linenumber_table_length, 2649 exception_table_length, 2650 checked_exceptions_length, 2651 method_parameters_length, 2652 generic_signature_index, 2653 runtime_visible_annotations_length, 2654 runtime_visible_parameter_annotations_length, 2655 runtime_visible_type_annotations_length, 2656 annotation_default_length, 2657 0); 2658 2659 Method* const m = Method::allocate(_loader_data, 2660 code_length, 2661 access_flags, 2662 &sizes, 2663 ConstMethod::NORMAL, 2664 _cp->symbol_at(name_index), 2665 CHECK_NULL); 2666 2667 ClassLoadingService::add_class_method_size(m->size()*wordSize); 2668 2669 // Fill in information from fixed part (access_flags already set) 2670 m->set_constants(_cp); 2671 m->set_name_index(name_index); 2672 m->set_signature_index(signature_index); 2673 m->constMethod()->compute_from_signature(cp->symbol_at(signature_index), access_flags.is_static()); 2674 assert(args_size < 0 || args_size == m->size_of_parameters(), ""); 2675 2676 // Fill in code attribute information 2677 m->set_max_stack(max_stack); 2678 m->set_max_locals(max_locals); 2679 if (stackmap_data != nullptr) { 2680 m->constMethod()->copy_stackmap_data(_loader_data, 2681 (u1*)stackmap_data, 2682 stackmap_data_length, 2683 CHECK_NULL); 2684 } 2685 2686 // Copy byte codes 2687 m->set_code((u1*)code_start); 2688 2689 // Copy line number table 2690 if (linenumber_table != nullptr) { 2691 memcpy(m->compressed_linenumber_table(), 2692 linenumber_table->buffer(), 2693 linenumber_table_length); 2694 } 2695 2696 // Copy exception table 2697 if (exception_table_length > 0) { 2698 Copy::conjoint_swap_if_needed<Endian::JAVA>(exception_table_start, 2699 m->exception_table_start(), 2700 exception_table_length * sizeof(ExceptionTableElement), 2701 sizeof(u2)); 2702 } 2703 2704 // Copy method parameters 2705 if (method_parameters_length > 0) { 2706 MethodParametersElement* elem = m->constMethod()->method_parameters_start(); 2707 for (int i = 0; i < method_parameters_length; i++) { 2708 elem[i].name_cp_index = Bytes::get_Java_u2((address)method_parameters_data); 2709 method_parameters_data += 2; 2710 elem[i].flags = Bytes::get_Java_u2((address)method_parameters_data); 2711 method_parameters_data += 2; 2712 } 2713 } 2714 2715 // Copy checked exceptions 2716 if (checked_exceptions_length > 0) { 2717 Copy::conjoint_swap_if_needed<Endian::JAVA>(checked_exceptions_start, 2718 m->checked_exceptions_start(), 2719 checked_exceptions_length * sizeof(CheckedExceptionElement), 2720 sizeof(u2)); 2721 } 2722 2723 // Copy class file LVT's/LVTT's into the HotSpot internal LVT. 2724 if (total_lvt_length > 0) { 2725 *has_localvariable_table = true; 2726 copy_localvariable_table(m->constMethod(), 2727 lvt_cnt, 2728 localvariable_table_length, 2729 localvariable_table_start, 2730 lvtt_cnt, 2731 localvariable_type_table_length, 2732 localvariable_type_table_start, 2733 CHECK_NULL); 2734 } 2735 2736 if (parsed_annotations.has_any_annotations()) 2737 parsed_annotations.apply_to(methodHandle(THREAD, m)); 2738 2739 if (is_hidden()) { // Mark methods in hidden classes as 'hidden'. 2740 m->set_is_hidden(); 2741 } 2742 2743 // Copy annotations 2744 copy_method_annotations(m->constMethod(), 2745 runtime_visible_annotations, 2746 runtime_visible_annotations_length, 2747 runtime_visible_parameter_annotations, 2748 runtime_visible_parameter_annotations_length, 2749 runtime_visible_type_annotations, 2750 runtime_visible_type_annotations_length, 2751 annotation_default, 2752 annotation_default_length, 2753 CHECK_NULL); 2754 2755 if (InstanceKlass::is_finalization_enabled() && 2756 name == vmSymbols::finalize_method_name() && 2757 signature == vmSymbols::void_method_signature()) { 2758 if (m->is_empty_method()) { 2759 _has_empty_finalizer = true; 2760 } else { 2761 _has_finalizer = true; 2762 } 2763 } 2764 2765 NOT_PRODUCT(m->verify()); 2766 return m; 2767 } 2768 2769 2770 // Side-effects: populates the _methods field in the parser 2771 void ClassFileParser::parse_methods(const ClassFileStream* const cfs, 2772 bool is_interface, 2773 bool is_value_class, 2774 bool is_abstract_type, 2775 bool* const has_localvariable_table, 2776 bool* has_final_method, 2777 bool* declares_nonstatic_concrete_methods, 2778 TRAPS) { 2779 assert(cfs != nullptr, "invariant"); 2780 assert(has_localvariable_table != nullptr, "invariant"); 2781 assert(has_final_method != nullptr, "invariant"); 2782 assert(declares_nonstatic_concrete_methods != nullptr, "invariant"); 2783 2784 assert(nullptr == _methods, "invariant"); 2785 2786 cfs->guarantee_more(2, CHECK); // length 2787 const u2 length = cfs->get_u2_fast(); 2788 if (length == 0) { 2789 _methods = Universe::the_empty_method_array(); 2790 } else { 2791 _methods = MetadataFactory::new_array<Method*>(_loader_data, 2792 length, 2793 nullptr, 2794 CHECK); 2795 2796 for (int index = 0; index < length; index++) { 2797 Method* method = parse_method(cfs, 2798 is_interface, 2799 is_value_class, 2800 is_abstract_type, 2801 _cp, 2802 has_localvariable_table, 2803 CHECK); 2804 2805 if (method->is_final()) { 2806 *has_final_method = true; 2807 } 2808 // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags 2809 // used for interface initialization, and default method inheritance analysis 2810 if (is_interface && !(*declares_nonstatic_concrete_methods) 2811 && !method->is_abstract() && !method->is_static()) { 2812 *declares_nonstatic_concrete_methods = true; 2813 } 2814 _methods->at_put(index, method); 2815 } 2816 2817 if (_need_verify && length > 1) { 2818 // Check duplicated methods 2819 ResourceMark rm(THREAD); 2820 // Set containing name-signature pairs 2821 NameSigHashtable* names_and_sigs = new NameSigHashtable(); 2822 for (int i = 0; i < length; i++) { 2823 const Method* const m = _methods->at(i); 2824 NameSigHash name_and_sig(m->name(), m->signature()); 2825 // If no duplicates, add name/signature in hashtable names_and_sigs. 2826 if(!names_and_sigs->put(name_and_sig, 0)) { 2827 classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s", 2828 name_and_sig._name->as_C_string(), name_and_sig._sig->as_klass_external_name(), THREAD); 2829 return; 2830 } 2831 } 2832 } 2833 } 2834 } 2835 2836 static const intArray* sort_methods(Array<Method*>* methods) { 2837 const int length = methods->length(); 2838 // If JVMTI original method ordering or sharing is enabled we have to 2839 // remember the original class file ordering. 2840 // We temporarily use the vtable_index field in the Method* to store the 2841 // class file index, so we can read in after calling qsort. 2842 // Put the method ordering in the shared archive. 2843 if (JvmtiExport::can_maintain_original_method_order() || CDSConfig::is_dumping_archive()) { 2844 for (int index = 0; index < length; index++) { 2845 Method* const m = methods->at(index); 2846 assert(!m->valid_vtable_index(), "vtable index should not be set"); 2847 m->set_vtable_index(index); 2848 } 2849 } 2850 // Sort method array by ascending method name (for faster lookups & vtable construction) 2851 // Note that the ordering is not alphabetical, see Symbol::fast_compare 2852 Method::sort_methods(methods); 2853 2854 intArray* method_ordering = nullptr; 2855 // If JVMTI original method ordering or sharing is enabled construct int 2856 // array remembering the original ordering 2857 if (JvmtiExport::can_maintain_original_method_order() || CDSConfig::is_dumping_archive()) { 2858 method_ordering = new intArray(length, length, -1); 2859 for (int index = 0; index < length; index++) { 2860 Method* const m = methods->at(index); 2861 const int old_index = m->vtable_index(); 2862 assert(old_index >= 0 && old_index < length, "invalid method index"); 2863 method_ordering->at_put(index, old_index); 2864 m->set_vtable_index(Method::invalid_vtable_index); 2865 } 2866 } 2867 return method_ordering; 2868 } 2869 2870 // Parse generic_signature attribute for methods and fields 2871 u2 ClassFileParser::parse_generic_signature_attribute(const ClassFileStream* const cfs, 2872 TRAPS) { 2873 assert(cfs != nullptr, "invariant"); 2874 2875 cfs->guarantee_more(2, CHECK_0); // generic_signature_index 2876 const u2 generic_signature_index = cfs->get_u2_fast(); 2877 guarantee_property( 2878 valid_symbol_at(generic_signature_index), 2879 "Invalid Signature attribute at constant pool index %u in class file %s", 2880 generic_signature_index, CHECK_0); 2881 return generic_signature_index; 2882 } 2883 2884 void ClassFileParser::parse_classfile_sourcefile_attribute(const ClassFileStream* const cfs, 2885 TRAPS) { 2886 2887 assert(cfs != nullptr, "invariant"); 2888 2889 cfs->guarantee_more(2, CHECK); // sourcefile_index 2890 const u2 sourcefile_index = cfs->get_u2_fast(); 2891 guarantee_property( 2892 valid_symbol_at(sourcefile_index), 2893 "Invalid SourceFile attribute at constant pool index %u in class file %s", 2894 sourcefile_index, CHECK); 2895 set_class_sourcefile_index(sourcefile_index); 2896 } 2897 2898 void ClassFileParser::parse_classfile_source_debug_extension_attribute(const ClassFileStream* const cfs, 2899 int length, 2900 TRAPS) { 2901 assert(cfs != nullptr, "invariant"); 2902 2903 const u1* const sde_buffer = cfs->current(); 2904 assert(sde_buffer != nullptr, "null sde buffer"); 2905 2906 // Don't bother storing it if there is no way to retrieve it 2907 if (JvmtiExport::can_get_source_debug_extension()) { 2908 assert((length+1) > length, "Overflow checking"); 2909 u1* const sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1); 2910 for (int i = 0; i < length; i++) { 2911 sde[i] = sde_buffer[i]; 2912 } 2913 sde[length] = '\0'; 2914 set_class_sde_buffer((const char*)sde, length); 2915 } 2916 // Got utf8 string, set stream position forward 2917 cfs->skip_u1(length, CHECK); 2918 } 2919 2920 2921 // Inner classes can be static, private or protected (classic VM does this) 2922 #define RECOGNIZED_INNER_CLASS_MODIFIERS ( JVM_RECOGNIZED_CLASS_MODIFIERS | \ 2923 JVM_ACC_PRIVATE | \ 2924 JVM_ACC_PROTECTED | \ 2925 JVM_ACC_STATIC \ 2926 ) 2927 2928 // Find index of the InnerClasses entry for the specified inner_class_info_index. 2929 // Return -1 if none is found. 2930 static int inner_classes_find_index(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) { 2931 Symbol* cp_klass_name = cp->klass_name_at(inner); 2932 for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) { 2933 int idx_inner = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset); 2934 if (cp->klass_name_at(idx_inner) == cp_klass_name) { 2935 return idx; 2936 } 2937 } 2938 return -1; 2939 } 2940 2941 // Return the outer_class_info_index for the InnerClasses entry containing the 2942 // specified inner_class_info_index. Return -1 if no InnerClasses entry is found. 2943 static int inner_classes_jump_to_outer(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) { 2944 if (inner == 0) return -1; 2945 int idx = inner_classes_find_index(inner_classes, inner, cp, length); 2946 if (idx == -1) return -1; 2947 int result = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset); 2948 return result; 2949 } 2950 2951 // Return true if circularity is found, false if no circularity is found. 2952 // Use Floyd's cycle finding algorithm. 2953 static bool inner_classes_check_loop_through_outer(const Array<u2>* inner_classes, int idx, const ConstantPool* cp, int length) { 2954 int slow = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset); 2955 int fast = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset); 2956 2957 while (fast != -1 && fast != 0) { 2958 if (slow != 0 && (cp->klass_name_at(slow) == cp->klass_name_at(fast))) { 2959 return true; // found a circularity 2960 } 2961 fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length); 2962 if (fast == -1) return false; 2963 fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length); 2964 if (fast == -1) return false; 2965 slow = inner_classes_jump_to_outer(inner_classes, slow, cp, length); 2966 assert(slow != -1, "sanity check"); 2967 } 2968 return false; 2969 } 2970 2971 // Loop through each InnerClasses entry checking for circularities and duplications 2972 // with other entries. If duplicate entries are found then throw CFE. Otherwise, 2973 // return true if a circularity or entries with duplicate inner_class_info_indexes 2974 // are found. 2975 bool ClassFileParser::check_inner_classes_circularity(const ConstantPool* cp, int length, TRAPS) { 2976 // Loop through each InnerClasses entry. 2977 for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) { 2978 // Return true if there are circular entries. 2979 if (inner_classes_check_loop_through_outer(_inner_classes, idx, cp, length)) { 2980 return true; 2981 } 2982 // Check if there are duplicate entries or entries with the same inner_class_info_index. 2983 for (int y = idx + InstanceKlass::inner_class_next_offset; y < length; 2984 y += InstanceKlass::inner_class_next_offset) { 2985 2986 // 4347400: make sure there's no duplicate entry in the classes array 2987 if (_major_version >= JAVA_1_5_VERSION) { 2988 guarantee_property((_inner_classes->at(idx) != _inner_classes->at(y) || 2989 _inner_classes->at(idx+1) != _inner_classes->at(y+1) || 2990 _inner_classes->at(idx+2) != _inner_classes->at(y+2) || 2991 _inner_classes->at(idx+3) != _inner_classes->at(y+3)), 2992 "Duplicate entry in InnerClasses attribute in class file %s", 2993 CHECK_(true)); 2994 } 2995 // Return true if there are two entries with the same inner_class_info_index. 2996 if (_inner_classes->at(y) == _inner_classes->at(idx)) { 2997 return true; 2998 } 2999 } 3000 } 3001 return false; 3002 } 3003 3004 // Return number of classes in the inner classes attribute table 3005 u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs, 3006 const ConstantPool* cp, 3007 const u1* const inner_classes_attribute_start, 3008 bool parsed_enclosingmethod_attribute, 3009 u2 enclosing_method_class_index, 3010 u2 enclosing_method_method_index, 3011 TRAPS) { 3012 const u1* const current_mark = cfs->current(); 3013 u2 length = 0; 3014 if (inner_classes_attribute_start != nullptr) { 3015 cfs->set_current(inner_classes_attribute_start); 3016 cfs->guarantee_more(2, CHECK_0); // length 3017 length = cfs->get_u2_fast(); 3018 } 3019 3020 // 4-tuples of shorts of inner classes data and 2 shorts of enclosing 3021 // method data: 3022 // [inner_class_info_index, 3023 // outer_class_info_index, 3024 // inner_name_index, 3025 // inner_class_access_flags, 3026 // ... 3027 // enclosing_method_class_index, 3028 // enclosing_method_method_index] 3029 const int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0); 3030 Array<u2>* inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0); 3031 _inner_classes = inner_classes; 3032 3033 int index = 0; 3034 cfs->guarantee_more(8 * length, CHECK_0); // 4-tuples of u2 3035 for (int n = 0; n < length; n++) { 3036 // Inner class index 3037 const u2 inner_class_info_index = cfs->get_u2_fast(); 3038 guarantee_property( 3039 valid_klass_reference_at(inner_class_info_index), 3040 "inner_class_info_index %u has bad constant type in class file %s", 3041 inner_class_info_index, CHECK_0); 3042 // Outer class index 3043 const u2 outer_class_info_index = cfs->get_u2_fast(); 3044 guarantee_property( 3045 outer_class_info_index == 0 || 3046 valid_klass_reference_at(outer_class_info_index), 3047 "outer_class_info_index %u has bad constant type in class file %s", 3048 outer_class_info_index, CHECK_0); 3049 3050 if (outer_class_info_index != 0) { 3051 const Symbol* const outer_class_name = cp->klass_name_at(outer_class_info_index); 3052 char* bytes = (char*)outer_class_name->bytes(); 3053 guarantee_property(bytes[0] != JVM_SIGNATURE_ARRAY, 3054 "Outer class is an array class in class file %s", CHECK_0); 3055 } 3056 // Inner class name 3057 const u2 inner_name_index = cfs->get_u2_fast(); 3058 guarantee_property( 3059 inner_name_index == 0 || valid_symbol_at(inner_name_index), 3060 "inner_name_index %u has bad constant type in class file %s", 3061 inner_name_index, CHECK_0); 3062 if (_need_verify) { 3063 guarantee_property(inner_class_info_index != outer_class_info_index, 3064 "Class is both outer and inner class in class file %s", CHECK_0); 3065 } 3066 3067 u2 recognized_modifiers = RECOGNIZED_INNER_CLASS_MODIFIERS; 3068 // JVM_ACC_MODULE is defined in JDK-9 and later. 3069 if (_major_version >= JAVA_9_VERSION) { 3070 recognized_modifiers |= JVM_ACC_MODULE; 3071 } 3072 3073 // Access flags 3074 u2 flags = cfs->get_u2_fast() & recognized_modifiers; 3075 3076 if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) { 3077 // Set abstract bit for old class files for backward compatibility 3078 flags |= JVM_ACC_ABSTRACT; 3079 } 3080 3081 if (!supports_inline_types()) { 3082 const bool is_module = (flags & JVM_ACC_MODULE) != 0; 3083 const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0; 3084 if (!is_module && !is_interface) { 3085 flags |= JVM_ACC_IDENTITY; 3086 } 3087 } 3088 3089 const char* name = inner_name_index == 0 ? "unnamed" : cp->symbol_at(inner_name_index)->as_utf8(); 3090 verify_legal_class_modifiers(flags, name, false, CHECK_0); 3091 AccessFlags inner_access_flags(flags); 3092 3093 inner_classes->at_put(index++, inner_class_info_index); 3094 inner_classes->at_put(index++, outer_class_info_index); 3095 inner_classes->at_put(index++, inner_name_index); 3096 inner_classes->at_put(index++, inner_access_flags.as_unsigned_short()); 3097 } 3098 3099 // Check for circular and duplicate entries. 3100 bool has_circularity = false; 3101 if (_need_verify) { 3102 has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0); 3103 if (has_circularity) { 3104 // If circularity check failed then ignore InnerClasses attribute. 3105 MetadataFactory::free_array<u2>(_loader_data, _inner_classes); 3106 index = 0; 3107 if (parsed_enclosingmethod_attribute) { 3108 inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0); 3109 _inner_classes = inner_classes; 3110 } else { 3111 _inner_classes = Universe::the_empty_short_array(); 3112 } 3113 } 3114 } 3115 // Set EnclosingMethod class and method indexes. 3116 if (parsed_enclosingmethod_attribute) { 3117 inner_classes->at_put(index++, enclosing_method_class_index); 3118 inner_classes->at_put(index++, enclosing_method_method_index); 3119 } 3120 assert(index == size || has_circularity, "wrong size"); 3121 3122 // Restore buffer's current position. 3123 cfs->set_current(current_mark); 3124 3125 return length; 3126 } 3127 3128 u2 ClassFileParser::parse_classfile_nest_members_attribute(const ClassFileStream* const cfs, 3129 const u1* const nest_members_attribute_start, 3130 TRAPS) { 3131 const u1* const current_mark = cfs->current(); 3132 u2 length = 0; 3133 if (nest_members_attribute_start != nullptr) { 3134 cfs->set_current(nest_members_attribute_start); 3135 cfs->guarantee_more(2, CHECK_0); // length 3136 length = cfs->get_u2_fast(); 3137 } 3138 const int size = length; 3139 Array<u2>* const nest_members = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0); 3140 _nest_members = nest_members; 3141 3142 int index = 0; 3143 cfs->guarantee_more(2 * length, CHECK_0); 3144 for (int n = 0; n < length; n++) { 3145 const u2 class_info_index = cfs->get_u2_fast(); 3146 guarantee_property( 3147 valid_klass_reference_at(class_info_index), 3148 "Nest member class_info_index %u has bad constant type in class file %s", 3149 class_info_index, CHECK_0); 3150 nest_members->at_put(index++, class_info_index); 3151 } 3152 assert(index == size, "wrong size"); 3153 3154 // Restore buffer's current position. 3155 cfs->set_current(current_mark); 3156 3157 return length; 3158 } 3159 3160 u2 ClassFileParser::parse_classfile_permitted_subclasses_attribute(const ClassFileStream* const cfs, 3161 const u1* const permitted_subclasses_attribute_start, 3162 TRAPS) { 3163 const u1* const current_mark = cfs->current(); 3164 u2 length = 0; 3165 if (permitted_subclasses_attribute_start != nullptr) { 3166 cfs->set_current(permitted_subclasses_attribute_start); 3167 cfs->guarantee_more(2, CHECK_0); // length 3168 length = cfs->get_u2_fast(); 3169 } 3170 const int size = length; 3171 Array<u2>* const permitted_subclasses = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0); 3172 _permitted_subclasses = permitted_subclasses; 3173 3174 if (length > 0) { 3175 int index = 0; 3176 cfs->guarantee_more(2 * length, CHECK_0); 3177 for (int n = 0; n < length; n++) { 3178 const u2 class_info_index = cfs->get_u2_fast(); 3179 guarantee_property( 3180 valid_klass_reference_at(class_info_index), 3181 "Permitted subclass class_info_index %u has bad constant type in class file %s", 3182 class_info_index, CHECK_0); 3183 permitted_subclasses->at_put(index++, class_info_index); 3184 } 3185 assert(index == size, "wrong size"); 3186 } 3187 3188 // Restore buffer's current position. 3189 cfs->set_current(current_mark); 3190 3191 return length; 3192 } 3193 3194 u2 ClassFileParser::parse_classfile_loadable_descriptors_attribute(const ClassFileStream* const cfs, 3195 const u1* const loadable_descriptors_attribute_start, 3196 TRAPS) { 3197 const u1* const current_mark = cfs->current(); 3198 u2 length = 0; 3199 if (loadable_descriptors_attribute_start != nullptr) { 3200 cfs->set_current(loadable_descriptors_attribute_start); 3201 cfs->guarantee_more(2, CHECK_0); // length 3202 length = cfs->get_u2_fast(); 3203 } 3204 const int size = length; 3205 Array<u2>* const loadable_descriptors = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0); 3206 _loadable_descriptors = loadable_descriptors; 3207 if (length > 0) { 3208 int index = 0; 3209 cfs->guarantee_more(2 * length, CHECK_0); 3210 for (int n = 0; n < length; n++) { 3211 const u2 descriptor_index = cfs->get_u2_fast(); 3212 guarantee_property( 3213 valid_symbol_at(descriptor_index), 3214 "LoadableDescriptors descriptor_index %u has bad constant type in class file %s", 3215 descriptor_index, CHECK_0); 3216 Symbol* descriptor = _cp->symbol_at(descriptor_index); 3217 bool valid = legal_field_signature(descriptor, CHECK_0); 3218 if(!valid) { 3219 ResourceMark rm(THREAD); 3220 Exceptions::fthrow(THREAD_AND_LOCATION, 3221 vmSymbols::java_lang_ClassFormatError(), 3222 "Descriptor from LoadableDescriptors attribute at index \"%d\" in class %s has illegal signature \"%s\"", 3223 descriptor_index, _class_name->as_C_string(), descriptor->as_C_string()); 3224 return 0; 3225 } 3226 loadable_descriptors->at_put(index++, descriptor_index); 3227 } 3228 assert(index == size, "wrong size"); 3229 } 3230 3231 // Restore buffer's current position. 3232 cfs->set_current(current_mark); 3233 3234 return length; 3235 } 3236 3237 // Record { 3238 // u2 attribute_name_index; 3239 // u4 attribute_length; 3240 // u2 components_count; 3241 // component_info components[components_count]; 3242 // } 3243 // component_info { 3244 // u2 name_index; 3245 // u2 descriptor_index 3246 // u2 attributes_count; 3247 // attribute_info_attributes[attributes_count]; 3248 // } 3249 u4 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* const cfs, 3250 const ConstantPool* cp, 3251 const u1* const record_attribute_start, 3252 TRAPS) { 3253 const u1* const current_mark = cfs->current(); 3254 int components_count = 0; 3255 unsigned int calculate_attr_size = 0; 3256 if (record_attribute_start != nullptr) { 3257 cfs->set_current(record_attribute_start); 3258 cfs->guarantee_more(2, CHECK_0); // num of components 3259 components_count = (int)cfs->get_u2_fast(); 3260 calculate_attr_size = 2; 3261 } 3262 3263 Array<RecordComponent*>* const record_components = 3264 MetadataFactory::new_array<RecordComponent*>(_loader_data, components_count, nullptr, CHECK_0); 3265 _record_components = record_components; 3266 3267 for (int x = 0; x < components_count; x++) { 3268 cfs->guarantee_more(6, CHECK_0); // name_index, descriptor_index, attributes_count 3269 3270 const u2 name_index = cfs->get_u2_fast(); 3271 guarantee_property(valid_symbol_at(name_index), 3272 "Invalid constant pool index %u for name in Record attribute in class file %s", 3273 name_index, CHECK_0); 3274 const Symbol* const name = cp->symbol_at(name_index); 3275 verify_legal_field_name(name, CHECK_0); 3276 3277 const u2 descriptor_index = cfs->get_u2_fast(); 3278 guarantee_property(valid_symbol_at(descriptor_index), 3279 "Invalid constant pool index %u for descriptor in Record attribute in class file %s", 3280 descriptor_index, CHECK_0); 3281 const Symbol* const descr = cp->symbol_at(descriptor_index); 3282 verify_legal_field_signature(name, descr, CHECK_0); 3283 3284 const u2 attributes_count = cfs->get_u2_fast(); 3285 calculate_attr_size += 6; 3286 u2 generic_sig_index = 0; 3287 const u1* runtime_visible_annotations = nullptr; 3288 int runtime_visible_annotations_length = 0; 3289 bool runtime_invisible_annotations_exists = false; 3290 const u1* runtime_visible_type_annotations = nullptr; 3291 int runtime_visible_type_annotations_length = 0; 3292 bool runtime_invisible_type_annotations_exists = false; 3293 3294 // Expected attributes for record components are Signature, Runtime(In)VisibleAnnotations, 3295 // and Runtime(In)VisibleTypeAnnotations. Other attributes are ignored. 3296 for (int y = 0; y < attributes_count; y++) { 3297 cfs->guarantee_more(6, CHECK_0); // attribute_name_index, attribute_length 3298 const u2 attribute_name_index = cfs->get_u2_fast(); 3299 const u4 attribute_length = cfs->get_u4_fast(); 3300 calculate_attr_size += 6; 3301 guarantee_property( 3302 valid_symbol_at(attribute_name_index), 3303 "Invalid Record attribute name index %u in class file %s", 3304 attribute_name_index, CHECK_0); 3305 3306 const Symbol* const attribute_name = cp->symbol_at(attribute_name_index); 3307 if (attribute_name == vmSymbols::tag_signature()) { 3308 if (generic_sig_index != 0) { 3309 classfile_parse_error( 3310 "Multiple Signature attributes for Record component in class file %s", 3311 THREAD); 3312 return 0; 3313 } 3314 if (attribute_length != 2) { 3315 classfile_parse_error( 3316 "Invalid Signature attribute length %u in Record component in class file %s", 3317 attribute_length, THREAD); 3318 return 0; 3319 } 3320 generic_sig_index = parse_generic_signature_attribute(cfs, CHECK_0); 3321 3322 } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) { 3323 if (runtime_visible_annotations != nullptr) { 3324 classfile_parse_error( 3325 "Multiple RuntimeVisibleAnnotations attributes for Record component in class file %s", THREAD); 3326 return 0; 3327 } 3328 runtime_visible_annotations_length = attribute_length; 3329 runtime_visible_annotations = cfs->current(); 3330 3331 assert(runtime_visible_annotations != nullptr, "null record component visible annotation"); 3332 cfs->guarantee_more(runtime_visible_annotations_length, CHECK_0); 3333 cfs->skip_u1_fast(runtime_visible_annotations_length); 3334 3335 } else if (attribute_name == vmSymbols::tag_runtime_invisible_annotations()) { 3336 if (runtime_invisible_annotations_exists) { 3337 classfile_parse_error( 3338 "Multiple RuntimeInvisibleAnnotations attributes for Record component in class file %s", THREAD); 3339 return 0; 3340 } 3341 runtime_invisible_annotations_exists = true; 3342 cfs->skip_u1(attribute_length, CHECK_0); 3343 3344 } else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) { 3345 if (runtime_visible_type_annotations != nullptr) { 3346 classfile_parse_error( 3347 "Multiple RuntimeVisibleTypeAnnotations attributes for Record component in class file %s", THREAD); 3348 return 0; 3349 } 3350 runtime_visible_type_annotations_length = attribute_length; 3351 runtime_visible_type_annotations = cfs->current(); 3352 3353 assert(runtime_visible_type_annotations != nullptr, "null record component visible type annotation"); 3354 cfs->guarantee_more(runtime_visible_type_annotations_length, CHECK_0); 3355 cfs->skip_u1_fast(runtime_visible_type_annotations_length); 3356 3357 } else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) { 3358 if (runtime_invisible_type_annotations_exists) { 3359 classfile_parse_error( 3360 "Multiple RuntimeInvisibleTypeAnnotations attributes for Record component in class file %s", THREAD); 3361 return 0; 3362 } 3363 runtime_invisible_type_annotations_exists = true; 3364 cfs->skip_u1(attribute_length, CHECK_0); 3365 3366 } else { 3367 // Skip unknown attributes 3368 cfs->skip_u1(attribute_length, CHECK_0); 3369 } 3370 calculate_attr_size += attribute_length; 3371 } // End of attributes For loop 3372 3373 AnnotationArray* annotations = allocate_annotations(runtime_visible_annotations, 3374 runtime_visible_annotations_length, 3375 CHECK_0); 3376 AnnotationArray* type_annotations = allocate_annotations(runtime_visible_type_annotations, 3377 runtime_visible_type_annotations_length, 3378 CHECK_0); 3379 3380 RecordComponent* record_component = 3381 RecordComponent::allocate(_loader_data, name_index, descriptor_index, generic_sig_index, 3382 annotations, type_annotations, CHECK_0); 3383 record_components->at_put(x, record_component); 3384 } // End of component processing loop 3385 3386 // Restore buffer's current position. 3387 cfs->set_current(current_mark); 3388 return calculate_attr_size; 3389 } 3390 3391 void ClassFileParser::parse_classfile_synthetic_attribute() { 3392 set_class_synthetic_flag(true); 3393 } 3394 3395 void ClassFileParser::parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS) { 3396 assert(cfs != nullptr, "invariant"); 3397 3398 const u2 signature_index = cfs->get_u2(CHECK); 3399 guarantee_property( 3400 valid_symbol_at(signature_index), 3401 "Invalid constant pool index %u in Signature attribute in class file %s", 3402 signature_index, CHECK); 3403 set_class_generic_signature_index(signature_index); 3404 } 3405 3406 void ClassFileParser::parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs, 3407 ConstantPool* cp, 3408 u4 attribute_byte_length, 3409 TRAPS) { 3410 assert(cfs != nullptr, "invariant"); 3411 assert(cp != nullptr, "invariant"); 3412 3413 const u1* const current_start = cfs->current(); 3414 3415 guarantee_property(attribute_byte_length >= sizeof(u2), 3416 "Invalid BootstrapMethods attribute length %u in class file %s", 3417 attribute_byte_length, 3418 CHECK); 3419 3420 cfs->guarantee_more(attribute_byte_length, CHECK); 3421 3422 const int attribute_array_length = cfs->get_u2_fast(); 3423 3424 guarantee_property(_max_bootstrap_specifier_index < attribute_array_length, 3425 "Short length on BootstrapMethods in class file %s", 3426 CHECK); 3427 3428 3429 // The attribute contains a counted array of counted tuples of shorts, 3430 // represending bootstrap specifiers: 3431 // length*{bootstrap_method_index, argument_count*{argument_index}} 3432 const unsigned int operand_count = (attribute_byte_length - (unsigned)sizeof(u2)) / (unsigned)sizeof(u2); 3433 // operand_count = number of shorts in attr, except for leading length 3434 3435 // The attribute is copied into a short[] array. 3436 // The array begins with a series of short[2] pairs, one for each tuple. 3437 const int index_size = (attribute_array_length * 2); 3438 3439 Array<u2>* const operands = 3440 MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK); 3441 3442 // Eagerly assign operands so they will be deallocated with the constant 3443 // pool if there is an error. 3444 cp->set_operands(operands); 3445 3446 int operand_fill_index = index_size; 3447 const int cp_size = cp->length(); 3448 3449 for (int n = 0; n < attribute_array_length; n++) { 3450 // Store a 32-bit offset into the header of the operand array. 3451 ConstantPool::operand_offset_at_put(operands, n, operand_fill_index); 3452 3453 // Read a bootstrap specifier. 3454 cfs->guarantee_more(sizeof(u2) * 2, CHECK); // bsm, argc 3455 const u2 bootstrap_method_index = cfs->get_u2_fast(); 3456 const u2 argument_count = cfs->get_u2_fast(); 3457 guarantee_property( 3458 valid_cp_range(bootstrap_method_index, cp_size) && 3459 cp->tag_at(bootstrap_method_index).is_method_handle(), 3460 "bootstrap_method_index %u has bad constant type in class file %s", 3461 bootstrap_method_index, 3462 CHECK); 3463 3464 guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(), 3465 "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s", 3466 CHECK); 3467 3468 operands->at_put(operand_fill_index++, bootstrap_method_index); 3469 operands->at_put(operand_fill_index++, argument_count); 3470 3471 cfs->guarantee_more(sizeof(u2) * argument_count, CHECK); // argv[argc] 3472 for (int j = 0; j < argument_count; j++) { 3473 const u2 argument_index = cfs->get_u2_fast(); 3474 guarantee_property( 3475 valid_cp_range(argument_index, cp_size) && 3476 cp->tag_at(argument_index).is_loadable_constant(), 3477 "argument_index %u has bad constant type in class file %s", 3478 argument_index, 3479 CHECK); 3480 operands->at_put(operand_fill_index++, argument_index); 3481 } 3482 } 3483 guarantee_property(current_start + attribute_byte_length == cfs->current(), 3484 "Bad length on BootstrapMethods in class file %s", 3485 CHECK); 3486 } 3487 3488 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs, 3489 ConstantPool* cp, 3490 ClassFileParser::ClassAnnotationCollector* parsed_annotations, 3491 TRAPS) { 3492 assert(cfs != nullptr, "invariant"); 3493 assert(cp != nullptr, "invariant"); 3494 assert(parsed_annotations != nullptr, "invariant"); 3495 3496 // Set inner classes attribute to default sentinel 3497 _inner_classes = Universe::the_empty_short_array(); 3498 // Set nest members attribute to default sentinel 3499 _nest_members = Universe::the_empty_short_array(); 3500 // Set _permitted_subclasses attribute to default sentinel 3501 _permitted_subclasses = Universe::the_empty_short_array(); 3502 // Set _loadable_descriptors attribute to default sentinel 3503 _loadable_descriptors = Universe::the_empty_short_array(); 3504 cfs->guarantee_more(2, CHECK); // attributes_count 3505 u2 attributes_count = cfs->get_u2_fast(); 3506 bool parsed_sourcefile_attribute = false; 3507 bool parsed_innerclasses_attribute = false; 3508 bool parsed_nest_members_attribute = false; 3509 bool parsed_permitted_subclasses_attribute = false; 3510 bool parsed_loadable_descriptors_attribute = false; 3511 bool parsed_nest_host_attribute = false; 3512 bool parsed_record_attribute = false; 3513 bool parsed_enclosingmethod_attribute = false; 3514 bool parsed_bootstrap_methods_attribute = false; 3515 const u1* runtime_visible_annotations = nullptr; 3516 int runtime_visible_annotations_length = 0; 3517 const u1* runtime_visible_type_annotations = nullptr; 3518 int runtime_visible_type_annotations_length = 0; 3519 bool runtime_invisible_type_annotations_exists = false; 3520 bool runtime_invisible_annotations_exists = false; 3521 bool parsed_source_debug_ext_annotations_exist = false; 3522 const u1* inner_classes_attribute_start = nullptr; 3523 u4 inner_classes_attribute_length = 0; 3524 u2 enclosing_method_class_index = 0; 3525 u2 enclosing_method_method_index = 0; 3526 const u1* nest_members_attribute_start = nullptr; 3527 u4 nest_members_attribute_length = 0; 3528 const u1* record_attribute_start = nullptr; 3529 u4 record_attribute_length = 0; 3530 const u1* permitted_subclasses_attribute_start = nullptr; 3531 u4 permitted_subclasses_attribute_length = 0; 3532 const u1* loadable_descriptors_attribute_start = nullptr; 3533 u4 loadable_descriptors_attribute_length = 0; 3534 3535 // Iterate over attributes 3536 while (attributes_count--) { 3537 cfs->guarantee_more(6, CHECK); // attribute_name_index, attribute_length 3538 const u2 attribute_name_index = cfs->get_u2_fast(); 3539 const u4 attribute_length = cfs->get_u4_fast(); 3540 guarantee_property( 3541 valid_symbol_at(attribute_name_index), 3542 "Attribute name has bad constant pool index %u in class file %s", 3543 attribute_name_index, CHECK); 3544 const Symbol* const tag = cp->symbol_at(attribute_name_index); 3545 if (tag == vmSymbols::tag_source_file()) { 3546 // Check for SourceFile tag 3547 if (_need_verify) { 3548 guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK); 3549 } 3550 if (parsed_sourcefile_attribute) { 3551 classfile_parse_error("Multiple SourceFile attributes in class file %s", THREAD); 3552 return; 3553 } else { 3554 parsed_sourcefile_attribute = true; 3555 } 3556 parse_classfile_sourcefile_attribute(cfs, CHECK); 3557 } else if (tag == vmSymbols::tag_source_debug_extension()) { 3558 // Check for SourceDebugExtension tag 3559 if (parsed_source_debug_ext_annotations_exist) { 3560 classfile_parse_error( 3561 "Multiple SourceDebugExtension attributes in class file %s", THREAD); 3562 return; 3563 } 3564 parsed_source_debug_ext_annotations_exist = true; 3565 parse_classfile_source_debug_extension_attribute(cfs, (int)attribute_length, CHECK); 3566 } else if (tag == vmSymbols::tag_inner_classes()) { 3567 // Check for InnerClasses tag 3568 if (parsed_innerclasses_attribute) { 3569 classfile_parse_error("Multiple InnerClasses attributes in class file %s", THREAD); 3570 return; 3571 } else { 3572 parsed_innerclasses_attribute = true; 3573 } 3574 inner_classes_attribute_start = cfs->current(); 3575 inner_classes_attribute_length = attribute_length; 3576 cfs->skip_u1(inner_classes_attribute_length, CHECK); 3577 } else if (tag == vmSymbols::tag_synthetic()) { 3578 // Check for Synthetic tag 3579 // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec 3580 if (attribute_length != 0) { 3581 classfile_parse_error( 3582 "Invalid Synthetic classfile attribute length %u in class file %s", 3583 attribute_length, THREAD); 3584 return; 3585 } 3586 parse_classfile_synthetic_attribute(); 3587 } else if (tag == vmSymbols::tag_deprecated()) { 3588 // Check for Deprecated tag - 4276120 3589 if (attribute_length != 0) { 3590 classfile_parse_error( 3591 "Invalid Deprecated classfile attribute length %u in class file %s", 3592 attribute_length, THREAD); 3593 return; 3594 } 3595 } else if (_major_version >= JAVA_1_5_VERSION) { 3596 if (tag == vmSymbols::tag_signature()) { 3597 if (_generic_signature_index != 0) { 3598 classfile_parse_error( 3599 "Multiple Signature attributes in class file %s", THREAD); 3600 return; 3601 } 3602 if (attribute_length != 2) { 3603 classfile_parse_error( 3604 "Wrong Signature attribute length %u in class file %s", 3605 attribute_length, THREAD); 3606 return; 3607 } 3608 parse_classfile_signature_attribute(cfs, CHECK); 3609 } else if (tag == vmSymbols::tag_runtime_visible_annotations()) { 3610 if (runtime_visible_annotations != nullptr) { 3611 classfile_parse_error( 3612 "Multiple RuntimeVisibleAnnotations attributes in class file %s", THREAD); 3613 return; 3614 } 3615 runtime_visible_annotations_length = attribute_length; 3616 runtime_visible_annotations = cfs->current(); 3617 assert(runtime_visible_annotations != nullptr, "null visible annotations"); 3618 cfs->guarantee_more(runtime_visible_annotations_length, CHECK); 3619 parse_annotations(cp, 3620 runtime_visible_annotations, 3621 runtime_visible_annotations_length, 3622 parsed_annotations, 3623 _loader_data, 3624 _can_access_vm_annotations); 3625 cfs->skip_u1_fast(runtime_visible_annotations_length); 3626 } else if (tag == vmSymbols::tag_runtime_invisible_annotations()) { 3627 if (runtime_invisible_annotations_exists) { 3628 classfile_parse_error( 3629 "Multiple RuntimeInvisibleAnnotations attributes in class file %s", THREAD); 3630 return; 3631 } 3632 runtime_invisible_annotations_exists = true; 3633 cfs->skip_u1(attribute_length, CHECK); 3634 } else if (tag == vmSymbols::tag_enclosing_method()) { 3635 if (parsed_enclosingmethod_attribute) { 3636 classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", THREAD); 3637 return; 3638 } else { 3639 parsed_enclosingmethod_attribute = true; 3640 } 3641 guarantee_property(attribute_length == 4, 3642 "Wrong EnclosingMethod attribute length %u in class file %s", 3643 attribute_length, CHECK); 3644 cfs->guarantee_more(4, CHECK); // class_index, method_index 3645 enclosing_method_class_index = cfs->get_u2_fast(); 3646 enclosing_method_method_index = cfs->get_u2_fast(); 3647 if (enclosing_method_class_index == 0) { 3648 classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", THREAD); 3649 return; 3650 } 3651 // Validate the constant pool indices and types 3652 guarantee_property(valid_klass_reference_at(enclosing_method_class_index), 3653 "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK); 3654 if (enclosing_method_method_index != 0 && 3655 (!cp->is_within_bounds(enclosing_method_method_index) || 3656 !cp->tag_at(enclosing_method_method_index).is_name_and_type())) { 3657 classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", THREAD); 3658 return; 3659 } 3660 } else if (tag == vmSymbols::tag_bootstrap_methods() && 3661 _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) { 3662 if (parsed_bootstrap_methods_attribute) { 3663 classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", THREAD); 3664 return; 3665 } 3666 parsed_bootstrap_methods_attribute = true; 3667 parse_classfile_bootstrap_methods_attribute(cfs, cp, attribute_length, CHECK); 3668 } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) { 3669 if (runtime_visible_type_annotations != nullptr) { 3670 classfile_parse_error( 3671 "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", THREAD); 3672 return; 3673 } 3674 runtime_visible_type_annotations_length = attribute_length; 3675 runtime_visible_type_annotations = cfs->current(); 3676 assert(runtime_visible_type_annotations != nullptr, "null visible type annotations"); 3677 // No need for the VM to parse Type annotations 3678 cfs->skip_u1(runtime_visible_type_annotations_length, CHECK); 3679 } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) { 3680 if (runtime_invisible_type_annotations_exists) { 3681 classfile_parse_error( 3682 "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", THREAD); 3683 return; 3684 } 3685 runtime_invisible_type_annotations_exists = true; 3686 cfs->skip_u1(attribute_length, CHECK); 3687 } else if (_major_version >= JAVA_11_VERSION) { 3688 if (tag == vmSymbols::tag_nest_members()) { 3689 // Check for NestMembers tag 3690 if (parsed_nest_members_attribute) { 3691 classfile_parse_error("Multiple NestMembers attributes in class file %s", THREAD); 3692 return; 3693 } else { 3694 parsed_nest_members_attribute = true; 3695 } 3696 if (parsed_nest_host_attribute) { 3697 classfile_parse_error("Conflicting NestHost and NestMembers attributes in class file %s", THREAD); 3698 return; 3699 } 3700 nest_members_attribute_start = cfs->current(); 3701 nest_members_attribute_length = attribute_length; 3702 cfs->skip_u1(nest_members_attribute_length, CHECK); 3703 } else if (tag == vmSymbols::tag_nest_host()) { 3704 if (parsed_nest_host_attribute) { 3705 classfile_parse_error("Multiple NestHost attributes in class file %s", THREAD); 3706 return; 3707 } else { 3708 parsed_nest_host_attribute = true; 3709 } 3710 if (parsed_nest_members_attribute) { 3711 classfile_parse_error("Conflicting NestMembers and NestHost attributes in class file %s", THREAD); 3712 return; 3713 } 3714 if (_need_verify) { 3715 guarantee_property(attribute_length == 2, "Wrong NestHost attribute length in class file %s", CHECK); 3716 } 3717 cfs->guarantee_more(2, CHECK); 3718 u2 class_info_index = cfs->get_u2_fast(); 3719 guarantee_property( 3720 valid_klass_reference_at(class_info_index), 3721 "Nest-host class_info_index %u has bad constant type in class file %s", 3722 class_info_index, CHECK); 3723 _nest_host = class_info_index; 3724 3725 } else if (_major_version >= JAVA_16_VERSION) { 3726 if (tag == vmSymbols::tag_record()) { 3727 if (parsed_record_attribute) { 3728 classfile_parse_error("Multiple Record attributes in class file %s", THREAD); 3729 return; 3730 } 3731 parsed_record_attribute = true; 3732 record_attribute_start = cfs->current(); 3733 record_attribute_length = attribute_length; 3734 } else if (_major_version >= JAVA_17_VERSION) { 3735 if (tag == vmSymbols::tag_permitted_subclasses()) { 3736 if (parsed_permitted_subclasses_attribute) { 3737 classfile_parse_error("Multiple PermittedSubclasses attributes in class file %s", CHECK); 3738 return; 3739 } 3740 // Classes marked ACC_FINAL cannot have a PermittedSubclasses attribute. 3741 if (_access_flags.is_final()) { 3742 classfile_parse_error("PermittedSubclasses attribute in final class file %s", CHECK); 3743 return; 3744 } 3745 parsed_permitted_subclasses_attribute = true; 3746 permitted_subclasses_attribute_start = cfs->current(); 3747 permitted_subclasses_attribute_length = attribute_length; 3748 } 3749 if (EnableValhalla && tag == vmSymbols::tag_loadable_descriptors()) { 3750 if (parsed_loadable_descriptors_attribute) { 3751 classfile_parse_error("Multiple LoadableDescriptors attributes in class file %s", CHECK); 3752 return; 3753 } 3754 parsed_loadable_descriptors_attribute = true; 3755 loadable_descriptors_attribute_start = cfs->current(); 3756 loadable_descriptors_attribute_length = attribute_length; 3757 } 3758 } 3759 // Skip attribute_length for any attribute where major_verson >= JAVA_17_VERSION 3760 cfs->skip_u1(attribute_length, CHECK); 3761 } else { 3762 // Unknown attribute 3763 cfs->skip_u1(attribute_length, CHECK); 3764 } 3765 } else { 3766 // Unknown attribute 3767 cfs->skip_u1(attribute_length, CHECK); 3768 } 3769 } else { 3770 // Unknown attribute 3771 cfs->skip_u1(attribute_length, CHECK); 3772 } 3773 } 3774 _class_annotations = allocate_annotations(runtime_visible_annotations, 3775 runtime_visible_annotations_length, 3776 CHECK); 3777 _class_type_annotations = allocate_annotations(runtime_visible_type_annotations, 3778 runtime_visible_type_annotations_length, 3779 CHECK); 3780 3781 if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) { 3782 const u2 num_of_classes = parse_classfile_inner_classes_attribute( 3783 cfs, 3784 cp, 3785 inner_classes_attribute_start, 3786 parsed_innerclasses_attribute, 3787 enclosing_method_class_index, 3788 enclosing_method_method_index, 3789 CHECK); 3790 if (parsed_innerclasses_attribute && _need_verify && _major_version >= JAVA_1_5_VERSION) { 3791 guarantee_property( 3792 inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes, 3793 "Wrong InnerClasses attribute length in class file %s", CHECK); 3794 } 3795 } 3796 3797 if (parsed_nest_members_attribute) { 3798 const u2 num_of_classes = parse_classfile_nest_members_attribute( 3799 cfs, 3800 nest_members_attribute_start, 3801 CHECK); 3802 if (_need_verify) { 3803 guarantee_property( 3804 nest_members_attribute_length == sizeof(num_of_classes) + sizeof(u2) * num_of_classes, 3805 "Wrong NestMembers attribute length in class file %s", CHECK); 3806 } 3807 } 3808 3809 if (parsed_record_attribute) { 3810 const unsigned int calculated_attr_length = parse_classfile_record_attribute( 3811 cfs, 3812 cp, 3813 record_attribute_start, 3814 CHECK); 3815 if (_need_verify) { 3816 guarantee_property(record_attribute_length == calculated_attr_length, 3817 "Record attribute has wrong length in class file %s", 3818 CHECK); 3819 } 3820 } 3821 3822 if (parsed_permitted_subclasses_attribute) { 3823 const u2 num_subclasses = parse_classfile_permitted_subclasses_attribute( 3824 cfs, 3825 permitted_subclasses_attribute_start, 3826 CHECK); 3827 if (_need_verify) { 3828 guarantee_property( 3829 permitted_subclasses_attribute_length == sizeof(num_subclasses) + sizeof(u2) * num_subclasses, 3830 "Wrong PermittedSubclasses attribute length in class file %s", CHECK); 3831 } 3832 } 3833 3834 if (parsed_loadable_descriptors_attribute) { 3835 const u2 num_classes = parse_classfile_loadable_descriptors_attribute( 3836 cfs, 3837 loadable_descriptors_attribute_start, 3838 CHECK); 3839 if (_need_verify) { 3840 guarantee_property( 3841 loadable_descriptors_attribute_length == sizeof(num_classes) + sizeof(u2) * num_classes, 3842 "Wrong LoadableDescriptors attribute length in class file %s", CHECK); 3843 } 3844 } 3845 3846 if (_max_bootstrap_specifier_index >= 0) { 3847 guarantee_property(parsed_bootstrap_methods_attribute, 3848 "Missing BootstrapMethods attribute in class file %s", CHECK); 3849 } 3850 } 3851 3852 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) { 3853 assert(k != nullptr, "invariant"); 3854 3855 if (_synthetic_flag) 3856 k->set_is_synthetic(); 3857 if (_sourcefile_index != 0) { 3858 k->set_source_file_name_index(_sourcefile_index); 3859 } 3860 if (_generic_signature_index != 0) { 3861 k->set_generic_signature_index(_generic_signature_index); 3862 } 3863 if (_sde_buffer != nullptr) { 3864 k->set_source_debug_extension(_sde_buffer, _sde_length); 3865 } 3866 } 3867 3868 // Create the Annotations object that will 3869 // hold the annotations array for the Klass. 3870 void ClassFileParser::create_combined_annotations(TRAPS) { 3871 if (_class_annotations == nullptr && 3872 _class_type_annotations == nullptr && 3873 _fields_annotations == nullptr && 3874 _fields_type_annotations == nullptr) { 3875 // Don't create the Annotations object unnecessarily. 3876 return; 3877 } 3878 3879 Annotations* const annotations = Annotations::allocate(_loader_data, CHECK); 3880 annotations->set_class_annotations(_class_annotations); 3881 annotations->set_class_type_annotations(_class_type_annotations); 3882 annotations->set_fields_annotations(_fields_annotations); 3883 annotations->set_fields_type_annotations(_fields_type_annotations); 3884 3885 // This is the Annotations object that will be 3886 // assigned to InstanceKlass being constructed. 3887 _combined_annotations = annotations; 3888 3889 // The annotations arrays below has been transferred the 3890 // _combined_annotations so these fields can now be cleared. 3891 _class_annotations = nullptr; 3892 _class_type_annotations = nullptr; 3893 _fields_annotations = nullptr; 3894 _fields_type_annotations = nullptr; 3895 } 3896 3897 // Transfer ownership of metadata allocated to the InstanceKlass. 3898 void ClassFileParser::apply_parsed_class_metadata( 3899 InstanceKlass* this_klass, 3900 int java_fields_count) { 3901 assert(this_klass != nullptr, "invariant"); 3902 3903 _cp->set_pool_holder(this_klass); 3904 this_klass->set_constants(_cp); 3905 this_klass->set_fieldinfo_stream(_fieldinfo_stream); 3906 this_klass->set_fields_status(_fields_status); 3907 this_klass->set_methods(_methods); 3908 this_klass->set_inner_classes(_inner_classes); 3909 this_klass->set_nest_members(_nest_members); 3910 this_klass->set_nest_host_index(_nest_host); 3911 this_klass->set_loadable_descriptors(_loadable_descriptors); 3912 this_klass->set_annotations(_combined_annotations); 3913 this_klass->set_permitted_subclasses(_permitted_subclasses); 3914 this_klass->set_record_components(_record_components); 3915 this_klass->set_inline_layout_info_array(_inline_layout_info_array); 3916 3917 // Delay the setting of _local_interfaces and _transitive_interfaces until after 3918 // initialize_supers() in fill_instance_klass(). It is because the _local_interfaces could 3919 // be shared with _transitive_interfaces and _transitive_interfaces may be shared with 3920 // its _super. If an OOM occurs while loading the current klass, its _super field 3921 // may not have been set. When GC tries to free the klass, the _transitive_interfaces 3922 // may be deallocated mistakenly in InstanceKlass::deallocate_interfaces(). Subsequent 3923 // dereferences to the deallocated _transitive_interfaces will result in a crash. 3924 3925 // Clear out these fields so they don't get deallocated by the destructor 3926 clear_class_metadata(); 3927 } 3928 3929 AnnotationArray* ClassFileParser::allocate_annotations(const u1* const anno, 3930 int anno_length, 3931 TRAPS) { 3932 AnnotationArray* annotations = nullptr; 3933 if (anno != nullptr) { 3934 annotations = MetadataFactory::new_array<u1>(_loader_data, 3935 anno_length, 3936 CHECK_(annotations)); 3937 for (int i = 0; i < anno_length; i++) { 3938 annotations->at_put(i, anno[i]); 3939 } 3940 } 3941 return annotations; 3942 } 3943 3944 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp, 3945 const int super_class_index, 3946 const bool need_verify, 3947 TRAPS) { 3948 assert(cp != nullptr, "invariant"); 3949 const InstanceKlass* super_klass = nullptr; 3950 3951 if (super_class_index == 0) { 3952 guarantee_property(_class_name == vmSymbols::java_lang_Object(), 3953 "Invalid superclass index 0 in class file %s", 3954 CHECK_NULL); 3955 } else { 3956 guarantee_property(valid_klass_reference_at(super_class_index), 3957 "Invalid superclass index %u in class file %s", 3958 super_class_index, 3959 CHECK_NULL); 3960 // The class name should be legal because it is checked when parsing constant pool. 3961 // However, make sure it is not an array type. 3962 if (cp->tag_at(super_class_index).is_klass()) { 3963 super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index)); 3964 } 3965 if (need_verify) { 3966 bool is_array = (cp->klass_name_at(super_class_index)->char_at(0) == JVM_SIGNATURE_ARRAY); 3967 guarantee_property(!is_array, 3968 "Bad superclass name in class file %s", CHECK_NULL); 3969 } 3970 } 3971 return super_klass; 3972 } 3973 3974 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) { 3975 _max_nonstatic_oop_maps = max_blocks; 3976 _nonstatic_oop_map_count = 0; 3977 if (max_blocks == 0) { 3978 _nonstatic_oop_maps = nullptr; 3979 } else { 3980 _nonstatic_oop_maps = 3981 NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps); 3982 memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks); 3983 } 3984 } 3985 3986 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const { 3987 assert(_nonstatic_oop_map_count > 0, "Has no oop maps"); 3988 return _nonstatic_oop_maps + (_nonstatic_oop_map_count - 1); 3989 } 3990 3991 // addition of super oop maps 3992 void OopMapBlocksBuilder::initialize_inherited_blocks(OopMapBlock* blocks, unsigned int nof_blocks) { 3993 assert(nof_blocks && _nonstatic_oop_map_count == 0 && 3994 nof_blocks <= _max_nonstatic_oop_maps, "invariant"); 3995 3996 memcpy(_nonstatic_oop_maps, blocks, sizeof(OopMapBlock) * nof_blocks); 3997 _nonstatic_oop_map_count += nof_blocks; 3998 } 3999 4000 // collection of oops 4001 void OopMapBlocksBuilder::add(int offset, int count) { 4002 if (_nonstatic_oop_map_count == 0) { 4003 _nonstatic_oop_map_count++; 4004 } 4005 OopMapBlock* nonstatic_oop_map = last_oop_map(); 4006 if (nonstatic_oop_map->count() == 0) { // Unused map, set it up 4007 nonstatic_oop_map->set_offset(offset); 4008 nonstatic_oop_map->set_count(count); 4009 } else if (nonstatic_oop_map->is_contiguous(offset)) { // contiguous, add 4010 nonstatic_oop_map->increment_count(count); 4011 } else { // Need a new one... 4012 _nonstatic_oop_map_count++; 4013 assert(_nonstatic_oop_map_count <= _max_nonstatic_oop_maps, "range check"); 4014 nonstatic_oop_map = last_oop_map(); 4015 nonstatic_oop_map->set_offset(offset); 4016 nonstatic_oop_map->set_count(count); 4017 } 4018 } 4019 4020 // general purpose copy, e.g. into allocated instanceKlass 4021 void OopMapBlocksBuilder::copy(OopMapBlock* dst) { 4022 if (_nonstatic_oop_map_count != 0) { 4023 memcpy(dst, _nonstatic_oop_maps, sizeof(OopMapBlock) * _nonstatic_oop_map_count); 4024 } 4025 } 4026 4027 // Sort and compact adjacent blocks 4028 void OopMapBlocksBuilder::compact() { 4029 if (_nonstatic_oop_map_count <= 1) { 4030 return; 4031 } 4032 /* 4033 * Since field layout sneaks in oops before values, we will be able to condense 4034 * blocks. There is potential to compact between super, own refs and values 4035 * containing refs. 4036 * 4037 * Currently compaction is slightly limited due to values being 8 byte aligned. 4038 * This may well change: FixMe if it doesn't, the code below is fairly general purpose 4039 * and maybe it doesn't need to be. 4040 */ 4041 qsort(_nonstatic_oop_maps, _nonstatic_oop_map_count, sizeof(OopMapBlock), 4042 (_sort_Fn)OopMapBlock::compare_offset); 4043 if (_nonstatic_oop_map_count < 2) { 4044 return; 4045 } 4046 4047 // Make a temp copy, and iterate through and copy back into the original 4048 ResourceMark rm; 4049 OopMapBlock* oop_maps_copy = 4050 NEW_RESOURCE_ARRAY(OopMapBlock, _nonstatic_oop_map_count); 4051 OopMapBlock* oop_maps_copy_end = oop_maps_copy + _nonstatic_oop_map_count; 4052 copy(oop_maps_copy); 4053 OopMapBlock* nonstatic_oop_map = _nonstatic_oop_maps; 4054 unsigned int new_count = 1; 4055 oop_maps_copy++; 4056 while(oop_maps_copy < oop_maps_copy_end) { 4057 assert(nonstatic_oop_map->offset() < oop_maps_copy->offset(), "invariant"); 4058 if (nonstatic_oop_map->is_contiguous(oop_maps_copy->offset())) { 4059 nonstatic_oop_map->increment_count(oop_maps_copy->count()); 4060 } else { 4061 nonstatic_oop_map++; 4062 new_count++; 4063 nonstatic_oop_map->set_offset(oop_maps_copy->offset()); 4064 nonstatic_oop_map->set_count(oop_maps_copy->count()); 4065 } 4066 oop_maps_copy++; 4067 } 4068 assert(new_count <= _nonstatic_oop_map_count, "end up with more maps after compact() ?"); 4069 _nonstatic_oop_map_count = new_count; 4070 } 4071 4072 void OopMapBlocksBuilder::print_on(outputStream* st) const { 4073 st->print_cr(" OopMapBlocks: %3d /%3d", _nonstatic_oop_map_count, _max_nonstatic_oop_maps); 4074 if (_nonstatic_oop_map_count > 0) { 4075 OopMapBlock* map = _nonstatic_oop_maps; 4076 OopMapBlock* last_map = last_oop_map(); 4077 assert(map <= last_map, "Last less than first"); 4078 while (map <= last_map) { 4079 st->print_cr(" Offset: %3d -%3d Count: %3d", map->offset(), 4080 map->offset() + map->offset_span() - heapOopSize, map->count()); 4081 map++; 4082 } 4083 } 4084 } 4085 4086 void OopMapBlocksBuilder::print_value_on(outputStream* st) const { 4087 print_on(st); 4088 } 4089 4090 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) { 4091 assert(ik != nullptr, "invariant"); 4092 4093 const InstanceKlass* const super = ik->java_super(); 4094 4095 // Check if this klass has an empty finalize method (i.e. one with return bytecode only), 4096 // in which case we don't have to register objects as finalizable 4097 if (!_has_empty_finalizer) { 4098 if (_has_finalizer || 4099 (super != nullptr && super->has_finalizer())) { 4100 ik->set_has_finalizer(); 4101 } 4102 } 4103 4104 #ifdef ASSERT 4105 bool f = false; 4106 const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(), 4107 vmSymbols::void_method_signature()); 4108 if (InstanceKlass::is_finalization_enabled() && 4109 (m != nullptr) && !m->is_empty_method()) { 4110 f = true; 4111 } 4112 4113 // Spec doesn't prevent agent from redefinition of empty finalizer. 4114 // Despite the fact that it's generally bad idea and redefined finalizer 4115 // will not work as expected we shouldn't abort vm in this case 4116 if (!ik->has_redefined_this_or_super()) { 4117 assert(ik->has_finalizer() == f, "inconsistent has_finalizer"); 4118 } 4119 #endif 4120 4121 // Check if this klass supports the java.lang.Cloneable interface 4122 if (vmClasses::Cloneable_klass_loaded()) { 4123 if (ik->is_subtype_of(vmClasses::Cloneable_klass())) { 4124 ik->set_is_cloneable(); 4125 } 4126 } 4127 4128 // If it cannot be fast-path allocated, set a bit in the layout helper. 4129 // See documentation of InstanceKlass::can_be_fastpath_allocated(). 4130 assert(ik->size_helper() > 0, "layout_helper is initialized"); 4131 if (ik->is_abstract() || ik->is_interface() 4132 || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == nullptr) 4133 || ik->size_helper() >= FastAllocateSizeLimit) { 4134 // Forbid fast-path allocation. 4135 const jint lh = Klass::instance_layout_helper(ik->size_helper(), true); 4136 ik->set_layout_helper(lh); 4137 } 4138 } 4139 4140 bool ClassFileParser::supports_inline_types() const { 4141 // Inline types are only supported by class file version 69.65535 and later 4142 return _major_version > JAVA_25_VERSION || 4143 (_major_version == JAVA_25_VERSION && _minor_version == JAVA_PREVIEW_MINOR_VERSION); 4144 } 4145 4146 // utility methods for appending an array with check for duplicates 4147 4148 static void append_interfaces(GrowableArray<InstanceKlass*>* result, 4149 const Array<InstanceKlass*>* const ifs) { 4150 // iterate over new interfaces 4151 for (int i = 0; i < ifs->length(); i++) { 4152 InstanceKlass* const e = ifs->at(i); 4153 assert(e->is_klass() && e->is_interface(), "just checking"); 4154 // add new interface 4155 result->append_if_missing(e); 4156 } 4157 } 4158 4159 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super, 4160 Array<InstanceKlass*>* local_ifs, 4161 ClassLoaderData* loader_data, 4162 TRAPS) { 4163 assert(local_ifs != nullptr, "invariant"); 4164 assert(loader_data != nullptr, "invariant"); 4165 4166 // Compute maximum size for transitive interfaces 4167 int max_transitive_size = 0; 4168 int super_size = 0; 4169 // Add superclass transitive interfaces size 4170 if (super != nullptr) { 4171 super_size = super->transitive_interfaces()->length(); 4172 max_transitive_size += super_size; 4173 } 4174 // Add local interfaces' super interfaces 4175 const int local_size = local_ifs->length(); 4176 for (int i = 0; i < local_size; i++) { 4177 InstanceKlass* const l = local_ifs->at(i); 4178 max_transitive_size += l->transitive_interfaces()->length(); 4179 } 4180 // Finally add local interfaces 4181 max_transitive_size += local_size; 4182 // Construct array 4183 if (max_transitive_size == 0) { 4184 // no interfaces, use canonicalized array 4185 return Universe::the_empty_instance_klass_array(); 4186 } else if (max_transitive_size == super_size) { 4187 // no new local interfaces added, share superklass' transitive interface array 4188 return super->transitive_interfaces(); 4189 // The three lines below are commented to work around bug JDK-8245487 4190 // } else if (max_transitive_size == local_size) { 4191 // // only local interfaces added, share local interface array 4192 // return local_ifs; 4193 } else { 4194 ResourceMark rm; 4195 GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size); 4196 4197 // Copy down from superclass 4198 if (super != nullptr) { 4199 append_interfaces(result, super->transitive_interfaces()); 4200 } 4201 4202 // Copy down from local interfaces' superinterfaces 4203 for (int i = 0; i < local_size; i++) { 4204 InstanceKlass* const l = local_ifs->at(i); 4205 append_interfaces(result, l->transitive_interfaces()); 4206 } 4207 // Finally add local interfaces 4208 append_interfaces(result, local_ifs); 4209 4210 // length will be less than the max_transitive_size if duplicates were removed 4211 const int length = result->length(); 4212 assert(length <= max_transitive_size, "just checking"); 4213 4214 Array<InstanceKlass*>* const new_result = 4215 MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL); 4216 for (int i = 0; i < length; i++) { 4217 InstanceKlass* const e = result->at(i); 4218 assert(e != nullptr, "just checking"); 4219 new_result->at_put(i, e); 4220 } 4221 return new_result; 4222 } 4223 } 4224 4225 void ClassFileParser::check_super_class_access(const InstanceKlass* this_klass, TRAPS) { 4226 assert(this_klass != nullptr, "invariant"); 4227 const Klass* const super = this_klass->super(); 4228 4229 if (super != nullptr) { 4230 const InstanceKlass* super_ik = InstanceKlass::cast(super); 4231 4232 if (super->is_final()) { 4233 classfile_icce_error("class %s cannot inherit from final class %s", super_ik, THREAD); 4234 return; 4235 } 4236 4237 if (super_ik->is_sealed()) { 4238 stringStream ss; 4239 ResourceMark rm(THREAD); 4240 if (!super_ik->has_as_permitted_subclass(this_klass, ss)) { 4241 classfile_icce_error(ss.as_string(), THREAD); 4242 return; 4243 } 4244 } 4245 4246 // The JVMS says that super classes for value types must not have the ACC_IDENTITY 4247 // flag set. But, java.lang.Object must still be allowed to be a direct super class 4248 // for a value classes. So, it is treated as a special case for now. 4249 if (!this_klass->access_flags().is_identity_class() && 4250 super_ik->name() != vmSymbols::java_lang_Object() && 4251 super_ik->is_identity_class()) { 4252 classfile_icce_error("value class %s cannot inherit from class %s", super_ik, THREAD); 4253 return; 4254 } 4255 4256 Reflection::VerifyClassAccessResults vca_result = 4257 Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false); 4258 if (vca_result != Reflection::ACCESS_OK) { 4259 ResourceMark rm(THREAD); 4260 char* msg = Reflection::verify_class_access_msg(this_klass, 4261 InstanceKlass::cast(super), 4262 vca_result); 4263 4264 // Names are all known to be < 64k so we know this formatted message is not excessively large. 4265 if (msg == nullptr) { 4266 bool same_module = (this_klass->module() == super->module()); 4267 Exceptions::fthrow( 4268 THREAD_AND_LOCATION, 4269 vmSymbols::java_lang_IllegalAccessError(), 4270 "class %s cannot access its %ssuperclass %s (%s%s%s)", 4271 this_klass->external_name(), 4272 super->is_abstract() ? "abstract " : "", 4273 super->external_name(), 4274 (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(), 4275 (same_module) ? "" : "; ", 4276 (same_module) ? "" : super->class_in_module_of_loader()); 4277 } else { 4278 // Add additional message content. 4279 Exceptions::fthrow( 4280 THREAD_AND_LOCATION, 4281 vmSymbols::java_lang_IllegalAccessError(), 4282 "superclass access check failed: %s", 4283 msg); 4284 } 4285 } 4286 } 4287 } 4288 4289 4290 void ClassFileParser::check_super_interface_access(const InstanceKlass* this_klass, TRAPS) { 4291 assert(this_klass != nullptr, "invariant"); 4292 const Array<InstanceKlass*>* const local_interfaces = this_klass->local_interfaces(); 4293 const int lng = local_interfaces->length(); 4294 for (int i = lng - 1; i >= 0; i--) { 4295 InstanceKlass* const k = local_interfaces->at(i); 4296 assert (k != nullptr && k->is_interface(), "invalid interface"); 4297 4298 if (k->is_sealed()) { 4299 stringStream ss; 4300 ResourceMark rm(THREAD); 4301 if (!k->has_as_permitted_subclass(this_klass, ss)) { 4302 classfile_icce_error(ss.as_string(), THREAD); 4303 return; 4304 } 4305 } 4306 4307 Reflection::VerifyClassAccessResults vca_result = 4308 Reflection::verify_class_access(this_klass, k, false); 4309 if (vca_result != Reflection::ACCESS_OK) { 4310 ResourceMark rm(THREAD); 4311 char* msg = Reflection::verify_class_access_msg(this_klass, 4312 k, 4313 vca_result); 4314 4315 // Names are all known to be < 64k so we know this formatted message is not excessively large. 4316 if (msg == nullptr) { 4317 bool same_module = (this_klass->module() == k->module()); 4318 Exceptions::fthrow( 4319 THREAD_AND_LOCATION, 4320 vmSymbols::java_lang_IllegalAccessError(), 4321 "class %s cannot access its superinterface %s (%s%s%s)", 4322 this_klass->external_name(), 4323 k->external_name(), 4324 (same_module) ? this_klass->joint_in_module_of_loader(k) : this_klass->class_in_module_of_loader(), 4325 (same_module) ? "" : "; ", 4326 (same_module) ? "" : k->class_in_module_of_loader()); 4327 return; 4328 } else { 4329 // Add additional message content. 4330 Exceptions::fthrow( 4331 THREAD_AND_LOCATION, 4332 vmSymbols::java_lang_IllegalAccessError(), 4333 "superinterface check failed: %s", 4334 msg); 4335 return; 4336 } 4337 } 4338 } 4339 } 4340 4341 4342 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) { 4343 assert(this_klass != nullptr, "invariant"); 4344 const Array<Method*>* const methods = this_klass->methods(); 4345 const int num_methods = methods->length(); 4346 4347 // go thru each method and check if it overrides a final method 4348 for (int index = 0; index < num_methods; index++) { 4349 const Method* const m = methods->at(index); 4350 4351 // skip private, static, and <init> methods 4352 if ((!m->is_private() && !m->is_static()) && 4353 (m->name() != vmSymbols::object_initializer_name())) { 4354 4355 const Symbol* const name = m->name(); 4356 const Symbol* const signature = m->signature(); 4357 const InstanceKlass* k = this_klass->java_super(); 4358 const Method* super_m = nullptr; 4359 while (k != nullptr) { 4360 // skip supers that don't have final methods. 4361 if (k->has_final_method()) { 4362 // lookup a matching method in the super class hierarchy 4363 super_m = InstanceKlass::cast(k)->lookup_method(name, signature); 4364 if (super_m == nullptr) { 4365 break; // didn't find any match; get out 4366 } 4367 4368 if (super_m->is_final() && !super_m->is_static() && 4369 !super_m->access_flags().is_private()) { 4370 // matching method in super is final, and not static or private 4371 bool can_access = Reflection::verify_member_access(this_klass, 4372 super_m->method_holder(), 4373 super_m->method_holder(), 4374 super_m->access_flags(), 4375 false, false, CHECK); 4376 if (can_access) { 4377 // this class can access super final method and therefore override 4378 ResourceMark rm(THREAD); 4379 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), 4380 err_msg("class %s overrides final method %s.%s%s", 4381 this_klass->external_name(), 4382 super_m->method_holder()->external_name(), 4383 name->as_C_string(), 4384 signature->as_C_string())); 4385 } 4386 } 4387 4388 // continue to look from super_m's holder's super. 4389 k = super_m->method_holder()->java_super(); 4390 continue; 4391 } 4392 4393 k = k->java_super(); 4394 } 4395 } 4396 } 4397 } 4398 4399 4400 // assumes that this_klass is an interface 4401 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) { 4402 assert(this_klass != nullptr, "invariant"); 4403 assert(this_klass->is_interface(), "not an interface"); 4404 const Array<Method*>* methods = this_klass->methods(); 4405 const int num_methods = methods->length(); 4406 4407 for (int index = 0; index < num_methods; index++) { 4408 const Method* const m = methods->at(index); 4409 // if m is static and not the init method, throw a verify error 4410 if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) { 4411 ResourceMark rm(THREAD); 4412 4413 // Names are all known to be < 64k so we know this formatted message is not excessively large. 4414 Exceptions::fthrow( 4415 THREAD_AND_LOCATION, 4416 vmSymbols::java_lang_VerifyError(), 4417 "Illegal static method %s in interface %s", 4418 m->name()->as_C_string(), 4419 this_klass->external_name() 4420 ); 4421 return; 4422 } 4423 } 4424 } 4425 4426 // utility methods for format checking 4427 4428 void ClassFileParser::verify_legal_class_modifiers(jint flags, const char* name, bool is_Object, TRAPS) const { 4429 const bool is_module = (flags & JVM_ACC_MODULE) != 0; 4430 const bool is_inner_class = name != nullptr; 4431 assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set"); 4432 if (is_module) { 4433 ResourceMark rm(THREAD); 4434 // Names are all known to be < 64k so we know this formatted message is not excessively large. 4435 Exceptions::fthrow( 4436 THREAD_AND_LOCATION, 4437 vmSymbols::java_lang_NoClassDefFoundError(), 4438 "%s is not a class because access_flag ACC_MODULE is set", 4439 _class_name->as_C_string()); 4440 return; 4441 } 4442 4443 if (!_need_verify) { return; } 4444 4445 const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0; 4446 const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0; 4447 const bool is_final = (flags & JVM_ACC_FINAL) != 0; 4448 const bool is_identity = (flags & JVM_ACC_IDENTITY) != 0; 4449 const bool is_enum = (flags & JVM_ACC_ENUM) != 0; 4450 const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0; 4451 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION; 4452 const bool valid_value_class = is_identity || is_interface || 4453 (supports_inline_types() && (!is_identity && (is_abstract || is_final))); 4454 4455 if ((is_abstract && is_final) || 4456 (is_interface && !is_abstract) || 4457 (is_interface && major_gte_1_5 && (is_identity || is_enum)) || // ACC_SUPER (now ACC_IDENTITY) was illegal for interfaces 4458 (!is_interface && major_gte_1_5 && is_annotation) || 4459 (!valid_value_class)) { 4460 ResourceMark rm(THREAD); 4461 const char* class_note = ""; 4462 if (!valid_value_class) { 4463 class_note = " (a value class must be final or else abstract)"; 4464 } 4465 if (name == nullptr) { // Not an inner class 4466 Exceptions::fthrow( 4467 THREAD_AND_LOCATION, 4468 vmSymbols::java_lang_ClassFormatError(), 4469 "Illegal class modifiers in class %s%s: 0x%X", 4470 _class_name->as_C_string(), class_note, flags 4471 ); 4472 return; 4473 } else { 4474 // Names are all known to be < 64k so we know this formatted message is not excessively large. 4475 Exceptions::fthrow( 4476 THREAD_AND_LOCATION, 4477 vmSymbols::java_lang_ClassFormatError(), 4478 "Illegal class modifiers in declaration of inner class %s%s of class %s: 0x%X", 4479 name, class_note, _class_name->as_C_string(), flags 4480 ); 4481 return; 4482 } 4483 } 4484 } 4485 4486 static bool has_illegal_visibility(jint flags) { 4487 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0; 4488 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0; 4489 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0; 4490 4491 return ((is_public && is_protected) || 4492 (is_public && is_private) || 4493 (is_protected && is_private)); 4494 } 4495 4496 // A legal major_version.minor_version must be one of the following: 4497 // 4498 // Major_version >= 45 and major_version < 56, any minor_version. 4499 // Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0. 4500 // Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present. 4501 // 4502 void ClassFileParser::verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){ 4503 ResourceMark rm(THREAD); 4504 const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION; 4505 if (major < JAVA_MIN_SUPPORTED_VERSION) { 4506 classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid major version", 4507 class_name, major, minor, THREAD); 4508 return; 4509 } 4510 4511 if (major > max_version) { 4512 // Names are all known to be < 64k so we know this formatted message is not excessively large. 4513 Exceptions::fthrow( 4514 THREAD_AND_LOCATION, 4515 vmSymbols::java_lang_UnsupportedClassVersionError(), 4516 "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), " 4517 "this version of the Java Runtime only recognizes class file versions up to %u.0", 4518 class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION); 4519 return; 4520 } 4521 4522 if (major < JAVA_12_VERSION || minor == 0) { 4523 return; 4524 } 4525 4526 if (minor == JAVA_PREVIEW_MINOR_VERSION) { 4527 if (major != max_version) { 4528 // Names are all known to be < 64k so we know this formatted message is not excessively large. 4529 Exceptions::fthrow( 4530 THREAD_AND_LOCATION, 4531 vmSymbols::java_lang_UnsupportedClassVersionError(), 4532 "%s (class file version %u.%u) was compiled with preview features that are unsupported. " 4533 "This version of the Java Runtime only recognizes preview features for class file version %u.%u", 4534 class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION); 4535 return; 4536 } 4537 4538 if (!Arguments::enable_preview()) { 4539 classfile_ucve_error("Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'", 4540 class_name, major, minor, THREAD); 4541 return; 4542 } 4543 4544 } else { // minor != JAVA_PREVIEW_MINOR_VERSION 4545 classfile_ucve_error("%s (class file version %u.%u) was compiled with an invalid non-zero minor version", 4546 class_name, major, minor, THREAD); 4547 } 4548 } 4549 4550 void ClassFileParser:: verify_legal_field_modifiers(jint flags, 4551 AccessFlags class_access_flags, 4552 TRAPS) const { 4553 if (!_need_verify) { return; } 4554 4555 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0; 4556 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0; 4557 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0; 4558 const bool is_static = (flags & JVM_ACC_STATIC) != 0; 4559 const bool is_final = (flags & JVM_ACC_FINAL) != 0; 4560 const bool is_volatile = (flags & JVM_ACC_VOLATILE) != 0; 4561 const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0; 4562 const bool is_enum = (flags & JVM_ACC_ENUM) != 0; 4563 const bool is_strict = (flags & JVM_ACC_STRICT) != 0; 4564 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION; 4565 4566 const bool is_interface = class_access_flags.is_interface(); 4567 const bool is_identity_class = class_access_flags.is_identity_class(); 4568 4569 bool is_illegal = false; 4570 const char* error_msg = ""; 4571 4572 // There is some overlap in the checks that apply, for example interface fields 4573 // must be static, static fields can't be strict, and therefore interfaces can't 4574 // have strict fields. So we don't have to check every possible invalid combination 4575 // individually as long as all are covered. Once we have found an illegal combination 4576 // we can stop checking. 4577 4578 if (supports_inline_types()) { 4579 if (is_strict && is_static) { 4580 is_illegal = true; 4581 error_msg = "field cannot be strict and static"; 4582 } 4583 else if (is_strict && !is_final) { 4584 is_illegal = true; 4585 error_msg = "strict field must be final"; 4586 } 4587 } 4588 4589 if (!is_illegal) { 4590 if (is_interface) { 4591 if (!is_public || !is_static || !is_final || is_private || 4592 is_protected || is_volatile || is_transient || 4593 (major_gte_1_5 && is_enum)) { 4594 is_illegal = true; 4595 error_msg = "interface fields must be public, static and final, and may be synthetic"; 4596 } 4597 } else { // not interface 4598 if (has_illegal_visibility(flags)) { 4599 is_illegal = true; 4600 error_msg = "invalid visibility flags for class field"; 4601 } else if (is_final && is_volatile) { 4602 is_illegal = true; 4603 error_msg = "fields cannot be final and volatile"; 4604 } else if (supports_inline_types()) { 4605 if (!is_identity_class && !is_static && !is_strict) { 4606 is_illegal = true; 4607 error_msg = "value class fields must be either strict or static"; 4608 } 4609 } 4610 } 4611 } 4612 4613 if (is_illegal) { 4614 ResourceMark rm(THREAD); 4615 // Names are all known to be < 64k so we know this formatted message is not excessively large. 4616 Exceptions::fthrow( 4617 THREAD_AND_LOCATION, 4618 vmSymbols::java_lang_ClassFormatError(), 4619 "Illegal field modifiers (%s) in class %s: 0x%X", 4620 error_msg, _class_name->as_C_string(), flags); 4621 return; 4622 } 4623 } 4624 4625 void ClassFileParser::verify_legal_method_modifiers(jint flags, 4626 AccessFlags class_access_flags, 4627 const Symbol* name, 4628 TRAPS) const { 4629 if (!_need_verify) { return; } 4630 4631 const bool is_public = (flags & JVM_ACC_PUBLIC) != 0; 4632 const bool is_private = (flags & JVM_ACC_PRIVATE) != 0; 4633 const bool is_static = (flags & JVM_ACC_STATIC) != 0; 4634 const bool is_final = (flags & JVM_ACC_FINAL) != 0; 4635 const bool is_native = (flags & JVM_ACC_NATIVE) != 0; 4636 const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0; 4637 const bool is_bridge = (flags & JVM_ACC_BRIDGE) != 0; 4638 const bool is_strict = (flags & JVM_ACC_STRICT) != 0; 4639 const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0; 4640 const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0; 4641 const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION; 4642 const bool major_gte_8 = _major_version >= JAVA_8_VERSION; 4643 const bool major_gte_17 = _major_version >= JAVA_17_VERSION; 4644 const bool is_initializer = (name == vmSymbols::object_initializer_name()); 4645 // LW401 CR required: removal of value factories support 4646 const bool is_interface = class_access_flags.is_interface(); 4647 const bool is_identity_class = class_access_flags.is_identity_class(); 4648 const bool is_abstract_class = class_access_flags.is_abstract(); 4649 4650 bool is_illegal = false; 4651 4652 const char* class_note = ""; 4653 if (is_interface) { 4654 if (major_gte_8) { 4655 // Class file version is JAVA_8_VERSION or later Methods of 4656 // interfaces may set any of the flags except ACC_PROTECTED, 4657 // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must 4658 // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set. 4659 if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */ 4660 (is_native || is_protected || is_final || is_synchronized) || 4661 // If a specific method of a class or interface has its 4662 // ACC_ABSTRACT flag set, it must not have any of its 4663 // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC, 4664 // ACC_STRICT, or ACC_SYNCHRONIZED flags set. No need to 4665 // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as 4666 // those flags are illegal irrespective of ACC_ABSTRACT being set or not. 4667 (is_abstract && (is_private || is_static || (!major_gte_17 && is_strict)))) { 4668 is_illegal = true; 4669 } 4670 } else if (major_gte_1_5) { 4671 // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION) 4672 if (!is_public || is_private || is_protected || is_static || is_final || 4673 is_synchronized || is_native || !is_abstract || is_strict) { 4674 is_illegal = true; 4675 } 4676 } else { 4677 // Class file version is pre-JAVA_1_5_VERSION 4678 if (!is_public || is_static || is_final || is_native || !is_abstract) { 4679 is_illegal = true; 4680 } 4681 } 4682 } else { // not interface 4683 if (has_illegal_visibility(flags)) { 4684 is_illegal = true; 4685 } else { 4686 if (is_initializer) { 4687 if (is_static || is_final || is_synchronized || is_native || 4688 is_abstract || (major_gte_1_5 && is_bridge)) { 4689 is_illegal = true; 4690 } 4691 } else { // not initializer 4692 if (!is_identity_class && is_synchronized && !is_static) { 4693 is_illegal = true; 4694 class_note = " (not an identity class)"; 4695 } else { 4696 if (is_abstract) { 4697 if ((is_final || is_native || is_private || is_static || 4698 (major_gte_1_5 && (is_synchronized || (!major_gte_17 && is_strict))))) { 4699 is_illegal = true; 4700 } 4701 } 4702 } 4703 } 4704 } 4705 } 4706 4707 if (is_illegal) { 4708 ResourceMark rm(THREAD); 4709 // Names are all known to be < 64k so we know this formatted message is not excessively large. 4710 Exceptions::fthrow( 4711 THREAD_AND_LOCATION, 4712 vmSymbols::java_lang_ClassFormatError(), 4713 "Method %s in class %s%s has illegal modifiers: 0x%X", 4714 name->as_C_string(), _class_name->as_C_string(), 4715 class_note, flags); 4716 return; 4717 } 4718 } 4719 4720 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer, 4721 int length, 4722 TRAPS) const { 4723 assert(_need_verify, "only called when _need_verify is true"); 4724 // Note: 0 <= length < 64K, as it comes from a u2 entry in the CP. 4725 if (!UTF8::is_legal_utf8(buffer, static_cast<size_t>(length), _major_version <= 47)) { 4726 classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", THREAD); 4727 } 4728 } 4729 4730 // Unqualified names may not contain the characters '.', ';', '[', or '/'. 4731 // In class names, '/' separates unqualified names. This is verified in this function also. 4732 // Method names also may not contain the characters '<' or '>', unless <init> 4733 // or <clinit>. Note that method names may not be <init> or <clinit> in this 4734 // method. Because these names have been checked as special cases before 4735 // calling this method in verify_legal_method_name. 4736 // 4737 // This method is also called from the modular system APIs in modules.cpp 4738 // to verify the validity of module and package names. 4739 bool ClassFileParser::verify_unqualified_name(const char* name, 4740 unsigned int length, 4741 int type) { 4742 if (length == 0) return false; // Must have at least one char. 4743 for (const char* p = name; p != name + length; p++) { 4744 switch(*p) { 4745 case JVM_SIGNATURE_DOT: 4746 case JVM_SIGNATURE_ENDCLASS: 4747 case JVM_SIGNATURE_ARRAY: 4748 // do not permit '.', ';', or '[' 4749 return false; 4750 case JVM_SIGNATURE_SLASH: 4751 // check for '//' or leading or trailing '/' which are not legal 4752 // unqualified name must not be empty 4753 if (type == ClassFileParser::LegalClass) { 4754 if (p == name || p+1 >= name+length || 4755 *(p+1) == JVM_SIGNATURE_SLASH) { 4756 return false; 4757 } 4758 } else { 4759 return false; // do not permit '/' unless it's class name 4760 } 4761 break; 4762 case JVM_SIGNATURE_SPECIAL: 4763 case JVM_SIGNATURE_ENDSPECIAL: 4764 // do not permit '<' or '>' in method names 4765 if (type == ClassFileParser::LegalMethod) { 4766 return false; 4767 } 4768 } 4769 } 4770 return true; 4771 } 4772 4773 bool ClassFileParser::is_class_in_loadable_descriptors_attribute(Symbol *klass) { 4774 if (_loadable_descriptors == nullptr) return false; 4775 for (int i = 0; i < _loadable_descriptors->length(); i++) { 4776 Symbol* class_name = _cp->symbol_at(_loadable_descriptors->at(i)); 4777 if (class_name == klass) return true; 4778 } 4779 return false; 4780 } 4781 4782 // Take pointer to a UTF8 byte string (not NUL-terminated). 4783 // Skip over the longest part of the string that could 4784 // be taken as a fieldname. Allow non-trailing '/'s if slash_ok is true. 4785 // Return a pointer to just past the fieldname. 4786 // Return null if no fieldname at all was found, or in the case of slash_ok 4787 // being true, we saw consecutive slashes (meaning we were looking for a 4788 // qualified path but found something that was badly-formed). 4789 static const char* skip_over_field_name(const char* const name, 4790 bool slash_ok, 4791 unsigned int length) { 4792 const char* p; 4793 jboolean last_is_slash = false; 4794 jboolean not_first_ch = false; 4795 4796 for (p = name; p != name + length; not_first_ch = true) { 4797 const char* old_p = p; 4798 jchar ch = *p; 4799 if (ch < 128) { 4800 p++; 4801 // quick check for ascii 4802 if ((ch >= 'a' && ch <= 'z') || 4803 (ch >= 'A' && ch <= 'Z') || 4804 (ch == '_' || ch == '$') || 4805 (not_first_ch && ch >= '0' && ch <= '9')) { 4806 last_is_slash = false; 4807 continue; 4808 } 4809 if (slash_ok && ch == JVM_SIGNATURE_SLASH) { 4810 if (last_is_slash) { 4811 return nullptr; // Don't permit consecutive slashes 4812 } 4813 last_is_slash = true; 4814 continue; 4815 } 4816 } 4817 else { 4818 jint unicode_ch; 4819 char* tmp_p = UTF8::next_character(p, &unicode_ch); 4820 p = tmp_p; 4821 last_is_slash = false; 4822 // Check if ch is Java identifier start or is Java identifier part 4823 // 4672820: call java.lang.Character methods directly without generating separate tables. 4824 EXCEPTION_MARK; 4825 // return value 4826 JavaValue result(T_BOOLEAN); 4827 // Set up the arguments to isJavaIdentifierStart or isJavaIdentifierPart 4828 JavaCallArguments args; 4829 args.push_int(unicode_ch); 4830 4831 if (not_first_ch) { 4832 // public static boolean isJavaIdentifierPart(char ch); 4833 JavaCalls::call_static(&result, 4834 vmClasses::Character_klass(), 4835 vmSymbols::isJavaIdentifierPart_name(), 4836 vmSymbols::int_bool_signature(), 4837 &args, 4838 THREAD); 4839 } else { 4840 // public static boolean isJavaIdentifierStart(char ch); 4841 JavaCalls::call_static(&result, 4842 vmClasses::Character_klass(), 4843 vmSymbols::isJavaIdentifierStart_name(), 4844 vmSymbols::int_bool_signature(), 4845 &args, 4846 THREAD); 4847 } 4848 if (HAS_PENDING_EXCEPTION) { 4849 CLEAR_PENDING_EXCEPTION; 4850 return nullptr; 4851 } 4852 if(result.get_jboolean()) { 4853 continue; 4854 } 4855 } 4856 return (not_first_ch) ? old_p : nullptr; 4857 } 4858 return (not_first_ch && !last_is_slash) ? p : nullptr; 4859 } 4860 4861 // Take pointer to a UTF8 byte string (not NUL-terminated). 4862 // Skip over the longest part of the string that could 4863 // be taken as a field signature. Allow "void" if void_ok. 4864 // Return a pointer to just past the signature. 4865 // Return null if no legal signature is found. 4866 const char* ClassFileParser::skip_over_field_signature(const char* signature, 4867 bool void_ok, 4868 unsigned int length, 4869 TRAPS) const { 4870 unsigned int array_dim = 0; 4871 while (length > 0) { 4872 switch (signature[0]) { 4873 case JVM_SIGNATURE_VOID: if (!void_ok) { return nullptr; } 4874 case JVM_SIGNATURE_BOOLEAN: 4875 case JVM_SIGNATURE_BYTE: 4876 case JVM_SIGNATURE_CHAR: 4877 case JVM_SIGNATURE_SHORT: 4878 case JVM_SIGNATURE_INT: 4879 case JVM_SIGNATURE_FLOAT: 4880 case JVM_SIGNATURE_LONG: 4881 case JVM_SIGNATURE_DOUBLE: 4882 return signature + 1; 4883 case JVM_SIGNATURE_CLASS: 4884 { 4885 if (_major_version < JAVA_1_5_VERSION) { 4886 // Skip over the class name if one is there 4887 const char* const p = skip_over_field_name(signature + 1, true, --length); 4888 4889 // The next character better be a semicolon 4890 if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) { 4891 return p + 1; 4892 } 4893 } 4894 else { 4895 // Skip leading 'L' or 'Q' and ignore first appearance of ';' 4896 signature++; 4897 const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1); 4898 // Format check signature 4899 if (c != nullptr) { 4900 int newlen = pointer_delta_as_int(c, (char*) signature); 4901 bool legal = verify_unqualified_name(signature, newlen, LegalClass); 4902 if (!legal) { 4903 classfile_parse_error("Class name is empty or contains illegal character " 4904 "in descriptor in class file %s", 4905 THREAD); 4906 return nullptr; 4907 } 4908 return signature + newlen + 1; 4909 } 4910 } 4911 return nullptr; 4912 } 4913 case JVM_SIGNATURE_ARRAY: 4914 array_dim++; 4915 if (array_dim > 255) { 4916 // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions. 4917 classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", THREAD); 4918 return nullptr; 4919 } 4920 // The rest of what's there better be a legal signature 4921 signature++; 4922 length--; 4923 void_ok = false; 4924 break; 4925 default: 4926 return nullptr; 4927 } 4928 } 4929 return nullptr; 4930 } 4931 4932 // Checks if name is a legal class name. 4933 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const { 4934 if (!_need_verify) { return; } 4935 4936 assert(name->refcount() > 0, "symbol must be kept alive"); 4937 char* bytes = (char*)name->bytes(); 4938 unsigned int length = name->utf8_length(); 4939 bool legal = false; 4940 4941 if (length > 0) { 4942 const char* p; 4943 if (bytes[0] == JVM_SIGNATURE_ARRAY) { 4944 p = skip_over_field_signature(bytes, false, length, CHECK); 4945 legal = (p != nullptr) && ((p - bytes) == (int)length); 4946 } else if (_major_version < JAVA_1_5_VERSION) { 4947 if (bytes[0] != JVM_SIGNATURE_SPECIAL) { 4948 p = skip_over_field_name(bytes, true, length); 4949 legal = (p != nullptr) && ((p - bytes) == (int)length); 4950 } 4951 } else if ((_major_version >= CONSTANT_CLASS_DESCRIPTORS || _class_name->starts_with("jdk/internal/reflect/")) 4952 && bytes[length - 1] == ';' ) { 4953 // Support for L...; descriptors 4954 legal = verify_unqualified_name(bytes + 1, length - 2, LegalClass); 4955 } else { 4956 // 4900761: relax the constraints based on JSR202 spec 4957 // Class names may be drawn from the entire Unicode character set. 4958 // Identifiers between '/' must be unqualified names. 4959 // The utf8 string has been verified when parsing cpool entries. 4960 legal = verify_unqualified_name(bytes, length, LegalClass); 4961 } 4962 } 4963 if (!legal) { 4964 ResourceMark rm(THREAD); 4965 assert(_class_name != nullptr, "invariant"); 4966 // Names are all known to be < 64k so we know this formatted message is not excessively large. 4967 Exceptions::fthrow( 4968 THREAD_AND_LOCATION, 4969 vmSymbols::java_lang_ClassFormatError(), 4970 "Illegal class name \"%.*s\" in class file %s", length, bytes, 4971 _class_name->as_C_string() 4972 ); 4973 return; 4974 } 4975 } 4976 4977 // Checks if name is a legal field name. 4978 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const { 4979 if (!_need_verify) { return; } 4980 4981 char* bytes = (char*)name->bytes(); 4982 unsigned int length = name->utf8_length(); 4983 bool legal = false; 4984 4985 if (length > 0) { 4986 if (_major_version < JAVA_1_5_VERSION) { 4987 if (bytes[0] != JVM_SIGNATURE_SPECIAL) { 4988 const char* p = skip_over_field_name(bytes, false, length); 4989 legal = (p != nullptr) && ((p - bytes) == (int)length); 4990 } 4991 } else { 4992 // 4881221: relax the constraints based on JSR202 spec 4993 legal = verify_unqualified_name(bytes, length, LegalField); 4994 } 4995 } 4996 4997 if (!legal) { 4998 ResourceMark rm(THREAD); 4999 assert(_class_name != nullptr, "invariant"); 5000 // Names are all known to be < 64k so we know this formatted message is not excessively large. 5001 Exceptions::fthrow( 5002 THREAD_AND_LOCATION, 5003 vmSymbols::java_lang_ClassFormatError(), 5004 "Illegal field name \"%.*s\" in class %s", length, bytes, 5005 _class_name->as_C_string() 5006 ); 5007 return; 5008 } 5009 } 5010 5011 // Checks if name is a legal method name. 5012 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const { 5013 if (!_need_verify) { return; } 5014 5015 assert(name != nullptr, "method name is null"); 5016 char* bytes = (char*)name->bytes(); 5017 unsigned int length = name->utf8_length(); 5018 bool legal = false; 5019 5020 if (length > 0) { 5021 if (bytes[0] == JVM_SIGNATURE_SPECIAL) { 5022 if (name == vmSymbols::object_initializer_name() || 5023 name == vmSymbols::class_initializer_name()) { 5024 legal = true; 5025 } 5026 } else if (_major_version < JAVA_1_5_VERSION) { 5027 const char* p; 5028 p = skip_over_field_name(bytes, false, length); 5029 legal = (p != nullptr) && ((p - bytes) == (int)length); 5030 } else { 5031 // 4881221: relax the constraints based on JSR202 spec 5032 legal = verify_unqualified_name(bytes, length, LegalMethod); 5033 } 5034 } 5035 5036 if (!legal) { 5037 ResourceMark rm(THREAD); 5038 assert(_class_name != nullptr, "invariant"); 5039 // Names are all known to be < 64k so we know this formatted message is not excessively large. 5040 Exceptions::fthrow( 5041 THREAD_AND_LOCATION, 5042 vmSymbols::java_lang_ClassFormatError(), 5043 "Illegal method name \"%.*s\" in class %s", length, bytes, 5044 _class_name->as_C_string() 5045 ); 5046 return; 5047 } 5048 } 5049 5050 bool ClassFileParser::legal_field_signature(const Symbol* signature, TRAPS) const { 5051 const char* const bytes = (const char*)signature->bytes(); 5052 const unsigned int length = signature->utf8_length(); 5053 const char* const p = skip_over_field_signature(bytes, false, length, CHECK_false); 5054 5055 if (p == nullptr || (p - bytes) != (int)length) { 5056 return false; 5057 } 5058 return true; 5059 } 5060 5061 // Checks if signature is a legal field signature. 5062 void ClassFileParser::verify_legal_field_signature(const Symbol* name, 5063 const Symbol* signature, 5064 TRAPS) const { 5065 if (!_need_verify) { return; } 5066 5067 const char* const bytes = (const char*)signature->bytes(); 5068 const unsigned int length = signature->utf8_length(); 5069 const char* const p = skip_over_field_signature(bytes, false, length, CHECK); 5070 5071 if (p == nullptr || (p - bytes) != (int)length) { 5072 throwIllegalSignature("Field", name, signature, CHECK); 5073 } 5074 } 5075 5076 // Check that the signature is compatible with the method name. For example, 5077 // check that <init> has a void signature. 5078 void ClassFileParser::verify_legal_name_with_signature(const Symbol* name, 5079 const Symbol* signature, 5080 TRAPS) const { 5081 if (!_need_verify) { 5082 return; 5083 } 5084 5085 // Class initializers cannot have args for class format version >= 51. 5086 if (name == vmSymbols::class_initializer_name() && 5087 signature != vmSymbols::void_method_signature() && 5088 _major_version >= JAVA_7_VERSION) { 5089 throwIllegalSignature("Method", name, signature, THREAD); 5090 return; 5091 } 5092 5093 int sig_length = signature->utf8_length(); 5094 if (name->utf8_length() > 0 && 5095 name->char_at(0) == JVM_SIGNATURE_SPECIAL && 5096 sig_length > 0 && 5097 signature->char_at(sig_length - 1) != JVM_SIGNATURE_VOID) { 5098 throwIllegalSignature("Method", name, signature, THREAD); 5099 } 5100 } 5101 5102 // Checks if signature is a legal method signature. 5103 // Returns number of parameters 5104 int ClassFileParser::verify_legal_method_signature(const Symbol* name, 5105 const Symbol* signature, 5106 TRAPS) const { 5107 if (!_need_verify) { 5108 // make sure caller's args_size will be less than 0 even for non-static 5109 // method so it will be recomputed in compute_size_of_parameters(). 5110 return -2; 5111 } 5112 5113 unsigned int args_size = 0; 5114 const char* p = (const char*)signature->bytes(); 5115 unsigned int length = signature->utf8_length(); 5116 const char* nextp; 5117 5118 // The first character must be a '(' 5119 if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) { 5120 length--; 5121 // Skip over legal field signatures 5122 nextp = skip_over_field_signature(p, false, length, CHECK_0); 5123 while ((length > 0) && (nextp != nullptr)) { 5124 args_size++; 5125 if (p[0] == 'J' || p[0] == 'D') { 5126 args_size++; 5127 } 5128 length -= pointer_delta_as_int(nextp, p); 5129 p = nextp; 5130 nextp = skip_over_field_signature(p, false, length, CHECK_0); 5131 } 5132 // The first non-signature thing better be a ')' 5133 if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) { 5134 length--; 5135 // Now we better just have a return value 5136 nextp = skip_over_field_signature(p, true, length, CHECK_0); 5137 if (nextp && ((int)length == (nextp - p))) { 5138 return args_size; 5139 } 5140 } 5141 } 5142 // Report error 5143 throwIllegalSignature("Method", name, signature, THREAD); 5144 return 0; 5145 } 5146 5147 int ClassFileParser::static_field_size() const { 5148 assert(_layout_info != nullptr, "invariant"); 5149 return _layout_info->_static_field_size; 5150 } 5151 5152 int ClassFileParser::total_oop_map_count() const { 5153 assert(_layout_info != nullptr, "invariant"); 5154 return _layout_info->oop_map_blocks->_nonstatic_oop_map_count; 5155 } 5156 5157 jint ClassFileParser::layout_size() const { 5158 assert(_layout_info != nullptr, "invariant"); 5159 return _layout_info->_instance_size; 5160 } 5161 5162 static void check_methods_for_intrinsics(const InstanceKlass* ik, 5163 const Array<Method*>* methods) { 5164 assert(ik != nullptr, "invariant"); 5165 assert(methods != nullptr, "invariant"); 5166 5167 // Set up Method*::intrinsic_id as soon as we know the names of methods. 5168 // (We used to do this lazily, but now we query it in Rewriter, 5169 // which is eagerly done for every method, so we might as well do it now, 5170 // when everything is fresh in memory.) 5171 const vmSymbolID klass_id = Method::klass_id_for_intrinsics(ik); 5172 5173 if (klass_id != vmSymbolID::NO_SID) { 5174 for (int j = 0; j < methods->length(); ++j) { 5175 Method* method = methods->at(j); 5176 method->init_intrinsic_id(klass_id); 5177 5178 if (CheckIntrinsics) { 5179 // Check if an intrinsic is defined for method 'method', 5180 // but the method is not annotated with @IntrinsicCandidate. 5181 if (method->intrinsic_id() != vmIntrinsics::_none && 5182 !method->intrinsic_candidate()) { 5183 tty->print("Compiler intrinsic is defined for method [%s], " 5184 "but the method is not annotated with @IntrinsicCandidate.%s", 5185 method->name_and_sig_as_C_string(), 5186 NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.") 5187 ); 5188 tty->cr(); 5189 DEBUG_ONLY(vm_exit(1)); 5190 } 5191 // Check is the method 'method' is annotated with @IntrinsicCandidate, 5192 // but there is no intrinsic available for it. 5193 if (method->intrinsic_candidate() && 5194 method->intrinsic_id() == vmIntrinsics::_none) { 5195 tty->print("Method [%s] is annotated with @IntrinsicCandidate, " 5196 "but no compiler intrinsic is defined for the method.%s", 5197 method->name_and_sig_as_C_string(), 5198 NOT_DEBUG("") DEBUG_ONLY(" Exiting.") 5199 ); 5200 tty->cr(); 5201 DEBUG_ONLY(vm_exit(1)); 5202 } 5203 } 5204 } // end for 5205 5206 #ifdef ASSERT 5207 if (CheckIntrinsics) { 5208 // Check for orphan methods in the current class. A method m 5209 // of a class C is orphan if an intrinsic is defined for method m, 5210 // but class C does not declare m. 5211 // The check is potentially expensive, therefore it is available 5212 // only in debug builds. 5213 5214 for (auto id : EnumRange<vmIntrinsicID>{}) { 5215 if (vmIntrinsics::_compiledLambdaForm == id) { 5216 // The _compiledLamdbdaForm intrinsic is a special marker for bytecode 5217 // generated for the JVM from a LambdaForm and therefore no method 5218 // is defined for it. 5219 continue; 5220 } 5221 if (vmIntrinsics::_blackhole == id) { 5222 // The _blackhole intrinsic is a special marker. No explicit method 5223 // is defined for it. 5224 continue; 5225 } 5226 5227 if (vmIntrinsics::class_for(id) == klass_id) { 5228 // Check if the current class contains a method with the same 5229 // name, flags, signature. 5230 bool match = false; 5231 for (int j = 0; j < methods->length(); ++j) { 5232 const Method* method = methods->at(j); 5233 if (method->intrinsic_id() == id) { 5234 match = true; 5235 break; 5236 } 5237 } 5238 5239 if (!match) { 5240 char buf[1000]; 5241 tty->print("Compiler intrinsic is defined for method [%s], " 5242 "but the method is not available in class [%s].%s", 5243 vmIntrinsics::short_name_as_C_string(id, buf, sizeof(buf)), 5244 ik->name()->as_C_string(), 5245 NOT_DEBUG("") DEBUG_ONLY(" Exiting.") 5246 ); 5247 tty->cr(); 5248 DEBUG_ONLY(vm_exit(1)); 5249 } 5250 } 5251 } // end for 5252 } // CheckIntrinsics 5253 #endif // ASSERT 5254 } 5255 } 5256 5257 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook, 5258 const ClassInstanceInfo& cl_inst_info, 5259 TRAPS) { 5260 if (_klass != nullptr) { 5261 return _klass; 5262 } 5263 5264 InstanceKlass* const ik = 5265 InstanceKlass::allocate_instance_klass(*this, CHECK_NULL); 5266 5267 if (is_hidden()) { 5268 mangle_hidden_class_name(ik); 5269 } 5270 5271 fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL); 5272 5273 assert(_klass == ik, "invariant"); 5274 return ik; 5275 } 5276 5277 void ClassFileParser::fill_instance_klass(InstanceKlass* ik, 5278 bool changed_by_loadhook, 5279 const ClassInstanceInfo& cl_inst_info, 5280 TRAPS) { 5281 assert(ik != nullptr, "invariant"); 5282 5283 // Set name and CLD before adding to CLD 5284 ik->set_class_loader_data(_loader_data); 5285 ik->set_name(_class_name); 5286 5287 // Add all classes to our internal class loader list here, 5288 // including classes in the bootstrap (null) class loader. 5289 const bool publicize = !is_internal(); 5290 5291 _loader_data->add_class(ik, publicize); 5292 5293 set_klass_to_deallocate(ik); 5294 5295 assert(_layout_info != nullptr, "invariant"); 5296 assert(ik->static_field_size() == _layout_info->_static_field_size, "sanity"); 5297 assert(ik->nonstatic_oop_map_count() == _layout_info->oop_map_blocks->_nonstatic_oop_map_count, 5298 "sanity"); 5299 5300 assert(ik->is_instance_klass(), "sanity"); 5301 assert(ik->size_helper() == _layout_info->_instance_size, "sanity"); 5302 5303 // Fill in information already parsed 5304 ik->set_should_verify_class(_need_verify); 5305 5306 // Not yet: supers are done below to support the new subtype-checking fields 5307 ik->set_nonstatic_field_size(_layout_info->_nonstatic_field_size); 5308 ik->set_has_nonstatic_fields(_layout_info->_has_nonstatic_fields); 5309 5310 if (_layout_info->_is_naturally_atomic) { 5311 ik->set_is_naturally_atomic(); 5312 } 5313 5314 if (_layout_info->_must_be_atomic) { 5315 ik->set_must_be_atomic(); 5316 } 5317 if (_is_implicitly_constructible) { 5318 ik->set_is_implicitly_constructible(); 5319 } 5320 5321 ik->set_static_oop_field_count(_static_oop_count); 5322 5323 // this transfers ownership of a lot of arrays from 5324 // the parser onto the InstanceKlass* 5325 apply_parsed_class_metadata(ik, _java_fields_count); 5326 if (ik->is_inline_klass()) { 5327 InlineKlass::cast(ik)->init_fixed_block(); 5328 } 5329 5330 // can only set dynamic nest-host after static nest information is set 5331 if (cl_inst_info.dynamic_nest_host() != nullptr) { 5332 ik->set_nest_host(cl_inst_info.dynamic_nest_host()); 5333 } 5334 5335 // note that is not safe to use the fields in the parser from this point on 5336 assert(nullptr == _cp, "invariant"); 5337 assert(nullptr == _fieldinfo_stream, "invariant"); 5338 assert(nullptr == _fields_status, "invariant"); 5339 assert(nullptr == _methods, "invariant"); 5340 assert(nullptr == _inner_classes, "invariant"); 5341 assert(nullptr == _nest_members, "invariant"); 5342 assert(nullptr == _loadable_descriptors, "invariant"); 5343 assert(nullptr == _combined_annotations, "invariant"); 5344 assert(nullptr == _record_components, "invariant"); 5345 assert(nullptr == _permitted_subclasses, "invariant"); 5346 assert(nullptr == _inline_layout_info_array, "invariant"); 5347 5348 if (_has_localvariable_table) { 5349 ik->set_has_localvariable_table(true); 5350 } 5351 5352 if (_has_final_method) { 5353 ik->set_has_final_method(); 5354 } 5355 5356 ik->copy_method_ordering(_method_ordering, CHECK); 5357 // The InstanceKlass::_methods_jmethod_ids cache 5358 // is managed on the assumption that the initial cache 5359 // size is equal to the number of methods in the class. If 5360 // that changes, then InstanceKlass::idnum_can_increment() 5361 // has to be changed accordingly. 5362 ik->set_initial_method_idnum(checked_cast<u2>(ik->methods()->length())); 5363 5364 ik->set_this_class_index(_this_class_index); 5365 5366 if (_is_hidden) { 5367 // _this_class_index is a CONSTANT_Class entry that refers to this 5368 // hidden class itself. If this class needs to refer to its own methods 5369 // or fields, it would use a CONSTANT_MethodRef, etc, which would reference 5370 // _this_class_index. However, because this class is hidden (it's 5371 // not stored in SystemDictionary), _this_class_index cannot be resolved 5372 // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup. 5373 // Therefore, we must eagerly resolve _this_class_index now. 5374 ik->constants()->klass_at_put(_this_class_index, ik); 5375 } 5376 5377 ik->set_minor_version(_minor_version); 5378 ik->set_major_version(_major_version); 5379 ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods); 5380 ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods); 5381 5382 assert(!_is_hidden || ik->is_hidden(), "must be set already"); 5383 5384 // Set PackageEntry for this_klass 5385 oop cl = ik->class_loader(); 5386 Handle clh = Handle(THREAD, cl); 5387 ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh()); 5388 ik->set_package(cld, nullptr, CHECK); 5389 5390 const Array<Method*>* const methods = ik->methods(); 5391 assert(methods != nullptr, "invariant"); 5392 const int methods_len = methods->length(); 5393 5394 check_methods_for_intrinsics(ik, methods); 5395 5396 // Fill in field values obtained by parse_classfile_attributes 5397 if (_parsed_annotations->has_any_annotations()) { 5398 _parsed_annotations->apply_to(ik); 5399 } 5400 5401 apply_parsed_class_attributes(ik); 5402 5403 // Miranda methods 5404 if ((_num_miranda_methods > 0) || 5405 // if this class introduced new miranda methods or 5406 (_super_klass != nullptr && _super_klass->has_miranda_methods()) 5407 // super class exists and this class inherited miranda methods 5408 ) { 5409 ik->set_has_miranda_methods(); // then set a flag 5410 } 5411 5412 // Fill in information needed to compute superclasses. 5413 ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK); 5414 ik->set_transitive_interfaces(_transitive_interfaces); 5415 ik->set_local_interfaces(_local_interfaces); 5416 _transitive_interfaces = nullptr; 5417 _local_interfaces = nullptr; 5418 5419 // Initialize itable offset tables 5420 klassItable::setup_itable_offset_table(ik); 5421 5422 // Compute transitive closure of interfaces this class implements 5423 // Do final class setup 5424 OopMapBlocksBuilder* oop_map_blocks = _layout_info->oop_map_blocks; 5425 if (oop_map_blocks->_nonstatic_oop_map_count > 0) { 5426 oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps()); 5427 } 5428 5429 if (_has_contended_fields || _parsed_annotations->is_contended() || 5430 ( _super_klass != nullptr && _super_klass->has_contended_annotations())) { 5431 ik->set_has_contended_annotations(true); 5432 } 5433 5434 // Fill in has_finalizer and layout_helper 5435 set_precomputed_flags(ik); 5436 5437 // check if this class can access its super class 5438 check_super_class_access(ik, CHECK); 5439 5440 // check if this class can access its superinterfaces 5441 check_super_interface_access(ik, CHECK); 5442 5443 // check if this class overrides any final method 5444 check_final_method_override(ik, CHECK); 5445 5446 // reject static interface methods prior to Java 8 5447 if (ik->is_interface() && _major_version < JAVA_8_VERSION) { 5448 check_illegal_static_method(ik, CHECK); 5449 } 5450 5451 // Obtain this_klass' module entry 5452 ModuleEntry* module_entry = ik->module(); 5453 assert(module_entry != nullptr, "module_entry should always be set"); 5454 5455 // Obtain java.lang.Module 5456 Handle module_handle(THREAD, module_entry->module()); 5457 5458 // Allocate mirror and initialize static fields 5459 java_lang_Class::create_mirror(ik, 5460 Handle(THREAD, _loader_data->class_loader()), 5461 module_handle, 5462 _protection_domain, 5463 cl_inst_info.class_data(), 5464 CHECK); 5465 5466 assert(_all_mirandas != nullptr, "invariant"); 5467 5468 // Generate any default methods - default methods are public interface methods 5469 // that have a default implementation. This is new with Java 8. 5470 if (_has_nonstatic_concrete_methods) { 5471 DefaultMethods::generate_default_methods(ik, 5472 _all_mirandas, 5473 CHECK); 5474 } 5475 5476 // Add read edges to the unnamed modules of the bootstrap and app class loaders. 5477 if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() && 5478 !module_entry->has_default_read_edges()) { 5479 if (!module_entry->set_has_default_read_edges()) { 5480 // We won a potential race 5481 JvmtiExport::add_default_read_edges(module_handle, THREAD); 5482 } 5483 } 5484 5485 if (is_inline_type()) { 5486 InlineKlass* vk = InlineKlass::cast(ik); 5487 vk->set_payload_alignment(_layout_info->_payload_alignment); 5488 vk->set_payload_offset(_layout_info->_payload_offset); 5489 vk->set_payload_size_in_bytes(_layout_info->_payload_size_in_bytes); 5490 vk->set_non_atomic_size_in_bytes(_layout_info->_non_atomic_size_in_bytes); 5491 vk->set_non_atomic_alignment(_layout_info->_non_atomic_alignment); 5492 vk->set_atomic_size_in_bytes(_layout_info->_atomic_layout_size_in_bytes); 5493 vk->set_nullable_size_in_bytes(_layout_info->_nullable_layout_size_in_bytes); 5494 vk->set_null_marker_offset(_layout_info->_null_marker_offset); 5495 vk->set_default_value_offset(_layout_info->_default_value_offset); 5496 vk->set_null_reset_value_offset(_layout_info->_null_reset_value_offset); 5497 if (_layout_info->_is_empty_inline_klass) vk->set_is_empty_inline_type(); 5498 vk->initialize_calling_convention(CHECK); 5499 } 5500 5501 ClassLoadingService::notify_class_loaded(ik, false /* not shared class */); 5502 5503 if (!is_internal()) { 5504 ik->print_class_load_logging(_loader_data, module_entry, _stream); 5505 5506 if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION && 5507 ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION && 5508 log_is_enabled(Info, class, preview)) { 5509 ResourceMark rm; 5510 log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)", 5511 ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION); 5512 } 5513 5514 if (log_is_enabled(Debug, class, resolve)) { 5515 ResourceMark rm; 5516 // print out the superclass. 5517 const char * from = ik->external_name(); 5518 if (ik->java_super() != nullptr) { 5519 log_debug(class, resolve)("%s %s (super)", 5520 from, 5521 ik->java_super()->external_name()); 5522 } 5523 // print out each of the interface classes referred to by this class. 5524 const Array<InstanceKlass*>* const local_interfaces = ik->local_interfaces(); 5525 if (local_interfaces != nullptr) { 5526 const int length = local_interfaces->length(); 5527 for (int i = 0; i < length; i++) { 5528 const InstanceKlass* const k = local_interfaces->at(i); 5529 const char * to = k->external_name(); 5530 log_debug(class, resolve)("%s %s (interface)", from, to); 5531 } 5532 } 5533 } 5534 } 5535 5536 JFR_ONLY(INIT_ID(ik);) 5537 5538 // If we reach here, all is well. 5539 // Now remove the InstanceKlass* from the _klass_to_deallocate field 5540 // in order for it to not be destroyed in the ClassFileParser destructor. 5541 set_klass_to_deallocate(nullptr); 5542 5543 // it's official 5544 set_klass(ik); 5545 5546 debug_only(ik->verify();) 5547 } 5548 5549 void ClassFileParser::update_class_name(Symbol* new_class_name) { 5550 // Decrement the refcount in the old name, since we're clobbering it. 5551 _class_name->decrement_refcount(); 5552 5553 _class_name = new_class_name; 5554 // Increment the refcount of the new name. 5555 // Now the ClassFileParser owns this name and will decrement in 5556 // the destructor. 5557 _class_name->increment_refcount(); 5558 } 5559 5560 ClassFileParser::ClassFileParser(ClassFileStream* stream, 5561 Symbol* name, 5562 ClassLoaderData* loader_data, 5563 const ClassLoadInfo* cl_info, 5564 Publicity pub_level, 5565 TRAPS) : 5566 _stream(stream), 5567 _class_name(nullptr), 5568 _loader_data(loader_data), 5569 _is_hidden(cl_info->is_hidden()), 5570 _can_access_vm_annotations(cl_info->can_access_vm_annotations()), 5571 _orig_cp_size(0), 5572 _static_oop_count(0), 5573 _super_klass(), 5574 _cp(nullptr), 5575 _fieldinfo_stream(nullptr), 5576 _fields_status(nullptr), 5577 _methods(nullptr), 5578 _inner_classes(nullptr), 5579 _nest_members(nullptr), 5580 _nest_host(0), 5581 _permitted_subclasses(nullptr), 5582 _loadable_descriptors(nullptr), 5583 _record_components(nullptr), 5584 _local_interfaces(nullptr), 5585 _local_interface_indexes(nullptr), 5586 _transitive_interfaces(nullptr), 5587 _combined_annotations(nullptr), 5588 _class_annotations(nullptr), 5589 _class_type_annotations(nullptr), 5590 _fields_annotations(nullptr), 5591 _fields_type_annotations(nullptr), 5592 _klass(nullptr), 5593 _klass_to_deallocate(nullptr), 5594 _parsed_annotations(nullptr), 5595 _layout_info(nullptr), 5596 _inline_layout_info_array(nullptr), 5597 _temp_field_info(nullptr), 5598 _method_ordering(nullptr), 5599 _all_mirandas(nullptr), 5600 _vtable_size(0), 5601 _itable_size(0), 5602 _num_miranda_methods(0), 5603 _protection_domain(cl_info->protection_domain()), 5604 _access_flags(), 5605 _pub_level(pub_level), 5606 _bad_constant_seen(0), 5607 _synthetic_flag(false), 5608 _sde_length(false), 5609 _sde_buffer(nullptr), 5610 _sourcefile_index(0), 5611 _generic_signature_index(0), 5612 _major_version(0), 5613 _minor_version(0), 5614 _this_class_index(0), 5615 _super_class_index(0), 5616 _itfs_len(0), 5617 _java_fields_count(0), 5618 _need_verify(false), 5619 _has_nonstatic_concrete_methods(false), 5620 _declares_nonstatic_concrete_methods(false), 5621 _has_localvariable_table(false), 5622 _has_final_method(false), 5623 _has_contended_fields(false), 5624 _has_inline_type_fields(false), 5625 _is_naturally_atomic(false), 5626 _must_be_atomic(true), 5627 _is_implicitly_constructible(false), 5628 _has_loosely_consistent_annotation(false), 5629 _has_implicitly_constructible_annotation(false), 5630 _has_finalizer(false), 5631 _has_empty_finalizer(false), 5632 _max_bootstrap_specifier_index(-1) { 5633 5634 _class_name = name != nullptr ? name : vmSymbols::unknown_class_name(); 5635 _class_name->increment_refcount(); 5636 5637 assert(_loader_data != nullptr, "invariant"); 5638 assert(stream != nullptr, "invariant"); 5639 assert(_stream != nullptr, "invariant"); 5640 assert(_stream->buffer() == _stream->current(), "invariant"); 5641 assert(_class_name != nullptr, "invariant"); 5642 assert(0 == _access_flags.as_unsigned_short(), "invariant"); 5643 5644 // Figure out whether we can skip format checking (matching classic VM behavior) 5645 _need_verify = Verifier::should_verify_for(_loader_data->class_loader()); 5646 5647 // synch back verification state to stream to check for truncation. 5648 stream->set_need_verify(_need_verify); 5649 5650 parse_stream(stream, CHECK); 5651 5652 post_process_parsed_stream(stream, _cp, CHECK); 5653 } 5654 5655 void ClassFileParser::clear_class_metadata() { 5656 // metadata created before the instance klass is created. Must be 5657 // deallocated if classfile parsing returns an error. 5658 _cp = nullptr; 5659 _fieldinfo_stream = nullptr; 5660 _fields_status = nullptr; 5661 _methods = nullptr; 5662 _inner_classes = nullptr; 5663 _nest_members = nullptr; 5664 _permitted_subclasses = nullptr; 5665 _loadable_descriptors = nullptr; 5666 _combined_annotations = nullptr; 5667 _class_annotations = _class_type_annotations = nullptr; 5668 _fields_annotations = _fields_type_annotations = nullptr; 5669 _record_components = nullptr; 5670 _inline_layout_info_array = nullptr; 5671 } 5672 5673 // Destructor to clean up 5674 ClassFileParser::~ClassFileParser() { 5675 _class_name->decrement_refcount(); 5676 5677 if (_cp != nullptr) { 5678 MetadataFactory::free_metadata(_loader_data, _cp); 5679 } 5680 5681 if (_fieldinfo_stream != nullptr) { 5682 MetadataFactory::free_array<u1>(_loader_data, _fieldinfo_stream); 5683 } 5684 5685 if (_fields_status != nullptr) { 5686 MetadataFactory::free_array<FieldStatus>(_loader_data, _fields_status); 5687 } 5688 5689 if (_inline_layout_info_array != nullptr) { 5690 MetadataFactory::free_array<InlineLayoutInfo>(_loader_data, _inline_layout_info_array); 5691 } 5692 5693 if (_methods != nullptr) { 5694 // Free methods 5695 InstanceKlass::deallocate_methods(_loader_data, _methods); 5696 } 5697 5698 // beware of the Universe::empty_blah_array!! 5699 if (_inner_classes != nullptr && _inner_classes != Universe::the_empty_short_array()) { 5700 MetadataFactory::free_array<u2>(_loader_data, _inner_classes); 5701 } 5702 5703 if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) { 5704 MetadataFactory::free_array<u2>(_loader_data, _nest_members); 5705 } 5706 5707 if (_record_components != nullptr) { 5708 InstanceKlass::deallocate_record_components(_loader_data, _record_components); 5709 } 5710 5711 if (_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array()) { 5712 MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses); 5713 } 5714 5715 if (_loadable_descriptors != nullptr && _loadable_descriptors != Universe::the_empty_short_array()) { 5716 MetadataFactory::free_array<u2>(_loader_data, _loadable_descriptors); 5717 } 5718 5719 // Free interfaces 5720 InstanceKlass::deallocate_interfaces(_loader_data, _super_klass, 5721 _local_interfaces, _transitive_interfaces); 5722 5723 if (_combined_annotations != nullptr) { 5724 // After all annotations arrays have been created, they are installed into the 5725 // Annotations object that will be assigned to the InstanceKlass being created. 5726 5727 // Deallocate the Annotations object and the installed annotations arrays. 5728 _combined_annotations->deallocate_contents(_loader_data); 5729 5730 // If the _combined_annotations pointer is non-null, 5731 // then the other annotations fields should have been cleared. 5732 assert(_class_annotations == nullptr, "Should have been cleared"); 5733 assert(_class_type_annotations == nullptr, "Should have been cleared"); 5734 assert(_fields_annotations == nullptr, "Should have been cleared"); 5735 assert(_fields_type_annotations == nullptr, "Should have been cleared"); 5736 } else { 5737 // If the annotations arrays were not installed into the Annotations object, 5738 // then they have to be deallocated explicitly. 5739 MetadataFactory::free_array<u1>(_loader_data, _class_annotations); 5740 MetadataFactory::free_array<u1>(_loader_data, _class_type_annotations); 5741 Annotations::free_contents(_loader_data, _fields_annotations); 5742 Annotations::free_contents(_loader_data, _fields_type_annotations); 5743 } 5744 5745 clear_class_metadata(); 5746 _transitive_interfaces = nullptr; 5747 _local_interfaces = nullptr; 5748 5749 // deallocate the klass if already created. Don't directly deallocate, but add 5750 // to the deallocate list so that the klass is removed from the CLD::_klasses list 5751 // at a safepoint. 5752 if (_klass_to_deallocate != nullptr) { 5753 _loader_data->add_to_deallocate_list(_klass_to_deallocate); 5754 } 5755 } 5756 5757 void ClassFileParser::parse_stream(const ClassFileStream* const stream, 5758 TRAPS) { 5759 5760 assert(stream != nullptr, "invariant"); 5761 assert(_class_name != nullptr, "invariant"); 5762 5763 // BEGIN STREAM PARSING 5764 stream->guarantee_more(8, CHECK); // magic, major, minor 5765 // Magic value 5766 const u4 magic = stream->get_u4_fast(); 5767 guarantee_property(magic == JAVA_CLASSFILE_MAGIC, 5768 "Incompatible magic value %u in class file %s", 5769 magic, CHECK); 5770 5771 // Version numbers 5772 _minor_version = stream->get_u2_fast(); 5773 _major_version = stream->get_u2_fast(); 5774 5775 // Check version numbers - we check this even with verifier off 5776 verify_class_version(_major_version, _minor_version, _class_name, CHECK); 5777 5778 stream->guarantee_more(3, CHECK); // length, first cp tag 5779 u2 cp_size = stream->get_u2_fast(); 5780 5781 guarantee_property( 5782 cp_size >= 1, "Illegal constant pool size %u in class file %s", 5783 cp_size, CHECK); 5784 5785 _orig_cp_size = cp_size; 5786 if (is_hidden()) { // Add a slot for hidden class name. 5787 cp_size++; 5788 } 5789 5790 _cp = ConstantPool::allocate(_loader_data, 5791 cp_size, 5792 CHECK); 5793 5794 ConstantPool* const cp = _cp; 5795 5796 parse_constant_pool(stream, cp, _orig_cp_size, CHECK); 5797 5798 assert(cp_size == (u2)cp->length(), "invariant"); 5799 5800 // ACCESS FLAGS 5801 stream->guarantee_more(8, CHECK); // flags, this_class, super_class, infs_len 5802 5803 u2 recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS; 5804 // JVM_ACC_MODULE is defined in JDK-9 and later. 5805 if (_major_version >= JAVA_9_VERSION) { 5806 recognized_modifiers |= JVM_ACC_MODULE; 5807 } 5808 5809 // Access flags 5810 u2 flags = stream->get_u2_fast() & recognized_modifiers; 5811 5812 if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) { 5813 // Set abstract bit for old class files for backward compatibility 5814 flags |= JVM_ACC_ABSTRACT; 5815 } 5816 5817 // Fixing ACC_SUPER/ACC_IDENTITY for old class files 5818 if (!supports_inline_types()) { 5819 const bool is_module = (flags & JVM_ACC_MODULE) != 0; 5820 const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0; 5821 if (!is_module && !is_interface) { 5822 flags |= JVM_ACC_IDENTITY; 5823 } 5824 } 5825 5826 5827 // This class and superclass 5828 _this_class_index = stream->get_u2_fast(); 5829 guarantee_property( 5830 valid_cp_range(_this_class_index, cp_size) && 5831 cp->tag_at(_this_class_index).is_unresolved_klass(), 5832 "Invalid this class index %u in constant pool in class file %s", 5833 _this_class_index, CHECK); 5834 5835 Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index); 5836 assert(class_name_in_cp != nullptr, "class_name can't be null"); 5837 5838 bool is_java_lang_Object = class_name_in_cp == vmSymbols::java_lang_Object(); 5839 5840 verify_legal_class_modifiers(flags, nullptr, is_java_lang_Object, CHECK); 5841 5842 _access_flags.set_flags(flags); 5843 5844 short bad_constant = class_bad_constant_seen(); 5845 if (bad_constant != 0) { 5846 // Do not throw CFE until after the access_flags are checked because if 5847 // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE. 5848 classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, THREAD); 5849 return; 5850 } 5851 5852 // Don't need to check whether this class name is legal or not. 5853 // It has been checked when constant pool is parsed. 5854 // However, make sure it is not an array type. 5855 if (_need_verify) { 5856 guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY, 5857 "Bad class name in class file %s", 5858 CHECK); 5859 } 5860 5861 #ifdef ASSERT 5862 // Basic sanity checks 5863 if (_is_hidden) { 5864 assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name"); 5865 } 5866 #endif 5867 5868 // Update the _class_name as needed depending on whether this is a named, un-named, or hidden class. 5869 5870 if (_is_hidden) { 5871 assert(_class_name != nullptr, "Unexpected null _class_name"); 5872 #ifdef ASSERT 5873 if (_need_verify) { 5874 verify_legal_class_name(_class_name, CHECK); 5875 } 5876 #endif 5877 5878 } else { 5879 // Check if name in class file matches given name 5880 if (_class_name != class_name_in_cp) { 5881 if (_class_name != vmSymbols::unknown_class_name()) { 5882 ResourceMark rm(THREAD); 5883 // Names are all known to be < 64k so we know this formatted message is not excessively large. 5884 Exceptions::fthrow(THREAD_AND_LOCATION, 5885 vmSymbols::java_lang_NoClassDefFoundError(), 5886 "%s (wrong name: %s)", 5887 _class_name->as_C_string(), 5888 class_name_in_cp->as_C_string() 5889 ); 5890 return; 5891 } else { 5892 // The class name was not known by the caller so we set it from 5893 // the value in the CP. 5894 update_class_name(class_name_in_cp); 5895 } 5896 // else nothing to do: the expected class name matches what is in the CP 5897 } 5898 } 5899 5900 // Verification prevents us from creating names with dots in them, this 5901 // asserts that that's the case. 5902 assert(is_internal_format(_class_name), "external class name format used internally"); 5903 5904 if (!is_internal()) { 5905 LogTarget(Debug, class, preorder) lt; 5906 if (lt.is_enabled()){ 5907 ResourceMark rm(THREAD); 5908 LogStream ls(lt); 5909 ls.print("%s", _class_name->as_klass_external_name()); 5910 if (stream->source() != nullptr) { 5911 ls.print(" source: %s", stream->source()); 5912 } 5913 ls.cr(); 5914 } 5915 } 5916 5917 // SUPERKLASS 5918 _super_class_index = stream->get_u2_fast(); 5919 _super_klass = parse_super_class(cp, 5920 _super_class_index, 5921 _need_verify, 5922 CHECK); 5923 5924 // Interfaces 5925 _itfs_len = stream->get_u2_fast(); 5926 parse_interfaces(stream, 5927 _itfs_len, 5928 cp, 5929 &_has_nonstatic_concrete_methods, 5930 CHECK); 5931 5932 // Fields (offsets are filled in later) 5933 parse_fields(stream, 5934 _access_flags, 5935 cp, 5936 cp_size, 5937 &_java_fields_count, 5938 CHECK); 5939 5940 assert(_temp_field_info != nullptr, "invariant"); 5941 5942 // Methods 5943 parse_methods(stream, 5944 is_interface(), 5945 !is_identity_class(), 5946 is_abstract_class(), 5947 &_has_localvariable_table, 5948 &_has_final_method, 5949 &_declares_nonstatic_concrete_methods, 5950 CHECK); 5951 5952 assert(_methods != nullptr, "invariant"); 5953 5954 if (_declares_nonstatic_concrete_methods) { 5955 _has_nonstatic_concrete_methods = true; 5956 } 5957 5958 // Additional attributes/annotations 5959 _parsed_annotations = new ClassAnnotationCollector(); 5960 parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK); 5961 5962 assert(_inner_classes != nullptr, "invariant"); 5963 5964 // Finalize the Annotations metadata object, 5965 // now that all annotation arrays have been created. 5966 create_combined_annotations(CHECK); 5967 5968 // Make sure this is the end of class file stream 5969 guarantee_property(stream->at_eos(), 5970 "Extra bytes at the end of class file %s", 5971 CHECK); 5972 5973 // all bytes in stream read and parsed 5974 } 5975 5976 void ClassFileParser::mangle_hidden_class_name(InstanceKlass* const ik) { 5977 ResourceMark rm; 5978 // Construct hidden name from _class_name, "+", and &ik. Note that we can't 5979 // use a '/' because that confuses finding the class's package. Also, can't 5980 // use an illegal char such as ';' because that causes serialization issues 5981 // and issues with hidden classes that create their own hidden classes. 5982 char addr_buf[20]; 5983 if (CDSConfig::is_dumping_static_archive()) { 5984 // We want stable names for the archived hidden classes (only for static 5985 // archive for now). Spaces under default_SharedBaseAddress() will be 5986 // occupied by the archive at run time, so we know that no dynamically 5987 // loaded InstanceKlass will be placed under there. 5988 static volatile size_t counter = 0; 5989 Atomic::cmpxchg(&counter, (size_t)0, Arguments::default_SharedBaseAddress()); // initialize it 5990 size_t new_id = Atomic::add(&counter, (size_t)1); 5991 jio_snprintf(addr_buf, 20, "0x%zx", new_id); 5992 } else { 5993 jio_snprintf(addr_buf, 20, INTPTR_FORMAT, p2i(ik)); 5994 } 5995 size_t new_name_len = _class_name->utf8_length() + 2 + strlen(addr_buf); 5996 char* new_name = NEW_RESOURCE_ARRAY(char, new_name_len); 5997 jio_snprintf(new_name, new_name_len, "%s+%s", 5998 _class_name->as_C_string(), addr_buf); 5999 update_class_name(SymbolTable::new_symbol(new_name)); 6000 6001 // Add a Utf8 entry containing the hidden name. 6002 assert(_class_name != nullptr, "Unexpected null _class_name"); 6003 int hidden_index = _orig_cp_size; // this is an extra slot we added 6004 _cp->symbol_at_put(hidden_index, _class_name); 6005 6006 // Update this_class_index's slot in the constant pool with the new Utf8 entry. 6007 // We have to update the resolved_klass_index and the name_index together 6008 // so extract the existing resolved_klass_index first. 6009 CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index); 6010 int resolved_klass_index = cp_klass_slot.resolved_klass_index(); 6011 _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index); 6012 assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size, 6013 "Bad name_index"); 6014 } 6015 6016 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream, 6017 ConstantPool* cp, 6018 TRAPS) { 6019 assert(stream != nullptr, "invariant"); 6020 assert(stream->at_eos(), "invariant"); 6021 assert(cp != nullptr, "invariant"); 6022 assert(_loader_data != nullptr, "invariant"); 6023 6024 if (_class_name == vmSymbols::java_lang_Object()) { 6025 guarantee_property(_local_interfaces == Universe::the_empty_instance_klass_array(), 6026 "java.lang.Object cannot implement an interface in class file %s", 6027 CHECK); 6028 } 6029 // We check super class after class file is parsed and format is checked 6030 if (_super_class_index > 0 && nullptr == _super_klass) { 6031 Symbol* const super_class_name = cp->klass_name_at(_super_class_index); 6032 if (is_interface()) { 6033 // Before attempting to resolve the superclass, check for class format 6034 // errors not checked yet. 6035 guarantee_property(super_class_name == vmSymbols::java_lang_Object(), 6036 "Interfaces must have java.lang.Object as superclass in class file %s", 6037 CHECK); 6038 } 6039 Handle loader(THREAD, _loader_data->class_loader()); 6040 if (loader.is_null() && super_class_name == vmSymbols::java_lang_Object()) { 6041 _super_klass = vmClasses::Object_klass(); 6042 } else { 6043 _super_klass = (const InstanceKlass*) 6044 SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name, 6045 super_class_name, 6046 loader, 6047 true, 6048 CHECK); 6049 } 6050 } 6051 6052 if (_super_klass != nullptr) { 6053 if (_super_klass->is_interface()) { 6054 classfile_icce_error("class %s has interface %s as super class", _super_klass, THREAD); 6055 return; 6056 } 6057 6058 if (_super_klass->is_final()) { 6059 classfile_icce_error("class %s cannot inherit from final class %s", _super_klass, THREAD); 6060 return; 6061 } 6062 6063 if (EnableValhalla) { 6064 check_identity_and_value_modifiers(this, _super_klass, CHECK); 6065 } 6066 6067 if (_super_klass->has_nonstatic_concrete_methods()) { 6068 _has_nonstatic_concrete_methods = true; 6069 } 6070 } 6071 6072 if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_LooselyConsistentValue) && _access_flags.is_identity_class()) { 6073 THROW_MSG(vmSymbols::java_lang_ClassFormatError(), 6074 err_msg("class %s cannot have annotation jdk.internal.vm.annotation.LooselyConsistentValue, because it is not a value class", 6075 _class_name->as_klass_external_name())); 6076 } 6077 if (_parsed_annotations->has_annotation(AnnotationCollector::_jdk_internal_ImplicitlyConstructible) && _access_flags.is_identity_class()) { 6078 THROW_MSG(vmSymbols::java_lang_ClassFormatError(), 6079 err_msg("class %s cannot have annotation jdk.internal.vm.annotation.ImplicitlyConstructible, because it is not a value class", 6080 _class_name->as_klass_external_name())); 6081 } 6082 6083 // Determining is the class allows tearing or not (default is not) 6084 if (EnableValhalla && !_access_flags.is_identity_class()) { 6085 if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_LooselyConsistentValue) 6086 && (_super_klass == vmClasses::Object_klass() || !_super_klass->must_be_atomic())) { 6087 // Conditions above are not sufficient to determine atomicity requirements, 6088 // the presence of fields with atomic requirements could force the current class to have atomicy requirements too 6089 // Marking as not needing atomicity for now, can be updated when computing the fields layout 6090 // The InstanceKlass must be filled with the value from the FieldLayoutInfo returned by 6091 // the FieldLayoutBuilder, not with this _must_be_atomic field. 6092 _must_be_atomic = false; 6093 } 6094 if (_parsed_annotations->has_annotation(ClassAnnotationCollector::_jdk_internal_ImplicitlyConstructible) 6095 && (_super_klass == vmClasses::Object_klass() || _super_klass == vmClasses::Record_klass() 6096 || _super_klass->is_implicitly_constructible())) { 6097 _is_implicitly_constructible = true; 6098 } 6099 // Apply VM options override 6100 if (*ForceNonTearable != '\0') { 6101 // Allow a command line switch to force the same atomicity property: 6102 const char* class_name_str = _class_name->as_C_string(); 6103 if (StringUtils::class_list_match(ForceNonTearable, class_name_str)) { 6104 _must_be_atomic = true; 6105 } 6106 } 6107 } 6108 6109 int itfs_len = _local_interface_indexes == nullptr ? 0 : _local_interface_indexes->length(); 6110 _local_interfaces = MetadataFactory::new_array<InstanceKlass*>(_loader_data, itfs_len, nullptr, CHECK); 6111 if (_local_interface_indexes != nullptr) { 6112 for (int i = 0; i < _local_interface_indexes->length(); i++) { 6113 u2 interface_index = _local_interface_indexes->at(i); 6114 Klass* interf; 6115 if (cp->tag_at(interface_index).is_klass()) { 6116 interf = cp->resolved_klass_at(interface_index); 6117 } else { 6118 Symbol* const unresolved_klass = cp->klass_name_at(interface_index); 6119 6120 // Don't need to check legal name because it's checked when parsing constant pool. 6121 // But need to make sure it's not an array type. 6122 guarantee_property(unresolved_klass->char_at(0) != JVM_SIGNATURE_ARRAY, 6123 "Bad interface name in class file %s", CHECK); 6124 6125 // Call resolve on the interface class name with class circularity checking 6126 interf = SystemDictionary::resolve_with_circularity_detection_or_fail( 6127 _class_name, 6128 unresolved_klass, 6129 Handle(THREAD, _loader_data->class_loader()), 6130 false, 6131 CHECK); 6132 } 6133 6134 if (!interf->is_interface()) { 6135 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), 6136 err_msg("class %s can not implement %s, because it is not an interface (%s)", 6137 _class_name->as_klass_external_name(), 6138 interf->external_name(), 6139 interf->class_in_module_of_loader())); 6140 } 6141 6142 if (EnableValhalla) { 6143 // Check modifiers and set carries_identity_modifier/carries_value_modifier flags 6144 check_identity_and_value_modifiers(this, InstanceKlass::cast(interf), CHECK); 6145 } 6146 6147 if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) { 6148 _has_nonstatic_concrete_methods = true; 6149 } 6150 _local_interfaces->at_put(i, InstanceKlass::cast(interf)); 6151 } 6152 } 6153 assert(_local_interfaces != nullptr, "invariant"); 6154 6155 // Compute the transitive list of all unique interfaces implemented by this class 6156 _transitive_interfaces = 6157 compute_transitive_interfaces(_super_klass, 6158 _local_interfaces, 6159 _loader_data, 6160 CHECK); 6161 6162 assert(_transitive_interfaces != nullptr, "invariant"); 6163 6164 // sort methods 6165 _method_ordering = sort_methods(_methods); 6166 6167 _all_mirandas = new GrowableArray<Method*>(20); 6168 6169 Handle loader(THREAD, _loader_data->class_loader()); 6170 klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size, 6171 &_num_miranda_methods, 6172 _all_mirandas, 6173 _super_klass, 6174 _methods, 6175 _access_flags, 6176 _major_version, 6177 loader, 6178 _class_name, 6179 _local_interfaces); 6180 6181 // Size of Java itable (in words) 6182 _itable_size = is_interface() ? 0 : 6183 klassItable::compute_itable_size(_transitive_interfaces); 6184 6185 assert(_parsed_annotations != nullptr, "invariant"); 6186 6187 if (EnableValhalla) { 6188 _inline_layout_info_array = MetadataFactory::new_array<InlineLayoutInfo>(_loader_data, 6189 java_fields_count(), 6190 CHECK); 6191 for (GrowableArrayIterator<FieldInfo> it = _temp_field_info->begin(); it != _temp_field_info->end(); ++it) { 6192 FieldInfo fieldinfo = *it; 6193 if (fieldinfo.access_flags().is_static()) continue; // Only non-static fields are processed at load time 6194 Symbol* sig = fieldinfo.signature(cp); 6195 if (fieldinfo.field_flags().is_null_free_inline_type()) { 6196 // Pre-load classes of null-free fields that are candidate for flattening 6197 TempNewSymbol s = Signature::strip_envelope(sig); 6198 if (s == _class_name) { 6199 THROW_MSG(vmSymbols::java_lang_ClassCircularityError(), err_msg("Class %s cannot have a null-free non-static field of its own type", _class_name->as_C_string())); 6200 } 6201 log_info(class, preload)("Preloading class %s during loading of class %s. Cause: a null-free non-static field is declared with this type", s->as_C_string(), _class_name->as_C_string()); 6202 Klass* klass = SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name, s, Handle(THREAD, _loader_data->class_loader()), false, THREAD); 6203 if (HAS_PENDING_EXCEPTION) { 6204 log_warning(class, preload)("Preloading of class %s during loading of class %s (cause: null-free non-static field) failed: %s", 6205 s->as_C_string(), _class_name->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string()); 6206 return; // Exception is still pending 6207 } 6208 assert(klass != nullptr, "Sanity check"); 6209 if (klass->access_flags().is_identity_class()) { 6210 assert(klass->is_instance_klass(), "Sanity check"); 6211 ResourceMark rm(THREAD); 6212 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), 6213 err_msg("Class %s expects class %s to be a value class, but it is an identity class", 6214 _class_name->as_C_string(), 6215 InstanceKlass::cast(klass)->external_name())); 6216 } 6217 if (klass->is_abstract()) { 6218 assert(klass->is_instance_klass(), "Sanity check"); 6219 ResourceMark rm(THREAD); 6220 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), 6221 err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class", 6222 _class_name->as_C_string(), 6223 InstanceKlass::cast(klass)->external_name())); 6224 } 6225 InlineKlass* vk = InlineKlass::cast(klass); 6226 if (!vk->is_implicitly_constructible()) { 6227 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), 6228 err_msg("class %s is not implicitly constructible and it is used in a null restricted non-static field (not supported)", 6229 klass->name()->as_C_string())); 6230 } 6231 _inline_layout_info_array->adr_at(fieldinfo.index())->set_klass(vk); 6232 log_info(class, preload)("Preloading of class %s during loading of class %s (cause: null-free non-static field) succeeded", s->as_C_string(), _class_name->as_C_string()); 6233 } else if (Signature::has_envelope(sig)) { 6234 // Preloading classes for nullable fields that are listed in the LoadableDescriptors attribute 6235 // Those classes would be required later for the flattening of nullable inline type fields 6236 TempNewSymbol name = Signature::strip_envelope(sig); 6237 if (name != _class_name && is_class_in_loadable_descriptors_attribute(sig)) { 6238 log_info(class, preload)("Preloading class %s during loading of class %s. Cause: field type in LoadableDescriptors attribute", name->as_C_string(), _class_name->as_C_string()); 6239 oop loader = loader_data()->class_loader(); 6240 Klass* klass = SystemDictionary::resolve_with_circularity_detection_or_fail(_class_name, name, Handle(THREAD, loader), false, THREAD); 6241 if (klass != nullptr) { 6242 if (klass->is_inline_klass()) { 6243 _inline_layout_info_array->adr_at(fieldinfo.index())->set_klass(InlineKlass::cast(klass)); 6244 log_info(class, preload)("Preloading of class %s during loading of class %s (cause: field type in LoadableDescriptors attribute) succeeded", name->as_C_string(), _class_name->as_C_string()); 6245 } else { 6246 // Non value class are allowed by the current spec, but it could be an indication of an issue so let's log a warning 6247 log_warning(class, preload)("Preloading class %s during loading of class %s (cause: field type in LoadableDescriptors attribute) but loaded class is not a value class", name->as_C_string(), _class_name->as_C_string()); 6248 } 6249 } else { 6250 log_warning(class, preload)("Preloading of class %s during loading of class %s (cause: field type in LoadableDescriptors attribute) failed : %s", 6251 name->as_C_string(), _class_name->as_C_string(), PENDING_EXCEPTION->klass()->name()->as_C_string()); 6252 } 6253 // Loads triggered by the LoadableDescriptors attribute are speculative, failures must not impact loading of current class 6254 if (HAS_PENDING_EXCEPTION) { 6255 CLEAR_PENDING_EXCEPTION; 6256 } 6257 } 6258 } 6259 } 6260 } 6261 6262 _layout_info = new FieldLayoutInfo(); 6263 FieldLayoutBuilder lb(class_name(), loader_data(), super_klass(), _cp, /*_fields*/ _temp_field_info, 6264 _parsed_annotations->is_contended(), is_inline_type(), 6265 access_flags().is_abstract() && !access_flags().is_identity_class() && !access_flags().is_interface(), 6266 _must_be_atomic, _layout_info, _inline_layout_info_array); 6267 lb.build_layout(); 6268 _has_inline_type_fields = _layout_info->_has_inline_fields; 6269 6270 int injected_fields_count = _temp_field_info->length() - _java_fields_count; 6271 _fieldinfo_stream = 6272 FieldInfoStream::create_FieldInfoStream(_temp_field_info, _java_fields_count, 6273 injected_fields_count, loader_data(), CHECK); 6274 6275 _fields_status = 6276 MetadataFactory::new_array<FieldStatus>(_loader_data, _temp_field_info->length(), 6277 FieldStatus(0), CHECK); 6278 } 6279 6280 void ClassFileParser::set_klass(InstanceKlass* klass) { 6281 6282 #ifdef ASSERT 6283 if (klass != nullptr) { 6284 assert(nullptr == _klass, "leaking?"); 6285 } 6286 #endif 6287 6288 _klass = klass; 6289 } 6290 6291 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) { 6292 6293 #ifdef ASSERT 6294 if (klass != nullptr) { 6295 assert(nullptr == _klass_to_deallocate, "leaking?"); 6296 } 6297 #endif 6298 6299 _klass_to_deallocate = klass; 6300 } 6301 6302 // Caller responsible for ResourceMark 6303 // clone stream with rewound position 6304 const ClassFileStream* ClassFileParser::clone_stream() const { 6305 assert(_stream != nullptr, "invariant"); 6306 6307 return _stream->clone(); 6308 } 6309 6310 ReferenceType ClassFileParser::super_reference_type() const { 6311 return _super_klass == nullptr ? REF_NONE : _super_klass->reference_type(); 6312 } 6313 6314 bool ClassFileParser::is_instance_ref_klass() const { 6315 // Only the subclasses of j.l.r.Reference are InstanceRefKlass. 6316 // j.l.r.Reference itself is InstanceKlass because InstanceRefKlass denotes a 6317 // klass requiring special treatment in ref-processing. The abstract 6318 // j.l.r.Reference cannot be instantiated so doesn't partake in 6319 // ref-processing. 6320 return is_java_lang_ref_Reference_subclass(); 6321 } 6322 6323 bool ClassFileParser::is_java_lang_ref_Reference_subclass() const { 6324 if (_super_klass == nullptr) { 6325 return false; 6326 } 6327 6328 if (_super_klass->name() == vmSymbols::java_lang_ref_Reference()) { 6329 // Direct subclass of j.l.r.Reference: Soft|Weak|Final|Phantom 6330 return true; 6331 } 6332 6333 return _super_klass->reference_type() != REF_NONE; 6334 } 6335 6336 // Returns true if the future Klass will need to be addressable with a narrow Klass ID. 6337 bool ClassFileParser::klass_needs_narrow_id() const { 6338 // Classes that are never instantiated need no narrow Klass Id, since the 6339 // only point of having a narrow id is to put it into an object header. Keeping 6340 // never instantiated classes out of class space lessens the class space pressure. 6341 // For more details, see JDK-8338526. 6342 return !is_interface() && !is_abstract(); 6343 } 6344 6345 // ---------------------------------------------------------------------------- 6346 // debugging 6347 6348 #ifdef ASSERT 6349 6350 // return true if class_name contains no '.' (internal format is '/') 6351 bool ClassFileParser::is_internal_format(Symbol* class_name) { 6352 if (class_name != nullptr) { 6353 ResourceMark rm; 6354 char* name = class_name->as_C_string(); 6355 return strchr(name, JVM_SIGNATURE_DOT) == nullptr; 6356 } else { 6357 return true; 6358 } 6359 } 6360 6361 #endif