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/javaClasses.inline.hpp"
35 #include "classfile/symbolTable.hpp"
36 #include "classfile/systemDictionary.hpp"
37 #include "classfile/systemDictionaryShared.hpp"
38 #include "classfile/verificationType.hpp"
39 #include "classfile/vmSymbols.hpp"
40 #include "interpreter/bootstrapInfo.hpp"
41 #include "jfr/jfrEvents.hpp"
42 #include "logging/log.hpp"
43 #include "logging/logStream.hpp"
44 #include "memory/allocation.hpp"
45 #include "memory/archiveUtils.hpp"
46 #include "memory/dynamicArchive.hpp"
47 #include "memory/filemap.hpp"
48 #include "memory/heapShared.hpp"
49 #include "memory/metadataFactory.hpp"
50 #include "memory/metaspaceClosure.hpp"
51 #include "memory/metaspaceShared.hpp"
52 #include "memory/oopFactory.hpp"
53 #include "memory/resourceArea.hpp"
54 #include "memory/universe.hpp"
55 #include "oops/instanceKlass.hpp"
56 #include "oops/klass.inline.hpp"
57 #include "oops/objArrayOop.inline.hpp"
58 #include "oops/oop.inline.hpp"
59 #include "oops/oopHandle.inline.hpp"
60 #include "oops/typeArrayOop.inline.hpp"
61 #include "prims/jvmtiExport.hpp"
62 #include "runtime/handles.inline.hpp"
63 #include "runtime/java.hpp"
64 #include "runtime/javaCalls.hpp"
65 #include "runtime/mutexLocker.hpp"
66 #include "utilities/hashtable.inline.hpp"
67 #include "utilities/resourceHash.hpp"
68 #include "utilities/stringUtils.hpp"
69 
70 
71 OopHandle SystemDictionaryShared::_shared_protection_domains;
72 OopHandle SystemDictionaryShared::_shared_jar_urls;
73 OopHandle SystemDictionaryShared::_shared_jar_manifests;
74 DEBUG_ONLY(bool SystemDictionaryShared::_no_class_loading_should_happen = false;)
75 bool SystemDictionaryShared::_dump_in_progress = false;
76 
77 class DumpTimeSharedClassInfo: public CHeapObj<mtClass> {
78   bool                         _excluded;
79   bool                         _is_early_klass;
80 public:
81   struct DTLoaderConstraint {
82     Symbol* _name;
83     char _loader_type1;
84     char _loader_type2;
DTLoaderConstraintDumpTimeSharedClassInfo::DTLoaderConstraint85     DTLoaderConstraint(Symbol* name, char l1, char l2) : _name(name), _loader_type1(l1), _loader_type2(l2) {
86       _name->increment_refcount();
87     }
DTLoaderConstraintDumpTimeSharedClassInfo::DTLoaderConstraint88     DTLoaderConstraint() : _name(NULL), _loader_type1('0'), _loader_type2('0') {}
equalsDumpTimeSharedClassInfo::DTLoaderConstraint89     bool equals(const DTLoaderConstraint& t) {
90       return t._name == _name &&
91              ((t._loader_type1 == _loader_type1 && t._loader_type2 == _loader_type2) ||
92               (t._loader_type2 == _loader_type1 && t._loader_type1 == _loader_type2));
93     }
94   };
95 
96   struct DTVerifierConstraint {
97     Symbol* _name;
98     Symbol* _from_name;
DTVerifierConstraintDumpTimeSharedClassInfo::DTVerifierConstraint99     DTVerifierConstraint() : _name(NULL), _from_name(NULL) {}
DTVerifierConstraintDumpTimeSharedClassInfo::DTVerifierConstraint100     DTVerifierConstraint(Symbol* n, Symbol* fn) : _name(n), _from_name(fn) {
101       _name->increment_refcount();
102       _from_name->increment_refcount();
103     }
104   };
105 
106   InstanceKlass*               _klass;
107   InstanceKlass*               _nest_host;
108   bool                         _failed_verification;
109   bool                         _is_archived_lambda_proxy;
110   int                          _id;
111   int                          _clsfile_size;
112   int                          _clsfile_crc32;
113   GrowableArray<DTVerifierConstraint>* _verifier_constraints;
114   GrowableArray<char>*                 _verifier_constraint_flags;
115   GrowableArray<DTLoaderConstraint>* _loader_constraints;
116 
DumpTimeSharedClassInfo()117   DumpTimeSharedClassInfo() {
118     _klass = NULL;
119     _nest_host = NULL;
120     _failed_verification = false;
121     _is_archived_lambda_proxy = false;
122     _id = -1;
123     _clsfile_size = -1;
124     _clsfile_crc32 = -1;
125     _excluded = false;
126     _is_early_klass = JvmtiExport::is_early_phase();
127     _verifier_constraints = NULL;
128     _verifier_constraint_flags = NULL;
129     _loader_constraints = NULL;
130   }
131 
132   void add_verification_constraint(InstanceKlass* k, Symbol* name,
133          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object);
134   void record_linking_constraint(Symbol* name, Handle loader1, Handle loader2);
135 
is_builtin()136   bool is_builtin() {
137     return SystemDictionaryShared::is_builtin(_klass);
138   }
139 
num_verifier_constraints()140   int num_verifier_constraints() {
141     if (_verifier_constraint_flags != NULL) {
142       return _verifier_constraint_flags->length();
143     } else {
144       return 0;
145     }
146   }
147 
num_loader_constraints()148   int num_loader_constraints() {
149     if (_loader_constraints != NULL) {
150       return _loader_constraints->length();
151     } else {
152       return 0;
153     }
154   }
155 
metaspace_pointers_do(MetaspaceClosure * it)156   void metaspace_pointers_do(MetaspaceClosure* it) {
157     it->push(&_klass);
158     it->push(&_nest_host);
159     if (_verifier_constraints != NULL) {
160       for (int i = 0; i < _verifier_constraints->length(); i++) {
161         DTVerifierConstraint* cons = _verifier_constraints->adr_at(i);
162         it->push(&cons->_name);
163         it->push(&cons->_from_name);
164       }
165     }
166     if (_loader_constraints != NULL) {
167       for (int i = 0; i < _loader_constraints->length(); i++) {
168         DTLoaderConstraint* lc = _loader_constraints->adr_at(i);
169         it->push(&lc->_name);
170       }
171     }
172   }
173 
set_excluded()174   void set_excluded() {
175     _excluded = true;
176   }
177 
is_excluded()178   bool is_excluded() {
179     // _klass may become NULL due to DynamicArchiveBuilder::set_to_null
180     return _excluded || _failed_verification || _klass == NULL;
181   }
182 
183   // Was this class loaded while JvmtiExport::is_early_phase()==true
is_early_klass()184   bool is_early_klass() {
185     return _is_early_klass;
186   }
187 
set_failed_verification()188   void set_failed_verification() {
189     _failed_verification = true;
190   }
191 
failed_verification()192   bool failed_verification() {
193     return _failed_verification;
194   }
195 
set_nest_host(InstanceKlass * nest_host)196   void set_nest_host(InstanceKlass* nest_host) {
197     _nest_host = nest_host;
198   }
199 
nest_host()200   InstanceKlass* nest_host() {
201     return _nest_host;
202   }
203 };
204 
DumpTimeSharedClassTable_hash(InstanceKlass * const & k)205 inline unsigned DumpTimeSharedClassTable_hash(InstanceKlass* const& k) {
206   if (DumpSharedSpaces) {
207     // Deterministic archive contents
208     uintx delta = k->name() - MetaspaceShared::symbol_rs_base();
209     return primitive_hash<uintx>(delta);
210   } else {
211     // Deterministic archive is not possible because classes can be loaded
212     // in multiple threads.
213     return primitive_hash<InstanceKlass*>(k);
214   }
215 }
216 
217 class DumpTimeSharedClassTable: public ResourceHashtable<
218   InstanceKlass*,
219   DumpTimeSharedClassInfo,
220   &DumpTimeSharedClassTable_hash,
221   primitive_equals<InstanceKlass*>,
222   15889, // prime number
223   ResourceObj::C_HEAP>
224 {
225   int _builtin_count;
226   int _unregistered_count;
227 public:
find_or_allocate_info_for(InstanceKlass * k,bool dump_in_progress)228   DumpTimeSharedClassInfo* find_or_allocate_info_for(InstanceKlass* k, bool dump_in_progress) {
229     bool created = false;
230     DumpTimeSharedClassInfo* p;
231     if (!dump_in_progress) {
232       p = put_if_absent(k, &created);
233     } else {
234       p = get(k);
235     }
236     if (created) {
237       assert(!SystemDictionaryShared::no_class_loading_should_happen(),
238              "no new classes can be loaded while dumping archive");
239       p->_klass = k;
240     } else {
241       if (!dump_in_progress) {
242         assert(p->_klass == k, "Sanity");
243       }
244     }
245     return p;
246   }
247 
248   class CountClassByCategory : StackObj {
249     DumpTimeSharedClassTable* _table;
250   public:
CountClassByCategory(DumpTimeSharedClassTable * table)251     CountClassByCategory(DumpTimeSharedClassTable* table) : _table(table) {}
do_entry(InstanceKlass * k,DumpTimeSharedClassInfo & info)252     bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
253       if (!info.is_excluded()) {
254         if (info.is_builtin()) {
255           ++ _table->_builtin_count;
256         } else {
257           ++ _table->_unregistered_count;
258         }
259       }
260       return true; // keep on iterating
261     }
262   };
263 
update_counts()264   void update_counts() {
265     _builtin_count = 0;
266     _unregistered_count = 0;
267     CountClassByCategory counter(this);
268     iterate(&counter);
269   }
270 
count_of(bool is_builtin) const271   int count_of(bool is_builtin) const {
272     if (is_builtin) {
273       return _builtin_count;
274     } else {
275       return _unregistered_count;
276     }
277   }
278 };
279 
280 class LambdaProxyClassKey {
original_to_target(T & field)281   template <typename T> static void original_to_target(T& field) {
282     if (field != NULL) {
283       if (DynamicDumpSharedSpaces) {
284         field = DynamicArchive::original_to_target(field);
285       }
286       ArchivePtrMarker::mark_pointer(&field);
287     }
288   }
289 
290   InstanceKlass* _caller_ik;
291   Symbol*        _invoked_name;
292   Symbol*        _invoked_type;
293   Symbol*        _method_type;
294   Method*        _member_method;
295   Symbol*        _instantiated_method_type;
296 
297 public:
LambdaProxyClassKey(InstanceKlass * caller_ik,Symbol * invoked_name,Symbol * invoked_type,Symbol * method_type,Method * member_method,Symbol * instantiated_method_type)298   LambdaProxyClassKey(InstanceKlass* caller_ik,
299                       Symbol*        invoked_name,
300                       Symbol*        invoked_type,
301                       Symbol*        method_type,
302                       Method*        member_method,
303                       Symbol*        instantiated_method_type) :
304     _caller_ik(caller_ik),
305     _invoked_name(invoked_name),
306     _invoked_type(invoked_type),
307     _method_type(method_type),
308     _member_method(member_method),
309     _instantiated_method_type(instantiated_method_type) {}
310 
metaspace_pointers_do(MetaspaceClosure * it)311   void metaspace_pointers_do(MetaspaceClosure* it) {
312     it->push(&_caller_ik);
313     it->push(&_invoked_name);
314     it->push(&_invoked_type);
315     it->push(&_method_type);
316     it->push(&_member_method);
317     it->push(&_instantiated_method_type);
318   }
319 
original_to_target()320   void original_to_target() {
321     original_to_target(_caller_ik);
322     original_to_target(_instantiated_method_type);
323     original_to_target(_invoked_name);
324     original_to_target(_invoked_type);
325     original_to_target(_member_method);
326     original_to_target(_method_type);
327   }
328 
equals(LambdaProxyClassKey const & other) const329   bool equals(LambdaProxyClassKey const& other) const {
330     return _caller_ik == other._caller_ik &&
331            _invoked_name == other._invoked_name &&
332            _invoked_type == other._invoked_type &&
333            _method_type == other._method_type &&
334            _member_method == other._member_method &&
335            _instantiated_method_type == other._instantiated_method_type;
336   }
337 
hash() const338   unsigned int hash() const {
339     return SystemDictionaryShared::hash_for_shared_dictionary(_caller_ik) +
340            SystemDictionaryShared::hash_for_shared_dictionary(_invoked_name) +
341            SystemDictionaryShared::hash_for_shared_dictionary(_invoked_type) +
342            SystemDictionaryShared::hash_for_shared_dictionary(_method_type) +
343            SystemDictionaryShared::hash_for_shared_dictionary(_instantiated_method_type);
344   }
345 
dumptime_hash(Symbol * sym)346   static unsigned int dumptime_hash(Symbol* sym)  {
347     if (sym == NULL) {
348       // _invoked_name maybe NULL
349       return 0;
350     }
351     return java_lang_String::hash_code((const jbyte*)sym->bytes(), sym->utf8_length());
352   }
353 
dumptime_hash() const354   unsigned int dumptime_hash() const {
355     return dumptime_hash(_caller_ik->name()) +
356            dumptime_hash(_invoked_name) +
357            dumptime_hash(_invoked_type) +
358            dumptime_hash(_method_type) +
359            dumptime_hash(_instantiated_method_type);
360   }
361 
DUMPTIME_HASH(LambdaProxyClassKey const & key)362   static inline unsigned int DUMPTIME_HASH(LambdaProxyClassKey const& key) {
363     return (key.dumptime_hash());
364   }
365 
DUMPTIME_EQUALS(LambdaProxyClassKey const & k1,LambdaProxyClassKey const & k2)366   static inline bool DUMPTIME_EQUALS(
367       LambdaProxyClassKey const& k1, LambdaProxyClassKey const& k2) {
368     return (k1.equals(k2));
369   }
370 };
371 
372 
373 class DumpTimeLambdaProxyClassInfo {
374 public:
375   GrowableArray<InstanceKlass*>* _proxy_klasses;
DumpTimeLambdaProxyClassInfo()376   DumpTimeLambdaProxyClassInfo() : _proxy_klasses(NULL) {}
add_proxy_klass(InstanceKlass * proxy_klass)377   void add_proxy_klass(InstanceKlass* proxy_klass) {
378     if (_proxy_klasses == NULL) {
379       _proxy_klasses = new (ResourceObj::C_HEAP, mtClassShared)GrowableArray<InstanceKlass*>(5, mtClassShared);
380     }
381     assert(_proxy_klasses != NULL, "sanity");
382     _proxy_klasses->append(proxy_klass);
383   }
384 
metaspace_pointers_do(MetaspaceClosure * it)385   void metaspace_pointers_do(MetaspaceClosure* it) {
386     for (int i=0; i<_proxy_klasses->length(); i++) {
387       it->push(_proxy_klasses->adr_at(i));
388     }
389   }
390 };
391 
392 class RunTimeLambdaProxyClassInfo {
393   LambdaProxyClassKey _key;
394   InstanceKlass* _proxy_klass_head;
395 public:
RunTimeLambdaProxyClassInfo(LambdaProxyClassKey key,InstanceKlass * proxy_klass_head)396   RunTimeLambdaProxyClassInfo(LambdaProxyClassKey key, InstanceKlass* proxy_klass_head) :
397     _key(key), _proxy_klass_head(proxy_klass_head) {}
398 
proxy_klass_head() const399   InstanceKlass* proxy_klass_head() const { return _proxy_klass_head; }
400 
401   // Used by LambdaProxyClassDictionary to implement OffsetCompactHashtable::EQUALS
EQUALS(const RunTimeLambdaProxyClassInfo * value,LambdaProxyClassKey * key,int len_unused)402   static inline bool EQUALS(
403        const RunTimeLambdaProxyClassInfo* value, LambdaProxyClassKey* key, int len_unused) {
404     return (value->_key.equals(*key));
405   }
init(LambdaProxyClassKey & key,DumpTimeLambdaProxyClassInfo & info)406   void init(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
407     _key = key;
408     _key.original_to_target();
409     _proxy_klass_head = DynamicDumpSharedSpaces ?
410                           DynamicArchive::original_to_target(info._proxy_klasses->at(0)) :
411                           info._proxy_klasses->at(0);
412     ArchivePtrMarker::mark_pointer(&_proxy_klass_head);
413   }
414 
hash() const415   unsigned int hash() const {
416     return _key.hash();
417   }
key() const418   LambdaProxyClassKey key() const {
419     return _key;
420   }
421 };
422 
423 class LambdaProxyClassDictionary : public OffsetCompactHashtable<
424   LambdaProxyClassKey*,
425   const RunTimeLambdaProxyClassInfo*,
426   RunTimeLambdaProxyClassInfo::EQUALS> {};
427 
428 LambdaProxyClassDictionary _lambda_proxy_class_dictionary;
429 
430 LambdaProxyClassDictionary _dynamic_lambda_proxy_class_dictionary;
431 
432 class DumpTimeLambdaProxyClassDictionary
433   : public ResourceHashtable<LambdaProxyClassKey,
434                              DumpTimeLambdaProxyClassInfo,
435                              LambdaProxyClassKey::DUMPTIME_HASH,
436                              LambdaProxyClassKey::DUMPTIME_EQUALS,
437                              137, // prime number
438                              ResourceObj::C_HEAP> {
439 public:
440   int _count;
441 };
442 
443 DumpTimeLambdaProxyClassDictionary* _dumptime_lambda_proxy_class_dictionary = NULL;
444 
add_to_dump_time_lambda_proxy_class_dictionary(LambdaProxyClassKey key,InstanceKlass * proxy_klass)445 static void add_to_dump_time_lambda_proxy_class_dictionary(LambdaProxyClassKey key,
446                                                            InstanceKlass* proxy_klass) {
447   assert(DumpTimeTable_lock->owned_by_self(), "sanity");
448   if (_dumptime_lambda_proxy_class_dictionary == NULL) {
449     _dumptime_lambda_proxy_class_dictionary =
450       new (ResourceObj::C_HEAP, mtClass)DumpTimeLambdaProxyClassDictionary();
451   }
452   DumpTimeLambdaProxyClassInfo* lambda_info = _dumptime_lambda_proxy_class_dictionary->get(key);
453   if (lambda_info == NULL) {
454     DumpTimeLambdaProxyClassInfo info;
455     info.add_proxy_klass(proxy_klass);
456     _dumptime_lambda_proxy_class_dictionary->put(key, info);
457     //lambda_info = _dumptime_lambda_proxy_class_dictionary->get(key);
458     //assert(lambda_info->_proxy_klass == proxy_klass, "must be"); // debug only -- remove
459     ++_dumptime_lambda_proxy_class_dictionary->_count;
460   } else {
461     lambda_info->add_proxy_klass(proxy_klass);
462   }
463 }
464 
465 class RunTimeSharedClassInfo {
466 public:
467   struct CrcInfo {
468     int _clsfile_size;
469     int _clsfile_crc32;
470   };
471 
472   // This is different than  DumpTimeSharedClassInfo::DTVerifierConstraint. We use
473   // u4 instead of Symbol* to save space on 64-bit CPU.
474   struct RTVerifierConstraint {
475     u4 _name;
476     u4 _from_name;
nameRunTimeSharedClassInfo::RTVerifierConstraint477     Symbol* name() { return (Symbol*)(SharedBaseAddress + _name);}
from_nameRunTimeSharedClassInfo::RTVerifierConstraint478     Symbol* from_name() { return (Symbol*)(SharedBaseAddress + _from_name); }
479   };
480 
481   struct RTLoaderConstraint {
482     u4   _name;
483     char _loader_type1;
484     char _loader_type2;
constraint_nameRunTimeSharedClassInfo::RTLoaderConstraint485     Symbol* constraint_name() {
486       return (Symbol*)(SharedBaseAddress + _name);
487     }
488   };
489 
490   InstanceKlass* _klass;
491   int _num_verifier_constraints;
492   int _num_loader_constraints;
493 
494   // optional CrcInfo              _crc;  (only for UNREGISTERED classes)
495   // optional InstanceKlass*       _nest_host
496   // optional RTLoaderConstraint   _loader_constraint_types[_num_loader_constraints]
497   // optional RTVerifierConstraint _verifier_constraints[_num_verifier_constraints]
498   // optional char                 _verifier_constraint_flags[_num_verifier_constraints]
499 
500 private:
header_size_size()501   static size_t header_size_size() {
502     return sizeof(RunTimeSharedClassInfo);
503   }
crc_size(InstanceKlass * klass)504   static size_t crc_size(InstanceKlass* klass) {
505     if (!SystemDictionaryShared::is_builtin(klass)) {
506       return sizeof(CrcInfo);
507     } else {
508       return 0;
509     }
510   }
verifier_constraints_size(int num_verifier_constraints)511   static size_t verifier_constraints_size(int num_verifier_constraints) {
512     return sizeof(RTVerifierConstraint) * num_verifier_constraints;
513   }
verifier_constraint_flags_size(int num_verifier_constraints)514   static size_t verifier_constraint_flags_size(int num_verifier_constraints) {
515     return sizeof(char) * num_verifier_constraints;
516   }
loader_constraints_size(int num_loader_constraints)517   static size_t loader_constraints_size(int num_loader_constraints) {
518     return sizeof(RTLoaderConstraint) * num_loader_constraints;
519   }
nest_host_size(InstanceKlass * klass)520   static size_t nest_host_size(InstanceKlass* klass) {
521     if (klass->is_hidden()) {
522       return sizeof(InstanceKlass*);
523     } else {
524       return 0;
525     }
526   }
527 
528 public:
byte_size(InstanceKlass * klass,int num_verifier_constraints,int num_loader_constraints)529   static size_t byte_size(InstanceKlass* klass, int num_verifier_constraints, int num_loader_constraints) {
530     return header_size_size() +
531            crc_size(klass) +
532            nest_host_size(klass) +
533            loader_constraints_size(num_loader_constraints) +
534            verifier_constraints_size(num_verifier_constraints) +
535            verifier_constraint_flags_size(num_verifier_constraints);
536   }
537 
538 private:
crc_offset() const539   size_t crc_offset() const {
540     return header_size_size();
541   }
542 
nest_host_offset() const543   size_t nest_host_offset() const {
544       return crc_offset() + crc_size(_klass);
545   }
546 
loader_constraints_offset() const547   size_t loader_constraints_offset() const  {
548     return nest_host_offset() + nest_host_size(_klass);
549   }
verifier_constraints_offset() const550   size_t verifier_constraints_offset() const {
551     return loader_constraints_offset() + loader_constraints_size(_num_loader_constraints);
552   }
verifier_constraint_flags_offset() const553   size_t verifier_constraint_flags_offset() const {
554     return verifier_constraints_offset() + verifier_constraints_size(_num_verifier_constraints);
555   }
556 
check_verifier_constraint_offset(int i) const557   void check_verifier_constraint_offset(int i) const {
558     assert(0 <= i && i < _num_verifier_constraints, "sanity");
559   }
560 
check_loader_constraint_offset(int i) const561   void check_loader_constraint_offset(int i) const {
562     assert(0 <= i && i < _num_loader_constraints, "sanity");
563   }
564 
565 public:
crc() const566   CrcInfo* crc() const {
567     assert(crc_size(_klass) > 0, "must be");
568     return (CrcInfo*)(address(this) + crc_offset());
569   }
verifier_constraints()570   RTVerifierConstraint* verifier_constraints() {
571     assert(_num_verifier_constraints > 0, "sanity");
572     return (RTVerifierConstraint*)(address(this) + verifier_constraints_offset());
573   }
verifier_constraint_at(int i)574   RTVerifierConstraint* verifier_constraint_at(int i) {
575     check_verifier_constraint_offset(i);
576     return verifier_constraints() + i;
577   }
578 
verifier_constraint_flags()579   char* verifier_constraint_flags() {
580     assert(_num_verifier_constraints > 0, "sanity");
581     return (char*)(address(this) + verifier_constraint_flags_offset());
582   }
583 
nest_host_addr()584   InstanceKlass** nest_host_addr() {
585     assert(_klass->is_hidden(), "sanity");
586     return (InstanceKlass**)(address(this) + nest_host_offset());
587   }
nest_host()588   InstanceKlass* nest_host() {
589     return *nest_host_addr();
590   }
set_nest_host(InstanceKlass * k)591   void set_nest_host(InstanceKlass* k) {
592     *nest_host_addr() = k;
593     ArchivePtrMarker::mark_pointer((address*)nest_host_addr());
594   }
595 
loader_constraints()596   RTLoaderConstraint* loader_constraints() {
597     assert(_num_loader_constraints > 0, "sanity");
598     return (RTLoaderConstraint*)(address(this) + loader_constraints_offset());
599   }
600 
loader_constraint_at(int i)601   RTLoaderConstraint* loader_constraint_at(int i) {
602     check_loader_constraint_offset(i);
603     return loader_constraints() + i;
604   }
605 
object_delta_u4(Symbol * sym)606   static u4 object_delta_u4(Symbol* sym) {
607     if (DynamicDumpSharedSpaces) {
608       sym = DynamicArchive::original_to_target(sym);
609     }
610     return MetaspaceShared::object_delta_u4(sym);
611   }
612 
init(DumpTimeSharedClassInfo & info)613   void init(DumpTimeSharedClassInfo& info) {
614     _klass = info._klass;
615     if (!SystemDictionaryShared::is_builtin(_klass)) {
616       CrcInfo* c = crc();
617       c->_clsfile_size = info._clsfile_size;
618       c->_clsfile_crc32 = info._clsfile_crc32;
619     }
620     _num_verifier_constraints = info.num_verifier_constraints();
621     _num_loader_constraints   = info.num_loader_constraints();
622     int i;
623     if (_num_verifier_constraints > 0) {
624       RTVerifierConstraint* vf_constraints = verifier_constraints();
625       char* flags = verifier_constraint_flags();
626       for (i = 0; i < _num_verifier_constraints; i++) {
627         vf_constraints[i]._name      = object_delta_u4(info._verifier_constraints->at(i)._name);
628         vf_constraints[i]._from_name = object_delta_u4(info._verifier_constraints->at(i)._from_name);
629       }
630       for (i = 0; i < _num_verifier_constraints; i++) {
631         flags[i] = info._verifier_constraint_flags->at(i);
632       }
633     }
634 
635     if (_num_loader_constraints > 0) {
636       RTLoaderConstraint* ld_constraints = loader_constraints();
637       for (i = 0; i < _num_loader_constraints; i++) {
638         ld_constraints[i]._name = object_delta_u4(info._loader_constraints->at(i)._name);
639         ld_constraints[i]._loader_type1 = info._loader_constraints->at(i)._loader_type1;
640         ld_constraints[i]._loader_type2 = info._loader_constraints->at(i)._loader_type2;
641       }
642     }
643 
644     if (_klass->is_hidden()) {
645       InstanceKlass* n_h = info.nest_host();
646       if (DynamicDumpSharedSpaces) {
647         n_h = DynamicArchive::original_to_target(n_h);
648       }
649       set_nest_host(n_h);
650     }
651     _klass = DynamicDumpSharedSpaces ? DynamicArchive::original_to_target(info._klass) : info._klass;
652     ArchivePtrMarker::mark_pointer(&_klass);
653   }
654 
matches(int clsfile_size,int clsfile_crc32) const655   bool matches(int clsfile_size, int clsfile_crc32) const {
656     return crc()->_clsfile_size  == clsfile_size &&
657            crc()->_clsfile_crc32 == clsfile_crc32;
658   }
659 
verifier_constraint_flag(int i)660   char verifier_constraint_flag(int i) {
661     check_verifier_constraint_offset(i);
662     return verifier_constraint_flags()[i];
663   }
664 
665 private:
666   // ArchiveBuilder::make_shallow_copy() has reserved a pointer immediately
667   // before archived InstanceKlasses. We can use this slot to do a quick
668   // lookup of InstanceKlass* -> RunTimeSharedClassInfo* without
669   // building a new hashtable.
670   //
671   //  info_pointer_addr(klass) --> 0x0100   RunTimeSharedClassInfo*
672   //  InstanceKlass* klass     --> 0x0108   <C++ vtbl>
673   //                               0x0110   fields from Klass ...
info_pointer_addr(InstanceKlass * klass)674   static RunTimeSharedClassInfo** info_pointer_addr(InstanceKlass* klass) {
675     return &((RunTimeSharedClassInfo**)klass)[-1];
676   }
677 
678 public:
get_for(InstanceKlass * klass)679   static RunTimeSharedClassInfo* get_for(InstanceKlass* klass) {
680     assert(klass->is_shared(), "don't call for non-shared class");
681     return *info_pointer_addr(klass);
682   }
set_for(InstanceKlass * klass,RunTimeSharedClassInfo * record)683   static void set_for(InstanceKlass* klass, RunTimeSharedClassInfo* record) {
684     if (DynamicDumpSharedSpaces) {
685       klass = DynamicArchive::original_to_buffer(klass);
686       *info_pointer_addr(klass) = DynamicArchive::buffer_to_target(record);
687     } else {
688       *info_pointer_addr(klass) = record;
689     }
690 
691     ArchivePtrMarker::mark_pointer(info_pointer_addr(klass));
692   }
693 
694   // Used by RunTimeSharedDictionary to implement OffsetCompactHashtable::EQUALS
EQUALS(const RunTimeSharedClassInfo * value,Symbol * key,int len_unused)695   static inline bool EQUALS(
696        const RunTimeSharedClassInfo* value, Symbol* key, int len_unused) {
697     return (value->_klass->name() == key);
698   }
699 };
700 
701 class RunTimeSharedDictionary : public OffsetCompactHashtable<
702   Symbol*,
703   const RunTimeSharedClassInfo*,
704   RunTimeSharedClassInfo::EQUALS> {};
705 
706 static DumpTimeSharedClassTable* _dumptime_table = NULL;
707 // SystemDictionaries in the base layer static archive
708 static RunTimeSharedDictionary _builtin_dictionary;
709 static RunTimeSharedDictionary _unregistered_dictionary;
710 // SystemDictionaries in the top layer dynamic archive
711 static RunTimeSharedDictionary _dynamic_builtin_dictionary;
712 static RunTimeSharedDictionary _dynamic_unregistered_dictionary;
713 
atomic_set_array_index(OopHandle array,int index,oop o)714 void SystemDictionaryShared::atomic_set_array_index(OopHandle array, int index, oop o) {
715   // Benign race condition:  array.obj_at(index) may already be filled in.
716   // The important thing here is that all threads pick up the same result.
717   // It doesn't matter which racing thread wins, as long as only one
718   // result is used by all threads, and all future queries.
719   ((objArrayOop)array.resolve())->atomic_compare_exchange_oop(index, o, NULL);
720 }
721 
create_jar_manifest(const char * manifest_chars,size_t size,TRAPS)722 Handle SystemDictionaryShared::create_jar_manifest(const char* manifest_chars, size_t size, TRAPS) {
723   typeArrayOop buf = oopFactory::new_byteArray((int)size, CHECK_NH);
724   typeArrayHandle bufhandle(THREAD, buf);
725   ArrayAccess<>::arraycopy_from_native(reinterpret_cast<const jbyte*>(manifest_chars),
726                                          buf, typeArrayOopDesc::element_offset<jbyte>(0), size);
727   Handle bais = JavaCalls::construct_new_instance(SystemDictionary::ByteArrayInputStream_klass(),
728                       vmSymbols::byte_array_void_signature(),
729                       bufhandle, CHECK_NH);
730   // manifest = new Manifest(ByteArrayInputStream)
731   Handle manifest = JavaCalls::construct_new_instance(SystemDictionary::Jar_Manifest_klass(),
732                       vmSymbols::input_stream_void_signature(),
733                       bais, CHECK_NH);
734   return manifest;
735 }
736 
shared_protection_domain(int index)737 oop SystemDictionaryShared::shared_protection_domain(int index) {
738   return ((objArrayOop)_shared_protection_domains.resolve())->obj_at(index);
739 }
740 
shared_jar_url(int index)741 oop SystemDictionaryShared::shared_jar_url(int index) {
742   return ((objArrayOop)_shared_jar_urls.resolve())->obj_at(index);
743 }
744 
shared_jar_manifest(int index)745 oop SystemDictionaryShared::shared_jar_manifest(int index) {
746   return ((objArrayOop)_shared_jar_manifests.resolve())->obj_at(index);
747 }
748 
get_shared_jar_manifest(int shared_path_index,TRAPS)749 Handle SystemDictionaryShared::get_shared_jar_manifest(int shared_path_index, TRAPS) {
750   Handle manifest ;
751   if (shared_jar_manifest(shared_path_index) == NULL) {
752     SharedClassPathEntry* ent = FileMapInfo::shared_path(shared_path_index);
753     size_t size = (size_t)ent->manifest_size();
754     if (size == 0) {
755       return Handle();
756     }
757 
758     // ByteArrayInputStream bais = new ByteArrayInputStream(buf);
759     const char* src = ent->manifest();
760     assert(src != NULL, "No Manifest data");
761     manifest = create_jar_manifest(src, size, THREAD);
762     atomic_set_shared_jar_manifest(shared_path_index, manifest());
763   }
764   manifest = Handle(THREAD, shared_jar_manifest(shared_path_index));
765   assert(manifest.not_null(), "sanity");
766   return manifest;
767 }
768 
get_shared_jar_url(int shared_path_index,TRAPS)769 Handle SystemDictionaryShared::get_shared_jar_url(int shared_path_index, TRAPS) {
770   Handle url_h;
771   if (shared_jar_url(shared_path_index) == NULL) {
772     JavaValue result(T_OBJECT);
773     const char* path = FileMapInfo::shared_path_name(shared_path_index);
774     Handle path_string = java_lang_String::create_from_str(path, CHECK_(url_h));
775     Klass* classLoaders_klass =
776         SystemDictionary::jdk_internal_loader_ClassLoaders_klass();
777     JavaCalls::call_static(&result, classLoaders_klass,
778                            vmSymbols::toFileURL_name(),
779                            vmSymbols::toFileURL_signature(),
780                            path_string, CHECK_(url_h));
781 
782     atomic_set_shared_jar_url(shared_path_index, (oop)result.get_jobject());
783   }
784 
785   url_h = Handle(THREAD, shared_jar_url(shared_path_index));
786   assert(url_h.not_null(), "sanity");
787   return url_h;
788 }
789 
get_package_name(Symbol * class_name,TRAPS)790 Handle SystemDictionaryShared::get_package_name(Symbol* class_name, TRAPS) {
791   ResourceMark rm(THREAD);
792   Handle pkgname_string;
793   TempNewSymbol pkg = ClassLoader::package_from_class_name(class_name);
794   if (pkg != NULL) { // Package prefix found
795     const char* pkgname = pkg->as_klass_external_name();
796     pkgname_string = java_lang_String::create_from_str(pkgname,
797                                                        CHECK_(pkgname_string));
798   }
799   return pkgname_string;
800 }
801 
802 // Define Package for shared app classes from JAR file and also checks for
803 // package sealing (all done in Java code)
804 // See http://docs.oracle.com/javase/tutorial/deployment/jar/sealman.html
define_shared_package(Symbol * class_name,Handle class_loader,Handle manifest,Handle url,TRAPS)805 void SystemDictionaryShared::define_shared_package(Symbol*  class_name,
806                                                    Handle class_loader,
807                                                    Handle manifest,
808                                                    Handle url,
809                                                    TRAPS) {
810   assert(SystemDictionary::is_system_class_loader(class_loader()), "unexpected class loader");
811   // get_package_name() returns a NULL handle if the class is in unnamed package
812   Handle pkgname_string = get_package_name(class_name, CHECK);
813   if (pkgname_string.not_null()) {
814     Klass* app_classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass();
815     JavaValue result(T_OBJECT);
816     JavaCallArguments args(3);
817     args.set_receiver(class_loader);
818     args.push_oop(pkgname_string);
819     args.push_oop(manifest);
820     args.push_oop(url);
821     JavaCalls::call_virtual(&result, app_classLoader_klass,
822                             vmSymbols::defineOrCheckPackage_name(),
823                             vmSymbols::defineOrCheckPackage_signature(),
824                             &args,
825                             CHECK);
826   }
827 }
828 
829 // Get the ProtectionDomain associated with the CodeSource from the classloader.
get_protection_domain_from_classloader(Handle class_loader,Handle url,TRAPS)830 Handle SystemDictionaryShared::get_protection_domain_from_classloader(Handle class_loader,
831                                                                       Handle url, TRAPS) {
832   // CodeSource cs = new CodeSource(url, null);
833   Handle cs = JavaCalls::construct_new_instance(SystemDictionary::CodeSource_klass(),
834                   vmSymbols::url_code_signer_array_void_signature(),
835                   url, Handle(), CHECK_NH);
836 
837   // protection_domain = SecureClassLoader.getProtectionDomain(cs);
838   Klass* secureClassLoader_klass = SystemDictionary::SecureClassLoader_klass();
839   JavaValue obj_result(T_OBJECT);
840   JavaCalls::call_virtual(&obj_result, class_loader, secureClassLoader_klass,
841                           vmSymbols::getProtectionDomain_name(),
842                           vmSymbols::getProtectionDomain_signature(),
843                           cs, CHECK_NH);
844   return Handle(THREAD, (oop)obj_result.get_jobject());
845 }
846 
847 // Returns the ProtectionDomain associated with the JAR file identified by the url.
get_shared_protection_domain(Handle class_loader,int shared_path_index,Handle url,TRAPS)848 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader,
849                                                             int shared_path_index,
850                                                             Handle url,
851                                                             TRAPS) {
852   Handle protection_domain;
853   if (shared_protection_domain(shared_path_index) == NULL) {
854     Handle pd = get_protection_domain_from_classloader(class_loader, url, THREAD);
855     atomic_set_shared_protection_domain(shared_path_index, pd());
856   }
857 
858   // Acquire from the cache because if another thread beats the current one to
859   // set the shared protection_domain and the atomic_set fails, the current thread
860   // needs to get the updated protection_domain from the cache.
861   protection_domain = Handle(THREAD, shared_protection_domain(shared_path_index));
862   assert(protection_domain.not_null(), "sanity");
863   return protection_domain;
864 }
865 
866 // Returns the ProtectionDomain associated with the moduleEntry.
get_shared_protection_domain(Handle class_loader,ModuleEntry * mod,TRAPS)867 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader,
868                                                             ModuleEntry* mod, TRAPS) {
869   ClassLoaderData *loader_data = mod->loader_data();
870   if (mod->shared_protection_domain() == NULL) {
871     Symbol* location = mod->location();
872     if (location != NULL) {
873       Handle location_string = java_lang_String::create_from_symbol(
874                                      location, CHECK_NH);
875       Handle url;
876       JavaValue result(T_OBJECT);
877       if (location->starts_with("jrt:/")) {
878         url = JavaCalls::construct_new_instance(SystemDictionary::URL_klass(),
879                                                 vmSymbols::string_void_signature(),
880                                                 location_string, CHECK_NH);
881       } else {
882         Klass* classLoaders_klass =
883           SystemDictionary::jdk_internal_loader_ClassLoaders_klass();
884         JavaCalls::call_static(&result, classLoaders_klass, vmSymbols::toFileURL_name(),
885                                vmSymbols::toFileURL_signature(),
886                                location_string, CHECK_NH);
887         url = Handle(THREAD, (oop)result.get_jobject());
888       }
889 
890       Handle pd = get_protection_domain_from_classloader(class_loader, url,
891                                                          CHECK_NH);
892       mod->set_shared_protection_domain(loader_data, pd);
893     }
894   }
895 
896   Handle protection_domain(THREAD, mod->shared_protection_domain());
897   assert(protection_domain.not_null(), "sanity");
898   return protection_domain;
899 }
900 
901 // Initializes the java.lang.Package and java.security.ProtectionDomain objects associated with
902 // the given InstanceKlass.
903 // Returns the ProtectionDomain for the InstanceKlass.
init_security_info(Handle class_loader,InstanceKlass * ik,PackageEntry * pkg_entry,TRAPS)904 Handle SystemDictionaryShared::init_security_info(Handle class_loader, InstanceKlass* ik, PackageEntry* pkg_entry, TRAPS) {
905   Handle pd;
906 
907   if (ik != NULL) {
908     int index = ik->shared_classpath_index();
909     assert(index >= 0, "Sanity");
910     SharedClassPathEntry* ent = FileMapInfo::shared_path(index);
911     Symbol* class_name = ik->name();
912 
913     if (ent->is_modules_image()) {
914       // For shared app/platform classes originated from the run-time image:
915       //   The ProtectionDomains are cached in the corresponding ModuleEntries
916       //   for fast access by the VM.
917       // all packages from module image are already created during VM bootstrap in
918       // Modules::define_module().
919       assert(pkg_entry != NULL, "archived class in module image cannot be from unnamed package");
920       ModuleEntry* mod_entry = pkg_entry->module();
921       pd = get_shared_protection_domain(class_loader, mod_entry, THREAD);
922     } else {
923       // For shared app/platform classes originated from JAR files on the class path:
924       //   Each of the 3 SystemDictionaryShared::_shared_xxx arrays has the same length
925       //   as the shared classpath table in the shared archive (see
926       //   FileMap::_shared_path_table in filemap.hpp for details).
927       //
928       //   If a shared InstanceKlass k is loaded from the class path, let
929       //
930       //     index = k->shared_classpath_index():
931       //
932       //   FileMap::_shared_path_table[index] identifies the JAR file that contains k.
933       //
934       //   k's protection domain is:
935       //
936       //     ProtectionDomain pd = _shared_protection_domains[index];
937       //
938       //   and k's Package is initialized using
939       //
940       //     manifest = _shared_jar_manifests[index];
941       //     url = _shared_jar_urls[index];
942       //     define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd));
943       //
944       //   Note that if an element of these 3 _shared_xxx arrays is NULL, it will be initialized by
945       //   the corresponding SystemDictionaryShared::get_shared_xxx() function.
946       Handle manifest = get_shared_jar_manifest(index, CHECK_(pd));
947       Handle url = get_shared_jar_url(index, CHECK_(pd));
948       int index_offset = index - ClassLoaderExt::app_class_paths_start_index();
949       if (index_offset < PackageEntry::max_index_for_defined_in_class_path()) {
950         if (pkg_entry == NULL || !pkg_entry->is_defined_by_cds_in_class_path(index_offset)) {
951           // define_shared_package only needs to be called once for each package in a jar specified
952           // in the shared class path.
953           define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd));
954           if (pkg_entry != NULL) {
955             pkg_entry->set_defined_by_cds_in_class_path(index_offset);
956           }
957         }
958       } else {
959         define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd));
960       }
961       pd = get_shared_protection_domain(class_loader, index, url, CHECK_(pd));
962     }
963   }
964   return pd;
965 }
966 
is_sharing_possible(ClassLoaderData * loader_data)967 bool SystemDictionaryShared::is_sharing_possible(ClassLoaderData* loader_data) {
968   oop class_loader = loader_data->class_loader();
969   return (class_loader == NULL ||
970           SystemDictionary::is_system_class_loader(class_loader) ||
971           SystemDictionary::is_platform_class_loader(class_loader));
972 }
973 
has_platform_or_app_classes()974 bool SystemDictionaryShared::has_platform_or_app_classes() {
975   if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
976     return true;
977   }
978   if (DynamicArchive::is_mapped() &&
979       FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
980     return true;
981   }
982   return false;
983 }
984 
985 // The following stack shows how this code is reached:
986 //
987 //   [0] SystemDictionaryShared::find_or_load_shared_class()
988 //   [1] JVM_FindLoadedClass
989 //   [2] java.lang.ClassLoader.findLoadedClass0()
990 //   [3] java.lang.ClassLoader.findLoadedClass()
991 //   [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
992 //   [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
993 //   [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
994 //       jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
995 //
996 // AppCDS supports fast class loading for these 2 built-in class loaders:
997 //    jdk.internal.loader.ClassLoaders$PlatformClassLoader
998 //    jdk.internal.loader.ClassLoaders$AppClassLoader
999 // with the following assumptions (based on the JDK core library source code):
1000 //
1001 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
1002 //     load the named class.
1003 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
1004 // [c] At this point, if we can find the named class inside the
1005 //     shared_dictionary, we can perform further checks (see
1006 //     SystemDictionary::is_shared_class_visible) to ensure that this class
1007 //     was loaded by the same class loader during dump time.
1008 //
1009 // Given these assumptions, we intercept the findLoadedClass() call to invoke
1010 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
1011 // the archive for the 2 built-in class loaders. This way,
1012 // we can improve start-up because we avoid decoding the classfile,
1013 // and avoid delegating to the parent loader.
1014 //
1015 // NOTE: there's a lot of assumption about the Java code. If any of that change, this
1016 // needs to be redesigned.
1017 
find_or_load_shared_class(Symbol * name,Handle class_loader,TRAPS)1018 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
1019                  Symbol* name, Handle class_loader, TRAPS) {
1020   InstanceKlass* k = NULL;
1021   if (UseSharedSpaces) {
1022     if (!has_platform_or_app_classes()) {
1023       return NULL;
1024     }
1025 
1026     if (SystemDictionary::is_system_class_loader(class_loader()) ||
1027         SystemDictionary::is_platform_class_loader(class_loader())) {
1028       // Fix for 4474172; see evaluation for more details
1029       class_loader = Handle(
1030         THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
1031       ClassLoaderData *loader_data = register_loader(class_loader);
1032       Dictionary* dictionary = loader_data->dictionary();
1033 
1034       unsigned int d_hash = dictionary->compute_hash(name);
1035 
1036       bool DoObjectLock = true;
1037       if (is_parallelCapable(class_loader)) {
1038         DoObjectLock = false;
1039       }
1040 
1041       // Make sure we are synchronized on the class loader before we proceed
1042       //
1043       // Note: currently, find_or_load_shared_class is called only from
1044       // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
1045       // which are parallel-capable loaders, so this lock is NOT taken.
1046       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1047       check_loader_lock_contention(lockObject, THREAD);
1048       ObjectLocker ol(lockObject, THREAD, DoObjectLock);
1049 
1050       {
1051         MutexLocker mu(THREAD, SystemDictionary_lock);
1052         InstanceKlass* check = find_class(d_hash, name, dictionary);
1053         if (check != NULL) {
1054           return check;
1055         }
1056       }
1057 
1058       k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
1059       if (k != NULL) {
1060         define_instance_class(k, CHECK_NULL);
1061       }
1062     }
1063   }
1064   return k;
1065 }
1066 
get_package_entry_from_class_name(Handle class_loader,Symbol * class_name)1067 PackageEntry* SystemDictionaryShared::get_package_entry_from_class_name(Handle class_loader, Symbol* class_name) {
1068   PackageEntry* pkg_entry = NULL;
1069   TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
1070   if (pkg_name != NULL) {
1071     pkg_entry = class_loader_data(class_loader)->packages()->lookup_only(pkg_name);
1072   }
1073   return pkg_entry;
1074 }
1075 
load_shared_class_for_builtin_loader(Symbol * class_name,Handle class_loader,TRAPS)1076 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
1077                  Symbol* class_name, Handle class_loader, TRAPS) {
1078   assert(UseSharedSpaces, "must be");
1079   InstanceKlass* ik = find_builtin_class(class_name);
1080 
1081   if (ik != NULL) {
1082     if ((ik->is_shared_app_class() &&
1083          SystemDictionary::is_system_class_loader(class_loader()))  ||
1084         (ik->is_shared_platform_class() &&
1085          SystemDictionary::is_platform_class_loader(class_loader()))) {
1086       PackageEntry* pkg_entry = get_package_entry_from_class_name(class_loader, class_name);
1087       Handle protection_domain =
1088         SystemDictionaryShared::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL);
1089       return load_shared_class(ik, class_loader, protection_domain, NULL, pkg_entry, THREAD);
1090     }
1091   }
1092   return NULL;
1093 }
1094 
allocate_shared_protection_domain_array(int size,TRAPS)1095 void SystemDictionaryShared::allocate_shared_protection_domain_array(int size, TRAPS) {
1096   if (_shared_protection_domains.resolve() == NULL) {
1097     oop spd = oopFactory::new_objArray(
1098         SystemDictionary::ProtectionDomain_klass(), size, CHECK);
1099     _shared_protection_domains = OopHandle(Universe::vm_global(), spd);
1100   }
1101 }
1102 
allocate_shared_jar_url_array(int size,TRAPS)1103 void SystemDictionaryShared::allocate_shared_jar_url_array(int size, TRAPS) {
1104   if (_shared_jar_urls.resolve() == NULL) {
1105     oop sju = oopFactory::new_objArray(
1106         SystemDictionary::URL_klass(), size, CHECK);
1107     _shared_jar_urls = OopHandle(Universe::vm_global(), sju);
1108   }
1109 }
1110 
allocate_shared_jar_manifest_array(int size,TRAPS)1111 void SystemDictionaryShared::allocate_shared_jar_manifest_array(int size, TRAPS) {
1112   if (_shared_jar_manifests.resolve() == NULL) {
1113     oop sjm = oopFactory::new_objArray(
1114         SystemDictionary::Jar_Manifest_klass(), size, CHECK);
1115     _shared_jar_manifests = OopHandle(Universe::vm_global(), sjm);
1116   }
1117 }
1118 
allocate_shared_data_arrays(int size,TRAPS)1119 void SystemDictionaryShared::allocate_shared_data_arrays(int size, TRAPS) {
1120   allocate_shared_protection_domain_array(size, CHECK);
1121   allocate_shared_jar_url_array(size, CHECK);
1122   allocate_shared_jar_manifest_array(size, CHECK);
1123 }
1124 
1125 // This function is called for loading only UNREGISTERED classes
lookup_from_stream(Symbol * class_name,Handle class_loader,Handle protection_domain,const ClassFileStream * cfs,TRAPS)1126 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
1127                                                           Handle class_loader,
1128                                                           Handle protection_domain,
1129                                                           const ClassFileStream* cfs,
1130                                                           TRAPS) {
1131   if (!UseSharedSpaces) {
1132     return NULL;
1133   }
1134   if (class_name == NULL) {  // don't do this for hidden and unsafe anonymous classes
1135     return NULL;
1136   }
1137   if (class_loader.is_null() ||
1138       SystemDictionary::is_system_class_loader(class_loader()) ||
1139       SystemDictionary::is_platform_class_loader(class_loader())) {
1140     // Do nothing for the BUILTIN loaders.
1141     return NULL;
1142   }
1143 
1144   const RunTimeSharedClassInfo* record = find_record(&_unregistered_dictionary, &_dynamic_unregistered_dictionary, class_name);
1145   if (record == NULL) {
1146     return NULL;
1147   }
1148 
1149   int clsfile_size  = cfs->length();
1150   int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
1151 
1152   if (!record->matches(clsfile_size, clsfile_crc32)) {
1153     return NULL;
1154   }
1155 
1156   return acquire_class_for_current_thread(record->_klass, class_loader,
1157                                           protection_domain, cfs,
1158                                           THREAD);
1159 }
1160 
acquire_class_for_current_thread(InstanceKlass * ik,Handle class_loader,Handle protection_domain,const ClassFileStream * cfs,TRAPS)1161 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
1162                    InstanceKlass *ik,
1163                    Handle class_loader,
1164                    Handle protection_domain,
1165                    const ClassFileStream *cfs,
1166                    TRAPS) {
1167   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1168 
1169   {
1170     MutexLocker mu(THREAD, SharedDictionary_lock);
1171     if (ik->class_loader_data() != NULL) {
1172       //    ik is already loaded (by this loader or by a different loader)
1173       // or ik is being loaded by a different thread (by this loader or by a different loader)
1174       return NULL;
1175     }
1176 
1177     // No other thread has acquired this yet, so give it to *this thread*
1178     ik->set_class_loader_data(loader_data);
1179   }
1180 
1181   // No longer holding SharedDictionary_lock
1182   // No need to lock, as <ik> can be held only by a single thread.
1183   loader_data->add_class(ik);
1184 
1185   // Get the package entry.
1186   PackageEntry* pkg_entry = get_package_entry_from_class_name(class_loader, ik->name());
1187 
1188   // Load and check super/interfaces, restore unsharable info
1189   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
1190                                                   cfs, pkg_entry, THREAD);
1191   if (shared_klass == NULL || HAS_PENDING_EXCEPTION) {
1192     // TODO: clean up <ik> so it can be used again
1193     return NULL;
1194   }
1195 
1196   return shared_klass;
1197 }
1198 
1199 class LoadedUnregisteredClassesTable : public ResourceHashtable<
1200   Symbol*, bool,
1201   primitive_hash<Symbol*>,
1202   primitive_equals<Symbol*>,
1203   6661,                             // prime number
1204   ResourceObj::C_HEAP> {};
1205 
1206 static LoadedUnregisteredClassesTable* _loaded_unregistered_classes = NULL;
1207 
add_unregistered_class(InstanceKlass * k,TRAPS)1208 bool SystemDictionaryShared::add_unregistered_class(InstanceKlass* k, TRAPS) {
1209   // We don't allow duplicated unregistered classes of the same name.
1210   assert(DumpSharedSpaces, "only when dumping");
1211   Symbol* name = k->name();
1212   if (_loaded_unregistered_classes == NULL) {
1213     _loaded_unregistered_classes = new (ResourceObj::C_HEAP, mtClass)LoadedUnregisteredClassesTable();
1214   }
1215   bool created = false;
1216   _loaded_unregistered_classes->put_if_absent(name, true, &created);
1217   if (created) {
1218     MutexLocker mu_r(THREAD, Compile_lock); // add_to_hierarchy asserts this.
1219     SystemDictionary::add_to_hierarchy(k, CHECK_false);
1220   }
1221   return created;
1222 }
1223 
1224 // This function is called to resolve the super/interfaces of shared classes for
1225 // non-built-in loaders. E.g., ChildClass in the below example
1226 // where "super:" (and optionally "interface:") have been specified.
1227 //
1228 // java/lang/Object id: 0
1229 // Interface   id: 2 super: 0 source: cust.jar
1230 // ChildClass  id: 4 super: 0 interfaces: 2 source: cust.jar
dump_time_resolve_super_or_fail(Symbol * child_name,Symbol * class_name,Handle class_loader,Handle protection_domain,bool is_superclass,TRAPS)1231 InstanceKlass* SystemDictionaryShared::dump_time_resolve_super_or_fail(
1232     Symbol* child_name, Symbol* class_name, Handle class_loader,
1233     Handle protection_domain, bool is_superclass, TRAPS) {
1234 
1235   assert(DumpSharedSpaces, "only when dumping");
1236 
1237   ClassListParser* parser = ClassListParser::instance();
1238   if (parser == NULL) {
1239     // We're still loading the well-known classes, before the ClassListParser is created.
1240     return NULL;
1241   }
1242   if (child_name->equals(parser->current_class_name())) {
1243     // When this function is called, all the numbered super and interface types
1244     // must have already been loaded. Hence this function is never recursively called.
1245     if (is_superclass) {
1246       return parser->lookup_super_for_current_class(class_name);
1247     } else {
1248       return parser->lookup_interface_for_current_class(class_name);
1249     }
1250   } else {
1251     // The VM is not trying to resolve a super type of parser->current_class_name().
1252     // Instead, it's resolving an error class (because parser->current_class_name() has
1253     // failed parsing or verification). Don't do anything here.
1254     return NULL;
1255   }
1256 }
1257 
start_dumping()1258 void SystemDictionaryShared::start_dumping() {
1259   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1260   _dump_in_progress = true;
1261 }
1262 
find_or_allocate_info_for(InstanceKlass * k)1263 DumpTimeSharedClassInfo* SystemDictionaryShared::find_or_allocate_info_for(InstanceKlass* k) {
1264   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1265   if (_dumptime_table == NULL) {
1266     _dumptime_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeSharedClassTable();
1267   }
1268   return _dumptime_table->find_or_allocate_info_for(k, _dump_in_progress);
1269 }
1270 
set_shared_class_misc_info(InstanceKlass * k,ClassFileStream * cfs)1271 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
1272   Arguments::assert_is_dumping_archive();
1273   assert(!is_builtin(k), "must be unregistered class");
1274   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1275   if (info != NULL) {
1276     info->_clsfile_size  = cfs->length();
1277     info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
1278   }
1279 }
1280 
init_dumptime_info(InstanceKlass * k)1281 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
1282   (void)find_or_allocate_info_for(k);
1283 }
1284 
remove_dumptime_info(InstanceKlass * k)1285 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
1286   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1287   DumpTimeSharedClassInfo* p = _dumptime_table->get(k);
1288   if (p == NULL) {
1289     return;
1290   }
1291   if (p->_verifier_constraints != NULL) {
1292     for (int i = 0; i < p->_verifier_constraints->length(); i++) {
1293       DumpTimeSharedClassInfo::DTVerifierConstraint constraint = p->_verifier_constraints->at(i);
1294       if (constraint._name != NULL ) {
1295         constraint._name->decrement_refcount();
1296       }
1297       if (constraint._from_name != NULL ) {
1298         constraint._from_name->decrement_refcount();
1299       }
1300     }
1301     FREE_C_HEAP_ARRAY(DumpTimeSharedClassInfo::DTVerifierConstraint, p->_verifier_constraints);
1302     p->_verifier_constraints = NULL;
1303     FREE_C_HEAP_ARRAY(char, p->_verifier_constraint_flags);
1304     p->_verifier_constraint_flags = NULL;
1305   }
1306   if (p->_loader_constraints != NULL) {
1307     for (int i = 0; i < p->_loader_constraints->length(); i++) {
1308       DumpTimeSharedClassInfo::DTLoaderConstraint ld =  p->_loader_constraints->at(i);
1309       if (ld._name != NULL) {
1310         ld._name->decrement_refcount();
1311       }
1312     }
1313     FREE_C_HEAP_ARRAY(DumpTimeSharedClassInfo::DTLoaderConstraint, p->_loader_constraints);
1314     p->_loader_constraints = NULL;
1315   }
1316   _dumptime_table->remove(k);
1317 }
1318 
is_jfr_event_class(InstanceKlass * k)1319 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
1320   while (k) {
1321     if (k->name()->equals("jdk/internal/event/Event")) {
1322       return true;
1323     }
1324     k = k->java_super();
1325   }
1326   return false;
1327 }
1328 
is_registered_lambda_proxy_class(InstanceKlass * ik)1329 bool SystemDictionaryShared::is_registered_lambda_proxy_class(InstanceKlass* ik) {
1330   DumpTimeSharedClassInfo* info = _dumptime_table->get(ik);
1331   return (info != NULL) ? info->_is_archived_lambda_proxy : false;
1332 }
1333 
is_hidden_lambda_proxy(InstanceKlass * ik)1334 bool SystemDictionaryShared::is_hidden_lambda_proxy(InstanceKlass* ik) {
1335   assert(ik->is_shared(), "applicable to only a shared class");
1336   if (ik->is_hidden()) {
1337     return true;
1338   } else {
1339     return false;
1340   }
1341 }
1342 
is_early_klass(InstanceKlass * ik)1343 bool SystemDictionaryShared::is_early_klass(InstanceKlass* ik) {
1344   DumpTimeSharedClassInfo* info = _dumptime_table->get(ik);
1345   return (info != NULL) ? info->is_early_klass() : false;
1346 }
1347 
warn_excluded(InstanceKlass * k,const char * reason)1348 void SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) {
1349   ResourceMark rm;
1350   log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason);
1351 }
1352 
should_be_excluded(InstanceKlass * k)1353 bool SystemDictionaryShared::should_be_excluded(InstanceKlass* k) {
1354 
1355   if (k->is_unsafe_anonymous()) {
1356     warn_excluded(k, "Unsafe anonymous class");
1357     return true; // unsafe anonymous classes are not archived, skip
1358   }
1359 
1360   if (k->is_in_error_state()) {
1361     warn_excluded(k, "In error state");
1362     return true;
1363   }
1364   if (k->has_been_redefined()) {
1365     warn_excluded(k, "Has been redefined");
1366     return true;
1367   }
1368   if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) {
1369     // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
1370     // agent during dump time).
1371     warn_excluded(k, "Unsupported location");
1372     return true;
1373   }
1374   if (k->signers() != NULL) {
1375     // We cannot include signed classes in the archive because the certificates
1376     // used during dump time may be different than those used during
1377     // runtime (due to expiration, etc).
1378     warn_excluded(k, "Signed JAR");
1379     return true;
1380   }
1381   if (is_jfr_event_class(k)) {
1382     // We cannot include JFR event classes because they need runtime-specific
1383     // instrumentation in order to work with -XX:FlightRecorderOptions=retransform=false.
1384     // There are only a small number of these classes, so it's not worthwhile to
1385     // support them and make CDS more complicated.
1386     warn_excluded(k, "JFR event class");
1387     return true;
1388   }
1389   if (k->init_state() < InstanceKlass::linked) {
1390     // In CDS dumping, we will attempt to link all classes. Those that fail to link will
1391     // be recorded in DumpTimeSharedClassInfo.
1392     Arguments::assert_is_dumping_archive();
1393 
1394     // TODO -- rethink how this can be handled.
1395     // We should try to link ik, however, we can't do it here because
1396     // 1. We are at VM exit
1397     // 2. linking a class may cause other classes to be loaded, which means
1398     //    a custom ClassLoader.loadClass() may be called, at a point where the
1399     //    class loader doesn't expect it.
1400     if (has_class_failed_verification(k)) {
1401       warn_excluded(k, "Failed verification");
1402     } else {
1403       warn_excluded(k, "Not linked");
1404     }
1405     return true;
1406   }
1407   if (k->major_version() < 50 /*JAVA_6_VERSION*/) {
1408     ResourceMark rm;
1409     log_warning(cds)("Pre JDK 6 class not supported by CDS: %u.%u %s",
1410                      k->major_version(),  k->minor_version(), k->name()->as_C_string());
1411     return true;
1412   }
1413 
1414   InstanceKlass* super = k->java_super();
1415   if (super != NULL && should_be_excluded(super)) {
1416     ResourceMark rm;
1417     log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
1418     return true;
1419   }
1420 
1421   if (k->is_hidden() && !is_registered_lambda_proxy_class(k)) {
1422     ResourceMark rm;
1423     log_debug(cds)("Skipping %s: %s", k->name()->as_C_string(), "Hidden class");
1424     return true;
1425   }
1426 
1427   Array<InstanceKlass*>* interfaces = k->local_interfaces();
1428   int len = interfaces->length();
1429   for (int i = 0; i < len; i++) {
1430     InstanceKlass* intf = interfaces->at(i);
1431     if (should_be_excluded(intf)) {
1432       log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
1433       return true;
1434     }
1435   }
1436 
1437   return false;
1438 }
1439 
1440 // k is a class before relocating by ArchiveBuilder
validate_before_archiving(InstanceKlass * k)1441 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
1442   ResourceMark rm;
1443   const char* name = k->name()->as_C_string();
1444   DumpTimeSharedClassInfo* info = _dumptime_table->get(k);
1445   assert(_no_class_loading_should_happen, "class loading must be disabled");
1446   guarantee(info != NULL, "Class %s must be entered into _dumptime_table", name);
1447   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
1448   if (is_builtin(k)) {
1449     if (k->is_hidden()) {
1450       assert(is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name);
1451     }
1452     guarantee(!k->is_shared_unregistered_class(),
1453               "Class loader type must be set for BUILTIN class %s", name);
1454 
1455   } else {
1456     guarantee(k->is_shared_unregistered_class(),
1457               "Class loader type must not be set for UNREGISTERED class %s", name);
1458   }
1459 }
1460 
1461 class ExcludeDumpTimeSharedClasses : StackObj {
1462 public:
do_entry(InstanceKlass * k,DumpTimeSharedClassInfo & info)1463   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1464     if (SystemDictionaryShared::should_be_excluded(k) || info.is_excluded()) {
1465       info.set_excluded();
1466     }
1467     return true; // keep on iterating
1468   }
1469 };
1470 
check_excluded_classes()1471 void SystemDictionaryShared::check_excluded_classes() {
1472   ExcludeDumpTimeSharedClasses excl;
1473   _dumptime_table->iterate(&excl);
1474   _dumptime_table->update_counts();
1475 }
1476 
is_excluded_class(InstanceKlass * k)1477 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
1478   assert(_no_class_loading_should_happen, "sanity");
1479   Arguments::assert_is_dumping_archive();
1480   DumpTimeSharedClassInfo* p = find_or_allocate_info_for(k);
1481   return (p == NULL) ? true : p->is_excluded();
1482 }
1483 
set_excluded(InstanceKlass * k)1484 void SystemDictionaryShared::set_excluded(InstanceKlass* k) {
1485   Arguments::assert_is_dumping_archive();
1486   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1487   if (info != NULL) {
1488     info->set_excluded();
1489   }
1490 }
1491 
set_class_has_failed_verification(InstanceKlass * ik)1492 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
1493   Arguments::assert_is_dumping_archive();
1494   DumpTimeSharedClassInfo* p = find_or_allocate_info_for(ik);
1495   if (p != NULL) {
1496     p->set_failed_verification();
1497   }
1498 }
1499 
has_class_failed_verification(InstanceKlass * ik)1500 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
1501   Arguments::assert_is_dumping_archive();
1502   if (_dumptime_table == NULL) {
1503     assert(DynamicDumpSharedSpaces, "sanity");
1504     assert(ik->is_shared(), "must be a shared class in the static archive");
1505     return false;
1506   }
1507   DumpTimeSharedClassInfo* p = _dumptime_table->get(ik);
1508   return (p == NULL) ? false : p->failed_verification();
1509 }
1510 
1511 class IterateDumpTimeSharedClassTable : StackObj {
1512   MetaspaceClosure *_it;
1513 public:
IterateDumpTimeSharedClassTable(MetaspaceClosure * it)1514   IterateDumpTimeSharedClassTable(MetaspaceClosure* it) : _it(it) {}
1515 
do_entry(InstanceKlass * k,DumpTimeSharedClassInfo & info)1516   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1517     if (!info.is_excluded()) {
1518       info.metaspace_pointers_do(_it);
1519     }
1520     return true; // keep on iterating
1521   }
1522 };
1523 
1524 class IterateDumpTimeLambdaProxyClassDictionary : StackObj {
1525   MetaspaceClosure *_it;
1526 public:
IterateDumpTimeLambdaProxyClassDictionary(MetaspaceClosure * it)1527   IterateDumpTimeLambdaProxyClassDictionary(MetaspaceClosure* it) : _it(it) {}
1528 
do_entry(LambdaProxyClassKey & key,DumpTimeLambdaProxyClassInfo & info)1529   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1530     info.metaspace_pointers_do(_it);
1531     key.metaspace_pointers_do(_it);
1532     return true;
1533   }
1534 };
1535 
dumptime_classes_do(class MetaspaceClosure * it)1536 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) {
1537   assert_locked_or_safepoint(DumpTimeTable_lock);
1538   IterateDumpTimeSharedClassTable iter(it);
1539   _dumptime_table->iterate(&iter);
1540   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
1541     IterateDumpTimeLambdaProxyClassDictionary iter_lambda(it);
1542     _dumptime_lambda_proxy_class_dictionary->iterate(&iter_lambda);
1543   }
1544 }
1545 
add_verification_constraint(InstanceKlass * k,Symbol * name,Symbol * from_name,bool from_field_is_protected,bool from_is_array,bool from_is_object)1546 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
1547          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1548   Arguments::assert_is_dumping_archive();
1549   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1550   if (info != NULL) {
1551     info->add_verification_constraint(k, name, from_name, from_field_is_protected,
1552                                       from_is_array, from_is_object);
1553   } else {
1554     return true;
1555   }
1556   if (DynamicDumpSharedSpaces) {
1557     // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
1558     // the initial run prior to creating the archive before vm exit. We will also perform verification
1559     // check when running with the archive.
1560     return false;
1561   } else {
1562     if (is_builtin(k)) {
1563       // For builtin class loaders, we can try to complete the verification check at dump time,
1564       // because we can resolve all the constraint classes. We will also perform verification check
1565       // when running with the archive.
1566       return false;
1567     } else {
1568       // For non-builtin class loaders, we cannot complete the verification check at dump time,
1569       // because at dump time we don't know how to resolve classes for such loaders.
1570       return true;
1571     }
1572   }
1573 }
1574 
add_verification_constraint(InstanceKlass * k,Symbol * name,Symbol * from_name,bool from_field_is_protected,bool from_is_array,bool from_is_object)1575 void DumpTimeSharedClassInfo::add_verification_constraint(InstanceKlass* k, Symbol* name,
1576          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1577   if (_verifier_constraints == NULL) {
1578     _verifier_constraints = new(ResourceObj::C_HEAP, mtClass) GrowableArray<DTVerifierConstraint>(4, mtClass);
1579   }
1580   if (_verifier_constraint_flags == NULL) {
1581     _verifier_constraint_flags = new(ResourceObj::C_HEAP, mtClass) GrowableArray<char>(4, mtClass);
1582   }
1583   GrowableArray<DTVerifierConstraint>* vc_array = _verifier_constraints;
1584   for (int i = 0; i < vc_array->length(); i++) {
1585     DTVerifierConstraint* p = vc_array->adr_at(i);
1586     if (name == p->_name && from_name == p->_from_name) {
1587       return;
1588     }
1589   }
1590   DTVerifierConstraint cons(name, from_name);
1591   vc_array->append(cons);
1592 
1593   GrowableArray<char>* vcflags_array = _verifier_constraint_flags;
1594   char c = 0;
1595   c |= from_field_is_protected ? SystemDictionaryShared::FROM_FIELD_IS_PROTECTED : 0;
1596   c |= from_is_array           ? SystemDictionaryShared::FROM_IS_ARRAY           : 0;
1597   c |= from_is_object          ? SystemDictionaryShared::FROM_IS_OBJECT          : 0;
1598   vcflags_array->append(c);
1599 
1600   if (log_is_enabled(Trace, cds, verification)) {
1601     ResourceMark rm;
1602     log_trace(cds, verification)("add_verification_constraint: %s: %s must be subclass of %s [0x%x] array len %d flags len %d",
1603                                  k->external_name(), from_name->as_klass_external_name(),
1604                                  name->as_klass_external_name(), c, vc_array->length(), vcflags_array->length());
1605   }
1606 }
1607 
add_lambda_proxy_class(InstanceKlass * caller_ik,InstanceKlass * lambda_ik,Symbol * invoked_name,Symbol * invoked_type,Symbol * method_type,Method * member_method,Symbol * instantiated_method_type,TRAPS)1608 void SystemDictionaryShared::add_lambda_proxy_class(InstanceKlass* caller_ik,
1609                                                     InstanceKlass* lambda_ik,
1610                                                     Symbol* invoked_name,
1611                                                     Symbol* invoked_type,
1612                                                     Symbol* method_type,
1613                                                     Method* member_method,
1614                                                     Symbol* instantiated_method_type,
1615                                                     TRAPS) {
1616 
1617   assert(caller_ik->class_loader() == lambda_ik->class_loader(), "mismatched class loader");
1618   assert(caller_ik->class_loader_data() == lambda_ik->class_loader_data(), "mismatched class loader data");
1619   assert(java_lang_Class::class_data(lambda_ik->java_mirror()) == NULL, "must not have class data");
1620 
1621   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1622 
1623   lambda_ik->assign_class_loader_type();
1624   lambda_ik->set_shared_classpath_index(caller_ik->shared_classpath_index());
1625   InstanceKlass* nest_host = caller_ik->nest_host(THREAD);
1626 
1627   DumpTimeSharedClassInfo* info = _dumptime_table->get(lambda_ik);
1628   if (info != NULL && !lambda_ik->is_non_strong_hidden() && is_builtin(lambda_ik) && is_builtin(caller_ik)
1629       // Don't include the lambda proxy if its nest host is not in the "linked" state.
1630       && nest_host->is_linked()) {
1631     // Set _is_archived_lambda_proxy in DumpTimeSharedClassInfo so that the lambda_ik
1632     // won't be excluded during dumping of shared archive. See ExcludeDumpTimeSharedClasses.
1633     info->_is_archived_lambda_proxy = true;
1634     info->set_nest_host(nest_host);
1635 
1636     LambdaProxyClassKey key(caller_ik,
1637                             invoked_name,
1638                             invoked_type,
1639                             method_type,
1640                             member_method,
1641                             instantiated_method_type);
1642     add_to_dump_time_lambda_proxy_class_dictionary(key, lambda_ik);
1643   }
1644 }
1645 
get_shared_lambda_proxy_class(InstanceKlass * caller_ik,Symbol * invoked_name,Symbol * invoked_type,Symbol * method_type,Method * member_method,Symbol * instantiated_method_type)1646 InstanceKlass* SystemDictionaryShared::get_shared_lambda_proxy_class(InstanceKlass* caller_ik,
1647                                                                      Symbol* invoked_name,
1648                                                                      Symbol* invoked_type,
1649                                                                      Symbol* method_type,
1650                                                                      Method* member_method,
1651                                                                      Symbol* instantiated_method_type) {
1652   MutexLocker ml(CDSLambda_lock, Mutex::_no_safepoint_check_flag);
1653   LambdaProxyClassKey key(caller_ik, invoked_name, invoked_type,
1654                           method_type, member_method, instantiated_method_type);
1655   const RunTimeLambdaProxyClassInfo* info = _lambda_proxy_class_dictionary.lookup(&key, key.hash(), 0);
1656   if (info == NULL) {
1657     // Try lookup from the dynamic lambda proxy class dictionary.
1658     info = _dynamic_lambda_proxy_class_dictionary.lookup(&key, key.hash(), 0);
1659   }
1660   InstanceKlass* proxy_klass = NULL;
1661   if (info != NULL) {
1662     InstanceKlass* curr_klass = info->proxy_klass_head();
1663     InstanceKlass* prev_klass = curr_klass;
1664     if (curr_klass->lambda_proxy_is_available()) {
1665       while (curr_klass->next_link() != NULL) {
1666         prev_klass = curr_klass;
1667         curr_klass = InstanceKlass::cast(curr_klass->next_link());
1668       }
1669       assert(curr_klass->is_hidden(), "must be");
1670       assert(curr_klass->lambda_proxy_is_available(), "must be");
1671 
1672       prev_klass->set_next_link(NULL);
1673       proxy_klass = curr_klass;
1674       proxy_klass->clear_lambda_proxy_is_available();
1675       if (log_is_enabled(Debug, cds)) {
1676         ResourceMark rm;
1677         log_debug(cds)("Loaded lambda proxy: %s ", proxy_klass->external_name());
1678       }
1679     } else {
1680       if (log_is_enabled(Debug, cds)) {
1681         ResourceMark rm;
1682         log_debug(cds)("Used all archived lambda proxy classes for: %s %s%s",
1683                        caller_ik->external_name(), invoked_name->as_C_string(), invoked_type->as_C_string());
1684       }
1685     }
1686   }
1687   return proxy_klass;
1688 }
1689 
get_shared_nest_host(InstanceKlass * lambda_ik)1690 InstanceKlass* SystemDictionaryShared::get_shared_nest_host(InstanceKlass* lambda_ik) {
1691   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1692   RunTimeSharedClassInfo* record = RunTimeSharedClassInfo::get_for(lambda_ik);
1693   return record->nest_host();
1694 }
1695 
prepare_shared_lambda_proxy_class(InstanceKlass * lambda_ik,InstanceKlass * caller_ik,TRAPS)1696 InstanceKlass* SystemDictionaryShared::prepare_shared_lambda_proxy_class(InstanceKlass* lambda_ik,
1697                                                                          InstanceKlass* caller_ik, TRAPS) {
1698   Handle class_loader(THREAD, caller_ik->class_loader());
1699   Handle protection_domain;
1700   PackageEntry* pkg_entry = get_package_entry_from_class_name(class_loader, caller_ik->name());
1701   if (caller_ik->class_loader() != NULL) {
1702     protection_domain = SystemDictionaryShared::init_security_info(class_loader, caller_ik, pkg_entry, CHECK_NULL);
1703   }
1704 
1705   InstanceKlass* shared_nest_host = get_shared_nest_host(lambda_ik);
1706   assert(shared_nest_host != NULL, "unexpected NULL _nest_host");
1707 
1708   InstanceKlass* loaded_lambda =
1709     SystemDictionary::load_shared_lambda_proxy_class(lambda_ik, class_loader, protection_domain, pkg_entry, CHECK_NULL);
1710 
1711   if (loaded_lambda == NULL) {
1712     return NULL;
1713   }
1714 
1715   // Ensures the nest host is the same as the lambda proxy's
1716   // nest host recorded at dump time.
1717   InstanceKlass* nest_host = caller_ik->nest_host(THREAD);
1718   assert(nest_host == shared_nest_host, "mismatched nest host");
1719 
1720   EventClassLoad class_load_start_event;
1721   {
1722     MutexLocker mu_r(THREAD, Compile_lock);
1723 
1724     // Add to class hierarchy, initialize vtables, and do possible
1725     // deoptimizations.
1726     SystemDictionary::add_to_hierarchy(loaded_lambda, CHECK_NULL); // No exception, but can block
1727     // But, do not add to dictionary.
1728   }
1729   loaded_lambda->link_class(CHECK_NULL);
1730   // notify jvmti
1731   if (JvmtiExport::should_post_class_load()) {
1732     JvmtiExport::post_class_load(THREAD->as_Java_thread(), loaded_lambda);
1733   }
1734   if (class_load_start_event.should_commit()) {
1735     SystemDictionary::post_class_load_event(&class_load_start_event, loaded_lambda, ClassLoaderData::class_loader_data(class_loader()));
1736   }
1737 
1738   loaded_lambda->initialize(CHECK_NULL);
1739 
1740   return loaded_lambda;
1741 }
1742 
get_loader_type_by(oop loader)1743 static char get_loader_type_by(oop  loader) {
1744   assert(SystemDictionary::is_builtin_class_loader(loader), "Must be built-in loader");
1745   if (SystemDictionary::is_boot_class_loader(loader)) {
1746     return (char)ClassLoader::BOOT_LOADER;
1747   } else if (SystemDictionary::is_platform_class_loader(loader)) {
1748     return (char)ClassLoader::PLATFORM_LOADER;
1749   } else {
1750     assert(SystemDictionary::is_system_class_loader(loader), "Class loader mismatch");
1751     return (char)ClassLoader::APP_LOADER;
1752   }
1753 }
1754 
get_class_loader_by(char type)1755 static oop get_class_loader_by(char type) {
1756   if (type == (char)ClassLoader::BOOT_LOADER) {
1757     return (oop)NULL;
1758   } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
1759     return SystemDictionary::java_platform_loader();
1760   } else {
1761     assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
1762     return SystemDictionary::java_system_loader();
1763   }
1764 }
1765 
record_linking_constraint(Symbol * name,Handle loader1,Handle loader2)1766 void DumpTimeSharedClassInfo::record_linking_constraint(Symbol* name, Handle loader1, Handle loader2) {
1767   assert(loader1 != loader2, "sanity");
1768   LogTarget(Info, class, loader, constraints) log;
1769   if (_loader_constraints == NULL) {
1770     _loader_constraints = new (ResourceObj::C_HEAP, mtClass) GrowableArray<DTLoaderConstraint>(4, mtClass);
1771   }
1772   char lt1 = get_loader_type_by(loader1());
1773   char lt2 = get_loader_type_by(loader2());
1774   DTLoaderConstraint lc(name, lt1, lt2);
1775   for (int i = 0; i < _loader_constraints->length(); i++) {
1776     DTLoaderConstraint dt = _loader_constraints->at(i);
1777     if (lc.equals(dt)) {
1778       if (log.is_enabled()) {
1779         ResourceMark rm;
1780         // Use loader[0]/loader[1] to be consistent with the logs in loaderConstraints.cpp
1781         log.print("[CDS record loader constraint for class: %s constraint_name: %s loader[0]: %s loader[1]: %s already added]",
1782                   _klass->external_name(), name->as_C_string(),
1783                   ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1784                   ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1785       }
1786       return;
1787     }
1788   }
1789   _loader_constraints->append(lc);
1790   if (log.is_enabled()) {
1791     ResourceMark rm;
1792     // Use loader[0]/loader[1] to be consistent with the logs in loaderConstraints.cpp
1793     log.print("[CDS record loader constraint for class: %s constraint_name: %s loader[0]: %s loader[1]: %s total %d]",
1794               _klass->external_name(), name->as_C_string(),
1795               ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1796               ClassLoaderData::class_loader_data(loader2())->loader_name_and_id(),
1797               _loader_constraints->length());
1798   }
1799 }
1800 
check_verification_constraints(InstanceKlass * klass,TRAPS)1801 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
1802                                                             TRAPS) {
1803   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1804   RunTimeSharedClassInfo* record = RunTimeSharedClassInfo::get_for(klass);
1805 
1806   int length = record->_num_verifier_constraints;
1807   if (length > 0) {
1808     for (int i = 0; i < length; i++) {
1809       RunTimeSharedClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
1810       Symbol* name      = vc->name();
1811       Symbol* from_name = vc->from_name();
1812       char c            = record->verifier_constraint_flag(i);
1813 
1814       if (log_is_enabled(Trace, cds, verification)) {
1815         ResourceMark rm(THREAD);
1816         log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1817                                      klass->external_name(), from_name->as_klass_external_name(),
1818                                      name->as_klass_external_name(), c);
1819       }
1820 
1821       bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false;
1822       bool from_is_array           = (c & SystemDictionaryShared::FROM_IS_ARRAY)           ? true : false;
1823       bool from_is_object          = (c & SystemDictionaryShared::FROM_IS_OBJECT)          ? true : false;
1824 
1825       bool ok = VerificationType::resolve_and_check_assignability(klass, name,
1826          from_name, from_field_is_protected, from_is_array, from_is_object, CHECK);
1827       if (!ok) {
1828         ResourceMark rm(THREAD);
1829         stringStream ss;
1830 
1831         ss.print_cr("Bad type on operand stack");
1832         ss.print_cr("Exception Details:");
1833         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
1834         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
1835                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
1836         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
1837       }
1838     }
1839   }
1840 }
1841 
1842 // Record class loader constraints that are checked inside
1843 // InstanceKlass::link_class(), so that these can be checked quickly
1844 // at runtime without laying out the vtable/itables.
record_linking_constraint(Symbol * name,InstanceKlass * klass,Handle loader1,Handle loader2,TRAPS)1845 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
1846                                                     Handle loader1, Handle loader2, TRAPS) {
1847   // A linking constraint check is executed when:
1848   //   - klass extends or implements type S
1849   //   - klass overrides method S.M(...) with X.M
1850   //     - If klass defines the method M, X is
1851   //       the same as klass.
1852   //     - If klass does not define the method M,
1853   //       X must be a supertype of klass and X.M is
1854   //       a default method defined by X.
1855   //   - loader1 = X->class_loader()
1856   //   - loader2 = S->class_loader()
1857   //   - loader1 != loader2
1858   //   - M's paramater(s) include an object type T
1859   // We require that
1860   //   - whenever loader1 and loader2 try to
1861   //     resolve the type T, they must always resolve to
1862   //     the same InstanceKlass.
1863   // NOTE: type T may or may not be currently resolved in
1864   // either of these two loaders. The check itself does not
1865   // try to resolve T.
1866   oop klass_loader = klass->class_loader();
1867   assert(klass_loader != NULL, "should not be called for boot loader");
1868   assert(loader1 != loader2, "must be");
1869 
1870   if (!is_system_class_loader(klass_loader) &&
1871       !is_platform_class_loader(klass_loader)) {
1872     // If klass is loaded by system/platform loaders, we can
1873     // guarantee that klass and S must be loaded by the same
1874     // respective loader between dump time and run time, and
1875     // the exact same check on (name, loader1, loader2) will
1876     // be executed. Hence, we can cache this check and execute
1877     // it at runtime without walking the vtable/itables.
1878     //
1879     // This cannot be guaranteed for classes loaded by other
1880     // loaders, so we bail.
1881     return;
1882   }
1883 
1884   if (THREAD->is_VM_thread()) {
1885     assert(DynamicDumpSharedSpaces, "must be");
1886     // We are re-laying out the vtable/itables of the *copy* of
1887     // a class during the final stage of dynamic dumping. The
1888     // linking constraints for this class has already been recorded.
1889     return;
1890   }
1891   Arguments::assert_is_dumping_archive();
1892   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(klass);
1893   if (info != NULL) {
1894     info->record_linking_constraint(name, loader1, loader2);
1895   }
1896 }
1897 
1898 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
1899 // the purpose of checking class loader constraints.
check_linking_constraints(InstanceKlass * klass,TRAPS)1900 bool SystemDictionaryShared::check_linking_constraints(InstanceKlass* klass, TRAPS) {
1901   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1902   LogTarget(Info, class, loader, constraints) log;
1903   if (klass->is_shared_boot_class()) {
1904     // No class loader constraint check performed for boot classes.
1905     return true;
1906   }
1907   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
1908     RunTimeSharedClassInfo* info = RunTimeSharedClassInfo::get_for(klass);
1909     assert(info != NULL, "Sanity");
1910     if (info->_num_loader_constraints > 0) {
1911       HandleMark hm(THREAD);
1912       for (int i = 0; i < info->_num_loader_constraints; i++) {
1913         RunTimeSharedClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1914         Symbol* name = lc->constraint_name();
1915         Handle loader1(THREAD, get_class_loader_by(lc->_loader_type1));
1916         Handle loader2(THREAD, get_class_loader_by(lc->_loader_type2));
1917         if (log.is_enabled()) {
1918           ResourceMark rm(THREAD);
1919           log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1920                     klass->external_name(), name->as_C_string(),
1921                     ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1922                     ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1923         }
1924         if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2, THREAD)) {
1925           // Loader constraint violation has been found. The caller
1926           // will re-layout the vtable/itables to produce the correct
1927           // exception.
1928           if (log.is_enabled()) {
1929             log.print(" failed]");
1930           }
1931           return false;
1932         }
1933         if (log.is_enabled()) {
1934             log.print(" succeeded]");
1935         }
1936       }
1937       return true; // for all recorded constraints added successully.
1938     }
1939   }
1940   if (log.is_enabled()) {
1941     ResourceMark rm(THREAD);
1942     log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
1943   }
1944   return false;
1945 }
1946 
is_supported_invokedynamic(BootstrapInfo * bsi)1947 bool SystemDictionaryShared::is_supported_invokedynamic(BootstrapInfo* bsi) {
1948   LogTarget(Debug, cds, lambda) log;
1949   if (bsi->arg_values() == NULL || !bsi->arg_values()->is_objArray()) {
1950     if (log.is_enabled()) {
1951       LogStream log_stream(log);
1952       log.print("bsi check failed");
1953       log.print("    bsi->arg_values().not_null() %d", bsi->arg_values().not_null());
1954       if (bsi->arg_values().not_null()) {
1955         log.print("    bsi->arg_values()->is_objArray() %d", bsi->arg_values()->is_objArray());
1956         bsi->print_msg_on(&log_stream);
1957       }
1958     }
1959     return false;
1960   }
1961 
1962   Handle bsm = bsi->bsm();
1963   if (bsm.is_null() || !java_lang_invoke_DirectMethodHandle::is_instance(bsm())) {
1964     if (log.is_enabled()) {
1965       log.print("bsm check failed");
1966       log.print("    bsm.is_null() %d", bsm.is_null());
1967       log.print("    java_lang_invoke_DirectMethodHandle::is_instance(bsm()) %d",
1968         java_lang_invoke_DirectMethodHandle::is_instance(bsm()));
1969     }
1970     return false;
1971   }
1972 
1973   oop mn = java_lang_invoke_DirectMethodHandle::member(bsm());
1974   Method* method = java_lang_invoke_MemberName::vmtarget(mn);
1975   if (method->klass_name()->equals("java/lang/invoke/LambdaMetafactory") &&
1976       method->name()->equals("metafactory") &&
1977       method->signature()->equals("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;")) {
1978       return true;
1979   } else {
1980     if (log.is_enabled()) {
1981       ResourceMark rm;
1982       log.print("method check failed");
1983       log.print("    klass_name() %s", method->klass_name()->as_C_string());
1984       log.print("    name() %s", method->name()->as_C_string());
1985       log.print("    signature() %s", method->signature()->as_C_string());
1986     }
1987   }
1988 
1989   return false;
1990 }
1991 
1992 class EstimateSizeForArchive : StackObj {
1993   size_t _shared_class_info_size;
1994   int _num_builtin_klasses;
1995   int _num_unregistered_klasses;
1996 
1997 public:
EstimateSizeForArchive()1998   EstimateSizeForArchive() {
1999     _shared_class_info_size = 0;
2000     _num_builtin_klasses = 0;
2001     _num_unregistered_klasses = 0;
2002   }
2003 
do_entry(InstanceKlass * k,DumpTimeSharedClassInfo & info)2004   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
2005     if (!info.is_excluded()) {
2006       size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_verifier_constraints(), info.num_loader_constraints());
2007       _shared_class_info_size += align_up(byte_size, SharedSpaceObjectAlignment);
2008     }
2009     return true; // keep on iterating
2010   }
2011 
total()2012   size_t total() {
2013     return _shared_class_info_size;
2014   }
2015 };
2016 
estimate_size_for_archive()2017 size_t SystemDictionaryShared::estimate_size_for_archive() {
2018   EstimateSizeForArchive est;
2019   _dumptime_table->iterate(&est);
2020   size_t total_size = est.total() +
2021     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) +
2022     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false));
2023   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
2024     size_t bytesize = align_up(sizeof(RunTimeLambdaProxyClassInfo), SharedSpaceObjectAlignment);
2025     total_size +=
2026       (bytesize * _dumptime_lambda_proxy_class_dictionary->_count) +
2027       CompactHashtableWriter::estimate_size(_dumptime_lambda_proxy_class_dictionary->_count);
2028   } else {
2029     total_size += CompactHashtableWriter::estimate_size(0);
2030   }
2031   return total_size;
2032 }
2033 
2034 class CopyLambdaProxyClassInfoToArchive : StackObj {
2035   CompactHashtableWriter* _writer;
2036 public:
CopyLambdaProxyClassInfoToArchive(CompactHashtableWriter * writer)2037   CopyLambdaProxyClassInfoToArchive(CompactHashtableWriter* writer)
2038     : _writer(writer) {}
do_entry(LambdaProxyClassKey & key,DumpTimeLambdaProxyClassInfo & info)2039   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
2040     // In static dump, info._proxy_klasses->at(0) is already relocated to point to the archived class
2041     // (not the original class).
2042     //
2043     // The following check has been moved to SystemDictionaryShared::check_excluded_classes(), which
2044     // happens before the classes are copied.
2045     //
2046     // if (SystemDictionaryShared::is_excluded_class(info._proxy_klasses->at(0))) {
2047     //  return true;
2048     //}
2049     ResourceMark rm;
2050     log_info(cds,dynamic)("Archiving hidden %s", info._proxy_klasses->at(0)->external_name());
2051     size_t byte_size = sizeof(RunTimeLambdaProxyClassInfo);
2052     RunTimeLambdaProxyClassInfo* runtime_info =
2053         (RunTimeLambdaProxyClassInfo*)MetaspaceShared::read_only_space_alloc(byte_size);
2054     runtime_info->init(key, info);
2055     unsigned int hash = runtime_info->hash(); // Fields in runtime_info->_key already point to target space.
2056     u4 delta = DynamicDumpSharedSpaces ?
2057                  MetaspaceShared::object_delta_u4((void*)DynamicArchive::buffer_to_target(runtime_info)) :
2058                  MetaspaceShared::object_delta_u4((void*)runtime_info);
2059     _writer->add(hash, delta);
2060     return true;
2061   }
2062 };
2063 
2064 class AdjustLambdaProxyClassInfo : StackObj {
2065 public:
AdjustLambdaProxyClassInfo()2066   AdjustLambdaProxyClassInfo() {}
do_entry(LambdaProxyClassKey & key,DumpTimeLambdaProxyClassInfo & info)2067   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
2068     int len = info._proxy_klasses->length();
2069     if (len > 1) {
2070       for (int i = 0; i < len-1; i++) {
2071         InstanceKlass* ok0 = info._proxy_klasses->at(i+0); // this is original klass
2072         InstanceKlass* ok1 = info._proxy_klasses->at(i+1); // this is original klass
2073         InstanceKlass* bk0 = DynamicDumpSharedSpaces ? DynamicArchive::original_to_buffer(ok0) : ok0;
2074         InstanceKlass* bk1 = DynamicDumpSharedSpaces ? DynamicArchive::original_to_buffer(ok1) : ok1;
2075         assert(bk0->next_link() == 0, "must be called after Klass::remove_unshareable_info()");
2076         assert(bk1->next_link() == 0, "must be called after Klass::remove_unshareable_info()");
2077         bk0->set_next_link(bk1);
2078         bk1->set_lambda_proxy_is_available();
2079         ArchivePtrMarker::mark_pointer(bk0->next_link_addr());
2080       }
2081     }
2082     if (DynamicDumpSharedSpaces) {
2083       DynamicArchive::original_to_buffer(info._proxy_klasses->at(0))->set_lambda_proxy_is_available();
2084     } else {
2085       info._proxy_klasses->at(0)->set_lambda_proxy_is_available();
2086     }
2087     return true;
2088   }
2089 };
2090 
2091 class CopySharedClassInfoToArchive : StackObj {
2092   CompactHashtableWriter* _writer;
2093   bool _is_builtin;
2094 public:
CopySharedClassInfoToArchive(CompactHashtableWriter * writer,bool is_builtin)2095   CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
2096                                bool is_builtin)
2097     : _writer(writer), _is_builtin(is_builtin) {}
2098 
do_entry(InstanceKlass * k,DumpTimeSharedClassInfo & info)2099   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
2100     if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
2101       size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_verifier_constraints(), info.num_loader_constraints());
2102       RunTimeSharedClassInfo* record;
2103       record = (RunTimeSharedClassInfo*)MetaspaceShared::read_only_space_alloc(byte_size);
2104       record->init(info);
2105 
2106       unsigned int hash;
2107       Symbol* name = info._klass->name();
2108       if (DynamicDumpSharedSpaces) {
2109         name = DynamicArchive::original_to_target(name);
2110       }
2111       hash = SystemDictionaryShared::hash_for_shared_dictionary(name);
2112       u4 delta;
2113       if (DynamicDumpSharedSpaces) {
2114         delta = MetaspaceShared::object_delta_u4(DynamicArchive::buffer_to_target(record));
2115       } else {
2116         delta = MetaspaceShared::object_delta_u4(record);
2117       }
2118       if (_is_builtin && info._klass->is_hidden()) {
2119         // skip
2120       } else {
2121         _writer->add(hash, delta);
2122       }
2123       if (log_is_enabled(Trace, cds, hashtables)) {
2124         ResourceMark rm;
2125         log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
2126       }
2127 
2128       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeSharedClassInfo*
2129       RunTimeSharedClassInfo::set_for(info._klass, record);
2130     }
2131     return true; // keep on iterating
2132   }
2133 };
2134 
write_lambda_proxy_class_dictionary(LambdaProxyClassDictionary * dictionary)2135 void SystemDictionaryShared::write_lambda_proxy_class_dictionary(LambdaProxyClassDictionary *dictionary) {
2136   CompactHashtableStats stats;
2137   dictionary->reset();
2138   CompactHashtableWriter writer(_dumptime_lambda_proxy_class_dictionary->_count, &stats);
2139   CopyLambdaProxyClassInfoToArchive copy(&writer);
2140   _dumptime_lambda_proxy_class_dictionary->iterate(&copy);
2141   writer.dump(dictionary, "lambda proxy class dictionary");
2142 }
2143 
write_dictionary(RunTimeSharedDictionary * dictionary,bool is_builtin)2144 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
2145                                               bool is_builtin) {
2146   CompactHashtableStats stats;
2147   dictionary->reset();
2148   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
2149   CopySharedClassInfoToArchive copy(&writer, is_builtin);
2150   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
2151   _dumptime_table->iterate(&copy);
2152   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
2153 }
2154 
write_to_archive(bool is_static_archive)2155 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
2156   if (is_static_archive) {
2157     write_dictionary(&_builtin_dictionary, true);
2158     write_dictionary(&_unregistered_dictionary, false);
2159   } else {
2160     write_dictionary(&_dynamic_builtin_dictionary, true);
2161     write_dictionary(&_dynamic_unregistered_dictionary, false);
2162   }
2163   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
2164     write_lambda_proxy_class_dictionary(&_lambda_proxy_class_dictionary);
2165   }
2166 }
2167 
adjust_lambda_proxy_class_dictionary()2168 void SystemDictionaryShared::adjust_lambda_proxy_class_dictionary() {
2169   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
2170     AdjustLambdaProxyClassInfo adjuster;
2171     _dumptime_lambda_proxy_class_dictionary->iterate(&adjuster);
2172   }
2173 }
2174 
serialize_dictionary_headers(SerializeClosure * soc,bool is_static_archive)2175 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
2176                                                           bool is_static_archive) {
2177   FileMapInfo *dynamic_mapinfo = FileMapInfo::dynamic_info();
2178   if (is_static_archive) {
2179     _builtin_dictionary.serialize_header(soc);
2180     _unregistered_dictionary.serialize_header(soc);
2181     if (dynamic_mapinfo == NULL || DynamicDumpSharedSpaces || (dynamic_mapinfo != NULL && UseSharedSpaces)) {
2182       _lambda_proxy_class_dictionary.serialize_header(soc);
2183     }
2184   } else {
2185     _dynamic_builtin_dictionary.serialize_header(soc);
2186     _dynamic_unregistered_dictionary.serialize_header(soc);
2187     if (DynamicDumpSharedSpaces) {
2188       _lambda_proxy_class_dictionary.serialize_header(soc);
2189     } else {
2190       _dynamic_lambda_proxy_class_dictionary.serialize_header(soc);
2191     }
2192   }
2193 }
2194 
serialize_well_known_klasses(SerializeClosure * soc)2195 void SystemDictionaryShared::serialize_well_known_klasses(SerializeClosure* soc) {
2196   for (int i = FIRST_WKID; i < WKID_LIMIT; i++) {
2197     soc->do_ptr((void**)&_well_known_klasses[i]);
2198   }
2199 }
2200 
2201 const RunTimeSharedClassInfo*
find_record(RunTimeSharedDictionary * static_dict,RunTimeSharedDictionary * dynamic_dict,Symbol * name)2202 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
2203   if (!UseSharedSpaces || !name->is_shared()) {
2204     // The names of all shared classes must also be a shared Symbol.
2205     return NULL;
2206   }
2207 
2208   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary(name);
2209   const RunTimeSharedClassInfo* record = NULL;
2210   if (!MetaspaceShared::is_shared_dynamic(name)) {
2211     // The names of all shared classes in the static dict must also be in the
2212     // static archive
2213     record = static_dict->lookup(name, hash, 0);
2214   }
2215 
2216   if (record == NULL && DynamicArchive::is_mapped()) {
2217     record = dynamic_dict->lookup(name, hash, 0);
2218   }
2219 
2220   return record;
2221 }
2222 
find_builtin_class(Symbol * name)2223 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
2224   const RunTimeSharedClassInfo* record = find_record(&_builtin_dictionary, &_dynamic_builtin_dictionary, name);
2225   if (record != NULL) {
2226     assert(!record->_klass->is_hidden(), "hidden class cannot be looked up by name");
2227     assert(check_alignment(record->_klass), "Address not aligned");
2228     return record->_klass;
2229   } else {
2230     return NULL;
2231   }
2232 }
2233 
update_shared_entry(InstanceKlass * k,int id)2234 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
2235   assert(DumpSharedSpaces, "supported only when dumping");
2236   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
2237   info->_id = id;
2238 }
2239 
2240 class SharedDictionaryPrinter : StackObj {
2241   outputStream* _st;
2242   int _index;
2243 public:
SharedDictionaryPrinter(outputStream * st)2244   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
2245 
do_value(const RunTimeSharedClassInfo * record)2246   void do_value(const RunTimeSharedClassInfo* record) {
2247     ResourceMark rm;
2248     _st->print_cr("%4d:  %s", (_index++), record->_klass->external_name());
2249   }
2250 };
2251 
2252 class SharedLambdaDictionaryPrinter : StackObj {
2253   outputStream* _st;
2254   int _index;
2255 public:
SharedLambdaDictionaryPrinter(outputStream * st)2256   SharedLambdaDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
2257 
do_value(const RunTimeLambdaProxyClassInfo * record)2258   void do_value(const RunTimeLambdaProxyClassInfo* record) {
2259     ResourceMark rm;
2260     _st->print_cr("%4d:  %s", (_index++), record->proxy_klass_head()->external_name());
2261     Klass* k = record->proxy_klass_head()->next_link();
2262     while (k != NULL) {
2263       _st->print_cr("%4d:  %s", (_index++), k->external_name());
2264       k = k->next_link();
2265     }
2266   }
2267 };
2268 
print_on(const char * prefix,RunTimeSharedDictionary * builtin_dictionary,RunTimeSharedDictionary * unregistered_dictionary,LambdaProxyClassDictionary * lambda_dictionary,outputStream * st)2269 void SystemDictionaryShared::print_on(const char* prefix,
2270                                       RunTimeSharedDictionary* builtin_dictionary,
2271                                       RunTimeSharedDictionary* unregistered_dictionary,
2272                                       LambdaProxyClassDictionary* lambda_dictionary,
2273                                       outputStream* st) {
2274   st->print_cr("%sShared Dictionary", prefix);
2275   SharedDictionaryPrinter p(st);
2276   builtin_dictionary->iterate(&p);
2277   unregistered_dictionary->iterate(&p);
2278   if (!lambda_dictionary->empty()) {
2279     st->print_cr("%sShared Lambda Dictionary", prefix);
2280     SharedLambdaDictionaryPrinter ldp(st);
2281     lambda_dictionary->iterate(&ldp);
2282   }
2283 }
2284 
print_on(outputStream * st)2285 void SystemDictionaryShared::print_on(outputStream* st) {
2286   if (UseSharedSpaces) {
2287     print_on("", &_builtin_dictionary, &_unregistered_dictionary, &_lambda_proxy_class_dictionary, st);
2288     if (DynamicArchive::is_mapped()) {
2289       print_on("", &_dynamic_builtin_dictionary, &_dynamic_unregistered_dictionary,
2290                &_dynamic_lambda_proxy_class_dictionary, st);
2291     }
2292   }
2293 }
2294 
print_table_statistics(outputStream * st)2295 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
2296   if (UseSharedSpaces) {
2297     _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
2298     _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
2299     _lambda_proxy_class_dictionary.print_table_statistics(st, "Lambda Shared Dictionary");
2300     if (DynamicArchive::is_mapped()) {
2301       _dynamic_builtin_dictionary.print_table_statistics(st, "Dynamic Builtin Shared Dictionary");
2302       _dynamic_unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
2303       _dynamic_lambda_proxy_class_dictionary.print_table_statistics(st, "Dynamic Lambda Shared Dictionary");
2304     }
2305   }
2306 }
2307 
empty_dumptime_table()2308 bool SystemDictionaryShared::empty_dumptime_table() {
2309   if (_dumptime_table == NULL) {
2310     return true;
2311   }
2312   _dumptime_table->update_counts();
2313   if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
2314     return true;
2315   }
2316   return false;
2317 }
2318 
2319 #if INCLUDE_CDS_JAVA_HEAP
2320 
2321 class ArchivedMirrorPatcher {
2322 protected:
update(Klass * k)2323   static void update(Klass* k) {
2324     if (k->has_archived_mirror_index()) {
2325       oop m = k->archived_java_mirror();
2326       if (m != NULL) {
2327         java_lang_Class::update_archived_mirror_native_pointers(m);
2328       }
2329     }
2330   }
2331 
2332 public:
update_array_klasses(Klass * ak)2333   static void update_array_klasses(Klass* ak) {
2334     while (ak != NULL) {
2335       update(ak);
2336       ak = ArrayKlass::cast(ak)->higher_dimension();
2337     }
2338   }
2339 
do_value(const RunTimeSharedClassInfo * info)2340   void do_value(const RunTimeSharedClassInfo* info) {
2341     InstanceKlass* ik = info->_klass;
2342     update(ik);
2343     update_array_klasses(ik->array_klasses());
2344   }
2345 };
2346 
2347 class ArchivedLambdaMirrorPatcher : public ArchivedMirrorPatcher {
2348 public:
do_value(const RunTimeLambdaProxyClassInfo * info)2349   void do_value(const RunTimeLambdaProxyClassInfo* info) {
2350     InstanceKlass* ik = info->proxy_klass_head();
2351     while (ik != NULL) {
2352       update(ik);
2353       Klass* k = ik->next_link();
2354       ik = (k != NULL) ? InstanceKlass::cast(k) : NULL;
2355     }
2356   }
2357 };
2358 
update_archived_mirror_native_pointers_for(RunTimeSharedDictionary * dict)2359 void SystemDictionaryShared::update_archived_mirror_native_pointers_for(RunTimeSharedDictionary* dict) {
2360   ArchivedMirrorPatcher patcher;
2361   dict->iterate(&patcher);
2362 }
2363 
update_archived_mirror_native_pointers_for(LambdaProxyClassDictionary * dict)2364 void SystemDictionaryShared::update_archived_mirror_native_pointers_for(LambdaProxyClassDictionary* dict) {
2365   ArchivedLambdaMirrorPatcher patcher;
2366   dict->iterate(&patcher);
2367 }
2368 
update_archived_mirror_native_pointers()2369 void SystemDictionaryShared::update_archived_mirror_native_pointers() {
2370   if (!HeapShared::open_archive_heap_region_mapped()) {
2371     return;
2372   }
2373   if (MetaspaceShared::relocation_delta() == 0) {
2374     return;
2375   }
2376   update_archived_mirror_native_pointers_for(&_builtin_dictionary);
2377   update_archived_mirror_native_pointers_for(&_unregistered_dictionary);
2378   update_archived_mirror_native_pointers_for(&_lambda_proxy_class_dictionary);
2379 
2380   for (int t = T_BOOLEAN; t <= T_LONG; t++) {
2381     Klass* k = Universe::typeArrayKlassObj((BasicType)t);
2382     ArchivedMirrorPatcher::update_array_klasses(k);
2383   }
2384 }
2385 #endif
2386