systemDictionary.cpp revision 11650:047ad22e7be5
1/*
2 * Copyright (c) 1997, 2016, 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/classFileParser.hpp"
27#include "classfile/classFileStream.hpp"
28#include "classfile/classLoader.hpp"
29#include "classfile/classLoaderData.inline.hpp"
30#include "classfile/classLoaderExt.hpp"
31#include "classfile/dictionary.hpp"
32#include "classfile/javaClasses.inline.hpp"
33#include "classfile/klassFactory.hpp"
34#include "classfile/loaderConstraints.hpp"
35#include "classfile/packageEntry.hpp"
36#include "classfile/placeholders.hpp"
37#include "classfile/resolutionErrors.hpp"
38#include "classfile/stringTable.hpp"
39#include "classfile/systemDictionary.hpp"
40#include "classfile/vmSymbols.hpp"
41#include "code/codeCache.hpp"
42#include "compiler/compileBroker.hpp"
43#include "gc/shared/gcLocker.hpp"
44#include "interpreter/bytecodeStream.hpp"
45#include "interpreter/interpreter.hpp"
46#include "memory/filemap.hpp"
47#include "memory/oopFactory.hpp"
48#include "memory/resourceArea.hpp"
49#include "oops/instanceKlass.hpp"
50#include "oops/instanceRefKlass.hpp"
51#include "oops/klass.inline.hpp"
52#include "oops/methodData.hpp"
53#include "oops/objArrayKlass.hpp"
54#include "oops/objArrayOop.inline.hpp"
55#include "oops/oop.inline.hpp"
56#include "oops/symbol.hpp"
57#include "oops/typeArrayKlass.hpp"
58#include "prims/jvmtiEnvBase.hpp"
59#include "prims/methodHandles.hpp"
60#include "runtime/arguments.hpp"
61#include "runtime/biasedLocking.hpp"
62#include "runtime/fieldType.hpp"
63#include "runtime/handles.inline.hpp"
64#include "runtime/java.hpp"
65#include "runtime/javaCalls.hpp"
66#include "runtime/mutexLocker.hpp"
67#include "runtime/orderAccess.inline.hpp"
68#include "runtime/signature.hpp"
69#include "services/classLoadingService.hpp"
70#include "services/threadService.hpp"
71#include "trace/traceMacros.hpp"
72#include "utilities/macros.hpp"
73#include "utilities/stringUtils.hpp"
74#include "utilities/ticks.hpp"
75#if INCLUDE_CDS
76#include "classfile/sharedClassUtil.hpp"
77#include "classfile/systemDictionaryShared.hpp"
78#endif
79#if INCLUDE_JVMCI
80#include "jvmci/jvmciRuntime.hpp"
81#endif
82#if INCLUDE_TRACE
83#include "trace/tracing.hpp"
84#endif
85
86Dictionary*            SystemDictionary::_dictionary          = NULL;
87PlaceholderTable*      SystemDictionary::_placeholders        = NULL;
88Dictionary*            SystemDictionary::_shared_dictionary   = NULL;
89LoaderConstraintTable* SystemDictionary::_loader_constraints  = NULL;
90ResolutionErrorTable*  SystemDictionary::_resolution_errors   = NULL;
91SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
92
93
94int         SystemDictionary::_number_of_modifications = 0;
95int         SystemDictionary::_sdgeneration               = 0;
96const int   SystemDictionary::_primelist[_prime_array_size] = {1009,2017,4049,5051,10103,
97              20201,40423,99991};
98
99oop         SystemDictionary::_system_loader_lock_obj     =  NULL;
100
101InstanceKlass*      SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
102                                                          =  { NULL /*, NULL...*/ };
103
104InstanceKlass*      SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
105
106oop         SystemDictionary::_java_system_loader         =  NULL;
107
108bool        SystemDictionary::_has_loadClassInternal      =  false;
109bool        SystemDictionary::_has_checkPackageAccess     =  false;
110
111// lazily initialized klass variables
112InstanceKlass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
113
114
115// ----------------------------------------------------------------------------
116// Java-level SystemLoader
117
118oop SystemDictionary::java_system_loader() {
119  return _java_system_loader;
120}
121
122void SystemDictionary::compute_java_system_loader(TRAPS) {
123  KlassHandle system_klass(THREAD, WK_KLASS(ClassLoader_klass));
124  JavaValue result(T_OBJECT);
125  JavaCalls::call_static(&result,
126                         KlassHandle(THREAD, WK_KLASS(ClassLoader_klass)),
127                         vmSymbols::getSystemClassLoader_name(),
128                         vmSymbols::void_classloader_signature(),
129                         CHECK);
130
131  _java_system_loader = (oop)result.get_jobject();
132
133  CDS_ONLY(SystemDictionaryShared::initialize(CHECK);)
134}
135
136
137ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, TRAPS) {
138  if (class_loader() == NULL) return ClassLoaderData::the_null_class_loader_data();
139  return ClassLoaderDataGraph::find_or_create(class_loader, THREAD);
140}
141
142// ----------------------------------------------------------------------------
143// debugging
144
145#ifdef ASSERT
146
147// return true if class_name contains no '.' (internal format is '/')
148bool SystemDictionary::is_internal_format(Symbol* class_name) {
149  if (class_name != NULL) {
150    ResourceMark rm;
151    char* name = class_name->as_C_string();
152    return strchr(name, '.') == NULL;
153  } else {
154    return true;
155  }
156}
157
158#endif
159
160// ----------------------------------------------------------------------------
161// Parallel class loading check
162
163bool SystemDictionary::is_parallelCapable(Handle class_loader) {
164  if (UnsyncloadClass || class_loader.is_null()) return true;
165  if (AlwaysLockClassLoader) return false;
166  return java_lang_ClassLoader::parallelCapable(class_loader());
167}
168// ----------------------------------------------------------------------------
169// ParallelDefineClass flag does not apply to bootclass loader
170bool SystemDictionary::is_parallelDefine(Handle class_loader) {
171   if (class_loader.is_null()) return false;
172   if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) {
173     return true;
174   }
175   return false;
176}
177
178// Returns true if the passed class loader is the builtin application class loader
179// or a custom system class loader. A customer system class loader can be
180// specified via -Djava.system.class.loader.
181bool SystemDictionary::is_system_class_loader(Handle class_loader) {
182  if (class_loader.is_null()) {
183    return false;
184  }
185  return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass() ||
186          class_loader() == _java_system_loader);
187}
188
189// Returns true if the passed class loader is the platform class loader.
190bool SystemDictionary::is_platform_class_loader(Handle class_loader) {
191  if (class_loader.is_null()) {
192    return false;
193  }
194  return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass());
195}
196
197// ----------------------------------------------------------------------------
198// Resolving of classes
199
200// Forwards to resolve_or_null
201
202Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
203  Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
204  if (HAS_PENDING_EXCEPTION || klass == NULL) {
205    KlassHandle k_h(THREAD, klass);
206    // can return a null klass
207    klass = handle_resolution_exception(class_name, throw_error, k_h, THREAD);
208  }
209  return klass;
210}
211
212Klass* SystemDictionary::handle_resolution_exception(Symbol* class_name,
213                                                     bool throw_error,
214                                                     KlassHandle klass_h, TRAPS) {
215  if (HAS_PENDING_EXCEPTION) {
216    // If we have a pending exception we forward it to the caller, unless throw_error is true,
217    // in which case we have to check whether the pending exception is a ClassNotFoundException,
218    // and if so convert it to a NoClassDefFoundError
219    // And chain the original ClassNotFoundException
220    if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) {
221      ResourceMark rm(THREAD);
222      assert(klass_h() == NULL, "Should not have result with exception pending");
223      Handle e(THREAD, PENDING_EXCEPTION);
224      CLEAR_PENDING_EXCEPTION;
225      THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
226    } else {
227      return NULL;
228    }
229  }
230  // Class not found, throw appropriate error or exception depending on value of throw_error
231  if (klass_h() == NULL) {
232    ResourceMark rm(THREAD);
233    if (throw_error) {
234      THROW_MSG_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
235    } else {
236      THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
237    }
238  }
239  return (Klass*)klass_h();
240}
241
242
243Klass* SystemDictionary::resolve_or_fail(Symbol* class_name,
244                                           bool throw_error, TRAPS)
245{
246  return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
247}
248
249
250// Forwards to resolve_instance_class_or_null
251
252Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) {
253  assert(THREAD->can_call_java(),
254         "can not load classes with compiler thread: class=%s, classloader=%s",
255         class_name->as_C_string(),
256         class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string());
257  if (FieldType::is_array(class_name)) {
258    return resolve_array_class_or_null(class_name, class_loader, protection_domain, THREAD);
259  } else if (FieldType::is_obj(class_name)) {
260    ResourceMark rm(THREAD);
261    // Ignore wrapping L and ;.
262    TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1,
263                                   class_name->utf8_length() - 2, CHECK_NULL);
264    return resolve_instance_class_or_null(name, class_loader, protection_domain, THREAD);
265  } else {
266    return resolve_instance_class_or_null(class_name, class_loader, protection_domain, THREAD);
267  }
268}
269
270Klass* SystemDictionary::resolve_or_null(Symbol* class_name, TRAPS) {
271  return resolve_or_null(class_name, Handle(), Handle(), THREAD);
272}
273
274// Forwards to resolve_instance_class_or_null
275
276Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name,
277                                                       Handle class_loader,
278                                                       Handle protection_domain,
279                                                       TRAPS) {
280  assert(FieldType::is_array(class_name), "must be array");
281  Klass* k = NULL;
282  FieldArrayInfo fd;
283  // dimension and object_key in FieldArrayInfo are assigned as a side-effect
284  // of this call
285  BasicType t = FieldType::get_array_info(class_name, fd, CHECK_NULL);
286  if (t == T_OBJECT) {
287    // naked oop "k" is OK here -- we assign back into it
288    k = SystemDictionary::resolve_instance_class_or_null(fd.object_key(),
289                                                         class_loader,
290                                                         protection_domain,
291                                                         CHECK_NULL);
292    if (k != NULL) {
293      k = k->array_klass(fd.dimension(), CHECK_NULL);
294    }
295  } else {
296    k = Universe::typeArrayKlassObj(t);
297    k = TypeArrayKlass::cast(k)->array_klass(fd.dimension(), CHECK_NULL);
298  }
299  return k;
300}
301
302
303// Must be called for any super-class or super-interface resolution
304// during class definition to allow class circularity checking
305// super-interface callers:
306//    parse_interfaces - for defineClass & jvmtiRedefineClasses
307// super-class callers:
308//   ClassFileParser - for defineClass & jvmtiRedefineClasses
309//   load_shared_class - while loading a class from shared archive
310//   resolve_instance_class_or_null:
311//     via: handle_parallel_super_load
312//      when resolving a class that has an existing placeholder with
313//      a saved superclass [i.e. a defineClass is currently in progress]
314//      if another thread is trying to resolve the class, it must do
315//      super-class checks on its own thread to catch class circularity
316// This last call is critical in class circularity checking for cases
317// where classloading is delegated to different threads and the
318// classloader lock is released.
319// Take the case: Base->Super->Base
320//   1. If thread T1 tries to do a defineClass of class Base
321//    resolve_super_or_fail creates placeholder: T1, Base (super Super)
322//   2. resolve_instance_class_or_null does not find SD or placeholder for Super
323//    so it tries to load Super
324//   3. If we load the class internally, or user classloader uses same thread
325//      loadClassFromxxx or defineClass via parseClassFile Super ...
326//      3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)
327//      3.3 resolve_instance_class_or_null Base, finds placeholder for Base
328//      3.4 calls resolve_super_or_fail Base
329//      3.5 finds T1,Base -> throws class circularity
330//OR 4. If T2 tries to resolve Super via defineClass Super ...
331//      4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)
332//      4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
333//      4.3 calls resolve_super_or_fail Super in parallel on own thread T2
334//      4.4 finds T2, Super -> throws class circularity
335// Must be called, even if superclass is null, since this is
336// where the placeholder entry is created which claims this
337// thread is loading this class/classloader.
338Klass* SystemDictionary::resolve_super_or_fail(Symbol* child_name,
339                                                 Symbol* class_name,
340                                                 Handle class_loader,
341                                                 Handle protection_domain,
342                                                 bool is_superclass,
343                                                 TRAPS) {
344#if INCLUDE_CDS
345  if (DumpSharedSpaces) {
346    // Special processing for CDS dump time.
347    Klass* k = SystemDictionaryShared::dump_time_resolve_super_or_fail(child_name,
348        class_name, class_loader, protection_domain, is_superclass, CHECK_NULL);
349    if (k) {
350      return k;
351    }
352  }
353#endif // INCLUDE_CDS
354
355  // Double-check, if child class is already loaded, just return super-class,interface
356  // Don't add a placedholder if already loaded, i.e. already in system dictionary
357  // Make sure there's a placeholder for the *child* before resolving.
358  // Used as a claim that this thread is currently loading superclass/classloader
359  // Used here for ClassCircularity checks and also for heap verification
360  // (every InstanceKlass in the heap needs to be in the system dictionary
361  // or have a placeholder).
362  // Must check ClassCircularity before checking if super class is already loaded
363  //
364  // We might not already have a placeholder if this child_name was
365  // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
366  // the name of the class might not be known until the stream is actually
367  // parsed.
368  // Bugs 4643874, 4715493
369  // compute_hash can have a safepoint
370
371  ClassLoaderData* loader_data = class_loader_data(class_loader);
372  unsigned int d_hash = dictionary()->compute_hash(child_name, loader_data);
373  int d_index = dictionary()->hash_to_index(d_hash);
374  unsigned int p_hash = placeholders()->compute_hash(child_name, loader_data);
375  int p_index = placeholders()->hash_to_index(p_hash);
376  // can't throw error holding a lock
377  bool child_already_loaded = false;
378  bool throw_circularity_error = false;
379  {
380    MutexLocker mu(SystemDictionary_lock, THREAD);
381    Klass* childk = find_class(d_index, d_hash, child_name, loader_data);
382    Klass* quicksuperk;
383    // to support // loading: if child done loading, just return superclass
384    // if class_name, & class_loader don't match:
385    // if initial define, SD update will give LinkageError
386    // if redefine: compare_class_versions will give HIERARCHY_CHANGED
387    // so we don't throw an exception here.
388    // see: nsk redefclass014 & java.lang.instrument Instrument032
389    if ((childk != NULL ) && (is_superclass) &&
390       ((quicksuperk = childk->super()) != NULL) &&
391
392         ((quicksuperk->name() == class_name) &&
393            (quicksuperk->class_loader()  == class_loader()))) {
394           return quicksuperk;
395    } else {
396      PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
397      if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
398          throw_circularity_error = true;
399      }
400    }
401    if (!throw_circularity_error) {
402      PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, class_name, THREAD);
403    }
404  }
405  if (throw_circularity_error) {
406      ResourceMark rm(THREAD);
407      THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
408  }
409
410// java.lang.Object should have been found above
411  assert(class_name != NULL, "null super class for resolving");
412  // Resolve the super class or interface, check results on return
413  Klass* superk = SystemDictionary::resolve_or_null(class_name,
414                                                 class_loader,
415                                                 protection_domain,
416                                                 THREAD);
417
418  KlassHandle superk_h(THREAD, superk);
419
420  // Clean up of placeholders moved so that each classloadAction registrar self-cleans up
421  // It is no longer necessary to keep the placeholder table alive until update_dictionary
422  // or error. GC used to walk the placeholder table as strong roots.
423  // The instanceKlass is kept alive because the class loader is on the stack,
424  // which keeps the loader_data alive, as well as all instanceKlasses in
425  // the loader_data. parseClassFile adds the instanceKlass to loader_data.
426  {
427    MutexLocker mu(SystemDictionary_lock, THREAD);
428    placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD);
429    SystemDictionary_lock->notify_all();
430  }
431  if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
432    // can null superk
433    superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, true, superk_h, THREAD));
434  }
435
436  return superk_h();
437}
438
439void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
440                                                  Handle class_loader,
441                                                  Handle protection_domain,
442                                                  TRAPS) {
443  if(!has_checkPackageAccess()) return;
444
445  // Now we have to call back to java to check if the initating class has access
446  JavaValue result(T_VOID);
447  if (log_is_enabled(Debug, protectiondomain)) {
448    ResourceMark rm;
449    // Print out trace information
450    outputStream* log = Log(protectiondomain)::debug_stream();
451    log->print_cr("Checking package access");
452    log->print("class loader: "); class_loader()->print_value_on(log);
453    log->print(" protection domain: "); protection_domain()->print_value_on(log);
454    log->print(" loading: "); klass()->print_value_on(log);
455    log->cr();
456  }
457
458  KlassHandle system_loader(THREAD, SystemDictionary::ClassLoader_klass());
459  JavaCalls::call_special(&result,
460                         class_loader,
461                         system_loader,
462                         vmSymbols::checkPackageAccess_name(),
463                         vmSymbols::class_protectiondomain_signature(),
464                         Handle(THREAD, klass->java_mirror()),
465                         protection_domain,
466                         THREAD);
467
468  if (HAS_PENDING_EXCEPTION) {
469    log_debug(protectiondomain)("DENIED !!!!!!!!!!!!!!!!!!!!!");
470  } else {
471   log_debug(protectiondomain)("granted");
472  }
473
474  if (HAS_PENDING_EXCEPTION) return;
475
476  // If no exception has been thrown, we have validated the protection domain
477  // Insert the protection domain of the initiating class into the set.
478  {
479    // We recalculate the entry here -- we've called out to java since
480    // the last time it was calculated.
481    ClassLoaderData* loader_data = class_loader_data(class_loader);
482
483    Symbol*  kn = klass->name();
484    unsigned int d_hash = dictionary()->compute_hash(kn, loader_data);
485    int d_index = dictionary()->hash_to_index(d_hash);
486
487    MutexLocker mu(SystemDictionary_lock, THREAD);
488    {
489      // Note that we have an entry, and entries can be deleted only during GC,
490      // so we cannot allow GC to occur while we're holding this entry.
491
492      // We're using a NoSafepointVerifier to catch any place where we
493      // might potentially do a GC at all.
494      // Dictionary::do_unloading() asserts that classes in SD are only
495      // unloaded at a safepoint. Anonymous classes are not in SD.
496      NoSafepointVerifier nosafepoint;
497      dictionary()->add_protection_domain(d_index, d_hash, klass, loader_data,
498                                          protection_domain, THREAD);
499    }
500  }
501}
502
503// We only get here if this thread finds that another thread
504// has already claimed the placeholder token for the current operation,
505// but that other thread either never owned or gave up the
506// object lock
507// Waits on SystemDictionary_lock to indicate placeholder table updated
508// On return, caller must recheck placeholder table state
509//
510// We only get here if
511//  1) custom classLoader, i.e. not bootstrap classloader
512//  2) UnsyncloadClass not set
513//  3) custom classLoader has broken the class loader objectLock
514//     so another thread got here in parallel
515//
516// lockObject must be held.
517// Complicated dance due to lock ordering:
518// Must first release the classloader object lock to
519// allow initial definer to complete the class definition
520// and to avoid deadlock
521// Reclaim classloader lock object with same original recursion count
522// Must release SystemDictionary_lock after notify, since
523// class loader lock must be claimed before SystemDictionary_lock
524// to prevent deadlocks
525//
526// The notify allows applications that did an untimed wait() on
527// the classloader object lock to not hang.
528void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {
529  assert_lock_strong(SystemDictionary_lock);
530
531  bool calledholdinglock
532      = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject);
533  assert(calledholdinglock,"must hold lock for notify");
534  assert((!(lockObject() == _system_loader_lock_obj) && !is_parallelCapable(lockObject)), "unexpected double_lock_wait");
535  ObjectSynchronizer::notifyall(lockObject, THREAD);
536  intptr_t recursions =  ObjectSynchronizer::complete_exit(lockObject, THREAD);
537  SystemDictionary_lock->wait();
538  SystemDictionary_lock->unlock();
539  ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
540  SystemDictionary_lock->lock();
541}
542
543// If the class in is in the placeholder table, class loading is in progress
544// For cases where the application changes threads to load classes, it
545// is critical to ClassCircularity detection that we try loading
546// the superclass on the same thread internally, so we do parallel
547// super class loading here.
548// This also is critical in cases where the original thread gets stalled
549// even in non-circularity situations.
550// Note: must call resolve_super_or_fail even if null super -
551// to force placeholder entry creation for this class for circularity detection
552// Caller must check for pending exception
553// Returns non-null Klass* if other thread has completed load
554// and we are done,
555// If return null Klass* and no pending exception, the caller must load the class
556instanceKlassHandle SystemDictionary::handle_parallel_super_load(
557    Symbol* name, Symbol* superclassname, Handle class_loader,
558    Handle protection_domain, Handle lockObject, TRAPS) {
559
560  instanceKlassHandle nh = instanceKlassHandle(); // null Handle
561  ClassLoaderData* loader_data = class_loader_data(class_loader);
562  unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
563  int d_index = dictionary()->hash_to_index(d_hash);
564  unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
565  int p_index = placeholders()->hash_to_index(p_hash);
566
567  // superk is not used, resolve_super called for circularity check only
568  // This code is reached in two situations. One if this thread
569  // is loading the same class twice (e.g. ClassCircularity, or
570  // java.lang.instrument).
571  // The second is if another thread started the resolve_super first
572  // and has not yet finished.
573  // In both cases the original caller will clean up the placeholder
574  // entry on error.
575  Klass* superk = SystemDictionary::resolve_super_or_fail(name,
576                                                          superclassname,
577                                                          class_loader,
578                                                          protection_domain,
579                                                          true,
580                                                          CHECK_(nh));
581
582  // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
583  // Serial class loaders and bootstrap classloader do wait for superclass loads
584 if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
585    MutexLocker mu(SystemDictionary_lock, THREAD);
586    // Check if classloading completed while we were loading superclass or waiting
587    Klass* check = find_class(d_index, d_hash, name, loader_data);
588    if (check != NULL) {
589      // Klass is already loaded, so just return it
590      return(instanceKlassHandle(THREAD, check));
591    } else {
592      return nh;
593    }
594  }
595
596  // must loop to both handle other placeholder updates
597  // and spurious notifications
598  bool super_load_in_progress = true;
599  PlaceholderEntry* placeholder;
600  while (super_load_in_progress) {
601    MutexLocker mu(SystemDictionary_lock, THREAD);
602    // Check if classloading completed while we were loading superclass or waiting
603    Klass* check = find_class(d_index, d_hash, name, loader_data);
604    if (check != NULL) {
605      // Klass is already loaded, so just return it
606      return(instanceKlassHandle(THREAD, check));
607    } else {
608      placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
609      if (placeholder && placeholder->super_load_in_progress() ){
610        // Before UnsyncloadClass:
611        // We only get here if the application has released the
612        // classloader lock when another thread was in the middle of loading a
613        // superclass/superinterface for this class, and now
614        // this thread is also trying to load this class.
615        // To minimize surprises, the first thread that started to
616        // load a class should be the one to complete the loading
617        // with the classfile it initially expected.
618        // This logic has the current thread wait once it has done
619        // all the superclass/superinterface loading it can, until
620        // the original thread completes the class loading or fails
621        // If it completes we will use the resulting InstanceKlass
622        // which we will find below in the systemDictionary.
623        // We also get here for parallel bootstrap classloader
624        if (class_loader.is_null()) {
625          SystemDictionary_lock->wait();
626        } else {
627          double_lock_wait(lockObject, THREAD);
628        }
629      } else {
630        // If not in SD and not in PH, other thread's load must have failed
631        super_load_in_progress = false;
632      }
633    }
634  }
635  return (nh);
636}
637
638// utility function for class load event
639static void post_class_load_event(const Ticks& start_time,
640                                  instanceKlassHandle k,
641                                  Handle initiating_loader) {
642#if INCLUDE_TRACE
643  EventClassLoad event(UNTIMED);
644  if (event.should_commit()) {
645    event.set_starttime(start_time);
646    event.set_loadedClass(k());
647    oop defining_class_loader = k->class_loader();
648    event.set_definingClassLoader(defining_class_loader != NULL ?
649      defining_class_loader->klass() : (Klass*)NULL);
650    oop class_loader = initiating_loader.is_null() ? (oop)NULL : initiating_loader();
651    event.set_initiatingClassLoader(class_loader != NULL ?
652      class_loader->klass() : (Klass*)NULL);
653    event.commit();
654  }
655#endif // INCLUDE_TRACE
656}
657
658// utility function for class define event
659static void class_define_event(instanceKlassHandle k) {
660#if INCLUDE_TRACE
661  EventClassDefine event(UNTIMED);
662  if (event.should_commit()) {
663    event.set_definedClass(k());
664    oop defining_class_loader = k->class_loader();
665    event.set_definingClassLoader(defining_class_loader != NULL ?
666      defining_class_loader->klass() : (Klass*)NULL);
667    event.commit();
668  }
669#endif // INCLUDE_TRACE
670}
671
672
673Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
674                                                        Handle class_loader,
675                                                        Handle protection_domain,
676                                                        TRAPS) {
677  assert(name != NULL && !FieldType::is_array(name) &&
678         !FieldType::is_obj(name), "invalid class name");
679
680  Ticks class_load_start_time = Ticks::now();
681
682  // Fix for 4474172; see evaluation for more details
683  class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
684  ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL);
685
686  // Do lookup to see if class already exist and the protection domain
687  // has the right access
688  // This call uses find which checks protection domain already matches
689  // All subsequent calls use find_class, and set has_loaded_class so that
690  // before we return a result we call out to java to check for valid protection domain
691  // to allow returning the Klass* and add it to the pd_set if it is valid
692  unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
693  int d_index = dictionary()->hash_to_index(d_hash);
694  Klass* probe = dictionary()->find(d_index, d_hash, name, loader_data,
695                                      protection_domain, THREAD);
696  if (probe != NULL) return probe;
697
698
699  // Non-bootstrap class loaders will call out to class loader and
700  // define via jvm/jni_DefineClass which will acquire the
701  // class loader object lock to protect against multiple threads
702  // defining the class in parallel by accident.
703  // This lock must be acquired here so the waiter will find
704  // any successful result in the SystemDictionary and not attempt
705  // the define
706  // ParallelCapable Classloaders and the bootstrap classloader,
707  // or all classloaders with UnsyncloadClass do not acquire lock here
708  bool DoObjectLock = true;
709  if (is_parallelCapable(class_loader)) {
710    DoObjectLock = false;
711  }
712
713  unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
714  int p_index = placeholders()->hash_to_index(p_hash);
715
716  // Class is not in SystemDictionary so we have to do loading.
717  // Make sure we are synchronized on the class loader before we proceed
718  Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
719  check_loader_lock_contention(lockObject, THREAD);
720  ObjectLocker ol(lockObject, THREAD, DoObjectLock);
721
722  // Check again (after locking) if class already exist in SystemDictionary
723  bool class_has_been_loaded   = false;
724  bool super_load_in_progress  = false;
725  bool havesupername = false;
726  instanceKlassHandle k;
727  PlaceholderEntry* placeholder;
728  Symbol* superclassname = NULL;
729
730  {
731    MutexLocker mu(SystemDictionary_lock, THREAD);
732    Klass* check = find_class(d_index, d_hash, name, loader_data);
733    if (check != NULL) {
734      // Klass is already loaded, so just return it
735      class_has_been_loaded = true;
736      k = instanceKlassHandle(THREAD, check);
737    } else {
738      placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
739      if (placeholder && placeholder->super_load_in_progress()) {
740         super_load_in_progress = true;
741         if (placeholder->havesupername() == true) {
742           superclassname = placeholder->supername();
743           havesupername = true;
744         }
745      }
746    }
747  }
748
749  // If the class is in the placeholder table, class loading is in progress
750  if (super_load_in_progress && havesupername==true) {
751    k = SystemDictionary::handle_parallel_super_load(name, superclassname,
752        class_loader, protection_domain, lockObject, THREAD);
753    if (HAS_PENDING_EXCEPTION) {
754      return NULL;
755    }
756    if (!k.is_null()) {
757      class_has_been_loaded = true;
758    }
759  }
760
761  bool throw_circularity_error = false;
762  if (!class_has_been_loaded) {
763    bool load_instance_added = false;
764
765    // add placeholder entry to record loading instance class
766    // Five cases:
767    // All cases need to prevent modifying bootclasssearchpath
768    // in parallel with a classload of same classname
769    // Redefineclasses uses existence of the placeholder for the duration
770    // of the class load to prevent concurrent redefinition of not completely
771    // defined classes.
772    // case 1. traditional classloaders that rely on the classloader object lock
773    //   - no other need for LOAD_INSTANCE
774    // case 2. traditional classloaders that break the classloader object lock
775    //    as a deadlock workaround. Detection of this case requires that
776    //    this check is done while holding the classloader object lock,
777    //    and that lock is still held when calling classloader's loadClass.
778    //    For these classloaders, we ensure that the first requestor
779    //    completes the load and other requestors wait for completion.
780    // case 3. UnsyncloadClass - don't use objectLocker
781    //    With this flag, we allow parallel classloading of a
782    //    class/classloader pair
783    // case4. Bootstrap classloader - don't own objectLocker
784    //    This classloader supports parallelism at the classloader level,
785    //    but only allows a single load of a class/classloader pair.
786    //    No performance benefit and no deadlock issues.
787    // case 5. parallelCapable user level classloaders - without objectLocker
788    //    Allow parallel classloading of a class/classloader pair
789
790    {
791      MutexLocker mu(SystemDictionary_lock, THREAD);
792      if (class_loader.is_null() || !is_parallelCapable(class_loader)) {
793        PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
794        if (oldprobe) {
795          // only need check_seen_thread once, not on each loop
796          // 6341374 java/lang/Instrument with -Xcomp
797          if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
798            throw_circularity_error = true;
799          } else {
800            // case 1: traditional: should never see load_in_progress.
801            while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
802
803              // case 4: bootstrap classloader: prevent futile classloading,
804              // wait on first requestor
805              if (class_loader.is_null()) {
806                SystemDictionary_lock->wait();
807              } else {
808              // case 2: traditional with broken classloader lock. wait on first
809              // requestor.
810                double_lock_wait(lockObject, THREAD);
811              }
812              // Check if classloading completed while we were waiting
813              Klass* check = find_class(d_index, d_hash, name, loader_data);
814              if (check != NULL) {
815                // Klass is already loaded, so just return it
816                k = instanceKlassHandle(THREAD, check);
817                class_has_been_loaded = true;
818              }
819              // check if other thread failed to load and cleaned up
820              oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
821            }
822          }
823        }
824      }
825      // All cases: add LOAD_INSTANCE holding SystemDictionary_lock
826      // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
827      // LOAD_INSTANCE in parallel
828
829      if (!throw_circularity_error && !class_has_been_loaded) {
830        PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
831        load_instance_added = true;
832        // For class loaders that do not acquire the classloader object lock,
833        // if they did not catch another thread holding LOAD_INSTANCE,
834        // need a check analogous to the acquire ObjectLocker/find_class
835        // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
836        // one final check if the load has already completed
837        // class loaders holding the ObjectLock shouldn't find the class here
838        Klass* check = find_class(d_index, d_hash, name, loader_data);
839        if (check != NULL) {
840        // Klass is already loaded, so return it after checking/adding protection domain
841          k = instanceKlassHandle(THREAD, check);
842          class_has_been_loaded = true;
843        }
844      }
845    }
846
847    // must throw error outside of owning lock
848    if (throw_circularity_error) {
849      assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");
850      ResourceMark rm(THREAD);
851      THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
852    }
853
854    if (!class_has_been_loaded) {
855
856      // Do actual loading
857      k = load_instance_class(name, class_loader, THREAD);
858
859      // For UnsyncloadClass only
860      // If they got a linkageError, check if a parallel class load succeeded.
861      // If it did, then for bytecode resolution the specification requires
862      // that we return the same result we did for the other thread, i.e. the
863      // successfully loaded InstanceKlass
864      // Should not get here for classloaders that support parallelism
865      // with the new cleaner mechanism, even with AllowParallelDefineClass
866      // Bootstrap goes through here to allow for an extra guarantee check
867      if (UnsyncloadClass || (class_loader.is_null())) {
868        if (k.is_null() && HAS_PENDING_EXCEPTION
869          && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
870          MutexLocker mu(SystemDictionary_lock, THREAD);
871          Klass* check = find_class(d_index, d_hash, name, loader_data);
872          if (check != NULL) {
873            // Klass is already loaded, so just use it
874            k = instanceKlassHandle(THREAD, check);
875            CLEAR_PENDING_EXCEPTION;
876            guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
877          }
878        }
879      }
880
881      // If everything was OK (no exceptions, no null return value), and
882      // class_loader is NOT the defining loader, do a little more bookkeeping.
883      if (!HAS_PENDING_EXCEPTION && !k.is_null() &&
884        k->class_loader() != class_loader()) {
885
886        check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
887
888        // Need to check for a PENDING_EXCEPTION again; check_constraints
889        // can throw and doesn't use the CHECK macro.
890        if (!HAS_PENDING_EXCEPTION) {
891          { // Grabbing the Compile_lock prevents systemDictionary updates
892            // during compilations.
893            MutexLocker mu(Compile_lock, THREAD);
894            update_dictionary(d_index, d_hash, p_index, p_hash,
895                              k, class_loader, THREAD);
896          }
897
898          if (JvmtiExport::should_post_class_load()) {
899            Thread *thread = THREAD;
900            assert(thread->is_Java_thread(), "thread->is_Java_thread()");
901            JvmtiExport::post_class_load((JavaThread *) thread, k());
902          }
903        }
904      }
905    } // load_instance_class loop
906
907    if (load_instance_added == true) {
908      // clean up placeholder entries for LOAD_INSTANCE success or error
909      // This brackets the SystemDictionary updates for both defining
910      // and initiating loaders
911      MutexLocker mu(SystemDictionary_lock, THREAD);
912      placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
913      SystemDictionary_lock->notify_all();
914    }
915  }
916
917  if (HAS_PENDING_EXCEPTION || k.is_null()) {
918    return NULL;
919  }
920
921  post_class_load_event(class_load_start_time, k, class_loader);
922
923#ifdef ASSERT
924  {
925    ClassLoaderData* loader_data = k->class_loader_data();
926    MutexLocker mu(SystemDictionary_lock, THREAD);
927    Klass* kk = find_class(name, loader_data);
928    assert(kk == k(), "should be present in dictionary");
929  }
930#endif
931
932  // return if the protection domain in NULL
933  if (protection_domain() == NULL) return k();
934
935  // Check the protection domain has the right access
936  {
937    MutexLocker mu(SystemDictionary_lock, THREAD);
938    // Note that we have an entry, and entries can be deleted only during GC,
939    // so we cannot allow GC to occur while we're holding this entry.
940    // We're using a NoSafepointVerifier to catch any place where we
941    // might potentially do a GC at all.
942    // Dictionary::do_unloading() asserts that classes in SD are only
943    // unloaded at a safepoint. Anonymous classes are not in SD.
944    NoSafepointVerifier nosafepoint;
945    if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
946                                                 loader_data,
947                                                 protection_domain)) {
948      return k();
949    }
950  }
951
952  // Verify protection domain. If it fails an exception is thrown
953  validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
954
955  return k();
956}
957
958
959// This routine does not lock the system dictionary.
960//
961// Since readers don't hold a lock, we must make sure that system
962// dictionary entries are only removed at a safepoint (when only one
963// thread is running), and are added to in a safe way (all links must
964// be updated in an MT-safe manner).
965//
966// Callers should be aware that an entry could be added just after
967// _dictionary->bucket(index) is read here, so the caller will not see
968// the new entry.
969
970Klass* SystemDictionary::find(Symbol* class_name,
971                              Handle class_loader,
972                              Handle protection_domain,
973                              TRAPS) {
974
975  // The result of this call should be consistent with the result
976  // of the call to resolve_instance_class_or_null().
977  // See evaluation 6790209 and 4474172 for more details.
978  class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
979  ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
980
981  if (loader_data == NULL) {
982    // If the ClassLoaderData has not been setup,
983    // then the class loader has no entries in the dictionary.
984    return NULL;
985  }
986
987  unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
988  int d_index = dictionary()->hash_to_index(d_hash);
989
990  {
991    // Note that we have an entry, and entries can be deleted only during GC,
992    // so we cannot allow GC to occur while we're holding this entry.
993    // We're using a NoSafepointVerifier to catch any place where we
994    // might potentially do a GC at all.
995    // Dictionary::do_unloading() asserts that classes in SD are only
996    // unloaded at a safepoint. Anonymous classes are not in SD.
997    NoSafepointVerifier nosafepoint;
998    return dictionary()->find(d_index, d_hash, class_name, loader_data,
999                              protection_domain, THREAD);
1000  }
1001}
1002
1003
1004// Look for a loaded instance or array klass by name.  Do not do any loading.
1005// return NULL in case of error.
1006Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
1007                                                      Handle class_loader,
1008                                                      Handle protection_domain,
1009                                                      TRAPS) {
1010  Klass* k = NULL;
1011  assert(class_name != NULL, "class name must be non NULL");
1012
1013  if (FieldType::is_array(class_name)) {
1014    // The name refers to an array.  Parse the name.
1015    // dimension and object_key in FieldArrayInfo are assigned as a
1016    // side-effect of this call
1017    FieldArrayInfo fd;
1018    BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
1019    if (t != T_OBJECT) {
1020      k = Universe::typeArrayKlassObj(t);
1021    } else {
1022      k = SystemDictionary::find(fd.object_key(), class_loader, protection_domain, THREAD);
1023    }
1024    if (k != NULL) {
1025      k = k->array_klass_or_null(fd.dimension());
1026    }
1027  } else {
1028    k = find(class_name, class_loader, protection_domain, THREAD);
1029  }
1030  return k;
1031}
1032
1033// Note: this method is much like resolve_from_stream, but
1034// updates no supplemental data structures.
1035// TODO consolidate the two methods with a helper routine?
1036Klass* SystemDictionary::parse_stream(Symbol* class_name,
1037                                      Handle class_loader,
1038                                      Handle protection_domain,
1039                                      ClassFileStream* st,
1040                                      const Klass* host_klass,
1041                                      GrowableArray<Handle>* cp_patches,
1042                                      TRAPS) {
1043
1044  Ticks class_load_start_time = Ticks::now();
1045
1046  ClassLoaderData* loader_data;
1047  if (host_klass != NULL) {
1048    // Create a new CLD for anonymous class, that uses the same class loader
1049    // as the host_klass
1050    guarantee(host_klass->class_loader() == class_loader(), "should be the same");
1051    guarantee(!DumpSharedSpaces, "must not create anonymous classes when dumping");
1052    loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL);
1053    loader_data->record_dependency(host_klass, CHECK_NULL);
1054  } else {
1055    loader_data = ClassLoaderData::class_loader_data(class_loader());
1056  }
1057
1058  assert(st != NULL, "invariant");
1059  assert(st->need_verify(), "invariant");
1060
1061  // Parse stream and create a klass.
1062  // Note that we do this even though this klass might
1063  // already be present in the SystemDictionary, otherwise we would not
1064  // throw potential ClassFormatErrors.
1065
1066  instanceKlassHandle k = KlassFactory::create_from_stream(st,
1067                                                           class_name,
1068                                                           loader_data,
1069                                                           protection_domain,
1070                                                           host_klass,
1071                                                           cp_patches,
1072                                                           NULL, // parsed_name
1073                                                           THREAD);
1074
1075  if (host_klass != NULL && k.not_null()) {
1076    // If it's anonymous, initialize it now, since nobody else will.
1077
1078    {
1079      MutexLocker mu_r(Compile_lock, THREAD);
1080
1081      // Add to class hierarchy, initialize vtables, and do possible
1082      // deoptimizations.
1083      add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
1084
1085      // But, do not add to system dictionary.
1086
1087      // compiled code dependencies need to be validated anyway
1088      notice_modification();
1089    }
1090
1091    // Rewrite and patch constant pool here.
1092    k->link_class(CHECK_NULL);
1093    if (cp_patches != NULL) {
1094      k->constants()->patch_resolved_references(cp_patches);
1095    }
1096    k->eager_initialize(CHECK_NULL);
1097
1098    // notify jvmti
1099    if (JvmtiExport::should_post_class_load()) {
1100        assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1101        JvmtiExport::post_class_load((JavaThread *) THREAD, k());
1102    }
1103
1104    post_class_load_event(class_load_start_time, k, class_loader);
1105  }
1106  assert(host_klass != NULL || NULL == cp_patches,
1107         "cp_patches only found with host_klass");
1108
1109  return k();
1110}
1111
1112// Add a klass to the system from a stream (called by jni_DefineClass and
1113// JVM_DefineClass).
1114// Note: class_name can be NULL. In that case we do not know the name of
1115// the class until we have parsed the stream.
1116
1117Klass* SystemDictionary::resolve_from_stream(Symbol* class_name,
1118                                             Handle class_loader,
1119                                             Handle protection_domain,
1120                                             ClassFileStream* st,
1121                                             TRAPS) {
1122
1123  // Classloaders that support parallelism, e.g. bootstrap classloader,
1124  // or all classloaders with UnsyncloadClass do not acquire lock here
1125  bool DoObjectLock = true;
1126  if (is_parallelCapable(class_loader)) {
1127    DoObjectLock = false;
1128  }
1129
1130  ClassLoaderData* loader_data = register_loader(class_loader, CHECK_NULL);
1131
1132  // Make sure we are synchronized on the class loader before we proceed
1133  Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1134  check_loader_lock_contention(lockObject, THREAD);
1135  ObjectLocker ol(lockObject, THREAD, DoObjectLock);
1136
1137  assert(st != NULL, "invariant");
1138
1139  // Parse the stream and create a klass.
1140  // Note that we do this even though this klass might
1141  // already be present in the SystemDictionary, otherwise we would not
1142  // throw potential ClassFormatErrors.
1143  //
1144  // Note: "parsed_name" is updated.
1145  TempNewSymbol parsed_name = NULL;
1146
1147 instanceKlassHandle k;
1148
1149#if INCLUDE_CDS
1150  k = SystemDictionaryShared::lookup_from_stream(class_name,
1151                                                 class_loader,
1152                                                 protection_domain,
1153                                                 st,
1154                                                 CHECK_NULL);
1155#endif
1156
1157  if (k.not_null()) {
1158    parsed_name = k->name();
1159  } else {
1160    if (st->buffer() == NULL) {
1161      return NULL;
1162    }
1163    k = KlassFactory::create_from_stream(st,
1164                                         class_name,
1165                                         loader_data,
1166                                         protection_domain,
1167                                         NULL, // host_klass
1168                                         NULL, // cp_patches
1169                                         &parsed_name,
1170                                         THREAD);
1171  }
1172
1173  const char* pkg = "java/";
1174  if (!HAS_PENDING_EXCEPTION &&
1175      !class_loader.is_null() &&
1176      !SystemDictionary::is_platform_class_loader(class_loader) &&
1177      parsed_name != NULL &&
1178      !strncmp((const char*)parsed_name->bytes(), pkg, strlen(pkg))) {
1179    // It is illegal to define classes in the "java." package from
1180    // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
1181    ResourceMark rm(THREAD);
1182    TempNewSymbol pkg_name = InstanceKlass::package_from_name(parsed_name, CHECK_NULL);
1183    assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'");
1184    char* name = pkg_name->as_C_string();
1185    StringUtils::replace_no_expand(name, "/", ".");
1186    const char* msg_text = "Prohibited package name: ";
1187    size_t len = strlen(msg_text) + strlen(name) + 1;
1188    char* message = NEW_RESOURCE_ARRAY(char, len);
1189    jio_snprintf(message, len, "%s%s", msg_text, name);
1190    Exceptions::_throw_msg(THREAD_AND_LOCATION,
1191      vmSymbols::java_lang_SecurityException(), message);
1192  }
1193
1194  if (!HAS_PENDING_EXCEPTION) {
1195    assert(parsed_name != NULL, "Sanity");
1196    assert(class_name == NULL || class_name == parsed_name, "name mismatch");
1197    // Verification prevents us from creating names with dots in them, this
1198    // asserts that that's the case.
1199    assert(is_internal_format(parsed_name),
1200           "external class name format used internally");
1201
1202    // Add class just loaded
1203    // If a class loader supports parallel classloading handle parallel define requests
1204    // find_or_define_instance_class may return a different InstanceKlass
1205    if (is_parallelCapable(class_loader)) {
1206      k = find_or_define_instance_class(class_name, class_loader, k, THREAD);
1207    } else {
1208      define_instance_class(k, THREAD);
1209    }
1210  }
1211
1212  // Make sure we have an entry in the SystemDictionary on success
1213  debug_only( {
1214    if (!HAS_PENDING_EXCEPTION) {
1215      assert(parsed_name != NULL, "parsed_name is still null?");
1216      Symbol*  h_name    = k->name();
1217      ClassLoaderData *defining_loader_data = k->class_loader_data();
1218
1219      MutexLocker mu(SystemDictionary_lock, THREAD);
1220
1221      Klass* check = find_class(parsed_name, loader_data);
1222      assert(check == k(), "should be present in the dictionary");
1223
1224      Klass* check2 = find_class(h_name, defining_loader_data);
1225      assert(check == check2, "name inconsistancy in SystemDictionary");
1226    }
1227  } );
1228
1229  return k();
1230}
1231
1232#if INCLUDE_CDS
1233void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,
1234                                             int number_of_entries) {
1235  assert(length == _nof_buckets * sizeof(HashtableBucket<mtClass>),
1236         "bad shared dictionary size.");
1237  _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
1238}
1239
1240
1241// If there is a shared dictionary, then find the entry for the
1242// given shared system class, if any.
1243
1244Klass* SystemDictionary::find_shared_class(Symbol* class_name) {
1245  if (shared_dictionary() != NULL) {
1246    unsigned int d_hash = shared_dictionary()->compute_hash(class_name, NULL);
1247    int d_index = shared_dictionary()->hash_to_index(d_hash);
1248
1249    return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
1250  } else {
1251    return NULL;
1252  }
1253}
1254
1255
1256// Load a class from the shared spaces (found through the shared system
1257// dictionary).  Force the superclass and all interfaces to be loaded.
1258// Update the class definition to include sibling classes and no
1259// subclasses (yet).  [Classes in the shared space are not part of the
1260// object hierarchy until loaded.]
1261
1262instanceKlassHandle SystemDictionary::load_shared_class(
1263                 Symbol* class_name, Handle class_loader, TRAPS) {
1264  // Don't load shared class when JvmtiExport::should_post_class_file_load_hook()
1265  // is enabled since posting CFLH is not supported when loading shared class.
1266  if (!JvmtiExport::should_post_class_file_load_hook()) {
1267    instanceKlassHandle ik (THREAD, find_shared_class(class_name));
1268    // Make sure we only return the boot class for the NULL classloader.
1269    if (ik.not_null() &&
1270        ik->is_shared_boot_class() && class_loader.is_null()) {
1271      Handle protection_domain;
1272      return load_shared_class(ik, class_loader, protection_domain, THREAD);
1273    }
1274  }
1275  return instanceKlassHandle();
1276}
1277
1278// Check if a shared class can be loaded by the specific classloader:
1279//
1280// NULL classloader:
1281//   - Module class from "modules" jimage. ModuleEntry must be defined in the classloader.
1282//   - Class from -Xbootclasspath/a. The class has no defined PackageEntry, or must
1283//     be defined in an unnamed module.
1284bool SystemDictionary::is_shared_class_visible(Symbol* class_name,
1285                                               instanceKlassHandle ik,
1286                                               Handle class_loader, TRAPS) {
1287  ResourceMark rm;
1288  int path_index = ik->shared_classpath_index();
1289  SharedClassPathEntry* ent =
1290            (SharedClassPathEntry*)FileMapInfo::shared_classpath(path_index);
1291  if (!Universe::is_module_initialized()) {
1292    assert(ent->is_jrt(),
1293           "Loading non-bootstrap classes before the module system is initialized");
1294    assert(class_loader.is_null(), "sanity");
1295    return true;
1296  }
1297  // Get the pkg_entry from the classloader
1298  TempNewSymbol pkg_name = NULL;
1299  PackageEntry* pkg_entry = NULL;
1300  ModuleEntry* mod_entry = NULL;
1301  const char* pkg_string = NULL;
1302  ClassLoaderData* loader_data = class_loader_data(class_loader);
1303  pkg_name = InstanceKlass::package_from_name(class_name, CHECK_false);
1304  if (pkg_name != NULL) {
1305    pkg_string = pkg_name->as_C_string();
1306    if (loader_data != NULL) {
1307      pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1308    }
1309    if (pkg_entry != NULL) {
1310      mod_entry = pkg_entry->module();
1311    }
1312  }
1313
1314  if (class_loader.is_null()) {
1315    // The NULL classloader can load archived class originated from the
1316    // "modules" jimage and the -Xbootclasspath/a. For class from the
1317    // "modules" jimage, the PackageEntry/ModuleEntry must be defined
1318    // by the NULL classloader.
1319    if (mod_entry != NULL) {
1320      // PackageEntry/ModuleEntry is found in the classloader. Check if the
1321      // ModuleEntry's location agrees with the archived class' origination.
1322      if (ent->is_jrt() && mod_entry->location()->starts_with("jrt:")) {
1323        return true; // Module class from the "module" jimage
1324      }
1325    }
1326
1327    // If the archived class is not from the "module" jimage, the class can be
1328    // loaded by the NULL classloader if
1329    //
1330    // 1. the class is from the unamed package
1331    // 2. or, the class is not from a module defined in the NULL classloader
1332    // 3. or, the class is from an unamed module
1333    if (!ent->is_jrt() && ik->is_shared_boot_class()) {
1334      // the class is from the -Xbootclasspath/a
1335      if (pkg_string == NULL ||
1336          pkg_entry == NULL ||
1337          pkg_entry->in_unnamed_module()) {
1338        assert(mod_entry == NULL ||
1339               mod_entry == loader_data->modules()->unnamed_module(),
1340               "the unnamed module is not defined in the classloader");
1341        return true;
1342      }
1343    }
1344    return false;
1345  } else {
1346    bool res = SystemDictionaryShared::is_shared_class_visible_for_classloader(
1347              ik, class_loader, pkg_string, pkg_name,
1348              pkg_entry, mod_entry, CHECK_(false));
1349    return res;
1350  }
1351}
1352
1353instanceKlassHandle SystemDictionary::load_shared_class(instanceKlassHandle ik,
1354                                                        Handle class_loader,
1355                                                        Handle protection_domain, TRAPS) {
1356  instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1357  if (JvmtiExport::should_post_class_file_load_hook()) {
1358    // Don't load shared class when JvmtiExport::should_post_class_file_load_hook()
1359    // is enabled since posting CFLH is not supported when loading shared class.
1360    return nh;
1361  }
1362
1363  if (ik.not_null()) {
1364    Symbol* class_name = ik->name();
1365
1366    bool visible = is_shared_class_visible(
1367                            class_name, ik, class_loader, CHECK_(nh));
1368    if (!visible) {
1369      return nh;
1370    }
1371
1372    // Resolve the superclass and interfaces. They must be the same
1373    // as in dump time, because the layout of <ik> depends on
1374    // the specific layout of ik->super() and ik->local_interfaces().
1375    //
1376    // If unexpected superclass or interfaces are found, we cannot
1377    // load <ik> from the shared archive.
1378
1379    if (ik->super() != NULL) {
1380      Symbol*  cn = ik->super()->name();
1381      Klass *s = resolve_super_or_fail(class_name, cn,
1382                                       class_loader, protection_domain, true, CHECK_(nh));
1383      if (s != ik->super()) {
1384        // The dynamically resolved super class is not the same as the one we used during dump time,
1385        // so we cannot use ik.
1386        return nh;
1387      } else {
1388        assert(s->is_shared(), "must be");
1389      }
1390    }
1391
1392    Array<Klass*>* interfaces = ik->local_interfaces();
1393    int num_interfaces = interfaces->length();
1394    for (int index = 0; index < num_interfaces; index++) {
1395      Klass* k = interfaces->at(index);
1396
1397      // Note: can not use InstanceKlass::cast here because
1398      // interfaces' InstanceKlass's C++ vtbls haven't been
1399      // reinitialized yet (they will be once the interface classes
1400      // are loaded)
1401      Symbol*  name  = k->name();
1402      Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_(nh));
1403      if (k != i) {
1404        // The dynamically resolved interface class is not the same as the one we used during dump time,
1405        // so we cannot use ik.
1406        return nh;
1407      } else {
1408        assert(i->is_shared(), "must be");
1409      }
1410    }
1411
1412    // Adjust methods to recover missing data.  They need addresses for
1413    // interpreter entry points and their default native method address
1414    // must be reset.
1415
1416    // Updating methods must be done under a lock so multiple
1417    // threads don't update these in parallel
1418    //
1419    // Shared classes are all currently loaded by either the bootstrap or
1420    // internal parallel class loaders, so this will never cause a deadlock
1421    // on a custom class loader lock.
1422
1423    ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1424    {
1425      Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1426      check_loader_lock_contention(lockObject, THREAD);
1427      ObjectLocker ol(lockObject, THREAD, true);
1428      ik->restore_unshareable_info(loader_data, protection_domain, CHECK_(nh));
1429    }
1430
1431    if (log_is_enabled(Info, class, load)) {
1432      ik()->print_loading_log(LogLevel::Info, loader_data, NULL, NULL);
1433    }
1434    // No 'else' here as logging levels are not mutually exclusive
1435
1436    if (log_is_enabled(Debug, class, load)) {
1437      ik()->print_loading_log(LogLevel::Debug, loader_data, NULL, NULL);
1438    }
1439
1440    // For boot loader, ensure that GetSystemPackage knows that a class in this
1441    // package was loaded.
1442    if (class_loader.is_null()) {
1443      int path_index = ik->shared_classpath_index();
1444      ResourceMark rm;
1445      ClassLoader::add_package(ik->name()->as_C_string(), path_index, THREAD);
1446    }
1447
1448    if (DumpLoadedClassList != NULL && classlist_file->is_open()) {
1449      // Only dump the classes that can be stored into CDS archive
1450      if (SystemDictionaryShared::is_sharing_possible(loader_data)) {
1451        ResourceMark rm(THREAD);
1452        classlist_file->print_cr("%s", ik->name()->as_C_string());
1453        classlist_file->flush();
1454      }
1455    }
1456
1457    // notify a class loaded from shared object
1458    ClassLoadingService::notify_class_loaded(ik(), true /* shared class */);
1459  }
1460  return ik;
1461}
1462#endif // INCLUDE_CDS
1463
1464instanceKlassHandle SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {
1465  instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1466
1467  if (class_loader.is_null()) {
1468    ResourceMark rm;
1469    PackageEntry* pkg_entry = NULL;
1470    bool search_only_bootloader_append = false;
1471    ClassLoaderData *loader_data = class_loader_data(class_loader);
1472
1473    // Find the package in the boot loader's package entry table.
1474    TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_NULL);
1475    if (pkg_name != NULL) {
1476      pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1477    }
1478
1479    // Prior to attempting to load the class, enforce the boot loader's
1480    // visibility boundaries.
1481    if (!Universe::is_module_initialized()) {
1482      // During bootstrapping, prior to module initialization, any
1483      // class attempting to be loaded must be checked against the
1484      // java.base packages in the boot loader's PackageEntryTable.
1485      // No class outside of java.base is allowed to be loaded during
1486      // this bootstrapping window.
1487      if (!DumpSharedSpaces) {
1488        if (pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1489          // Class is either in the unnamed package or in
1490          // a named package within the unnamed module.  Either
1491          // case is outside of java.base, do not attempt to
1492          // load the class post java.base definition.  If
1493          // java.base has not been defined, let the class load
1494          // and its package will be checked later by
1495          // ModuleEntryTable::verify_javabase_packages.
1496          if (ModuleEntryTable::javabase_defined()) {
1497            return nh;
1498          }
1499        } else {
1500          // Check that the class' package is defined within java.base.
1501          ModuleEntry* mod_entry = pkg_entry->module();
1502          Symbol* mod_entry_name = mod_entry->name();
1503          if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) {
1504            return nh;
1505          }
1506        }
1507      }
1508    } else {
1509      assert(!DumpSharedSpaces, "Archive dumped after module system initialization");
1510      // After the module system has been initialized, check if the class'
1511      // package is in a module defined to the boot loader.
1512      if (pkg_name == NULL || pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1513        // Class is either in the unnamed package, in a named package
1514        // within a module not defined to the boot loader or in a
1515        // a named package within the unnamed module.  In all cases,
1516        // limit visibility to search for the class only in the boot
1517        // loader's append path.
1518        search_only_bootloader_append = true;
1519      }
1520    }
1521
1522    // Prior to bootstrapping's module initialization, never load a class outside
1523    // of the boot loader's module path
1524    assert(Universe::is_module_initialized() || DumpSharedSpaces ||
1525           !search_only_bootloader_append,
1526           "Attempt to load a class outside of boot loader's module path");
1527
1528    // Search the shared system dictionary for classes preloaded into the
1529    // shared spaces.
1530    instanceKlassHandle k;
1531    {
1532#if INCLUDE_CDS
1533      PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
1534      k = load_shared_class(class_name, class_loader, THREAD);
1535#endif
1536    }
1537
1538    if (k.is_null()) {
1539      // Use VM class loader
1540      PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
1541      k = ClassLoader::load_class(class_name, search_only_bootloader_append, CHECK_(nh));
1542    }
1543
1544    // find_or_define_instance_class may return a different InstanceKlass
1545    if (!k.is_null()) {
1546      k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
1547    }
1548    return k;
1549  } else {
1550    // Use user specified class loader to load class. Call loadClass operation on class_loader.
1551    ResourceMark rm(THREAD);
1552
1553    assert(THREAD->is_Java_thread(), "must be a JavaThread");
1554    JavaThread* jt = (JavaThread*) THREAD;
1555
1556    PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
1557                               ClassLoader::perf_app_classload_selftime(),
1558                               ClassLoader::perf_app_classload_count(),
1559                               jt->get_thread_stat()->perf_recursion_counts_addr(),
1560                               jt->get_thread_stat()->perf_timers_addr(),
1561                               PerfClassTraceTime::CLASS_LOAD);
1562
1563    Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
1564    // Translate to external class name format, i.e., convert '/' chars to '.'
1565    Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));
1566
1567    JavaValue result(T_OBJECT);
1568
1569    KlassHandle spec_klass (THREAD, SystemDictionary::ClassLoader_klass());
1570
1571    // Call public unsynchronized loadClass(String) directly for all class loaders
1572    // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will
1573    // acquire a class-name based lock rather than the class loader object lock.
1574    // JDK < 7 already acquire the class loader lock in loadClass(String, boolean),
1575    // so the call to loadClassInternal() was not required.
1576    //
1577    // UnsyncloadClass flag means both call loadClass(String) and do
1578    // not acquire the class loader lock even for class loaders that are
1579    // not parallelCapable. This was a risky transitional
1580    // flag for diagnostic purposes only. It is risky to call
1581    // custom class loaders without synchronization.
1582    // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
1583    // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.
1584    // Do NOT assume this will be supported in future releases.
1585    //
1586    // Added MustCallLoadClassInternal in case we discover in the field
1587    // a customer that counts on this call
1588    if (MustCallLoadClassInternal && has_loadClassInternal()) {
1589      JavaCalls::call_special(&result,
1590                              class_loader,
1591                              spec_klass,
1592                              vmSymbols::loadClassInternal_name(),
1593                              vmSymbols::string_class_signature(),
1594                              string,
1595                              CHECK_(nh));
1596    } else {
1597      JavaCalls::call_virtual(&result,
1598                              class_loader,
1599                              spec_klass,
1600                              vmSymbols::loadClass_name(),
1601                              vmSymbols::string_class_signature(),
1602                              string,
1603                              CHECK_(nh));
1604    }
1605
1606    assert(result.get_type() == T_OBJECT, "just checking");
1607    oop obj = (oop) result.get_jobject();
1608
1609    // Primitive classes return null since forName() can not be
1610    // used to obtain any of the Class objects representing primitives or void
1611    if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
1612      instanceKlassHandle k =
1613                instanceKlassHandle(THREAD, java_lang_Class::as_Klass(obj));
1614      // For user defined Java class loaders, check that the name returned is
1615      // the same as that requested.  This check is done for the bootstrap
1616      // loader when parsing the class file.
1617      if (class_name == k->name()) {
1618        return k;
1619      }
1620    }
1621    // Class is not found or has the wrong name, return NULL
1622    return nh;
1623  }
1624}
1625
1626void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {
1627
1628  ClassLoaderData* loader_data = k->class_loader_data();
1629  Handle class_loader_h(THREAD, loader_data->class_loader());
1630
1631 // for bootstrap and other parallel classloaders don't acquire lock,
1632 // use placeholder token
1633 // If a parallelCapable class loader calls define_instance_class instead of
1634 // find_or_define_instance_class to get here, we have a timing
1635 // hole with systemDictionary updates and check_constraints
1636 if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1637    assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1638         compute_loader_lock_object(class_loader_h, THREAD)),
1639         "define called without lock");
1640  }
1641
1642  // Check class-loading constraints. Throw exception if violation is detected.
1643  // Grabs and releases SystemDictionary_lock
1644  // The check_constraints/find_class call and update_dictionary sequence
1645  // must be "atomic" for a specific class/classloader pair so we never
1646  // define two different instanceKlasses for that class/classloader pair.
1647  // Existing classloaders will call define_instance_class with the
1648  // classloader lock held
1649  // Parallel classloaders will call find_or_define_instance_class
1650  // which will require a token to perform the define class
1651  Symbol*  name_h = k->name();
1652  unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
1653  int d_index = dictionary()->hash_to_index(d_hash);
1654  check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
1655
1656  // Register class just loaded with class loader (placed in Vector)
1657  // Note we do this before updating the dictionary, as this can
1658  // fail with an OutOfMemoryError (if it does, we will *not* put this
1659  // class in the dictionary and will not update the class hierarchy).
1660  // JVMTI FollowReferences needs to find the classes this way.
1661  if (k->class_loader() != NULL) {
1662    methodHandle m(THREAD, Universe::loader_addClass_method());
1663    JavaValue result(T_VOID);
1664    JavaCallArguments args(class_loader_h);
1665    args.push_oop(Handle(THREAD, k->java_mirror()));
1666    JavaCalls::call(&result, m, &args, CHECK);
1667  }
1668
1669  // Add the new class. We need recompile lock during update of CHA.
1670  {
1671    unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1672    int p_index = placeholders()->hash_to_index(p_hash);
1673
1674    MutexLocker mu_r(Compile_lock, THREAD);
1675
1676    // Add to class hierarchy, initialize vtables, and do possible
1677    // deoptimizations.
1678    add_to_hierarchy(k, CHECK); // No exception, but can block
1679
1680    // Add to systemDictionary - so other classes can see it.
1681    // Grabs and releases SystemDictionary_lock
1682    update_dictionary(d_index, d_hash, p_index, p_hash,
1683                      k, class_loader_h, THREAD);
1684  }
1685  k->eager_initialize(THREAD);
1686
1687  // notify jvmti
1688  if (JvmtiExport::should_post_class_load()) {
1689      assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1690      JvmtiExport::post_class_load((JavaThread *) THREAD, k());
1691
1692  }
1693  TRACE_KLASS_DEFINITION(k, THREAD);
1694  class_define_event(k);
1695}
1696
1697// Support parallel classloading
1698// All parallel class loaders, including bootstrap classloader
1699// lock a placeholder entry for this class/class_loader pair
1700// to allow parallel defines of different classes for this class loader
1701// With AllowParallelDefine flag==true, in case they do not synchronize around
1702// FindLoadedClass/DefineClass, calls, we check for parallel
1703// loading for them, wait if a defineClass is in progress
1704// and return the initial requestor's results
1705// This flag does not apply to the bootstrap classloader.
1706// With AllowParallelDefine flag==false, call through to define_instance_class
1707// which will throw LinkageError: duplicate class definition.
1708// False is the requested default.
1709// For better performance, the class loaders should synchronize
1710// findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1711// potentially waste time reading and parsing the bytestream.
1712// Note: VM callers should ensure consistency of k/class_name,class_loader
1713instanceKlassHandle SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
1714
1715  instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1716  Symbol*  name_h = k->name(); // passed in class_name may be null
1717  ClassLoaderData* loader_data = class_loader_data(class_loader);
1718
1719  unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
1720  int d_index = dictionary()->hash_to_index(d_hash);
1721
1722// Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1723  unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1724  int p_index = placeholders()->hash_to_index(p_hash);
1725  PlaceholderEntry* probe;
1726
1727  {
1728    MutexLocker mu(SystemDictionary_lock, THREAD);
1729    // First check if class already defined
1730    if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
1731      Klass* check = find_class(d_index, d_hash, name_h, loader_data);
1732      if (check != NULL) {
1733        return(instanceKlassHandle(THREAD, check));
1734      }
1735    }
1736
1737    // Acquire define token for this class/classloader
1738    probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1739    // Wait if another thread defining in parallel
1740    // All threads wait - even those that will throw duplicate class: otherwise
1741    // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1742    // if other thread has not finished updating dictionary
1743    while (probe->definer() != NULL) {
1744      SystemDictionary_lock->wait();
1745    }
1746    // Only special cases allow parallel defines and can use other thread's results
1747    // Other cases fall through, and may run into duplicate defines
1748    // caught by finding an entry in the SystemDictionary
1749    if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
1750        placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1751        SystemDictionary_lock->notify_all();
1752#ifdef ASSERT
1753        Klass* check = find_class(d_index, d_hash, name_h, loader_data);
1754        assert(check != NULL, "definer missed recording success");
1755#endif
1756        return(instanceKlassHandle(THREAD, probe->instance_klass()));
1757    } else {
1758      // This thread will define the class (even if earlier thread tried and had an error)
1759      probe->set_definer(THREAD);
1760    }
1761  }
1762
1763  define_instance_class(k, THREAD);
1764
1765  Handle linkage_exception = Handle(); // null handle
1766
1767  // definer must notify any waiting threads
1768  {
1769    MutexLocker mu(SystemDictionary_lock, THREAD);
1770    PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
1771    assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1772    if (probe != NULL) {
1773      if (HAS_PENDING_EXCEPTION) {
1774        linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1775        CLEAR_PENDING_EXCEPTION;
1776      } else {
1777        probe->set_instance_klass(k());
1778      }
1779      probe->set_definer(NULL);
1780      placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1781      SystemDictionary_lock->notify_all();
1782    }
1783  }
1784
1785  // Can't throw exception while holding lock due to rank ordering
1786  if (linkage_exception() != NULL) {
1787    THROW_OOP_(linkage_exception(), nh); // throws exception and returns
1788  }
1789
1790  return k;
1791}
1792Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1793  // If class_loader is NULL we synchronize on _system_loader_lock_obj
1794  if (class_loader.is_null()) {
1795    return Handle(THREAD, _system_loader_lock_obj);
1796  } else {
1797    return class_loader;
1798  }
1799}
1800
1801// This method is added to check how often we have to wait to grab loader
1802// lock. The results are being recorded in the performance counters defined in
1803// ClassLoader::_sync_systemLoaderLockContentionRate and
1804// ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1805void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1806  if (!UsePerfData) {
1807    return;
1808  }
1809
1810  assert(!loader_lock.is_null(), "NULL lock object");
1811
1812  if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1813      == ObjectSynchronizer::owner_other) {
1814    // contention will likely happen, so increment the corresponding
1815    // contention counter.
1816    if (loader_lock() == _system_loader_lock_obj) {
1817      ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1818    } else {
1819      ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1820    }
1821  }
1822}
1823
1824// ----------------------------------------------------------------------------
1825// Lookup
1826
1827Klass* SystemDictionary::find_class(int index, unsigned int hash,
1828                                      Symbol* class_name,
1829                                      ClassLoaderData* loader_data) {
1830  assert_locked_or_safepoint(SystemDictionary_lock);
1831  assert (index == dictionary()->index_for(class_name, loader_data),
1832          "incorrect index?");
1833
1834  Klass* k = dictionary()->find_class(index, hash, class_name, loader_data);
1835  return k;
1836}
1837
1838
1839// Basic find on classes in the midst of being loaded
1840Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1841                                           ClassLoaderData* loader_data) {
1842  assert_locked_or_safepoint(SystemDictionary_lock);
1843  unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);
1844  int p_index = placeholders()->hash_to_index(p_hash);
1845  return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
1846}
1847
1848
1849// Used for assertions and verification only
1850Klass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
1851  #ifndef ASSERT
1852  guarantee(VerifyBeforeGC      ||
1853            VerifyDuringGC      ||
1854            VerifyBeforeExit    ||
1855            VerifyDuringStartup ||
1856            VerifyAfterGC, "too expensive");
1857  #endif
1858  assert_locked_or_safepoint(SystemDictionary_lock);
1859
1860  // First look in the loaded class array
1861  unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
1862  int d_index = dictionary()->hash_to_index(d_hash);
1863  return find_class(d_index, d_hash, class_name, loader_data);
1864}
1865
1866
1867// Get the next class in the dictionary.
1868Klass* SystemDictionary::try_get_next_class() {
1869  return dictionary()->try_get_next_class();
1870}
1871
1872
1873// ----------------------------------------------------------------------------
1874// Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1875// is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1876// before a new class is used.
1877
1878void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
1879  assert(k.not_null(), "just checking");
1880  assert_locked_or_safepoint(Compile_lock);
1881
1882  // Link into hierachy. Make sure the vtables are initialized before linking into
1883  k->append_to_sibling_list();                    // add to superklass/sibling list
1884  k->process_interfaces(THREAD);                  // handle all "implements" declarations
1885  k->set_init_state(InstanceKlass::loaded);
1886  // Now flush all code that depended on old class hierarchy.
1887  // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1888  // Also, first reinitialize vtable because it may have gotten out of synch
1889  // while the new class wasn't connected to the class hierarchy.
1890  CodeCache::flush_dependents_on(k);
1891}
1892
1893// ----------------------------------------------------------------------------
1894// GC support
1895
1896// Following roots during mark-sweep is separated in two phases.
1897//
1898// The first phase follows preloaded classes and all other system
1899// classes, since these will never get unloaded anyway.
1900//
1901// The second phase removes (unloads) unreachable classes from the
1902// system dictionary and follows the remaining classes' contents.
1903
1904void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
1905  roots_oops_do(blk, NULL);
1906}
1907
1908void SystemDictionary::always_strong_classes_do(KlassClosure* closure) {
1909  // Follow all system classes and temporary placeholders in dictionary
1910  dictionary()->always_strong_classes_do(closure);
1911
1912  // Placeholders. These represent classes we're actively loading.
1913  placeholders()->classes_do(closure);
1914}
1915
1916// Calculate a "good" systemdictionary size based
1917// on predicted or current loaded classes count
1918int SystemDictionary::calculate_systemdictionary_size(int classcount) {
1919  int newsize = _old_default_sdsize;
1920  if ((classcount > 0)  && !DumpSharedSpaces) {
1921    int desiredsize = classcount/_average_depth_goal;
1922    for (newsize = _primelist[_sdgeneration]; _sdgeneration < _prime_array_size -1;
1923         newsize = _primelist[++_sdgeneration]) {
1924      if (desiredsize <=  newsize) {
1925        break;
1926      }
1927    }
1928  }
1929  return newsize;
1930}
1931
1932#ifdef ASSERT
1933class VerifySDReachableAndLiveClosure : public OopClosure {
1934private:
1935  BoolObjectClosure* _is_alive;
1936
1937  template <class T> void do_oop_work(T* p) {
1938    oop obj = oopDesc::load_decode_heap_oop(p);
1939    guarantee(_is_alive->do_object_b(obj), "Oop in system dictionary must be live");
1940  }
1941
1942public:
1943  VerifySDReachableAndLiveClosure(BoolObjectClosure* is_alive) : OopClosure(), _is_alive(is_alive) { }
1944
1945  virtual void do_oop(oop* p)       { do_oop_work(p); }
1946  virtual void do_oop(narrowOop* p) { do_oop_work(p); }
1947};
1948#endif
1949
1950// Assumes classes in the SystemDictionary are only unloaded at a safepoint
1951// Note: anonymous classes are not in the SD.
1952bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive,
1953                                    bool clean_previous_versions) {
1954  // First, mark for unload all ClassLoaderData referencing a dead class loader.
1955  bool unloading_occurred = ClassLoaderDataGraph::do_unloading(is_alive,
1956                                                               clean_previous_versions);
1957  if (unloading_occurred) {
1958    dictionary()->do_unloading();
1959    constraints()->purge_loader_constraints();
1960    resolution_errors()->purge_resolution_errors();
1961  }
1962  // Oops referenced by the system dictionary may get unreachable independently
1963  // of the class loader (eg. cached protection domain oops). So we need to
1964  // explicitly unlink them here instead of in Dictionary::do_unloading.
1965  dictionary()->unlink(is_alive);
1966#ifdef ASSERT
1967  VerifySDReachableAndLiveClosure cl(is_alive);
1968  dictionary()->oops_do(&cl);
1969#endif
1970  return unloading_occurred;
1971}
1972
1973void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
1974  strong->do_oop(&_java_system_loader);
1975  strong->do_oop(&_system_loader_lock_obj);
1976  CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);)
1977
1978  // Adjust dictionary
1979  dictionary()->roots_oops_do(strong, weak);
1980
1981  // Visit extra methods
1982  invoke_method_table()->oops_do(strong);
1983}
1984
1985void SystemDictionary::oops_do(OopClosure* f) {
1986  f->do_oop(&_java_system_loader);
1987  f->do_oop(&_system_loader_lock_obj);
1988  CDS_ONLY(SystemDictionaryShared::oops_do(f);)
1989
1990  // Adjust dictionary
1991  dictionary()->oops_do(f);
1992
1993  // Visit extra methods
1994  invoke_method_table()->oops_do(f);
1995}
1996
1997// Extended Class redefinition support.
1998// If one of these classes is replaced, we need to replace it in these places.
1999// KlassClosure::do_klass should take the address of a class but we can
2000// change that later.
2001void SystemDictionary::preloaded_classes_do(KlassClosure* f) {
2002  for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {
2003    f->do_klass(_well_known_klasses[k]);
2004  }
2005
2006  {
2007    for (int i = 0; i < T_VOID+1; i++) {
2008      if (_box_klasses[i] != NULL) {
2009        assert(i >= T_BOOLEAN, "checking");
2010        f->do_klass(_box_klasses[i]);
2011      }
2012    }
2013  }
2014
2015  FilteredFieldsMap::classes_do(f);
2016}
2017
2018void SystemDictionary::lazily_loaded_classes_do(KlassClosure* f) {
2019  f->do_klass(_abstract_ownable_synchronizer_klass);
2020}
2021
2022// Just the classes from defining class loaders
2023// Don't iterate over placeholders
2024void SystemDictionary::classes_do(void f(Klass*)) {
2025  dictionary()->classes_do(f);
2026}
2027
2028// Added for initialize_itable_for_klass
2029//   Just the classes from defining class loaders
2030// Don't iterate over placeholders
2031void SystemDictionary::classes_do(void f(Klass*, TRAPS), TRAPS) {
2032  dictionary()->classes_do(f, CHECK);
2033}
2034
2035//   All classes, and their class loaders
2036// Don't iterate over placeholders
2037void SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*)) {
2038  dictionary()->classes_do(f);
2039}
2040
2041void SystemDictionary::placeholders_do(void f(Symbol*)) {
2042  placeholders()->entries_do(f);
2043}
2044
2045void SystemDictionary::methods_do(void f(Method*)) {
2046  dictionary()->methods_do(f);
2047  invoke_method_table()->methods_do(f);
2048}
2049
2050void SystemDictionary::remove_classes_in_error_state() {
2051  dictionary()->remove_classes_in_error_state();
2052}
2053
2054// ----------------------------------------------------------------------------
2055// Lazily load klasses
2056
2057void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
2058  // if multiple threads calling this function, only one thread will load
2059  // the class.  The other threads will find the loaded version once the
2060  // class is loaded.
2061  Klass* aos = _abstract_ownable_synchronizer_klass;
2062  if (aos == NULL) {
2063    Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
2064    // Force a fence to prevent any read before the write completes
2065    OrderAccess::fence();
2066    _abstract_ownable_synchronizer_klass = InstanceKlass::cast(k);
2067  }
2068}
2069
2070// ----------------------------------------------------------------------------
2071// Initialization
2072
2073void SystemDictionary::initialize(TRAPS) {
2074  // Allocate arrays
2075  assert(dictionary() == NULL,
2076         "SystemDictionary should only be initialized once");
2077  _sdgeneration        = 0;
2078  _dictionary          = new Dictionary(calculate_systemdictionary_size(PredictedLoadedClassCount));
2079  _placeholders        = new PlaceholderTable(_nof_buckets);
2080  _number_of_modifications = 0;
2081  _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
2082  _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
2083  _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
2084
2085  // Allocate private object used as system class loader lock
2086  _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
2087  // Initialize basic classes
2088  initialize_preloaded_classes(CHECK);
2089}
2090
2091// Compact table of directions on the initialization of klasses:
2092static const short wk_init_info[] = {
2093  #define WK_KLASS_INIT_INFO(name, symbol, option) \
2094    ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
2095          << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
2096      | (int)SystemDictionary::option ),
2097  WK_KLASSES_DO(WK_KLASS_INIT_INFO)
2098  #undef WK_KLASS_INIT_INFO
2099  0
2100};
2101
2102bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
2103  assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
2104  int  info = wk_init_info[id - FIRST_WKID];
2105  int  sid  = (info >> CEIL_LG_OPTION_LIMIT);
2106  Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
2107  InstanceKlass** klassp = &_well_known_klasses[id];
2108
2109  bool must_load;
2110#if INCLUDE_JVMCI
2111  if (EnableJVMCI) {
2112    // If JVMCI is enabled we require its classes to be found.
2113    must_load = (init_opt < SystemDictionary::Opt) || (init_opt == SystemDictionary::Jvmci);
2114  } else
2115#endif
2116  {
2117    must_load = (init_opt < SystemDictionary::Opt);
2118  }
2119
2120  if ((*klassp) == NULL) {
2121    Klass* k;
2122    if (must_load) {
2123      k = resolve_or_fail(symbol, true, CHECK_0); // load required class
2124    } else {
2125      k = resolve_or_null(symbol,       CHECK_0); // load optional klass
2126    }
2127    (*klassp) = (k == NULL) ? NULL : InstanceKlass::cast(k);
2128  }
2129  return ((*klassp) != NULL);
2130}
2131
2132void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
2133  assert((int)start_id <= (int)limit_id, "IDs are out of order!");
2134  for (int id = (int)start_id; id < (int)limit_id; id++) {
2135    assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
2136    int info = wk_init_info[id - FIRST_WKID];
2137    int sid  = (info >> CEIL_LG_OPTION_LIMIT);
2138    int opt  = (info & right_n_bits(CEIL_LG_OPTION_LIMIT));
2139
2140    initialize_wk_klass((WKID)id, opt, CHECK);
2141  }
2142
2143  // move the starting value forward to the limit:
2144  start_id = limit_id;
2145}
2146
2147void SystemDictionary::initialize_preloaded_classes(TRAPS) {
2148  assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once");
2149
2150  // Create the ModuleEntry for java.base.  This call needs to be done here,
2151  // after vmSymbols::initialize() is called but before any classes are pre-loaded.
2152  ClassLoader::create_javabase();
2153
2154  // Preload commonly used klasses
2155  WKID scan = FIRST_WKID;
2156  // first do Object, then String, Class
2157  if (UseSharedSpaces) {
2158    initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK);
2159    // Initialize the constant pool for the Object_class
2160    InstanceKlass* ik = InstanceKlass::cast(Object_klass());
2161    ik->constants()->restore_unshareable_info(CHECK);
2162    initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
2163  } else {
2164    initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
2165  }
2166
2167  // Calculate offsets for String and Class classes since they are loaded and
2168  // can be used after this point.
2169  java_lang_String::compute_offsets();
2170  java_lang_Class::compute_offsets();
2171
2172  // Fixup mirrors for classes loaded before java.lang.Class.
2173  // These calls iterate over the objects currently in the perm gen
2174  // so calling them at this point is matters (not before when there
2175  // are fewer objects and not later after there are more objects
2176  // in the perm gen.
2177  Universe::initialize_basic_type_mirrors(CHECK);
2178  Universe::fixup_mirrors(CHECK);
2179
2180  // do a bunch more:
2181  initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);
2182
2183  // Preload ref klasses and set reference types
2184  InstanceKlass::cast(WK_KLASS(Reference_klass))->set_reference_type(REF_OTHER);
2185  InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass));
2186
2187  initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(PhantomReference_klass), scan, CHECK);
2188  InstanceKlass::cast(WK_KLASS(SoftReference_klass))->set_reference_type(REF_SOFT);
2189  InstanceKlass::cast(WK_KLASS(WeakReference_klass))->set_reference_type(REF_WEAK);
2190  InstanceKlass::cast(WK_KLASS(FinalReference_klass))->set_reference_type(REF_FINAL);
2191  InstanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM);
2192
2193  // JSR 292 classes
2194  WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
2195  WKID jsr292_group_end   = WK_KLASS_ENUM_NAME(VolatileCallSite_klass);
2196  initialize_wk_klasses_until(jsr292_group_start, scan, CHECK);
2197  initialize_wk_klasses_through(jsr292_group_end, scan, CHECK);
2198  initialize_wk_klasses_until(NOT_JVMCI(WKID_LIMIT) JVMCI_ONLY(FIRST_JVMCI_WKID), scan, CHECK);
2199
2200  _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass);
2201  _box_klasses[T_CHAR]    = WK_KLASS(Character_klass);
2202  _box_klasses[T_FLOAT]   = WK_KLASS(Float_klass);
2203  _box_klasses[T_DOUBLE]  = WK_KLASS(Double_klass);
2204  _box_klasses[T_BYTE]    = WK_KLASS(Byte_klass);
2205  _box_klasses[T_SHORT]   = WK_KLASS(Short_klass);
2206  _box_klasses[T_INT]     = WK_KLASS(Integer_klass);
2207  _box_klasses[T_LONG]    = WK_KLASS(Long_klass);
2208  //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
2209  //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);
2210
2211  { // Compute whether we should use loadClass or loadClassInternal when loading classes.
2212    Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
2213    _has_loadClassInternal = (method != NULL);
2214  }
2215  { // Compute whether we should use checkPackageAccess or NOT
2216    Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
2217    _has_checkPackageAccess = (method != NULL);
2218  }
2219}
2220
2221// Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
2222// If so, returns the basic type it holds.  If not, returns T_OBJECT.
2223BasicType SystemDictionary::box_klass_type(Klass* k) {
2224  assert(k != NULL, "");
2225  for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
2226    if (_box_klasses[i] == k)
2227      return (BasicType)i;
2228  }
2229  return T_OBJECT;
2230}
2231
2232// Constraints on class loaders. The details of the algorithm can be
2233// found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
2234// Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
2235// that the system dictionary needs to maintain a set of contraints that
2236// must be satisfied by all classes in the dictionary.
2237// if defining is true, then LinkageError if already in systemDictionary
2238// if initiating loader, then ok if InstanceKlass matches existing entry
2239
2240void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
2241                                         instanceKlassHandle k,
2242                                         Handle class_loader, bool defining,
2243                                         TRAPS) {
2244  const char *linkage_error1 = NULL;
2245  const char *linkage_error2 = NULL;
2246  {
2247    Symbol*  name  = k->name();
2248    ClassLoaderData *loader_data = class_loader_data(class_loader);
2249
2250    MutexLocker mu(SystemDictionary_lock, THREAD);
2251
2252    Klass* check = find_class(d_index, d_hash, name, loader_data);
2253    if (check != (Klass*)NULL) {
2254      // if different InstanceKlass - duplicate class definition,
2255      // else - ok, class loaded by a different thread in parallel,
2256      // we should only have found it if it was done loading and ok to use
2257      // system dictionary only holds instance classes, placeholders
2258      // also holds array classes
2259
2260      assert(check->is_instance_klass(), "noninstance in systemdictionary");
2261      if ((defining == true) || (k() != check)) {
2262        linkage_error1 = "loader (instance of  ";
2263        linkage_error2 = "): attempted  duplicate class definition for name: \"";
2264      } else {
2265        return;
2266      }
2267    }
2268
2269#ifdef ASSERT
2270    Symbol* ph_check = find_placeholder(name, loader_data);
2271    assert(ph_check == NULL || ph_check == name, "invalid symbol");
2272#endif
2273
2274    if (linkage_error1 == NULL) {
2275      if (constraints()->check_or_update(k, class_loader, name) == false) {
2276        linkage_error1 = "loader constraint violation: loader (instance of ";
2277        linkage_error2 = ") previously initiated loading for a different type with name \"";
2278      }
2279    }
2280  }
2281
2282  // Throw error now if needed (cannot throw while holding
2283  // SystemDictionary_lock because of rank ordering)
2284
2285  if (linkage_error1) {
2286    ResourceMark rm(THREAD);
2287    const char* class_loader_name = loader_name(class_loader());
2288    char* type_name = k->name()->as_C_string();
2289    size_t buflen = strlen(linkage_error1) + strlen(class_loader_name) +
2290      strlen(linkage_error2) + strlen(type_name) + 2; // +2 for '"' and null byte.
2291    char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
2292    jio_snprintf(buf, buflen, "%s%s%s%s\"", linkage_error1, class_loader_name, linkage_error2, type_name);
2293    THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
2294  }
2295}
2296
2297
2298// Update system dictionary - done after check_constraint and add_to_hierachy
2299// have been called.
2300void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
2301                                         int p_index, unsigned int p_hash,
2302                                         instanceKlassHandle k,
2303                                         Handle class_loader,
2304                                         TRAPS) {
2305  // Compile_lock prevents systemDictionary updates during compilations
2306  assert_locked_or_safepoint(Compile_lock);
2307  Symbol*  name  = k->name();
2308  ClassLoaderData *loader_data = class_loader_data(class_loader);
2309
2310  {
2311  MutexLocker mu1(SystemDictionary_lock, THREAD);
2312
2313  // See whether biased locking is enabled and if so set it for this
2314  // klass.
2315  // Note that this must be done past the last potential blocking
2316  // point / safepoint. We enable biased locking lazily using a
2317  // VM_Operation to iterate the SystemDictionary and installing the
2318  // biasable mark word into each InstanceKlass's prototype header.
2319  // To avoid race conditions where we accidentally miss enabling the
2320  // optimization for one class in the process of being added to the
2321  // dictionary, we must not safepoint after the test of
2322  // BiasedLocking::enabled().
2323  if (UseBiasedLocking && BiasedLocking::enabled()) {
2324    // Set biased locking bit for all loaded classes; it will be
2325    // cleared if revocation occurs too often for this type
2326    // NOTE that we must only do this when the class is initally
2327    // defined, not each time it is referenced from a new class loader
2328    if (k->class_loader() == class_loader()) {
2329      k->set_prototype_header(markOopDesc::biased_locking_prototype());
2330    }
2331  }
2332
2333  // Make a new system dictionary entry.
2334  Klass* sd_check = find_class(d_index, d_hash, name, loader_data);
2335  if (sd_check == NULL) {
2336    dictionary()->add_klass(name, loader_data, k);
2337    notice_modification();
2338  }
2339#ifdef ASSERT
2340  sd_check = find_class(d_index, d_hash, name, loader_data);
2341  assert (sd_check != NULL, "should have entry in system dictionary");
2342  // Note: there may be a placeholder entry: for circularity testing
2343  // or for parallel defines
2344#endif
2345    SystemDictionary_lock->notify_all();
2346  }
2347}
2348
2349
2350// Try to find a class name using the loader constraints.  The
2351// loader constraints might know about a class that isn't fully loaded
2352// yet and these will be ignored.
2353Klass* SystemDictionary::find_constrained_instance_or_array_klass(
2354                    Symbol* class_name, Handle class_loader, TRAPS) {
2355
2356  // First see if it has been loaded directly.
2357  // Force the protection domain to be null.  (This removes protection checks.)
2358  Handle no_protection_domain;
2359  Klass* klass = find_instance_or_array_klass(class_name, class_loader,
2360                                              no_protection_domain, CHECK_NULL);
2361  if (klass != NULL)
2362    return klass;
2363
2364  // Now look to see if it has been loaded elsewhere, and is subject to
2365  // a loader constraint that would require this loader to return the
2366  // klass that is already loaded.
2367  if (FieldType::is_array(class_name)) {
2368    // For array classes, their Klass*s are not kept in the
2369    // constraint table. The element Klass*s are.
2370    FieldArrayInfo fd;
2371    BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
2372    if (t != T_OBJECT) {
2373      klass = Universe::typeArrayKlassObj(t);
2374    } else {
2375      MutexLocker mu(SystemDictionary_lock, THREAD);
2376      klass = constraints()->find_constrained_klass(fd.object_key(), class_loader);
2377    }
2378    // If element class already loaded, allocate array klass
2379    if (klass != NULL) {
2380      klass = klass->array_klass_or_null(fd.dimension());
2381    }
2382  } else {
2383    MutexLocker mu(SystemDictionary_lock, THREAD);
2384    // Non-array classes are easy: simply check the constraint table.
2385    klass = constraints()->find_constrained_klass(class_name, class_loader);
2386  }
2387
2388  return klass;
2389}
2390
2391
2392bool SystemDictionary::add_loader_constraint(Symbol* class_name,
2393                                             Handle class_loader1,
2394                                             Handle class_loader2,
2395                                             Thread* THREAD) {
2396  ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
2397  ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
2398
2399  Symbol* constraint_name = NULL;
2400  if (!FieldType::is_array(class_name)) {
2401    constraint_name = class_name;
2402  } else {
2403    // For array classes, their Klass*s are not kept in the
2404    // constraint table. The element classes are.
2405    FieldArrayInfo fd;
2406    BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
2407    // primitive types always pass
2408    if (t != T_OBJECT) {
2409      return true;
2410    } else {
2411      constraint_name = fd.object_key();
2412    }
2413  }
2414  unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);
2415  int d_index1 = dictionary()->hash_to_index(d_hash1);
2416
2417  unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);
2418  int d_index2 = dictionary()->hash_to_index(d_hash2);
2419  {
2420  MutexLocker mu_s(SystemDictionary_lock, THREAD);
2421
2422  // Better never do a GC while we're holding these oops
2423  NoSafepointVerifier nosafepoint;
2424
2425  Klass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1);
2426  Klass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2);
2427  return constraints()->add_entry(constraint_name, klass1, class_loader1,
2428                                  klass2, class_loader2);
2429  }
2430}
2431
2432// Add entry to resolution error table to record the error when the first
2433// attempt to resolve a reference to a class has failed.
2434void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
2435                                            Symbol* error, Symbol* message) {
2436  unsigned int hash = resolution_errors()->compute_hash(pool, which);
2437  int index = resolution_errors()->hash_to_index(hash);
2438  {
2439    MutexLocker ml(SystemDictionary_lock, Thread::current());
2440    resolution_errors()->add_entry(index, hash, pool, which, error, message);
2441  }
2442}
2443
2444// Delete a resolution error for RedefineClasses for a constant pool is going away
2445void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
2446  resolution_errors()->delete_entry(pool);
2447}
2448
2449// Lookup resolution error table. Returns error if found, otherwise NULL.
2450Symbol* SystemDictionary::find_resolution_error(const constantPoolHandle& pool, int which,
2451                                                Symbol** message) {
2452  unsigned int hash = resolution_errors()->compute_hash(pool, which);
2453  int index = resolution_errors()->hash_to_index(hash);
2454  {
2455    MutexLocker ml(SystemDictionary_lock, Thread::current());
2456    ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2457    if (entry != NULL) {
2458      *message = entry->message();
2459      return entry->error();
2460    } else {
2461      return NULL;
2462    }
2463  }
2464}
2465
2466
2467// Signature constraints ensure that callers and callees agree about
2468// the meaning of type names in their signatures.  This routine is the
2469// intake for constraints.  It collects them from several places:
2470//
2471//  * LinkResolver::resolve_method (if check_access is true) requires
2472//    that the resolving class (the caller) and the defining class of
2473//    the resolved method (the callee) agree on each type in the
2474//    method's signature.
2475//
2476//  * LinkResolver::resolve_interface_method performs exactly the same
2477//    checks.
2478//
2479//  * LinkResolver::resolve_field requires that the constant pool
2480//    attempting to link to a field agree with the field's defining
2481//    class about the type of the field signature.
2482//
2483//  * klassVtable::initialize_vtable requires that, when a class
2484//    overrides a vtable entry allocated by a superclass, that the
2485//    overriding method (i.e., the callee) agree with the superclass
2486//    on each type in the method's signature.
2487//
2488//  * klassItable::initialize_itable requires that, when a class fills
2489//    in its itables, for each non-abstract method installed in an
2490//    itable, the method (i.e., the callee) agree with the interface
2491//    on each type in the method's signature.
2492//
2493// All those methods have a boolean (check_access, checkconstraints)
2494// which turns off the checks.  This is used from specialized contexts
2495// such as bootstrapping, dumping, and debugging.
2496//
2497// No direct constraint is placed between the class and its
2498// supertypes.  Constraints are only placed along linked relations
2499// between callers and callees.  When a method overrides or implements
2500// an abstract method in a supertype (superclass or interface), the
2501// constraints are placed as if the supertype were the caller to the
2502// overriding method.  (This works well, since callers to the
2503// supertype have already established agreement between themselves and
2504// the supertype.)  As a result of all this, a class can disagree with
2505// its supertype about the meaning of a type name, as long as that
2506// class neither calls a relevant method of the supertype, nor is
2507// called (perhaps via an override) from the supertype.
2508//
2509//
2510// SystemDictionary::check_signature_loaders(sig, l1, l2)
2511//
2512// Make sure all class components (including arrays) in the given
2513// signature will be resolved to the same class in both loaders.
2514// Returns the name of the type that failed a loader constraint check, or
2515// NULL if no constraint failed.  No exception except OOME is thrown.
2516// Arrays are not added to the loader constraint table, their elements are.
2517Symbol* SystemDictionary::check_signature_loaders(Symbol* signature,
2518                                               Handle loader1, Handle loader2,
2519                                               bool is_method, TRAPS)  {
2520  // Nothing to do if loaders are the same.
2521  if (loader1() == loader2()) {
2522    return NULL;
2523  }
2524
2525  SignatureStream sig_strm(signature, is_method);
2526  while (!sig_strm.is_done()) {
2527    if (sig_strm.is_object()) {
2528      Symbol* sig = sig_strm.as_symbol(CHECK_NULL);
2529      if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
2530        return sig;
2531      }
2532    }
2533    sig_strm.next();
2534  }
2535  return NULL;
2536}
2537
2538
2539methodHandle SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid,
2540                                                            Symbol* signature,
2541                                                            TRAPS) {
2542  methodHandle empty;
2543  assert(MethodHandles::is_signature_polymorphic(iid) &&
2544         MethodHandles::is_signature_polymorphic_intrinsic(iid) &&
2545         iid != vmIntrinsics::_invokeGeneric,
2546         "must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid));
2547
2548  unsigned int hash  = invoke_method_table()->compute_hash(signature, iid);
2549  int          index = invoke_method_table()->hash_to_index(hash);
2550  SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2551  methodHandle m;
2552  if (spe == NULL || spe->method() == NULL) {
2553    spe = NULL;
2554    // Must create lots of stuff here, but outside of the SystemDictionary lock.
2555    m = Method::make_method_handle_intrinsic(iid, signature, CHECK_(empty));
2556    if (!Arguments::is_interpreter_only()) {
2557      // Generate a compiled form of the MH intrinsic.
2558      AdapterHandlerLibrary::create_native_wrapper(m);
2559      // Check if have the compiled code.
2560      if (!m->has_compiled_code()) {
2561        THROW_MSG_(vmSymbols::java_lang_VirtualMachineError(),
2562                   "Out of space in CodeCache for method handle intrinsic", empty);
2563      }
2564    }
2565    // Now grab the lock.  We might have to throw away the new method,
2566    // if a racing thread has managed to install one at the same time.
2567    {
2568      MutexLocker ml(SystemDictionary_lock, THREAD);
2569      spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2570      if (spe == NULL)
2571        spe = invoke_method_table()->add_entry(index, hash, signature, iid);
2572      if (spe->method() == NULL)
2573        spe->set_method(m());
2574    }
2575  }
2576
2577  assert(spe != NULL && spe->method() != NULL, "");
2578  assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
2579         spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
2580         "MH intrinsic invariant");
2581  return spe->method();
2582}
2583
2584// Helper for unpacking the return value from linkMethod and linkCallSite.
2585static methodHandle unpack_method_and_appendix(Handle mname,
2586                                               KlassHandle accessing_klass,
2587                                               objArrayHandle appendix_box,
2588                                               Handle* appendix_result,
2589                                               TRAPS) {
2590  methodHandle empty;
2591  if (mname.not_null()) {
2592    Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
2593    if (vmtarget != NULL && vmtarget->is_method()) {
2594      Method* m = (Method*)vmtarget;
2595      oop appendix = appendix_box->obj_at(0);
2596      if (TraceMethodHandles) {
2597    #ifndef PRODUCT
2598        ttyLocker ttyl;
2599        tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2600        m->print();
2601        if (appendix != NULL) { tty->print("appendix = "); appendix->print(); }
2602        tty->cr();
2603    #endif //PRODUCT
2604      }
2605      (*appendix_result) = Handle(THREAD, appendix);
2606      // the target is stored in the cpCache and if a reference to this
2607      // MethodName is dropped we need a way to make sure the
2608      // class_loader containing this method is kept alive.
2609      // FIXME: the appendix might also preserve this dependency.
2610      ClassLoaderData* this_key = InstanceKlass::cast(accessing_klass())->class_loader_data();
2611      this_key->record_dependency(m->method_holder(), CHECK_NULL); // Can throw OOM
2612      return methodHandle(THREAD, m);
2613    }
2614  }
2615  THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives", empty);
2616  return empty;
2617}
2618
2619methodHandle SystemDictionary::find_method_handle_invoker(KlassHandle klass,
2620                                                          Symbol* name,
2621                                                          Symbol* signature,
2622                                                          KlassHandle accessing_klass,
2623                                                          Handle *appendix_result,
2624                                                          Handle *method_type_result,
2625                                                          TRAPS) {
2626  methodHandle empty;
2627  assert(THREAD->can_call_java() ,"");
2628  Handle method_type =
2629    SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_(empty));
2630
2631  int ref_kind = JVM_REF_invokeVirtual;
2632  Handle name_str = StringTable::intern(name, CHECK_(empty));
2633  objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
2634  assert(appendix_box->obj_at(0) == NULL, "");
2635
2636  // This should not happen.  JDK code should take care of that.
2637  if (accessing_klass.is_null() || method_type.is_null()) {
2638    THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokehandle", empty);
2639  }
2640
2641  // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
2642  JavaCallArguments args;
2643  args.push_oop(accessing_klass()->java_mirror());
2644  args.push_int(ref_kind);
2645  args.push_oop(klass()->java_mirror());
2646  args.push_oop(name_str());
2647  args.push_oop(method_type());
2648  args.push_oop(appendix_box());
2649  JavaValue result(T_OBJECT);
2650  JavaCalls::call_static(&result,
2651                         SystemDictionary::MethodHandleNatives_klass(),
2652                         vmSymbols::linkMethod_name(),
2653                         vmSymbols::linkMethod_signature(),
2654                         &args, CHECK_(empty));
2655  Handle mname(THREAD, (oop) result.get_jobject());
2656  (*method_type_result) = method_type;
2657  return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);
2658}
2659
2660// Decide if we can globally cache a lookup of this class, to be returned to any client that asks.
2661// We must ensure that all class loaders everywhere will reach this class, for any client.
2662// This is a safe bet for public classes in java.lang, such as Object and String.
2663// We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.
2664// Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.
2665static bool is_always_visible_class(oop mirror) {
2666  Klass* klass = java_lang_Class::as_Klass(mirror);
2667  if (klass->is_objArray_klass()) {
2668    klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type
2669  }
2670  if (klass->is_typeArray_klass()) {
2671    return true; // primitive array
2672  }
2673  assert(klass->is_instance_klass(), "%s", klass->external_name());
2674  return klass->is_public() &&
2675         (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) ||       // java.lang
2676          InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass()));  // java.lang.invoke
2677}
2678
2679// Ask Java code to find or construct a java.lang.invoke.MethodType for the given
2680// signature, as interpreted relative to the given class loader.
2681// Because of class loader constraints, all method handle usage must be
2682// consistent with this loader.
2683Handle SystemDictionary::find_method_handle_type(Symbol* signature,
2684                                                 KlassHandle accessing_klass,
2685                                                 TRAPS) {
2686  Handle empty;
2687  vmIntrinsics::ID null_iid = vmIntrinsics::_none;  // distinct from all method handle invoker intrinsics
2688  unsigned int hash  = invoke_method_table()->compute_hash(signature, null_iid);
2689  int          index = invoke_method_table()->hash_to_index(hash);
2690  SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2691  if (spe != NULL && spe->method_type() != NULL) {
2692    assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");
2693    return Handle(THREAD, spe->method_type());
2694  } else if (!THREAD->can_call_java()) {
2695    warning("SystemDictionary::find_method_handle_type called from compiler thread");  // FIXME
2696    return Handle();  // do not attempt from within compiler, unless it was cached
2697  }
2698
2699  Handle class_loader, protection_domain;
2700  if (accessing_klass.not_null()) {
2701    class_loader      = Handle(THREAD, InstanceKlass::cast(accessing_klass())->class_loader());
2702    protection_domain = Handle(THREAD, InstanceKlass::cast(accessing_klass())->protection_domain());
2703  }
2704  bool can_be_cached = true;
2705  int npts = ArgumentCount(signature).size();
2706  objArrayHandle pts = oopFactory::new_objArray(SystemDictionary::Class_klass(), npts, CHECK_(empty));
2707  int arg = 0;
2708  Handle rt; // the return type from the signature
2709  ResourceMark rm(THREAD);
2710  for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2711    oop mirror = NULL;
2712    if (can_be_cached) {
2713      // Use neutral class loader to lookup candidate classes to be placed in the cache.
2714      mirror = ss.as_java_mirror(Handle(), Handle(),
2715                                 SignatureStream::ReturnNull, CHECK_(empty));
2716      if (mirror == NULL || (ss.is_object() && !is_always_visible_class(mirror))) {
2717        // Fall back to accessing_klass context.
2718        can_be_cached = false;
2719      }
2720    }
2721    if (!can_be_cached) {
2722      // Resolve, throwing a real error if it doesn't work.
2723      mirror = ss.as_java_mirror(class_loader, protection_domain,
2724                                 SignatureStream::NCDFError, CHECK_(empty));
2725    }
2726    assert(!oopDesc::is_null(mirror), "%s", ss.as_symbol(THREAD)->as_C_string());
2727    if (ss.at_return_type())
2728      rt = Handle(THREAD, mirror);
2729    else
2730      pts->obj_at_put(arg++, mirror);
2731
2732    // Check accessibility.
2733    if (ss.is_object() && accessing_klass.not_null()) {
2734      Klass* sel_klass = java_lang_Class::as_Klass(mirror);
2735      mirror = NULL;  // safety
2736      // Emulate ConstantPool::verify_constant_pool_resolve.
2737      if (sel_klass->is_objArray_klass())
2738        sel_klass = ObjArrayKlass::cast(sel_klass)->bottom_klass();
2739      if (sel_klass->is_instance_klass()) {
2740        KlassHandle sel_kh(THREAD, sel_klass);
2741        LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty));
2742      }
2743    }
2744  }
2745  assert(arg == npts, "");
2746
2747  // call java.lang.invoke.MethodHandleNatives::findMethodType(Class rt, Class[] pts) -> MethodType
2748  JavaCallArguments args(Handle(THREAD, rt()));
2749  args.push_oop(pts());
2750  JavaValue result(T_OBJECT);
2751  JavaCalls::call_static(&result,
2752                         SystemDictionary::MethodHandleNatives_klass(),
2753                         vmSymbols::findMethodHandleType_name(),
2754                         vmSymbols::findMethodHandleType_signature(),
2755                         &args, CHECK_(empty));
2756  Handle method_type(THREAD, (oop) result.get_jobject());
2757
2758  if (can_be_cached) {
2759    // We can cache this MethodType inside the JVM.
2760    MutexLocker ml(SystemDictionary_lock, THREAD);
2761    spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2762    if (spe == NULL)
2763      spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
2764    if (spe->method_type() == NULL) {
2765      spe->set_method_type(method_type());
2766    }
2767  }
2768
2769  // report back to the caller with the MethodType
2770  return method_type;
2771}
2772
2773// Ask Java code to find or construct a method handle constant.
2774Handle SystemDictionary::link_method_handle_constant(KlassHandle caller,
2775                                                     int ref_kind, //e.g., JVM_REF_invokeVirtual
2776                                                     KlassHandle callee,
2777                                                     Symbol* name_sym,
2778                                                     Symbol* signature,
2779                                                     TRAPS) {
2780  Handle empty;
2781  Handle name = java_lang_String::create_from_symbol(name_sym, CHECK_(empty));
2782  Handle type;
2783  if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') {
2784    type = find_method_handle_type(signature, caller, CHECK_(empty));
2785  } else if (caller.is_null()) {
2786    // This should not happen.  JDK code should take care of that.
2787    THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);
2788  } else {
2789    ResourceMark rm(THREAD);
2790    SignatureStream ss(signature, false);
2791    if (!ss.is_done()) {
2792      oop mirror = ss.as_java_mirror(caller->class_loader(), caller->protection_domain(),
2793                                     SignatureStream::NCDFError, CHECK_(empty));
2794      type = Handle(THREAD, mirror);
2795      ss.next();
2796      if (!ss.is_done())  type = Handle();  // error!
2797    }
2798  }
2799  if (type.is_null()) {
2800    THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty);
2801  }
2802
2803  // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
2804  JavaCallArguments args;
2805  args.push_oop(caller->java_mirror());  // the referring class
2806  args.push_int(ref_kind);
2807  args.push_oop(callee->java_mirror());  // the target class
2808  args.push_oop(name());
2809  args.push_oop(type());
2810  JavaValue result(T_OBJECT);
2811  JavaCalls::call_static(&result,
2812                         SystemDictionary::MethodHandleNatives_klass(),
2813                         vmSymbols::linkMethodHandleConstant_name(),
2814                         vmSymbols::linkMethodHandleConstant_signature(),
2815                         &args, CHECK_(empty));
2816  return Handle(THREAD, (oop) result.get_jobject());
2817}
2818
2819// Ask Java code to find or construct a java.lang.invoke.CallSite for the given
2820// name and signature, as interpreted relative to the given class loader.
2821methodHandle SystemDictionary::find_dynamic_call_site_invoker(KlassHandle caller,
2822                                                              Handle bootstrap_specifier,
2823                                                              Symbol* name,
2824                                                              Symbol* type,
2825                                                              Handle *appendix_result,
2826                                                              Handle *method_type_result,
2827                                                              TRAPS) {
2828  methodHandle empty;
2829  Handle bsm, info;
2830  if (java_lang_invoke_MethodHandle::is_instance(bootstrap_specifier())) {
2831    bsm = bootstrap_specifier;
2832  } else {
2833    assert(bootstrap_specifier->is_objArray(), "");
2834    objArrayHandle args(THREAD, (objArrayOop) bootstrap_specifier());
2835    int len = args->length();
2836    assert(len >= 1, "");
2837    bsm = Handle(THREAD, args->obj_at(0));
2838    if (len > 1) {
2839      objArrayOop args1 = oopFactory::new_objArray(SystemDictionary::Object_klass(), len-1, CHECK_(empty));
2840      for (int i = 1; i < len; i++)
2841        args1->obj_at_put(i-1, args->obj_at(i));
2842      info = Handle(THREAD, args1);
2843    }
2844  }
2845  guarantee(java_lang_invoke_MethodHandle::is_instance(bsm()),
2846            "caller must supply a valid BSM");
2847
2848  Handle method_name = java_lang_String::create_from_symbol(name, CHECK_(empty));
2849  Handle method_type = find_method_handle_type(type, caller, CHECK_(empty));
2850
2851  // This should not happen.  JDK code should take care of that.
2852  if (caller.is_null() || method_type.is_null()) {
2853    THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokedynamic", empty);
2854  }
2855
2856  objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
2857  assert(appendix_box->obj_at(0) == NULL, "");
2858
2859  // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
2860  JavaCallArguments args;
2861  args.push_oop(caller->java_mirror());
2862  args.push_oop(bsm());
2863  args.push_oop(method_name());
2864  args.push_oop(method_type());
2865  args.push_oop(info());
2866  args.push_oop(appendix_box);
2867  JavaValue result(T_OBJECT);
2868  JavaCalls::call_static(&result,
2869                         SystemDictionary::MethodHandleNatives_klass(),
2870                         vmSymbols::linkCallSite_name(),
2871                         vmSymbols::linkCallSite_signature(),
2872                         &args, CHECK_(empty));
2873  Handle mname(THREAD, (oop) result.get_jobject());
2874  (*method_type_result) = method_type;
2875  return unpack_method_and_appendix(mname, caller, appendix_box, appendix_result, THREAD);
2876}
2877
2878// Since the identity hash code for symbols changes when the symbols are
2879// moved from the regular perm gen (hash in the mark word) to the shared
2880// spaces (hash is the address), the classes loaded into the dictionary
2881// may be in the wrong buckets.
2882
2883void SystemDictionary::reorder_dictionary() {
2884  dictionary()->reorder_dictionary();
2885}
2886
2887
2888void SystemDictionary::copy_buckets(char** top, char* end) {
2889  dictionary()->copy_buckets(top, end);
2890}
2891
2892
2893void SystemDictionary::copy_table(char** top, char* end) {
2894  dictionary()->copy_table(top, end);
2895}
2896
2897
2898void SystemDictionary::reverse() {
2899  dictionary()->reverse();
2900}
2901
2902int SystemDictionary::number_of_classes() {
2903  return dictionary()->number_of_entries();
2904}
2905
2906
2907// ----------------------------------------------------------------------------
2908void SystemDictionary::print_shared(bool details) {
2909  shared_dictionary()->print(details);
2910}
2911
2912void SystemDictionary::print(bool details) {
2913  dictionary()->print(details);
2914
2915  // Placeholders
2916  GCMutexLocker mu(SystemDictionary_lock);
2917  placeholders()->print();
2918
2919  // loader constraints - print under SD_lock
2920  constraints()->print();
2921}
2922
2923
2924void SystemDictionary::verify() {
2925  guarantee(dictionary() != NULL, "Verify of system dictionary failed");
2926  guarantee(constraints() != NULL,
2927            "Verify of loader constraints failed");
2928  guarantee(dictionary()->number_of_entries() >= 0 &&
2929            placeholders()->number_of_entries() >= 0,
2930            "Verify of system dictionary failed");
2931
2932  // Verify dictionary
2933  dictionary()->verify();
2934
2935  GCMutexLocker mu(SystemDictionary_lock);
2936  placeholders()->verify();
2937
2938  // Verify constraint table
2939  guarantee(constraints() != NULL, "Verify of loader constraints failed");
2940  constraints()->verify(dictionary(), placeholders());
2941}
2942
2943// caller needs ResourceMark
2944const char* SystemDictionary::loader_name(const oop loader) {
2945  return ((loader) == NULL ? "<bootloader>" :
2946    InstanceKlass::cast((loader)->klass())->name()->as_C_string());
2947}
2948
2949// caller needs ResourceMark
2950const char* SystemDictionary::loader_name(const ClassLoaderData* loader_data) {
2951  return (loader_data->class_loader() == NULL ? "<bootloader>" :
2952    InstanceKlass::cast((loader_data->class_loader())->klass())->name()->as_C_string());
2953}
2954