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