jdk

Форк
0
/
systemDictionaryShared.cpp 
1491 строка · 58.1 Кб
1
/*
2
 * Copyright (c) 2014, 2024, 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 "cds/archiveBuilder.hpp"
27
#include "cds/archiveHeapLoader.hpp"
28
#include "cds/archiveUtils.hpp"
29
#include "cds/cdsConfig.hpp"
30
#include "cds/classListParser.hpp"
31
#include "cds/classListWriter.hpp"
32
#include "cds/dynamicArchive.hpp"
33
#include "cds/filemap.hpp"
34
#include "cds/cdsProtectionDomain.hpp"
35
#include "cds/dumpTimeClassInfo.inline.hpp"
36
#include "cds/metaspaceShared.hpp"
37
#include "cds/runTimeClassInfo.hpp"
38
#include "classfile/classFileStream.hpp"
39
#include "classfile/classLoader.hpp"
40
#include "classfile/classLoaderData.inline.hpp"
41
#include "classfile/classLoaderDataGraph.hpp"
42
#include "classfile/classLoaderExt.hpp"
43
#include "classfile/dictionary.hpp"
44
#include "classfile/javaClasses.hpp"
45
#include "classfile/javaClasses.inline.hpp"
46
#include "classfile/symbolTable.hpp"
47
#include "classfile/systemDictionary.hpp"
48
#include "classfile/systemDictionaryShared.hpp"
49
#include "classfile/verificationType.hpp"
50
#include "classfile/vmClasses.hpp"
51
#include "classfile/vmSymbols.hpp"
52
#include "interpreter/bootstrapInfo.hpp"
53
#include "jfr/jfrEvents.hpp"
54
#include "logging/log.hpp"
55
#include "logging/logStream.hpp"
56
#include "memory/allocation.hpp"
57
#include "memory/metadataFactory.hpp"
58
#include "memory/metaspaceClosure.hpp"
59
#include "memory/oopFactory.hpp"
60
#include "memory/resourceArea.hpp"
61
#include "memory/universe.hpp"
62
#include "oops/instanceKlass.hpp"
63
#include "oops/klass.inline.hpp"
64
#include "oops/objArrayKlass.hpp"
65
#include "oops/objArrayOop.inline.hpp"
66
#include "oops/oop.inline.hpp"
67
#include "oops/oopHandle.inline.hpp"
68
#include "oops/typeArrayOop.inline.hpp"
69
#include "runtime/arguments.hpp"
70
#include "runtime/handles.inline.hpp"
71
#include "runtime/java.hpp"
72
#include "runtime/javaCalls.hpp"
73
#include "runtime/mutexLocker.hpp"
74
#include "utilities/resourceHash.hpp"
75
#include "utilities/stringUtils.hpp"
76

77
SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_static_archive;
78
SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_dynamic_archive;
79

80
DumpTimeSharedClassTable* SystemDictionaryShared::_dumptime_table = nullptr;
81
DumpTimeLambdaProxyClassDictionary* SystemDictionaryShared::_dumptime_lambda_proxy_class_dictionary = nullptr;
82

83
// Used by NoClassLoadingMark
84
DEBUG_ONLY(bool SystemDictionaryShared::_class_loading_may_happen = true;)
85

86
InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
87
                 Symbol* class_name, Handle class_loader, TRAPS) {
88
  assert(CDSConfig::is_using_archive(), "must be");
89
  InstanceKlass* ik = find_builtin_class(class_name);
90

91
  if (ik != nullptr && !ik->shared_loading_failed()) {
92
    if ((SystemDictionary::is_system_class_loader(class_loader()) && ik->is_shared_app_class())  ||
93
        (SystemDictionary::is_platform_class_loader(class_loader()) && ik->is_shared_platform_class())) {
94
      SharedClassLoadingMark slm(THREAD, ik);
95
      PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
96
      Handle protection_domain =
97
        CDSProtectionDomain::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL);
98
      return load_shared_class(ik, class_loader, protection_domain, nullptr, pkg_entry, THREAD);
99
    }
100
  }
101
  return nullptr;
102
}
103

104
// This function is called for loading only UNREGISTERED classes
105
InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
106
                                                          Handle class_loader,
107
                                                          Handle protection_domain,
108
                                                          const ClassFileStream* cfs,
109
                                                          TRAPS) {
110
  if (!CDSConfig::is_using_archive()) {
111
    return nullptr;
112
  }
113
  if (class_name == nullptr) {  // don't do this for hidden classes
114
    return nullptr;
115
  }
116
  if (class_loader.is_null() ||
117
      SystemDictionary::is_system_class_loader(class_loader()) ||
118
      SystemDictionary::is_platform_class_loader(class_loader())) {
119
    // Do nothing for the BUILTIN loaders.
120
    return nullptr;
121
  }
122

123
  const RunTimeClassInfo* record = find_record(&_static_archive._unregistered_dictionary,
124
                                               &_dynamic_archive._unregistered_dictionary,
125
                                               class_name);
126
  if (record == nullptr) {
127
    return nullptr;
128
  }
129

130
  int clsfile_size  = cfs->length();
131
  int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
132

133
  if (!record->matches(clsfile_size, clsfile_crc32)) {
134
    return nullptr;
135
  }
136

137
  return acquire_class_for_current_thread(record->_klass, class_loader,
138
                                          protection_domain, cfs,
139
                                          THREAD);
140
}
141

142
InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
143
                   InstanceKlass *ik,
144
                   Handle class_loader,
145
                   Handle protection_domain,
146
                   const ClassFileStream *cfs,
147
                   TRAPS) {
148
  ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
149

150
  {
151
    MutexLocker mu(THREAD, SharedDictionary_lock);
152
    if (ik->class_loader_data() != nullptr) {
153
      //    ik is already loaded (by this loader or by a different loader)
154
      // or ik is being loaded by a different thread (by this loader or by a different loader)
155
      return nullptr;
156
    }
157

158
    // No other thread has acquired this yet, so give it to *this thread*
159
    ik->set_class_loader_data(loader_data);
160
  }
161

162
  // No longer holding SharedDictionary_lock
163
  // No need to lock, as <ik> can be held only by a single thread.
164
  loader_data->add_class(ik);
165

166
  // Get the package entry.
167
  PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
168

169
  // Load and check super/interfaces, restore unshareable info
170
  InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
171
                                                  cfs, pkg_entry, THREAD);
172
  if (shared_klass == nullptr || HAS_PENDING_EXCEPTION) {
173
    // TODO: clean up <ik> so it can be used again
174
    return nullptr;
175
  }
176

177
  return shared_klass;
178
}
179

180
// Guaranteed to return non-null value for non-shared classes.
181
// k must not be a shared class.
182
DumpTimeClassInfo* SystemDictionaryShared::get_info(InstanceKlass* k) {
183
  MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
184
  assert(!k->is_shared(), "sanity");
185
  return get_info_locked(k);
186
}
187

188
DumpTimeClassInfo* SystemDictionaryShared::get_info_locked(InstanceKlass* k) {
189
  assert_lock_strong(DumpTimeTable_lock);
190
  assert(!k->is_shared(), "sanity");
191
  DumpTimeClassInfo* info = _dumptime_table->get_info(k);
192
  assert(info != nullptr, "must be");
193
  return info;
194
}
195

196
bool SystemDictionaryShared::check_for_exclusion(InstanceKlass* k, DumpTimeClassInfo* info) {
197
  if (MetaspaceShared::is_in_shared_metaspace(k)) {
198
    // We have reached a super type that's already in the base archive. Treat it
199
    // as "not excluded".
200
    assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
201
    return false;
202
  }
203

204
  if (info == nullptr) {
205
    info = _dumptime_table->get(k);
206
    assert(info != nullptr, "supertypes of any classes in _dumptime_table must either be shared, or must also be in _dumptime_table");
207
  }
208

209
  if (!info->has_checked_exclusion()) {
210
    if (check_for_exclusion_impl(k)) {
211
      info->set_excluded();
212
    }
213
    info->set_has_checked_exclusion();
214
  }
215

216
  return info->is_excluded();
217
}
218

219
// Returns true so the caller can do:    return warn_excluded(".....");
220
bool SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) {
221
  ResourceMark rm;
222
  log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason);
223
  return true;
224
}
225

226
bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
227
  while (k) {
228
    if (k->name()->equals("jdk/internal/event/Event")) {
229
      return true;
230
    }
231
    k = k->java_super();
232
  }
233
  return false;
234
}
235

236
bool SystemDictionaryShared::is_registered_lambda_proxy_class(InstanceKlass* ik) {
237
  DumpTimeClassInfo* info = _dumptime_table->get(ik);
238
  return (info != nullptr) ? info->_is_archived_lambda_proxy : false;
239
}
240

241
void SystemDictionaryShared::reset_registered_lambda_proxy_class(InstanceKlass* ik) {
242
  DumpTimeClassInfo* info = _dumptime_table->get(ik);
243
  if (info != nullptr) {
244
    info->_is_archived_lambda_proxy = false;
245
    info->set_excluded();
246
  }
247
}
248

249
bool SystemDictionaryShared::is_early_klass(InstanceKlass* ik) {
250
  DumpTimeClassInfo* info = _dumptime_table->get(ik);
251
  return (info != nullptr) ? info->is_early_klass() : false;
252
}
253

254
bool SystemDictionaryShared::is_hidden_lambda_proxy(InstanceKlass* ik) {
255
  assert(ik->is_shared(), "applicable to only a shared class");
256
  if (ik->is_hidden()) {
257
    return true;
258
  } else {
259
    return false;
260
  }
261
}
262

263
bool SystemDictionaryShared::check_for_exclusion_impl(InstanceKlass* k) {
264
  if (k->is_in_error_state()) {
265
    return warn_excluded(k, "In error state");
266
  }
267
  if (k->is_scratch_class()) {
268
    return warn_excluded(k, "A scratch class");
269
  }
270
  if (!k->is_loaded()) {
271
    return warn_excluded(k, "Not in loaded state");
272
  }
273
  if (has_been_redefined(k)) {
274
    return warn_excluded(k, "Has been redefined");
275
  }
276
  if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) {
277
    // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
278
    // agent during dump time).
279
    return warn_excluded(k, "Unsupported location");
280
  }
281
  if (k->signers() != nullptr) {
282
    // We cannot include signed classes in the archive because the certificates
283
    // used during dump time may be different than those used during
284
    // runtime (due to expiration, etc).
285
    return warn_excluded(k, "Signed JAR");
286
  }
287
  if (is_jfr_event_class(k)) {
288
    // We cannot include JFR event classes because they need runtime-specific
289
    // instrumentation in order to work with -XX:FlightRecorderOptions:retransform=false.
290
    // There are only a small number of these classes, so it's not worthwhile to
291
    // support them and make CDS more complicated.
292
    return warn_excluded(k, "JFR event class");
293
  }
294

295
  if (!k->is_linked()) {
296
    if (has_class_failed_verification(k)) {
297
      return warn_excluded(k, "Failed verification");
298
    }
299
  } else {
300
    if (!k->can_be_verified_at_dumptime()) {
301
      // We have an old class that has been linked (e.g., it's been executed during
302
      // dump time). This class has been verified using the old verifier, which
303
      // doesn't save the verification constraints, so check_verification_constraints()
304
      // won't work at runtime.
305
      // As a result, we cannot store this class. It must be loaded and fully verified
306
      // at runtime.
307
      return warn_excluded(k, "Old class has been linked");
308
    }
309
  }
310

311
  if (k->is_hidden() && !is_registered_lambda_proxy_class(k)) {
312
    ResourceMark rm;
313
    log_debug(cds)("Skipping %s: Hidden class", k->name()->as_C_string());
314
    return true;
315
  }
316

317
  InstanceKlass* super = k->java_super();
318
  if (super != nullptr && check_for_exclusion(super, nullptr)) {
319
    ResourceMark rm;
320
    log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
321
    return true;
322
  }
323

324
  Array<InstanceKlass*>* interfaces = k->local_interfaces();
325
  int len = interfaces->length();
326
  for (int i = 0; i < len; i++) {
327
    InstanceKlass* intf = interfaces->at(i);
328
    if (check_for_exclusion(intf, nullptr)) {
329
      ResourceMark rm;
330
      log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
331
      return true;
332
    }
333
  }
334

335
  return false; // false == k should NOT be excluded
336
}
337

338
bool SystemDictionaryShared::is_builtin_loader(ClassLoaderData* loader_data) {
339
  oop class_loader = loader_data->class_loader();
340
  return (class_loader == nullptr ||
341
          SystemDictionary::is_system_class_loader(class_loader) ||
342
          SystemDictionary::is_platform_class_loader(class_loader));
343
}
344

345
bool SystemDictionaryShared::has_platform_or_app_classes() {
346
  if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
347
    return true;
348
  }
349
  if (DynamicArchive::is_mapped() &&
350
      FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
351
    return true;
352
  }
353
  return false;
354
}
355

356
// The following stack shows how this code is reached:
357
//
358
//   [0] SystemDictionaryShared::find_or_load_shared_class()
359
//   [1] JVM_FindLoadedClass
360
//   [2] java.lang.ClassLoader.findLoadedClass0()
361
//   [3] java.lang.ClassLoader.findLoadedClass()
362
//   [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
363
//   [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
364
//   [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
365
//       jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
366
//
367
// AppCDS supports fast class loading for these 2 built-in class loaders:
368
//    jdk.internal.loader.ClassLoaders$PlatformClassLoader
369
//    jdk.internal.loader.ClassLoaders$AppClassLoader
370
// with the following assumptions (based on the JDK core library source code):
371
//
372
// [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
373
//     load the named class.
374
// [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
375
// [c] At this point, if we can find the named class inside the
376
//     shared_dictionary, we can perform further checks (see
377
//     SystemDictionary::is_shared_class_visible) to ensure that this class
378
//     was loaded by the same class loader during dump time.
379
//
380
// Given these assumptions, we intercept the findLoadedClass() call to invoke
381
// SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
382
// the archive for the 2 built-in class loaders. This way,
383
// we can improve start-up because we avoid decoding the classfile,
384
// and avoid delegating to the parent loader.
385
//
386
// NOTE: there's a lot of assumption about the Java code. If any of that change, this
387
// needs to be redesigned.
388

389
InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
390
                 Symbol* name, Handle class_loader, TRAPS) {
391
  InstanceKlass* k = nullptr;
392
  if (CDSConfig::is_using_archive()) {
393
    if (!has_platform_or_app_classes()) {
394
      return nullptr;
395
    }
396

397
    if (SystemDictionary::is_system_class_loader(class_loader()) ||
398
        SystemDictionary::is_platform_class_loader(class_loader())) {
399
      // Fix for 4474172; see evaluation for more details
400
      class_loader = Handle(
401
        THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
402
      ClassLoaderData *loader_data = register_loader(class_loader);
403
      Dictionary* dictionary = loader_data->dictionary();
404

405
      // Note: currently, find_or_load_shared_class is called only from
406
      // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
407
      // which are parallel-capable loaders, so a lock here is NOT taken.
408
      assert(get_loader_lock_or_null(class_loader) == nullptr, "ObjectLocker not required");
409
      {
410
        MutexLocker mu(THREAD, SystemDictionary_lock);
411
        InstanceKlass* check = dictionary->find_class(THREAD, name);
412
        if (check != nullptr) {
413
          return check;
414
        }
415
      }
416

417
      k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
418
      if (k != nullptr) {
419
        SharedClassLoadingMark slm(THREAD, k);
420
        k = find_or_define_instance_class(name, class_loader, k, CHECK_NULL);
421
      }
422
    }
423
  }
424
  return k;
425
}
426

427
class UnregisteredClassesTable : public ResourceHashtable<
428
  Symbol*, InstanceKlass*,
429
  15889, // prime number
430
  AnyObj::C_HEAP> {};
431

432
static UnregisteredClassesTable* _unregistered_classes_table = nullptr;
433

434
// true == class was successfully added; false == a duplicated class (with the same name) already exists.
435
bool SystemDictionaryShared::add_unregistered_class(Thread* current, InstanceKlass* klass) {
436
  // We don't allow duplicated unregistered classes with the same name.
437
  // We only archive the first class with that name that succeeds putting
438
  // itself into the table.
439
  assert(CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity");
440
  MutexLocker ml(current, UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
441
  Symbol* name = klass->name();
442
  if (_unregistered_classes_table == nullptr) {
443
    _unregistered_classes_table = new (mtClass)UnregisteredClassesTable();
444
  }
445
  bool created;
446
  InstanceKlass** v = _unregistered_classes_table->put_if_absent(name, klass, &created);
447
  if (created) {
448
    name->increment_refcount();
449
  }
450
  return (klass == *v);
451
}
452

453
// This function is called to lookup the super/interfaces of shared classes for
454
// unregistered loaders. E.g., SharedClass in the below example
455
// where "super:" (and optionally "interface:") have been specified.
456
//
457
// java/lang/Object id: 0
458
// Interface    id: 2 super: 0 source: cust.jar
459
// SharedClass  id: 4 super: 0 interfaces: 2 source: cust.jar
460
InstanceKlass* SystemDictionaryShared::lookup_super_for_unregistered_class(
461
    Symbol* class_name, Symbol* super_name, bool is_superclass) {
462

463
  assert(CDSConfig::is_dumping_static_archive(), "only when static dumping");
464

465
  if (!ClassListParser::is_parsing_thread()) {
466
    // Unregistered classes can be created only by ClassListParser::_parsing_thread.
467

468
    return nullptr;
469
  }
470

471
  ClassListParser* parser = ClassListParser::instance();
472
  if (parser == nullptr) {
473
    // We're still loading the well-known classes, before the ClassListParser is created.
474
    return nullptr;
475
  }
476
  if (class_name->equals(parser->current_class_name())) {
477
    // When this function is called, all the numbered super and interface types
478
    // must have already been loaded. Hence this function is never recursively called.
479
    if (is_superclass) {
480
      return parser->lookup_super_for_current_class(super_name);
481
    } else {
482
      return parser->lookup_interface_for_current_class(super_name);
483
    }
484
  } else {
485
    // The VM is not trying to resolve a super type of parser->current_class_name().
486
    // Instead, it's resolving an error class (because parser->current_class_name() has
487
    // failed parsing or verification). Don't do anything here.
488
    return nullptr;
489
  }
490
}
491

492
void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
493
  assert(CDSConfig::is_dumping_archive(), "sanity");
494
  assert(!is_builtin(k), "must be unregistered class");
495
  DumpTimeClassInfo* info = get_info(k);
496
  info->_clsfile_size  = cfs->length();
497
  info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
498
}
499

500
void SystemDictionaryShared::initialize() {
501
  if (CDSConfig::is_dumping_archive()) {
502
    _dumptime_table = new (mtClass) DumpTimeSharedClassTable;
503
    _dumptime_lambda_proxy_class_dictionary =
504
                      new (mtClass) DumpTimeLambdaProxyClassDictionary;
505
  }
506
}
507

508
void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
509
  MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
510
  assert(SystemDictionaryShared::class_loading_may_happen(), "sanity");
511
  _dumptime_table->allocate_info(k);
512
}
513

514
void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
515
  MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
516
  _dumptime_table->remove(k);
517
}
518

519
void SystemDictionaryShared::handle_class_unloading(InstanceKlass* klass) {
520
  if (CDSConfig::is_dumping_archive()) {
521
    remove_dumptime_info(klass);
522
  }
523

524
  if (CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled()) {
525
    MutexLocker ml(Thread::current(), UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag);
526
    if (_unregistered_classes_table != nullptr) {
527
      // Remove the class from _unregistered_classes_table: keep the entry but
528
      // set it to null. This ensure no classes with the same name can be
529
      // added again.
530
      InstanceKlass** v = _unregistered_classes_table->get(klass->name());
531
      if (v != nullptr) {
532
        *v = nullptr;
533
      }
534
    }
535
  } else {
536
    assert(_unregistered_classes_table == nullptr, "must not be used");
537
  }
538

539
  if (ClassListWriter::is_enabled()) {
540
    ClassListWriter cw;
541
    cw.handle_class_unloading((const InstanceKlass*)klass);
542
  }
543
}
544

545
// Check if a class or any of its supertypes has been redefined.
546
bool SystemDictionaryShared::has_been_redefined(InstanceKlass* k) {
547
  if (k->has_been_redefined()) {
548
    return true;
549
  }
550
  if (k->java_super() != nullptr && has_been_redefined(k->java_super())) {
551
    return true;
552
  }
553
  Array<InstanceKlass*>* interfaces = k->local_interfaces();
554
  int len = interfaces->length();
555
  for (int i = 0; i < len; i++) {
556
    if (has_been_redefined(interfaces->at(i))) {
557
      return true;
558
    }
559
  }
560
  return false;
561
}
562

563
// k is a class before relocating by ArchiveBuilder
564
void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
565
  ResourceMark rm;
566
  const char* name = k->name()->as_C_string();
567
  DumpTimeClassInfo* info = _dumptime_table->get(k);
568
  assert(!class_loading_may_happen(), "class loading must be disabled");
569
  guarantee(info != nullptr, "Class %s must be entered into _dumptime_table", name);
570
  guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
571
  if (is_builtin(k)) {
572
    if (k->is_hidden()) {
573
      assert(is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name);
574
    }
575
    guarantee(!k->is_shared_unregistered_class(),
576
              "Class loader type must be set for BUILTIN class %s", name);
577

578
  } else {
579
    guarantee(k->is_shared_unregistered_class(),
580
              "Class loader type must not be set for UNREGISTERED class %s", name);
581
  }
582
}
583

584
class UnregisteredClassesDuplicationChecker : StackObj {
585
  GrowableArray<InstanceKlass*> _list;
586
  Thread* _thread;
587
public:
588
  UnregisteredClassesDuplicationChecker() : _thread(Thread::current()) {}
589

590
  void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
591
    if (!SystemDictionaryShared::is_builtin(k)) {
592
      _list.append(k);
593
    }
594
  }
595

596
  static int compare_by_loader(InstanceKlass** a, InstanceKlass** b) {
597
    ClassLoaderData* loader_a = a[0]->class_loader_data();
598
    ClassLoaderData* loader_b = b[0]->class_loader_data();
599

600
    if (loader_a != loader_b) {
601
      return primitive_compare(loader_a, loader_b);
602
    } else {
603
      return primitive_compare(a[0], b[0]);
604
    }
605
  }
606

607
  void mark_duplicated_classes() {
608
    // Two loaders may load two identical or similar hierarchies of classes. If we
609
    // check for duplication in random order, we may end up excluding important base classes
610
    // in both hierarchies, causing most of the classes to be excluded.
611
    // We sort the classes by their loaders. This way we're likely to archive
612
    // all classes in the one of the two hierarchies.
613
    _list.sort(compare_by_loader);
614
    for (int i = 0; i < _list.length(); i++) {
615
      InstanceKlass* k = _list.at(i);
616
      bool i_am_first = SystemDictionaryShared::add_unregistered_class(_thread, k);
617
      if (!i_am_first) {
618
        SystemDictionaryShared::warn_excluded(k, "Duplicated unregistered class");
619
        SystemDictionaryShared::set_excluded_locked(k);
620
      }
621
    }
622
  }
623
};
624

625
void SystemDictionaryShared::check_excluded_classes() {
626
  assert(!class_loading_may_happen(), "class loading must be disabled");
627
  assert_lock_strong(DumpTimeTable_lock);
628

629
  if (CDSConfig::is_dumping_dynamic_archive()) {
630
    // Do this first -- if a base class is excluded due to duplication,
631
    // all of its subclasses will also be excluded.
632
    ResourceMark rm;
633
    UnregisteredClassesDuplicationChecker dup_checker;
634
    _dumptime_table->iterate_all_live_classes(&dup_checker);
635
    dup_checker.mark_duplicated_classes();
636
  }
637

638
  auto check_for_exclusion = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
639
    SystemDictionaryShared::check_for_exclusion(k, &info);
640
  };
641
  _dumptime_table->iterate_all_live_classes(check_for_exclusion);
642
  _dumptime_table->update_counts();
643

644
  cleanup_lambda_proxy_class_dictionary();
645
}
646

647
bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
648
  assert(!class_loading_may_happen(), "class loading must be disabled");
649
  assert_lock_strong(DumpTimeTable_lock);
650
  assert(CDSConfig::is_dumping_archive(), "sanity");
651
  DumpTimeClassInfo* p = get_info_locked(k);
652
  return p->is_excluded();
653
}
654

655
void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) {
656
  assert_lock_strong(DumpTimeTable_lock);
657
  assert(CDSConfig::is_dumping_archive(), "sanity");
658
  DumpTimeClassInfo* info = get_info_locked(k);
659
  info->set_excluded();
660
}
661

662
void SystemDictionaryShared::set_excluded(InstanceKlass* k) {
663
  assert(CDSConfig::is_dumping_archive(), "sanity");
664
  DumpTimeClassInfo* info = get_info(k);
665
  info->set_excluded();
666
}
667

668
void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
669
  assert(CDSConfig::is_dumping_archive(), "sanity");
670
  DumpTimeClassInfo* p = get_info(ik);
671
  p->set_failed_verification();
672
}
673

674
bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
675
  assert(CDSConfig::is_dumping_archive(), "sanity");
676
  DumpTimeClassInfo* p = _dumptime_table->get(ik);
677
  return (p == nullptr) ? false : p->failed_verification();
678
}
679

680
void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) {
681
  assert_lock_strong(DumpTimeTable_lock);
682

683
  auto do_klass = [&] (InstanceKlass* k, DumpTimeClassInfo& info) {
684
    if (k->is_loader_alive() && !info.is_excluded()) {
685
      info.metaspace_pointers_do(it);
686
    }
687
  };
688
  _dumptime_table->iterate_all_live_classes(do_klass);
689

690
  auto do_lambda = [&] (LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
691
    if (key.caller_ik()->is_loader_alive()) {
692
      info.metaspace_pointers_do(it);
693
      key.metaspace_pointers_do(it);
694
    }
695
  };
696
  _dumptime_lambda_proxy_class_dictionary->iterate_all(do_lambda);
697
}
698

699
bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
700
         Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
701
  assert(CDSConfig::is_dumping_archive(), "sanity");
702
  DumpTimeClassInfo* info = get_info(k);
703
  info->add_verification_constraint(k, name, from_name, from_field_is_protected,
704
                                    from_is_array, from_is_object);
705

706
  if (CDSConfig::is_dumping_dynamic_archive()) {
707
    // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
708
    // the initial run prior to creating the archive before vm exit. We will also perform verification
709
    // check when running with the archive.
710
    return false;
711
  } else {
712
    if (is_builtin(k)) {
713
      // For builtin class loaders, we can try to complete the verification check at dump time,
714
      // because we can resolve all the constraint classes. We will also perform verification check
715
      // when running with the archive.
716
      return false;
717
    } else {
718
      // For non-builtin class loaders, we cannot complete the verification check at dump time,
719
      // because at dump time we don't know how to resolve classes for such loaders.
720
      return true;
721
    }
722
  }
723
}
724

725
void SystemDictionaryShared::add_enum_klass_static_field(InstanceKlass* ik, int root_index) {
726
  assert(CDSConfig::is_dumping_heap(), "sanity");
727
  DumpTimeClassInfo* info = get_info_locked(ik);
728
  info->add_enum_klass_static_field(root_index);
729
}
730

731
void SystemDictionaryShared::add_to_dump_time_lambda_proxy_class_dictionary(LambdaProxyClassKey& key,
732
                                                           InstanceKlass* proxy_klass) {
733
  assert_lock_strong(DumpTimeTable_lock);
734

735
  bool created;
736
  DumpTimeLambdaProxyClassInfo* info = _dumptime_lambda_proxy_class_dictionary->put_if_absent(key, &created);
737
  info->add_proxy_klass(proxy_klass);
738
  if (created) {
739
    ++_dumptime_lambda_proxy_class_dictionary->_count;
740
  }
741
}
742

743
void SystemDictionaryShared::add_lambda_proxy_class(InstanceKlass* caller_ik,
744
                                                    InstanceKlass* lambda_ik,
745
                                                    Symbol* invoked_name,
746
                                                    Symbol* invoked_type,
747
                                                    Symbol* method_type,
748
                                                    Method* member_method,
749
                                                    Symbol* instantiated_method_type,
750
                                                    TRAPS) {
751

752
  assert(caller_ik->class_loader() == lambda_ik->class_loader(), "mismatched class loader");
753
  assert(caller_ik->class_loader_data() == lambda_ik->class_loader_data(), "mismatched class loader data");
754
  assert(java_lang_Class::class_data(lambda_ik->java_mirror()) == nullptr, "must not have class data");
755

756
  MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
757

758
  lambda_ik->assign_class_loader_type();
759
  lambda_ik->set_shared_classpath_index(caller_ik->shared_classpath_index());
760
  InstanceKlass* nest_host = caller_ik->nest_host(CHECK);
761
  assert(nest_host != nullptr, "unexpected nullptr nest_host");
762

763
  DumpTimeClassInfo* info = _dumptime_table->get(lambda_ik);
764
  if (info != nullptr && !lambda_ik->is_non_strong_hidden() && is_builtin(lambda_ik) && is_builtin(caller_ik)
765
      // Don't include the lambda proxy if its nest host is not in the "linked" state.
766
      && nest_host->is_linked()) {
767
    // Set _is_archived_lambda_proxy in DumpTimeClassInfo so that the lambda_ik
768
    // won't be excluded during dumping of shared archive. See ExcludeDumpTimeSharedClasses.
769
    info->_is_archived_lambda_proxy = true;
770
    info->set_nest_host(nest_host);
771

772
    LambdaProxyClassKey key(caller_ik,
773
                            invoked_name,
774
                            invoked_type,
775
                            method_type,
776
                            member_method,
777
                            instantiated_method_type);
778
    add_to_dump_time_lambda_proxy_class_dictionary(key, lambda_ik);
779
  }
780
}
781

782
InstanceKlass* SystemDictionaryShared::get_shared_lambda_proxy_class(InstanceKlass* caller_ik,
783
                                                                     Symbol* invoked_name,
784
                                                                     Symbol* invoked_type,
785
                                                                     Symbol* method_type,
786
                                                                     Method* member_method,
787
                                                                     Symbol* instantiated_method_type) {
788
  MutexLocker ml(CDSLambda_lock, Mutex::_no_safepoint_check_flag);
789
  LambdaProxyClassKey key(caller_ik, invoked_name, invoked_type,
790
                          method_type, member_method, instantiated_method_type);
791

792
  // Try to retrieve the lambda proxy class from static archive.
793
  const RunTimeLambdaProxyClassInfo* info = _static_archive.lookup_lambda_proxy_class(&key);
794
  InstanceKlass* proxy_klass = retrieve_lambda_proxy_class(info);
795
  if (proxy_klass == nullptr) {
796
    if (info != nullptr && log_is_enabled(Debug, cds)) {
797
      ResourceMark rm;
798
      log_debug(cds)("Used all static archived lambda proxy classes for: %s %s%s",
799
                     caller_ik->external_name(), invoked_name->as_C_string(), invoked_type->as_C_string());
800
    }
801
  } else {
802
    return proxy_klass;
803
  }
804

805
  // Retrieving from static archive is unsuccessful, try dynamic archive.
806
  info = _dynamic_archive.lookup_lambda_proxy_class(&key);
807
  proxy_klass = retrieve_lambda_proxy_class(info);
808
  if (proxy_klass == nullptr) {
809
    if (info != nullptr && log_is_enabled(Debug, cds)) {
810
      ResourceMark rm;
811
      log_debug(cds)("Used all dynamic archived lambda proxy classes for: %s %s%s",
812
                     caller_ik->external_name(), invoked_name->as_C_string(), invoked_type->as_C_string());
813
    }
814
  }
815
  return proxy_klass;
816
}
817

818
InstanceKlass* SystemDictionaryShared::retrieve_lambda_proxy_class(const RunTimeLambdaProxyClassInfo* info) {
819
  InstanceKlass* proxy_klass = nullptr;
820
  if (info != nullptr) {
821
    InstanceKlass* curr_klass = info->proxy_klass_head();
822
    InstanceKlass* prev_klass = curr_klass;
823
    if (curr_klass->lambda_proxy_is_available()) {
824
      while (curr_klass->next_link() != nullptr) {
825
        prev_klass = curr_klass;
826
        curr_klass = InstanceKlass::cast(curr_klass->next_link());
827
      }
828
      assert(curr_klass->is_hidden(), "must be");
829
      assert(curr_klass->lambda_proxy_is_available(), "must be");
830

831
      prev_klass->set_next_link(nullptr);
832
      proxy_klass = curr_klass;
833
      proxy_klass->clear_lambda_proxy_is_available();
834
      if (log_is_enabled(Debug, cds)) {
835
        ResourceMark rm;
836
        log_debug(cds)("Loaded lambda proxy: %s ", proxy_klass->external_name());
837
      }
838
    }
839
  }
840
  return proxy_klass;
841
}
842

843
InstanceKlass* SystemDictionaryShared::get_shared_nest_host(InstanceKlass* lambda_ik) {
844
  assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
845
  RunTimeClassInfo* record = RunTimeClassInfo::get_for(lambda_ik);
846
  return record->nest_host();
847
}
848

849
InstanceKlass* SystemDictionaryShared::prepare_shared_lambda_proxy_class(InstanceKlass* lambda_ik,
850
                                                                         InstanceKlass* caller_ik, TRAPS) {
851
  Handle class_loader(THREAD, caller_ik->class_loader());
852
  Handle protection_domain;
853
  PackageEntry* pkg_entry = caller_ik->package();
854
  if (caller_ik->class_loader() != nullptr) {
855
    protection_domain = CDSProtectionDomain::init_security_info(class_loader, caller_ik, pkg_entry, CHECK_NULL);
856
  }
857

858
  InstanceKlass* shared_nest_host = get_shared_nest_host(lambda_ik);
859
  assert(shared_nest_host != nullptr, "unexpected nullptr _nest_host");
860

861
  InstanceKlass* loaded_lambda =
862
    SystemDictionary::load_shared_lambda_proxy_class(lambda_ik, class_loader, protection_domain, pkg_entry, CHECK_NULL);
863

864
  if (loaded_lambda == nullptr) {
865
    return nullptr;
866
  }
867

868
  // Ensures the nest host is the same as the lambda proxy's
869
  // nest host recorded at dump time.
870
  InstanceKlass* nest_host = caller_ik->nest_host(THREAD);
871
  assert(nest_host == shared_nest_host, "mismatched nest host");
872

873
  EventClassLoad class_load_start_event;
874

875
  // Add to class hierarchy, and do possible deoptimizations.
876
  loaded_lambda->add_to_hierarchy(THREAD);
877
  // But, do not add to dictionary.
878

879
  loaded_lambda->link_class(CHECK_NULL);
880
  // notify jvmti
881
  if (JvmtiExport::should_post_class_load()) {
882
    JvmtiExport::post_class_load(THREAD, loaded_lambda);
883
  }
884
  if (class_load_start_event.should_commit()) {
885
    SystemDictionary::post_class_load_event(&class_load_start_event, loaded_lambda, ClassLoaderData::class_loader_data(class_loader()));
886
  }
887

888
  loaded_lambda->initialize(CHECK_NULL);
889

890
  return loaded_lambda;
891
}
892

893
void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
894
                                                            TRAPS) {
895
  assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
896
  RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass);
897

898
  int length = record->_num_verifier_constraints;
899
  if (length > 0) {
900
    for (int i = 0; i < length; i++) {
901
      RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
902
      Symbol* name      = vc->name();
903
      Symbol* from_name = vc->from_name();
904
      char c            = record->verifier_constraint_flag(i);
905

906
      if (log_is_enabled(Trace, cds, verification)) {
907
        ResourceMark rm(THREAD);
908
        log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
909
                                     klass->external_name(), from_name->as_klass_external_name(),
910
                                     name->as_klass_external_name(), c);
911
      }
912

913
      bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false;
914
      bool from_is_array           = (c & SystemDictionaryShared::FROM_IS_ARRAY)           ? true : false;
915
      bool from_is_object          = (c & SystemDictionaryShared::FROM_IS_OBJECT)          ? true : false;
916

917
      bool ok = VerificationType::resolve_and_check_assignability(klass, name,
918
         from_name, from_field_is_protected, from_is_array, from_is_object, CHECK);
919
      if (!ok) {
920
        ResourceMark rm(THREAD);
921
        stringStream ss;
922

923
        ss.print_cr("Bad type on operand stack");
924
        ss.print_cr("Exception Details:");
925
        ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
926
        ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
927
                    from_name->as_quoted_ascii(), name->as_quoted_ascii());
928
        THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
929
      }
930
    }
931
  }
932
}
933

934
static oop get_class_loader_by(char type) {
935
  if (type == (char)ClassLoader::BOOT_LOADER) {
936
    return (oop)nullptr;
937
  } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
938
    return SystemDictionary::java_platform_loader();
939
  } else {
940
    assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
941
    return SystemDictionary::java_system_loader();
942
  }
943
}
944

945
// Record class loader constraints that are checked inside
946
// InstanceKlass::link_class(), so that these can be checked quickly
947
// at runtime without laying out the vtable/itables.
948
void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
949
                                                    Handle loader1, Handle loader2) {
950
  // A linking constraint check is executed when:
951
  //   - klass extends or implements type S
952
  //   - klass overrides method S.M(...) with X.M
953
  //     - If klass defines the method M, X is
954
  //       the same as klass.
955
  //     - If klass does not define the method M,
956
  //       X must be a supertype of klass and X.M is
957
  //       a default method defined by X.
958
  //   - loader1 = X->class_loader()
959
  //   - loader2 = S->class_loader()
960
  //   - loader1 != loader2
961
  //   - M's parameter(s) include an object type T
962
  // We require that
963
  //   - whenever loader1 and loader2 try to
964
  //     resolve the type T, they must always resolve to
965
  //     the same InstanceKlass.
966
  // NOTE: type T may or may not be currently resolved in
967
  // either of these two loaders. The check itself does not
968
  // try to resolve T.
969
  oop klass_loader = klass->class_loader();
970

971
  if (!is_system_class_loader(klass_loader) &&
972
      !is_platform_class_loader(klass_loader)) {
973
    // If klass is loaded by system/platform loaders, we can
974
    // guarantee that klass and S must be loaded by the same
975
    // respective loader between dump time and run time, and
976
    // the exact same check on (name, loader1, loader2) will
977
    // be executed. Hence, we can cache this check and execute
978
    // it at runtime without walking the vtable/itables.
979
    //
980
    // This cannot be guaranteed for classes loaded by other
981
    // loaders, so we bail.
982
    return;
983
  }
984

985
  assert(is_builtin(klass), "must be");
986
  assert(klass_loader != nullptr, "should not be called for boot loader");
987
  assert(loader1 != loader2, "must be");
988

989
  if (CDSConfig::is_dumping_dynamic_archive() && Thread::current()->is_VM_thread()) {
990
    // We are re-laying out the vtable/itables of the *copy* of
991
    // a class during the final stage of dynamic dumping. The
992
    // linking constraints for this class has already been recorded.
993
    return;
994
  }
995
  assert(!Thread::current()->is_VM_thread(), "must be");
996

997
  assert(CDSConfig::is_dumping_archive(), "sanity");
998
  DumpTimeClassInfo* info = get_info(klass);
999
  info->record_linking_constraint(name, loader1, loader2);
1000
}
1001

1002
// returns true IFF there's no need to re-initialize the i/v-tables for klass for
1003
// the purpose of checking class loader constraints.
1004
bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) {
1005
  assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only");
1006
  LogTarget(Info, class, loader, constraints) log;
1007
  if (klass->is_shared_boot_class()) {
1008
    // No class loader constraint check performed for boot classes.
1009
    return true;
1010
  }
1011
  if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
1012
    RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass);
1013
    assert(info != nullptr, "Sanity");
1014
    if (info->_num_loader_constraints > 0) {
1015
      HandleMark hm(current);
1016
      for (int i = 0; i < info->_num_loader_constraints; i++) {
1017
        RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1018
        Symbol* name = lc->constraint_name();
1019
        Handle loader1(current, get_class_loader_by(lc->_loader_type1));
1020
        Handle loader2(current, get_class_loader_by(lc->_loader_type2));
1021
        if (log.is_enabled()) {
1022
          ResourceMark rm(current);
1023
          log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1024
                    klass->external_name(), name->as_C_string(),
1025
                    ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1026
                    ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1027
        }
1028
        if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2)) {
1029
          // Loader constraint violation has been found. The caller
1030
          // will re-layout the vtable/itables to produce the correct
1031
          // exception.
1032
          if (log.is_enabled()) {
1033
            log.print(" failed]");
1034
          }
1035
          return false;
1036
        }
1037
        if (log.is_enabled()) {
1038
            log.print(" succeeded]");
1039
        }
1040
      }
1041
      return true; // for all recorded constraints added successfully.
1042
    }
1043
  }
1044
  if (log.is_enabled()) {
1045
    ResourceMark rm(current);
1046
    log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
1047
  }
1048
  return false;
1049
}
1050

1051
bool SystemDictionaryShared::is_supported_invokedynamic(BootstrapInfo* bsi) {
1052
  LogTarget(Debug, cds, lambda) log;
1053
  if (bsi->arg_values() == nullptr || !bsi->arg_values()->is_objArray()) {
1054
    if (log.is_enabled()) {
1055
      LogStream log_stream(log);
1056
      log.print("bsi check failed");
1057
      log.print("    bsi->arg_values().not_null() %d", bsi->arg_values().not_null());
1058
      if (bsi->arg_values().not_null()) {
1059
        log.print("    bsi->arg_values()->is_objArray() %d", bsi->arg_values()->is_objArray());
1060
        bsi->print_msg_on(&log_stream);
1061
      }
1062
    }
1063
    return false;
1064
  }
1065

1066
  Handle bsm = bsi->bsm();
1067
  if (bsm.is_null() || !java_lang_invoke_DirectMethodHandle::is_instance(bsm())) {
1068
    if (log.is_enabled()) {
1069
      log.print("bsm check failed");
1070
      log.print("    bsm.is_null() %d", bsm.is_null());
1071
      log.print("    java_lang_invoke_DirectMethodHandle::is_instance(bsm()) %d",
1072
        java_lang_invoke_DirectMethodHandle::is_instance(bsm()));
1073
    }
1074
    return false;
1075
  }
1076

1077
  oop mn = java_lang_invoke_DirectMethodHandle::member(bsm());
1078
  Method* method = java_lang_invoke_MemberName::vmtarget(mn);
1079
  if (method->klass_name()->equals("java/lang/invoke/LambdaMetafactory") &&
1080
      method->name()->equals("metafactory") &&
1081
      method->signature()->equals("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;"
1082
            "Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;"
1083
            "Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;")) {
1084
      return true;
1085
  } else {
1086
    if (log.is_enabled()) {
1087
      ResourceMark rm;
1088
      log.print("method check failed");
1089
      log.print("    klass_name() %s", method->klass_name()->as_C_string());
1090
      log.print("    name() %s", method->name()->as_C_string());
1091
      log.print("    signature() %s", method->signature()->as_C_string());
1092
    }
1093
  }
1094

1095
  return false;
1096
}
1097

1098
class EstimateSizeForArchive : StackObj {
1099
  size_t _shared_class_info_size;
1100
  int _num_builtin_klasses;
1101
  int _num_unregistered_klasses;
1102

1103
public:
1104
  EstimateSizeForArchive() {
1105
    _shared_class_info_size = 0;
1106
    _num_builtin_klasses = 0;
1107
    _num_unregistered_klasses = 0;
1108
  }
1109

1110
  void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1111
    if (!info.is_excluded()) {
1112
      size_t byte_size = info.runtime_info_bytesize();
1113
      _shared_class_info_size += align_up(byte_size, SharedSpaceObjectAlignment);
1114
    }
1115
  }
1116

1117
  size_t total() {
1118
    return _shared_class_info_size;
1119
  }
1120
};
1121

1122
size_t SystemDictionaryShared::estimate_size_for_archive() {
1123
  EstimateSizeForArchive est;
1124
  _dumptime_table->iterate_all_live_classes(&est);
1125
  size_t total_size = est.total() +
1126
    CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) +
1127
    CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false));
1128

1129
  size_t bytesize = align_up(sizeof(RunTimeLambdaProxyClassInfo), SharedSpaceObjectAlignment);
1130
  total_size +=
1131
      (bytesize * _dumptime_lambda_proxy_class_dictionary->_count) +
1132
      CompactHashtableWriter::estimate_size(_dumptime_lambda_proxy_class_dictionary->_count);
1133

1134
  return total_size;
1135
}
1136

1137
unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) {
1138
  if (ArchiveBuilder::is_active()) {
1139
    uintx offset = ArchiveBuilder::current()->any_to_offset(ptr);
1140
    unsigned int hash = primitive_hash<uintx>(offset);
1141
    DEBUG_ONLY({
1142
        if (MetaspaceObj::is_shared((const MetaspaceObj*)ptr)) {
1143
          assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be");
1144
        }
1145
      });
1146
    return hash;
1147
  } else {
1148
    return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr);
1149
  }
1150
}
1151

1152
class CopyLambdaProxyClassInfoToArchive : StackObj {
1153
  CompactHashtableWriter* _writer;
1154
  ArchiveBuilder* _builder;
1155
public:
1156
  CopyLambdaProxyClassInfoToArchive(CompactHashtableWriter* writer)
1157
  : _writer(writer), _builder(ArchiveBuilder::current()) {}
1158
  bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1159
    // In static dump, info._proxy_klasses->at(0) is already relocated to point to the archived class
1160
    // (not the original class).
1161
    //
1162
    // The following check has been moved to SystemDictionaryShared::check_excluded_classes(), which
1163
    // happens before the classes are copied.
1164
    //
1165
    // if (SystemDictionaryShared::is_excluded_class(info._proxy_klasses->at(0))) {
1166
    //  return true;
1167
    //}
1168
    ResourceMark rm;
1169
    log_info(cds,dynamic)("Archiving hidden %s", info._proxy_klasses->at(0)->external_name());
1170
    size_t byte_size = sizeof(RunTimeLambdaProxyClassInfo);
1171
    RunTimeLambdaProxyClassInfo* runtime_info =
1172
        (RunTimeLambdaProxyClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1173
    runtime_info->init(key, info);
1174
    unsigned int hash = runtime_info->hash();
1175
    u4 delta = _builder->any_to_offset_u4((void*)runtime_info);
1176
    _writer->add(hash, delta);
1177
    return true;
1178
  }
1179
};
1180

1181
class AdjustLambdaProxyClassInfo : StackObj {
1182
public:
1183
  AdjustLambdaProxyClassInfo() {}
1184
  bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1185
    int len = info._proxy_klasses->length();
1186
    InstanceKlass* last_buff_k = nullptr;
1187

1188
    for (int i = len - 1; i >= 0; i--) {
1189
      InstanceKlass* orig_k = info._proxy_klasses->at(i);
1190
      InstanceKlass* buff_k = ArchiveBuilder::current()->get_buffered_addr(orig_k);
1191
      assert(ArchiveBuilder::current()->is_in_buffer_space(buff_k), "must be");
1192
      buff_k->set_lambda_proxy_is_available();
1193
      buff_k->set_next_link(last_buff_k);
1194
      if (last_buff_k != nullptr) {
1195
        ArchivePtrMarker::mark_pointer(buff_k->next_link_addr());
1196
      }
1197
      last_buff_k = buff_k;
1198
    }
1199

1200
    return true;
1201
  }
1202
};
1203

1204
class CopySharedClassInfoToArchive : StackObj {
1205
  CompactHashtableWriter* _writer;
1206
  bool _is_builtin;
1207
  ArchiveBuilder *_builder;
1208
public:
1209
  CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
1210
                               bool is_builtin)
1211
    : _writer(writer), _is_builtin(is_builtin), _builder(ArchiveBuilder::current()) {}
1212

1213
  void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) {
1214
    if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
1215
      size_t byte_size = info.runtime_info_bytesize();
1216
      RunTimeClassInfo* record;
1217
      record = (RunTimeClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size);
1218
      record->init(info);
1219

1220
      unsigned int hash;
1221
      Symbol* name = info._klass->name();
1222
      name = ArchiveBuilder::current()->get_buffered_addr(name);
1223
      hash = SystemDictionaryShared::hash_for_shared_dictionary((address)name);
1224
      u4 delta = _builder->buffer_to_offset_u4((address)record);
1225
      if (_is_builtin && info._klass->is_hidden()) {
1226
        // skip
1227
      } else {
1228
        _writer->add(hash, delta);
1229
      }
1230
      if (log_is_enabled(Trace, cds, hashtables)) {
1231
        ResourceMark rm;
1232
        log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1233
      }
1234

1235
      // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo*
1236
      InstanceKlass* buffered_klass = ArchiveBuilder::current()->get_buffered_addr(info._klass);
1237
      RunTimeClassInfo::set_for(buffered_klass, record);
1238
    }
1239
  }
1240
};
1241

1242
void SystemDictionaryShared::write_lambda_proxy_class_dictionary(LambdaProxyClassDictionary *dictionary) {
1243
  CompactHashtableStats stats;
1244
  dictionary->reset();
1245
  CompactHashtableWriter writer(_dumptime_lambda_proxy_class_dictionary->_count, &stats);
1246
  CopyLambdaProxyClassInfoToArchive copy(&writer);
1247
  _dumptime_lambda_proxy_class_dictionary->iterate(&copy);
1248
  writer.dump(dictionary, "lambda proxy class dictionary");
1249
}
1250

1251
void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1252
                                              bool is_builtin) {
1253
  CompactHashtableStats stats;
1254
  dictionary->reset();
1255
  CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1256
  CopySharedClassInfoToArchive copy(&writer, is_builtin);
1257
  assert_lock_strong(DumpTimeTable_lock);
1258
  _dumptime_table->iterate_all_live_classes(&copy);
1259
  writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1260
}
1261

1262
void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1263
  ArchiveInfo* archive = get_archive(is_static_archive);
1264

1265
  write_dictionary(&archive->_builtin_dictionary, true);
1266
  write_dictionary(&archive->_unregistered_dictionary, false);
1267

1268
  write_lambda_proxy_class_dictionary(&archive->_lambda_proxy_class_dictionary);
1269
}
1270

1271
void SystemDictionaryShared::adjust_lambda_proxy_class_dictionary() {
1272
  AdjustLambdaProxyClassInfo adjuster;
1273
  _dumptime_lambda_proxy_class_dictionary->iterate(&adjuster);
1274
}
1275

1276
void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1277
                                                          bool is_static_archive) {
1278
  ArchiveInfo* archive = get_archive(is_static_archive);
1279

1280
  archive->_builtin_dictionary.serialize_header(soc);
1281
  archive->_unregistered_dictionary.serialize_header(soc);
1282
  archive->_lambda_proxy_class_dictionary.serialize_header(soc);
1283
}
1284

1285
void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) {
1286
  for (auto id : EnumRange<vmClassID>{}) {
1287
    soc->do_ptr(vmClasses::klass_addr_at(id));
1288
  }
1289
}
1290

1291
const RunTimeClassInfo*
1292
SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1293
  if (!CDSConfig::is_using_archive() || !name->is_shared()) {
1294
    // The names of all shared classes must also be a shared Symbol.
1295
    return nullptr;
1296
  }
1297

1298
  unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name);
1299
  const RunTimeClassInfo* record = nullptr;
1300
  if (DynamicArchive::is_mapped()) {
1301
    // Use the regenerated holder classes in the dynamic archive as they
1302
    // have more methods than those in the base archive.
1303
    if (name == vmSymbols::java_lang_invoke_Invokers_Holder() ||
1304
        name == vmSymbols::java_lang_invoke_DirectMethodHandle_Holder() ||
1305
        name == vmSymbols::java_lang_invoke_LambdaForm_Holder() ||
1306
        name == vmSymbols::java_lang_invoke_DelegatingMethodHandle_Holder()) {
1307
      record = dynamic_dict->lookup(name, hash, 0);
1308
      if (record != nullptr) {
1309
        return record;
1310
      }
1311
    }
1312
  }
1313

1314
  if (!MetaspaceShared::is_shared_dynamic(name)) {
1315
    // The names of all shared classes in the static dict must also be in the
1316
    // static archive
1317
    record = static_dict->lookup(name, hash, 0);
1318
  }
1319

1320
  if (record == nullptr && DynamicArchive::is_mapped()) {
1321
    record = dynamic_dict->lookup(name, hash, 0);
1322
  }
1323

1324
  return record;
1325
}
1326

1327
InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1328
  const RunTimeClassInfo* record = find_record(&_static_archive._builtin_dictionary,
1329
                                               &_dynamic_archive._builtin_dictionary,
1330
                                               name);
1331
  if (record != nullptr) {
1332
    assert(!record->_klass->is_hidden(), "hidden class cannot be looked up by name");
1333
    assert(check_alignment(record->_klass), "Address not aligned");
1334
    // We did not save the classfile data of the generated LambdaForm invoker classes,
1335
    // so we cannot support CLFH for such classes.
1336
    if (record->_klass->is_generated_shared_class() && JvmtiExport::should_post_class_file_load_hook()) {
1337
       return nullptr;
1338
    }
1339
    return record->_klass;
1340
  } else {
1341
    return nullptr;
1342
  }
1343
}
1344

1345
void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1346
  assert(CDSConfig::is_dumping_static_archive(), "class ID is used only for static dump (from classlist)");
1347
  DumpTimeClassInfo* info = get_info(k);
1348
  info->_id = id;
1349
}
1350

1351
static const char* class_loader_name_for_shared(Klass* k) {
1352
  assert(k != nullptr, "Sanity");
1353
  assert(k->is_shared(), "Must be");
1354
  assert(k->is_instance_klass(), "Must be");
1355
  InstanceKlass* ik = InstanceKlass::cast(k);
1356
  if (ik->is_shared_boot_class()) {
1357
    return "boot_loader";
1358
  } else if (ik->is_shared_platform_class()) {
1359
    return "platform_loader";
1360
  } else if (ik->is_shared_app_class()) {
1361
    return "app_loader";
1362
  } else if (ik->is_shared_unregistered_class()) {
1363
    return "unregistered_loader";
1364
  } else {
1365
    return "unknown loader";
1366
  }
1367
}
1368

1369
class SharedDictionaryPrinter : StackObj {
1370
  outputStream* _st;
1371
  int _index;
1372
public:
1373
  SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1374

1375
  void do_value(const RunTimeClassInfo* record) {
1376
    ResourceMark rm;
1377
    _st->print_cr("%4d: %s %s", _index++, record->_klass->external_name(),
1378
        class_loader_name_for_shared(record->_klass));
1379
    if (record->_klass->array_klasses() != nullptr) {
1380
      record->_klass->array_klasses()->cds_print_value_on(_st);
1381
      _st->cr();
1382
    }
1383
  }
1384
  int index() const { return _index; }
1385
};
1386

1387
class SharedLambdaDictionaryPrinter : StackObj {
1388
  outputStream* _st;
1389
  int _index;
1390
public:
1391
  SharedLambdaDictionaryPrinter(outputStream* st, int idx) : _st(st), _index(idx) {}
1392

1393
  void do_value(const RunTimeLambdaProxyClassInfo* record) {
1394
    if (record->proxy_klass_head()->lambda_proxy_is_available()) {
1395
      ResourceMark rm;
1396
      Klass* k = record->proxy_klass_head();
1397
      while (k != nullptr) {
1398
        _st->print_cr("%4d: %s %s", _index++, k->external_name(),
1399
                      class_loader_name_for_shared(k));
1400
        k = k->next_link();
1401
      }
1402
    }
1403
  }
1404
};
1405

1406
void SystemDictionaryShared::ArchiveInfo::print_on(const char* prefix,
1407
                                                   outputStream* st) {
1408
  st->print_cr("%sShared Dictionary", prefix);
1409
  SharedDictionaryPrinter p(st);
1410
  st->print_cr("%sShared Builtin Dictionary", prefix);
1411
  _builtin_dictionary.iterate(&p);
1412
  st->print_cr("%sShared Unregistered Dictionary", prefix);
1413
  _unregistered_dictionary.iterate(&p);
1414
  if (!_lambda_proxy_class_dictionary.empty()) {
1415
    st->print_cr("%sShared Lambda Dictionary", prefix);
1416
    SharedLambdaDictionaryPrinter ldp(st, p.index());
1417
    _lambda_proxy_class_dictionary.iterate(&ldp);
1418
  }
1419
}
1420

1421
void SystemDictionaryShared::ArchiveInfo::print_table_statistics(const char* prefix,
1422
                                                                 outputStream* st) {
1423
  st->print_cr("%sArchve Statistics", prefix);
1424
  _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1425
  _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1426
  _lambda_proxy_class_dictionary.print_table_statistics(st, "Lambda Shared Dictionary");
1427
}
1428

1429
void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) {
1430
  if (CDSConfig::is_using_archive()) {
1431
    if (is_static) {
1432
      _static_archive.print_on("", st);
1433
    } else {
1434
      if (DynamicArchive::is_mapped()) {
1435
        _dynamic_archive.print_on("Dynamic ", st);
1436
      }
1437
    }
1438
  }
1439
}
1440

1441
void SystemDictionaryShared::print_on(outputStream* st) {
1442
  print_shared_archive(st, true);
1443
  print_shared_archive(st, false);
1444
}
1445

1446
void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1447
  if (CDSConfig::is_using_archive()) {
1448
    _static_archive.print_table_statistics("Static ", st);
1449
    if (DynamicArchive::is_mapped()) {
1450
      _dynamic_archive.print_table_statistics("Dynamic ", st);
1451
    }
1452
  }
1453
}
1454

1455
bool SystemDictionaryShared::is_dumptime_table_empty() {
1456
  assert_lock_strong(DumpTimeTable_lock);
1457
  _dumptime_table->update_counts();
1458
  if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
1459
    return true;
1460
  }
1461
  return false;
1462
}
1463

1464
class CleanupDumpTimeLambdaProxyClassTable: StackObj {
1465
 public:
1466
  bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1467
    assert_lock_strong(DumpTimeTable_lock);
1468
    InstanceKlass* caller_ik = key.caller_ik();
1469
    InstanceKlass* nest_host = caller_ik->nest_host_not_null();
1470

1471
    // If the caller class and/or nest_host are excluded, the associated lambda proxy
1472
    // must also be excluded.
1473
    bool always_exclude = SystemDictionaryShared::check_for_exclusion(caller_ik, nullptr) ||
1474
                          SystemDictionaryShared::check_for_exclusion(nest_host, nullptr);
1475

1476
    for (int i = info._proxy_klasses->length() - 1; i >= 0; i--) {
1477
      InstanceKlass* ik = info._proxy_klasses->at(i);
1478
      if (always_exclude || SystemDictionaryShared::check_for_exclusion(ik, nullptr)) {
1479
        SystemDictionaryShared::reset_registered_lambda_proxy_class(ik);
1480
        info._proxy_klasses->remove_at(i);
1481
      }
1482
    }
1483
    return info._proxy_klasses->length() == 0 ? true /* delete the node*/ : false;
1484
  }
1485
};
1486

1487
void SystemDictionaryShared::cleanup_lambda_proxy_class_dictionary() {
1488
  assert_lock_strong(DumpTimeTable_lock);
1489
  CleanupDumpTimeLambdaProxyClassTable cleanup_proxy_classes;
1490
  _dumptime_lambda_proxy_class_dictionary->unlink(&cleanup_proxy_classes);
1491
}
1492

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.