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