1 /* 2 * Copyright (c) 2014, 2020, 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 "precompiled.hpp" 26 #include "classfile/classFileStream.hpp" 27 #include "classfile/classListParser.hpp" 28 #include "classfile/classLoader.hpp" 29 #include "classfile/classLoaderData.inline.hpp" 30 #include "classfile/classLoaderDataGraph.hpp" 31 #include "classfile/classLoaderExt.hpp" 32 #include "classfile/dictionary.hpp" 33 #include "classfile/javaClasses.hpp" 34 #include "classfile/symbolTable.hpp" 35 #include "classfile/systemDictionary.hpp" 36 #include "classfile/systemDictionaryShared.hpp" 37 #include "classfile/verificationType.hpp" 38 #include "classfile/vmSymbols.hpp" 39 #include "logging/log.hpp" 40 #include "memory/allocation.hpp" 41 #include "memory/archiveUtils.hpp" 42 #include "memory/filemap.hpp" 43 #include "memory/metadataFactory.hpp" 44 #include "memory/metaspaceClosure.hpp" 45 #include "memory/oopFactory.hpp" 46 #include "memory/resourceArea.hpp" 47 #include "memory/universe.hpp" 48 #include "memory/dynamicArchive.hpp" 49 #include "oops/instanceKlass.hpp" 50 #include "oops/klass.inline.hpp" 51 #include "oops/objArrayOop.inline.hpp" 52 #include "oops/oop.inline.hpp" 53 #include "oops/typeArrayOop.inline.hpp" 54 #include "runtime/handles.inline.hpp" 55 #include "runtime/java.hpp" 56 #include "runtime/javaCalls.hpp" 57 #include "runtime/mutexLocker.hpp" 58 #include "utilities/hashtable.inline.hpp" 59 #include "utilities/resourceHash.hpp" 60 #include "utilities/stringUtils.hpp" 61 62 63 objArrayOop SystemDictionaryShared::_shared_protection_domains = NULL; 64 objArrayOop SystemDictionaryShared::_shared_jar_urls = NULL; 65 objArrayOop SystemDictionaryShared::_shared_jar_manifests = NULL; 66 DEBUG_ONLY(bool SystemDictionaryShared::_no_class_loading_should_happen = false;) 67 68 class DumpTimeSharedClassInfo: public CHeapObj<mtClass> { 69 bool _excluded; 70 public: 71 struct DTConstraint { 72 Symbol* _name; 73 Symbol* _from_name; 74 DTConstraint() : _name(NULL), _from_name(NULL) {} 75 DTConstraint(Symbol* n, Symbol* fn) : _name(n), _from_name(fn) {} 76 }; 77 78 InstanceKlass* _klass; 79 bool _failed_verification; 80 int _id; 81 int _clsfile_size; 82 int _clsfile_crc32; 83 GrowableArray<DTConstraint>* _verifier_constraints; 84 GrowableArray<char>* _verifier_constraint_flags; 85 86 DumpTimeSharedClassInfo() { 87 _klass = NULL; 88 _failed_verification = false; 89 _id = -1; 90 _clsfile_size = -1; 91 _clsfile_crc32 = -1; 92 _excluded = false; 93 _verifier_constraints = NULL; 94 _verifier_constraint_flags = NULL; 95 } 96 97 void add_verification_constraint(InstanceKlass* k, Symbol* name, 98 Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object); 99 100 bool is_builtin() { 101 return SystemDictionaryShared::is_builtin(_klass); 102 } 103 104 int num_constraints() { 105 if (_verifier_constraint_flags != NULL) { 106 return _verifier_constraint_flags->length(); 107 } else { 108 return 0; 109 } 110 } 111 112 void metaspace_pointers_do(MetaspaceClosure* it) { 113 it->push(&_klass); 114 if (_verifier_constraints != NULL) { 115 for (int i = 0; i < _verifier_constraints->length(); i++) { 116 DTConstraint* cons = _verifier_constraints->adr_at(i); 117 it->push(&cons->_name); 118 it->push(&cons->_from_name); 119 } 120 } 121 } 122 123 void set_excluded() { 124 _excluded = true; 125 } 126 127 bool is_excluded() { 128 // _klass may become NULL due to DynamicArchiveBuilder::set_to_null 129 return _excluded || _failed_verification || _klass == NULL; 130 } 131 132 void set_failed_verification() { 133 _failed_verification = true; 134 } 135 136 bool failed_verification() { 137 return _failed_verification; 138 } 139 }; 140 141 class DumpTimeSharedClassTable: public ResourceHashtable< 142 InstanceKlass*, 143 DumpTimeSharedClassInfo, 144 primitive_hash<InstanceKlass*>, 145 primitive_equals<InstanceKlass*>, 146 15889, // prime number 147 ResourceObj::C_HEAP> 148 { 149 int _builtin_count; 150 int _unregistered_count; 151 public: 152 DumpTimeSharedClassInfo* find_or_allocate_info_for(InstanceKlass* k) { 153 DumpTimeSharedClassInfo* p = get(k); 154 if (p == NULL) { 155 assert(!SystemDictionaryShared::no_class_loading_should_happen(), 156 "no new classes can be loaded while dumping archive"); 157 put(k, DumpTimeSharedClassInfo()); 158 p = get(k); 159 assert(p != NULL, "sanity"); 160 p->_klass = k; 161 } 162 return p; 163 } 164 165 class CountClassByCategory : StackObj { 166 DumpTimeSharedClassTable* _table; 167 public: 168 CountClassByCategory(DumpTimeSharedClassTable* table) : _table(table) {} 169 bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) { 170 if (!info.is_excluded()) { 171 if (info.is_builtin()) { 172 ++ _table->_builtin_count; 173 } else { 174 ++ _table->_unregistered_count; 175 } 176 } 177 return true; // keep on iterating 178 } 179 }; 180 181 void update_counts() { 182 _builtin_count = 0; 183 _unregistered_count = 0; 184 CountClassByCategory counter(this); 185 iterate(&counter); 186 } 187 188 int count_of(bool is_builtin) const { 189 if (is_builtin) { 190 return _builtin_count; 191 } else { 192 return _unregistered_count; 193 } 194 } 195 }; 196 197 class RunTimeSharedClassInfo { 198 public: 199 struct CrcInfo { 200 int _clsfile_size; 201 int _clsfile_crc32; 202 }; 203 204 // This is different than DumpTimeSharedClassInfo::DTConstraint. We use 205 // u4 instead of Symbol* to save space on 64-bit CPU. 206 struct RTConstraint { 207 u4 _name; 208 u4 _from_name; 209 }; 210 211 InstanceKlass* _klass; 212 int _num_constraints; 213 214 // optional CrcInfo _crc; (only for UNREGISTERED classes) 215 // optional RTConstraint _verifier_constraints[_num_constraints] 216 // optional char _verifier_constraint_flags[_num_constraints] 217 218 private: 219 static size_t header_size_size() { 220 return sizeof(RunTimeSharedClassInfo); 221 } 222 static size_t crc_size(InstanceKlass* klass) { 223 if (!SystemDictionaryShared::is_builtin(klass)) { 224 return sizeof(CrcInfo); 225 } else { 226 return 0; 227 } 228 } 229 static size_t verifier_constraints_size(int num_constraints) { 230 return sizeof(RTConstraint) * num_constraints; 231 } 232 static size_t verifier_constraint_flags_size(int num_constraints) { 233 return sizeof(char) * num_constraints; 234 } 235 236 public: 237 static size_t byte_size(InstanceKlass* klass, int num_constraints) { 238 return header_size_size() + 239 crc_size(klass) + 240 verifier_constraints_size(num_constraints) + 241 verifier_constraint_flags_size(num_constraints); 242 } 243 244 private: 245 size_t crc_offset() const { 246 return header_size_size(); 247 } 248 size_t verifier_constraints_offset() const { 249 return crc_offset() + crc_size(_klass); 250 } 251 size_t verifier_constraint_flags_offset() const { 252 return verifier_constraints_offset() + verifier_constraints_size(_num_constraints); 253 } 254 255 void check_constraint_offset(int i) const { 256 assert(0 <= i && i < _num_constraints, "sanity"); 257 } 258 259 public: 260 CrcInfo* crc() const { 261 assert(crc_size(_klass) > 0, "must be"); 262 return (CrcInfo*)(address(this) + crc_offset()); 263 } 264 RTConstraint* verifier_constraints() { 265 assert(_num_constraints > 0, "sanity"); 266 return (RTConstraint*)(address(this) + verifier_constraints_offset()); 267 } 268 RTConstraint* verifier_constraint_at(int i) { 269 check_constraint_offset(i); 270 return verifier_constraints() + i; 271 } 272 273 char* verifier_constraint_flags() { 274 assert(_num_constraints > 0, "sanity"); 275 return (char*)(address(this) + verifier_constraint_flags_offset()); 276 } 277 278 static u4 object_delta_u4(Symbol* sym) { 279 if (DynamicDumpSharedSpaces) { 280 sym = DynamicArchive::original_to_target(sym); 281 } 282 return MetaspaceShared::object_delta_u4(sym); 283 } 284 285 void init(DumpTimeSharedClassInfo& info) { 286 _klass = info._klass; 287 if (!SystemDictionaryShared::is_builtin(_klass)) { 288 CrcInfo* c = crc(); 289 c->_clsfile_size = info._clsfile_size; 290 c->_clsfile_crc32 = info._clsfile_crc32; 291 } 292 _num_constraints = info.num_constraints(); 293 if (_num_constraints > 0) { 294 RTConstraint* constraints = verifier_constraints(); 295 char* flags = verifier_constraint_flags(); 296 int i; 297 for (i = 0; i < _num_constraints; i++) { 298 constraints[i]._name = object_delta_u4(info._verifier_constraints->at(i)._name); 299 constraints[i]._from_name = object_delta_u4(info._verifier_constraints->at(i)._from_name); 300 } 301 for (i = 0; i < _num_constraints; i++) { 302 flags[i] = info._verifier_constraint_flags->at(i); 303 } 304 } 305 if (DynamicDumpSharedSpaces) { 306 _klass = DynamicArchive::original_to_target(info._klass); 307 } 308 ArchivePtrMarker::mark_pointer(&_klass); 309 } 310 311 bool matches(int clsfile_size, int clsfile_crc32) const { 312 return crc()->_clsfile_size == clsfile_size && 313 crc()->_clsfile_crc32 == clsfile_crc32; 314 } 315 316 Symbol* get_constraint_name(int i) { 317 return (Symbol*)(SharedBaseAddress + verifier_constraint_at(i)->_name); 318 } 319 Symbol* get_constraint_from_name(int i) { 320 return (Symbol*)(SharedBaseAddress + verifier_constraint_at(i)->_from_name); 321 } 322 323 char get_constraint_flag(int i) { 324 check_constraint_offset(i); 325 return verifier_constraint_flags()[i]; 326 } 327 328 private: 329 // ArchiveCompactor::allocate() has reserved a pointer immediately before 330 // archived InstanceKlasses. We can use this slot to do a quick 331 // lookup of InstanceKlass* -> RunTimeSharedClassInfo* without 332 // building a new hashtable. 333 // 334 // info_pointer_addr(klass) --> 0x0100 RunTimeSharedClassInfo* 335 // InstanceKlass* klass --> 0x0108 <C++ vtbl> 336 // 0x0110 fields from Klass ... 337 static RunTimeSharedClassInfo** info_pointer_addr(InstanceKlass* klass) { 338 return &((RunTimeSharedClassInfo**)klass)[-1]; 339 } 340 341 public: 342 static RunTimeSharedClassInfo* get_for(InstanceKlass* klass) { 343 return *info_pointer_addr(klass); 344 } 345 static void set_for(InstanceKlass* klass, RunTimeSharedClassInfo* record) { 346 if (DynamicDumpSharedSpaces) { 347 klass = DynamicArchive::original_to_buffer(klass); 348 *info_pointer_addr(klass) = DynamicArchive::buffer_to_target(record); 349 } else { 350 *info_pointer_addr(klass) = record; 351 } 352 353 ArchivePtrMarker::mark_pointer(info_pointer_addr(klass)); 354 } 355 356 // Used by RunTimeSharedDictionary to implement OffsetCompactHashtable::EQUALS 357 static inline bool EQUALS( 358 const RunTimeSharedClassInfo* value, Symbol* key, int len_unused) { 359 return (value->_klass->name() == key); 360 } 361 }; 362 363 class RunTimeSharedDictionary : public OffsetCompactHashtable< 364 Symbol*, 365 const RunTimeSharedClassInfo*, 366 RunTimeSharedClassInfo::EQUALS> {}; 367 368 static DumpTimeSharedClassTable* _dumptime_table = NULL; 369 // SystemDictionaries in the base layer static archive 370 static RunTimeSharedDictionary _builtin_dictionary; 371 static RunTimeSharedDictionary _unregistered_dictionary; 372 // SystemDictionaries in the top layer dynamic archive 373 static RunTimeSharedDictionary _dynamic_builtin_dictionary; 374 static RunTimeSharedDictionary _dynamic_unregistered_dictionary; 375 376 oop SystemDictionaryShared::shared_protection_domain(int index) { 377 return _shared_protection_domains->obj_at(index); 378 } 379 380 oop SystemDictionaryShared::shared_jar_url(int index) { 381 return _shared_jar_urls->obj_at(index); 382 } 383 384 oop SystemDictionaryShared::shared_jar_manifest(int index) { 385 return _shared_jar_manifests->obj_at(index); 386 } 387 388 389 Handle SystemDictionaryShared::get_shared_jar_manifest(int shared_path_index, TRAPS) { 390 Handle manifest ; 391 if (shared_jar_manifest(shared_path_index) == NULL) { 392 SharedClassPathEntry* ent = FileMapInfo::shared_path(shared_path_index); 393 long size = ent->manifest_size(); 394 if (size <= 0) { 395 return Handle(); 396 } 397 398 // ByteArrayInputStream bais = new ByteArrayInputStream(buf); 399 const char* src = ent->manifest(); 400 assert(src != NULL, "No Manifest data"); 401 typeArrayOop buf = oopFactory::new_byteArray(size, CHECK_NH); 402 typeArrayHandle bufhandle(THREAD, buf); 403 ArrayAccess<>::arraycopy_from_native(reinterpret_cast<const jbyte*>(src), 404 buf, typeArrayOopDesc::element_offset<jbyte>(0), size); 405 406 Handle bais = JavaCalls::construct_new_instance(SystemDictionary::ByteArrayInputStream_klass(), 407 vmSymbols::byte_array_void_signature(), 408 bufhandle, CHECK_NH); 409 410 // manifest = new Manifest(bais) 411 manifest = JavaCalls::construct_new_instance(SystemDictionary::Jar_Manifest_klass(), 412 vmSymbols::input_stream_void_signature(), 413 bais, CHECK_NH); 414 atomic_set_shared_jar_manifest(shared_path_index, manifest()); 415 } 416 417 manifest = Handle(THREAD, shared_jar_manifest(shared_path_index)); 418 assert(manifest.not_null(), "sanity"); 419 return manifest; 420 } 421 422 Handle SystemDictionaryShared::get_shared_jar_url(int shared_path_index, TRAPS) { 423 Handle url_h; 424 if (shared_jar_url(shared_path_index) == NULL) { 425 JavaValue result(T_OBJECT); 426 const char* path = FileMapInfo::shared_path_name(shared_path_index); 427 Handle path_string = java_lang_String::create_from_str(path, CHECK_(url_h)); 428 Klass* classLoaders_klass = 429 SystemDictionary::jdk_internal_loader_ClassLoaders_klass(); 430 JavaCalls::call_static(&result, classLoaders_klass, 431 vmSymbols::toFileURL_name(), 432 vmSymbols::toFileURL_signature(), 433 path_string, CHECK_(url_h)); 434 435 atomic_set_shared_jar_url(shared_path_index, (oop)result.get_jobject()); 436 } 437 438 url_h = Handle(THREAD, shared_jar_url(shared_path_index)); 439 assert(url_h.not_null(), "sanity"); 440 return url_h; 441 } 442 443 Handle SystemDictionaryShared::get_package_name(Symbol* class_name, TRAPS) { 444 ResourceMark rm(THREAD); 445 Handle pkgname_string; 446 Symbol* pkg = ClassLoader::package_from_class_name(class_name); 447 if (pkg != NULL) { // Package prefix found 448 const char* pkgname = pkg->as_klass_external_name(); 449 pkgname_string = java_lang_String::create_from_str(pkgname, 450 CHECK_(pkgname_string)); 451 } 452 return pkgname_string; 453 } 454 455 // Define Package for shared app classes from JAR file and also checks for 456 // package sealing (all done in Java code) 457 // See http://docs.oracle.com/javase/tutorial/deployment/jar/sealman.html 458 void SystemDictionaryShared::define_shared_package(Symbol* class_name, 459 Handle class_loader, 460 Handle manifest, 461 Handle url, 462 TRAPS) { 463 assert(SystemDictionary::is_system_class_loader(class_loader()), "unexpected class loader"); 464 // get_package_name() returns a NULL handle if the class is in unnamed package 465 Handle pkgname_string = get_package_name(class_name, CHECK); 466 if (pkgname_string.not_null()) { 467 Klass* app_classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass(); 468 JavaValue result(T_OBJECT); 469 JavaCallArguments args(3); 470 args.set_receiver(class_loader); 471 args.push_oop(pkgname_string); 472 args.push_oop(manifest); 473 args.push_oop(url); 474 JavaCalls::call_virtual(&result, app_classLoader_klass, 475 vmSymbols::defineOrCheckPackage_name(), 476 vmSymbols::defineOrCheckPackage_signature(), 477 &args, 478 CHECK); 479 } 480 } 481 482 // Define Package for shared app/platform classes from named module 483 void SystemDictionaryShared::define_shared_package(Symbol* class_name, 484 Handle class_loader, 485 ModuleEntry* mod_entry, 486 TRAPS) { 487 assert(mod_entry != NULL, "module_entry should not be NULL"); 488 Handle module_handle(THREAD, mod_entry->module()); 489 490 Handle pkg_name = get_package_name(class_name, CHECK); 491 assert(pkg_name.not_null(), "Package should not be null for class in named module"); 492 493 Klass* classLoader_klass; 494 if (SystemDictionary::is_system_class_loader(class_loader())) { 495 classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass(); 496 } else { 497 assert(SystemDictionary::is_platform_class_loader(class_loader()), "unexpected classloader"); 498 classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass(); 499 } 500 501 JavaValue result(T_OBJECT); 502 JavaCallArguments args(2); 503 args.set_receiver(class_loader); 504 args.push_oop(pkg_name); 505 args.push_oop(module_handle); 506 JavaCalls::call_virtual(&result, classLoader_klass, 507 vmSymbols::definePackage_name(), 508 vmSymbols::definePackage_signature(), 509 &args, 510 CHECK); 511 } 512 513 // Get the ProtectionDomain associated with the CodeSource from the classloader. 514 Handle SystemDictionaryShared::get_protection_domain_from_classloader(Handle class_loader, 515 Handle url, TRAPS) { 516 // CodeSource cs = new CodeSource(url, null); 517 Handle cs = JavaCalls::construct_new_instance(SystemDictionary::CodeSource_klass(), 518 vmSymbols::url_code_signer_array_void_signature(), 519 url, Handle(), CHECK_NH); 520 521 // protection_domain = SecureClassLoader.getProtectionDomain(cs); 522 Klass* secureClassLoader_klass = SystemDictionary::SecureClassLoader_klass(); 523 JavaValue obj_result(T_OBJECT); 524 JavaCalls::call_virtual(&obj_result, class_loader, secureClassLoader_klass, 525 vmSymbols::getProtectionDomain_name(), 526 vmSymbols::getProtectionDomain_signature(), 527 cs, CHECK_NH); 528 return Handle(THREAD, (oop)obj_result.get_jobject()); 529 } 530 531 // Returns the ProtectionDomain associated with the JAR file identified by the url. 532 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader, 533 int shared_path_index, 534 Handle url, 535 TRAPS) { 536 Handle protection_domain; 537 if (shared_protection_domain(shared_path_index) == NULL) { 538 Handle pd = get_protection_domain_from_classloader(class_loader, url, THREAD); 539 atomic_set_shared_protection_domain(shared_path_index, pd()); 540 } 541 542 // Acquire from the cache because if another thread beats the current one to 543 // set the shared protection_domain and the atomic_set fails, the current thread 544 // needs to get the updated protection_domain from the cache. 545 protection_domain = Handle(THREAD, shared_protection_domain(shared_path_index)); 546 assert(protection_domain.not_null(), "sanity"); 547 return protection_domain; 548 } 549 550 // Returns the ProtectionDomain associated with the moduleEntry. 551 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader, 552 ModuleEntry* mod, TRAPS) { 553 ClassLoaderData *loader_data = mod->loader_data(); 554 if (mod->shared_protection_domain() == NULL) { 555 Symbol* location = mod->location(); 556 if (location != NULL) { 557 Handle location_string = java_lang_String::create_from_symbol( 558 location, CHECK_NH); 559 Handle url; 560 JavaValue result(T_OBJECT); 561 if (location->starts_with("jrt:/")) { 562 url = JavaCalls::construct_new_instance(SystemDictionary::URL_klass(), 563 vmSymbols::string_void_signature(), 564 location_string, CHECK_NH); 565 } else { 566 Klass* classLoaders_klass = 567 SystemDictionary::jdk_internal_loader_ClassLoaders_klass(); 568 JavaCalls::call_static(&result, classLoaders_klass, vmSymbols::toFileURL_name(), 569 vmSymbols::toFileURL_signature(), 570 location_string, CHECK_NH); 571 url = Handle(THREAD, (oop)result.get_jobject()); 572 } 573 574 Handle pd = get_protection_domain_from_classloader(class_loader, url, 575 CHECK_NH); 576 mod->set_shared_protection_domain(loader_data, pd); 577 } 578 } 579 580 Handle protection_domain(THREAD, mod->shared_protection_domain()); 581 assert(protection_domain.not_null(), "sanity"); 582 return protection_domain; 583 } 584 585 // Initializes the java.lang.Package and java.security.ProtectionDomain objects associated with 586 // the given InstanceKlass. 587 // Returns the ProtectionDomain for the InstanceKlass. 588 Handle SystemDictionaryShared::init_security_info(Handle class_loader, InstanceKlass* ik, PackageEntry* pkg_entry, TRAPS) { 589 Handle pd; 590 591 if (ik != NULL) { 592 int index = ik->shared_classpath_index(); 593 assert(index >= 0, "Sanity"); 594 SharedClassPathEntry* ent = FileMapInfo::shared_path(index); 595 Symbol* class_name = ik->name(); 596 597 if (ent->is_modules_image()) { 598 // For shared app/platform classes originated from the run-time image: 599 // The ProtectionDomains are cached in the corresponding ModuleEntries 600 // for fast access by the VM. 601 if (pkg_entry != NULL) { 602 ModuleEntry* mod_entry = pkg_entry->module(); 603 pd = get_shared_protection_domain(class_loader, mod_entry, THREAD); 604 define_shared_package(class_name, class_loader, mod_entry, CHECK_(pd)); 605 } 606 } else { 607 // For shared app/platform classes originated from JAR files on the class path: 608 // Each of the 3 SystemDictionaryShared::_shared_xxx arrays has the same length 609 // as the shared classpath table in the shared archive (see 610 // FileMap::_shared_path_table in filemap.hpp for details). 611 // 612 // If a shared InstanceKlass k is loaded from the class path, let 613 // 614 // index = k->shared_classpath_index(): 615 // 616 // FileMap::_shared_path_table[index] identifies the JAR file that contains k. 617 // 618 // k's protection domain is: 619 // 620 // ProtectionDomain pd = _shared_protection_domains[index]; 621 // 622 // and k's Package is initialized using 623 // 624 // manifest = _shared_jar_manifests[index]; 625 // url = _shared_jar_urls[index]; 626 // define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd)); 627 // 628 // Note that if an element of these 3 _shared_xxx arrays is NULL, it will be initialized by 629 // the corresponding SystemDictionaryShared::get_shared_xxx() function. 630 Handle manifest = get_shared_jar_manifest(index, CHECK_(pd)); 631 Handle url = get_shared_jar_url(index, CHECK_(pd)); 632 define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd)); 633 pd = get_shared_protection_domain(class_loader, index, url, CHECK_(pd)); 634 } 635 } 636 return pd; 637 } 638 639 bool SystemDictionaryShared::is_sharing_possible(ClassLoaderData* loader_data) { 640 oop class_loader = loader_data->class_loader(); 641 return (class_loader == NULL || 642 SystemDictionary::is_system_class_loader(class_loader) || 643 SystemDictionary::is_platform_class_loader(class_loader)); 644 } 645 646 // Currently AppCDS only archives classes from the run-time image, the 647 // -Xbootclasspath/a path, the class path, and the module path. 648 // 649 // Check if a shared class can be loaded by the specific classloader. Following 650 // are the "visible" archived classes for different classloaders. 651 // 652 // NULL classloader: 653 // - see SystemDictionary::is_shared_class_visible() 654 // Platform classloader: 655 // - Module class from runtime image. ModuleEntry must be defined in the 656 // classloader. 657 // App classloader: 658 // - Module Class from runtime image and module path. ModuleEntry must be defined in the 659 // classloader. 660 // - Class from -cp. The class must have no PackageEntry defined in any of the 661 // boot/platform/app classloader, or must be in the unnamed module defined in the 662 // AppClassLoader. 663 bool SystemDictionaryShared::is_shared_class_visible_for_classloader( 664 InstanceKlass* ik, 665 Handle class_loader, 666 Symbol* pkg_name, 667 PackageEntry* pkg_entry, 668 ModuleEntry* mod_entry, 669 TRAPS) { 670 assert(class_loader.not_null(), "Class loader should not be NULL"); 671 assert(Universe::is_module_initialized(), "Module system is not initialized"); 672 ResourceMark rm(THREAD); 673 674 int path_index = ik->shared_classpath_index(); 675 SharedClassPathEntry* ent = 676 (SharedClassPathEntry*)FileMapInfo::shared_path(path_index); 677 678 if (SystemDictionary::is_platform_class_loader(class_loader())) { 679 assert(ent != NULL, "shared class for PlatformClassLoader should have valid SharedClassPathEntry"); 680 // The PlatformClassLoader can only load archived class originated from the 681 // run-time image. The class' PackageEntry/ModuleEntry must be 682 // defined by the PlatformClassLoader. 683 if (mod_entry != NULL) { 684 // PackageEntry/ModuleEntry is found in the classloader. Check if the 685 // ModuleEntry's location agrees with the archived class' origination. 686 if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) { 687 return true; // Module class from the runtime image 688 } 689 } 690 } else if (SystemDictionary::is_system_class_loader(class_loader())) { 691 assert(ent != NULL, "shared class for system loader should have valid SharedClassPathEntry"); 692 if (pkg_name == NULL) { 693 // The archived class is in the unnamed package. Currently, the boot image 694 // does not contain any class in the unnamed package. 695 assert(!ent->is_modules_image(), "Class in the unnamed package must be from the classpath"); 696 if (path_index >= ClassLoaderExt::app_class_paths_start_index()) { 697 assert(path_index < ClassLoaderExt::app_module_paths_start_index(), "invalid path_index"); 698 return true; 699 } 700 } else { 701 // Check if this is from a PackageEntry/ModuleEntry defined in the AppClassloader. 702 if (pkg_entry == NULL) { 703 // It's not guaranteed that the class is from the classpath if the 704 // PackageEntry cannot be found from the AppClassloader. Need to check 705 // the boot and platform classloader as well. 706 if (get_package_entry(pkg_name, ClassLoaderData::class_loader_data_or_null(SystemDictionary::java_platform_loader())) == NULL && 707 get_package_entry(pkg_name, ClassLoaderData::the_null_class_loader_data()) == NULL) { 708 // The PackageEntry is not defined in any of the boot/platform/app classloaders. 709 // The archived class must from -cp path and not from the runtime image. 710 if (!ent->is_modules_image() && path_index >= ClassLoaderExt::app_class_paths_start_index() && 711 path_index < ClassLoaderExt::app_module_paths_start_index()) { 712 return true; 713 } 714 } 715 } else if (mod_entry != NULL) { 716 // The package/module is defined in the AppClassLoader. We support 717 // archiving application module class from the runtime image or from 718 // a named module from a module path. 719 // Packages from the -cp path are in the unnamed_module. 720 if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) { 721 // shared module class from runtime image 722 return true; 723 } else if (pkg_entry->in_unnamed_module() && path_index >= ClassLoaderExt::app_class_paths_start_index() && 724 path_index < ClassLoaderExt::app_module_paths_start_index()) { 725 // shared class from -cp 726 DEBUG_ONLY( \ 727 ClassLoaderData* loader_data = class_loader_data(class_loader); \ 728 assert(mod_entry == loader_data->unnamed_module(), "the unnamed module is not defined in the classloader");) 729 return true; 730 } else { 731 if(!pkg_entry->in_unnamed_module() && 732 (path_index >= ClassLoaderExt::app_module_paths_start_index())&& 733 (path_index < FileMapInfo::get_number_of_shared_paths()) && 734 (strcmp(ent->name(), ClassLoader::skip_uri_protocol(mod_entry->location()->as_C_string())) == 0)) { 735 // shared module class from module path 736 return true; 737 } else { 738 assert(path_index < FileMapInfo::get_number_of_shared_paths(), "invalid path_index"); 739 } 740 } 741 } 742 } 743 } else { 744 // TEMP: if a shared class can be found by a custom loader, consider it visible now. 745 // FIXME: is this actually correct? 746 return true; 747 } 748 return false; 749 } 750 751 bool SystemDictionaryShared::has_platform_or_app_classes() { 752 if (FileMapInfo::current_info()->has_platform_or_app_classes()) { 753 return true; 754 } 755 if (DynamicArchive::is_mapped() && 756 FileMapInfo::dynamic_info()->has_platform_or_app_classes()) { 757 return true; 758 } 759 return false; 760 } 761 762 // The following stack shows how this code is reached: 763 // 764 // [0] SystemDictionaryShared::find_or_load_shared_class() 765 // [1] JVM_FindLoadedClass 766 // [2] java.lang.ClassLoader.findLoadedClass0() 767 // [3] java.lang.ClassLoader.findLoadedClass() 768 // [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull() 769 // [5] jdk.internal.loader.BuiltinClassLoader.loadClass() 770 // [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or 771 // jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass() 772 // 773 // AppCDS supports fast class loading for these 2 built-in class loaders: 774 // jdk.internal.loader.ClassLoaders$PlatformClassLoader 775 // jdk.internal.loader.ClassLoaders$AppClassLoader 776 // with the following assumptions (based on the JDK core library source code): 777 // 778 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to 779 // load the named class. 780 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name). 781 // [c] At this point, if we can find the named class inside the 782 // shared_dictionary, we can perform further checks (see 783 // is_shared_class_visible_for_classloader() to ensure that this class 784 // was loaded by the same class loader during dump time. 785 // 786 // Given these assumptions, we intercept the findLoadedClass() call to invoke 787 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from 788 // the archive for the 2 built-in class loaders. This way, 789 // we can improve start-up because we avoid decoding the classfile, 790 // and avoid delegating to the parent loader. 791 // 792 // NOTE: there's a lot of assumption about the Java code. If any of that change, this 793 // needs to be redesigned. 794 795 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class( 796 Symbol* name, Handle class_loader, TRAPS) { 797 InstanceKlass* k = NULL; 798 if (UseSharedSpaces) { 799 if (!has_platform_or_app_classes()) { 800 return NULL; 801 } 802 803 if (SystemDictionary::is_system_class_loader(class_loader()) || 804 SystemDictionary::is_platform_class_loader(class_loader())) { 805 // Fix for 4474172; see evaluation for more details 806 class_loader = Handle( 807 THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader())); 808 ClassLoaderData *loader_data = register_loader(class_loader); 809 Dictionary* dictionary = loader_data->dictionary(); 810 811 unsigned int d_hash = dictionary->compute_hash(name); 812 813 bool DoObjectLock = true; 814 if (is_parallelCapable(class_loader)) { 815 DoObjectLock = false; 816 } 817 818 // Make sure we are synchronized on the class loader before we proceed 819 // 820 // Note: currently, find_or_load_shared_class is called only from 821 // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader, 822 // which are parallel-capable loaders, so this lock is NOT taken. 823 Handle lockObject = compute_loader_lock_object(class_loader, THREAD); 824 check_loader_lock_contention(lockObject, THREAD); 825 ObjectLocker ol(lockObject, THREAD, DoObjectLock); 826 827 { 828 MutexLocker mu(THREAD, SystemDictionary_lock); 829 InstanceKlass* check = find_class(d_hash, name, dictionary); 830 if (check != NULL) { 831 return check; 832 } 833 } 834 835 k = load_shared_class_for_builtin_loader(name, class_loader, THREAD); 836 if (k != NULL) { 837 define_instance_class(k, CHECK_NULL); 838 } 839 } 840 } 841 return k; 842 } 843 844 PackageEntry* SystemDictionaryShared::get_package_entry_from_class_name(Handle class_loader, Symbol* class_name) { 845 PackageEntry* pkg_entry = NULL; 846 TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name); 847 if (pkg_name != NULL) { 848 pkg_entry = class_loader_data(class_loader)->packages()->lookup_only(pkg_name); 849 } 850 return pkg_entry; 851 } 852 853 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader( 854 Symbol* class_name, Handle class_loader, TRAPS) { 855 assert(UseSharedSpaces, "must be"); 856 InstanceKlass* ik = find_builtin_class(class_name); 857 858 if (ik != NULL) { 859 if ((ik->is_shared_app_class() && 860 SystemDictionary::is_system_class_loader(class_loader())) || 861 (ik->is_shared_platform_class() && 862 SystemDictionary::is_platform_class_loader(class_loader()))) { 863 PackageEntry* pkg_entry = get_package_entry_from_class_name(class_loader, class_name); 864 Handle protection_domain = 865 SystemDictionaryShared::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL); 866 return load_shared_class(ik, class_loader, protection_domain, NULL, pkg_entry, THREAD); 867 } 868 } 869 return NULL; 870 } 871 872 void SystemDictionaryShared::oops_do(OopClosure* f) { 873 f->do_oop((oop*)&_shared_protection_domains); 874 f->do_oop((oop*)&_shared_jar_urls); 875 f->do_oop((oop*)&_shared_jar_manifests); 876 } 877 878 void SystemDictionaryShared::allocate_shared_protection_domain_array(int size, TRAPS) { 879 if (_shared_protection_domains == NULL) { 880 _shared_protection_domains = oopFactory::new_objArray( 881 SystemDictionary::ProtectionDomain_klass(), size, CHECK); 882 } 883 } 884 885 void SystemDictionaryShared::allocate_shared_jar_url_array(int size, TRAPS) { 886 if (_shared_jar_urls == NULL) { 887 _shared_jar_urls = oopFactory::new_objArray( 888 SystemDictionary::URL_klass(), size, CHECK); 889 } 890 } 891 892 void SystemDictionaryShared::allocate_shared_jar_manifest_array(int size, TRAPS) { 893 if (_shared_jar_manifests == NULL) { 894 _shared_jar_manifests = oopFactory::new_objArray( 895 SystemDictionary::Jar_Manifest_klass(), size, CHECK); 896 } 897 } 898 899 void SystemDictionaryShared::allocate_shared_data_arrays(int size, TRAPS) { 900 allocate_shared_protection_domain_array(size, CHECK); 901 allocate_shared_jar_url_array(size, CHECK); 902 allocate_shared_jar_manifest_array(size, CHECK); 903 } 904 905 // This function is called for loading only UNREGISTERED classes 906 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name, 907 Handle class_loader, 908 Handle protection_domain, 909 const ClassFileStream* cfs, 910 TRAPS) { 911 if (!UseSharedSpaces) { 912 return NULL; 913 } 914 if (class_name == NULL) { // don't do this for anonymous classes 915 return NULL; 916 } 917 if (class_loader.is_null() || 918 SystemDictionary::is_system_class_loader(class_loader()) || 919 SystemDictionary::is_platform_class_loader(class_loader())) { 920 // Do nothing for the BUILTIN loaders. 921 return NULL; 922 } 923 924 const RunTimeSharedClassInfo* record = find_record(&_unregistered_dictionary, &_dynamic_unregistered_dictionary, class_name); 925 if (record == NULL) { 926 return NULL; 927 } 928 929 int clsfile_size = cfs->length(); 930 int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length()); 931 932 if (!record->matches(clsfile_size, clsfile_crc32)) { 933 return NULL; 934 } 935 936 return acquire_class_for_current_thread(record->_klass, class_loader, 937 protection_domain, cfs, 938 THREAD); 939 } 940 941 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread( 942 InstanceKlass *ik, 943 Handle class_loader, 944 Handle protection_domain, 945 const ClassFileStream *cfs, 946 TRAPS) { 947 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader()); 948 949 { 950 MutexLocker mu(THREAD, SharedDictionary_lock); 951 if (ik->class_loader_data() != NULL) { 952 // ik is already loaded (by this loader or by a different loader) 953 // or ik is being loaded by a different thread (by this loader or by a different loader) 954 return NULL; 955 } 956 957 // No other thread has acquired this yet, so give it to *this thread* 958 ik->set_class_loader_data(loader_data); 959 } 960 961 // No longer holding SharedDictionary_lock 962 // No need to lock, as <ik> can be held only by a single thread. 963 loader_data->add_class(ik); 964 965 // Get the package entry. 966 PackageEntry* pkg_entry = get_package_entry_from_class_name(class_loader, ik->name()); 967 968 // Load and check super/interfaces, restore unsharable info 969 InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain, 970 cfs, pkg_entry, THREAD); 971 if (shared_klass == NULL || HAS_PENDING_EXCEPTION) { 972 // TODO: clean up <ik> so it can be used again 973 return NULL; 974 } 975 976 return shared_klass; 977 } 978 979 static ResourceHashtable< 980 Symbol*, bool, 981 primitive_hash<Symbol*>, 982 primitive_equals<Symbol*>, 983 6661, // prime number 984 ResourceObj::C_HEAP> _loaded_unregistered_classes; 985 986 bool SystemDictionaryShared::add_unregistered_class(InstanceKlass* k, TRAPS) { 987 assert(DumpSharedSpaces, "only when dumping"); 988 989 Symbol* name = k->name(); 990 if (_loaded_unregistered_classes.get(name) != NULL) { 991 // We don't allow duplicated unregistered classes of the same name. 992 return false; 993 } else { 994 bool isnew = _loaded_unregistered_classes.put(name, true); 995 assert(isnew, "sanity"); 996 MutexLocker mu_r(THREAD, Compile_lock); // add_to_hierarchy asserts this. 997 SystemDictionary::add_to_hierarchy(k, CHECK_false); 998 return true; 999 } 1000 } 1001 1002 // This function is called to resolve the super/interfaces of shared classes for 1003 // non-built-in loaders. E.g., ChildClass in the below example 1004 // where "super:" (and optionally "interface:") have been specified. 1005 // 1006 // java/lang/Object id: 0 1007 // Interface id: 2 super: 0 source: cust.jar 1008 // ChildClass id: 4 super: 0 interfaces: 2 source: cust.jar 1009 InstanceKlass* SystemDictionaryShared::dump_time_resolve_super_or_fail( 1010 Symbol* child_name, Symbol* class_name, Handle class_loader, 1011 Handle protection_domain, bool is_superclass, TRAPS) { 1012 1013 assert(DumpSharedSpaces, "only when dumping"); 1014 1015 ClassListParser* parser = ClassListParser::instance(); 1016 if (parser == NULL) { 1017 // We're still loading the well-known classes, before the ClassListParser is created. 1018 return NULL; 1019 } 1020 if (child_name->equals(parser->current_class_name())) { 1021 // When this function is called, all the numbered super and interface types 1022 // must have already been loaded. Hence this function is never recursively called. 1023 if (is_superclass) { 1024 return parser->lookup_super_for_current_class(class_name); 1025 } else { 1026 return parser->lookup_interface_for_current_class(class_name); 1027 } 1028 } else { 1029 // The VM is not trying to resolve a super type of parser->current_class_name(). 1030 // Instead, it's resolving an error class (because parser->current_class_name() has 1031 // failed parsing or verification). Don't do anything here. 1032 return NULL; 1033 } 1034 } 1035 1036 DumpTimeSharedClassInfo* SystemDictionaryShared::find_or_allocate_info_for(InstanceKlass* k) { 1037 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 1038 if (_dumptime_table == NULL) { 1039 _dumptime_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeSharedClassTable(); 1040 } 1041 return _dumptime_table->find_or_allocate_info_for(k); 1042 } 1043 1044 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) { 1045 Arguments::assert_is_dumping_archive(); 1046 assert(!is_builtin(k), "must be unregistered class"); 1047 DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k); 1048 info->_clsfile_size = cfs->length(); 1049 info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length()); 1050 } 1051 1052 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) { 1053 (void)find_or_allocate_info_for(k); 1054 } 1055 1056 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) { 1057 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 1058 DumpTimeSharedClassInfo* p = _dumptime_table->get(k); 1059 if (p == NULL) { 1060 return; 1061 } 1062 if (p->_verifier_constraints != NULL) { 1063 for (int i = 0; i < p->_verifier_constraints->length(); i++) { 1064 DumpTimeSharedClassInfo::DTConstraint constraint = p->_verifier_constraints->at(i); 1065 if (constraint._name != NULL ) { 1066 constraint._name->decrement_refcount(); 1067 } 1068 if (constraint._from_name != NULL ) { 1069 constraint._from_name->decrement_refcount(); 1070 } 1071 } 1072 FREE_C_HEAP_ARRAY(DTConstraint, p->_verifier_constraints); 1073 p->_verifier_constraints = NULL; 1074 } 1075 FREE_C_HEAP_ARRAY(char, p->_verifier_constraint_flags); 1076 p->_verifier_constraint_flags = NULL; 1077 _dumptime_table->remove(k); 1078 } 1079 1080 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) { 1081 while (k) { 1082 if (k->name()->equals("jdk/internal/event/Event")) { 1083 return true; 1084 } 1085 k = k->java_super(); 1086 } 1087 return false; 1088 } 1089 1090 void SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) { 1091 ResourceMark rm; 1092 log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason); 1093 } 1094 1095 bool SystemDictionaryShared::should_be_excluded(InstanceKlass* k) { 1096 if (k->class_loader_data()->is_unsafe_anonymous()) { 1097 warn_excluded(k, "Unsafe anonymous class"); 1098 return true; // unsafe anonymous classes are not archived, skip 1099 } 1100 if (k->is_in_error_state()) { 1101 warn_excluded(k, "In error state"); 1102 return true; 1103 } 1104 if (k->has_been_redefined()) { 1105 warn_excluded(k, "Has been redefined"); 1106 return true; 1107 } 1108 if (k->shared_classpath_index() < 0 && is_builtin(k)) { 1109 // These are classes loaded from unsupported locations (such as those loaded by JVMTI native 1110 // agent during dump time). 1111 warn_excluded(k, "Unsupported location"); 1112 return true; 1113 } 1114 if (k->signers() != NULL) { 1115 // We cannot include signed classes in the archive because the certificates 1116 // used during dump time may be different than those used during 1117 // runtime (due to expiration, etc). 1118 warn_excluded(k, "Signed JAR"); 1119 return true; 1120 } 1121 if (is_jfr_event_class(k)) { 1122 // We cannot include JFR event classes because they need runtime-specific 1123 // instrumentation in order to work with -XX:FlightRecorderOptions=retransform=false. 1124 // There are only a small number of these classes, so it's not worthwhile to 1125 // support them and make CDS more complicated. 1126 warn_excluded(k, "JFR event class"); 1127 return true; 1128 } 1129 if (k->init_state() < InstanceKlass::linked) { 1130 // In CDS dumping, we will attempt to link all classes. Those that fail to link will 1131 // be recorded in DumpTimeSharedClassInfo. 1132 Arguments::assert_is_dumping_archive(); 1133 1134 // TODO -- rethink how this can be handled. 1135 // We should try to link ik, however, we can't do it here because 1136 // 1. We are at VM exit 1137 // 2. linking a class may cause other classes to be loaded, which means 1138 // a custom ClassLoader.loadClass() may be called, at a point where the 1139 // class loader doesn't expect it. 1140 if (has_class_failed_verification(k)) { 1141 warn_excluded(k, "Failed verification"); 1142 } else { 1143 warn_excluded(k, "Not linked"); 1144 } 1145 return true; 1146 } 1147 if (k->major_version() < 50 /*JAVA_6_VERSION*/) { 1148 ResourceMark rm; 1149 log_warning(cds)("Pre JDK 6 class not supported by CDS: %u.%u %s", 1150 k->major_version(), k->minor_version(), k->name()->as_C_string()); 1151 return true; 1152 } 1153 1154 InstanceKlass* super = k->java_super(); 1155 if (super != NULL && should_be_excluded(super)) { 1156 ResourceMark rm; 1157 log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string()); 1158 return true; 1159 } 1160 1161 Array<InstanceKlass*>* interfaces = k->local_interfaces(); 1162 int len = interfaces->length(); 1163 for (int i = 0; i < len; i++) { 1164 InstanceKlass* intf = interfaces->at(i); 1165 if (should_be_excluded(intf)) { 1166 log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string()); 1167 return true; 1168 } 1169 } 1170 1171 return false; 1172 } 1173 1174 // k is a class before relocating by ArchiveCompactor 1175 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) { 1176 ResourceMark rm; 1177 const char* name = k->name()->as_C_string(); 1178 DumpTimeSharedClassInfo* info = _dumptime_table->get(k); 1179 assert(_no_class_loading_should_happen, "class loading must be disabled"); 1180 guarantee(info != NULL, "Class %s must be entered into _dumptime_table", name); 1181 guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name); 1182 if (is_builtin(k)) { 1183 guarantee(!k->is_shared_unregistered_class(), 1184 "Class loader type must be set for BUILTIN class %s", name); 1185 } else { 1186 guarantee(k->is_shared_unregistered_class(), 1187 "Class loader type must not be set for UNREGISTERED class %s", name); 1188 } 1189 } 1190 1191 class ExcludeDumpTimeSharedClasses : StackObj { 1192 public: 1193 bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) { 1194 if (SystemDictionaryShared::should_be_excluded(k)) { 1195 info.set_excluded(); 1196 } 1197 return true; // keep on iterating 1198 } 1199 }; 1200 1201 void SystemDictionaryShared::check_excluded_classes() { 1202 ExcludeDumpTimeSharedClasses excl; 1203 _dumptime_table->iterate(&excl); 1204 _dumptime_table->update_counts(); 1205 } 1206 1207 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) { 1208 assert(_no_class_loading_should_happen, "sanity"); 1209 Arguments::assert_is_dumping_archive(); 1210 return find_or_allocate_info_for(k)->is_excluded(); 1211 } 1212 1213 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) { 1214 Arguments::assert_is_dumping_archive(); 1215 find_or_allocate_info_for(ik)->set_failed_verification(); 1216 } 1217 1218 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) { 1219 Arguments::assert_is_dumping_archive(); 1220 if (_dumptime_table == NULL) { 1221 assert(DynamicDumpSharedSpaces, "sanity"); 1222 assert(ik->is_shared(), "must be a shared class in the static archive"); 1223 return false; 1224 } 1225 DumpTimeSharedClassInfo* p = _dumptime_table->get(ik); 1226 return (p == NULL) ? false : p->failed_verification(); 1227 } 1228 1229 class IterateDumpTimeSharedClassTable : StackObj { 1230 MetaspaceClosure *_it; 1231 public: 1232 IterateDumpTimeSharedClassTable(MetaspaceClosure* it) : _it(it) {} 1233 1234 bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) { 1235 if (!info.is_excluded()) { 1236 info.metaspace_pointers_do(_it); 1237 } 1238 return true; // keep on iterating 1239 } 1240 }; 1241 1242 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) { 1243 IterateDumpTimeSharedClassTable iter(it); 1244 _dumptime_table->iterate(&iter); 1245 } 1246 1247 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name, 1248 Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) { 1249 Arguments::assert_is_dumping_archive(); 1250 DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k); 1251 info->add_verification_constraint(k, name, from_name, from_field_is_protected, 1252 from_is_array, from_is_object); 1253 1254 if (DynamicDumpSharedSpaces) { 1255 // For dynamic dumping, we can resolve all the constraint classes for all class loaders during 1256 // the initial run prior to creating the archive before vm exit. We will also perform verification 1257 // check when running with the archive. 1258 return false; 1259 } else { 1260 if (is_builtin(k)) { 1261 // For builtin class loaders, we can try to complete the verification check at dump time, 1262 // because we can resolve all the constraint classes. We will also perform verification check 1263 // when running with the archive. 1264 return false; 1265 } else { 1266 // For non-builtin class loaders, we cannot complete the verification check at dump time, 1267 // because at dump time we don't know how to resolve classes for such loaders. 1268 return true; 1269 } 1270 } 1271 } 1272 1273 void DumpTimeSharedClassInfo::add_verification_constraint(InstanceKlass* k, Symbol* name, 1274 Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) { 1275 if (_verifier_constraints == NULL) { 1276 _verifier_constraints = new(ResourceObj::C_HEAP, mtClass) GrowableArray<DTConstraint>(4, true, mtClass); 1277 } 1278 if (_verifier_constraint_flags == NULL) { 1279 _verifier_constraint_flags = new(ResourceObj::C_HEAP, mtClass) GrowableArray<char>(4, true, mtClass); 1280 } 1281 GrowableArray<DTConstraint>* vc_array = _verifier_constraints; 1282 for (int i = 0; i < vc_array->length(); i++) { 1283 DTConstraint* p = vc_array->adr_at(i); 1284 if (name == p->_name && from_name == p->_from_name) { 1285 return; 1286 } 1287 } 1288 DTConstraint cons(name, from_name); 1289 vc_array->append(cons); 1290 1291 GrowableArray<char>* vcflags_array = _verifier_constraint_flags; 1292 char c = 0; 1293 c |= from_field_is_protected ? SystemDictionaryShared::FROM_FIELD_IS_PROTECTED : 0; 1294 c |= from_is_array ? SystemDictionaryShared::FROM_IS_ARRAY : 0; 1295 c |= from_is_object ? SystemDictionaryShared::FROM_IS_OBJECT : 0; 1296 vcflags_array->append(c); 1297 1298 if (log_is_enabled(Trace, cds, verification)) { 1299 ResourceMark rm; 1300 log_trace(cds, verification)("add_verification_constraint: %s: %s must be subclass of %s [0x%x]", 1301 k->external_name(), from_name->as_klass_external_name(), 1302 name->as_klass_external_name(), c); 1303 } 1304 } 1305 1306 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass, 1307 TRAPS) { 1308 assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only"); 1309 RunTimeSharedClassInfo* record = RunTimeSharedClassInfo::get_for(klass); 1310 1311 int length = record->_num_constraints; 1312 if (length > 0) { 1313 for (int i = 0; i < length; i++) { 1314 Symbol* name = record->get_constraint_name(i); 1315 Symbol* from_name = record->get_constraint_from_name(i); 1316 char c = record->get_constraint_flag(i); 1317 1318 if (log_is_enabled(Trace, cds, verification)) { 1319 ResourceMark rm(THREAD); 1320 log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]", 1321 klass->external_name(), from_name->as_klass_external_name(), 1322 name->as_klass_external_name(), c); 1323 } 1324 1325 bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false; 1326 bool from_is_array = (c & SystemDictionaryShared::FROM_IS_ARRAY) ? true : false; 1327 bool from_is_object = (c & SystemDictionaryShared::FROM_IS_OBJECT) ? true : false; 1328 1329 bool ok = VerificationType::resolve_and_check_assignability(klass, name, 1330 from_name, from_field_is_protected, from_is_array, from_is_object, CHECK); 1331 if (!ok) { 1332 ResourceMark rm(THREAD); 1333 stringStream ss; 1334 1335 ss.print_cr("Bad type on operand stack"); 1336 ss.print_cr("Exception Details:"); 1337 ss.print_cr(" Location:\n %s", klass->name()->as_C_string()); 1338 ss.print_cr(" Reason:\n Type '%s' is not assignable to '%s'", 1339 from_name->as_quoted_ascii(), name->as_quoted_ascii()); 1340 THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string()); 1341 } 1342 } 1343 } 1344 } 1345 1346 class EstimateSizeForArchive : StackObj { 1347 size_t _shared_class_info_size; 1348 int _num_builtin_klasses; 1349 int _num_unregistered_klasses; 1350 1351 public: 1352 EstimateSizeForArchive() { 1353 _shared_class_info_size = 0; 1354 _num_builtin_klasses = 0; 1355 _num_unregistered_klasses = 0; 1356 } 1357 1358 bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) { 1359 if (!info.is_excluded()) { 1360 size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_constraints()); 1361 _shared_class_info_size += align_up(byte_size, BytesPerWord); 1362 } 1363 return true; // keep on iterating 1364 } 1365 1366 size_t total() { 1367 return _shared_class_info_size; 1368 } 1369 }; 1370 1371 size_t SystemDictionaryShared::estimate_size_for_archive() { 1372 EstimateSizeForArchive est; 1373 _dumptime_table->iterate(&est); 1374 return est.total() + 1375 CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) + 1376 CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false)); 1377 } 1378 1379 class CopySharedClassInfoToArchive : StackObj { 1380 CompactHashtableWriter* _writer; 1381 bool _is_builtin; 1382 public: 1383 CopySharedClassInfoToArchive(CompactHashtableWriter* writer, 1384 bool is_builtin, 1385 bool is_static_archive) 1386 : _writer(writer), _is_builtin(is_builtin) {} 1387 1388 bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) { 1389 if (!info.is_excluded() && info.is_builtin() == _is_builtin) { 1390 size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_constraints()); 1391 RunTimeSharedClassInfo* record; 1392 record = (RunTimeSharedClassInfo*)MetaspaceShared::read_only_space_alloc(byte_size); 1393 record->init(info); 1394 1395 unsigned int hash; 1396 Symbol* name = info._klass->name(); 1397 if (DynamicDumpSharedSpaces) { 1398 name = DynamicArchive::original_to_target(name); 1399 } 1400 hash = SystemDictionaryShared::hash_for_shared_dictionary(name); 1401 u4 delta; 1402 if (DynamicDumpSharedSpaces) { 1403 delta = MetaspaceShared::object_delta_u4(DynamicArchive::buffer_to_target(record)); 1404 } else { 1405 delta = MetaspaceShared::object_delta_u4(record); 1406 } 1407 _writer->add(hash, delta); 1408 if (log_is_enabled(Trace, cds, hashtables)) { 1409 ResourceMark rm; 1410 log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name()); 1411 } 1412 1413 // Save this for quick runtime lookup of InstanceKlass* -> RunTimeSharedClassInfo* 1414 RunTimeSharedClassInfo::set_for(info._klass, record); 1415 } 1416 return true; // keep on iterating 1417 } 1418 }; 1419 1420 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary, 1421 bool is_builtin, 1422 bool is_static_archive) { 1423 CompactHashtableStats stats; 1424 dictionary->reset(); 1425 CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats); 1426 CopySharedClassInfoToArchive copy(&writer, is_builtin, is_static_archive); 1427 _dumptime_table->iterate(©); 1428 writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary"); 1429 } 1430 1431 void SystemDictionaryShared::write_to_archive(bool is_static_archive) { 1432 if (is_static_archive) { 1433 write_dictionary(&_builtin_dictionary, true); 1434 write_dictionary(&_unregistered_dictionary, false); 1435 } else { 1436 write_dictionary(&_dynamic_builtin_dictionary, true); 1437 write_dictionary(&_dynamic_unregistered_dictionary, false); 1438 } 1439 } 1440 1441 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc, 1442 bool is_static_archive) { 1443 if (is_static_archive) { 1444 _builtin_dictionary.serialize_header(soc); 1445 _unregistered_dictionary.serialize_header(soc); 1446 } else { 1447 _dynamic_builtin_dictionary.serialize_header(soc); 1448 _dynamic_unregistered_dictionary.serialize_header(soc); 1449 } 1450 } 1451 1452 void SystemDictionaryShared::serialize_well_known_klasses(SerializeClosure* soc) { 1453 for (int i = FIRST_WKID; i < WKID_LIMIT; i++) { 1454 soc->do_ptr((void**)&_well_known_klasses[i]); 1455 } 1456 } 1457 1458 const RunTimeSharedClassInfo* 1459 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) { 1460 if (!UseSharedSpaces || !name->is_shared()) { 1461 // The names of all shared classes must also be a shared Symbol. 1462 return NULL; 1463 } 1464 1465 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary(name); 1466 const RunTimeSharedClassInfo* record = NULL; 1467 if (!MetaspaceShared::is_shared_dynamic(name)) { 1468 // The names of all shared classes in the static dict must also be in the 1469 // static archive 1470 record = static_dict->lookup(name, hash, 0); 1471 } 1472 1473 if (record == NULL && DynamicArchive::is_mapped()) { 1474 record = dynamic_dict->lookup(name, hash, 0); 1475 } 1476 1477 return record; 1478 } 1479 1480 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) { 1481 const RunTimeSharedClassInfo* record = find_record(&_builtin_dictionary, &_dynamic_builtin_dictionary, name); 1482 if (record != NULL) { 1483 return record->_klass; 1484 } else { 1485 return NULL; 1486 } 1487 } 1488 1489 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) { 1490 assert(DumpSharedSpaces, "supported only when dumping"); 1491 DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k); 1492 info->_id = id; 1493 } 1494 1495 class SharedDictionaryPrinter : StackObj { 1496 outputStream* _st; 1497 int _index; 1498 public: 1499 SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {} 1500 1501 void do_value(const RunTimeSharedClassInfo* record) { 1502 ResourceMark rm; 1503 _st->print_cr("%4d: %s", (_index++), record->_klass->external_name()); 1504 } 1505 }; 1506 1507 void SystemDictionaryShared::print_on(outputStream* st) { 1508 if (UseSharedSpaces) { 1509 st->print_cr("Shared Dictionary"); 1510 SharedDictionaryPrinter p(st); 1511 _builtin_dictionary.iterate(&p); 1512 _unregistered_dictionary.iterate(&p); 1513 if (DynamicArchive::is_mapped()) { 1514 _dynamic_builtin_dictionary.iterate(&p); 1515 _unregistered_dictionary.iterate(&p); 1516 } 1517 } 1518 } 1519 1520 void SystemDictionaryShared::print_table_statistics(outputStream* st) { 1521 if (UseSharedSpaces) { 1522 _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary"); 1523 _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary"); 1524 if (DynamicArchive::is_mapped()) { 1525 _dynamic_builtin_dictionary.print_table_statistics(st, "Dynamic Builtin Shared Dictionary"); 1526 _dynamic_unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary"); 1527 } 1528 } 1529 } 1530 1531 bool SystemDictionaryShared::empty_dumptime_table() { 1532 if (_dumptime_table == NULL) { 1533 return true; 1534 } 1535 _dumptime_table->update_counts(); 1536 if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){ 1537 return true; 1538 } 1539 return false; 1540 }