systemDictionary.cpp 121.0 KB
Newer Older
D
duke 已提交
1
/*
K
kbarrett 已提交
2
 * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25
#include "precompiled.hpp"
26
#include "classfile/classLoaderData.inline.hpp"
27 28 29 30 31 32
#include "classfile/dictionary.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/loaderConstraints.hpp"
#include "classfile/placeholders.hpp"
#include "classfile/resolutionErrors.hpp"
#include "classfile/systemDictionary.hpp"
33 34 35 36
#if INCLUDE_CDS
#include "classfile/sharedClassUtil.hpp"
#include "classfile/systemDictionaryShared.hpp"
#endif
37
#include "classfile/vmSymbols.hpp"
38
#include "compiler/compileBroker.hpp"
39 40
#include "interpreter/bytecodeStream.hpp"
#include "interpreter/interpreter.hpp"
A
apetushkov 已提交
41
#include "jfr/jfrEvents.hpp"
42
#include "jfr/jni/jfrUpcalls.hpp"
43
#include "memory/filemap.hpp"
44 45 46 47 48
#include "memory/gcLocker.hpp"
#include "memory/oopFactory.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/instanceRefKlass.hpp"
#include "oops/klass.inline.hpp"
49
#include "oops/methodData.hpp"
50 51 52 53 54 55
#include "oops/objArrayKlass.hpp"
#include "oops/oop.inline.hpp"
#include "oops/oop.inline2.hpp"
#include "oops/typeArrayKlass.hpp"
#include "prims/jvmtiEnvBase.hpp"
#include "prims/methodHandles.hpp"
56
#include "runtime/arguments.hpp"
57 58 59 60 61 62
#include "runtime/biasedLocking.hpp"
#include "runtime/fieldType.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/java.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/mutexLocker.hpp"
63
#include "runtime/orderAccess.inline.hpp"
64 65 66
#include "runtime/signature.hpp"
#include "services/classLoadingService.hpp"
#include "services/threadService.hpp"
67 68
#include "utilities/macros.hpp"
#include "utilities/ticks.hpp"
S
sla 已提交
69

70 71 72 73 74 75
Dictionary*            SystemDictionary::_dictionary          = NULL;
PlaceholderTable*      SystemDictionary::_placeholders        = NULL;
Dictionary*            SystemDictionary::_shared_dictionary   = NULL;
LoaderConstraintTable* SystemDictionary::_loader_constraints  = NULL;
ResolutionErrorTable*  SystemDictionary::_resolution_errors   = NULL;
SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
D
duke 已提交
76 77 78


int         SystemDictionary::_number_of_modifications = 0;
79 80 81
int         SystemDictionary::_sdgeneration               = 0;
const int   SystemDictionary::_primelist[_prime_array_size] = {1009,2017,4049,5051,10103,
              20201,40423,99991};
D
duke 已提交
82 83 84

oop         SystemDictionary::_system_loader_lock_obj     =  NULL;

85
Klass*      SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
86 87
                                                          =  { NULL /*, NULL...*/ };

88
Klass*      SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
D
duke 已提交
89 90 91 92 93 94 95

oop         SystemDictionary::_java_system_loader         =  NULL;

bool        SystemDictionary::_has_loadClassInternal      =  false;
bool        SystemDictionary::_has_checkPackageAccess     =  false;

// lazily initialized klass variables
96
Klass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
D
duke 已提交
97

98 99 100
#if INCLUDE_JFR
static const Symbol* jfr_event_handler_proxy = NULL;
#endif // INCLUDE_JFR
D
duke 已提交
101 102 103 104 105 106 107 108 109

// ----------------------------------------------------------------------------
// Java-level SystemLoader

oop SystemDictionary::java_system_loader() {
  return _java_system_loader;
}

void SystemDictionary::compute_java_system_loader(TRAPS) {
110
  KlassHandle system_klass(THREAD, WK_KLASS(ClassLoader_klass));
D
duke 已提交
111 112
  JavaValue result(T_OBJECT);
  JavaCalls::call_static(&result,
113
                         KlassHandle(THREAD, WK_KLASS(ClassLoader_klass)),
114 115
                         vmSymbols::getSystemClassLoader_name(),
                         vmSymbols::void_classloader_signature(),
D
duke 已提交
116 117 118
                         CHECK);

  _java_system_loader = (oop)result.get_jobject();
119 120

  CDS_ONLY(SystemDictionaryShared::initialize(CHECK);)
D
duke 已提交
121 122 123
}


124
ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, TRAPS) {
125
  if (class_loader() == NULL) return ClassLoaderData::the_null_class_loader_data();
126
  return ClassLoaderDataGraph::find_or_create(class_loader, THREAD);
127 128
}

D
duke 已提交
129 130 131 132 133 134
// ----------------------------------------------------------------------------
// debugging

#ifdef ASSERT

// return true if class_name contains no '.' (internal format is '/')
135 136
bool SystemDictionary::is_internal_format(Symbol* class_name) {
  if (class_name != NULL) {
D
duke 已提交
137 138 139 140 141 142 143 144
    ResourceMark rm;
    char* name = class_name->as_C_string();
    return strchr(name, '.') == NULL;
  } else {
    return true;
  }
}

145 146 147
#endif
#if INCLUDE_JFR
#include "jfr/jfr.hpp"
D
duke 已提交
148 149
#endif

150 151 152 153 154 155
// ----------------------------------------------------------------------------
// Parallel class loading check

bool SystemDictionary::is_parallelCapable(Handle class_loader) {
  if (UnsyncloadClass || class_loader.is_null()) return true;
  if (AlwaysLockClassLoader) return false;
156
  return java_lang_ClassLoader::parallelCapable(class_loader());
157
}
D
duke 已提交
158
// ----------------------------------------------------------------------------
159 160 161
// ParallelDefineClass flag does not apply to bootclass loader
bool SystemDictionary::is_parallelDefine(Handle class_loader) {
   if (class_loader.is_null()) return false;
162
   if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) {
163 164 165 166
     return true;
   }
   return false;
}
167 168 169 170 171 172 173 174 175 176 177

/**
 * Returns true if the passed class loader is the extension class loader.
 */
bool SystemDictionary::is_ext_class_loader(Handle class_loader) {
  if (class_loader.is_null()) {
    return false;
  }
  return (class_loader->klass()->name() == vmSymbols::sun_misc_Launcher_ExtClassLoader());
}

178
// ----------------------------------------------------------------------------
D
duke 已提交
179 180 181 182
// Resolving of classes

// Forwards to resolve_or_null

183 184
Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
  Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
D
duke 已提交
185 186 187 188 189 190 191 192
  if (HAS_PENDING_EXCEPTION || klass == NULL) {
    KlassHandle k_h(THREAD, klass);
    // can return a null klass
    klass = handle_resolution_exception(class_name, class_loader, protection_domain, throw_error, k_h, THREAD);
  }
  return klass;
}

193
Klass* SystemDictionary::handle_resolution_exception(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, KlassHandle klass_h, TRAPS) {
D
duke 已提交
194 195 196 197 198
  if (HAS_PENDING_EXCEPTION) {
    // If we have a pending exception we forward it to the caller, unless throw_error is true,
    // in which case we have to check whether the pending exception is a ClassNotFoundException,
    // and if so convert it to a NoClassDefFoundError
    // And chain the original ClassNotFoundException
199
    if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) {
D
duke 已提交
200 201 202 203
      ResourceMark rm(THREAD);
      assert(klass_h() == NULL, "Should not have result with exception pending");
      Handle e(THREAD, PENDING_EXCEPTION);
      CLEAR_PENDING_EXCEPTION;
204
      THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
D
duke 已提交
205 206 207 208 209 210 211 212
    } else {
      return NULL;
    }
  }
  // Class not found, throw appropriate error or exception depending on value of throw_error
  if (klass_h() == NULL) {
    ResourceMark rm(THREAD);
    if (throw_error) {
213
      THROW_MSG_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
D
duke 已提交
214
    } else {
215
      THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
D
duke 已提交
216 217
    }
  }
218
  return (Klass*)klass_h();
D
duke 已提交
219 220 221
}


222
Klass* SystemDictionary::resolve_or_fail(Symbol* class_name,
D
duke 已提交
223 224 225 226 227 228 229 230
                                           bool throw_error, TRAPS)
{
  return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
}


// Forwards to resolve_instance_class_or_null

231
Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) {
232 233 234
  assert(!THREAD->is_Compiler_thread(),
         err_msg("can not load classes with compiler thread: class=%s, classloader=%s",
                 class_name->as_C_string(),
235
                 class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string()));
236
  if (FieldType::is_array(class_name)) {
D
duke 已提交
237
    return resolve_array_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
238 239 240 241 242 243
  } else if (FieldType::is_obj(class_name)) {
    ResourceMark rm(THREAD);
    // Ignore wrapping L and ;.
    TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1,
                                   class_name->utf8_length() - 2, CHECK_NULL);
    return resolve_instance_class_or_null(name, class_loader, protection_domain, CHECK_NULL);
D
duke 已提交
244 245 246 247 248
  } else {
    return resolve_instance_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
  }
}

249
Klass* SystemDictionary::resolve_or_null(Symbol* class_name, TRAPS) {
D
duke 已提交
250 251 252 253 254
  return resolve_or_null(class_name, Handle(), Handle(), THREAD);
}

// Forwards to resolve_instance_class_or_null

255
Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name,
D
duke 已提交
256 257 258
                                                       Handle class_loader,
                                                       Handle protection_domain,
                                                       TRAPS) {
259
  assert(FieldType::is_array(class_name), "must be array");
260
  Klass* k = NULL;
261 262 263 264
  FieldArrayInfo fd;
  // dimension and object_key in FieldArrayInfo are assigned as a side-effect
  // of this call
  BasicType t = FieldType::get_array_info(class_name, fd, CHECK_NULL);
D
duke 已提交
265 266
  if (t == T_OBJECT) {
    // naked oop "k" is OK here -- we assign back into it
267
    k = SystemDictionary::resolve_instance_class_or_null(fd.object_key(),
D
duke 已提交
268 269 270 271
                                                         class_loader,
                                                         protection_domain,
                                                         CHECK_NULL);
    if (k != NULL) {
H
hseigel 已提交
272
      k = k->array_klass(fd.dimension(), CHECK_NULL);
D
duke 已提交
273 274 275
    }
  } else {
    k = Universe::typeArrayKlassObj(t);
276
    k = TypeArrayKlass::cast(k)->array_klass(fd.dimension(), CHECK_NULL);
D
duke 已提交
277 278 279 280 281 282 283 284 285 286 287 288
  }
  return k;
}


// Must be called for any super-class or super-interface resolution
// during class definition to allow class circularity checking
// super-interface callers:
//    parse_interfaces - for defineClass & jvmtiRedefineClasses
// super-class callers:
//   ClassFileParser - for defineClass & jvmtiRedefineClasses
//   load_shared_class - while loading a class from shared archive
289 290
//   resolve_instance_class_or_null:
//     via: handle_parallel_super_load
D
duke 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
//      when resolving a class that has an existing placeholder with
//      a saved superclass [i.e. a defineClass is currently in progress]
//      if another thread is trying to resolve the class, it must do
//      super-class checks on its own thread to catch class circularity
// This last call is critical in class circularity checking for cases
// where classloading is delegated to different threads and the
// classloader lock is released.
// Take the case: Base->Super->Base
//   1. If thread T1 tries to do a defineClass of class Base
//    resolve_super_or_fail creates placeholder: T1, Base (super Super)
//   2. resolve_instance_class_or_null does not find SD or placeholder for Super
//    so it tries to load Super
//   3. If we load the class internally, or user classloader uses same thread
//      loadClassFromxxx or defineClass via parseClassFile Super ...
//      3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)
//      3.3 resolve_instance_class_or_null Base, finds placeholder for Base
//      3.4 calls resolve_super_or_fail Base
//      3.5 finds T1,Base -> throws class circularity
//OR 4. If T2 tries to resolve Super via defineClass Super ...
//      4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)
//      4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
//      4.3 calls resolve_super_or_fail Super in parallel on own thread T2
//      4.4 finds T2, Super -> throws class circularity
// Must be called, even if superclass is null, since this is
// where the placeholder entry is created which claims this
// thread is loading this class/classloader.
317
Klass* SystemDictionary::resolve_super_or_fail(Symbol* child_name,
318
                                                 Symbol* class_name,
D
duke 已提交
319 320 321 322 323 324 325 326 327
                                                 Handle class_loader,
                                                 Handle protection_domain,
                                                 bool is_superclass,
                                                 TRAPS) {
  // Double-check, if child class is already loaded, just return super-class,interface
  // Don't add a placedholder if already loaded, i.e. already in system dictionary
  // Make sure there's a placeholder for the *child* before resolving.
  // Used as a claim that this thread is currently loading superclass/classloader
  // Used here for ClassCircularity checks and also for heap verification
328
  // (every InstanceKlass in the heap needs to be in the system dictionary
D
duke 已提交
329 330 331 332 333 334 335 336 337 338
  // or have a placeholder).
  // Must check ClassCircularity before checking if super class is already loaded
  //
  // We might not already have a placeholder if this child_name was
  // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
  // the name of the class might not be known until the stream is actually
  // parsed.
  // Bugs 4643874, 4715493
  // compute_hash can have a safepoint

339 340
  ClassLoaderData* loader_data = class_loader_data(class_loader);
  unsigned int d_hash = dictionary()->compute_hash(child_name, loader_data);
D
duke 已提交
341
  int d_index = dictionary()->hash_to_index(d_hash);
342
  unsigned int p_hash = placeholders()->compute_hash(child_name, loader_data);
D
duke 已提交
343 344 345 346 347 348
  int p_index = placeholders()->hash_to_index(p_hash);
  // can't throw error holding a lock
  bool child_already_loaded = false;
  bool throw_circularity_error = false;
  {
    MutexLocker mu(SystemDictionary_lock, THREAD);
349 350
    Klass* childk = find_class(d_index, d_hash, child_name, loader_data);
    Klass* quicksuperk;
D
duke 已提交
351 352 353 354 355 356 357
    // to support // loading: if child done loading, just return superclass
    // if class_name, & class_loader don't match:
    // if initial define, SD update will give LinkageError
    // if redefine: compare_class_versions will give HIERARCHY_CHANGED
    // so we don't throw an exception here.
    // see: nsk redefclass014 & java.lang.instrument Instrument032
    if ((childk != NULL ) && (is_superclass) &&
358
       ((quicksuperk = InstanceKlass::cast(childk)->super()) != NULL) &&
D
duke 已提交
359

H
hseigel 已提交
360 361
         ((quicksuperk->name() == class_name) &&
            (quicksuperk->class_loader()  == class_loader()))) {
D
duke 已提交
362 363
           return quicksuperk;
    } else {
364
      PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
D
duke 已提交
365 366 367
      if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
          throw_circularity_error = true;
      }
368 369
    }
    if (!throw_circularity_error) {
370
      PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, class_name, THREAD);
D
duke 已提交
371 372 373 374
    }
  }
  if (throw_circularity_error) {
      ResourceMark rm(THREAD);
375
      THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
D
duke 已提交
376 377 378
  }

// java.lang.Object should have been found above
379
  assert(class_name != NULL, "null super class for resolving");
D
duke 已提交
380
  // Resolve the super class or interface, check results on return
381
  Klass* superk = SystemDictionary::resolve_or_null(class_name,
D
duke 已提交
382 383 384 385 386 387
                                                 class_loader,
                                                 protection_domain,
                                                 THREAD);

  KlassHandle superk_h(THREAD, superk);

388 389 390 391 392 393
  // Clean up of placeholders moved so that each classloadAction registrar self-cleans up
  // It is no longer necessary to keep the placeholder table alive until update_dictionary
  // or error. GC used to walk the placeholder table as strong roots.
  // The instanceKlass is kept alive because the class loader is on the stack,
  // which keeps the loader_data alive, as well as all instanceKlasses in
  // the loader_data. parseClassFile adds the instanceKlass to loader_data.
D
duke 已提交
394
  {
395 396 397
    MutexLocker mu(SystemDictionary_lock, THREAD);
    placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD);
    SystemDictionary_lock->notify_all();
D
duke 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
  }
  if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
    // can null superk
    superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, class_loader, protection_domain, true, superk_h, THREAD));
  }

  return superk_h();
}

void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
                                                  Handle class_loader,
                                                  Handle protection_domain,
                                                  TRAPS) {
  if(!has_checkPackageAccess()) return;

  // Now we have to call back to java to check if the initating class has access
  JavaValue result(T_VOID);
  if (TraceProtectionDomainVerification) {
    // Print out trace information
    tty->print_cr("Checking package access");
    tty->print(" - class loader:      "); class_loader()->print_value_on(tty);      tty->cr();
    tty->print(" - protection domain: "); protection_domain()->print_value_on(tty); tty->cr();
    tty->print(" - loading:           "); klass()->print_value_on(tty);             tty->cr();
  }

423
  KlassHandle system_loader(THREAD, SystemDictionary::ClassLoader_klass());
D
duke 已提交
424 425 426
  JavaCalls::call_special(&result,
                         class_loader,
                         system_loader,
427 428
                         vmSymbols::checkPackageAccess_name(),
                         vmSymbols::class_protectiondomain_signature(),
D
duke 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
                         Handle(THREAD, klass->java_mirror()),
                         protection_domain,
                         THREAD);

  if (TraceProtectionDomainVerification) {
    if (HAS_PENDING_EXCEPTION) {
      tty->print_cr(" -> DENIED !!!!!!!!!!!!!!!!!!!!!");
    } else {
     tty->print_cr(" -> granted");
    }
    tty->cr();
  }

  if (HAS_PENDING_EXCEPTION) return;

  // If no exception has been thrown, we have validated the protection domain
  // Insert the protection domain of the initiating class into the set.
  {
    // We recalculate the entry here -- we've called out to java since
    // the last time it was calculated.
449 450
    ClassLoaderData* loader_data = class_loader_data(class_loader);

451
    Symbol*  kn = klass->name();
452
    unsigned int d_hash = dictionary()->compute_hash(kn, loader_data);
D
duke 已提交
453 454 455 456 457 458 459 460 461
    int d_index = dictionary()->hash_to_index(d_hash);

    MutexLocker mu(SystemDictionary_lock, THREAD);
    {
      // Note that we have an entry, and entries can be deleted only during GC,
      // so we cannot allow GC to occur while we're holding this entry.

      // We're using a No_Safepoint_Verifier to catch any place where we
      // might potentially do a GC at all.
462 463
      // Dictionary::do_unloading() asserts that classes in SD are only
      // unloaded at a safepoint. Anonymous classes are not in SD.
D
duke 已提交
464
      No_Safepoint_Verifier nosafepoint;
465
      dictionary()->add_protection_domain(d_index, d_hash, klass, loader_data,
D
duke 已提交
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
                                          protection_domain, THREAD);
    }
  }
}

// We only get here if this thread finds that another thread
// has already claimed the placeholder token for the current operation,
// but that other thread either never owned or gave up the
// object lock
// Waits on SystemDictionary_lock to indicate placeholder table updated
// On return, caller must recheck placeholder table state
//
// We only get here if
//  1) custom classLoader, i.e. not bootstrap classloader
//  2) UnsyncloadClass not set
//  3) custom classLoader has broken the class loader objectLock
//     so another thread got here in parallel
//
// lockObject must be held.
// Complicated dance due to lock ordering:
// Must first release the classloader object lock to
// allow initial definer to complete the class definition
// and to avoid deadlock
// Reclaim classloader lock object with same original recursion count
// Must release SystemDictionary_lock after notify, since
// class loader lock must be claimed before SystemDictionary_lock
// to prevent deadlocks
//
// The notify allows applications that did an untimed wait() on
// the classloader object lock to not hang.
void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {
  assert_lock_strong(SystemDictionary_lock);

  bool calledholdinglock
      = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject);
  assert(calledholdinglock,"must hold lock for notify");
502
  assert((!(lockObject() == _system_loader_lock_obj) && !is_parallelCapable(lockObject)), "unexpected double_lock_wait");
D
duke 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
  ObjectSynchronizer::notifyall(lockObject, THREAD);
  intptr_t recursions =  ObjectSynchronizer::complete_exit(lockObject, THREAD);
  SystemDictionary_lock->wait();
  SystemDictionary_lock->unlock();
  ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
  SystemDictionary_lock->lock();
}

// If the class in is in the placeholder table, class loading is in progress
// For cases where the application changes threads to load classes, it
// is critical to ClassCircularity detection that we try loading
// the superclass on the same thread internally, so we do parallel
// super class loading here.
// This also is critical in cases where the original thread gets stalled
// even in non-circularity situations.
// Note: must call resolve_super_or_fail even if null super -
519
// to force placeholder entry creation for this class for circularity detection
D
duke 已提交
520
// Caller must check for pending exception
521
// Returns non-null Klass* if other thread has completed load
D
duke 已提交
522
// and we are done,
523
// If return null Klass* and no pending exception, the caller must load the class
D
duke 已提交
524
instanceKlassHandle SystemDictionary::handle_parallel_super_load(
525
    Symbol* name, Symbol* superclassname, Handle class_loader,
D
duke 已提交
526 527 528
    Handle protection_domain, Handle lockObject, TRAPS) {

  instanceKlassHandle nh = instanceKlassHandle(); // null Handle
529 530
  ClassLoaderData* loader_data = class_loader_data(class_loader);
  unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
D
duke 已提交
531
  int d_index = dictionary()->hash_to_index(d_hash);
532
  unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
D
duke 已提交
533 534 535 536 537 538 539 540 541 542
  int p_index = placeholders()->hash_to_index(p_hash);

  // superk is not used, resolve_super called for circularity check only
  // This code is reached in two situations. One if this thread
  // is loading the same class twice (e.g. ClassCircularity, or
  // java.lang.instrument).
  // The second is if another thread started the resolve_super first
  // and has not yet finished.
  // In both cases the original caller will clean up the placeholder
  // entry on error.
543
  Klass* superk = SystemDictionary::resolve_super_or_fail(name,
D
duke 已提交
544 545 546 547 548 549
                                                          superclassname,
                                                          class_loader,
                                                          protection_domain,
                                                          true,
                                                          CHECK_(nh));

550 551 552
  // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
  // Serial class loaders and bootstrap classloader do wait for superclass loads
 if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
D
duke 已提交
553 554
    MutexLocker mu(SystemDictionary_lock, THREAD);
    // Check if classloading completed while we were loading superclass or waiting
555
    Klass* check = find_class(d_index, d_hash, name, loader_data);
D
duke 已提交
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    if (check != NULL) {
      // Klass is already loaded, so just return it
      return(instanceKlassHandle(THREAD, check));
    } else {
      return nh;
    }
  }

  // must loop to both handle other placeholder updates
  // and spurious notifications
  bool super_load_in_progress = true;
  PlaceholderEntry* placeholder;
  while (super_load_in_progress) {
    MutexLocker mu(SystemDictionary_lock, THREAD);
    // Check if classloading completed while we were loading superclass or waiting
571
    Klass* check = find_class(d_index, d_hash, name, loader_data);
D
duke 已提交
572 573 574 575
    if (check != NULL) {
      // Klass is already loaded, so just return it
      return(instanceKlassHandle(THREAD, check));
    } else {
576
      placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
D
duke 已提交
577 578 579 580 581 582 583 584 585 586 587 588
      if (placeholder && placeholder->super_load_in_progress() ){
        // Before UnsyncloadClass:
        // We only get here if the application has released the
        // classloader lock when another thread was in the middle of loading a
        // superclass/superinterface for this class, and now
        // this thread is also trying to load this class.
        // To minimize surprises, the first thread that started to
        // load a class should be the one to complete the loading
        // with the classfile it initially expected.
        // This logic has the current thread wait once it has done
        // all the superclass/superinterface loading it can, until
        // the original thread completes the class loading or fails
589
        // If it completes we will use the resulting InstanceKlass
D
duke 已提交
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
        // which we will find below in the systemDictionary.
        // We also get here for parallel bootstrap classloader
        if (class_loader.is_null()) {
          SystemDictionary_lock->wait();
        } else {
          double_lock_wait(lockObject, THREAD);
        }
      } else {
        // If not in SD and not in PH, other thread's load must have failed
        super_load_in_progress = false;
      }
    }
  }
  return (nh);
}

A
apetushkov 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
// utility function for class load event
static void post_class_load_event(EventClassLoad &event,
                                  instanceKlassHandle k,
                                  Handle initiating_loader) {
#if INCLUDE_JFR
  if (event.should_commit()) {
    event.set_loadedClass(k());
    event.set_definingClassLoader(k->class_loader_data());
    oop class_loader = initiating_loader.is_null() ? (oop)NULL : initiating_loader();
    event.set_initiatingClassLoader(class_loader != NULL ?
                                    ClassLoaderData::class_loader_data_or_null(class_loader) :
                                    (ClassLoaderData*)NULL);
    event.commit();
  }
#endif // INCLUDE_JFR
}
D
duke 已提交
622

S
sla 已提交
623 624 625 626
Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
                                                        Handle class_loader,
                                                        Handle protection_domain,
                                                        TRAPS) {
627 628
  assert(name != NULL && !FieldType::is_array(name) &&
         !FieldType::is_obj(name), "invalid class name");
D
duke 已提交
629

A
apetushkov 已提交
630
  EventClassLoad class_load_start_event;
S
sla 已提交
631

D
duke 已提交
632 633 634
  // UseNewReflection
  // Fix for 4474172; see evaluation for more details
  class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
635
  ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL);
D
duke 已提交
636 637 638

  // Do lookup to see if class already exist and the protection domain
  // has the right access
639 640 641 642
  // This call uses find which checks protection domain already matches
  // All subsequent calls use find_class, and set has_loaded_class so that
  // before we return a result we call out to java to check for valid protection domain
  // to allow returning the Klass* and add it to the pd_set if it is valid
643
  unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
D
duke 已提交
644
  int d_index = dictionary()->hash_to_index(d_hash);
645
  Klass* probe = dictionary()->find(d_index, d_hash, name, loader_data,
D
duke 已提交
646 647 648 649 650 651 652 653 654 655 656
                                      protection_domain, THREAD);
  if (probe != NULL) return probe;


  // Non-bootstrap class loaders will call out to class loader and
  // define via jvm/jni_DefineClass which will acquire the
  // class loader object lock to protect against multiple threads
  // defining the class in parallel by accident.
  // This lock must be acquired here so the waiter will find
  // any successful result in the SystemDictionary and not attempt
  // the define
657
  // ParallelCapable Classloaders and the bootstrap classloader,
D
duke 已提交
658 659
  // or all classloaders with UnsyncloadClass do not acquire lock here
  bool DoObjectLock = true;
660
  if (is_parallelCapable(class_loader)) {
D
duke 已提交
661 662 663
    DoObjectLock = false;
  }

664
  unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
D
duke 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677 678
  int p_index = placeholders()->hash_to_index(p_hash);

  // Class is not in SystemDictionary so we have to do loading.
  // Make sure we are synchronized on the class loader before we proceed
  Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
  check_loader_lock_contention(lockObject, THREAD);
  ObjectLocker ol(lockObject, THREAD, DoObjectLock);

  // Check again (after locking) if class already exist in SystemDictionary
  bool class_has_been_loaded   = false;
  bool super_load_in_progress  = false;
  bool havesupername = false;
  instanceKlassHandle k;
  PlaceholderEntry* placeholder;
679
  Symbol* superclassname = NULL;
D
duke 已提交
680 681 682

  {
    MutexLocker mu(SystemDictionary_lock, THREAD);
683
    Klass* check = find_class(d_index, d_hash, name, loader_data);
D
duke 已提交
684 685 686 687 688
    if (check != NULL) {
      // Klass is already loaded, so just return it
      class_has_been_loaded = true;
      k = instanceKlassHandle(THREAD, check);
    } else {
689
      placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
D
duke 已提交
690 691 692
      if (placeholder && placeholder->super_load_in_progress()) {
         super_load_in_progress = true;
         if (placeholder->havesupername() == true) {
693
           superclassname = placeholder->supername();
D
duke 已提交
694 695 696 697 698 699
           havesupername = true;
         }
      }
    }
  }

700
  // If the class is in the placeholder table, class loading is in progress
D
duke 已提交
701 702 703 704 705 706 707 708 709 710 711
  if (super_load_in_progress && havesupername==true) {
    k = SystemDictionary::handle_parallel_super_load(name, superclassname,
        class_loader, protection_domain, lockObject, THREAD);
    if (HAS_PENDING_EXCEPTION) {
      return NULL;
    }
    if (!k.is_null()) {
      class_has_been_loaded = true;
    }
  }

712
  bool throw_circularity_error = false;
D
duke 已提交
713
  if (!class_has_been_loaded) {
714
    bool load_instance_added = false;
D
duke 已提交
715 716 717 718 719

    // add placeholder entry to record loading instance class
    // Five cases:
    // All cases need to prevent modifying bootclasssearchpath
    // in parallel with a classload of same classname
720 721 722
    // Redefineclasses uses existence of the placeholder for the duration
    // of the class load to prevent concurrent redefinition of not completely
    // defined classes.
D
duke 已提交
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    // case 1. traditional classloaders that rely on the classloader object lock
    //   - no other need for LOAD_INSTANCE
    // case 2. traditional classloaders that break the classloader object lock
    //    as a deadlock workaround. Detection of this case requires that
    //    this check is done while holding the classloader object lock,
    //    and that lock is still held when calling classloader's loadClass.
    //    For these classloaders, we ensure that the first requestor
    //    completes the load and other requestors wait for completion.
    // case 3. UnsyncloadClass - don't use objectLocker
    //    With this flag, we allow parallel classloading of a
    //    class/classloader pair
    // case4. Bootstrap classloader - don't own objectLocker
    //    This classloader supports parallelism at the classloader level,
    //    but only allows a single load of a class/classloader pair.
    //    No performance benefit and no deadlock issues.
738 739
    // case 5. parallelCapable user level classloaders - without objectLocker
    //    Allow parallel classloading of a class/classloader pair
740

D
duke 已提交
741 742
    {
      MutexLocker mu(SystemDictionary_lock, THREAD);
743
      if (class_loader.is_null() || !is_parallelCapable(class_loader)) {
744
        PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
D
duke 已提交
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
        if (oldprobe) {
          // only need check_seen_thread once, not on each loop
          // 6341374 java/lang/Instrument with -Xcomp
          if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
            throw_circularity_error = true;
          } else {
            // case 1: traditional: should never see load_in_progress.
            while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {

              // case 4: bootstrap classloader: prevent futile classloading,
              // wait on first requestor
              if (class_loader.is_null()) {
                SystemDictionary_lock->wait();
              } else {
              // case 2: traditional with broken classloader lock. wait on first
              // requestor.
                double_lock_wait(lockObject, THREAD);
              }
              // Check if classloading completed while we were waiting
764
              Klass* check = find_class(d_index, d_hash, name, loader_data);
D
duke 已提交
765 766 767 768 769 770
              if (check != NULL) {
                // Klass is already loaded, so just return it
                k = instanceKlassHandle(THREAD, check);
                class_has_been_loaded = true;
              }
              // check if other thread failed to load and cleaned up
771
              oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
D
duke 已提交
772 773 774 775
            }
          }
        }
      }
776
      // All cases: add LOAD_INSTANCE holding SystemDictionary_lock
777
      // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
D
duke 已提交
778
      // LOAD_INSTANCE in parallel
779

780
      if (!throw_circularity_error && !class_has_been_loaded) {
781
        PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
782
        load_instance_added = true;
D
duke 已提交
783 784 785 786 787
        // For class loaders that do not acquire the classloader object lock,
        // if they did not catch another thread holding LOAD_INSTANCE,
        // need a check analogous to the acquire ObjectLocker/find_class
        // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
        // one final check if the load has already completed
788
        // class loaders holding the ObjectLock shouldn't find the class here
789
        Klass* check = find_class(d_index, d_hash, name, loader_data);
D
duke 已提交
790
        if (check != NULL) {
791
        // Klass is already loaded, so return it after checking/adding protection domain
D
duke 已提交
792 793 794 795 796
          k = instanceKlassHandle(THREAD, check);
          class_has_been_loaded = true;
        }
      }
    }
797

D
duke 已提交
798 799
    // must throw error outside of owning lock
    if (throw_circularity_error) {
800
      assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");
D
duke 已提交
801
      ResourceMark rm(THREAD);
802
      THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
D
duke 已提交
803 804 805 806 807 808 809
    }

    if (!class_has_been_loaded) {

      // Do actual loading
      k = load_instance_class(name, class_loader, THREAD);

810
      // For UnsyncloadClass only
D
duke 已提交
811 812 813
      // If they got a linkageError, check if a parallel class load succeeded.
      // If it did, then for bytecode resolution the specification requires
      // that we return the same result we did for the other thread, i.e. the
814
      // successfully loaded InstanceKlass
D
duke 已提交
815
      // Should not get here for classloaders that support parallelism
816
      // with the new cleaner mechanism, even with AllowParallelDefineClass
817
      // Bootstrap goes through here to allow for an extra guarantee check
D
duke 已提交
818 819
      if (UnsyncloadClass || (class_loader.is_null())) {
        if (k.is_null() && HAS_PENDING_EXCEPTION
820
          && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
D
duke 已提交
821
          MutexLocker mu(SystemDictionary_lock, THREAD);
822
          Klass* check = find_class(d_index, d_hash, name, loader_data);
D
duke 已提交
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
          if (check != NULL) {
            // Klass is already loaded, so just use it
            k = instanceKlassHandle(THREAD, check);
            CLEAR_PENDING_EXCEPTION;
            guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
          }
        }
      }

      // If everything was OK (no exceptions, no null return value), and
      // class_loader is NOT the defining loader, do a little more bookkeeping.
      if (!HAS_PENDING_EXCEPTION && !k.is_null() &&
        k->class_loader() != class_loader()) {

        check_constraints(d_index, d_hash, k, class_loader, false, THREAD);

        // Need to check for a PENDING_EXCEPTION again; check_constraints
840 841 842 843 844 845 846 847 848 849
        // can throw but we may have to remove entry from the placeholder table below.
        if (!HAS_PENDING_EXCEPTION) {
          // Record dependency for non-parent delegation.
          // This recording keeps the defining class loader of the klass (k) found
          // from being unloaded while the initiating class loader is loaded
          // even if the reference to the defining class loader is dropped
          // before references to the initiating class loader.
          loader_data->record_dependency(k(), THREAD);
        }

D
duke 已提交
850 851 852 853 854
        if (!HAS_PENDING_EXCEPTION) {
          { // Grabbing the Compile_lock prevents systemDictionary updates
            // during compilations.
            MutexLocker mu(Compile_lock, THREAD);
            update_dictionary(d_index, d_hash, p_index, p_hash,
S
sla 已提交
855
                              k, class_loader, THREAD);
D
duke 已提交
856
          }
S
sla 已提交
857

D
duke 已提交
858 859 860 861 862 863 864
          if (JvmtiExport::should_post_class_load()) {
            Thread *thread = THREAD;
            assert(thread->is_Java_thread(), "thread->is_Java_thread()");
            JvmtiExport::post_class_load((JavaThread *) thread, k());
          }
        }
      }
865 866 867 868 869 870 871
    } // load_instance_class loop

    if (load_instance_added == true) {
      // clean up placeholder entries for LOAD_INSTANCE success or error
      // This brackets the SystemDictionary updates for both defining
      // and initiating loaders
      MutexLocker mu(SystemDictionary_lock, THREAD);
S
sla 已提交
872 873
      placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
      SystemDictionary_lock->notify_all();
D
duke 已提交
874 875 876
    }
  }

877 878 879 880
  if (HAS_PENDING_EXCEPTION || k.is_null()) {
    return NULL;
  }

A
apetushkov 已提交
881
  post_class_load_event(class_load_start_event, k, class_loader);
S
sla 已提交
882

D
duke 已提交
883 884
#ifdef ASSERT
  {
885
    ClassLoaderData* loader_data = k->class_loader_data();
D
duke 已提交
886
    MutexLocker mu(SystemDictionary_lock, THREAD);
887
    Klass* kk = find_class(name, loader_data);
D
duke 已提交
888 889 890 891 892 893 894 895 896 897 898 899 900 901
    assert(kk == k(), "should be present in dictionary");
  }
#endif

  // return if the protection domain in NULL
  if (protection_domain() == NULL) return k();

  // Check the protection domain has the right access
  {
    MutexLocker mu(SystemDictionary_lock, THREAD);
    // Note that we have an entry, and entries can be deleted only during GC,
    // so we cannot allow GC to occur while we're holding this entry.
    // We're using a No_Safepoint_Verifier to catch any place where we
    // might potentially do a GC at all.
902 903
    // Dictionary::do_unloading() asserts that classes in SD are only
    // unloaded at a safepoint. Anonymous classes are not in SD.
D
duke 已提交
904 905
    No_Safepoint_Verifier nosafepoint;
    if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
906
                                                 loader_data,
D
duke 已提交
907 908 909 910 911 912
                                                 protection_domain)) {
      return k();
    }
  }

  // Verify protection domain. If it fails an exception is thrown
913
  validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
D
duke 已提交
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929

  return k();
}


// This routine does not lock the system dictionary.
//
// Since readers don't hold a lock, we must make sure that system
// dictionary entries are only removed at a safepoint (when only one
// thread is running), and are added to in a safe way (all links must
// be updated in an MT-safe manner).
//
// Callers should be aware that an entry could be added just after
// _dictionary->bucket(index) is read here, so the caller will not see
// the new entry.

930
Klass* SystemDictionary::find(Symbol* class_name,
931 932 933
                              Handle class_loader,
                              Handle protection_domain,
                              TRAPS) {
D
duke 已提交
934

935 936 937 938 939
  // UseNewReflection
  // The result of this call should be consistent with the result
  // of the call to resolve_instance_class_or_null().
  // See evaluation 6790209 and 4474172 for more details.
  class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
940 941 942 943 944 945 946
  ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());

  if (loader_data == NULL) {
    // If the ClassLoaderData has not been setup,
    // then the class loader has no entries in the dictionary.
    return NULL;
  }
947

948
  unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
D
duke 已提交
949 950 951 952 953 954 955
  int d_index = dictionary()->hash_to_index(d_hash);

  {
    // Note that we have an entry, and entries can be deleted only during GC,
    // so we cannot allow GC to occur while we're holding this entry.
    // We're using a No_Safepoint_Verifier to catch any place where we
    // might potentially do a GC at all.
956 957
    // Dictionary::do_unloading() asserts that classes in SD are only
    // unloaded at a safepoint. Anonymous classes are not in SD.
D
duke 已提交
958
    No_Safepoint_Verifier nosafepoint;
959
    return dictionary()->find(d_index, d_hash, class_name, loader_data,
D
duke 已提交
960 961 962 963 964 965 966
                              protection_domain, THREAD);
  }
}


// Look for a loaded instance or array klass by name.  Do not do any loading.
// return NULL in case of error.
967
Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
968 969 970
                                                      Handle class_loader,
                                                      Handle protection_domain,
                                                      TRAPS) {
971
  Klass* k = NULL;
972
  assert(class_name != NULL, "class name must be non NULL");
973

974
  if (FieldType::is_array(class_name)) {
D
duke 已提交
975
    // The name refers to an array.  Parse the name.
976 977 978 979
    // dimension and object_key in FieldArrayInfo are assigned as a
    // side-effect of this call
    FieldArrayInfo fd;
    BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
D
duke 已提交
980 981 982
    if (t != T_OBJECT) {
      k = Universe::typeArrayKlassObj(t);
    } else {
983
      k = SystemDictionary::find(fd.object_key(), class_loader, protection_domain, THREAD);
D
duke 已提交
984 985
    }
    if (k != NULL) {
H
hseigel 已提交
986
      k = k->array_klass_or_null(fd.dimension());
D
duke 已提交
987 988 989 990 991 992 993 994 995 996
    }
  } else {
    k = find(class_name, class_loader, protection_domain, THREAD);
  }
  return k;
}

// Note: this method is much like resolve_from_stream, but
// updates no supplemental data structures.
// TODO consolidate the two methods with a helper routine?
997
Klass* SystemDictionary::parse_stream(Symbol* class_name,
998 999 1000 1001 1002 1003
                                      Handle class_loader,
                                      Handle protection_domain,
                                      ClassFileStream* st,
                                      KlassHandle host_klass,
                                      GrowableArray<Handle>* cp_patches,
                                      TRAPS) {
1004
  TempNewSymbol parsed_name = NULL;
D
duke 已提交
1005

A
apetushkov 已提交
1006
  EventClassLoad class_load_start_event;
S
sla 已提交
1007

1008 1009 1010 1011 1012 1013
  ClassLoaderData* loader_data;
  if (host_klass.not_null()) {
    // Create a new CLD for anonymous class, that uses the same class loader
    // as the host_klass
    assert(EnableInvokeDynamic, "");
    guarantee(host_klass->class_loader() == class_loader(), "should be the same");
1014
    guarantee(!DumpSharedSpaces, "must not create anonymous classes when dumping");
1015 1016 1017 1018 1019 1020
    loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL);
    loader_data->record_dependency(host_klass(), CHECK_NULL);
  } else {
    loader_data = ClassLoaderData::class_loader_data(class_loader());
  }

D
duke 已提交
1021 1022 1023 1024 1025 1026 1027
  // Parse the stream. Note that we do this even though this klass might
  // already be present in the SystemDictionary, otherwise we would not
  // throw potential ClassFormatErrors.
  //
  // Note: "name" is updated.

  instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
1028
                                                             loader_data,
D
duke 已提交
1029
                                                             protection_domain,
1030 1031
                                                             host_klass,
                                                             cp_patches,
D
duke 已提交
1032
                                                             parsed_name,
1033
                                                             true,
D
duke 已提交
1034 1035 1036
                                                             THREAD);


1037
  if (host_klass.not_null() && k.not_null()) {
1038
    assert(EnableInvokeDynamic, "");
1039
    // If it's anonymous, initialize it now, since nobody else will.
1040 1041 1042 1043 1044 1045 1046 1047 1048

    {
      MutexLocker mu_r(Compile_lock, THREAD);

      // Add to class hierarchy, initialize vtables, and do possible
      // deoptimizations.
      add_to_hierarchy(k, CHECK_NULL); // No exception, but can block

      // But, do not add to system dictionary.
1049 1050 1051

      // compiled code dependencies need to be validated anyway
      notice_modification();
1052 1053
    }

1054
    // Rewrite and patch constant pool here.
1055
    k->link_class(CHECK_NULL);
1056 1057 1058
    if (cp_patches != NULL) {
      k->constants()->patch_resolved_references(cp_patches);
    }
1059
    k->eager_initialize(CHECK_NULL);
1060 1061 1062 1063 1064 1065

    // notify jvmti
    if (JvmtiExport::should_post_class_load()) {
        assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
        JvmtiExport::post_class_load((JavaThread *) THREAD, k());
    }
S
sla 已提交
1066

A
apetushkov 已提交
1067
    post_class_load_event(class_load_start_event, k, class_loader);
1068
  }
1069 1070
  assert(host_klass.not_null() || cp_patches == NULL,
         "cp_patches only found with host_klass");
1071

D
duke 已提交
1072 1073 1074 1075 1076 1077 1078 1079
  return k();
}

// Add a klass to the system from a stream (called by jni_DefineClass and
// JVM_DefineClass).
// Note: class_name can be NULL. In that case we do not know the name of
// the class until we have parsed the stream.

1080
Klass* SystemDictionary::resolve_from_stream(Symbol* class_name,
1081 1082 1083 1084 1085
                                             Handle class_loader,
                                             Handle protection_domain,
                                             ClassFileStream* st,
                                             bool verify,
                                             TRAPS) {
D
duke 已提交
1086

1087 1088 1089 1090 1091 1092 1093
  // Classloaders that support parallelism, e.g. bootstrap classloader,
  // or all classloaders with UnsyncloadClass do not acquire lock here
  bool DoObjectLock = true;
  if (is_parallelCapable(class_loader)) {
    DoObjectLock = false;
  }

1094
  ClassLoaderData* loader_data = register_loader(class_loader, CHECK_NULL);
1095

1096
  // Make sure we are synchronized on the class loader before we proceed
D
duke 已提交
1097 1098
  Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
  check_loader_lock_contention(lockObject, THREAD);
1099
  ObjectLocker ol(lockObject, THREAD, DoObjectLock);
D
duke 已提交
1100

1101
  TempNewSymbol parsed_name = NULL;
D
duke 已提交
1102 1103 1104 1105 1106 1107 1108

  // Parse the stream. Note that we do this even though this klass might
  // already be present in the SystemDictionary, otherwise we would not
  // throw potential ClassFormatErrors.
  //
  // Note: "name" is updated.

A
apetushkov 已提交
1109 1110 1111 1112 1113 1114 1115
  ClassFileParser parser(st);
  instanceKlassHandle k = parser.parseClassFile(class_name,
                                                loader_data,
                                                protection_domain,
                                                parsed_name,
                                                verify,
                                                THREAD);
D
duke 已提交
1116 1117

  const char* pkg = "java/";
1118
  size_t pkglen = strlen(pkg);
D
duke 已提交
1119 1120
  if (!HAS_PENDING_EXCEPTION &&
      !class_loader.is_null() &&
1121
      parsed_name != NULL &&
1122 1123
      parsed_name->utf8_length() >= (int)pkglen &&
      !strncmp((const char*)parsed_name->bytes(), pkg, pkglen)) {
D
duke 已提交
1124 1125 1126 1127 1128
    // It is illegal to define classes in the "java." package from
    // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
    ResourceMark rm(THREAD);
    char* name = parsed_name->as_C_string();
    char* index = strrchr(name, '/');
1129
    assert(index != NULL, "must be");
D
duke 已提交
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
    *index = '\0'; // chop to just the package name
    while ((index = strchr(name, '/')) != NULL) {
      *index = '.'; // replace '/' with '.' in package name
    }
    const char* fmt = "Prohibited package name: %s";
    size_t len = strlen(fmt) + strlen(name);
    char* message = NEW_RESOURCE_ARRAY(char, len);
    jio_snprintf(message, len, fmt, name);
    Exceptions::_throw_msg(THREAD_AND_LOCATION,
      vmSymbols::java_lang_SecurityException(), message);
  }

  if (!HAS_PENDING_EXCEPTION) {
1143 1144
    assert(parsed_name != NULL, "Sanity");
    assert(class_name == NULL || class_name == parsed_name, "name mismatch");
D
duke 已提交
1145 1146 1147 1148 1149
    // Verification prevents us from creating names with dots in them, this
    // asserts that that's the case.
    assert(is_internal_format(parsed_name),
           "external class name format used internally");

A
apetushkov 已提交
1150 1151 1152 1153 1154 1155 1156 1157
#if INCLUDE_JFR
    {
      InstanceKlass* ik = k();
      ON_KLASS_CREATION(ik, parser, THREAD);
      k = instanceKlassHandle(ik);
    }
#endif

D
duke 已提交
1158
    // Add class just loaded
1159
    // If a class loader supports parallel classloading handle parallel define requests
1160
    // find_or_define_instance_class may return a different InstanceKlass
1161 1162 1163 1164 1165
    if (is_parallelCapable(class_loader)) {
      k = find_or_define_instance_class(class_name, class_loader, k, THREAD);
    } else {
      define_instance_class(k, THREAD);
    }
D
duke 已提交
1166 1167
  }

1168
  // Make sure we have an entry in the SystemDictionary on success
D
duke 已提交
1169 1170
  debug_only( {
    if (!HAS_PENDING_EXCEPTION) {
1171 1172
      assert(parsed_name != NULL, "parsed_name is still null?");
      Symbol*  h_name    = k->name();
1173
      ClassLoaderData *defining_loader_data = k->class_loader_data();
D
duke 已提交
1174 1175 1176

      MutexLocker mu(SystemDictionary_lock, THREAD);

1177
      Klass* check = find_class(parsed_name, loader_data);
D
duke 已提交
1178 1179
      assert(check == k(), "should be present in the dictionary");

1180
      Klass* check2 = find_class(h_name, defining_loader_data);
D
duke 已提交
1181 1182 1183 1184 1185 1186 1187
      assert(check == check2, "name inconsistancy in SystemDictionary");
    }
  } );

  return k();
}

1188
#if INCLUDE_CDS
Z
zgu 已提交
1189
void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,
D
duke 已提交
1190
                                             int number_of_entries) {
Z
zgu 已提交
1191
  assert(length == _nof_buckets * sizeof(HashtableBucket<mtClass>),
D
duke 已提交
1192 1193 1194 1195 1196 1197 1198 1199
         "bad shared dictionary size.");
  _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
}


// If there is a shared dictionary, then find the entry for the
// given shared system class, if any.

1200
Klass* SystemDictionary::find_shared_class(Symbol* class_name) {
D
duke 已提交
1201
  if (shared_dictionary() != NULL) {
1202
    unsigned int d_hash = shared_dictionary()->compute_hash(class_name, NULL);
1203
    int d_index = shared_dictionary()->hash_to_index(d_hash);
1204

D
duke 已提交
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
  } else {
    return NULL;
  }
}


// Load a class from the shared spaces (found through the shared system
// dictionary).  Force the superclass and all interfaces to be loaded.
// Update the class definition to include sibling classes and no
// subclasses (yet).  [Classes in the shared space are not part of the
// object hierarchy until loaded.]

instanceKlassHandle SystemDictionary::load_shared_class(
1219
                 Symbol* class_name, Handle class_loader, TRAPS) {
D
duke 已提交
1220
  instanceKlassHandle ik (THREAD, find_shared_class(class_name));
1221 1222 1223 1224 1225 1226 1227
  // Make sure we only return the boot class for the NULL classloader.
  if (ik.not_null() &&
      SharedClassUtil::is_shared_boot_class(ik()) && class_loader.is_null()) {
    Handle protection_domain;
    return load_shared_class(ik, class_loader, protection_domain, THREAD);
  }
  return instanceKlassHandle();
D
duke 已提交
1228 1229
}

1230 1231 1232
instanceKlassHandle SystemDictionary::load_shared_class(instanceKlassHandle ik,
                                                        Handle class_loader,
                                                        Handle protection_domain, TRAPS) {
D
duke 已提交
1233 1234
  if (ik.not_null()) {
    instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1235
    Symbol* class_name = ik->name();
D
duke 已提交
1236 1237 1238 1239 1240 1241

    // Found the class, now load the superclass and interfaces.  If they
    // are shared, add them to the main system dictionary and reset
    // their hierarchy references (supers, subs, and interfaces).

    if (ik->super() != NULL) {
1242
      Symbol*  cn = ik->super()->name();
I
iklam 已提交
1243 1244 1245 1246 1247 1248 1249
      Klass *s = resolve_super_or_fail(class_name, cn,
                                       class_loader, protection_domain, true, CHECK_(nh));
      if (s != ik->super()) {
        // The dynamically resolved super class is not the same as the one we used during dump time,
        // so we cannot use ik.
        return nh;
      }
D
duke 已提交
1250 1251
    }

1252
    Array<Klass*>* interfaces = ik->local_interfaces();
D
duke 已提交
1253 1254
    int num_interfaces = interfaces->length();
    for (int index = 0; index < num_interfaces; index++) {
1255
      Klass* k = interfaces->at(index);
D
duke 已提交
1256

1257 1258
      // Note: can not use InstanceKlass::cast here because
      // interfaces' InstanceKlass's C++ vtbls haven't been
D
duke 已提交
1259 1260
      // reinitialized yet (they will be once the interface classes
      // are loaded)
1261
      Symbol*  name  = k->name();
I
iklam 已提交
1262 1263 1264 1265 1266 1267
      Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_(nh));
      if (k != i) {
        // The dynamically resolved interface class is not the same as the one we used during dump time,
        // so we cannot use ik.
        return nh;
      }
D
duke 已提交
1268 1269 1270 1271 1272 1273 1274 1275
    }

    // Adjust methods to recover missing data.  They need addresses for
    // interpreter entry points and their default native method address
    // must be reset.

    // Updating methods must be done under a lock so multiple
    // threads don't update these in parallel
1276 1277 1278 1279
    //
    // Shared classes are all currently loaded by either the bootstrap or
    // internal parallel class loaders, so this will never cause a deadlock
    // on a custom class loader lock.
D
duke 已提交
1280

1281
    ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
D
duke 已提交
1282 1283 1284 1285
    {
      Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
      check_loader_lock_contention(lockObject, THREAD);
      ObjectLocker ol(lockObject, THREAD, true);
1286
      ik->restore_unshareable_info(loader_data, protection_domain, CHECK_(nh));
D
duke 已提交
1287 1288 1289 1290 1291 1292
    }

    if (TraceClassLoading) {
      ResourceMark rm;
      tty->print("[Loaded %s", ik->external_name());
      tty->print(" from shared objects file");
1293 1294 1295
      if (class_loader.not_null()) {
        tty->print(" by %s", loader_data->loader_name());
      }
D
duke 已提交
1296 1297
      tty->print_cr("]");
    }
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307

    if (DumpLoadedClassList != NULL && classlist_file->is_open()) {
      // Only dump the classes that can be stored into CDS archive
      if (SystemDictionaryShared::is_sharing_possible(loader_data)) {
        ResourceMark rm(THREAD);
        classlist_file->print_cr("%s", ik->name()->as_C_string());
        classlist_file->flush();
      }
    }

D
duke 已提交
1308
    // notify a class loaded from shared object
1309
    ClassLoadingService::notify_class_loaded(InstanceKlass::cast(ik()),
D
duke 已提交
1310 1311 1312 1313
                                             true /* shared class */);
  }
  return ik;
}
I
iklam 已提交
1314
#endif // INCLUDE_CDS
D
duke 已提交
1315

1316
instanceKlassHandle SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {
D
duke 已提交
1317 1318
  instanceKlassHandle nh = instanceKlassHandle(); // null Handle
  if (class_loader.is_null()) {
1319

D
duke 已提交
1320 1321 1322
    // Search the shared system dictionary for classes preloaded into the
    // shared spaces.
    instanceKlassHandle k;
1323
    {
1324
#if INCLUDE_CDS
1325 1326
      PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
      k = load_shared_class(class_name, class_loader, THREAD);
1327
#endif
1328
    }
D
duke 已提交
1329 1330 1331

    if (k.is_null()) {
      // Use VM class loader
1332
      PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
D
duke 已提交
1333 1334 1335
      k = ClassLoader::load_classfile(class_name, CHECK_(nh));
    }

1336
    // find_or_define_instance_class may return a different InstanceKlass
D
duke 已提交
1337 1338 1339
    if (!k.is_null()) {
      k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
    }
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
#if INCLUDE_JFR
    else {
      assert(jfr_event_handler_proxy != NULL, "invariant");
      if (class_name == jfr_event_handler_proxy) {
        // EventHandlerProxy class is generated dynamically in
        // EventHandlerProxyCreator::makeEventHandlerProxyClass
        // method, so we generate a Java call from here.
        //
        // EventHandlerProxy class will finally be defined in
        // SystemDictionary::resolve_from_stream method, down
        // the call stack. Bootstrap classloader is parallel-capable,
        // so no concurrency issues are expected.
        CLEAR_PENDING_EXCEPTION;
        k = JfrUpcalls::load_event_handler_proxy_class(THREAD);
        assert(!k.is_null(), "invariant");
      }
    }
#endif // INCLUDE_JFR

D
duke 已提交
1359 1360 1361 1362 1363
    return k;
  } else {
    // Use user specified class loader to load class. Call loadClass operation on class_loader.
    ResourceMark rm(THREAD);

1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
    assert(THREAD->is_Java_thread(), "must be a JavaThread");
    JavaThread* jt = (JavaThread*) THREAD;

    PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
                               ClassLoader::perf_app_classload_selftime(),
                               ClassLoader::perf_app_classload_count(),
                               jt->get_thread_stat()->perf_recursion_counts_addr(),
                               jt->get_thread_stat()->perf_timers_addr(),
                               PerfClassTraceTime::CLASS_LOAD);

D
duke 已提交
1374 1375 1376 1377 1378 1379
    Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
    // Translate to external class name format, i.e., convert '/' chars to '.'
    Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));

    JavaValue result(T_OBJECT);

1380
    KlassHandle spec_klass (THREAD, SystemDictionary::ClassLoader_klass());
D
duke 已提交
1381

1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    // Call public unsynchronized loadClass(String) directly for all class loaders
    // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will
    // acquire a class-name based lock rather than the class loader object lock.
    // JDK < 7 already acquire the class loader lock in loadClass(String, boolean),
    // so the call to loadClassInternal() was not required.
    //
    // UnsyncloadClass flag means both call loadClass(String) and do
    // not acquire the class loader lock even for class loaders that are
    // not parallelCapable. This was a risky transitional
    // flag for diagnostic purposes only. It is risky to call
D
duke 已提交
1392 1393
    // custom class loaders without synchronization.
    // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
1394
    // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.
D
duke 已提交
1395
    // Do NOT assume this will be supported in future releases.
1396 1397 1398 1399
    //
    // Added MustCallLoadClassInternal in case we discover in the field
    // a customer that counts on this call
    if (MustCallLoadClassInternal && has_loadClassInternal()) {
D
duke 已提交
1400 1401 1402
      JavaCalls::call_special(&result,
                              class_loader,
                              spec_klass,
1403 1404
                              vmSymbols::loadClassInternal_name(),
                              vmSymbols::string_class_signature(),
D
duke 已提交
1405 1406 1407 1408 1409 1410
                              string,
                              CHECK_(nh));
    } else {
      JavaCalls::call_virtual(&result,
                              class_loader,
                              spec_klass,
1411 1412
                              vmSymbols::loadClass_name(),
                              vmSymbols::string_class_signature(),
D
duke 已提交
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
                              string,
                              CHECK_(nh));
    }

    assert(result.get_type() == T_OBJECT, "just checking");
    oop obj = (oop) result.get_jobject();

    // Primitive classes return null since forName() can not be
    // used to obtain any of the Class objects representing primitives or void
    if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
      instanceKlassHandle k =
1424
                instanceKlassHandle(THREAD, java_lang_Class::as_Klass(obj));
D
duke 已提交
1425 1426 1427
      // For user defined Java class loaders, check that the name returned is
      // the same as that requested.  This check is done for the bootstrap
      // loader when parsing the class file.
1428
      if (class_name == k->name()) {
D
duke 已提交
1429 1430 1431 1432 1433 1434 1435 1436
        return k;
      }
    }
    // Class is not found or has the wrong name, return NULL
    return nh;
  }
}

A
apetushkov 已提交
1437 1438 1439 1440 1441 1442 1443 1444 1445
static void post_class_define_event(InstanceKlass* k, const ClassLoaderData* def_cld) {
  EventClassDefine event;
  if (event.should_commit()) {
    event.set_definedClass(k);
    event.set_definingClassLoader(def_cld);
    event.commit();
  }
}

D
duke 已提交
1446 1447
void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {

1448 1449 1450 1451
  ClassLoaderData* loader_data = k->class_loader_data();
  Handle class_loader_h(THREAD, loader_data->class_loader());

  for (uintx it = 0; it < GCExpandToAllocateDelayMillis; it++){}
D
duke 已提交
1452

1453 1454 1455 1456 1457 1458
 // for bootstrap and other parallel classloaders don't acquire lock,
 // use placeholder token
 // If a parallelCapable class loader calls define_instance_class instead of
 // find_or_define_instance_class to get here, we have a timing
 // hole with systemDictionary updates and check_constraints
 if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
D
duke 已提交
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
    assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
         compute_loader_lock_object(class_loader_h, THREAD)),
         "define called without lock");
  }

  // Check class-loading constraints. Throw exception if violation is detected.
  // Grabs and releases SystemDictionary_lock
  // The check_constraints/find_class call and update_dictionary sequence
  // must be "atomic" for a specific class/classloader pair so we never
  // define two different instanceKlasses for that class/classloader pair.
  // Existing classloaders will call define_instance_class with the
  // classloader lock held
  // Parallel classloaders will call find_or_define_instance_class
  // which will require a token to perform the define class
1473
  Symbol*  name_h = k->name();
1474
  unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
D
duke 已提交
1475 1476 1477
  int d_index = dictionary()->hash_to_index(d_hash);
  check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);

1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
  // Register class just loaded with class loader (placed in Vector)
  // Note we do this before updating the dictionary, as this can
  // fail with an OutOfMemoryError (if it does, we will *not* put this
  // class in the dictionary and will not update the class hierarchy).
  // JVMTI FollowReferences needs to find the classes this way.
  if (k->class_loader() != NULL) {
    methodHandle m(THREAD, Universe::loader_addClass_method());
    JavaValue result(T_VOID);
    JavaCallArguments args(class_loader_h);
    args.push_oop(Handle(THREAD, k->java_mirror()));
    JavaCalls::call(&result, m, &args, CHECK);
  }

D
duke 已提交
1491 1492
  // Add the new class. We need recompile lock during update of CHA.
  {
1493
    unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
D
duke 已提交
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
    int p_index = placeholders()->hash_to_index(p_hash);

    MutexLocker mu_r(Compile_lock, THREAD);

    // Add to class hierarchy, initialize vtables, and do possible
    // deoptimizations.
    add_to_hierarchy(k, CHECK); // No exception, but can block

    // Add to systemDictionary - so other classes can see it.
    // Grabs and releases SystemDictionary_lock
    update_dictionary(d_index, d_hash, p_index, p_hash,
                      k, class_loader_h, THREAD);
  }
  k->eager_initialize(THREAD);

  // notify jvmti
  if (JvmtiExport::should_post_class_load()) {
      assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
      JvmtiExport::post_class_load((JavaThread *) THREAD, k());

  }
S
sla 已提交
1515

A
apetushkov 已提交
1516
  post_class_define_event(k(), loader_data);
D
duke 已提交
1517 1518 1519
}

// Support parallel classloading
1520 1521 1522
// All parallel class loaders, including bootstrap classloader
// lock a placeholder entry for this class/class_loader pair
// to allow parallel defines of different classes for this class loader
1523 1524
// With AllowParallelDefine flag==true, in case they do not synchronize around
// FindLoadedClass/DefineClass, calls, we check for parallel
D
duke 已提交
1525 1526
// loading for them, wait if a defineClass is in progress
// and return the initial requestor's results
1527
// This flag does not apply to the bootstrap classloader.
1528 1529
// With AllowParallelDefine flag==false, call through to define_instance_class
// which will throw LinkageError: duplicate class definition.
1530
// False is the requested default.
D
duke 已提交
1531
// For better performance, the class loaders should synchronize
1532
// findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
D
duke 已提交
1533 1534
// potentially waste time reading and parsing the bytestream.
// Note: VM callers should ensure consistency of k/class_name,class_loader
1535
instanceKlassHandle SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
D
duke 已提交
1536 1537

  instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1538
  Symbol*  name_h = k->name(); // passed in class_name may be null
1539
  ClassLoaderData* loader_data = class_loader_data(class_loader);
D
duke 已提交
1540

1541
  unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
D
duke 已提交
1542 1543 1544
  int d_index = dictionary()->hash_to_index(d_hash);

// Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1545
  unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
D
duke 已提交
1546 1547 1548 1549 1550 1551
  int p_index = placeholders()->hash_to_index(p_hash);
  PlaceholderEntry* probe;

  {
    MutexLocker mu(SystemDictionary_lock, THREAD);
    // First check if class already defined
1552
    if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
1553
      Klass* check = find_class(d_index, d_hash, name_h, loader_data);
1554 1555 1556
      if (check != NULL) {
        return(instanceKlassHandle(THREAD, check));
      }
D
duke 已提交
1557 1558 1559
    }

    // Acquire define token for this class/classloader
1560
    probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
    // Wait if another thread defining in parallel
    // All threads wait - even those that will throw duplicate class: otherwise
    // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
    // if other thread has not finished updating dictionary
    while (probe->definer() != NULL) {
      SystemDictionary_lock->wait();
    }
    // Only special cases allow parallel defines and can use other thread's results
    // Other cases fall through, and may run into duplicate defines
    // caught by finding an entry in the SystemDictionary
H
hseigel 已提交
1571
    if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
1572
        placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1573
        SystemDictionary_lock->notify_all();
D
duke 已提交
1574
#ifdef ASSERT
1575
        Klass* check = find_class(d_index, d_hash, name_h, loader_data);
1576
        assert(check != NULL, "definer missed recording success");
D
duke 已提交
1577
#endif
H
hseigel 已提交
1578
        return(instanceKlassHandle(THREAD, probe->instance_klass()));
1579 1580 1581
    } else {
      // This thread will define the class (even if earlier thread tried and had an error)
      probe->set_definer(THREAD);
D
duke 已提交
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
    }
  }

  define_instance_class(k, THREAD);

  Handle linkage_exception = Handle(); // null handle

  // definer must notify any waiting threads
  {
    MutexLocker mu(SystemDictionary_lock, THREAD);
1592
    PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
D
duke 已提交
1593 1594 1595 1596 1597 1598
    assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
    if (probe != NULL) {
      if (HAS_PENDING_EXCEPTION) {
        linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
        CLEAR_PENDING_EXCEPTION;
      } else {
H
hseigel 已提交
1599
        probe->set_instance_klass(k());
D
duke 已提交
1600 1601
      }
      probe->set_definer(NULL);
1602
      placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
D
duke 已提交
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
      SystemDictionary_lock->notify_all();
    }
  }

  // Can't throw exception while holding lock due to rank ordering
  if (linkage_exception() != NULL) {
    THROW_OOP_(linkage_exception(), nh); // throws exception and returns
  }

  return k;
}
Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
  // If class_loader is NULL we synchronize on _system_loader_lock_obj
  if (class_loader.is_null()) {
    return Handle(THREAD, _system_loader_lock_obj);
  } else {
    return class_loader;
  }
}

// This method is added to check how often we have to wait to grab loader
// lock. The results are being recorded in the performance counters defined in
// ClassLoader::_sync_systemLoaderLockContentionRate and
// ClassLoader::_sync_nonSystemLoaderLockConteionRate.
void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
  if (!UsePerfData) {
    return;
  }

  assert(!loader_lock.is_null(), "NULL lock object");

  if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
      == ObjectSynchronizer::owner_other) {
    // contention will likely happen, so increment the corresponding
    // contention counter.
    if (loader_lock() == _system_loader_lock_obj) {
      ClassLoader::sync_systemLoaderLockContentionRate()->inc();
    } else {
      ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
    }
  }
}

// ----------------------------------------------------------------------------
// Lookup

1649
Klass* SystemDictionary::find_class(int index, unsigned int hash,
1650
                                      Symbol* class_name,
1651
                                      ClassLoaderData* loader_data) {
D
duke 已提交
1652
  assert_locked_or_safepoint(SystemDictionary_lock);
1653
  assert (index == dictionary()->index_for(class_name, loader_data),
D
duke 已提交
1654 1655
          "incorrect index?");

1656
  Klass* k = dictionary()->find_class(index, hash, class_name, loader_data);
D
duke 已提交
1657 1658 1659 1660 1661
  return k;
}


// Basic find on classes in the midst of being loaded
1662
Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1663
                                           ClassLoaderData* loader_data) {
D
duke 已提交
1664
  assert_locked_or_safepoint(SystemDictionary_lock);
1665
  unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);
1666
  int p_index = placeholders()->hash_to_index(p_hash);
1667
  return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
D
duke 已提交
1668 1669 1670 1671
}


// Used for assertions and verification only
1672
Klass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
D
duke 已提交
1673
  #ifndef ASSERT
1674 1675 1676 1677
  guarantee(VerifyBeforeGC      ||
            VerifyDuringGC      ||
            VerifyBeforeExit    ||
            VerifyDuringStartup ||
D
duke 已提交
1678 1679 1680 1681 1682
            VerifyAfterGC, "too expensive");
  #endif
  assert_locked_or_safepoint(SystemDictionary_lock);

  // First look in the loaded class array
1683
  unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
D
duke 已提交
1684
  int d_index = dictionary()->hash_to_index(d_hash);
1685
  return find_class(d_index, d_hash, class_name, loader_data);
D
duke 已提交
1686 1687 1688 1689
}


// Get the next class in the diictionary.
1690
Klass* SystemDictionary::try_get_next_class() {
D
duke 已提交
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
  return dictionary()->try_get_next_class();
}


// ----------------------------------------------------------------------------
// Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
// is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
// before a new class is used.

void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
  assert(k.not_null(), "just checking");
1702 1703
  assert_locked_or_safepoint(Compile_lock);

D
duke 已提交
1704 1705 1706
  // Link into hierachy. Make sure the vtables are initialized before linking into
  k->append_to_sibling_list();                    // add to superklass/sibling list
  k->process_interfaces(THREAD);                  // handle all "implements" declarations
1707
  k->set_init_state(InstanceKlass::loaded);
D
duke 已提交
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
  // Now flush all code that depended on old class hierarchy.
  // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
  // Also, first reinitialize vtable because it may have gotten out of synch
  // while the new class wasn't connected to the class hierarchy.
  Universe::flush_dependents_on(k);
}

// ----------------------------------------------------------------------------
// GC support

// Following roots during mark-sweep is separated in two phases.
//
// The first phase follows preloaded classes and all other system
// classes, since these will never get unloaded anyway.
//
// The second phase removes (unloads) unreachable classes from the
// system dictionary and follows the remaining classes' contents.

void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
1727
  roots_oops_do(blk, NULL);
D
duke 已提交
1728 1729
}

1730 1731 1732
void SystemDictionary::always_strong_classes_do(KlassClosure* closure) {
  // Follow all system classes and temporary placeholders in dictionary
  dictionary()->always_strong_classes_do(closure);
D
duke 已提交
1733

1734 1735
  // Placeholders. These represent classes we're actively loading.
  placeholders()->classes_do(closure);
D
duke 已提交
1736 1737
}

1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
// Calculate a "good" systemdictionary size based
// on predicted or current loaded classes count
int SystemDictionary::calculate_systemdictionary_size(int classcount) {
  int newsize = _old_default_sdsize;
  if ((classcount > 0)  && !DumpSharedSpaces) {
    int desiredsize = classcount/_average_depth_goal;
    for (newsize = _primelist[_sdgeneration]; _sdgeneration < _prime_array_size -1;
         newsize = _primelist[++_sdgeneration]) {
      if (desiredsize <=  newsize) {
        break;
      }
    }
  }
  return newsize;
}
S
sla 已提交
1753

1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
#ifdef ASSERT
class VerifySDReachableAndLiveClosure : public OopClosure {
private:
  BoolObjectClosure* _is_alive;

  template <class T> void do_oop_work(T* p) {
    oop obj = oopDesc::load_decode_heap_oop(p);
    guarantee(_is_alive->do_object_b(obj), "Oop in system dictionary must be live");
  }

public:
  VerifySDReachableAndLiveClosure(BoolObjectClosure* is_alive) : OopClosure(), _is_alive(is_alive) { }

  virtual void do_oop(oop* p)       { do_oop_work(p); }
  virtual void do_oop(narrowOop* p) { do_oop_work(p); }
};
#endif

1772 1773
// Assumes classes in the SystemDictionary are only unloaded at a safepoint
// Note: anonymous classes are not in the SD.
1774
bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive, bool clean_alive) {
1775
  // First, mark for unload all ClassLoaderData referencing a dead class loader.
1776
  bool unloading_occurred = ClassLoaderDataGraph::do_unloading(is_alive, clean_alive);
1777
  if (unloading_occurred) {
1778
    JFR_ONLY(Jfr::on_unloading_classes();)
1779
    dictionary()->do_unloading();
1780 1781
    constraints()->purge_loader_constraints();
    resolution_errors()->purge_resolution_errors();
1782 1783 1784 1785 1786 1787 1788 1789 1790
  }
  // Oops referenced by the system dictionary may get unreachable independently
  // of the class loader (eg. cached protection domain oops). So we need to
  // explicitly unlink them here instead of in Dictionary::do_unloading.
  dictionary()->unlink(is_alive);
#ifdef ASSERT
  VerifySDReachableAndLiveClosure cl(is_alive);
  dictionary()->oops_do(&cl);
#endif
1791
  return unloading_occurred;
D
duke 已提交
1792 1793
}

1794 1795 1796
void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
  strong->do_oop(&_java_system_loader);
  strong->do_oop(&_system_loader_lock_obj);
1797
  CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);)
1798 1799 1800 1801 1802 1803 1804 1805

  // Adjust dictionary
  dictionary()->roots_oops_do(strong, weak);

  // Visit extra methods
  invoke_method_table()->oops_do(strong);
}

D
duke 已提交
1806 1807
void SystemDictionary::oops_do(OopClosure* f) {
  f->do_oop(&_java_system_loader);
1808
  f->do_oop(&_system_loader_lock_obj);
1809
  CDS_ONLY(SystemDictionaryShared::oops_do(f);)
D
duke 已提交
1810 1811 1812 1813

  // Adjust dictionary
  dictionary()->oops_do(f);

1814
  // Visit extra methods
1815
  invoke_method_table()->oops_do(f);
D
duke 已提交
1816 1817
}

1818 1819 1820 1821 1822
// Extended Class redefinition support.
// If one of these classes is replaced, we need to replace it in these places.
// KlassClosure::do_klass should take the address of a class but we can
// change that later.
void SystemDictionary::preloaded_classes_do(KlassClosure* f) {
1823
  for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {
1824
    f->do_klass(_well_known_klasses[k]);
1825 1826
  }

D
duke 已提交
1827 1828 1829 1830
  {
    for (int i = 0; i < T_VOID+1; i++) {
      if (_box_klasses[i] != NULL) {
        assert(i >= T_BOOLEAN, "checking");
1831
        f->do_klass(_box_klasses[i]);
D
duke 已提交
1832 1833 1834 1835
      }
    }
  }

1836
  FilteredFieldsMap::classes_do(f);
D
duke 已提交
1837 1838
}

1839 1840
void SystemDictionary::lazily_loaded_classes_do(KlassClosure* f) {
  f->do_klass(_abstract_ownable_synchronizer_klass);
D
duke 已提交
1841 1842 1843 1844
}

// Just the classes from defining class loaders
// Don't iterate over placeholders
1845
void SystemDictionary::classes_do(void f(Klass*)) {
D
duke 已提交
1846 1847 1848 1849 1850 1851
  dictionary()->classes_do(f);
}

// Added for initialize_itable_for_klass
//   Just the classes from defining class loaders
// Don't iterate over placeholders
1852
void SystemDictionary::classes_do(void f(Klass*, TRAPS), TRAPS) {
D
duke 已提交
1853 1854 1855 1856 1857
  dictionary()->classes_do(f, CHECK);
}

//   All classes, and their class loaders
// Don't iterate over placeholders
1858
void SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*)) {
D
duke 已提交
1859 1860 1861
  dictionary()->classes_do(f);
}

1862
void SystemDictionary::placeholders_do(void f(Symbol*)) {
D
duke 已提交
1863 1864 1865
  placeholders()->entries_do(f);
}

1866
void SystemDictionary::methods_do(void f(Method*)) {
D
duke 已提交
1867
  dictionary()->methods_do(f);
1868
  invoke_method_table()->methods_do(f);
D
duke 已提交
1869 1870
}

1871 1872 1873 1874
void SystemDictionary::remove_classes_in_error_state() {
  dictionary()->remove_classes_in_error_state();
}

D
duke 已提交
1875 1876 1877 1878 1879 1880 1881 1882 1883
// ----------------------------------------------------------------------------
// Lazily load klasses

void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
  assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later");

  // if multiple threads calling this function, only one thread will load
  // the class.  The other threads will find the loaded version once the
  // class is loaded.
1884
  Klass* aos = _abstract_ownable_synchronizer_klass;
D
duke 已提交
1885
  if (aos == NULL) {
1886
    Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
D
duke 已提交
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
    // Force a fence to prevent any read before the write completes
    OrderAccess::fence();
    _abstract_ownable_synchronizer_klass = k;
  }
}

// ----------------------------------------------------------------------------
// Initialization

void SystemDictionary::initialize(TRAPS) {
  // Allocate arrays
  assert(dictionary() == NULL,
         "SystemDictionary should only be initialized once");
1900 1901
  _sdgeneration        = 0;
  _dictionary          = new Dictionary(calculate_systemdictionary_size(PredictedLoadedClassCount));
1902
  _placeholders        = new PlaceholderTable(_nof_buckets);
D
duke 已提交
1903
  _number_of_modifications = 0;
1904 1905 1906
  _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
  _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
  _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
D
duke 已提交
1907 1908

  // Allocate private object used as system class loader lock
1909
  _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
D
duke 已提交
1910 1911
  // Initialize basic classes
  initialize_preloaded_classes(CHECK);
1912 1913 1914
#if INCLUDE_JFR
  jfr_event_handler_proxy = SymbolTable::new_permanent_symbol("jdk/jfr/proxy/internal/EventHandlerProxy", CHECK);
#endif // INCLUDE_JFR
D
duke 已提交
1915 1916
}

1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
// Compact table of directions on the initialization of klasses:
static const short wk_init_info[] = {
  #define WK_KLASS_INIT_INFO(name, symbol, option) \
    ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
          << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
      | (int)SystemDictionary::option ),
  WK_KLASSES_DO(WK_KLASS_INIT_INFO)
  #undef WK_KLASS_INIT_INFO
  0
};

bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
  assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
  int  info = wk_init_info[id - FIRST_WKID];
  int  sid  = (info >> CEIL_LG_OPTION_LIMIT);
1932
  Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
1933
  Klass**    klassp = &_well_known_klasses[id];
1934
  bool must_load = (init_opt < SystemDictionary::Opt);
Z
zgu 已提交
1935
  if ((*klassp) == NULL) {
1936 1937 1938 1939 1940 1941
    if (must_load) {
      (*klassp) = resolve_or_fail(symbol, true, CHECK_0); // load required class
    } else {
      (*klassp) = resolve_or_null(symbol,       CHECK_0); // load optional klass
    }
  }
1942
  return ((*klassp) != NULL);
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
}

void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
  assert((int)start_id <= (int)limit_id, "IDs are out of order!");
  for (int id = (int)start_id; id < (int)limit_id; id++) {
    assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
    int info = wk_init_info[id - FIRST_WKID];
    int sid  = (info >> CEIL_LG_OPTION_LIMIT);
    int opt  = (info & right_n_bits(CEIL_LG_OPTION_LIMIT));

    initialize_wk_klass((WKID)id, opt, CHECK);
  }
1955 1956 1957

  // move the starting value forward to the limit:
  start_id = limit_id;
1958 1959
}

D
duke 已提交
1960
void SystemDictionary::initialize_preloaded_classes(TRAPS) {
1961
  assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once");
D
duke 已提交
1962
  // Preload commonly used klasses
1963
  WKID scan = FIRST_WKID;
1964 1965 1966 1967 1968 1969
  // first do Object, then String, Class
  if (UseSharedSpaces) {
    initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK);
    // Initialize the constant pool for the Object_class
    InstanceKlass* ik = InstanceKlass::cast(Object_klass());
    ik->constants()->restore_unshareable_info(CHECK);
1970
    initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
1971 1972 1973
  } else {
    initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
  }
1974

K
kvn 已提交
1975 1976 1977
  // Calculate offsets for String and Class classes since they are loaded and
  // can be used after this point.
  java_lang_String::compute_offsets();
1978
  java_lang_Class::compute_offsets();
1979

D
duke 已提交
1980 1981 1982 1983 1984 1985 1986 1987
  // Fixup mirrors for classes loaded before java.lang.Class.
  // These calls iterate over the objects currently in the perm gen
  // so calling them at this point is matters (not before when there
  // are fewer objects and not later after there are more objects
  // in the perm gen.
  Universe::initialize_basic_type_mirrors(CHECK);
  Universe::fixup_mirrors(CHECK);

1988
  // do a bunch more:
1989
  initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);
D
duke 已提交
1990 1991

  // Preload ref klasses and set reference types
1992
  InstanceKlass::cast(WK_KLASS(Reference_klass))->set_reference_type(REF_OTHER);
1993
  InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass));
1994

1995
  initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Cleaner_klass), scan, CHECK);
1996 1997 1998 1999
  InstanceKlass::cast(WK_KLASS(SoftReference_klass))->set_reference_type(REF_SOFT);
  InstanceKlass::cast(WK_KLASS(WeakReference_klass))->set_reference_type(REF_WEAK);
  InstanceKlass::cast(WK_KLASS(FinalReference_klass))->set_reference_type(REF_FINAL);
  InstanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM);
2000
  InstanceKlass::cast(WK_KLASS(Cleaner_klass))->set_reference_type(REF_CLEANER);
2001

K
kbarrett 已提交
2002 2003
  initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(ReferenceQueue_klass), scan, CHECK);

2004 2005
  // JSR 292 classes
  WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
2006
  WKID jsr292_group_end   = WK_KLASS_ENUM_NAME(VolatileCallSite_klass);
2007
  initialize_wk_klasses_until(jsr292_group_start, scan, CHECK);
2008
  if (EnableInvokeDynamic) {
2009 2010 2011 2012
    initialize_wk_klasses_through(jsr292_group_end, scan, CHECK);
  } else {
    // Skip the JSR 292 classes, if not enabled.
    scan = WKID(jsr292_group_end + 1);
2013
  }
2014

2015 2016
  initialize_wk_klasses_until(WKID_LIMIT, scan, CHECK);

2017 2018 2019 2020 2021 2022 2023 2024
  _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass);
  _box_klasses[T_CHAR]    = WK_KLASS(Character_klass);
  _box_klasses[T_FLOAT]   = WK_KLASS(Float_klass);
  _box_klasses[T_DOUBLE]  = WK_KLASS(Double_klass);
  _box_klasses[T_BYTE]    = WK_KLASS(Byte_klass);
  _box_klasses[T_SHORT]   = WK_KLASS(Short_klass);
  _box_klasses[T_INT]     = WK_KLASS(Integer_klass);
  _box_klasses[T_LONG]    = WK_KLASS(Long_klass);
2025 2026 2027
  //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
  //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);

D
duke 已提交
2028
  { // Compute whether we should use loadClass or loadClassInternal when loading classes.
2029
    Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
D
duke 已提交
2030 2031 2032
    _has_loadClassInternal = (method != NULL);
  }
  { // Compute whether we should use checkPackageAccess or NOT
2033
    Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
D
duke 已提交
2034 2035 2036 2037 2038 2039
    _has_checkPackageAccess = (method != NULL);
  }
}

// Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
// If so, returns the basic type it holds.  If not, returns T_OBJECT.
2040
BasicType SystemDictionary::box_klass_type(Klass* k) {
D
duke 已提交
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
  assert(k != NULL, "");
  for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
    if (_box_klasses[i] == k)
      return (BasicType)i;
  }
  return T_OBJECT;
}

// Constraints on class loaders. The details of the algorithm can be
// found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
// Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
// that the system dictionary needs to maintain a set of contraints that
// must be satisfied by all classes in the dictionary.
// if defining is true, then LinkageError if already in systemDictionary
2055
// if initiating loader, then ok if InstanceKlass matches existing entry
D
duke 已提交
2056 2057 2058 2059 2060 2061 2062

void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
                                         instanceKlassHandle k,
                                         Handle class_loader, bool defining,
                                         TRAPS) {
  const char *linkage_error = NULL;
  {
2063
    Symbol*  name  = k->name();
2064 2065
    ClassLoaderData *loader_data = class_loader_data(class_loader);

D
duke 已提交
2066 2067
    MutexLocker mu(SystemDictionary_lock, THREAD);

2068 2069 2070
    Klass* check = find_class(d_index, d_hash, name, loader_data);
    if (check != (Klass*)NULL) {
      // if different InstanceKlass - duplicate class definition,
D
duke 已提交
2071 2072 2073 2074 2075
      // else - ok, class loaded by a different thread in parallel,
      // we should only have found it if it was done loading and ok to use
      // system dictionary only holds instance classes, placeholders
      // also holds array classes

2076
      assert(check->oop_is_instance(), "noninstance in systemdictionary");
D
duke 已提交
2077 2078 2079 2080 2081 2082 2083 2084 2085
      if ((defining == true) || (k() != check)) {
        linkage_error = "loader (instance of  %s): attempted  duplicate class "
          "definition for name: \"%s\"";
      } else {
        return;
      }
    }

#ifdef ASSERT
2086
    Symbol* ph_check = find_placeholder(name, loader_data);
2087
    assert(ph_check == NULL || ph_check == name, "invalid symbol");
D
duke 已提交
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
#endif

    if (linkage_error == NULL) {
      if (constraints()->check_or_update(k, class_loader, name) == false) {
        linkage_error = "loader constraint violation: loader (instance of %s)"
          " previously initiated loading for a different type with name \"%s\"";
      }
    }
  }

  // Throw error now if needed (cannot throw while holding
  // SystemDictionary_lock because of rank ordering)

  if (linkage_error) {
    ResourceMark rm(THREAD);
    const char* class_loader_name = loader_name(class_loader());
    char* type_name = k->name()->as_C_string();
    size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +
      strlen(type_name);
    char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
    jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);
    THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
  }
}


// Update system dictionary - done after check_constraint and add_to_hierachy
// have been called.
void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
                                         int p_index, unsigned int p_hash,
                                         instanceKlassHandle k,
                                         Handle class_loader,
                                         TRAPS) {
  // Compile_lock prevents systemDictionary updates during compilations
  assert_locked_or_safepoint(Compile_lock);
2123
  Symbol*  name  = k->name();
2124
  ClassLoaderData *loader_data = class_loader_data(class_loader);
D
duke 已提交
2125 2126 2127 2128 2129 2130 2131 2132 2133

  {
  MutexLocker mu1(SystemDictionary_lock, THREAD);

  // See whether biased locking is enabled and if so set it for this
  // klass.
  // Note that this must be done past the last potential blocking
  // point / safepoint. We enable biased locking lazily using a
  // VM_Operation to iterate the SystemDictionary and installing the
2134
  // biasable mark word into each InstanceKlass's prototype header.
D
duke 已提交
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
  // To avoid race conditions where we accidentally miss enabling the
  // optimization for one class in the process of being added to the
  // dictionary, we must not safepoint after the test of
  // BiasedLocking::enabled().
  if (UseBiasedLocking && BiasedLocking::enabled()) {
    // Set biased locking bit for all loaded classes; it will be
    // cleared if revocation occurs too often for this type
    // NOTE that we must only do this when the class is initally
    // defined, not each time it is referenced from a new class loader
    if (k->class_loader() == class_loader()) {
      k->set_prototype_header(markOopDesc::biased_locking_prototype());
    }
  }

2149
  // Make a new system dictionary entry.
2150
  Klass* sd_check = find_class(d_index, d_hash, name, loader_data);
D
duke 已提交
2151
  if (sd_check == NULL) {
2152
    dictionary()->add_klass(name, loader_data, k);
D
duke 已提交
2153 2154 2155
    notice_modification();
  }
#ifdef ASSERT
2156
  sd_check = find_class(d_index, d_hash, name, loader_data);
D
duke 已提交
2157
  assert (sd_check != NULL, "should have entry in system dictionary");
2158 2159
  // Note: there may be a placeholder entry: for circularity testing
  // or for parallel defines
D
duke 已提交
2160 2161 2162 2163 2164 2165
#endif
    SystemDictionary_lock->notify_all();
  }
}


2166 2167 2168
// Try to find a class name using the loader constraints.  The
// loader constraints might know about a class that isn't fully loaded
// yet and these will be ignored.
2169
Klass* SystemDictionary::find_constrained_instance_or_array_klass(
2170
                    Symbol* class_name, Handle class_loader, TRAPS) {
D
duke 已提交
2171 2172 2173 2174

  // First see if it has been loaded directly.
  // Force the protection domain to be null.  (This removes protection checks.)
  Handle no_protection_domain;
2175
  Klass* klass = find_instance_or_array_klass(class_name, class_loader,
2176
                                              no_protection_domain, CHECK_NULL);
D
duke 已提交
2177 2178 2179 2180 2181 2182
  if (klass != NULL)
    return klass;

  // Now look to see if it has been loaded elsewhere, and is subject to
  // a loader constraint that would require this loader to return the
  // klass that is already loaded.
2183
  if (FieldType::is_array(class_name)) {
2184 2185
    // For array classes, their Klass*s are not kept in the
    // constraint table. The element Klass*s are.
2186 2187
    FieldArrayInfo fd;
    BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
D
duke 已提交
2188 2189 2190 2191
    if (t != T_OBJECT) {
      klass = Universe::typeArrayKlassObj(t);
    } else {
      MutexLocker mu(SystemDictionary_lock, THREAD);
2192
      klass = constraints()->find_constrained_klass(fd.object_key(), class_loader);
D
duke 已提交
2193
    }
2194
    // If element class already loaded, allocate array klass
D
duke 已提交
2195
    if (klass != NULL) {
H
hseigel 已提交
2196
      klass = klass->array_klass_or_null(fd.dimension());
D
duke 已提交
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
    }
  } else {
    MutexLocker mu(SystemDictionary_lock, THREAD);
    // Non-array classes are easy: simply check the constraint table.
    klass = constraints()->find_constrained_klass(class_name, class_loader);
  }

  return klass;
}


2208
bool SystemDictionary::add_loader_constraint(Symbol* class_name,
D
duke 已提交
2209 2210 2211
                                             Handle class_loader1,
                                             Handle class_loader2,
                                             Thread* THREAD) {
2212 2213 2214
  ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
  ClassLoaderData* loader_data2 = class_loader_data(class_loader2);

2215 2216
  Symbol* constraint_name = NULL;
  if (!FieldType::is_array(class_name)) {
2217 2218
    constraint_name = class_name;
  } else {
2219
    // For array classes, their Klass*s are not kept in the
2220
    // constraint table. The element classes are.
2221 2222
    FieldArrayInfo fd;
    BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
2223 2224 2225 2226
    // primitive types always pass
    if (t != T_OBJECT) {
      return true;
    } else {
2227
      constraint_name = fd.object_key();
2228 2229
    }
  }
2230
  unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);
D
duke 已提交
2231 2232
  int d_index1 = dictionary()->hash_to_index(d_hash1);

2233
  unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);
D
duke 已提交
2234 2235
  int d_index2 = dictionary()->hash_to_index(d_hash2);
  {
2236
  MutexLocker mu_s(SystemDictionary_lock, THREAD);
D
duke 已提交
2237

2238 2239
  // Better never do a GC while we're holding these oops
  No_Safepoint_Verifier nosafepoint;
D
duke 已提交
2240

2241 2242
  Klass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1);
  Klass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2);
2243 2244
  return constraints()->add_entry(constraint_name, klass1, class_loader1,
                                  klass2, class_loader2);
D
duke 已提交
2245 2246 2247 2248 2249
  }
}

// Add entry to resolution error table to record the error when the first
// attempt to resolve a reference to a class has failed.
2250
void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which, Symbol* error) {
D
duke 已提交
2251 2252 2253 2254 2255 2256 2257 2258
  unsigned int hash = resolution_errors()->compute_hash(pool, which);
  int index = resolution_errors()->hash_to_index(hash);
  {
    MutexLocker ml(SystemDictionary_lock, Thread::current());
    resolution_errors()->add_entry(index, hash, pool, which, error);
  }
}

2259 2260 2261 2262 2263
// Delete a resolution error for RedefineClasses for a constant pool is going away
void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
  resolution_errors()->delete_entry(pool);
}

D
duke 已提交
2264
// Lookup resolution error table. Returns error if found, otherwise NULL.
2265
Symbol* SystemDictionary::find_resolution_error(constantPoolHandle pool, int which) {
D
duke 已提交
2266 2267 2268 2269 2270
  unsigned int hash = resolution_errors()->compute_hash(pool, which);
  int index = resolution_errors()->hash_to_index(hash);
  {
    MutexLocker ml(SystemDictionary_lock, Thread::current());
    ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2271
    return (entry != NULL) ? entry->error() : (Symbol*)NULL;
D
duke 已提交
2272 2273 2274 2275
  }
}


2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
// Signature constraints ensure that callers and callees agree about
// the meaning of type names in their signatures.  This routine is the
// intake for constraints.  It collects them from several places:
//
//  * LinkResolver::resolve_method (if check_access is true) requires
//    that the resolving class (the caller) and the defining class of
//    the resolved method (the callee) agree on each type in the
//    method's signature.
//
//  * LinkResolver::resolve_interface_method performs exactly the same
//    checks.
//
//  * LinkResolver::resolve_field requires that the constant pool
//    attempting to link to a field agree with the field's defining
//    class about the type of the field signature.
//
//  * klassVtable::initialize_vtable requires that, when a class
//    overrides a vtable entry allocated by a superclass, that the
//    overriding method (i.e., the callee) agree with the superclass
//    on each type in the method's signature.
//
//  * klassItable::initialize_itable requires that, when a class fills
//    in its itables, for each non-abstract method installed in an
//    itable, the method (i.e., the callee) agree with the interface
//    on each type in the method's signature.
//
// All those methods have a boolean (check_access, checkconstraints)
// which turns off the checks.  This is used from specialized contexts
// such as bootstrapping, dumping, and debugging.
//
// No direct constraint is placed between the class and its
// supertypes.  Constraints are only placed along linked relations
// between callers and callees.  When a method overrides or implements
// an abstract method in a supertype (superclass or interface), the
// constraints are placed as if the supertype were the caller to the
// overriding method.  (This works well, since callers to the
// supertype have already established agreement between themselves and
// the supertype.)  As a result of all this, a class can disagree with
// its supertype about the meaning of a type name, as long as that
// class neither calls a relevant method of the supertype, nor is
// called (perhaps via an override) from the supertype.
//
//
// SystemDictionary::check_signature_loaders(sig, l1, l2)
//
D
duke 已提交
2321 2322 2323
// Make sure all class components (including arrays) in the given
// signature will be resolved to the same class in both loaders.
// Returns the name of the type that failed a loader constraint check, or
2324
// NULL if no constraint failed.  No exception except OOME is thrown.
2325
// Arrays are not added to the loader constraint table, their elements are.
2326
Symbol* SystemDictionary::check_signature_loaders(Symbol* signature,
D
duke 已提交
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
                                               Handle loader1, Handle loader2,
                                               bool is_method, TRAPS)  {
  // Nothing to do if loaders are the same.
  if (loader1() == loader2()) {
    return NULL;
  }

  SignatureStream sig_strm(signature, is_method);
  while (!sig_strm.is_done()) {
    if (sig_strm.is_object()) {
2337
      Symbol* sig = sig_strm.as_symbol(CHECK_NULL);
D
duke 已提交
2338
      if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
2339
        return sig;
D
duke 已提交
2340 2341 2342 2343 2344 2345 2346 2347
      }
    }
    sig_strm.next();
  }
  return NULL;
}


2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
methodHandle SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid,
                                                            Symbol* signature,
                                                            TRAPS) {
  methodHandle empty;
  assert(EnableInvokeDynamic, "");
  assert(MethodHandles::is_signature_polymorphic(iid) &&
         MethodHandles::is_signature_polymorphic_intrinsic(iid) &&
         iid != vmIntrinsics::_invokeGeneric,
         err_msg("must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid)));

  unsigned int hash  = invoke_method_table()->compute_hash(signature, iid);
2359
  int          index = invoke_method_table()->hash_to_index(hash);
2360 2361
  SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid);
  methodHandle m;
2362
  if (spe == NULL || spe->method() == NULL) {
2363
    spe = NULL;
2364
    // Must create lots of stuff here, but outside of the SystemDictionary lock.
2365
    m = Method::make_method_handle_intrinsic(iid, signature, CHECK_(empty));
2366 2367 2368 2369 2370 2371 2372 2373
    if (!Arguments::is_interpreter_only()) {
      // Generate a compiled form of the MH intrinsic.
      AdapterHandlerLibrary::create_native_wrapper(m);
      // Check if have the compiled code.
      if (!m->has_compiled_code()) {
        THROW_MSG_(vmSymbols::java_lang_VirtualMachineError(),
                   "out of space in CodeCache for method handle intrinsic", empty);
      }
2374
    }
2375 2376
    // Now grab the lock.  We might have to throw away the new method,
    // if a racing thread has managed to install one at the same time.
2377 2378 2379
    {
      MutexLocker ml(SystemDictionary_lock, THREAD);
      spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2380
      if (spe == NULL)
2381
        spe = invoke_method_table()->add_entry(index, hash, signature, iid);
2382 2383
      if (spe->method() == NULL)
        spe->set_method(m());
2384 2385 2386
    }
  }

2387
  assert(spe != NULL && spe->method() != NULL, "");
2388
  assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
2389 2390
         spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
         "MH intrinsic invariant");
2391
  return spe->method();
2392 2393 2394 2395
}

// Helper for unpacking the return value from linkMethod and linkCallSite.
static methodHandle unpack_method_and_appendix(Handle mname,
2396
                                               KlassHandle accessing_klass,
2397 2398 2399 2400 2401
                                               objArrayHandle appendix_box,
                                               Handle* appendix_result,
                                               TRAPS) {
  methodHandle empty;
  if (mname.not_null()) {
2402
    Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
2403
    if (vmtarget != NULL && vmtarget->is_method()) {
2404
      Method* m = (Method*)vmtarget;
2405 2406 2407
      oop appendix = appendix_box->obj_at(0);
      if (TraceMethodHandles) {
    #ifndef PRODUCT
2408
        tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2409 2410 2411 2412
        m->print();
        if (appendix != NULL) { tty->print("appendix = "); appendix->print(); }
        tty->cr();
    #endif //PRODUCT
2413
      }
2414
      (*appendix_result) = Handle(THREAD, appendix);
2415 2416 2417 2418 2419 2420
      // the target is stored in the cpCache and if a reference to this
      // MethodName is dropped we need a way to make sure the
      // class_loader containing this method is kept alive.
      // FIXME: the appendix might also preserve this dependency.
      ClassLoaderData* this_key = InstanceKlass::cast(accessing_klass())->class_loader_data();
      this_key->record_dependency(m->method_holder(), CHECK_NULL); // Can throw OOM
2421
      return methodHandle(THREAD, m);
2422 2423
    }
  }
2424 2425 2426 2427 2428 2429 2430
  THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives", empty);
  return empty;
}

methodHandle SystemDictionary::find_method_handle_invoker(Symbol* name,
                                                          Symbol* signature,
                                                          KlassHandle accessing_klass,
2431 2432
                                                          Handle *appendix_result,
                                                          Handle *method_type_result,
2433 2434 2435 2436 2437 2438 2439
                                                          TRAPS) {
  methodHandle empty;
  assert(EnableInvokeDynamic, "");
  assert(!THREAD->is_Compiler_thread(), "");
  Handle method_type =
    SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_(empty));

2440
  KlassHandle  mh_klass = SystemDictionary::MethodHandle_klass();
2441 2442 2443 2444 2445
  int ref_kind = JVM_REF_invokeVirtual;
  Handle name_str = StringTable::intern(name, CHECK_(empty));
  objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
  assert(appendix_box->obj_at(0) == NULL, "");

2446 2447 2448 2449 2450
  // This should not happen.  JDK code should take care of that.
  if (accessing_klass.is_null() || method_type.is_null()) {
    THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokehandle", empty);
  }

2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465
  // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
  JavaCallArguments args;
  args.push_oop(accessing_klass()->java_mirror());
  args.push_int(ref_kind);
  args.push_oop(mh_klass()->java_mirror());
  args.push_oop(name_str());
  args.push_oop(method_type());
  args.push_oop(appendix_box());
  JavaValue result(T_OBJECT);
  JavaCalls::call_static(&result,
                         SystemDictionary::MethodHandleNatives_klass(),
                         vmSymbols::linkMethod_name(),
                         vmSymbols::linkMethod_signature(),
                         &args, CHECK_(empty));
  Handle mname(THREAD, (oop) result.get_jobject());
2466
  (*method_type_result) = method_type;
2467
  return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);
2468 2469
}

2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
// Decide if we can globally cache a lookup of this class, to be returned to any client that asks.
// We must ensure that all class loaders everywhere will reach this class, for any client.
// This is a safe bet for public classes in java.lang, such as Object and String.
// We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.
// Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.
static bool is_always_visible_class(oop mirror) {
  Klass* klass = java_lang_Class::as_Klass(mirror);
  if (klass->oop_is_objArray()) {
    klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type
  }
  if (klass->oop_is_typeArray()) {
    return true; // primitive array
  }
  assert(klass->oop_is_instance(), klass->external_name());
  return klass->is_public() &&
         (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) ||       // java.lang
          InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass()));  // java.lang.invoke
}
2488

2489
// Ask Java code to find or construct a java.lang.invoke.MethodType for the given
2490 2491 2492
// signature, as interpreted relative to the given class loader.
// Because of class loader constraints, all method handle usage must be
// consistent with this loader.
2493
Handle SystemDictionary::find_method_handle_type(Symbol* signature,
2494
                                                 KlassHandle accessing_klass,
2495
                                                 TRAPS) {
2496 2497 2498 2499 2500
  Handle empty;
  vmIntrinsics::ID null_iid = vmIntrinsics::_none;  // distinct from all method handle invoker intrinsics
  unsigned int hash  = invoke_method_table()->compute_hash(signature, null_iid);
  int          index = invoke_method_table()->hash_to_index(hash);
  SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2501 2502 2503
  if (spe != NULL && spe->method_type() != NULL) {
    assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");
    return Handle(THREAD, spe->method_type());
2504 2505 2506 2507 2508
  } else if (THREAD->is_Compiler_thread()) {
    warning("SystemDictionary::find_method_handle_type called from compiler thread");  // FIXME
    return Handle();  // do not attempt from within compiler, unless it was cached
  }

2509
  Handle class_loader, protection_domain;
2510 2511 2512 2513 2514
  if (accessing_klass.not_null()) {
    class_loader      = Handle(THREAD, InstanceKlass::cast(accessing_klass())->class_loader());
    protection_domain = Handle(THREAD, InstanceKlass::cast(accessing_klass())->protection_domain());
  }
  bool can_be_cached = true;
2515
  int npts = ArgumentCount(signature).size();
2516
  objArrayHandle pts = oopFactory::new_objArray(SystemDictionary::Class_klass(), npts, CHECK_(empty));
2517
  int arg = 0;
2518
  Handle rt; // the return type from the signature
2519 2520
  ResourceMark rm(THREAD);
  for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2521
    oop mirror = NULL;
2522 2523 2524
    if (can_be_cached) {
      // Use neutral class loader to lookup candidate classes to be placed in the cache.
      mirror = ss.as_java_mirror(Handle(), Handle(),
2525
                                 SignatureStream::ReturnNull, CHECK_(empty));
2526 2527 2528
      if (mirror == NULL || (ss.is_object() && !is_always_visible_class(mirror))) {
        // Fall back to accessing_klass context.
        can_be_cached = false;
2529 2530
      }
    }
2531
    if (!can_be_cached) {
2532 2533 2534
      // Resolve, throwing a real error if it doesn't work.
      mirror = ss.as_java_mirror(class_loader, protection_domain,
                                 SignatureStream::NCDFError, CHECK_(empty));
2535
    }
2536
    assert(!oopDesc::is_null(mirror), ss.as_symbol(THREAD)->as_C_string());
2537 2538 2539 2540
    if (ss.at_return_type())
      rt = Handle(THREAD, mirror);
    else
      pts->obj_at_put(arg++, mirror);
2541

2542 2543
    // Check accessibility.
    if (ss.is_object() && accessing_klass.not_null()) {
2544
      Klass* sel_klass = java_lang_Class::as_Klass(mirror);
2545
      mirror = NULL;  // safety
2546
      // Emulate ConstantPool::verify_constant_pool_resolve.
H
hseigel 已提交
2547
      if (sel_klass->oop_is_objArray())
2548
        sel_klass = ObjArrayKlass::cast(sel_klass)->bottom_klass();
H
hseigel 已提交
2549
      if (sel_klass->oop_is_instance()) {
2550 2551 2552 2553
        KlassHandle sel_kh(THREAD, sel_klass);
        LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty));
      }
    }
2554 2555 2556
  }
  assert(arg == npts, "");

2557
  // call java.lang.invoke.MethodHandleNatives::findMethodType(Class rt, Class[] pts) -> MethodType
2558 2559 2560 2561
  JavaCallArguments args(Handle(THREAD, rt()));
  args.push_oop(pts());
  JavaValue result(T_OBJECT);
  JavaCalls::call_static(&result,
2562 2563
                         SystemDictionary::MethodHandleNatives_klass(),
                         vmSymbols::findMethodHandleType_name(),
2564
                         vmSymbols::findMethodHandleType_signature(),
2565
                         &args, CHECK_(empty));
2566 2567
  Handle method_type(THREAD, (oop) result.get_jobject());

2568
  if (can_be_cached) {
2569 2570 2571 2572 2573
    // We can cache this MethodType inside the JVM.
    MutexLocker ml(SystemDictionary_lock, THREAD);
    spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
    if (spe == NULL)
      spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
2574 2575
    if (spe->method_type() == NULL) {
      spe->set_method_type(method_type());
2576 2577
    }
  }
2578

2579
  // report back to the caller with the MethodType
2580
  return method_type;
2581 2582
}

2583 2584 2585 2586
// Ask Java code to find or construct a method handle constant.
Handle SystemDictionary::link_method_handle_constant(KlassHandle caller,
                                                     int ref_kind, //e.g., JVM_REF_invokeVirtual
                                                     KlassHandle callee,
2587 2588
                                                     Symbol* name_sym,
                                                     Symbol* signature,
2589 2590
                                                     TRAPS) {
  Handle empty;
2591
  Handle name = java_lang_String::create_from_symbol(name_sym, CHECK_(empty));
2592 2593
  Handle type;
  if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') {
2594
    type = find_method_handle_type(signature, caller, CHECK_(empty));
2595 2596 2597
  } else if (caller.is_null()) {
    // This should not happen.  JDK code should take care of that.
    THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);
2598
  } else {
2599 2600
    ResourceMark rm(THREAD);
    SignatureStream ss(signature, false);
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612
    if (!ss.is_done()) {
      oop mirror = ss.as_java_mirror(caller->class_loader(), caller->protection_domain(),
                                     SignatureStream::NCDFError, CHECK_(empty));
      type = Handle(THREAD, mirror);
      ss.next();
      if (!ss.is_done())  type = Handle();  // error!
    }
  }
  if (type.is_null()) {
    THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty);
  }

2613
  // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
2614 2615 2616 2617 2618 2619 2620 2621 2622 2623
  JavaCallArguments args;
  args.push_oop(caller->java_mirror());  // the referring class
  args.push_int(ref_kind);
  args.push_oop(callee->java_mirror());  // the target class
  args.push_oop(name());
  args.push_oop(type());
  JavaValue result(T_OBJECT);
  JavaCalls::call_static(&result,
                         SystemDictionary::MethodHandleNatives_klass(),
                         vmSymbols::linkMethodHandleConstant_name(),
2624
                         vmSymbols::linkMethodHandleConstant_signature(),
2625 2626 2627
                         &args, CHECK_(empty));
  return Handle(THREAD, (oop) result.get_jobject());
}
2628

2629
// Ask Java code to find or construct a java.lang.invoke.CallSite for the given
2630
// name and signature, as interpreted relative to the given class loader.
2631 2632 2633 2634
methodHandle SystemDictionary::find_dynamic_call_site_invoker(KlassHandle caller,
                                                              Handle bootstrap_specifier,
                                                              Symbol* name,
                                                              Symbol* type,
2635 2636
                                                              Handle *appendix_result,
                                                              Handle *method_type_result,
2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
                                                              TRAPS) {
  methodHandle empty;
  Handle bsm, info;
  if (java_lang_invoke_MethodHandle::is_instance(bootstrap_specifier())) {
    bsm = bootstrap_specifier;
  } else {
    assert(bootstrap_specifier->is_objArray(), "");
    objArrayHandle args(THREAD, (objArrayOop) bootstrap_specifier());
    int len = args->length();
    assert(len >= 1, "");
    bsm = Handle(THREAD, args->obj_at(0));
    if (len > 1) {
      objArrayOop args1 = oopFactory::new_objArray(SystemDictionary::Object_klass(), len-1, CHECK_(empty));
      for (int i = 1; i < len; i++)
        args1->obj_at_put(i-1, args->obj_at(i));
      info = Handle(THREAD, args1);
    }
  }
  guarantee(java_lang_invoke_MethodHandle::is_instance(bsm()),
2656 2657
            "caller must supply a valid BSM");

2658 2659 2660
  Handle method_name = java_lang_String::create_from_symbol(name, CHECK_(empty));
  Handle method_type = find_method_handle_type(type, caller, CHECK_(empty));

2661 2662 2663 2664 2665
  // This should not happen.  JDK code should take care of that.
  if (caller.is_null() || method_type.is_null()) {
    THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokedynamic", empty);
  }

2666 2667
  objArrayHandle appendix_box = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1, CHECK_(empty));
  assert(appendix_box->obj_at(0) == NULL, "");
2668

2669 2670 2671 2672 2673 2674
  // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
  JavaCallArguments args;
  args.push_oop(caller->java_mirror());
  args.push_oop(bsm());
  args.push_oop(method_name());
  args.push_oop(method_type());
2675
  args.push_oop(info());
2676
  args.push_oop(appendix_box);
2677 2678
  JavaValue result(T_OBJECT);
  JavaCalls::call_static(&result,
2679
                         SystemDictionary::MethodHandleNatives_klass(),
2680 2681
                         vmSymbols::linkCallSite_name(),
                         vmSymbols::linkCallSite_signature(),
2682
                         &args, CHECK_(empty));
2683
  Handle mname(THREAD, (oop) result.get_jobject());
2684
  (*method_type_result) = method_type;
2685
  return unpack_method_and_appendix(mname, caller, appendix_box, appendix_result, THREAD);
2686 2687
}

D
duke 已提交
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717
// Since the identity hash code for symbols changes when the symbols are
// moved from the regular perm gen (hash in the mark word) to the shared
// spaces (hash is the address), the classes loaded into the dictionary
// may be in the wrong buckets.

void SystemDictionary::reorder_dictionary() {
  dictionary()->reorder_dictionary();
}


void SystemDictionary::copy_buckets(char** top, char* end) {
  dictionary()->copy_buckets(top, end);
}


void SystemDictionary::copy_table(char** top, char* end) {
  dictionary()->copy_table(top, end);
}


void SystemDictionary::reverse() {
  dictionary()->reverse();
}

int SystemDictionary::number_of_classes() {
  return dictionary()->number_of_entries();
}


// ----------------------------------------------------------------------------
2718 2719 2720
void SystemDictionary::print_shared(bool details) {
  shared_dictionary()->print(details);
}
D
duke 已提交
2721

2722 2723
void SystemDictionary::print(bool details) {
  dictionary()->print(details);
D
duke 已提交
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749

  // Placeholders
  GCMutexLocker mu(SystemDictionary_lock);
  placeholders()->print();

  // loader constraints - print under SD_lock
  constraints()->print();
}


void SystemDictionary::verify() {
  guarantee(dictionary() != NULL, "Verify of system dictionary failed");
  guarantee(constraints() != NULL,
            "Verify of loader constraints failed");
  guarantee(dictionary()->number_of_entries() >= 0 &&
            placeholders()->number_of_entries() >= 0,
            "Verify of system dictionary failed");

  // Verify dictionary
  dictionary()->verify();

  GCMutexLocker mu(SystemDictionary_lock);
  placeholders()->verify();

  // Verify constraint table
  guarantee(constraints() != NULL, "Verify of loader constraints failed");
2750
  constraints()->verify(dictionary(), placeholders());
D
duke 已提交
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
}

#ifndef PRODUCT

// statistics code
class ClassStatistics: AllStatic {
 private:
  static int nclasses;        // number of classes
  static int nmethods;        // number of methods
  static int nmethoddata;     // number of methodData
  static int class_size;      // size of class objects in words
  static int method_size;     // size of method objects in words
  static int debug_size;      // size of debug info in methods
  static int methoddata_size; // size of methodData objects in words

2766
  static void do_class(Klass* k) {
D
duke 已提交
2767 2768
    nclasses++;
    class_size += k->size();
2769 2770
    if (k->oop_is_instance()) {
      InstanceKlass* ik = (InstanceKlass*)k;
D
duke 已提交
2771 2772 2773 2774 2775
      class_size += ik->methods()->size();
      class_size += ik->constants()->size();
      class_size += ik->local_interfaces()->size();
      class_size += ik->transitive_interfaces()->size();
      // We do not have to count implementors, since we only store one!
2776 2777
      // SSS: How should these be accounted now that they have moved?
      // class_size += ik->fields()->length();
D
duke 已提交
2778 2779 2780
    }
  }

2781
  static void do_method(Method* m) {
D
duke 已提交
2782 2783 2784 2785 2786 2787 2788
    nmethods++;
    method_size += m->size();
    // class loader uses same objArray for empty vectors, so don't count these
    if (m->has_stackmap_table()) {
      method_size += m->stackmap_data()->size();
    }

2789
    MethodData* mdo = m->method_data();
D
duke 已提交
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851
    if (mdo != NULL) {
      nmethoddata++;
      methoddata_size += mdo->size();
    }
  }

 public:
  static void print() {
    SystemDictionary::classes_do(do_class);
    SystemDictionary::methods_do(do_method);
    tty->print_cr("Class statistics:");
    tty->print_cr("%d classes (%d bytes)", nclasses, class_size * oopSize);
    tty->print_cr("%d methods (%d bytes = %d base + %d debug info)", nmethods,
                  (method_size + debug_size) * oopSize, method_size * oopSize, debug_size * oopSize);
    tty->print_cr("%d methoddata (%d bytes)", nmethoddata, methoddata_size * oopSize);
  }
};


int ClassStatistics::nclasses        = 0;
int ClassStatistics::nmethods        = 0;
int ClassStatistics::nmethoddata     = 0;
int ClassStatistics::class_size      = 0;
int ClassStatistics::method_size     = 0;
int ClassStatistics::debug_size      = 0;
int ClassStatistics::methoddata_size = 0;

void SystemDictionary::print_class_statistics() {
  ResourceMark rm;
  ClassStatistics::print();
}


class MethodStatistics: AllStatic {
 public:
  enum {
    max_parameter_size = 10
  };
 private:

  static int _number_of_methods;
  static int _number_of_final_methods;
  static int _number_of_static_methods;
  static int _number_of_native_methods;
  static int _number_of_synchronized_methods;
  static int _number_of_profiled_methods;
  static int _number_of_bytecodes;
  static int _parameter_size_profile[max_parameter_size];
  static int _bytecodes_profile[Bytecodes::number_of_java_codes];

  static void initialize() {
    _number_of_methods        = 0;
    _number_of_final_methods  = 0;
    _number_of_static_methods = 0;
    _number_of_native_methods = 0;
    _number_of_synchronized_methods = 0;
    _number_of_profiled_methods = 0;
    _number_of_bytecodes      = 0;
    for (int i = 0; i < max_parameter_size             ; i++) _parameter_size_profile[i] = 0;
    for (int j = 0; j < Bytecodes::number_of_java_codes; j++) _bytecodes_profile     [j] = 0;
  };

2852
  static void do_method(Method* m) {
D
duke 已提交
2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
    _number_of_methods++;
    // collect flag info
    if (m->is_final()       ) _number_of_final_methods++;
    if (m->is_static()      ) _number_of_static_methods++;
    if (m->is_native()      ) _number_of_native_methods++;
    if (m->is_synchronized()) _number_of_synchronized_methods++;
    if (m->method_data() != NULL) _number_of_profiled_methods++;
    // collect parameter size info (add one for receiver, if any)
    _parameter_size_profile[MIN2(m->size_of_parameters() + (m->is_static() ? 0 : 1), max_parameter_size - 1)]++;
    // collect bytecodes info
    {
      Thread *thread = Thread::current();
      HandleMark hm(thread);
      BytecodeStream s(methodHandle(thread, m));
      Bytecodes::Code c;
      while ((c = s.next()) >= 0) {
        _number_of_bytecodes++;
        _bytecodes_profile[c]++;
      }
    }
  }

 public:
  static void print() {
    initialize();
    SystemDictionary::methods_do(do_method);
    // generate output
    tty->cr();
    tty->print_cr("Method statistics (static):");
    // flag distribution
    tty->cr();
    tty->print_cr("%6d final        methods  %6.1f%%", _number_of_final_methods       , _number_of_final_methods        * 100.0F / _number_of_methods);
    tty->print_cr("%6d static       methods  %6.1f%%", _number_of_static_methods      , _number_of_static_methods       * 100.0F / _number_of_methods);
    tty->print_cr("%6d native       methods  %6.1f%%", _number_of_native_methods      , _number_of_native_methods       * 100.0F / _number_of_methods);
    tty->print_cr("%6d synchronized methods  %6.1f%%", _number_of_synchronized_methods, _number_of_synchronized_methods * 100.0F / _number_of_methods);
    tty->print_cr("%6d profiled     methods  %6.1f%%", _number_of_profiled_methods, _number_of_profiled_methods * 100.0F / _number_of_methods);
    // parameter size profile
    tty->cr();
    { int tot = 0;
      int avg = 0;
      for (int i = 0; i < max_parameter_size; i++) {
        int n = _parameter_size_profile[i];
        tot += n;
        avg += n*i;
        tty->print_cr("parameter size = %1d: %6d methods  %5.1f%%", i, n, n * 100.0F / _number_of_methods);
      }
      assert(tot == _number_of_methods, "should be the same");
      tty->print_cr("                    %6d methods  100.0%%", _number_of_methods);
      tty->print_cr("(average parameter size = %3.1f including receiver, if any)", (float)avg / _number_of_methods);
    }
    // bytecodes profile
    tty->cr();
    { int tot = 0;
      for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
        if (Bytecodes::is_defined(i)) {
          Bytecodes::Code c = Bytecodes::cast(i);
          int n = _bytecodes_profile[c];
          tot += n;
          tty->print_cr("%9d  %7.3f%%  %s", n, n * 100.0F / _number_of_bytecodes, Bytecodes::name(c));
        }
      }
      assert(tot == _number_of_bytecodes, "should be the same");
      tty->print_cr("%9d  100.000%%", _number_of_bytecodes);
    }
    tty->cr();
  }
};

int MethodStatistics::_number_of_methods;
int MethodStatistics::_number_of_final_methods;
int MethodStatistics::_number_of_static_methods;
int MethodStatistics::_number_of_native_methods;
int MethodStatistics::_number_of_synchronized_methods;
int MethodStatistics::_number_of_profiled_methods;
int MethodStatistics::_number_of_bytecodes;
int MethodStatistics::_parameter_size_profile[MethodStatistics::max_parameter_size];
int MethodStatistics::_bytecodes_profile[Bytecodes::number_of_java_codes];


void SystemDictionary::print_method_statistics() {
  MethodStatistics::print();
}

#endif // PRODUCT