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