1 /*
   2  * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 
  27 #include <new>
  28 
  29 #include "classfile/classLoaderDataGraph.hpp"
  30 #include "classfile/modules.hpp"
  31 #include "classfile/protectionDomainCache.hpp"
  32 #include "classfile/stringTable.hpp"
  33 #include "classfile/symbolTable.hpp"
  34 #include "code/codeCache.hpp"
  35 #include "compiler/compilationPolicy.hpp"
  36 #include "compiler/methodMatcher.hpp"
  37 #include "compiler/directivesParser.hpp"
  38 #include "gc/shared/gcConfig.hpp"
  39 #include "gc/shared/genArguments.hpp"
  40 #include "gc/shared/genCollectedHeap.hpp"
  41 #include "jvmtifiles/jvmtiEnv.hpp"
  42 #include "memory/filemap.hpp"
  43 #include "memory/heapShared.inline.hpp"
  44 #include "memory/metaspaceShared.hpp"
  45 #include "memory/metadataFactory.hpp"
  46 #include "memory/iterator.hpp"
  47 #include "memory/resourceArea.hpp"
  48 #include "memory/universe.hpp"
  49 #include "memory/oopFactory.hpp"
  50 #include "oops/array.hpp"
  51 #include "oops/compressedOops.hpp"
  52 #include "oops/constantPool.inline.hpp"
  53 #include "oops/method.inline.hpp"
  54 #include "oops/objArrayKlass.hpp"
  55 #include "oops/objArrayOop.inline.hpp"
  56 #include "oops/oop.inline.hpp"
  57 #include "oops/typeArrayOop.inline.hpp"
  58 #include "prims/resolvedMethodTable.hpp"
  59 #include "prims/wbtestmethods/parserTests.hpp"
  60 #include "prims/whitebox.inline.hpp"
  61 #include "runtime/arguments.hpp"
  62 #include "runtime/atomic.hpp"
  63 #include "runtime/deoptimization.hpp"
  64 #include "runtime/fieldDescriptor.inline.hpp"
  65 #include "runtime/flags/jvmFlag.hpp"
  66 #include "runtime/frame.inline.hpp"
  67 #include "runtime/handles.inline.hpp"
  68 #include "runtime/handshake.hpp"
  69 #include "runtime/interfaceSupport.inline.hpp"
  70 #include "runtime/javaCalls.hpp"
  71 #include "runtime/jniHandles.inline.hpp"
  72 #include "runtime/os.hpp"
  73 #include "runtime/sweeper.hpp"
  74 #include "runtime/thread.hpp"
  75 #include "runtime/threadSMR.hpp"
  76 #include "runtime/vm_version.hpp"
  77 #include "services/memoryService.hpp"
  78 #include "utilities/align.hpp"
  79 #include "utilities/debug.hpp"
  80 #include "utilities/elfFile.hpp"
  81 #include "utilities/exceptions.hpp"
  82 #include "utilities/macros.hpp"
  83 #if INCLUDE_CDS
  84 #include "prims/cdsoffsets.hpp"
  85 #endif // INCLUDE_CDS
  86 #if INCLUDE_G1GC
  87 #include "gc/g1/g1Arguments.hpp"
  88 #include "gc/g1/g1CollectedHeap.inline.hpp"
  89 #include "gc/g1/g1ConcurrentMark.hpp"
  90 #include "gc/g1/g1ConcurrentMarkThread.hpp"
  91 #include "gc/g1/heapRegionRemSet.hpp"
  92 #include "gc/g1/heterogeneousHeapRegionManager.hpp"
  93 #endif // INCLUDE_G1GC
  94 #if INCLUDE_PARALLELGC
  95 #include "gc/parallel/parallelScavengeHeap.inline.hpp"
  96 #include "gc/parallel/adjoiningGenerations.hpp"
  97 #endif // INCLUDE_PARALLELGC
  98 #if INCLUDE_NMT
  99 #include "services/mallocSiteTable.hpp"
 100 #include "services/memTracker.hpp"
 101 #include "utilities/nativeCallStack.hpp"
 102 #endif // INCLUDE_NMT
 103 #if INCLUDE_AOT
 104 #include "aot/aotLoader.hpp"
 105 #endif // INCLUDE_AOT
 106 
 107 #ifdef LINUX
 108 #include "osContainer_linux.hpp"
 109 #endif
 110 
 111 #define SIZE_T_MAX_VALUE ((size_t) -1)
 112 
 113 #define CHECK_JNI_EXCEPTION_(env, value)                               \
 114   do {                                                                 \
 115     JavaThread* THREAD = JavaThread::thread_from_jni_environment(env); \
 116     THREAD->clear_pending_jni_exception_check();                       \
 117     if (HAS_PENDING_EXCEPTION) {                                       \
 118       return(value);                                                   \
 119     }                                                                  \
 120   } while (0)
 121 
 122 #define CHECK_JNI_EXCEPTION(env)                                       \
 123   do {                                                                 \
 124     JavaThread* THREAD = JavaThread::thread_from_jni_environment(env); \
 125     THREAD->clear_pending_jni_exception_check();                       \
 126     if (HAS_PENDING_EXCEPTION) {                                       \
 127       return;                                                          \
 128     }                                                                  \
 129   } while (0)
 130 
 131 bool WhiteBox::_used = false;
 132 volatile bool WhiteBox::compilation_locked = false;
 133 
 134 class VM_WhiteBoxOperation : public VM_Operation {
 135  public:
 136   VM_WhiteBoxOperation()                         { }
 137   VMOp_Type type()                  const        { return VMOp_WhiteBoxOperation; }
 138   bool allow_nested_vm_operations() const        { return true; }
 139 };
 140 
 141 
 142 WB_ENTRY(jlong, WB_GetObjectAddress(JNIEnv* env, jobject o, jobject obj))
 143   return (jlong)(void*)JNIHandles::resolve(obj);
 144 WB_END
 145 
 146 WB_ENTRY(jint, WB_GetHeapOopSize(JNIEnv* env, jobject o))
 147   return heapOopSize;
 148 WB_END
 149 
 150 WB_ENTRY(jint, WB_GetVMPageSize(JNIEnv* env, jobject o))
 151   return os::vm_page_size();
 152 WB_END
 153 
 154 WB_ENTRY(jlong, WB_GetVMAllocationGranularity(JNIEnv* env, jobject o))
 155   return os::vm_allocation_granularity();
 156 WB_END
 157 
 158 WB_ENTRY(jlong, WB_GetVMLargePageSize(JNIEnv* env, jobject o))
 159   return os::large_page_size();
 160 WB_END
 161 
 162 class WBIsKlassAliveClosure : public LockedClassesDo {
 163     Symbol* _name;
 164     bool _found;
 165 public:
 166     WBIsKlassAliveClosure(Symbol* name) : _name(name), _found(false) {}
 167 
 168     void do_klass(Klass* k) {
 169       if (_found) return;
 170       Symbol* ksym = k->name();
 171       if (ksym->fast_compare(_name) == 0) {
 172         _found = true;
 173       }
 174     }
 175 
 176     bool found() const {
 177         return _found;
 178     }
 179 };
 180 
 181 WB_ENTRY(jboolean, WB_IsClassAlive(JNIEnv* env, jobject target, jstring name))
 182   oop h_name = JNIHandles::resolve(name);
 183   if (h_name == NULL) return false;
 184   Symbol* sym = java_lang_String::as_symbol(h_name);
 185   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
 186 
 187   WBIsKlassAliveClosure closure(sym);
 188   ClassLoaderDataGraph::classes_do(&closure);
 189 
 190   return closure.found();
 191 WB_END
 192 
 193 WB_ENTRY(jint, WB_GetSymbolRefcount(JNIEnv* env, jobject unused, jstring name))
 194   oop h_name = JNIHandles::resolve(name);
 195   if (h_name == NULL) return false;
 196   Symbol* sym = java_lang_String::as_symbol(h_name);
 197   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
 198   return (jint)sym->refcount();
 199 WB_END
 200 
 201 
 202 WB_ENTRY(void, WB_AddToBootstrapClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 203 #if INCLUDE_JVMTI
 204   ResourceMark rm;
 205   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 206   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 207   jvmtiError err = jvmti_env->AddToBootstrapClassLoaderSearch(seg);
 208   assert(err == JVMTI_ERROR_NONE, "must not fail");
 209 #endif
 210 }
 211 WB_END
 212 
 213 WB_ENTRY(void, WB_AddToSystemClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 214 #if INCLUDE_JVMTI
 215   ResourceMark rm;
 216   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 217   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 218   jvmtiError err = jvmti_env->AddToSystemClassLoaderSearch(seg);
 219   assert(err == JVMTI_ERROR_NONE, "must not fail");
 220 #endif
 221 }
 222 WB_END
 223 
 224 
 225 WB_ENTRY(jlong, WB_GetCompressedOopsMaxHeapSize(JNIEnv* env, jobject o)) {
 226   return (jlong)Arguments::max_heap_for_compressed_oops();
 227 }
 228 WB_END
 229 
 230 WB_ENTRY(void, WB_PrintHeapSizes(JNIEnv* env, jobject o)) {
 231   tty->print_cr("Minimum heap " SIZE_FORMAT " Initial heap " SIZE_FORMAT " "
 232                 "Maximum heap " SIZE_FORMAT " Space alignment " SIZE_FORMAT " Heap alignment " SIZE_FORMAT,
 233                 MinHeapSize,
 234                 InitialHeapSize,
 235                 MaxHeapSize,
 236                 SpaceAlignment,
 237                 HeapAlignment);
 238 }
 239 WB_END
 240 
 241 #ifndef PRODUCT
 242 // Forward declaration
 243 void TestReservedSpace_test();
 244 void TestReserveMemorySpecial_test();
 245 void TestVirtualSpace_test();
 246 #endif
 247 
 248 WB_ENTRY(void, WB_RunMemoryUnitTests(JNIEnv* env, jobject o))
 249 #ifndef PRODUCT
 250   TestReservedSpace_test();
 251   TestReserveMemorySpecial_test();
 252   TestVirtualSpace_test();
 253 #endif
 254 WB_END
 255 
 256 WB_ENTRY(void, WB_ReadFromNoaccessArea(JNIEnv* env, jobject o))
 257   size_t granularity = os::vm_allocation_granularity();
 258   ReservedHeapSpace rhs(100 * granularity, granularity, false);
 259   VirtualSpace vs;
 260   vs.initialize(rhs, 50 * granularity);
 261 
 262   // Check if constraints are complied
 263   if (!( UseCompressedOops && rhs.base() != NULL &&
 264          CompressedOops::base() != NULL &&
 265          CompressedOops::use_implicit_null_checks() )) {
 266     tty->print_cr("WB_ReadFromNoaccessArea method is useless:\n "
 267                   "\tUseCompressedOops is %d\n"
 268                   "\trhs.base() is " PTR_FORMAT "\n"
 269                   "\tCompressedOops::base() is " PTR_FORMAT "\n"
 270                   "\tCompressedOops::use_implicit_null_checks() is %d",
 271                   UseCompressedOops,
 272                   p2i(rhs.base()),
 273                   p2i(CompressedOops::base()),
 274                   CompressedOops::use_implicit_null_checks());
 275     return;
 276   }
 277   tty->print_cr("Reading from no access area... ");
 278   tty->print_cr("*(vs.low_boundary() - rhs.noaccess_prefix() / 2 ) = %c",
 279                 *(vs.low_boundary() - rhs.noaccess_prefix() / 2 ));
 280 WB_END
 281 
 282 static jint wb_stress_virtual_space_resize(size_t reserved_space_size,
 283                                            size_t magnitude, size_t iterations) {
 284   size_t granularity = os::vm_allocation_granularity();
 285   ReservedHeapSpace rhs(reserved_space_size * granularity, granularity, false);
 286   VirtualSpace vs;
 287   if (!vs.initialize(rhs, 0)) {
 288     tty->print_cr("Failed to initialize VirtualSpace. Can't proceed.");
 289     return 3;
 290   }
 291 
 292   int seed = os::random();
 293   tty->print_cr("Random seed is %d", seed);
 294   os::init_random(seed);
 295 
 296   for (size_t i = 0; i < iterations; i++) {
 297 
 298     // Whether we will shrink or grow
 299     bool shrink = os::random() % 2L == 0;
 300 
 301     // Get random delta to resize virtual space
 302     size_t delta = (size_t)os::random() % magnitude;
 303 
 304     // If we are about to shrink virtual space below zero, then expand instead
 305     if (shrink && vs.committed_size() < delta) {
 306       shrink = false;
 307     }
 308 
 309     // Resizing by delta
 310     if (shrink) {
 311       vs.shrink_by(delta);
 312     } else {
 313       // If expanding fails expand_by will silently return false
 314       vs.expand_by(delta, true);
 315     }
 316   }
 317   return 0;
 318 }
 319 
 320 WB_ENTRY(jint, WB_StressVirtualSpaceResize(JNIEnv* env, jobject o,
 321         jlong reserved_space_size, jlong magnitude, jlong iterations))
 322   tty->print_cr("reservedSpaceSize=" JLONG_FORMAT ", magnitude=" JLONG_FORMAT ", "
 323                 "iterations=" JLONG_FORMAT "\n", reserved_space_size, magnitude,
 324                 iterations);
 325   if (reserved_space_size < 0 || magnitude < 0 || iterations < 0) {
 326     tty->print_cr("One of variables printed above is negative. Can't proceed.\n");
 327     return 1;
 328   }
 329 
 330   // sizeof(size_t) depends on whether OS is 32bit or 64bit. sizeof(jlong) is
 331   // always 8 byte. That's why we should avoid overflow in case of 32bit platform.
 332   if (sizeof(size_t) < sizeof(jlong)) {
 333     jlong size_t_max_value = (jlong) SIZE_T_MAX_VALUE;
 334     if (reserved_space_size > size_t_max_value || magnitude > size_t_max_value
 335         || iterations > size_t_max_value) {
 336       tty->print_cr("One of variables printed above overflows size_t. Can't proceed.\n");
 337       return 2;
 338     }
 339   }
 340 
 341   return wb_stress_virtual_space_resize((size_t) reserved_space_size,
 342                                         (size_t) magnitude, (size_t) iterations);
 343 WB_END
 344 
 345 WB_ENTRY(jboolean, WB_IsGCSupported(JNIEnv* env, jobject o, jint name))
 346   return GCConfig::is_gc_supported((CollectedHeap::Name)name);
 347 WB_END
 348 
 349 WB_ENTRY(jboolean, WB_IsGCSelected(JNIEnv* env, jobject o, jint name))
 350   return GCConfig::is_gc_selected((CollectedHeap::Name)name);
 351 WB_END
 352 
 353 WB_ENTRY(jboolean, WB_IsGCSelectedErgonomically(JNIEnv* env, jobject o))
 354   return GCConfig::is_gc_selected_ergonomically();
 355 WB_END
 356 
 357 WB_ENTRY(jboolean, WB_isObjectInOldGen(JNIEnv* env, jobject o, jobject obj))
 358   oop p = JNIHandles::resolve(obj);
 359 #if INCLUDE_G1GC
 360   if (UseG1GC) {
 361     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 362     const HeapRegion* hr = g1h->heap_region_containing(p);
 363     if (hr == NULL) {
 364       return false;
 365     }
 366     return !(hr->is_young());
 367   }
 368 #endif
 369 #if INCLUDE_PARALLELGC
 370   if (UseParallelGC) {
 371     ParallelScavengeHeap* psh = ParallelScavengeHeap::heap();
 372     return !psh->is_in_young(p);
 373   }
 374 #endif
 375 #if INCLUDE_ZGC
 376   if (UseZGC) {
 377     return Universe::heap()->is_in(p);
 378   }
 379 #endif
 380   GenCollectedHeap* gch = GenCollectedHeap::heap();
 381   return !gch->is_in_young(p);
 382 WB_END
 383 
 384 WB_ENTRY(jlong, WB_GetObjectSize(JNIEnv* env, jobject o, jobject obj))
 385   oop p = JNIHandles::resolve(obj);
 386   return Universe::heap()->obj_size(p) * HeapWordSize;
 387 WB_END
 388 
 389 WB_ENTRY(jlong, WB_GetHeapSpaceAlignment(JNIEnv* env, jobject o))
 390   return (jlong)SpaceAlignment;
 391 WB_END
 392 
 393 WB_ENTRY(jlong, WB_GetHeapAlignment(JNIEnv* env, jobject o))
 394   return (jlong)HeapAlignment;
 395 WB_END
 396 
 397 WB_ENTRY(jboolean, WB_SupportsConcurrentGCPhaseControl(JNIEnv* env, jobject o))
 398   return Universe::heap()->supports_concurrent_phase_control();
 399 WB_END
 400 
 401 WB_ENTRY(jboolean, WB_RequestConcurrentGCPhase(JNIEnv* env, jobject o, jstring name))
 402   Handle h_name(THREAD, JNIHandles::resolve(name));
 403   ResourceMark rm;
 404   const char* c_name = java_lang_String::as_utf8_string(h_name());
 405   return Universe::heap()->request_concurrent_phase(c_name);
 406 WB_END
 407 
 408 #if INCLUDE_G1GC
 409 
 410 WB_ENTRY(jboolean, WB_G1IsHumongous(JNIEnv* env, jobject o, jobject obj))
 411   if (UseG1GC) {
 412     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 413     oop result = JNIHandles::resolve(obj);
 414     const HeapRegion* hr = g1h->heap_region_containing(result);
 415     return hr->is_humongous();
 416   }
 417   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1IsHumongous: G1 GC is not enabled");
 418 WB_END
 419 
 420 WB_ENTRY(jboolean, WB_G1BelongsToHumongousRegion(JNIEnv* env, jobject o, jlong addr))
 421   if (UseG1GC) {
 422     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 423     const HeapRegion* hr = g1h->heap_region_containing((void*) addr);
 424     return hr->is_humongous();
 425   }
 426   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1BelongsToHumongousRegion: G1 GC is not enabled");
 427 WB_END
 428 
 429 WB_ENTRY(jboolean, WB_G1BelongsToFreeRegion(JNIEnv* env, jobject o, jlong addr))
 430   if (UseG1GC) {
 431     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 432     const HeapRegion* hr = g1h->heap_region_containing((void*) addr);
 433     return hr->is_free();
 434   }
 435   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1BelongsToFreeRegion: G1 GC is not enabled");
 436 WB_END
 437 
 438 WB_ENTRY(jlong, WB_G1NumMaxRegions(JNIEnv* env, jobject o))
 439   if (UseG1GC) {
 440     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 441     size_t nr = g1h->max_regions();
 442     return (jlong)nr;
 443   }
 444   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1NumMaxRegions: G1 GC is not enabled");
 445 WB_END
 446 
 447 WB_ENTRY(jlong, WB_G1NumFreeRegions(JNIEnv* env, jobject o))
 448   if (UseG1GC) {
 449     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 450     size_t nr = g1h->num_free_regions();
 451     return (jlong)nr;
 452   }
 453   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1NumFreeRegions: G1 GC is not enabled");
 454 WB_END
 455 
 456 WB_ENTRY(jboolean, WB_G1InConcurrentMark(JNIEnv* env, jobject o))
 457   if (UseG1GC) {
 458     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 459     return g1h->concurrent_mark()->cm_thread()->during_cycle();
 460   }
 461   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1InConcurrentMark: G1 GC is not enabled");
 462 WB_END
 463 
 464 WB_ENTRY(jboolean, WB_G1StartMarkCycle(JNIEnv* env, jobject o))
 465   if (UseG1GC) {
 466     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 467     if (!g1h->concurrent_mark()->cm_thread()->during_cycle()) {
 468       g1h->collect(GCCause::_wb_conc_mark);
 469       return true;
 470     }
 471     return false;
 472   }
 473   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1StartMarkCycle: G1 GC is not enabled");
 474 WB_END
 475 
 476 WB_ENTRY(jint, WB_G1RegionSize(JNIEnv* env, jobject o))
 477   if (UseG1GC) {
 478     return (jint)HeapRegion::GrainBytes;
 479   }
 480   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1RegionSize: G1 GC is not enabled");
 481 WB_END
 482 
 483 #endif // INCLUDE_G1GC
 484 
 485 #if INCLUDE_G1GC || INCLUDE_PARALLELGC
 486 WB_ENTRY(jlong, WB_DramReservedStart(JNIEnv* env, jobject o))
 487 #if INCLUDE_G1GC
 488   if (UseG1GC) {
 489     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 490     if (g1h->is_heterogeneous_heap()) {
 491       uint start_region = HeterogeneousHeapRegionManager::manager()->start_index_of_dram();
 492       return (jlong)(g1h->base() + start_region * HeapRegion::GrainBytes);
 493     } else {
 494       return (jlong)g1h->base();
 495     }
 496   }
 497 #endif // INCLUDE_G1GC
 498 #if INCLUDE_PARALLELGC
 499   if (UseParallelGC) {
 500     ParallelScavengeHeap* ps_heap = ParallelScavengeHeap::heap();
 501     if (AllocateOldGenAt != NULL) {
 502       MemRegion reserved = ps_heap->young_gen()->reserved();
 503       return (jlong)reserved.start();
 504     } else {
 505       return (jlong)ps_heap->base();
 506     }
 507   }
 508 #endif // INCLUDE_PARALLELGC
 509   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_DramReservedStart: enabled only for G1 and Parallel GC");
 510 WB_END
 511 
 512 WB_ENTRY(jlong, WB_DramReservedEnd(JNIEnv* env, jobject o))
 513 #if INCLUDE_G1GC
 514   if (UseG1GC) {
 515     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 516     if (g1h->is_heterogeneous_heap()) {
 517       uint end_region = HeterogeneousHeapRegionManager::manager()->end_index_of_dram();
 518       return (jlong)(g1h->base() + (end_region + 1) * HeapRegion::GrainBytes - 1);
 519     } else {
 520       return (jlong)g1h->base() + G1Arguments::heap_max_size_bytes();
 521     }
 522   }
 523 #endif // INCLUDE_G1GC
 524 #if INCLUDE_PARALLELGC
 525   if (UseParallelGC) {
 526     ParallelScavengeHeap* ps_heap = ParallelScavengeHeap::heap();
 527     if (AllocateOldGenAt != NULL) {
 528       MemRegion reserved = ps_heap->young_gen()->reserved();
 529       return (jlong)reserved.end();
 530     } else {
 531       return (jlong)ps_heap->reserved_region().end();
 532     }
 533   }
 534 #endif // INCLUDE_PARALLELGC
 535   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_DramReservedEnd: enabled only for G1 and Parallel GC");
 536 WB_END
 537 
 538 WB_ENTRY(jlong, WB_NvdimmReservedStart(JNIEnv* env, jobject o))
 539 #if INCLUDE_G1GC
 540   if (UseG1GC) {
 541     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 542     if (g1h->is_heterogeneous_heap()) {
 543       uint start_region = HeterogeneousHeapRegionManager::manager()->start_index_of_nvdimm();
 544       return (jlong)(g1h->base() + start_region * HeapRegion::GrainBytes);
 545     } else {
 546       THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedStart: Old gen is not allocated on NV-DIMM using AllocateOldGenAt flag");
 547     }
 548   }
 549 #endif // INCLUDE_G1GC
 550 #if INCLUDE_PARALLELGC
 551   if (UseParallelGC) {
 552     ParallelScavengeHeap* ps_heap = ParallelScavengeHeap::heap();
 553     if (AllocateOldGenAt != NULL) {
 554       MemRegion reserved = ps_heap->old_gen()->reserved();
 555       return (jlong)reserved.start();
 556     } else {
 557       THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedStart: Old gen is not allocated on NV-DIMM using AllocateOldGenAt flag");
 558     }
 559   }
 560 #endif // INCLUDE_PARALLELGC
 561   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedStart: enabled only for G1 and Parallel GC");
 562 WB_END
 563 
 564 WB_ENTRY(jlong, WB_NvdimmReservedEnd(JNIEnv* env, jobject o))
 565 #if INCLUDE_G1GC
 566   if (UseG1GC) {
 567     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 568     if (g1h->is_heterogeneous_heap()) {
 569       uint end_region = HeterogeneousHeapRegionManager::manager()->start_index_of_nvdimm();
 570       return (jlong)(g1h->base() + (end_region + 1) * HeapRegion::GrainBytes - 1);
 571     } else {
 572       THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedEnd: Old gen is not allocated on NV-DIMM using AllocateOldGenAt flag");
 573     }
 574   }
 575 #endif // INCLUDE_G1GC
 576 #if INCLUDE_PARALLELGC
 577   if (UseParallelGC) {
 578     ParallelScavengeHeap* ps_heap = ParallelScavengeHeap::heap();
 579     if (AllocateOldGenAt != NULL) {
 580       MemRegion reserved = ps_heap->old_gen()->reserved();
 581       return (jlong)reserved.end();
 582       } else {
 583       THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedEnd: Old gen is not allocated on NV-DIMM using AllocateOldGenAt flag");
 584     }
 585   }
 586 #endif // INCLUDE_PARALLELGC
 587   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_NvdimmReservedEnd: enabled only for G1 and Parallel GC");
 588 WB_END
 589 
 590 #endif // INCLUDE_G1GC || INCLUDE_PARALLELGC
 591 
 592 #if INCLUDE_PARALLELGC
 593 
 594 WB_ENTRY(jlong, WB_PSVirtualSpaceAlignment(JNIEnv* env, jobject o))
 595   if (UseParallelGC) {
 596     return ParallelScavengeHeap::heap()->gens()->virtual_spaces()->alignment();
 597   }
 598   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_PSVirtualSpaceAlignment: Parallel GC is not enabled");
 599 WB_END
 600 
 601 WB_ENTRY(jlong, WB_PSHeapGenerationAlignment(JNIEnv* env, jobject o))
 602   if (UseParallelGC) {
 603     return GenAlignment;
 604   }
 605   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_PSHeapGenerationAlignment: Parallel GC is not enabled");
 606 WB_END
 607 
 608 #endif // INCLUDE_PARALLELGC
 609 
 610 #if INCLUDE_G1GC
 611 
 612 WB_ENTRY(jobject, WB_G1AuxiliaryMemoryUsage(JNIEnv* env))
 613   if (UseG1GC) {
 614     ResourceMark rm(THREAD);
 615     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 616     MemoryUsage usage = g1h->get_auxiliary_data_memory_usage();
 617     Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
 618     return JNIHandles::make_local(env, h());
 619   }
 620   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1AuxiliaryMemoryUsage: G1 GC is not enabled");
 621 WB_END
 622 
 623 WB_ENTRY(jint, WB_G1ActiveMemoryNodeCount(JNIEnv* env, jobject o))
 624   if (UseG1GC) {
 625     G1NUMA* numa = G1NUMA::numa();
 626     return (jint)numa->num_active_nodes();
 627   }
 628   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1ActiveMemoryNodeCount: G1 GC is not enabled");
 629 WB_END
 630 
 631 WB_ENTRY(jintArray, WB_G1MemoryNodeIds(JNIEnv* env, jobject o))
 632   if (UseG1GC) {
 633     G1NUMA* numa = G1NUMA::numa();
 634     int num_node_ids = (int)numa->num_active_nodes();
 635     const int* node_ids = numa->node_ids();
 636 
 637     typeArrayOop result = oopFactory::new_intArray(num_node_ids, CHECK_NULL);
 638     for (int i = 0; i < num_node_ids; i++) {
 639       result->int_at_put(i, (jint)node_ids[i]);
 640     }
 641     return (jintArray) JNIHandles::make_local(env, result);
 642   }
 643   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1MemoryNodeIds: G1 GC is not enabled");
 644 WB_END
 645 
 646 class OldRegionsLivenessClosure: public HeapRegionClosure {
 647 
 648  private:
 649   const int _liveness;
 650   size_t _total_count;
 651   size_t _total_memory;
 652   size_t _total_memory_to_free;
 653 
 654  public:
 655   OldRegionsLivenessClosure(int liveness) :
 656     _liveness(liveness),
 657     _total_count(0),
 658     _total_memory(0),
 659     _total_memory_to_free(0) { }
 660 
 661     size_t total_count() { return _total_count; }
 662     size_t total_memory() { return _total_memory; }
 663     size_t total_memory_to_free() { return _total_memory_to_free; }
 664 
 665   bool do_heap_region(HeapRegion* r) {
 666     if (r->is_old()) {
 667       size_t prev_live = r->marked_bytes();
 668       size_t live = r->live_bytes();
 669       size_t size = r->used();
 670       size_t reg_size = HeapRegion::GrainBytes;
 671       if (size > 0 && ((int)(live * 100 / size) < _liveness)) {
 672         _total_memory += size;
 673         ++_total_count;
 674         if (size == reg_size) {
 675         // we don't include non-full regions since they are unlikely included in mixed gc
 676         // for testing purposes it's enough to have lowest estimation of total memory that is expected to be freed
 677           _total_memory_to_free += size - prev_live;
 678         }
 679       }
 680     }
 681     return false;
 682   }
 683 };
 684 
 685 
 686 WB_ENTRY(jlongArray, WB_G1GetMixedGCInfo(JNIEnv* env, jobject o, jint liveness))
 687   if (!UseG1GC) {
 688     THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1GetMixedGCInfo: G1 GC is not enabled");
 689   }
 690   if (liveness < 0) {
 691     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "liveness value should be non-negative");
 692   }
 693 
 694   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 695   OldRegionsLivenessClosure rli(liveness);
 696   g1h->heap_region_iterate(&rli);
 697 
 698   typeArrayOop result = oopFactory::new_longArray(3, CHECK_NULL);
 699   result->long_at_put(0, rli.total_count());
 700   result->long_at_put(1, rli.total_memory());
 701   result->long_at_put(2, rli.total_memory_to_free());
 702   return (jlongArray) JNIHandles::make_local(env, result);
 703 WB_END
 704 
 705 #endif // INCLUDE_G1GC
 706 
 707 #if INCLUDE_NMT
 708 // Alloc memory using the test memory type so that we can use that to see if
 709 // NMT picks it up correctly
 710 WB_ENTRY(jlong, WB_NMTMalloc(JNIEnv* env, jobject o, jlong size))
 711   jlong addr = 0;
 712   addr = (jlong)(uintptr_t)os::malloc(size, mtTest);
 713   return addr;
 714 WB_END
 715 
 716 // Alloc memory with pseudo call stack. The test can create psudo malloc
 717 // allocation site to stress the malloc tracking.
 718 WB_ENTRY(jlong, WB_NMTMallocWithPseudoStack(JNIEnv* env, jobject o, jlong size, jint pseudo_stack))
 719   address pc = (address)(size_t)pseudo_stack;
 720   NativeCallStack stack(&pc, 1);
 721   return (jlong)(uintptr_t)os::malloc(size, mtTest, stack);
 722 WB_END
 723 
 724 // Alloc memory with pseudo call stack and specific memory type.
 725 WB_ENTRY(jlong, WB_NMTMallocWithPseudoStackAndType(JNIEnv* env, jobject o, jlong size, jint pseudo_stack, jint type))
 726   address pc = (address)(size_t)pseudo_stack;
 727   NativeCallStack stack(&pc, 1);
 728   return (jlong)(uintptr_t)os::malloc(size, (MEMFLAGS)type, stack);
 729 WB_END
 730 
 731 // Free the memory allocated by NMTAllocTest
 732 WB_ENTRY(void, WB_NMTFree(JNIEnv* env, jobject o, jlong mem))
 733   os::free((void*)(uintptr_t)mem);
 734 WB_END
 735 
 736 WB_ENTRY(jlong, WB_NMTReserveMemory(JNIEnv* env, jobject o, jlong size))
 737   jlong addr = 0;
 738 
 739   addr = (jlong)(uintptr_t)os::reserve_memory(size);
 740   MemTracker::record_virtual_memory_type((address)addr, mtTest);
 741 
 742   return addr;
 743 WB_END
 744 
 745 WB_ENTRY(jlong, WB_NMTAttemptReserveMemoryAt(JNIEnv* env, jobject o, jlong addr, jlong size))
 746   addr = (jlong)(uintptr_t)os::attempt_reserve_memory_at((size_t)size, (char*)(uintptr_t)addr);
 747   MemTracker::record_virtual_memory_type((address)addr, mtTest);
 748 
 749   return addr;
 750 WB_END
 751 
 752 WB_ENTRY(void, WB_NMTCommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 753   os::commit_memory((char *)(uintptr_t)addr, size, !ExecMem);
 754   MemTracker::record_virtual_memory_type((address)(uintptr_t)addr, mtTest);
 755 WB_END
 756 
 757 WB_ENTRY(void, WB_NMTUncommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 758   os::uncommit_memory((char *)(uintptr_t)addr, size);
 759 WB_END
 760 
 761 WB_ENTRY(void, WB_NMTReleaseMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 762   os::release_memory((char *)(uintptr_t)addr, size);
 763 WB_END
 764 
 765 WB_ENTRY(jboolean, WB_NMTChangeTrackingLevel(JNIEnv* env))
 766   // Test that we can downgrade NMT levels but not upgrade them.
 767   if (MemTracker::tracking_level() == NMT_off) {
 768     MemTracker::transition_to(NMT_off);
 769     return MemTracker::tracking_level() == NMT_off;
 770   } else {
 771     assert(MemTracker::tracking_level() == NMT_detail, "Should start out as detail tracking");
 772     MemTracker::transition_to(NMT_summary);
 773     assert(MemTracker::tracking_level() == NMT_summary, "Should be summary now");
 774 
 775     // Can't go to detail once NMT is set to summary.
 776     MemTracker::transition_to(NMT_detail);
 777     assert(MemTracker::tracking_level() == NMT_summary, "Should still be summary now");
 778 
 779     // Shutdown sets tracking level to minimal.
 780     MemTracker::shutdown();
 781     assert(MemTracker::tracking_level() == NMT_minimal, "Should be minimal now");
 782 
 783     // Once the tracking level is minimal, we cannot increase to summary.
 784     // The code ignores this request instead of asserting because if the malloc site
 785     // table overflows in another thread, it tries to change the code to summary.
 786     MemTracker::transition_to(NMT_summary);
 787     assert(MemTracker::tracking_level() == NMT_minimal, "Should still be minimal now");
 788 
 789     // Really can never go up to detail, verify that the code would never do this.
 790     MemTracker::transition_to(NMT_detail);
 791     assert(MemTracker::tracking_level() == NMT_minimal, "Should still be minimal now");
 792     return MemTracker::tracking_level() == NMT_minimal;
 793   }
 794 WB_END
 795 
 796 WB_ENTRY(jint, WB_NMTGetHashSize(JNIEnv* env, jobject o))
 797   int hash_size = MallocSiteTable::hash_buckets();
 798   assert(hash_size > 0, "NMT hash_size should be > 0");
 799   return (jint)hash_size;
 800 WB_END
 801 
 802 WB_ENTRY(jlong, WB_NMTNewArena(JNIEnv* env, jobject o, jlong init_size))
 803   Arena* arena =  new (mtTest) Arena(mtTest, size_t(init_size));
 804   return (jlong)arena;
 805 WB_END
 806 
 807 WB_ENTRY(void, WB_NMTFreeArena(JNIEnv* env, jobject o, jlong arena))
 808   Arena* a = (Arena*)arena;
 809   delete a;
 810 WB_END
 811 
 812 WB_ENTRY(void, WB_NMTArenaMalloc(JNIEnv* env, jobject o, jlong arena, jlong size))
 813   Arena* a = (Arena*)arena;
 814   a->Amalloc(size_t(size));
 815 WB_END
 816 #endif // INCLUDE_NMT
 817 
 818 static jmethodID reflected_method_to_jmid(JavaThread* thread, JNIEnv* env, jobject method) {
 819   assert(method != NULL, "method should not be null");
 820   ThreadToNativeFromVM ttn(thread);
 821   return env->FromReflectedMethod(method);
 822 }
 823 
 824 // Deoptimizes all compiled frames and makes nmethods not entrant if it's requested
 825 class VM_WhiteBoxDeoptimizeFrames : public VM_WhiteBoxOperation {
 826  private:
 827   int _result;
 828   const bool _make_not_entrant;
 829  public:
 830   VM_WhiteBoxDeoptimizeFrames(bool make_not_entrant) :
 831         _result(0), _make_not_entrant(make_not_entrant) { }
 832   int  result() const { return _result; }
 833 
 834   void doit() {
 835     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
 836       if (t->has_last_Java_frame()) {
 837         for (StackFrameStream fst(t, UseBiasedLocking); !fst.is_done(); fst.next()) {
 838           frame* f = fst.current();
 839           if (f->can_be_deoptimized() && !f->is_deoptimized_frame()) {
 840             RegisterMap* reg_map = fst.register_map();
 841             Deoptimization::deoptimize(t, *f, reg_map);
 842             if (_make_not_entrant) {
 843                 CompiledMethod* cm = CodeCache::find_compiled(f->pc());
 844                 assert(cm != NULL, "sanity check");
 845                 cm->make_not_entrant();
 846             }
 847             ++_result;
 848           }
 849         }
 850       }
 851     }
 852   }
 853 };
 854 
 855 WB_ENTRY(jint, WB_DeoptimizeFrames(JNIEnv* env, jobject o, jboolean make_not_entrant))
 856   VM_WhiteBoxDeoptimizeFrames op(make_not_entrant == JNI_TRUE);
 857   VMThread::execute(&op);
 858   return op.result();
 859 WB_END
 860 
 861 WB_ENTRY(void, WB_DeoptimizeAll(JNIEnv* env, jobject o))
 862   CodeCache::mark_all_nmethods_for_deoptimization();
 863   Deoptimization::deoptimize_all_marked();
 864 WB_END
 865 
 866 WB_ENTRY(jint, WB_DeoptimizeMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 867   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 868   int result = 0;
 869   CHECK_JNI_EXCEPTION_(env, result);
 870   MutexLocker mu(Compile_lock);
 871   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 872   if (is_osr) {
 873     result += mh->mark_osr_nmethods();
 874   } else if (mh->code() != NULL) {
 875     mh->code()->mark_for_deoptimization();
 876     ++result;
 877   }
 878   result += CodeCache::mark_for_deoptimization(mh());
 879   if (result > 0) {
 880     Deoptimization::deoptimize_all_marked();
 881   }
 882   return result;
 883 WB_END
 884 
 885 WB_ENTRY(jboolean, WB_IsMethodCompiled(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 886   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 887   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 888   MutexLocker mu(Compile_lock);
 889   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 890   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 891   if (code == NULL) {
 892     return JNI_FALSE;
 893   }
 894   return (code->is_alive() && !code->is_marked_for_deoptimization());
 895 WB_END
 896 
 897 WB_ENTRY(jboolean, WB_IsMethodCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 898   if (method == NULL || comp_level > MIN2((CompLevel) TieredStopAtLevel, CompLevel_highest_tier)) {
 899     return false;
 900   }
 901   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 902   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 903   MutexLocker mu(Compile_lock);
 904   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 905   if (is_osr) {
 906     return CompilationPolicy::can_be_osr_compiled(mh, comp_level);
 907   } else {
 908     return CompilationPolicy::can_be_compiled(mh, comp_level);
 909   }
 910 WB_END
 911 
 912 WB_ENTRY(jboolean, WB_IsMethodQueuedForCompilation(JNIEnv* env, jobject o, jobject method))
 913   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 914   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 915   MutexLocker mu(Compile_lock);
 916   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 917   return mh->queued_for_compilation();
 918 WB_END
 919 
 920 WB_ENTRY(jboolean, WB_IsIntrinsicAvailable(JNIEnv* env, jobject o, jobject method, jobject compilation_context, jint compLevel))
 921   if (compLevel < CompLevel_none || compLevel > MIN2((CompLevel) TieredStopAtLevel, CompLevel_highest_tier)) {
 922     return false; // Intrinsic is not available on a non-existent compilation level.
 923   }
 924   jmethodID method_id, compilation_context_id;
 925   method_id = reflected_method_to_jmid(thread, env, method);
 926   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 927   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(method_id));
 928 
 929   DirectiveSet* directive;
 930   AbstractCompiler* comp = CompileBroker::compiler((int)compLevel);
 931   assert(comp != NULL, "compiler not available");
 932   if (compilation_context != NULL) {
 933     compilation_context_id = reflected_method_to_jmid(thread, env, compilation_context);
 934     CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 935     methodHandle cch(THREAD, Method::checked_resolve_jmethod_id(compilation_context_id));
 936     directive = DirectivesStack::getMatchingDirective(cch, comp);
 937   } else {
 938     // Calling with NULL matches default directive
 939     directive = DirectivesStack::getDefaultDirective(comp);
 940   }
 941   bool result = comp->is_intrinsic_available(mh, directive);
 942   DirectivesStack::release(directive);
 943   return result;
 944 WB_END
 945 
 946 WB_ENTRY(jint, WB_GetMethodCompilationLevel(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 947   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 948   CHECK_JNI_EXCEPTION_(env, CompLevel_none);
 949   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 950   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 951   return (code != NULL ? code->comp_level() : CompLevel_none);
 952 WB_END
 953 
 954 WB_ENTRY(void, WB_MakeMethodNotCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 955   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 956   CHECK_JNI_EXCEPTION(env);
 957   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 958   if (is_osr) {
 959     mh->set_not_osr_compilable("WhiteBox", comp_level);
 960   } else {
 961     mh->set_not_compilable("WhiteBox", comp_level);
 962   }
 963 WB_END
 964 
 965 WB_ENTRY(jint, WB_GetMethodEntryBci(JNIEnv* env, jobject o, jobject method))
 966   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 967   CHECK_JNI_EXCEPTION_(env, InvocationEntryBci);
 968   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 969   CompiledMethod* code = mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false);
 970   return (code != NULL && code->is_osr_method() ? code->osr_entry_bci() : InvocationEntryBci);
 971 WB_END
 972 
 973 WB_ENTRY(jboolean, WB_TestSetDontInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 974   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 975   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 976   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 977   bool result = mh->dont_inline();
 978   mh->set_dont_inline(value == JNI_TRUE);
 979   return result;
 980 WB_END
 981 
 982 WB_ENTRY(jint, WB_GetCompileQueueSize(JNIEnv* env, jobject o, jint comp_level))
 983   if (comp_level == CompLevel_any) {
 984     return CompileBroker::queue_size(CompLevel_full_optimization) /* C2 */ +
 985         CompileBroker::queue_size(CompLevel_full_profile) /* C1 */;
 986   } else {
 987     return CompileBroker::queue_size(comp_level);
 988   }
 989 WB_END
 990 
 991 WB_ENTRY(jboolean, WB_TestSetForceInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 992   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 993   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 994   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 995   bool result = mh->force_inline();
 996   mh->set_force_inline(value == JNI_TRUE);
 997   return result;
 998 WB_END
 999 
1000 bool WhiteBox::compile_method(Method* method, int comp_level, int bci, Thread* THREAD) {
1001   // Screen for unavailable/bad comp level or null method
1002   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1003   if (method == NULL) {
1004     tty->print_cr("WB error: request to compile NULL method");
1005     return false;
1006   }
1007   if (comp_level > MIN2((CompLevel) TieredStopAtLevel, CompLevel_highest_tier)) {
1008     tty->print_cr("WB error: invalid compilation level %d", comp_level);
1009     return false;
1010   }
1011   if (comp == NULL) {
1012     tty->print_cr("WB error: no compiler for requested compilation level %d", comp_level);
1013     return false;
1014   }
1015 
1016   // Check if compilation is blocking
1017   methodHandle mh(THREAD, method);
1018   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, comp);
1019   bool is_blocking = !directive->BackgroundCompilationOption;
1020   DirectivesStack::release(directive);
1021 
1022   // Compile method and check result
1023   nmethod* nm = CompileBroker::compile_method(mh, bci, comp_level, mh, mh->invocation_count(), CompileTask::Reason_Whitebox, THREAD);
1024   MutexLocker mu(Compile_lock);
1025   bool is_queued = mh->queued_for_compilation();
1026   if ((!is_blocking && is_queued) || nm != NULL) {
1027     return true;
1028   }
1029   tty->print("WB error: failed to %s compile at level %d method ", is_blocking ? "blocking" : "", comp_level);
1030   mh->print_short_name(tty);
1031   tty->cr();
1032   if (is_blocking && is_queued) {
1033     tty->print_cr("WB error: blocking compilation is still in queue!");
1034   }
1035   return false;
1036 }
1037 
1038 WB_ENTRY(jboolean, WB_EnqueueMethodForCompilation(JNIEnv* env, jobject o, jobject method, jint comp_level, jint bci))
1039   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1040   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1041   return WhiteBox::compile_method(Method::checked_resolve_jmethod_id(jmid), comp_level, bci, THREAD);
1042 WB_END
1043 
1044 WB_ENTRY(jboolean, WB_EnqueueInitializerForCompilation(JNIEnv* env, jobject o, jclass klass, jint comp_level))
1045   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1046   Method* clinit = ik->class_initializer();
1047   if (clinit == NULL) {
1048     return false;
1049   }
1050   return WhiteBox::compile_method(clinit, comp_level, InvocationEntryBci, THREAD);
1051 WB_END
1052 
1053 WB_ENTRY(jboolean, WB_ShouldPrintAssembly(JNIEnv* env, jobject o, jobject method, jint comp_level))
1054   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1055   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1056 
1057   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1058   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, CompileBroker::compiler(comp_level));
1059   bool result = directive->PrintAssemblyOption;
1060   DirectivesStack::release(directive);
1061 
1062   return result;
1063 WB_END
1064 
1065 WB_ENTRY(jint, WB_MatchesInline(JNIEnv* env, jobject o, jobject method, jstring pattern))
1066   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1067   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1068 
1069   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1070 
1071   ResourceMark rm;
1072   const char* error_msg = NULL;
1073   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
1074   InlineMatcher* m = InlineMatcher::parse_inline_pattern(method_str, error_msg);
1075 
1076   if (m == NULL) {
1077     assert(error_msg != NULL, "Always have an error message");
1078     tty->print_cr("Got error: %s", error_msg);
1079     return -1; // Pattern failed
1080   }
1081 
1082   // Pattern works - now check if it matches
1083   int result;
1084   if (m->match(mh, InlineMatcher::force_inline)) {
1085     result = 2; // Force inline match
1086   } else if (m->match(mh, InlineMatcher::dont_inline)) {
1087     result = 1; // Dont inline match
1088   } else {
1089     result = 0; // No match
1090   }
1091   delete m;
1092   return result;
1093 WB_END
1094 
1095 WB_ENTRY(jint, WB_MatchesMethod(JNIEnv* env, jobject o, jobject method, jstring pattern))
1096   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1097   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1098 
1099   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1100 
1101   ResourceMark rm;
1102   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
1103 
1104   const char* error_msg = NULL;
1105 
1106   BasicMatcher* m = BasicMatcher::parse_method_pattern(method_str, error_msg);
1107   if (m == NULL) {
1108     assert(error_msg != NULL, "Must have error_msg");
1109     tty->print_cr("Got error: %s", error_msg);
1110     return -1;
1111   }
1112 
1113   // Pattern works - now check if it matches
1114   int result = m->matches(mh);
1115   delete m;
1116   assert(result == 0 || result == 1, "Result out of range");
1117   return result;
1118 WB_END
1119 
1120 WB_ENTRY(void, WB_MarkMethodProfiled(JNIEnv* env, jobject o, jobject method))
1121   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1122   CHECK_JNI_EXCEPTION(env);
1123   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1124 
1125   MethodData* mdo = mh->method_data();
1126   if (mdo == NULL) {
1127     Method::build_interpreter_method_data(mh, CHECK_AND_CLEAR);
1128     mdo = mh->method_data();
1129   }
1130   mdo->init();
1131   InvocationCounter* icnt = mdo->invocation_counter();
1132   InvocationCounter* bcnt = mdo->backedge_counter();
1133   // set i-counter according to TieredThresholdPolicy::is_method_profiled
1134   icnt->set(InvocationCounter::wait_for_compile, Tier4MinInvocationThreshold);
1135   bcnt->set(InvocationCounter::wait_for_compile, Tier4CompileThreshold);
1136 WB_END
1137 
1138 WB_ENTRY(void, WB_ClearMethodState(JNIEnv* env, jobject o, jobject method))
1139   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1140   CHECK_JNI_EXCEPTION(env);
1141   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1142   MutexLocker mu(Compile_lock);
1143   MethodData* mdo = mh->method_data();
1144   MethodCounters* mcs = mh->method_counters();
1145 
1146   if (mdo != NULL) {
1147     mdo->init();
1148     ResourceMark rm;
1149     int arg_count = mdo->method()->size_of_parameters();
1150     for (int i = 0; i < arg_count; i++) {
1151       mdo->set_arg_modified(i, 0);
1152     }
1153     MutexLocker mu(mdo->extra_data_lock());
1154     mdo->clean_method_data(/*always_clean*/true);
1155   }
1156 
1157   mh->clear_not_c1_compilable();
1158   mh->clear_not_c2_compilable();
1159   mh->clear_not_c2_osr_compilable();
1160   NOT_PRODUCT(mh->set_compiled_invocation_count(0));
1161   if (mcs != NULL) {
1162     mcs->backedge_counter()->init();
1163     mcs->invocation_counter()->init();
1164     mcs->set_interpreter_invocation_count(0);
1165     mcs->set_interpreter_throwout_count(0);
1166 
1167 #ifdef TIERED
1168     mcs->set_rate(0.0F);
1169     mh->set_prev_event_count(0);
1170     mh->set_prev_time(0);
1171 #endif
1172   }
1173 WB_END
1174 
1175 template <typename T>
1176 static bool GetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, JVMFlag::Error (*TAt)(const JVMFlag*, T*)) {
1177   if (name == NULL) {
1178     return false;
1179   }
1180   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1181   const char* flag_name = env->GetStringUTFChars(name, NULL);
1182   CHECK_JNI_EXCEPTION_(env, false);
1183   const JVMFlag* flag = JVMFlag::find_declared_flag(flag_name);
1184   JVMFlag::Error result = (*TAt)(flag, value);
1185   env->ReleaseStringUTFChars(name, flag_name);
1186   return (result == JVMFlag::SUCCESS);
1187 }
1188 
1189 template <typename T>
1190 static bool SetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, JVMFlag::Error (*TAtPut)(JVMFlag* flag, T*, JVMFlag::Flags)) {
1191   if (name == NULL) {
1192     return false;
1193   }
1194   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1195   const char* flag_name = env->GetStringUTFChars(name, NULL);
1196   CHECK_JNI_EXCEPTION_(env, false);
1197   JVMFlag* flag = JVMFlag::find_flag(flag_name);
1198   JVMFlag::Error result = (*TAtPut)(flag, value, JVMFlag::INTERNAL);
1199   env->ReleaseStringUTFChars(name, flag_name);
1200   return (result == JVMFlag::SUCCESS);
1201 }
1202 
1203 template <typename T>
1204 static jobject box(JavaThread* thread, JNIEnv* env, Symbol* name, Symbol* sig, T value) {
1205   ResourceMark rm(thread);
1206   jclass clazz = env->FindClass(name->as_C_string());
1207   CHECK_JNI_EXCEPTION_(env, NULL);
1208   jmethodID methodID = env->GetStaticMethodID(clazz,
1209         vmSymbols::valueOf_name()->as_C_string(),
1210         sig->as_C_string());
1211   CHECK_JNI_EXCEPTION_(env, NULL);
1212   jobject result = env->CallStaticObjectMethod(clazz, methodID, value);
1213   CHECK_JNI_EXCEPTION_(env, NULL);
1214   return result;
1215 }
1216 
1217 static jobject booleanBox(JavaThread* thread, JNIEnv* env, jboolean value) {
1218   return box(thread, env, vmSymbols::java_lang_Boolean(), vmSymbols::Boolean_valueOf_signature(), value);
1219 }
1220 static jobject integerBox(JavaThread* thread, JNIEnv* env, jint value) {
1221   return box(thread, env, vmSymbols::java_lang_Integer(), vmSymbols::Integer_valueOf_signature(), value);
1222 }
1223 static jobject longBox(JavaThread* thread, JNIEnv* env, jlong value) {
1224   return box(thread, env, vmSymbols::java_lang_Long(), vmSymbols::Long_valueOf_signature(), value);
1225 }
1226 /* static jobject floatBox(JavaThread* thread, JNIEnv* env, jfloat value) {
1227   return box(thread, env, vmSymbols::java_lang_Float(), vmSymbols::Float_valueOf_signature(), value);
1228 }*/
1229 static jobject doubleBox(JavaThread* thread, JNIEnv* env, jdouble value) {
1230   return box(thread, env, vmSymbols::java_lang_Double(), vmSymbols::Double_valueOf_signature(), value);
1231 }
1232 
1233 static const JVMFlag* getVMFlag(JavaThread* thread, JNIEnv* env, jstring name) {
1234   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1235   const char* flag_name = env->GetStringUTFChars(name, NULL);
1236   CHECK_JNI_EXCEPTION_(env, NULL);
1237   const JVMFlag* result = JVMFlag::find_declared_flag(flag_name);
1238   env->ReleaseStringUTFChars(name, flag_name);
1239   return result;
1240 }
1241 
1242 WB_ENTRY(jboolean, WB_IsConstantVMFlag(JNIEnv* env, jobject o, jstring name))
1243   const JVMFlag* flag = getVMFlag(thread, env, name);
1244   return (flag != NULL) && flag->is_constant_in_binary();
1245 WB_END
1246 
1247 WB_ENTRY(jboolean, WB_IsLockedVMFlag(JNIEnv* env, jobject o, jstring name))
1248   const JVMFlag* flag = getVMFlag(thread, env, name);
1249   return (flag != NULL) && !(flag->is_unlocked() || flag->is_unlocker());
1250 WB_END
1251 
1252 WB_ENTRY(jobject, WB_GetBooleanVMFlag(JNIEnv* env, jobject o, jstring name))
1253   bool result;
1254   if (GetVMFlag <bool> (thread, env, name, &result, &JVMFlag::boolAt)) {
1255     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1256     return booleanBox(thread, env, result);
1257   }
1258   return NULL;
1259 WB_END
1260 
1261 WB_ENTRY(jobject, WB_GetIntVMFlag(JNIEnv* env, jobject o, jstring name))
1262   int result;
1263   if (GetVMFlag <int> (thread, env, name, &result, &JVMFlag::intAt)) {
1264     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1265     return longBox(thread, env, result);
1266   }
1267   return NULL;
1268 WB_END
1269 
1270 WB_ENTRY(jobject, WB_GetUintVMFlag(JNIEnv* env, jobject o, jstring name))
1271   uint result;
1272   if (GetVMFlag <uint> (thread, env, name, &result, &JVMFlag::uintAt)) {
1273     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1274     return longBox(thread, env, result);
1275   }
1276   return NULL;
1277 WB_END
1278 
1279 WB_ENTRY(jobject, WB_GetIntxVMFlag(JNIEnv* env, jobject o, jstring name))
1280   intx result;
1281   if (GetVMFlag <intx> (thread, env, name, &result, &JVMFlag::intxAt)) {
1282     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1283     return longBox(thread, env, result);
1284   }
1285   return NULL;
1286 WB_END
1287 
1288 WB_ENTRY(jobject, WB_GetUintxVMFlag(JNIEnv* env, jobject o, jstring name))
1289   uintx result;
1290   if (GetVMFlag <uintx> (thread, env, name, &result, &JVMFlag::uintxAt)) {
1291     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1292     return longBox(thread, env, result);
1293   }
1294   return NULL;
1295 WB_END
1296 
1297 WB_ENTRY(jobject, WB_GetUint64VMFlag(JNIEnv* env, jobject o, jstring name))
1298   uint64_t result;
1299   if (GetVMFlag <uint64_t> (thread, env, name, &result, &JVMFlag::uint64_tAt)) {
1300     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1301     return longBox(thread, env, result);
1302   }
1303   return NULL;
1304 WB_END
1305 
1306 WB_ENTRY(jobject, WB_GetSizeTVMFlag(JNIEnv* env, jobject o, jstring name))
1307   size_t result;
1308   if (GetVMFlag <size_t> (thread, env, name, &result, &JVMFlag::size_tAt)) {
1309     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1310     return longBox(thread, env, result);
1311   }
1312   return NULL;
1313 WB_END
1314 
1315 WB_ENTRY(jobject, WB_GetDoubleVMFlag(JNIEnv* env, jobject o, jstring name))
1316   double result;
1317   if (GetVMFlag <double> (thread, env, name, &result, &JVMFlag::doubleAt)) {
1318     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1319     return doubleBox(thread, env, result);
1320   }
1321   return NULL;
1322 WB_END
1323 
1324 WB_ENTRY(jstring, WB_GetStringVMFlag(JNIEnv* env, jobject o, jstring name))
1325   ccstr ccstrResult;
1326   if (GetVMFlag <ccstr> (thread, env, name, &ccstrResult, &JVMFlag::ccstrAt)) {
1327     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1328     jstring result = env->NewStringUTF(ccstrResult);
1329     CHECK_JNI_EXCEPTION_(env, NULL);
1330     return result;
1331   }
1332   return NULL;
1333 WB_END
1334 
1335 WB_ENTRY(void, WB_SetBooleanVMFlag(JNIEnv* env, jobject o, jstring name, jboolean value))
1336   bool result = value == JNI_TRUE ? true : false;
1337   SetVMFlag <bool> (thread, env, name, &result, &JVMFlag::boolAtPut);
1338 WB_END
1339 
1340 WB_ENTRY(void, WB_SetIntVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1341   int result = value;
1342   SetVMFlag <int> (thread, env, name, &result, &JVMFlag::intAtPut);
1343 WB_END
1344 
1345 WB_ENTRY(void, WB_SetUintVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1346   uint result = value;
1347   SetVMFlag <uint> (thread, env, name, &result, &JVMFlag::uintAtPut);
1348 WB_END
1349 
1350 WB_ENTRY(void, WB_SetIntxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1351   intx result = value;
1352   SetVMFlag <intx> (thread, env, name, &result, &JVMFlag::intxAtPut);
1353 WB_END
1354 
1355 WB_ENTRY(void, WB_SetUintxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1356   uintx result = value;
1357   SetVMFlag <uintx> (thread, env, name, &result, &JVMFlag::uintxAtPut);
1358 WB_END
1359 
1360 WB_ENTRY(void, WB_SetUint64VMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1361   uint64_t result = value;
1362   SetVMFlag <uint64_t> (thread, env, name, &result, &JVMFlag::uint64_tAtPut);
1363 WB_END
1364 
1365 WB_ENTRY(void, WB_SetSizeTVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1366   size_t result = value;
1367   SetVMFlag <size_t> (thread, env, name, &result, &JVMFlag::size_tAtPut);
1368 WB_END
1369 
1370 WB_ENTRY(void, WB_SetDoubleVMFlag(JNIEnv* env, jobject o, jstring name, jdouble value))
1371   double result = value;
1372   SetVMFlag <double> (thread, env, name, &result, &JVMFlag::doubleAtPut);
1373 WB_END
1374 
1375 WB_ENTRY(void, WB_SetStringVMFlag(JNIEnv* env, jobject o, jstring name, jstring value))
1376   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1377   const char* ccstrValue;
1378   if (value == NULL) {
1379     ccstrValue = NULL;
1380   }
1381   else {
1382     ccstrValue = env->GetStringUTFChars(value, NULL);
1383     CHECK_JNI_EXCEPTION(env);
1384   }
1385   ccstr ccstrResult = ccstrValue;
1386   bool needFree;
1387   {
1388     ThreadInVMfromNative ttvfn(thread); // back to VM
1389     needFree = SetVMFlag <ccstr> (thread, env, name, &ccstrResult, &JVMFlag::ccstrAtPut);
1390   }
1391   if (value != NULL) {
1392     env->ReleaseStringUTFChars(value, ccstrValue);
1393   }
1394   if (needFree) {
1395     FREE_C_HEAP_ARRAY(char, ccstrResult);
1396   }
1397 WB_END
1398 
1399 WB_ENTRY(void, WB_LockCompilation(JNIEnv* env, jobject o, jlong timeout))
1400   WhiteBox::compilation_locked = true;
1401 WB_END
1402 
1403 WB_ENTRY(void, WB_UnlockCompilation(JNIEnv* env, jobject o))
1404   MonitorLocker mo(Compilation_lock, Mutex::_no_safepoint_check_flag);
1405   WhiteBox::compilation_locked = false;
1406   mo.notify_all();
1407 WB_END
1408 
1409 WB_ENTRY(void, WB_ForceNMethodSweep(JNIEnv* env, jobject o))
1410   // Force a code cache sweep and block until it finished
1411   NMethodSweeper::force_sweep();
1412 WB_END
1413 
1414 WB_ENTRY(jboolean, WB_IsInStringTable(JNIEnv* env, jobject o, jstring javaString))
1415   ResourceMark rm(THREAD);
1416   int len;
1417   jchar* name = java_lang_String::as_unicode_string(JNIHandles::resolve(javaString), len, CHECK_false);
1418   return (StringTable::lookup(name, len) != NULL);
1419 WB_END
1420 
1421 WB_ENTRY(void, WB_FullGC(JNIEnv* env, jobject o))
1422   Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(true);
1423   Universe::heap()->collect(GCCause::_wb_full_gc);
1424 #if INCLUDE_G1GC
1425   if (UseG1GC) {
1426     // Needs to be cleared explicitly for G1
1427     Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(false);
1428   }
1429 #endif // INCLUDE_G1GC
1430 WB_END
1431 
1432 WB_ENTRY(void, WB_YoungGC(JNIEnv* env, jobject o))
1433   Universe::heap()->collect(GCCause::_wb_young_gc);
1434 WB_END
1435 
1436 WB_ENTRY(void, WB_ReadReservedMemory(JNIEnv* env, jobject o))
1437   // static+volatile in order to force the read to happen
1438   // (not be eliminated by the compiler)
1439   static char c;
1440   static volatile char* p;
1441 
1442   p = os::reserve_memory(os::vm_allocation_granularity(), NULL, 0);
1443   if (p == NULL) {
1444     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "Failed to reserve memory");
1445   }
1446 
1447   c = *p;
1448 WB_END
1449 
1450 WB_ENTRY(jstring, WB_GetCPUFeatures(JNIEnv* env, jobject o))
1451   const char* features = VM_Version::features_string();
1452   ThreadToNativeFromVM ttn(thread);
1453   jstring features_string = env->NewStringUTF(features);
1454 
1455   CHECK_JNI_EXCEPTION_(env, NULL);
1456 
1457   return features_string;
1458 WB_END
1459 
1460 int WhiteBox::get_blob_type(const CodeBlob* code) {
1461   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1462   if (code->is_aot()) {
1463     return -1;
1464   }
1465   return CodeCache::get_code_heap(code)->code_blob_type();
1466 }
1467 
1468 CodeHeap* WhiteBox::get_code_heap(int blob_type) {
1469   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1470   return CodeCache::get_code_heap(blob_type);
1471 }
1472 
1473 struct CodeBlobStub {
1474   CodeBlobStub(const CodeBlob* blob) :
1475       name(os::strdup(blob->name())),
1476       size(blob->size()),
1477       blob_type(WhiteBox::get_blob_type(blob)),
1478       address((jlong) blob) { }
1479   ~CodeBlobStub() { os::free((void*) name); }
1480   const char* const name;
1481   const jint        size;
1482   const jint        blob_type;
1483   const jlong       address;
1484 };
1485 
1486 static jobjectArray codeBlob2objectArray(JavaThread* thread, JNIEnv* env, CodeBlobStub* cb) {
1487   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1488   CHECK_JNI_EXCEPTION_(env, NULL);
1489   jobjectArray result = env->NewObjectArray(4, clazz, NULL);
1490 
1491   jstring name = env->NewStringUTF(cb->name);
1492   CHECK_JNI_EXCEPTION_(env, NULL);
1493   env->SetObjectArrayElement(result, 0, name);
1494 
1495   jobject obj = integerBox(thread, env, cb->size);
1496   CHECK_JNI_EXCEPTION_(env, NULL);
1497   env->SetObjectArrayElement(result, 1, obj);
1498 
1499   obj = integerBox(thread, env, cb->blob_type);
1500   CHECK_JNI_EXCEPTION_(env, NULL);
1501   env->SetObjectArrayElement(result, 2, obj);
1502 
1503   obj = longBox(thread, env, cb->address);
1504   CHECK_JNI_EXCEPTION_(env, NULL);
1505   env->SetObjectArrayElement(result, 3, obj);
1506 
1507   return result;
1508 }
1509 
1510 WB_ENTRY(jobjectArray, WB_GetNMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
1511   ResourceMark rm(THREAD);
1512   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1513   CHECK_JNI_EXCEPTION_(env, NULL);
1514   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1515   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
1516   jobjectArray result = NULL;
1517   if (code == NULL) {
1518     return result;
1519   }
1520   int comp_level = code->comp_level();
1521   int insts_size = comp_level == CompLevel_aot ? code->code_end() - code->code_begin() : code->insts_size();
1522 
1523   ThreadToNativeFromVM ttn(thread);
1524   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1525   CHECK_JNI_EXCEPTION_(env, NULL);
1526   result = env->NewObjectArray(5, clazz, NULL);
1527   if (result == NULL) {
1528     return result;
1529   }
1530 
1531   CodeBlobStub stub(code);
1532   jobjectArray codeBlob = codeBlob2objectArray(thread, env, &stub);
1533   CHECK_JNI_EXCEPTION_(env, NULL);
1534   env->SetObjectArrayElement(result, 0, codeBlob);
1535 
1536   jobject level = integerBox(thread, env, comp_level);
1537   CHECK_JNI_EXCEPTION_(env, NULL);
1538   env->SetObjectArrayElement(result, 1, level);
1539 
1540   jbyteArray insts = env->NewByteArray(insts_size);
1541   CHECK_JNI_EXCEPTION_(env, NULL);
1542   env->SetByteArrayRegion(insts, 0, insts_size, (jbyte*) code->insts_begin());
1543   env->SetObjectArrayElement(result, 2, insts);
1544 
1545   jobject id = integerBox(thread, env, code->compile_id());
1546   CHECK_JNI_EXCEPTION_(env, NULL);
1547   env->SetObjectArrayElement(result, 3, id);
1548 
1549   jobject entry_point = longBox(thread, env, (jlong) code->entry_point());
1550   CHECK_JNI_EXCEPTION_(env, NULL);
1551   env->SetObjectArrayElement(result, 4, entry_point);
1552 
1553   return result;
1554 WB_END
1555 
1556 CodeBlob* WhiteBox::allocate_code_blob(int size, int blob_type) {
1557   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1558   BufferBlob* blob;
1559   int full_size = CodeBlob::align_code_offset(sizeof(BufferBlob));
1560   if (full_size < size) {
1561     full_size += align_up(size - full_size, oopSize);
1562   }
1563   {
1564     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1565     blob = (BufferBlob*) CodeCache::allocate(full_size, blob_type);
1566     if (blob != NULL) {
1567       ::new (blob) BufferBlob("WB::DummyBlob", full_size);
1568     }
1569   }
1570   // Track memory usage statistic after releasing CodeCache_lock
1571   MemoryService::track_code_cache_memory_usage();
1572   return blob;
1573 }
1574 
1575 WB_ENTRY(jlong, WB_AllocateCodeBlob(JNIEnv* env, jobject o, jint size, jint blob_type))
1576   if (size < 0) {
1577     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1578       err_msg("WB_AllocateCodeBlob: size is negative: " INT32_FORMAT, size));
1579   }
1580   return (jlong) WhiteBox::allocate_code_blob(size, blob_type);
1581 WB_END
1582 
1583 WB_ENTRY(void, WB_FreeCodeBlob(JNIEnv* env, jobject o, jlong addr))
1584   if (addr == 0) {
1585     return;
1586   }
1587   BufferBlob::free((BufferBlob*) addr);
1588 WB_END
1589 
1590 WB_ENTRY(jobjectArray, WB_GetCodeHeapEntries(JNIEnv* env, jobject o, jint blob_type))
1591   ResourceMark rm;
1592   GrowableArray<CodeBlobStub*> blobs;
1593   {
1594     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1595     CodeHeap* heap = WhiteBox::get_code_heap(blob_type);
1596     if (heap == NULL) {
1597       return NULL;
1598     }
1599     for (CodeBlob* cb = (CodeBlob*) heap->first();
1600          cb != NULL; cb = (CodeBlob*) heap->next(cb)) {
1601       CodeBlobStub* stub = NEW_RESOURCE_OBJ(CodeBlobStub);
1602       new (stub) CodeBlobStub(cb);
1603       blobs.append(stub);
1604     }
1605   }
1606   ThreadToNativeFromVM ttn(thread);
1607   jobjectArray result = NULL;
1608   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1609   CHECK_JNI_EXCEPTION_(env, NULL);
1610   result = env->NewObjectArray(blobs.length(), clazz, NULL);
1611   CHECK_JNI_EXCEPTION_(env, NULL);
1612   if (result == NULL) {
1613     return result;
1614   }
1615   int i = 0;
1616   for (GrowableArrayIterator<CodeBlobStub*> it = blobs.begin();
1617        it != blobs.end(); ++it) {
1618     jobjectArray obj = codeBlob2objectArray(thread, env, *it);
1619     CHECK_JNI_EXCEPTION_(env, NULL);
1620     env->SetObjectArrayElement(result, i, obj);
1621     CHECK_JNI_EXCEPTION_(env, NULL);
1622     ++i;
1623   }
1624   return result;
1625 WB_END
1626 
1627 WB_ENTRY(jint, WB_GetCompilationActivityMode(JNIEnv* env, jobject o))
1628   return CompileBroker::get_compilation_activity_mode();
1629 WB_END
1630 
1631 WB_ENTRY(jobjectArray, WB_GetCodeBlob(JNIEnv* env, jobject o, jlong addr))
1632   if (addr == 0) {
1633     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
1634       "WB_GetCodeBlob: addr is null");
1635   }
1636   ThreadToNativeFromVM ttn(thread);
1637   CodeBlobStub stub((CodeBlob*) addr);
1638   return codeBlob2objectArray(thread, env, &stub);
1639 WB_END
1640 
1641 WB_ENTRY(jlong, WB_GetMethodData(JNIEnv* env, jobject wv, jobject method))
1642   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1643   CHECK_JNI_EXCEPTION_(env, 0);
1644   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1645   return (jlong) mh->method_data();
1646 WB_END
1647 
1648 WB_ENTRY(jlong, WB_GetThreadStackSize(JNIEnv* env, jobject o))
1649   return (jlong) Thread::current()->stack_size();
1650 WB_END
1651 
1652 WB_ENTRY(jlong, WB_GetThreadRemainingStackSize(JNIEnv* env, jobject o))
1653   JavaThread* t = JavaThread::current();
1654   return (jlong) t->stack_available(os::current_stack_pointer()) - (jlong)JavaThread::stack_shadow_zone_size();
1655 WB_END
1656 
1657 
1658 int WhiteBox::array_bytes_to_length(size_t bytes) {
1659   return Array<u1>::bytes_to_length(bytes);
1660 }
1661 
1662 WB_ENTRY(jlong, WB_AllocateMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong size))
1663   if (size < 0) {
1664     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1665         err_msg("WB_AllocateMetaspace: size is negative: " JLONG_FORMAT, size));
1666   }
1667 
1668   oop class_loader_oop = JNIHandles::resolve(class_loader);
1669   ClassLoaderData* cld = class_loader_oop != NULL
1670       ? java_lang_ClassLoader::loader_data_acquire(class_loader_oop)
1671       : ClassLoaderData::the_null_class_loader_data();
1672 
1673   void* metadata = MetadataFactory::new_array<u1>(cld, WhiteBox::array_bytes_to_length((size_t)size), thread);
1674 
1675   return (jlong)(uintptr_t)metadata;
1676 WB_END
1677 
1678 WB_ENTRY(void, WB_FreeMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong addr, jlong size))
1679   oop class_loader_oop = JNIHandles::resolve(class_loader);
1680   ClassLoaderData* cld = class_loader_oop != NULL
1681       ? java_lang_ClassLoader::loader_data_acquire(class_loader_oop)
1682       : ClassLoaderData::the_null_class_loader_data();
1683 
1684   MetadataFactory::free_array(cld, (Array<u1>*)(uintptr_t)addr);
1685 WB_END
1686 
1687 WB_ENTRY(void, WB_DefineModule(JNIEnv* env, jobject o, jobject module, jboolean is_open,
1688                                 jstring version, jstring location, jobjectArray packages))
1689   ResourceMark rm(THREAD);
1690 
1691   objArrayOop packages_oop = objArrayOop(JNIHandles::resolve(packages));
1692   objArrayHandle packages_h(THREAD, packages_oop);
1693   int num_packages = (packages_h == NULL ? 0 : packages_h->length());
1694 
1695   char** pkgs = NULL;
1696   if (num_packages > 0) {
1697     pkgs = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char*, num_packages);
1698     for (int x = 0; x < num_packages; x++) {
1699       oop pkg_str = packages_h->obj_at(x);
1700       if (pkg_str == NULL || !pkg_str->is_a(SystemDictionary::String_klass())) {
1701         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1702                   err_msg("Bad package name"));
1703       }
1704       pkgs[x] = java_lang_String::as_utf8_string(pkg_str);
1705     }
1706   }
1707   Modules::define_module(module, is_open, version, location, (const char* const*)pkgs, num_packages, CHECK);
1708 WB_END
1709 
1710 WB_ENTRY(void, WB_AddModuleExports(JNIEnv* env, jobject o, jobject from_module, jstring package, jobject to_module))
1711   ResourceMark rm(THREAD);
1712   char* package_name = NULL;
1713   if (package != NULL) {
1714       package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
1715   }
1716   Modules::add_module_exports_qualified(from_module, package_name, to_module, CHECK);
1717 WB_END
1718 
1719 WB_ENTRY(void, WB_AddModuleExportsToAllUnnamed(JNIEnv* env, jobject o, jclass module, jstring package))
1720   ResourceMark rm(THREAD);
1721   char* package_name = NULL;
1722   if (package != NULL) {
1723       package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
1724   }
1725   Modules::add_module_exports_to_all_unnamed(module, package_name, CHECK);
1726 WB_END
1727 
1728 WB_ENTRY(void, WB_AddModuleExportsToAll(JNIEnv* env, jobject o, jclass module, jstring package))
1729   ResourceMark rm(THREAD);
1730   char* package_name = NULL;
1731   if (package != NULL) {
1732       package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
1733   }
1734   Modules::add_module_exports(module, package_name, NULL, CHECK);
1735 WB_END
1736 
1737 WB_ENTRY(void, WB_AddReadsModule(JNIEnv* env, jobject o, jobject from_module, jobject source_module))
1738   Modules::add_reads_module(from_module, source_module, CHECK);
1739 WB_END
1740 
1741 WB_ENTRY(jlong, WB_IncMetaspaceCapacityUntilGC(JNIEnv* env, jobject wb, jlong inc))
1742   if (inc < 0) {
1743     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1744         err_msg("WB_IncMetaspaceCapacityUntilGC: inc is negative: " JLONG_FORMAT, inc));
1745   }
1746 
1747   jlong max_size_t = (jlong) ((size_t) -1);
1748   if (inc > max_size_t) {
1749     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1750         err_msg("WB_IncMetaspaceCapacityUntilGC: inc does not fit in size_t: " JLONG_FORMAT, inc));
1751   }
1752 
1753   size_t new_cap_until_GC = 0;
1754   size_t aligned_inc = align_down((size_t) inc, Metaspace::commit_alignment());
1755   bool success = MetaspaceGC::inc_capacity_until_GC(aligned_inc, &new_cap_until_GC);
1756   if (!success) {
1757     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(),
1758                 "WB_IncMetaspaceCapacityUntilGC: could not increase capacity until GC "
1759                 "due to contention with another thread");
1760   }
1761   return (jlong) new_cap_until_GC;
1762 WB_END
1763 
1764 WB_ENTRY(jlong, WB_MetaspaceCapacityUntilGC(JNIEnv* env, jobject wb))
1765   return (jlong) MetaspaceGC::capacity_until_GC();
1766 WB_END
1767 
1768 WB_ENTRY(jlong, WB_MetaspaceReserveAlignment(JNIEnv* env, jobject wb))
1769   return (jlong)Metaspace::reserve_alignment();
1770 WB_END
1771 
1772 WB_ENTRY(void, WB_AssertMatchingSafepointCalls(JNIEnv* env, jobject o, jboolean mutexSafepointValue, jboolean attemptedNoSafepointValue))
1773   Mutex::SafepointCheckRequired sfpt_check_required = mutexSafepointValue ?
1774                                            Mutex::_safepoint_check_always :
1775                                            Mutex::_safepoint_check_never;
1776   Mutex::SafepointCheckFlag sfpt_check_attempted = attemptedNoSafepointValue ?
1777                                            Mutex::_no_safepoint_check_flag :
1778                                            Mutex::_safepoint_check_flag;
1779   MutexLocker ml(new Mutex(Mutex::leaf, "SFPT_Test_lock", true, sfpt_check_required),
1780                  sfpt_check_attempted);
1781 WB_END
1782 
1783 WB_ENTRY(void, WB_AssertSpecialLock(JNIEnv* env, jobject o, jboolean allowVMBlock, jboolean safepointCheck))
1784   // Create a special lock violating condition in value
1785   Mutex::SafepointCheckRequired sfpt_check_required = safepointCheck ?
1786                                            Mutex::_safepoint_check_always :
1787                                            Mutex::_safepoint_check_never;
1788   Mutex::SafepointCheckFlag safepoint_check = safepointCheck ?
1789                                            Monitor::_safepoint_check_flag :
1790                                            Monitor::_no_safepoint_check_flag;
1791 
1792   MutexLocker ml(new Mutex(Mutex::special, "SpecialTest_lock", allowVMBlock, sfpt_check_required), safepoint_check);
1793   // If the lock above succeeds, try to safepoint to test the NSV implied with this special lock.
1794   ThreadBlockInVM tbivm(JavaThread::current());
1795 WB_END
1796 
1797 WB_ENTRY(jboolean, WB_IsMonitorInflated(JNIEnv* env, jobject wb, jobject obj))
1798   oop obj_oop = JNIHandles::resolve(obj);
1799   return (jboolean) obj_oop->mark().has_monitor();
1800 WB_END
1801 
1802 WB_ENTRY(void, WB_ForceSafepoint(JNIEnv* env, jobject wb))
1803   VM_ForceSafepoint force_safepoint_op;
1804   VMThread::execute(&force_safepoint_op);
1805 WB_END
1806 
1807 WB_ENTRY(jlong, WB_GetConstantPool(JNIEnv* env, jobject wb, jclass klass))
1808   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1809   return (jlong) ik->constants();
1810 WB_END
1811 
1812 WB_ENTRY(jint, WB_GetConstantPoolCacheIndexTag(JNIEnv* env, jobject wb))
1813   return ConstantPool::CPCACHE_INDEX_TAG;
1814 WB_END
1815 
1816 WB_ENTRY(jint, WB_GetConstantPoolCacheLength(JNIEnv* env, jobject wb, jclass klass))
1817   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1818   ConstantPool* cp = ik->constants();
1819   if (cp->cache() == NULL) {
1820       return -1;
1821   }
1822   return cp->cache()->length();
1823 WB_END
1824 
1825 WB_ENTRY(jint, WB_ConstantPoolRemapInstructionOperandFromCache(JNIEnv* env, jobject wb, jclass klass, jint index))
1826   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1827   ConstantPool* cp = ik->constants();
1828   if (cp->cache() == NULL) {
1829     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(), "Constant pool does not have a cache");
1830   }
1831   jint cpci = index;
1832   jint cpciTag = ConstantPool::CPCACHE_INDEX_TAG;
1833   if (cpciTag > cpci || cpci >= cp->cache()->length() + cpciTag) {
1834     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool cache index is out of range");
1835   }
1836   jint cpi = cp->remap_instruction_operand_from_cache(cpci);
1837   return cpi;
1838 WB_END
1839 
1840 WB_ENTRY(jint, WB_ConstantPoolEncodeIndyIndex(JNIEnv* env, jobject wb, jint index))
1841   return ConstantPool::encode_invokedynamic_index(index);
1842 WB_END
1843 
1844 WB_ENTRY(void, WB_ClearInlineCaches(JNIEnv* env, jobject wb, jboolean preserve_static_stubs))
1845   VM_ClearICs clear_ics(preserve_static_stubs == JNI_TRUE);
1846   VMThread::execute(&clear_ics);
1847 WB_END
1848 
1849 template <typename T>
1850 static bool GetMethodOption(JavaThread* thread, JNIEnv* env, jobject method, jstring name, T* value) {
1851   assert(value != NULL, "sanity");
1852   if (method == NULL || name == NULL) {
1853     return false;
1854   }
1855   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1856   CHECK_JNI_EXCEPTION_(env, false);
1857   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1858   // can't be in VM when we call JNI
1859   ThreadToNativeFromVM ttnfv(thread);
1860   const char* flag_name = env->GetStringUTFChars(name, NULL);
1861   CHECK_JNI_EXCEPTION_(env, false);
1862   bool result =  CompilerOracle::has_option_value(mh, flag_name, *value);
1863   env->ReleaseStringUTFChars(name, flag_name);
1864   return result;
1865 }
1866 
1867 WB_ENTRY(jobject, WB_GetMethodBooleaneOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1868   bool result;
1869   if (GetMethodOption<bool> (thread, env, method, name, &result)) {
1870     // can't be in VM when we call JNI
1871     ThreadToNativeFromVM ttnfv(thread);
1872     return booleanBox(thread, env, result);
1873   }
1874   return NULL;
1875 WB_END
1876 
1877 WB_ENTRY(jobject, WB_GetMethodIntxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1878   intx result;
1879   if (GetMethodOption <intx> (thread, env, method, name, &result)) {
1880     // can't be in VM when we call JNI
1881     ThreadToNativeFromVM ttnfv(thread);
1882     return longBox(thread, env, result);
1883   }
1884   return NULL;
1885 WB_END
1886 
1887 WB_ENTRY(jobject, WB_GetMethodUintxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1888   uintx result;
1889   if (GetMethodOption <uintx> (thread, env, method, name, &result)) {
1890     // can't be in VM when we call JNI
1891     ThreadToNativeFromVM ttnfv(thread);
1892     return longBox(thread, env, result);
1893   }
1894   return NULL;
1895 WB_END
1896 
1897 WB_ENTRY(jobject, WB_GetMethodDoubleOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1898   double result;
1899   if (GetMethodOption <double> (thread, env, method, name, &result)) {
1900     // can't be in VM when we call JNI
1901     ThreadToNativeFromVM ttnfv(thread);
1902     return doubleBox(thread, env, result);
1903   }
1904   return NULL;
1905 WB_END
1906 
1907 WB_ENTRY(jobject, WB_GetMethodStringOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1908   ccstr ccstrResult;
1909   if (GetMethodOption <ccstr> (thread, env, method, name, &ccstrResult)) {
1910     // can't be in VM when we call JNI
1911     ThreadToNativeFromVM ttnfv(thread);
1912     jstring result = env->NewStringUTF(ccstrResult);
1913     CHECK_JNI_EXCEPTION_(env, NULL);
1914     return result;
1915   }
1916   return NULL;
1917 WB_END
1918 
1919 WB_ENTRY(jobject, WB_GetDefaultArchivePath(JNIEnv* env, jobject wb))
1920   const char* p = Arguments::get_default_shared_archive_path();
1921   ThreadToNativeFromVM ttn(thread);
1922   jstring path_string = env->NewStringUTF(p);
1923 
1924   CHECK_JNI_EXCEPTION_(env, NULL);
1925 
1926   return path_string;
1927 WB_END
1928 
1929 WB_ENTRY(jboolean, WB_IsSharingEnabled(JNIEnv* env, jobject wb))
1930   return UseSharedSpaces;
1931 WB_END
1932 
1933 WB_ENTRY(jboolean, WB_CDSMemoryMappingFailed(JNIEnv* env, jobject wb))
1934   return FileMapInfo::memory_mapping_failed();
1935 WB_END
1936 
1937 WB_ENTRY(jboolean, WB_IsShared(JNIEnv* env, jobject wb, jobject obj))
1938   oop obj_oop = JNIHandles::resolve(obj);
1939   return HeapShared::is_archived_object(obj_oop);
1940 WB_END
1941 
1942 WB_ENTRY(jboolean, WB_IsSharedClass(JNIEnv* env, jobject wb, jclass clazz))
1943   return (jboolean)MetaspaceShared::is_in_shared_metaspace(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
1944 WB_END
1945 
1946 WB_ENTRY(jboolean, WB_AreSharedStringsIgnored(JNIEnv* env))
1947   return !HeapShared::closed_archive_heap_region_mapped();
1948 WB_END
1949 
1950 WB_ENTRY(jobject, WB_GetResolvedReferences(JNIEnv* env, jobject wb, jclass clazz))
1951   Klass *k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
1952   if (k->is_instance_klass()) {
1953     InstanceKlass *ik = InstanceKlass::cast(k);
1954     ConstantPool *cp = ik->constants();
1955     objArrayOop refs =  cp->resolved_references();
1956     return (jobject)JNIHandles::make_local(env, refs);
1957   } else {
1958     return NULL;
1959   }
1960 WB_END
1961 
1962 WB_ENTRY(void, WB_LinkClass(JNIEnv* env, jobject wb, jclass clazz))
1963   Klass *k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
1964   if (!k->is_instance_klass()) {
1965     return;
1966   }
1967   InstanceKlass *ik = InstanceKlass::cast(k);
1968   ik->link_class(THREAD); // may throw verification error
1969 WB_END
1970 
1971 WB_ENTRY(jboolean, WB_AreOpenArchiveHeapObjectsMapped(JNIEnv* env))
1972   return HeapShared::open_archive_heap_region_mapped();
1973 WB_END
1974 
1975 WB_ENTRY(jboolean, WB_IsCDSIncludedInVmBuild(JNIEnv* env))
1976 #if INCLUDE_CDS
1977 # ifdef _LP64
1978     if (!UseCompressedOops || !UseCompressedClassPointers) {
1979       // On 64-bit VMs, CDS is supported only with compressed oops/pointers
1980       return false;
1981     }
1982 # endif // _LP64
1983   return true;
1984 #else
1985   return false;
1986 #endif // INCLUDE_CDS
1987 WB_END
1988 
1989 WB_ENTRY(jboolean, WB_isC2OrJVMCIIncludedInVmBuild(JNIEnv* env))
1990 #if COMPILER2_OR_JVMCI
1991   return true;
1992 #else
1993   return false;
1994 #endif
1995 WB_END
1996 
1997 WB_ENTRY(jboolean, WB_IsJavaHeapArchiveSupported(JNIEnv* env))
1998   return HeapShared::is_heap_object_archiving_allowed();
1999 WB_END
2000 
2001 
2002 WB_ENTRY(jboolean, WB_IsJFRIncludedInVmBuild(JNIEnv* env))
2003 #if INCLUDE_JFR
2004   return true;
2005 #else
2006   return false;
2007 #endif // INCLUDE_JFR
2008 WB_END
2009 
2010 #if INCLUDE_CDS
2011 
2012 WB_ENTRY(jint, WB_GetOffsetForName(JNIEnv* env, jobject o, jstring name))
2013   ResourceMark rm;
2014   char* c_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
2015   int result = CDSOffsets::find_offset(c_name);
2016   return (jint)result;
2017 WB_END
2018 
2019 #endif // INCLUDE_CDS
2020 
2021 WB_ENTRY(jint, WB_HandshakeWalkStack(JNIEnv* env, jobject wb, jobject thread_handle, jboolean all_threads))
2022   class TraceSelfClosure : public HandshakeClosure {
2023     jint _num_threads_completed;
2024 
2025     void do_thread(Thread* th) {
2026       assert(th->is_Java_thread(), "sanity");
2027       JavaThread* jt = (JavaThread*)th;
2028       ResourceMark rm;
2029 
2030       jt->print_on(tty);
2031       jt->print_stack_on(tty);
2032       tty->cr();
2033       Atomic::inc(&_num_threads_completed);
2034     }
2035 
2036   public:
2037     TraceSelfClosure() : HandshakeClosure("WB_TraceSelf"), _num_threads_completed(0) {}
2038 
2039     jint num_threads_completed() const { return _num_threads_completed; }
2040   };
2041   TraceSelfClosure tsc;
2042 
2043   if (all_threads) {
2044     Handshake::execute(&tsc);
2045   } else {
2046     oop thread_oop = JNIHandles::resolve(thread_handle);
2047     if (thread_oop != NULL) {
2048       JavaThread* target = java_lang_Thread::thread(thread_oop);
2049       Handshake::execute(&tsc, target);
2050     }
2051   }
2052   return tsc.num_threads_completed();
2053 WB_END
2054 
2055 //Some convenience methods to deal with objects from java
2056 int WhiteBox::offset_for_field(const char* field_name, oop object,
2057     Symbol* signature_symbol) {
2058   assert(field_name != NULL && strlen(field_name) > 0, "Field name not valid");
2059   Thread* THREAD = Thread::current();
2060 
2061   //Get the class of our object
2062   Klass* arg_klass = object->klass();
2063   //Turn it into an instance-klass
2064   InstanceKlass* ik = InstanceKlass::cast(arg_klass);
2065 
2066   //Create symbols to look for in the class
2067   TempNewSymbol name_symbol = SymbolTable::new_symbol(field_name);
2068 
2069   //To be filled in with an offset of the field we're looking for
2070   fieldDescriptor fd;
2071 
2072   Klass* res = ik->find_field(name_symbol, signature_symbol, &fd);
2073   if (res == NULL) {
2074     tty->print_cr("Invalid layout of %s at %s", ik->external_name(),
2075         name_symbol->as_C_string());
2076     vm_exit_during_initialization("Invalid layout of preloaded class: use -Xlog:class+load=info to see the origin of the problem class");
2077   }
2078 
2079   //fetch the field at the offset we've found
2080   int dest_offset = fd.offset();
2081 
2082   return dest_offset;
2083 }
2084 
2085 
2086 const char* WhiteBox::lookup_jstring(const char* field_name, oop object) {
2087   int offset = offset_for_field(field_name, object,
2088       vmSymbols::string_signature());
2089   oop string = object->obj_field(offset);
2090   if (string == NULL) {
2091     return NULL;
2092   }
2093   const char* ret = java_lang_String::as_utf8_string(string);
2094   return ret;
2095 }
2096 
2097 bool WhiteBox::lookup_bool(const char* field_name, oop object) {
2098   int offset =
2099       offset_for_field(field_name, object, vmSymbols::bool_signature());
2100   bool ret = (object->bool_field(offset) == JNI_TRUE);
2101   return ret;
2102 }
2103 
2104 void WhiteBox::register_methods(JNIEnv* env, jclass wbclass, JavaThread* thread, JNINativeMethod* method_array, int method_count) {
2105   ResourceMark rm;
2106   ThreadToNativeFromVM ttnfv(thread); // can't be in VM when we call JNI
2107 
2108   //  one by one registration natives for exception catching
2109   jclass no_such_method_error_klass = env->FindClass(vmSymbols::java_lang_NoSuchMethodError()->as_C_string());
2110   CHECK_JNI_EXCEPTION(env);
2111   for (int i = 0, n = method_count; i < n; ++i) {
2112     // Skip dummy entries
2113     if (method_array[i].fnPtr == NULL) continue;
2114     if (env->RegisterNatives(wbclass, &method_array[i], 1) != 0) {
2115       jthrowable throwable_obj = env->ExceptionOccurred();
2116       if (throwable_obj != NULL) {
2117         env->ExceptionClear();
2118         if (env->IsInstanceOf(throwable_obj, no_such_method_error_klass)) {
2119           // NoSuchMethodError is thrown when a method can't be found or a method is not native.
2120           // Ignoring the exception since it is not preventing use of other WhiteBox methods.
2121           tty->print_cr("Warning: 'NoSuchMethodError' on register of sun.hotspot.WhiteBox::%s%s",
2122               method_array[i].name, method_array[i].signature);
2123         }
2124       } else {
2125         // Registration failed unexpectedly.
2126         tty->print_cr("Warning: unexpected error on register of sun.hotspot.WhiteBox::%s%s. All methods will be unregistered",
2127             method_array[i].name, method_array[i].signature);
2128         env->UnregisterNatives(wbclass);
2129         break;
2130       }
2131     }
2132   }
2133 }
2134 
2135 WB_ENTRY(jint, WB_AddCompilerDirective(JNIEnv* env, jobject o, jstring compDirect))
2136   // can't be in VM when we call JNI
2137   ThreadToNativeFromVM ttnfv(thread);
2138   const char* dir = env->GetStringUTFChars(compDirect, NULL);
2139   CHECK_JNI_EXCEPTION_(env, 0);
2140   int ret;
2141   {
2142     ThreadInVMfromNative ttvfn(thread); // back to VM
2143     ret = DirectivesParser::parse_string(dir, tty);
2144   }
2145   env->ReleaseStringUTFChars(compDirect, dir);
2146   // -1 for error parsing directive. Return 0 as number of directives added.
2147   if (ret == -1) {
2148     ret = 0;
2149   }
2150   return (jint) ret;
2151 WB_END
2152 
2153 WB_ENTRY(void, WB_RemoveCompilerDirective(JNIEnv* env, jobject o, jint count))
2154   DirectivesStack::pop(count);
2155 WB_END
2156 
2157 // Checks that the library libfile has the noexecstack bit set.
2158 WB_ENTRY(jboolean, WB_CheckLibSpecifiesNoexecstack(JNIEnv* env, jobject o, jstring libfile))
2159   jboolean ret = false;
2160 #ifdef LINUX
2161   // Can't be in VM when we call JNI.
2162   ThreadToNativeFromVM ttnfv(thread);
2163   const char* lf = env->GetStringUTFChars(libfile, NULL);
2164   CHECK_JNI_EXCEPTION_(env, 0);
2165   ret = (jboolean) ElfFile::specifies_noexecstack(lf);
2166   env->ReleaseStringUTFChars(libfile, lf);
2167 #endif
2168   return ret;
2169 WB_END
2170 
2171 WB_ENTRY(jboolean, WB_IsContainerized(JNIEnv* env, jobject o))
2172   LINUX_ONLY(return OSContainer::is_containerized();)
2173   return false;
2174 WB_END
2175 
2176 WB_ENTRY(void, WB_PrintOsInfo(JNIEnv* env, jobject o))
2177   os::print_os_info(tty);
2178 WB_END
2179 
2180 // Elf decoder
2181 WB_ENTRY(void, WB_DisableElfSectionCache(JNIEnv* env))
2182 #if !defined(_WINDOWS) && !defined(__APPLE__) && !defined(_AIX)
2183   ElfFile::_do_not_cache_elf_section = true;
2184 #endif
2185 WB_END
2186 
2187 WB_ENTRY(jlong, WB_ResolvedMethodItemsCount(JNIEnv* env, jobject o))
2188   return (jlong) ResolvedMethodTable::items_count();
2189 WB_END
2190 
2191 WB_ENTRY(jint, WB_ProtectionDomainRemovedCount(JNIEnv* env, jobject o))
2192   return (jint) SystemDictionary::pd_cache_table()->removed_entries_count();
2193 WB_END
2194 
2195 WB_ENTRY(jint, WB_AotLibrariesCount(JNIEnv* env, jobject o))
2196   jint result = 0;
2197 #if INCLUDE_AOT
2198   result = (jint) AOTLoader::heaps_count();
2199 #endif
2200   return result;
2201 WB_END
2202 
2203 WB_ENTRY(jint, WB_GetKlassMetadataSize(JNIEnv* env, jobject wb, jclass mirror))
2204   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(mirror));
2205   // Return size in bytes.
2206   return k->size() * wordSize;
2207 WB_END
2208 
2209 #define CC (char*)
2210 
2211 static JNINativeMethod methods[] = {
2212   {CC"getObjectAddress0",                CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectAddress  },
2213   {CC"getObjectSize0",                   CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectSize     },
2214   {CC"isObjectInOldGen0",                CC"(Ljava/lang/Object;)Z", (void*)&WB_isObjectInOldGen  },
2215   {CC"getHeapOopSize",                   CC"()I",                   (void*)&WB_GetHeapOopSize    },
2216   {CC"getVMPageSize",                    CC"()I",                   (void*)&WB_GetVMPageSize     },
2217   {CC"getVMAllocationGranularity",       CC"()J",                   (void*)&WB_GetVMAllocationGranularity },
2218   {CC"getVMLargePageSize",               CC"()J",                   (void*)&WB_GetVMLargePageSize},
2219   {CC"getHeapSpaceAlignment",            CC"()J",                   (void*)&WB_GetHeapSpaceAlignment},
2220   {CC"getHeapAlignment",                 CC"()J",                   (void*)&WB_GetHeapAlignment},
2221   {CC"isClassAlive0",                    CC"(Ljava/lang/String;)Z", (void*)&WB_IsClassAlive      },
2222   {CC"getSymbolRefcount",                CC"(Ljava/lang/String;)I", (void*)&WB_GetSymbolRefcount },
2223   {CC"parseCommandLine0",
2224       CC"(Ljava/lang/String;C[Lsun/hotspot/parser/DiagnosticCommand;)[Ljava/lang/Object;",
2225       (void*) &WB_ParseCommandLine
2226   },
2227   {CC"addToBootstrapClassLoaderSearch0", CC"(Ljava/lang/String;)V",
2228                                                       (void*)&WB_AddToBootstrapClassLoaderSearch},
2229   {CC"addToSystemClassLoaderSearch0",    CC"(Ljava/lang/String;)V",
2230                                                       (void*)&WB_AddToSystemClassLoaderSearch},
2231   {CC"getCompressedOopsMaxHeapSize", CC"()J",
2232       (void*)&WB_GetCompressedOopsMaxHeapSize},
2233   {CC"printHeapSizes",     CC"()V",                   (void*)&WB_PrintHeapSizes    },
2234   {CC"runMemoryUnitTests", CC"()V",                   (void*)&WB_RunMemoryUnitTests},
2235   {CC"readFromNoaccessArea",CC"()V",                  (void*)&WB_ReadFromNoaccessArea},
2236   {CC"stressVirtualSpaceResize",CC"(JJJ)I",           (void*)&WB_StressVirtualSpaceResize},
2237 #if INCLUDE_CDS
2238   {CC"getOffsetForName0", CC"(Ljava/lang/String;)I",  (void*)&WB_GetOffsetForName},
2239 #endif
2240 #if INCLUDE_G1GC
2241   {CC"g1InConcurrentMark", CC"()Z",                   (void*)&WB_G1InConcurrentMark},
2242   {CC"g1IsHumongous0",      CC"(Ljava/lang/Object;)Z", (void*)&WB_G1IsHumongous     },
2243   {CC"g1BelongsToHumongousRegion0", CC"(J)Z",         (void*)&WB_G1BelongsToHumongousRegion},
2244   {CC"g1BelongsToFreeRegion0", CC"(J)Z",              (void*)&WB_G1BelongsToFreeRegion},
2245   {CC"g1NumMaxRegions",    CC"()J",                   (void*)&WB_G1NumMaxRegions  },
2246   {CC"g1NumFreeRegions",   CC"()J",                   (void*)&WB_G1NumFreeRegions  },
2247   {CC"g1RegionSize",       CC"()I",                   (void*)&WB_G1RegionSize      },
2248   {CC"g1StartConcMarkCycle",       CC"()Z",           (void*)&WB_G1StartMarkCycle  },
2249   {CC"g1AuxiliaryMemoryUsage", CC"()Ljava/lang/management/MemoryUsage;",
2250                                                       (void*)&WB_G1AuxiliaryMemoryUsage  },
2251   {CC"g1ActiveMemoryNodeCount", CC"()I",              (void*)&WB_G1ActiveMemoryNodeCount },
2252   {CC"g1MemoryNodeIds",    CC"()[I",                  (void*)&WB_G1MemoryNodeIds },
2253   {CC"g1GetMixedGCInfo",   CC"(I)[J",                 (void*)&WB_G1GetMixedGCInfo },
2254 #endif // INCLUDE_G1GC
2255 #if INCLUDE_G1GC || INCLUDE_PARALLELGC
2256   {CC"dramReservedStart",   CC"()J",                  (void*)&WB_DramReservedStart },
2257   {CC"dramReservedEnd",     CC"()J",                  (void*)&WB_DramReservedEnd },
2258   {CC"nvdimmReservedStart", CC"()J",                  (void*)&WB_NvdimmReservedStart },
2259   {CC"nvdimmReservedEnd",   CC"()J",                  (void*)&WB_NvdimmReservedEnd },
2260 #endif // INCLUDE_G1GC || INCLUDE_PARALLELGC
2261 #if INCLUDE_PARALLELGC
2262   {CC"psVirtualSpaceAlignment",CC"()J",               (void*)&WB_PSVirtualSpaceAlignment},
2263   {CC"psHeapGenerationAlignment",CC"()J",             (void*)&WB_PSHeapGenerationAlignment},
2264 #endif
2265 #if INCLUDE_NMT
2266   {CC"NMTMalloc",           CC"(J)J",                 (void*)&WB_NMTMalloc          },
2267   {CC"NMTMallocWithPseudoStack", CC"(JI)J",           (void*)&WB_NMTMallocWithPseudoStack},
2268   {CC"NMTMallocWithPseudoStackAndType", CC"(JII)J",   (void*)&WB_NMTMallocWithPseudoStackAndType},
2269   {CC"NMTFree",             CC"(J)V",                 (void*)&WB_NMTFree            },
2270   {CC"NMTReserveMemory",    CC"(J)J",                 (void*)&WB_NMTReserveMemory   },
2271   {CC"NMTAttemptReserveMemoryAt",    CC"(JJ)J",       (void*)&WB_NMTAttemptReserveMemoryAt },
2272   {CC"NMTCommitMemory",     CC"(JJ)V",                (void*)&WB_NMTCommitMemory    },
2273   {CC"NMTUncommitMemory",   CC"(JJ)V",                (void*)&WB_NMTUncommitMemory  },
2274   {CC"NMTReleaseMemory",    CC"(JJ)V",                (void*)&WB_NMTReleaseMemory   },
2275   {CC"NMTChangeTrackingLevel", CC"()Z",               (void*)&WB_NMTChangeTrackingLevel},
2276   {CC"NMTGetHashSize",      CC"()I",                  (void*)&WB_NMTGetHashSize     },
2277   {CC"NMTNewArena",         CC"(J)J",                 (void*)&WB_NMTNewArena        },
2278   {CC"NMTFreeArena",        CC"(J)V",                 (void*)&WB_NMTFreeArena       },
2279   {CC"NMTArenaMalloc",      CC"(JJ)V",                (void*)&WB_NMTArenaMalloc     },
2280 #endif // INCLUDE_NMT
2281   {CC"deoptimizeFrames",   CC"(Z)I",                  (void*)&WB_DeoptimizeFrames  },
2282   {CC"deoptimizeAll",      CC"()V",                   (void*)&WB_DeoptimizeAll     },
2283   {CC"deoptimizeMethod0",   CC"(Ljava/lang/reflect/Executable;Z)I",
2284                                                       (void*)&WB_DeoptimizeMethod  },
2285   {CC"isMethodCompiled0",   CC"(Ljava/lang/reflect/Executable;Z)Z",
2286                                                       (void*)&WB_IsMethodCompiled  },
2287   {CC"isMethodCompilable0", CC"(Ljava/lang/reflect/Executable;IZ)Z",
2288                                                       (void*)&WB_IsMethodCompilable},
2289   {CC"isMethodQueuedForCompilation0",
2290       CC"(Ljava/lang/reflect/Executable;)Z",          (void*)&WB_IsMethodQueuedForCompilation},
2291   {CC"isIntrinsicAvailable0",
2292       CC"(Ljava/lang/reflect/Executable;Ljava/lang/reflect/Executable;I)Z",
2293                                                       (void*)&WB_IsIntrinsicAvailable},
2294   {CC"makeMethodNotCompilable0",
2295       CC"(Ljava/lang/reflect/Executable;IZ)V",        (void*)&WB_MakeMethodNotCompilable},
2296   {CC"testSetDontInlineMethod0",
2297       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetDontInlineMethod},
2298   {CC"getMethodCompilationLevel0",
2299       CC"(Ljava/lang/reflect/Executable;Z)I",         (void*)&WB_GetMethodCompilationLevel},
2300   {CC"getMethodEntryBci0",
2301       CC"(Ljava/lang/reflect/Executable;)I",          (void*)&WB_GetMethodEntryBci},
2302   {CC"getCompileQueueSize",
2303       CC"(I)I",                                       (void*)&WB_GetCompileQueueSize},
2304   {CC"testSetForceInlineMethod0",
2305       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetForceInlineMethod},
2306   {CC"enqueueMethodForCompilation0",
2307       CC"(Ljava/lang/reflect/Executable;II)Z",        (void*)&WB_EnqueueMethodForCompilation},
2308   {CC"enqueueInitializerForCompilation0",
2309       CC"(Ljava/lang/Class;I)Z",                      (void*)&WB_EnqueueInitializerForCompilation},
2310   {CC"markMethodProfiled",
2311       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_MarkMethodProfiled},
2312   {CC"clearMethodState0",
2313       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_ClearMethodState},
2314   {CC"lockCompilation",    CC"()V",                   (void*)&WB_LockCompilation},
2315   {CC"unlockCompilation",  CC"()V",                   (void*)&WB_UnlockCompilation},
2316   {CC"matchesMethod",
2317       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2318                                                       (void*)&WB_MatchesMethod},
2319   {CC"matchesInline",
2320       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2321                                                       (void*)&WB_MatchesInline},
2322   {CC"shouldPrintAssembly",
2323         CC"(Ljava/lang/reflect/Executable;I)Z",
2324                                                         (void*)&WB_ShouldPrintAssembly},
2325 
2326   {CC"isConstantVMFlag",   CC"(Ljava/lang/String;)Z", (void*)&WB_IsConstantVMFlag},
2327   {CC"isLockedVMFlag",     CC"(Ljava/lang/String;)Z", (void*)&WB_IsLockedVMFlag},
2328   {CC"setBooleanVMFlag",   CC"(Ljava/lang/String;Z)V",(void*)&WB_SetBooleanVMFlag},
2329   {CC"setIntVMFlag",       CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntVMFlag},
2330   {CC"setUintVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintVMFlag},
2331   {CC"setIntxVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntxVMFlag},
2332   {CC"setUintxVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintxVMFlag},
2333   {CC"setUint64VMFlag",    CC"(Ljava/lang/String;J)V",(void*)&WB_SetUint64VMFlag},
2334   {CC"setSizeTVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetSizeTVMFlag},
2335   {CC"setDoubleVMFlag",    CC"(Ljava/lang/String;D)V",(void*)&WB_SetDoubleVMFlag},
2336   {CC"setStringVMFlag",    CC"(Ljava/lang/String;Ljava/lang/String;)V",
2337                                                       (void*)&WB_SetStringVMFlag},
2338   {CC"getBooleanVMFlag",   CC"(Ljava/lang/String;)Ljava/lang/Boolean;",
2339                                                       (void*)&WB_GetBooleanVMFlag},
2340   {CC"getIntVMFlag",       CC"(Ljava/lang/String;)Ljava/lang/Long;",
2341                                                       (void*)&WB_GetIntVMFlag},
2342   {CC"getUintVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
2343                                                       (void*)&WB_GetUintVMFlag},
2344   {CC"getIntxVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
2345                                                       (void*)&WB_GetIntxVMFlag},
2346   {CC"getUintxVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
2347                                                       (void*)&WB_GetUintxVMFlag},
2348   {CC"getUint64VMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Long;",
2349                                                       (void*)&WB_GetUint64VMFlag},
2350   {CC"getSizeTVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
2351                                                       (void*)&WB_GetSizeTVMFlag},
2352   {CC"getDoubleVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Double;",
2353                                                       (void*)&WB_GetDoubleVMFlag},
2354   {CC"getStringVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/String;",
2355                                                       (void*)&WB_GetStringVMFlag},
2356   {CC"isInStringTable",    CC"(Ljava/lang/String;)Z", (void*)&WB_IsInStringTable  },
2357   {CC"fullGC",   CC"()V",                             (void*)&WB_FullGC },
2358   {CC"youngGC",  CC"()V",                             (void*)&WB_YoungGC },
2359   {CC"readReservedMemory", CC"()V",                   (void*)&WB_ReadReservedMemory },
2360   {CC"allocateMetaspace",
2361      CC"(Ljava/lang/ClassLoader;J)J",                 (void*)&WB_AllocateMetaspace },
2362   {CC"freeMetaspace",
2363      CC"(Ljava/lang/ClassLoader;JJ)V",                (void*)&WB_FreeMetaspace },
2364   {CC"incMetaspaceCapacityUntilGC", CC"(J)J",         (void*)&WB_IncMetaspaceCapacityUntilGC },
2365   {CC"metaspaceCapacityUntilGC", CC"()J",             (void*)&WB_MetaspaceCapacityUntilGC },
2366   {CC"metaspaceReserveAlignment", CC"()J",            (void*)&WB_MetaspaceReserveAlignment },
2367   {CC"getCPUFeatures",     CC"()Ljava/lang/String;",  (void*)&WB_GetCPUFeatures     },
2368   {CC"getNMethod0",         CC"(Ljava/lang/reflect/Executable;Z)[Ljava/lang/Object;",
2369                                                       (void*)&WB_GetNMethod         },
2370   {CC"forceNMethodSweep",  CC"()V",                   (void*)&WB_ForceNMethodSweep  },
2371   {CC"allocateCodeBlob",   CC"(II)J",                 (void*)&WB_AllocateCodeBlob   },
2372   {CC"freeCodeBlob",       CC"(J)V",                  (void*)&WB_FreeCodeBlob       },
2373   {CC"getCodeHeapEntries", CC"(I)[Ljava/lang/Object;",(void*)&WB_GetCodeHeapEntries },
2374   {CC"getCompilationActivityMode",
2375                            CC"()I",                   (void*)&WB_GetCompilationActivityMode},
2376   {CC"getMethodData0",     CC"(Ljava/lang/reflect/Executable;)J",
2377                                                       (void*)&WB_GetMethodData      },
2378   {CC"getCodeBlob",        CC"(J)[Ljava/lang/Object;",(void*)&WB_GetCodeBlob        },
2379   {CC"getThreadStackSize", CC"()J",                   (void*)&WB_GetThreadStackSize },
2380   {CC"getThreadRemainingStackSize", CC"()J",          (void*)&WB_GetThreadRemainingStackSize },
2381   {CC"DefineModule",       CC"(Ljava/lang/Object;ZLjava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V",
2382                                                       (void*)&WB_DefineModule },
2383   {CC"AddModuleExports",   CC"(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V",
2384                                                       (void*)&WB_AddModuleExports },
2385   {CC"AddReadsModule",     CC"(Ljava/lang/Object;Ljava/lang/Object;)V",
2386                                                       (void*)&WB_AddReadsModule },
2387   {CC"AddModuleExportsToAllUnnamed", CC"(Ljava/lang/Object;Ljava/lang/String;)V",
2388                                                       (void*)&WB_AddModuleExportsToAllUnnamed },
2389   {CC"AddModuleExportsToAll", CC"(Ljava/lang/Object;Ljava/lang/String;)V",
2390                                                       (void*)&WB_AddModuleExportsToAll },
2391   {CC"assertMatchingSafepointCalls", CC"(ZZ)V",       (void*)&WB_AssertMatchingSafepointCalls },
2392   {CC"assertSpecialLock",  CC"(ZZ)V",                 (void*)&WB_AssertSpecialLock },
2393   {CC"isMonitorInflated0", CC"(Ljava/lang/Object;)Z", (void*)&WB_IsMonitorInflated  },
2394   {CC"forceSafepoint",     CC"()V",                   (void*)&WB_ForceSafepoint     },
2395   {CC"getConstantPool0",   CC"(Ljava/lang/Class;)J",  (void*)&WB_GetConstantPool    },
2396   {CC"getConstantPoolCacheIndexTag0", CC"()I",  (void*)&WB_GetConstantPoolCacheIndexTag},
2397   {CC"getConstantPoolCacheLength0", CC"(Ljava/lang/Class;)I",  (void*)&WB_GetConstantPoolCacheLength},
2398   {CC"remapInstructionOperandFromCPCache0",
2399       CC"(Ljava/lang/Class;I)I",                      (void*)&WB_ConstantPoolRemapInstructionOperandFromCache},
2400   {CC"encodeConstantPoolIndyIndex0",
2401       CC"(I)I",                      (void*)&WB_ConstantPoolEncodeIndyIndex},
2402   {CC"getMethodBooleanOption",
2403       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Boolean;",
2404                                                       (void*)&WB_GetMethodBooleaneOption},
2405   {CC"getMethodIntxOption",
2406       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
2407                                                       (void*)&WB_GetMethodIntxOption},
2408   {CC"getMethodUintxOption",
2409       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
2410                                                       (void*)&WB_GetMethodUintxOption},
2411   {CC"getMethodDoubleOption",
2412       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Double;",
2413                                                       (void*)&WB_GetMethodDoubleOption},
2414   {CC"getMethodStringOption",
2415       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/String;",
2416                                                       (void*)&WB_GetMethodStringOption},
2417   {CC"getDefaultArchivePath",             CC"()Ljava/lang/String;",
2418                                                       (void*)&WB_GetDefaultArchivePath},
2419   {CC"isSharingEnabled",   CC"()Z",                   (void*)&WB_IsSharingEnabled},
2420   {CC"isShared",           CC"(Ljava/lang/Object;)Z", (void*)&WB_IsShared },
2421   {CC"isSharedClass",      CC"(Ljava/lang/Class;)Z",  (void*)&WB_IsSharedClass },
2422   {CC"areSharedStringsIgnored",           CC"()Z",    (void*)&WB_AreSharedStringsIgnored },
2423   {CC"getResolvedReferences", CC"(Ljava/lang/Class;)Ljava/lang/Object;", (void*)&WB_GetResolvedReferences},
2424   {CC"linkClass",          CC"(Ljava/lang/Class;)V",  (void*)&WB_LinkClass},
2425   {CC"areOpenArchiveHeapObjectsMapped",   CC"()Z",    (void*)&WB_AreOpenArchiveHeapObjectsMapped},
2426   {CC"isCDSIncludedInVmBuild",            CC"()Z",    (void*)&WB_IsCDSIncludedInVmBuild },
2427   {CC"isJFRIncludedInVmBuild",            CC"()Z",    (void*)&WB_IsJFRIncludedInVmBuild },
2428   {CC"isC2OrJVMCIIncludedInVmBuild",      CC"()Z",    (void*)&WB_isC2OrJVMCIIncludedInVmBuild },
2429   {CC"isJavaHeapArchiveSupported",        CC"()Z",    (void*)&WB_IsJavaHeapArchiveSupported },
2430   {CC"cdsMemoryMappingFailed",            CC"()Z",    (void*)&WB_CDSMemoryMappingFailed },
2431 
2432   {CC"clearInlineCaches0",  CC"(Z)V",                 (void*)&WB_ClearInlineCaches },
2433   {CC"handshakeWalkStack", CC"(Ljava/lang/Thread;Z)I", (void*)&WB_HandshakeWalkStack },
2434   {CC"addCompilerDirective",    CC"(Ljava/lang/String;)I",
2435                                                       (void*)&WB_AddCompilerDirective },
2436   {CC"removeCompilerDirective",   CC"(I)V",           (void*)&WB_RemoveCompilerDirective },
2437   {CC"isGCSupported",             CC"(I)Z",           (void*)&WB_IsGCSupported},
2438   {CC"isGCSelected",              CC"(I)Z",           (void*)&WB_IsGCSelected},
2439   {CC"isGCSelectedErgonomically", CC"()Z",            (void*)&WB_IsGCSelectedErgonomically},
2440   {CC"supportsConcurrentGCPhaseControl", CC"()Z",     (void*)&WB_SupportsConcurrentGCPhaseControl},
2441   {CC"requestConcurrentGCPhase0", CC"(Ljava/lang/String;)Z",
2442                                                       (void*)&WB_RequestConcurrentGCPhase},
2443   {CC"checkLibSpecifiesNoexecstack", CC"(Ljava/lang/String;)Z",
2444                                                       (void*)&WB_CheckLibSpecifiesNoexecstack},
2445   {CC"isContainerized",           CC"()Z",            (void*)&WB_IsContainerized },
2446   {CC"printOsInfo",               CC"()V",            (void*)&WB_PrintOsInfo },
2447   {CC"disableElfSectionCache",    CC"()V",            (void*)&WB_DisableElfSectionCache },
2448   {CC"resolvedMethodItemsCount",  CC"()J",            (void*)&WB_ResolvedMethodItemsCount },
2449   {CC"protectionDomainRemovedCount",   CC"()I",       (void*)&WB_ProtectionDomainRemovedCount },
2450   {CC"aotLibrariesCount", CC"()I",                    (void*)&WB_AotLibrariesCount },
2451   {CC"getKlassMetadataSize", CC"(Ljava/lang/Class;)I",(void*)&WB_GetKlassMetadataSize},
2452 };
2453 
2454 
2455 #undef CC
2456 
2457 JVM_ENTRY(void, JVM_RegisterWhiteBoxMethods(JNIEnv* env, jclass wbclass))
2458   {
2459     if (WhiteBoxAPI) {
2460       // Make sure that wbclass is loaded by the null classloader
2461       InstanceKlass* ik = InstanceKlass::cast(JNIHandles::resolve(wbclass)->klass());
2462       Handle loader(THREAD, ik->class_loader());
2463       if (loader.is_null()) {
2464         WhiteBox::register_methods(env, wbclass, thread, methods, sizeof(methods) / sizeof(methods[0]));
2465         WhiteBox::set_used();
2466       }
2467     }
2468   }
2469 JVM_END