1 /*
   2  * Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include <new>
  27 #include "cds.h"
  28 #include "cds/cdsConstants.hpp"
  29 #include "cds/filemap.hpp"
  30 #include "cds/heapShared.inline.hpp"
  31 #include "cds/metaspaceShared.hpp"
  32 #include "classfile/classLoaderDataGraph.hpp"
  33 #include "classfile/javaClasses.inline.hpp"
  34 #include "classfile/modules.hpp"
  35 #include "classfile/protectionDomainCache.hpp"
  36 #include "classfile/stringTable.hpp"
  37 #include "classfile/symbolTable.hpp"
  38 #include "classfile/systemDictionary.hpp"
  39 #include "classfile/vmSymbols.hpp"
  40 #include "code/codeCache.hpp"
  41 #include "compiler/compilationPolicy.hpp"
  42 #include "compiler/directivesParser.hpp"
  43 #include "compiler/methodMatcher.hpp"
  44 #include "gc/shared/concurrentGCBreakpoints.hpp"
  45 #include "gc/shared/gcConfig.hpp"
  46 #include "gc/shared/gcLocker.inline.hpp"
  47 #include "gc/shared/genArguments.hpp"
  48 #include "gc/shared/genCollectedHeap.hpp"
  49 #include "jvmtifiles/jvmtiEnv.hpp"
  50 #include "logging/log.hpp"
  51 #include "memory/iterator.hpp"
  52 #include "memory/metadataFactory.hpp"
  53 #include "memory/iterator.inline.hpp"
  54 #include "memory/metaspace/testHelpers.hpp"
  55 #include "memory/metaspaceUtils.hpp"
  56 #include "memory/oopFactory.hpp"
  57 #include "memory/resourceArea.hpp"
  58 #include "memory/universe.hpp"
  59 #include "oops/array.hpp"
  60 #include "oops/compressedOops.hpp"
  61 #include "oops/compressedOops.inline.hpp"
  62 #include "oops/constantPool.inline.hpp"
  63 #include "oops/klass.inline.hpp"
  64 #include "oops/method.inline.hpp"
  65 #include "oops/objArrayKlass.hpp"
  66 #include "oops/objArrayOop.inline.hpp"
  67 #include "oops/oop.inline.hpp"
  68 #include "oops/objArrayOop.inline.hpp"
  69 #include "oops/typeArrayOop.inline.hpp"
  70 #include "prims/resolvedMethodTable.hpp"
  71 #include "prims/wbtestmethods/parserTests.hpp"
  72 #include "prims/whitebox.inline.hpp"
  73 #include "runtime/arguments.hpp"
  74 #include "runtime/atomic.hpp"
  75 #include "runtime/deoptimization.hpp"
  76 #include "runtime/fieldDescriptor.inline.hpp"
  77 #include "runtime/flags/jvmFlag.hpp"
  78 #include "runtime/flags/jvmFlagAccess.hpp"
  79 #include "runtime/frame.inline.hpp"
  80 #include "runtime/handles.inline.hpp"
  81 #include "runtime/handshake.hpp"
  82 #include "runtime/interfaceSupport.inline.hpp"
  83 #include "runtime/javaCalls.hpp"
  84 #include "runtime/jniHandles.inline.hpp"
  85 #include "runtime/os.hpp"
  86 #include "runtime/stackFrameStream.inline.hpp"
  87 #include "runtime/sweeper.hpp"
  88 #include "runtime/synchronizer.hpp"
  89 #include "runtime/thread.hpp"
  90 #include "runtime/threadSMR.hpp"
  91 #include "runtime/vframe.hpp"
  92 #include "runtime/vm_version.hpp"
  93 #include "services/mallocSiteTable.hpp"
  94 #include "services/memoryService.hpp"
  95 #include "services/memTracker.hpp"
  96 #include "utilities/align.hpp"
  97 #include "utilities/debug.hpp"
  98 #include "utilities/elfFile.hpp"
  99 #include "utilities/exceptions.hpp"
 100 #include "utilities/macros.hpp"
 101 #include "utilities/nativeCallStack.hpp"
 102 #include "utilities/ostream.hpp"
 103 #if INCLUDE_G1GC
 104 #include "gc/g1/g1Arguments.hpp"
 105 #include "gc/g1/g1CollectedHeap.inline.hpp"
 106 #include "gc/g1/g1ConcurrentMark.hpp"
 107 #include "gc/g1/g1ConcurrentMarkThread.inline.hpp"
 108 #include "gc/g1/heapRegionManager.hpp"
 109 #include "gc/g1/heapRegionRemSet.inline.hpp"
 110 #endif // INCLUDE_G1GC
 111 #if INCLUDE_PARALLELGC
 112 #include "gc/parallel/parallelScavengeHeap.inline.hpp"
 113 #endif // INCLUDE_PARALLELGC
 114 #if INCLUDE_JVMCI
 115 #include "jvmci/jvmciEnv.hpp"
 116 #include "jvmci/jvmciRuntime.hpp"
 117 #endif
 118 
 119 #ifdef LINUX
 120 #include "osContainer_linux.hpp"
 121 #include "cgroupSubsystem_linux.hpp"
 122 #endif
 123 
 124 #define SIZE_T_MAX_VALUE ((size_t) -1)
 125 
 126 #define CHECK_JNI_EXCEPTION_(env, value)                               \
 127   do {                                                                 \
 128     JavaThread* THREAD = JavaThread::thread_from_jni_environment(env); \
 129     THREAD->clear_pending_jni_exception_check();                       \
 130     if (HAS_PENDING_EXCEPTION) {                                       \
 131       return(value);                                                   \
 132     }                                                                  \
 133   } while (0)
 134 
 135 #define CHECK_JNI_EXCEPTION(env)                                       \
 136   do {                                                                 \
 137     JavaThread* THREAD = JavaThread::thread_from_jni_environment(env); \
 138     THREAD->clear_pending_jni_exception_check();                       \
 139     if (HAS_PENDING_EXCEPTION) {                                       \
 140       return;                                                          \
 141     }                                                                  \
 142   } while (0)
 143 
 144 bool WhiteBox::_used = false;
 145 volatile bool WhiteBox::compilation_locked = false;
 146 
 147 class VM_WhiteBoxOperation : public VM_Operation {
 148  public:
 149   VM_WhiteBoxOperation()                         { }
 150   VMOp_Type type()                  const        { return VMOp_WhiteBoxOperation; }
 151   bool allow_nested_vm_operations() const        { return true; }
 152 };
 153 
 154 
 155 WB_ENTRY(jlong, WB_GetObjectAddress(JNIEnv* env, jobject o, jobject obj))
 156   return (jlong)(void*)JNIHandles::resolve(obj);
 157 WB_END
 158 
 159 WB_ENTRY(jint, WB_GetHeapOopSize(JNIEnv* env, jobject o))
 160   return heapOopSize;
 161 WB_END
 162 
 163 WB_ENTRY(jint, WB_GetVMPageSize(JNIEnv* env, jobject o))
 164   return os::vm_page_size();
 165 WB_END
 166 
 167 WB_ENTRY(jlong, WB_GetVMAllocationGranularity(JNIEnv* env, jobject o))
 168   return os::vm_allocation_granularity();
 169 WB_END
 170 
 171 WB_ENTRY(jlong, WB_GetVMLargePageSize(JNIEnv* env, jobject o))
 172   return os::large_page_size();
 173 WB_END
 174 
 175 class WBIsKlassAliveClosure : public LockedClassesDo {
 176     Symbol* _name;
 177     int _count;
 178 public:
 179     WBIsKlassAliveClosure(Symbol* name) : _name(name), _count(0) {}
 180 
 181     void do_klass(Klass* k) {
 182       Symbol* ksym = k->name();
 183       if (ksym->fast_compare(_name) == 0) {
 184         _count++;
 185       } else if (k->is_instance_klass()) {
 186         // Need special handling for hidden classes because the JVM
 187         // appends "+<hex-address>" to hidden class names.
 188         InstanceKlass *ik = InstanceKlass::cast(k);
 189         if (ik->is_hidden()) {
 190           ResourceMark rm;
 191           char* k_name = ksym->as_C_string();
 192           // Find the first '+' char and truncate the string at that point.
 193           // NOTE: This will not work correctly if the original hidden class
 194           // name contains a '+'.
 195           char* plus_char = strchr(k_name, '+');
 196           if (plus_char != NULL) {
 197             *plus_char = 0;
 198             char* c_name = _name->as_C_string();
 199             if (strcmp(c_name, k_name) == 0) {
 200               _count++;
 201             }
 202           }
 203         }
 204       }
 205     }
 206 
 207     int count() const {
 208         return _count;
 209     }
 210 };
 211 
 212 WB_ENTRY(jint, WB_CountAliveClasses(JNIEnv* env, jobject target, jstring name))
 213   oop h_name = JNIHandles::resolve(name);
 214   if (h_name == NULL) return false;
 215   Symbol* sym = java_lang_String::as_symbol(h_name);
 216   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
 217 
 218   WBIsKlassAliveClosure closure(sym);
 219   ClassLoaderDataGraph::classes_do(&closure);
 220 
 221   // Return the count of alive classes with this name.
 222   return closure.count();
 223 WB_END
 224 
 225 WB_ENTRY(jint, WB_GetSymbolRefcount(JNIEnv* env, jobject unused, jstring name))
 226   oop h_name = JNIHandles::resolve(name);
 227   if (h_name == NULL) return false;
 228   Symbol* sym = java_lang_String::as_symbol(h_name);
 229   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
 230   return (jint)sym->refcount();
 231 WB_END
 232 
 233 
 234 WB_ENTRY(void, WB_AddToBootstrapClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 235 #if INCLUDE_JVMTI
 236   ResourceMark rm;
 237   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 238   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 239   jvmtiError err = jvmti_env->AddToBootstrapClassLoaderSearch(seg);
 240   assert(err == JVMTI_ERROR_NONE, "must not fail");
 241 #endif
 242 }
 243 WB_END
 244 
 245 WB_ENTRY(void, WB_AddToSystemClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 246 #if INCLUDE_JVMTI
 247   ResourceMark rm;
 248   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 249   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 250   jvmtiError err = jvmti_env->AddToSystemClassLoaderSearch(seg);
 251   assert(err == JVMTI_ERROR_NONE, "must not fail");
 252 #endif
 253 }
 254 WB_END
 255 
 256 
 257 WB_ENTRY(jlong, WB_GetCompressedOopsMaxHeapSize(JNIEnv* env, jobject o)) {
 258   return (jlong)Arguments::max_heap_for_compressed_oops();
 259 }
 260 WB_END
 261 
 262 WB_ENTRY(void, WB_PrintHeapSizes(JNIEnv* env, jobject o)) {
 263   tty->print_cr("Minimum heap " SIZE_FORMAT " Initial heap " SIZE_FORMAT " "
 264                 "Maximum heap " SIZE_FORMAT " Space alignment " SIZE_FORMAT " Heap alignment " SIZE_FORMAT,
 265                 MinHeapSize,
 266                 InitialHeapSize,
 267                 MaxHeapSize,
 268                 SpaceAlignment,
 269                 HeapAlignment);
 270 }
 271 WB_END
 272 
 273 WB_ENTRY(void, WB_ReadFromNoaccessArea(JNIEnv* env, jobject o))
 274   size_t granularity = os::vm_allocation_granularity();
 275   ReservedHeapSpace rhs(100 * granularity, granularity, os::vm_page_size());
 276   VirtualSpace vs;
 277   vs.initialize(rhs, 50 * granularity);
 278 
 279   // Check if constraints are complied
 280   if (!( UseCompressedOops && rhs.base() != NULL &&
 281          CompressedOops::base() != NULL &&
 282          CompressedOops::use_implicit_null_checks() )) {
 283     tty->print_cr("WB_ReadFromNoaccessArea method is useless:\n "
 284                   "\tUseCompressedOops is %d\n"
 285                   "\trhs.base() is " PTR_FORMAT "\n"
 286                   "\tCompressedOops::base() is " PTR_FORMAT "\n"
 287                   "\tCompressedOops::use_implicit_null_checks() is %d",
 288                   UseCompressedOops,
 289                   p2i(rhs.base()),
 290                   p2i(CompressedOops::base()),
 291                   CompressedOops::use_implicit_null_checks());
 292     return;
 293   }
 294   tty->print_cr("Reading from no access area... ");
 295   tty->print_cr("*(vs.low_boundary() - rhs.noaccess_prefix() / 2 ) = %c",
 296                 *(vs.low_boundary() - rhs.noaccess_prefix() / 2 ));
 297 WB_END
 298 
 299 static jint wb_stress_virtual_space_resize(size_t reserved_space_size,
 300                                            size_t magnitude, size_t iterations) {
 301   size_t granularity = os::vm_allocation_granularity();
 302   ReservedHeapSpace rhs(reserved_space_size * granularity, granularity, os::vm_page_size());
 303   VirtualSpace vs;
 304   if (!vs.initialize(rhs, 0)) {
 305     tty->print_cr("Failed to initialize VirtualSpace. Can't proceed.");
 306     return 3;
 307   }
 308 
 309   int seed = os::random();
 310   tty->print_cr("Random seed is %d", seed);
 311 
 312   for (size_t i = 0; i < iterations; i++) {
 313 
 314     // Whether we will shrink or grow
 315     bool shrink = os::random() % 2L == 0;
 316 
 317     // Get random delta to resize virtual space
 318     size_t delta = (size_t)os::random() % magnitude;
 319 
 320     // If we are about to shrink virtual space below zero, then expand instead
 321     if (shrink && vs.committed_size() < delta) {
 322       shrink = false;
 323     }
 324 
 325     // Resizing by delta
 326     if (shrink) {
 327       vs.shrink_by(delta);
 328     } else {
 329       // If expanding fails expand_by will silently return false
 330       vs.expand_by(delta, true);
 331     }
 332   }
 333   return 0;
 334 }
 335 
 336 WB_ENTRY(jint, WB_StressVirtualSpaceResize(JNIEnv* env, jobject o,
 337         jlong reserved_space_size, jlong magnitude, jlong iterations))
 338   tty->print_cr("reservedSpaceSize=" JLONG_FORMAT ", magnitude=" JLONG_FORMAT ", "
 339                 "iterations=" JLONG_FORMAT "\n", reserved_space_size, magnitude,
 340                 iterations);
 341   if (reserved_space_size < 0 || magnitude < 0 || iterations < 0) {
 342     tty->print_cr("One of variables printed above is negative. Can't proceed.\n");
 343     return 1;
 344   }
 345 
 346   // sizeof(size_t) depends on whether OS is 32bit or 64bit. sizeof(jlong) is
 347   // always 8 byte. That's why we should avoid overflow in case of 32bit platform.
 348   if (sizeof(size_t) < sizeof(jlong)) {
 349     jlong size_t_max_value = (jlong) SIZE_T_MAX_VALUE;
 350     if (reserved_space_size > size_t_max_value || magnitude > size_t_max_value
 351         || iterations > size_t_max_value) {
 352       tty->print_cr("One of variables printed above overflows size_t. Can't proceed.\n");
 353       return 2;
 354     }
 355   }
 356 
 357   return wb_stress_virtual_space_resize((size_t) reserved_space_size,
 358                                         (size_t) magnitude, (size_t) iterations);
 359 WB_END
 360 
 361 WB_ENTRY(jboolean, WB_IsGCSupported(JNIEnv* env, jobject o, jint name))
 362   return GCConfig::is_gc_supported((CollectedHeap::Name)name);
 363 WB_END
 364 
 365 WB_ENTRY(jboolean, WB_IsGCSupportedByJVMCICompiler(JNIEnv* env, jobject o, jint name))
 366 #if INCLUDE_JVMCI
 367   if (EnableJVMCI) {
 368     JVMCIEnv jvmciEnv(thread, env, __FILE__, __LINE__);
 369     return jvmciEnv.runtime()->is_gc_supported(&jvmciEnv, (CollectedHeap::Name)name);
 370   }
 371 #endif
 372   return false;
 373 WB_END
 374 
 375 WB_ENTRY(jboolean, WB_IsGCSelected(JNIEnv* env, jobject o, jint name))
 376   return GCConfig::is_gc_selected((CollectedHeap::Name)name);
 377 WB_END
 378 
 379 WB_ENTRY(jboolean, WB_IsGCSelectedErgonomically(JNIEnv* env, jobject o))
 380   return GCConfig::is_gc_selected_ergonomically();
 381 WB_END
 382 
 383 WB_ENTRY(jboolean, WB_isObjectInOldGen(JNIEnv* env, jobject o, jobject obj))
 384   oop p = JNIHandles::resolve(obj);
 385 #if INCLUDE_G1GC
 386   if (UseG1GC) {
 387     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 388     const HeapRegion* hr = g1h->heap_region_containing(p);
 389     if (hr == NULL) {
 390       return false;
 391     }
 392     return !(hr->is_young());
 393   }
 394 #endif
 395 #if INCLUDE_PARALLELGC
 396   if (UseParallelGC) {
 397     ParallelScavengeHeap* psh = ParallelScavengeHeap::heap();
 398     return !psh->is_in_young(p);
 399   }
 400 #endif
 401 #if INCLUDE_ZGC
 402   if (UseZGC) {
 403     return Universe::heap()->is_in(p);
 404   }
 405 #endif
 406 #if INCLUDE_SHENANDOAHGC
 407   if (UseShenandoahGC) {
 408     return Universe::heap()->is_in(p);
 409   }
 410 #endif
 411   GenCollectedHeap* gch = GenCollectedHeap::heap();
 412   return !gch->is_in_young(p);
 413 WB_END
 414 
 415 WB_ENTRY(jlong, WB_GetObjectSize(JNIEnv* env, jobject o, jobject obj))
 416   oop p = JNIHandles::resolve(obj);
 417   return p->size() * HeapWordSize;
 418 WB_END
 419 
 420 WB_ENTRY(jlong, WB_GetHeapSpaceAlignment(JNIEnv* env, jobject o))
 421   return (jlong)SpaceAlignment;
 422 WB_END
 423 
 424 WB_ENTRY(jlong, WB_GetHeapAlignment(JNIEnv* env, jobject o))
 425   return (jlong)HeapAlignment;
 426 WB_END
 427 
 428 WB_ENTRY(jboolean, WB_SupportsConcurrentGCBreakpoints(JNIEnv* env, jobject o))
 429   return Universe::heap()->supports_concurrent_gc_breakpoints();
 430 WB_END
 431 
 432 WB_ENTRY(void, WB_ConcurrentGCAcquireControl(JNIEnv* env, jobject o))
 433   ConcurrentGCBreakpoints::acquire_control();
 434 WB_END
 435 
 436 WB_ENTRY(void, WB_ConcurrentGCReleaseControl(JNIEnv* env, jobject o))
 437   ConcurrentGCBreakpoints::release_control();
 438 WB_END
 439 
 440 WB_ENTRY(void, WB_ConcurrentGCRunToIdle(JNIEnv* env, jobject o))
 441   ConcurrentGCBreakpoints::run_to_idle();
 442 WB_END
 443 
 444 WB_ENTRY(jboolean, WB_ConcurrentGCRunTo(JNIEnv* env, jobject o, jobject at))
 445   Handle h_name(THREAD, JNIHandles::resolve(at));
 446   ResourceMark rm;
 447   const char* c_name = java_lang_String::as_utf8_string(h_name());
 448   return ConcurrentGCBreakpoints::run_to(c_name);
 449 WB_END
 450 
 451 #if INCLUDE_G1GC
 452 
 453 WB_ENTRY(jboolean, WB_G1IsHumongous(JNIEnv* env, jobject o, jobject obj))
 454   if (UseG1GC) {
 455     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 456     oop result = JNIHandles::resolve(obj);
 457     const HeapRegion* hr = g1h->heap_region_containing(result);
 458     return hr->is_humongous();
 459   }
 460   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1IsHumongous: G1 GC is not enabled");
 461 WB_END
 462 
 463 WB_ENTRY(jboolean, WB_G1BelongsToHumongousRegion(JNIEnv* env, jobject o, jlong addr))
 464   if (UseG1GC) {
 465     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 466     const HeapRegion* hr = g1h->heap_region_containing((void*) addr);
 467     return hr->is_humongous();
 468   }
 469   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1BelongsToHumongousRegion: G1 GC is not enabled");
 470 WB_END
 471 
 472 WB_ENTRY(jboolean, WB_G1BelongsToFreeRegion(JNIEnv* env, jobject o, jlong addr))
 473   if (UseG1GC) {
 474     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 475     const HeapRegion* hr = g1h->heap_region_containing((void*) addr);
 476     return hr->is_free();
 477   }
 478   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1BelongsToFreeRegion: G1 GC is not enabled");
 479 WB_END
 480 
 481 WB_ENTRY(jlong, WB_G1NumMaxRegions(JNIEnv* env, jobject o))
 482   if (UseG1GC) {
 483     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 484     size_t nr = g1h->max_regions();
 485     return (jlong)nr;
 486   }
 487   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1NumMaxRegions: G1 GC is not enabled");
 488 WB_END
 489 
 490 WB_ENTRY(jlong, WB_G1NumFreeRegions(JNIEnv* env, jobject o))
 491   if (UseG1GC) {
 492     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 493     size_t nr = g1h->num_free_regions();
 494     return (jlong)nr;
 495   }
 496   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1NumFreeRegions: G1 GC is not enabled");
 497 WB_END
 498 
 499 WB_ENTRY(jboolean, WB_G1InConcurrentMark(JNIEnv* env, jobject o))
 500   if (UseG1GC) {
 501     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 502     return g1h->concurrent_mark()->cm_thread()->in_progress();
 503   }
 504   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1InConcurrentMark: G1 GC is not enabled");
 505 WB_END
 506 
 507 WB_ENTRY(jboolean, WB_G1StartMarkCycle(JNIEnv* env, jobject o))
 508   if (UseG1GC) {
 509     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 510     if (!g1h->concurrent_mark()->cm_thread()->in_progress()) {
 511       g1h->collect(GCCause::_wb_conc_mark);
 512       return true;
 513     }
 514     return false;
 515   }
 516   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1StartMarkCycle: G1 GC is not enabled");
 517 WB_END
 518 
 519 WB_ENTRY(jint, WB_G1RegionSize(JNIEnv* env, jobject o))
 520   if (UseG1GC) {
 521     return (jint)HeapRegion::GrainBytes;
 522   }
 523   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1RegionSize: G1 GC is not enabled");
 524 WB_END
 525 
 526 WB_ENTRY(jboolean, WB_G1HasRegionsToUncommit(JNIEnv* env, jobject o))
 527   if (UseG1GC) {
 528     return G1CollectedHeap::heap()->has_uncommittable_regions();
 529   }
 530   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1HasRegionsToUncommit: G1 GC is not enabled");
 531 WB_END
 532 
 533 #endif // INCLUDE_G1GC
 534 
 535 #if INCLUDE_PARALLELGC
 536 
 537 WB_ENTRY(jlong, WB_PSVirtualSpaceAlignment(JNIEnv* env, jobject o))
 538   if (UseParallelGC) {
 539     return GenAlignment;
 540   }
 541   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_PSVirtualSpaceAlignment: Parallel GC is not enabled");
 542 WB_END
 543 
 544 WB_ENTRY(jlong, WB_PSHeapGenerationAlignment(JNIEnv* env, jobject o))
 545   if (UseParallelGC) {
 546     return GenAlignment;
 547   }
 548   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_PSHeapGenerationAlignment: Parallel GC is not enabled");
 549 WB_END
 550 
 551 #endif // INCLUDE_PARALLELGC
 552 
 553 #if INCLUDE_G1GC
 554 
 555 WB_ENTRY(jobject, WB_G1AuxiliaryMemoryUsage(JNIEnv* env))
 556   if (UseG1GC) {
 557     ResourceMark rm(THREAD);
 558     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 559     MemoryUsage usage = g1h->get_auxiliary_data_memory_usage();
 560     Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
 561     return JNIHandles::make_local(THREAD, h());
 562   }
 563   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1AuxiliaryMemoryUsage: G1 GC is not enabled");
 564 WB_END
 565 
 566 WB_ENTRY(jint, WB_G1ActiveMemoryNodeCount(JNIEnv* env, jobject o))
 567   if (UseG1GC) {
 568     G1NUMA* numa = G1NUMA::numa();
 569     return (jint)numa->num_active_nodes();
 570   }
 571   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1ActiveMemoryNodeCount: G1 GC is not enabled");
 572 WB_END
 573 
 574 WB_ENTRY(jintArray, WB_G1MemoryNodeIds(JNIEnv* env, jobject o))
 575   if (UseG1GC) {
 576     G1NUMA* numa = G1NUMA::numa();
 577     int num_node_ids = (int)numa->num_active_nodes();
 578     const int* node_ids = numa->node_ids();
 579 
 580     typeArrayOop result = oopFactory::new_intArray(num_node_ids, CHECK_NULL);
 581     for (int i = 0; i < num_node_ids; i++) {
 582       result->int_at_put(i, (jint)node_ids[i]);
 583     }
 584     return (jintArray) JNIHandles::make_local(THREAD, result);
 585   }
 586   THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1MemoryNodeIds: G1 GC is not enabled");
 587 WB_END
 588 
 589 class OldRegionsLivenessClosure: public HeapRegionClosure {
 590 
 591  private:
 592   const int _liveness;
 593   size_t _total_count;
 594   size_t _total_memory;
 595   size_t _total_memory_to_free;
 596 
 597  public:
 598   OldRegionsLivenessClosure(int liveness) :
 599     _liveness(liveness),
 600     _total_count(0),
 601     _total_memory(0),
 602     _total_memory_to_free(0) { }
 603 
 604     size_t total_count() { return _total_count; }
 605     size_t total_memory() { return _total_memory; }
 606     size_t total_memory_to_free() { return _total_memory_to_free; }
 607 
 608   bool do_heap_region(HeapRegion* r) {
 609     if (r->is_old()) {
 610       size_t prev_live = r->marked_bytes();
 611       size_t live = r->live_bytes();
 612       size_t size = r->used();
 613       size_t reg_size = HeapRegion::GrainBytes;
 614       if (size > 0 && ((int)(live * 100 / size) < _liveness)) {
 615         _total_memory += size;
 616         ++_total_count;
 617         if (size == reg_size) {
 618         // we don't include non-full regions since they are unlikely included in mixed gc
 619         // for testing purposes it's enough to have lowest estimation of total memory that is expected to be freed
 620           _total_memory_to_free += size - prev_live;
 621         }
 622       }
 623     }
 624     return false;
 625   }
 626 };
 627 
 628 
 629 WB_ENTRY(jlongArray, WB_G1GetMixedGCInfo(JNIEnv* env, jobject o, jint liveness))
 630   if (!UseG1GC) {
 631     THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1GetMixedGCInfo: G1 GC is not enabled");
 632   }
 633   if (liveness < 0) {
 634     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "liveness value should be non-negative");
 635   }
 636 
 637   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 638   OldRegionsLivenessClosure rli(liveness);
 639   g1h->heap_region_iterate(&rli);
 640 
 641   typeArrayOop result = oopFactory::new_longArray(3, CHECK_NULL);
 642   result->long_at_put(0, rli.total_count());
 643   result->long_at_put(1, rli.total_memory());
 644   result->long_at_put(2, rli.total_memory_to_free());
 645   return (jlongArray) JNIHandles::make_local(THREAD, result);
 646 WB_END
 647 
 648 #endif // INCLUDE_G1GC
 649 
 650 // Alloc memory using the test memory type so that we can use that to see if
 651 // NMT picks it up correctly
 652 WB_ENTRY(jlong, WB_NMTMalloc(JNIEnv* env, jobject o, jlong size))
 653   jlong addr = 0;
 654   addr = (jlong)(uintptr_t)os::malloc(size, mtTest);
 655   return addr;
 656 WB_END
 657 
 658 // Alloc memory with pseudo call stack. The test can create psudo malloc
 659 // allocation site to stress the malloc tracking.
 660 WB_ENTRY(jlong, WB_NMTMallocWithPseudoStack(JNIEnv* env, jobject o, jlong size, jint pseudo_stack))
 661   address pc = (address)(size_t)pseudo_stack;
 662   NativeCallStack stack(&pc, 1);
 663   return (jlong)(uintptr_t)os::malloc(size, mtTest, stack);
 664 WB_END
 665 
 666 // Alloc memory with pseudo call stack and specific memory type.
 667 WB_ENTRY(jlong, WB_NMTMallocWithPseudoStackAndType(JNIEnv* env, jobject o, jlong size, jint pseudo_stack, jint type))
 668   address pc = (address)(size_t)pseudo_stack;
 669   NativeCallStack stack(&pc, 1);
 670   return (jlong)(uintptr_t)os::malloc(size, (MEMFLAGS)type, stack);
 671 WB_END
 672 
 673 // Free the memory allocated by NMTAllocTest
 674 WB_ENTRY(void, WB_NMTFree(JNIEnv* env, jobject o, jlong mem))
 675   os::free((void*)(uintptr_t)mem);
 676 WB_END
 677 
 678 WB_ENTRY(jlong, WB_NMTReserveMemory(JNIEnv* env, jobject o, jlong size))
 679   jlong addr = 0;
 680 
 681   addr = (jlong)(uintptr_t)os::reserve_memory(size);
 682   MemTracker::record_virtual_memory_type((address)addr, mtTest);
 683 
 684   return addr;
 685 WB_END
 686 
 687 WB_ENTRY(jlong, WB_NMTAttemptReserveMemoryAt(JNIEnv* env, jobject o, jlong addr, jlong size))
 688   addr = (jlong)(uintptr_t)os::attempt_reserve_memory_at((char*)(uintptr_t)addr, (size_t)size);
 689   MemTracker::record_virtual_memory_type((address)addr, mtTest);
 690 
 691   return addr;
 692 WB_END
 693 
 694 WB_ENTRY(void, WB_NMTCommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 695   os::commit_memory((char *)(uintptr_t)addr, size, !ExecMem);
 696   MemTracker::record_virtual_memory_type((address)(uintptr_t)addr, mtTest);
 697 WB_END
 698 
 699 WB_ENTRY(void, WB_NMTUncommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 700   os::uncommit_memory((char *)(uintptr_t)addr, size);
 701 WB_END
 702 
 703 WB_ENTRY(void, WB_NMTReleaseMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 704   os::release_memory((char *)(uintptr_t)addr, size);
 705 WB_END
 706 
 707 WB_ENTRY(jint, WB_NMTGetHashSize(JNIEnv* env, jobject o))
 708   int hash_size = MallocSiteTable::hash_buckets();
 709   assert(hash_size > 0, "NMT hash_size should be > 0");
 710   return (jint)hash_size;
 711 WB_END
 712 
 713 WB_ENTRY(jlong, WB_NMTNewArena(JNIEnv* env, jobject o, jlong init_size))
 714   Arena* arena =  new (mtTest) Arena(mtTest, size_t(init_size));
 715   return (jlong)arena;
 716 WB_END
 717 
 718 WB_ENTRY(void, WB_NMTFreeArena(JNIEnv* env, jobject o, jlong arena))
 719   Arena* a = (Arena*)arena;
 720   delete a;
 721 WB_END
 722 
 723 WB_ENTRY(void, WB_NMTArenaMalloc(JNIEnv* env, jobject o, jlong arena, jlong size))
 724   Arena* a = (Arena*)arena;
 725   a->Amalloc(size_t(size));
 726 WB_END
 727 
 728 static jmethodID reflected_method_to_jmid(JavaThread* thread, JNIEnv* env, jobject method) {
 729   assert(method != NULL, "method should not be null");
 730   ThreadToNativeFromVM ttn(thread);
 731   return env->FromReflectedMethod(method);
 732 }
 733 
 734 // Deoptimizes all compiled frames and makes nmethods not entrant if it's requested
 735 class VM_WhiteBoxDeoptimizeFrames : public VM_WhiteBoxOperation {
 736  private:
 737   int _result;
 738   const bool _make_not_entrant;
 739  public:
 740   VM_WhiteBoxDeoptimizeFrames(bool make_not_entrant) :
 741         _result(0), _make_not_entrant(make_not_entrant) { }
 742   int  result() const { return _result; }
 743 
 744   void doit() {
 745     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
 746       if (t->has_last_Java_frame()) {
 747         for (StackFrameStream fst(t, false /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
 748           frame* f = fst.current();
 749           if (f->can_be_deoptimized() && !f->is_deoptimized_frame()) {
 750             Deoptimization::deoptimize(t, *f);
 751             if (_make_not_entrant) {
 752                 CompiledMethod* cm = CodeCache::find_compiled(f->pc());
 753                 assert(cm != NULL, "sanity check");
 754                 cm->make_not_entrant();
 755             }
 756             ++_result;
 757           }
 758         }
 759       }
 760     }
 761   }
 762 };
 763 
 764 WB_ENTRY(jint, WB_DeoptimizeFrames(JNIEnv* env, jobject o, jboolean make_not_entrant))
 765   VM_WhiteBoxDeoptimizeFrames op(make_not_entrant == JNI_TRUE);
 766   VMThread::execute(&op);
 767   return op.result();
 768 WB_END
 769 
 770 WB_ENTRY(jboolean, WB_IsFrameDeoptimized(JNIEnv* env, jobject o, jint depth))
 771   bool result = false;
 772   if (thread->has_last_Java_frame()) {
 773     RegisterMap reg_map(thread);
 774     javaVFrame *jvf = thread->last_java_vframe(&reg_map);
 775     for (jint d = 0; d < depth && jvf != NULL; d++) {
 776       jvf = jvf->java_sender();
 777     }
 778     result = jvf != NULL && jvf->fr().is_deoptimized_frame();
 779   }
 780   return result;
 781 WB_END
 782 
 783 WB_ENTRY(void, WB_DeoptimizeAll(JNIEnv* env, jobject o))
 784   CodeCache::mark_all_nmethods_for_deoptimization();
 785   Deoptimization::deoptimize_all_marked();
 786 WB_END
 787 
 788 WB_ENTRY(jint, WB_DeoptimizeMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 789   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 790   int result = 0;
 791   CHECK_JNI_EXCEPTION_(env, result);
 792   MutexLocker mu(Compile_lock);
 793   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 794   if (is_osr) {
 795     result += mh->mark_osr_nmethods();
 796   } else if (mh->code() != NULL) {
 797     mh->code()->mark_for_deoptimization();
 798     ++result;
 799   }
 800   result += CodeCache::mark_for_deoptimization(mh());
 801   if (result > 0) {
 802     Deoptimization::deoptimize_all_marked();
 803   }
 804   return result;
 805 WB_END
 806 
 807 WB_ENTRY(jboolean, WB_IsMethodCompiled(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 808   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 809   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 810   MutexLocker mu(Compile_lock);
 811   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 812   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 813   if (code == NULL) {
 814     return JNI_FALSE;
 815   }
 816   return (code->is_alive() && !code->is_marked_for_deoptimization());
 817 WB_END
 818 
 819 static bool is_excluded_for_compiler(AbstractCompiler* comp, methodHandle& mh) {
 820   if (comp == NULL) {
 821     return true;
 822   }
 823   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, comp);
 824   if (directive->ExcludeOption) {
 825     return true;
 826   }
 827   return false;
 828 }
 829 
 830 static bool can_be_compiled_at_level(methodHandle& mh, jboolean is_osr, int level) {
 831   if (is_osr) {
 832     return CompilationPolicy::can_be_osr_compiled(mh, level);
 833   } else {
 834     return CompilationPolicy::can_be_compiled(mh, level);
 835   }
 836 }
 837 
 838 WB_ENTRY(jboolean, WB_IsMethodCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 839   if (method == NULL || comp_level > CompilationPolicy::highest_compile_level()) {
 840     return false;
 841   }
 842   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 843   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 844   MutexLocker mu(Compile_lock);
 845   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 846 
 847   // The ExcludeOption directive is evaluated lazily upon compilation attempt. If a method was not tried to be compiled by
 848   // a compiler, yet, the method object is not set to be not compilable by that compiler. Thus, evaluate the compiler directive
 849   // to exclude a compilation of 'method'.
 850   if (comp_level == CompLevel_any) {
 851     // Both compilers could have ExcludeOption set. Check all combinations.
 852     bool excluded_c1 = is_excluded_for_compiler(CompileBroker::compiler1(), mh);
 853     bool excluded_c2 = is_excluded_for_compiler(CompileBroker::compiler2(), mh);
 854     if (excluded_c1 && excluded_c2) {
 855       // Compilation of 'method' excluded by both compilers.
 856       return false;
 857     }
 858 
 859     if (excluded_c1) {
 860       // C1 only has ExcludeOption set: Check if compilable with C2.
 861       return can_be_compiled_at_level(mh, is_osr, CompLevel_full_optimization);
 862     } else if (excluded_c2) {
 863       // C2 only has ExcludeOption set: Check if compilable with C1.
 864       return can_be_compiled_at_level(mh, is_osr, CompLevel_simple);
 865     }
 866   } else if (comp_level > CompLevel_none && is_excluded_for_compiler(CompileBroker::compiler((int)comp_level), mh)) {
 867     // Compilation of 'method' excluded by compiler used for 'comp_level'.
 868     return false;
 869   }
 870 
 871   return can_be_compiled_at_level(mh, is_osr, (int)comp_level);
 872 WB_END
 873 
 874 WB_ENTRY(jboolean, WB_IsMethodQueuedForCompilation(JNIEnv* env, jobject o, jobject method))
 875   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 876   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 877   MutexLocker mu(Compile_lock);
 878   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 879   return mh->queued_for_compilation();
 880 WB_END
 881 
 882 WB_ENTRY(jboolean, WB_IsIntrinsicAvailable(JNIEnv* env, jobject o, jobject method, jobject compilation_context, jint compLevel))
 883   if (compLevel < CompLevel_none || compLevel > CompilationPolicy::highest_compile_level()) {
 884     return false; // Intrinsic is not available on a non-existent compilation level.
 885   }
 886   jmethodID method_id, compilation_context_id;
 887   method_id = reflected_method_to_jmid(thread, env, method);
 888   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 889   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(method_id));
 890 
 891   DirectiveSet* directive;
 892   AbstractCompiler* comp = CompileBroker::compiler((int)compLevel);
 893   assert(comp != NULL, "compiler not available");
 894   if (compilation_context != NULL) {
 895     compilation_context_id = reflected_method_to_jmid(thread, env, compilation_context);
 896     CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 897     methodHandle cch(THREAD, Method::checked_resolve_jmethod_id(compilation_context_id));
 898     directive = DirectivesStack::getMatchingDirective(cch, comp);
 899   } else {
 900     // Calling with NULL matches default directive
 901     directive = DirectivesStack::getDefaultDirective(comp);
 902   }
 903   bool result = comp->is_intrinsic_available(mh, directive);
 904   DirectivesStack::release(directive);
 905   return result;
 906 WB_END
 907 
 908 WB_ENTRY(jint, WB_GetMethodCompilationLevel(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 909   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 910   CHECK_JNI_EXCEPTION_(env, CompLevel_none);
 911   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 912   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 913   return (code != NULL ? code->comp_level() : CompLevel_none);
 914 WB_END
 915 
 916 WB_ENTRY(void, WB_MakeMethodNotCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 917   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 918   CHECK_JNI_EXCEPTION(env);
 919   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 920   if (is_osr) {
 921     mh->set_not_osr_compilable("WhiteBox", comp_level);
 922   } else {
 923     mh->set_not_compilable("WhiteBox", comp_level);
 924   }
 925 WB_END
 926 
 927 WB_ENTRY(jint, WB_GetMethodDecompileCount(JNIEnv* env, jobject o, jobject method))
 928   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 929   CHECK_JNI_EXCEPTION_(env, 0);
 930   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 931   uint cnt = 0;
 932   MethodData* mdo = mh->method_data();
 933   if (mdo != NULL) {
 934     cnt = mdo->decompile_count();
 935   }
 936   return cnt;
 937 WB_END
 938 
 939 // Get the trap count of a method for a specific reason. If the trap count for
 940 // that reason did overflow, this includes the overflow trap count of the method.
 941 // If 'reason' is NULL, the sum of the traps for all reasons will be returned.
 942 // This number includes the overflow trap count if the trap count for any reason
 943 // did overflow.
 944 WB_ENTRY(jint, WB_GetMethodTrapCount(JNIEnv* env, jobject o, jobject method, jstring reason_obj))
 945   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 946   CHECK_JNI_EXCEPTION_(env, 0);
 947   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 948   uint cnt = 0;
 949   MethodData* mdo = mh->method_data();
 950   if (mdo != NULL) {
 951     ResourceMark rm(THREAD);
 952     char* reason_str = (reason_obj == NULL) ?
 953       NULL : java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(reason_obj));
 954     bool overflow = false;
 955     for (uint reason = 0; reason < mdo->trap_reason_limit(); reason++) {
 956       if (reason_str != NULL && !strcmp(reason_str, Deoptimization::trap_reason_name(reason))) {
 957         cnt = mdo->trap_count(reason);
 958         // Count in the overflow trap count on overflow
 959         if (cnt == (uint)-1) {
 960           cnt = mdo->trap_count_limit() + mdo->overflow_trap_count();
 961         }
 962         break;
 963       } else if (reason_str == NULL) {
 964         uint c = mdo->trap_count(reason);
 965         if (c == (uint)-1) {
 966           c = mdo->trap_count_limit();
 967           if (!overflow) {
 968             // Count overflow trap count just once
 969             overflow = true;
 970             c += mdo->overflow_trap_count();
 971           }
 972         }
 973         cnt += c;
 974       }
 975     }
 976   }
 977   return cnt;
 978 WB_END
 979 
 980 WB_ENTRY(jint, WB_GetDeoptCount(JNIEnv* env, jobject o, jstring reason_obj, jstring action_obj))
 981   if (reason_obj == NULL && action_obj == NULL) {
 982     return Deoptimization::total_deoptimization_count();
 983   }
 984   ResourceMark rm(THREAD);
 985   const char *reason_str = (reason_obj == NULL) ?
 986     NULL : java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(reason_obj));
 987   const char *action_str = (action_obj == NULL) ?
 988     NULL : java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(action_obj));
 989 
 990   return Deoptimization::deoptimization_count(reason_str, action_str);
 991 WB_END
 992 
 993 WB_ENTRY(jint, WB_GetMethodEntryBci(JNIEnv* env, jobject o, jobject method))
 994   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 995   CHECK_JNI_EXCEPTION_(env, InvocationEntryBci);
 996   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 997   CompiledMethod* code = mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false);
 998   return (code != NULL && code->is_osr_method() ? code->osr_entry_bci() : InvocationEntryBci);
 999 WB_END
1000 
1001 WB_ENTRY(jboolean, WB_TestSetDontInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
1002   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1003   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1004   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1005   bool result = mh->dont_inline();
1006   mh->set_dont_inline(value == JNI_TRUE);
1007   return result;
1008 WB_END
1009 
1010 WB_ENTRY(jint, WB_GetCompileQueueSize(JNIEnv* env, jobject o, jint comp_level))
1011   if (comp_level == CompLevel_any) {
1012     return CompileBroker::queue_size(CompLevel_full_optimization) /* C2 */ +
1013         CompileBroker::queue_size(CompLevel_full_profile) /* C1 */;
1014   } else {
1015     return CompileBroker::queue_size(comp_level);
1016   }
1017 WB_END
1018 
1019 WB_ENTRY(jboolean, WB_TestSetForceInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
1020   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1021   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1022   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1023   bool result = mh->force_inline();
1024   mh->set_force_inline(value == JNI_TRUE);
1025   return result;
1026 WB_END
1027 
1028 #ifdef LINUX
1029 bool WhiteBox::validate_cgroup(const char* proc_cgroups,
1030                                const char* proc_self_cgroup,
1031                                const char* proc_self_mountinfo,
1032                                u1* cg_flags) {
1033   CgroupInfo cg_infos[CG_INFO_LENGTH];
1034   return CgroupSubsystemFactory::determine_type(cg_infos, proc_cgroups,
1035                                                     proc_self_cgroup,
1036                                                     proc_self_mountinfo, cg_flags);
1037 }
1038 #endif
1039 
1040 bool WhiteBox::compile_method(Method* method, int comp_level, int bci, JavaThread* THREAD) {
1041   // Screen for unavailable/bad comp level or null method
1042   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1043   if (method == NULL) {
1044     tty->print_cr("WB error: request to compile NULL method");
1045     return false;
1046   }
1047   if (comp_level > CompilationPolicy::highest_compile_level()) {
1048     tty->print_cr("WB error: invalid compilation level %d", comp_level);
1049     return false;
1050   }
1051   if (comp == NULL) {
1052     tty->print_cr("WB error: no compiler for requested compilation level %d", comp_level);
1053     return false;
1054   }
1055 
1056   // Check if compilation is blocking
1057   methodHandle mh(THREAD, method);
1058   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, comp);
1059   bool is_blocking = !directive->BackgroundCompilationOption;
1060   DirectivesStack::release(directive);
1061 
1062   // Compile method and check result
1063   nmethod* nm = CompileBroker::compile_method(mh, bci, comp_level, mh, mh->invocation_count(), CompileTask::Reason_Whitebox, CHECK_false);
1064   MutexLocker mu(THREAD, Compile_lock);
1065   bool is_queued = mh->queued_for_compilation();
1066   if ((!is_blocking && is_queued) || nm != NULL) {
1067     return true;
1068   }
1069   // Check code again because compilation may be finished before Compile_lock is acquired.
1070   if (bci == InvocationEntryBci) {
1071     CompiledMethod* code = mh->code();
1072     if (code != NULL && code->as_nmethod_or_null() != NULL) {
1073       return true;
1074     }
1075   } else if (mh->lookup_osr_nmethod_for(bci, comp_level, false) != NULL) {
1076     return true;
1077   }
1078   tty->print("WB error: failed to %s compile at level %d method ", is_blocking ? "blocking" : "", comp_level);
1079   mh->print_short_name(tty);
1080   tty->cr();
1081   if (is_blocking && is_queued) {
1082     tty->print_cr("WB error: blocking compilation is still in queue!");
1083   }
1084   return false;
1085 }
1086 
1087 WB_ENTRY(jboolean, WB_EnqueueMethodForCompilation(JNIEnv* env, jobject o, jobject method, jint comp_level, jint bci))
1088   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1089   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1090   return WhiteBox::compile_method(Method::checked_resolve_jmethod_id(jmid), comp_level, bci, THREAD);
1091 WB_END
1092 
1093 WB_ENTRY(jboolean, WB_EnqueueInitializerForCompilation(JNIEnv* env, jobject o, jclass klass, jint comp_level))
1094   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1095   Method* clinit = ik->class_initializer();
1096   if (clinit == NULL || clinit->method_holder()->is_not_initialized()) {
1097     return false;
1098   }
1099   return WhiteBox::compile_method(clinit, comp_level, InvocationEntryBci, THREAD);
1100 WB_END
1101 
1102 WB_ENTRY(jboolean, WB_ShouldPrintAssembly(JNIEnv* env, jobject o, jobject method, jint comp_level))
1103   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1104   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1105 
1106   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1107   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, CompileBroker::compiler(comp_level));
1108   bool result = directive->PrintAssemblyOption;
1109   DirectivesStack::release(directive);
1110 
1111   return result;
1112 WB_END
1113 
1114 WB_ENTRY(jint, WB_MatchesInline(JNIEnv* env, jobject o, jobject method, jstring pattern))
1115   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1116   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1117 
1118   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1119 
1120   ResourceMark rm(THREAD);
1121   const char* error_msg = NULL;
1122   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
1123   InlineMatcher* m = InlineMatcher::parse_inline_pattern(method_str, error_msg);
1124 
1125   if (m == NULL) {
1126     assert(error_msg != NULL, "Always have an error message");
1127     tty->print_cr("Got error: %s", error_msg);
1128     return -1; // Pattern failed
1129   }
1130 
1131   // Pattern works - now check if it matches
1132   int result;
1133   if (m->match(mh, InlineMatcher::force_inline)) {
1134     result = 2; // Force inline match
1135   } else if (m->match(mh, InlineMatcher::dont_inline)) {
1136     result = 1; // Dont inline match
1137   } else {
1138     result = 0; // No match
1139   }
1140   delete m;
1141   return result;
1142 WB_END
1143 
1144 WB_ENTRY(jint, WB_MatchesMethod(JNIEnv* env, jobject o, jobject method, jstring pattern))
1145   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1146   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
1147 
1148   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1149 
1150   ResourceMark rm;
1151   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
1152 
1153   const char* error_msg = NULL;
1154 
1155   BasicMatcher* m = BasicMatcher::parse_method_pattern(method_str, error_msg, false);
1156   if (m == NULL) {
1157     assert(error_msg != NULL, "Must have error_msg");
1158     tty->print_cr("Got error: %s", error_msg);
1159     return -1;
1160   }
1161 
1162   // Pattern works - now check if it matches
1163   int result = m->matches(mh);
1164   delete m;
1165   assert(result == 0 || result == 1, "Result out of range");
1166   return result;
1167 WB_END
1168 
1169 WB_ENTRY(void, WB_MarkMethodProfiled(JNIEnv* env, jobject o, jobject method))
1170   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1171   CHECK_JNI_EXCEPTION(env);
1172   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1173 
1174   MethodData* mdo = mh->method_data();
1175   if (mdo == NULL) {
1176     Method::build_interpreter_method_data(mh, CHECK_AND_CLEAR);
1177     mdo = mh->method_data();
1178   }
1179   mdo->init();
1180   InvocationCounter* icnt = mdo->invocation_counter();
1181   InvocationCounter* bcnt = mdo->backedge_counter();
1182   // set i-counter according to CompilationPolicy::is_method_profiled
1183   icnt->set(Tier4MinInvocationThreshold);
1184   bcnt->set(Tier4CompileThreshold);
1185 WB_END
1186 
1187 WB_ENTRY(void, WB_ClearMethodState(JNIEnv* env, jobject o, jobject method))
1188   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1189   CHECK_JNI_EXCEPTION(env);
1190   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1191   MutexLocker mu(THREAD, Compile_lock);
1192   MethodData* mdo = mh->method_data();
1193   MethodCounters* mcs = mh->method_counters();
1194 
1195   if (mdo != NULL) {
1196     mdo->init();
1197     ResourceMark rm(THREAD);
1198     int arg_count = mdo->method()->size_of_parameters();
1199     for (int i = 0; i < arg_count; i++) {
1200       mdo->set_arg_modified(i, 0);
1201     }
1202     MutexLocker mu(THREAD, mdo->extra_data_lock());
1203     mdo->clean_method_data(/*always_clean*/true);
1204   }
1205 
1206   mh->clear_not_c1_compilable();
1207   mh->clear_not_c2_compilable();
1208   mh->clear_not_c2_osr_compilable();
1209   NOT_PRODUCT(mh->set_compiled_invocation_count(0));
1210   if (mcs != NULL) {
1211     mcs->clear_counters();
1212   }
1213 WB_END
1214 
1215 template <typename T, int type_enum>
1216 static bool GetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value) {
1217   if (name == NULL) {
1218     return false;
1219   }
1220   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1221   const char* flag_name = env->GetStringUTFChars(name, NULL);
1222   CHECK_JNI_EXCEPTION_(env, false);
1223   const JVMFlag* flag = JVMFlag::find_declared_flag(flag_name);
1224   JVMFlag::Error result = JVMFlagAccess::get<T, type_enum>(flag, value);
1225   env->ReleaseStringUTFChars(name, flag_name);
1226   return (result == JVMFlag::SUCCESS);
1227 }
1228 
1229 template <typename T, int type_enum>
1230 static bool SetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value) {
1231   if (name == NULL) {
1232     return false;
1233   }
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, false);
1237   JVMFlag* flag = JVMFlag::find_flag(flag_name);
1238   JVMFlag::Error result = JVMFlagAccess::set<T, type_enum>(flag, value, JVMFlagOrigin::INTERNAL);
1239   env->ReleaseStringUTFChars(name, flag_name);
1240   return (result == JVMFlag::SUCCESS);
1241 }
1242 
1243 template <typename T>
1244 static jobject box(JavaThread* thread, JNIEnv* env, Symbol* name, Symbol* sig, T value) {
1245   ResourceMark rm(thread);
1246   jclass clazz = env->FindClass(name->as_C_string());
1247   CHECK_JNI_EXCEPTION_(env, NULL);
1248   jmethodID methodID = env->GetStaticMethodID(clazz,
1249         vmSymbols::valueOf_name()->as_C_string(),
1250         sig->as_C_string());
1251   CHECK_JNI_EXCEPTION_(env, NULL);
1252   jobject result = env->CallStaticObjectMethod(clazz, methodID, value);
1253   CHECK_JNI_EXCEPTION_(env, NULL);
1254   return result;
1255 }
1256 
1257 static jobject booleanBox(JavaThread* thread, JNIEnv* env, jboolean value) {
1258   return box(thread, env, vmSymbols::java_lang_Boolean(), vmSymbols::Boolean_valueOf_signature(), value);
1259 }
1260 static jobject integerBox(JavaThread* thread, JNIEnv* env, jint value) {
1261   return box(thread, env, vmSymbols::java_lang_Integer(), vmSymbols::Integer_valueOf_signature(), value);
1262 }
1263 static jobject longBox(JavaThread* thread, JNIEnv* env, jlong value) {
1264   return box(thread, env, vmSymbols::java_lang_Long(), vmSymbols::Long_valueOf_signature(), value);
1265 }
1266 /* static jobject floatBox(JavaThread* thread, JNIEnv* env, jfloat value) {
1267   return box(thread, env, vmSymbols::java_lang_Float(), vmSymbols::Float_valueOf_signature(), value);
1268 }*/
1269 static jobject doubleBox(JavaThread* thread, JNIEnv* env, jdouble value) {
1270   return box(thread, env, vmSymbols::java_lang_Double(), vmSymbols::Double_valueOf_signature(), value);
1271 }
1272 
1273 static const JVMFlag* getVMFlag(JavaThread* thread, JNIEnv* env, jstring name) {
1274   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1275   const char* flag_name = env->GetStringUTFChars(name, NULL);
1276   CHECK_JNI_EXCEPTION_(env, NULL);
1277   const JVMFlag* result = JVMFlag::find_declared_flag(flag_name);
1278   env->ReleaseStringUTFChars(name, flag_name);
1279   return result;
1280 }
1281 
1282 WB_ENTRY(jboolean, WB_IsConstantVMFlag(JNIEnv* env, jobject o, jstring name))
1283   const JVMFlag* flag = getVMFlag(thread, env, name);
1284   return (flag != NULL) && flag->is_constant_in_binary();
1285 WB_END
1286 
1287 WB_ENTRY(jboolean, WB_IsLockedVMFlag(JNIEnv* env, jobject o, jstring name))
1288   const JVMFlag* flag = getVMFlag(thread, env, name);
1289   return (flag != NULL) && !(flag->is_unlocked() || flag->is_unlocker());
1290 WB_END
1291 
1292 WB_ENTRY(jobject, WB_GetBooleanVMFlag(JNIEnv* env, jobject o, jstring name))
1293   bool result;
1294   if (GetVMFlag <JVM_FLAG_TYPE(bool)> (thread, env, name, &result)) {
1295     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1296     return booleanBox(thread, env, result);
1297   }
1298   return NULL;
1299 WB_END
1300 
1301 template <typename T, int type_enum>
1302 jobject GetVMFlag_longBox(JNIEnv* env, JavaThread* thread, jstring name) {
1303   T result;
1304   if (GetVMFlag <T, type_enum> (thread, env, name, &result)) {
1305     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1306     return longBox(thread, env, result);
1307   }
1308   return NULL;
1309 }
1310 
1311 WB_ENTRY(jobject, WB_GetIntVMFlag(JNIEnv* env, jobject o, jstring name))
1312   return GetVMFlag_longBox<JVM_FLAG_TYPE(int)>(env, thread, name);
1313 WB_END
1314 
1315 WB_ENTRY(jobject, WB_GetUintVMFlag(JNIEnv* env, jobject o, jstring name))
1316   return GetVMFlag_longBox<JVM_FLAG_TYPE(uint)>(env, thread, name);
1317 WB_END
1318 
1319 WB_ENTRY(jobject, WB_GetIntxVMFlag(JNIEnv* env, jobject o, jstring name))
1320   return GetVMFlag_longBox<JVM_FLAG_TYPE(intx)>(env, thread, name);
1321 WB_END
1322 
1323 WB_ENTRY(jobject, WB_GetUintxVMFlag(JNIEnv* env, jobject o, jstring name))
1324   return GetVMFlag_longBox<JVM_FLAG_TYPE(uintx)>(env, thread, name);
1325 WB_END
1326 
1327 WB_ENTRY(jobject, WB_GetUint64VMFlag(JNIEnv* env, jobject o, jstring name))
1328   return GetVMFlag_longBox<JVM_FLAG_TYPE(uint64_t)>(env, thread, name);
1329 WB_END
1330 
1331 WB_ENTRY(jobject, WB_GetSizeTVMFlag(JNIEnv* env, jobject o, jstring name))
1332   return GetVMFlag_longBox<JVM_FLAG_TYPE(size_t)>(env, thread, name);
1333 WB_END
1334 
1335 WB_ENTRY(jobject, WB_GetDoubleVMFlag(JNIEnv* env, jobject o, jstring name))
1336   double result;
1337   if (GetVMFlag <JVM_FLAG_TYPE(double)> (thread, env, name, &result)) {
1338     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1339     return doubleBox(thread, env, result);
1340   }
1341   return NULL;
1342 WB_END
1343 
1344 WB_ENTRY(jstring, WB_GetStringVMFlag(JNIEnv* env, jobject o, jstring name))
1345   ccstr ccstrResult;
1346   if (GetVMFlag <JVM_FLAG_TYPE(ccstr)> (thread, env, name, &ccstrResult)) {
1347     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1348     jstring result = env->NewStringUTF(ccstrResult);
1349     CHECK_JNI_EXCEPTION_(env, NULL);
1350     return result;
1351   }
1352   return NULL;
1353 WB_END
1354 
1355 WB_ENTRY(void, WB_SetBooleanVMFlag(JNIEnv* env, jobject o, jstring name, jboolean value))
1356   bool result = value == JNI_TRUE ? true : false;
1357   SetVMFlag <JVM_FLAG_TYPE(bool)> (thread, env, name, &result);
1358 WB_END
1359 
1360 WB_ENTRY(void, WB_SetIntVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1361   int result = value;
1362   SetVMFlag <JVM_FLAG_TYPE(int)> (thread, env, name, &result);
1363 WB_END
1364 
1365 WB_ENTRY(void, WB_SetUintVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1366   uint result = value;
1367   SetVMFlag <JVM_FLAG_TYPE(uint)> (thread, env, name, &result);
1368 WB_END
1369 
1370 WB_ENTRY(void, WB_SetIntxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1371   intx result = value;
1372   SetVMFlag <JVM_FLAG_TYPE(intx)> (thread, env, name, &result);
1373 WB_END
1374 
1375 WB_ENTRY(void, WB_SetUintxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1376   uintx result = value;
1377   SetVMFlag <JVM_FLAG_TYPE(uintx)> (thread, env, name, &result);
1378 WB_END
1379 
1380 WB_ENTRY(void, WB_SetUint64VMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1381   uint64_t result = value;
1382   SetVMFlag <JVM_FLAG_TYPE(uint64_t)> (thread, env, name, &result);
1383 WB_END
1384 
1385 WB_ENTRY(void, WB_SetSizeTVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1386   size_t result = value;
1387   SetVMFlag <JVM_FLAG_TYPE(size_t)> (thread, env, name, &result);
1388 WB_END
1389 
1390 WB_ENTRY(void, WB_SetDoubleVMFlag(JNIEnv* env, jobject o, jstring name, jdouble value))
1391   double result = value;
1392   SetVMFlag <JVM_FLAG_TYPE(double)> (thread, env, name, &result);
1393 WB_END
1394 
1395 WB_ENTRY(void, WB_SetStringVMFlag(JNIEnv* env, jobject o, jstring name, jstring value))
1396   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1397   const char* ccstrValue;
1398   if (value == NULL) {
1399     ccstrValue = NULL;
1400   }
1401   else {
1402     ccstrValue = env->GetStringUTFChars(value, NULL);
1403     CHECK_JNI_EXCEPTION(env);
1404   }
1405   {
1406     ccstr param = ccstrValue;
1407     ThreadInVMfromNative ttvfn(thread); // back to VM
1408     if (SetVMFlag <JVM_FLAG_TYPE(ccstr)> (thread, env, name, &param)) {
1409       assert(param == NULL, "old value is freed automatically and not returned");
1410     }
1411   }
1412   if (value != NULL) {
1413     env->ReleaseStringUTFChars(value, ccstrValue);
1414   }
1415 WB_END
1416 
1417 WB_ENTRY(void, WB_LockCompilation(JNIEnv* env, jobject o, jlong timeout))
1418   WhiteBox::compilation_locked = true;
1419 WB_END
1420 
1421 WB_ENTRY(void, WB_UnlockCompilation(JNIEnv* env, jobject o))
1422   MonitorLocker mo(Compilation_lock, Mutex::_no_safepoint_check_flag);
1423   WhiteBox::compilation_locked = false;
1424   mo.notify_all();
1425 WB_END
1426 
1427 WB_ENTRY(void, WB_ForceNMethodSweep(JNIEnv* env, jobject o))
1428   // Force a code cache sweep and block until it finished
1429   NMethodSweeper::force_sweep();
1430 WB_END
1431 
1432 WB_ENTRY(jboolean, WB_IsInStringTable(JNIEnv* env, jobject o, jstring javaString))
1433   ResourceMark rm(THREAD);
1434   int len;
1435   jchar* name = java_lang_String::as_unicode_string(JNIHandles::resolve(javaString), len, CHECK_false);
1436   return (StringTable::lookup(name, len) != NULL);
1437 WB_END
1438 
1439 WB_ENTRY(void, WB_FullGC(JNIEnv* env, jobject o))
1440   Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(true);
1441   Universe::heap()->collect(GCCause::_wb_full_gc);
1442 #if INCLUDE_G1GC
1443   if (UseG1GC) {
1444     // Needs to be cleared explicitly for G1
1445     Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(false);
1446   }
1447 #endif // INCLUDE_G1GC
1448 WB_END
1449 
1450 WB_ENTRY(void, WB_YoungGC(JNIEnv* env, jobject o))
1451   Universe::heap()->collect(GCCause::_wb_young_gc);
1452 WB_END
1453 
1454 WB_ENTRY(void, WB_ReadReservedMemory(JNIEnv* env, jobject o))
1455   // static+volatile in order to force the read to happen
1456   // (not be eliminated by the compiler)
1457   static char c;
1458   static volatile char* p;
1459 
1460   p = os::reserve_memory(os::vm_allocation_granularity());
1461   if (p == NULL) {
1462     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "Failed to reserve memory");
1463   }
1464 
1465   c = *p;
1466 WB_END
1467 
1468 WB_ENTRY(jstring, WB_GetCPUFeatures(JNIEnv* env, jobject o))
1469   const char* features = VM_Version::features_string();
1470   ThreadToNativeFromVM ttn(thread);
1471   jstring features_string = env->NewStringUTF(features);
1472 
1473   CHECK_JNI_EXCEPTION_(env, NULL);
1474 
1475   return features_string;
1476 WB_END
1477 
1478 int WhiteBox::get_blob_type(const CodeBlob* code) {
1479   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1480   return CodeCache::get_code_heap(code)->code_blob_type();
1481 }
1482 
1483 CodeHeap* WhiteBox::get_code_heap(int blob_type) {
1484   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1485   return CodeCache::get_code_heap(blob_type);
1486 }
1487 
1488 struct CodeBlobStub {
1489   CodeBlobStub(const CodeBlob* blob) :
1490       name(os::strdup(blob->name())),
1491       size(blob->size()),
1492       blob_type(WhiteBox::get_blob_type(blob)),
1493       address((jlong) blob) { }
1494   ~CodeBlobStub() { os::free((void*) name); }
1495   const char* const name;
1496   const jint        size;
1497   const jint        blob_type;
1498   const jlong       address;
1499 };
1500 
1501 static jobjectArray codeBlob2objectArray(JavaThread* thread, JNIEnv* env, CodeBlobStub* cb) {
1502   ResourceMark rm;
1503   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1504   CHECK_JNI_EXCEPTION_(env, NULL);
1505   jobjectArray result = env->NewObjectArray(4, clazz, NULL);
1506 
1507   jstring name = env->NewStringUTF(cb->name);
1508   CHECK_JNI_EXCEPTION_(env, NULL);
1509   env->SetObjectArrayElement(result, 0, name);
1510 
1511   jobject obj = integerBox(thread, env, cb->size);
1512   CHECK_JNI_EXCEPTION_(env, NULL);
1513   env->SetObjectArrayElement(result, 1, obj);
1514 
1515   obj = integerBox(thread, env, cb->blob_type);
1516   CHECK_JNI_EXCEPTION_(env, NULL);
1517   env->SetObjectArrayElement(result, 2, obj);
1518 
1519   obj = longBox(thread, env, cb->address);
1520   CHECK_JNI_EXCEPTION_(env, NULL);
1521   env->SetObjectArrayElement(result, 3, obj);
1522 
1523   return result;
1524 }
1525 
1526 WB_ENTRY(jobjectArray, WB_GetNMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
1527   ResourceMark rm(THREAD);
1528   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1529   CHECK_JNI_EXCEPTION_(env, NULL);
1530   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1531   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
1532   jobjectArray result = NULL;
1533   if (code == NULL) {
1534     return result;
1535   }
1536   int comp_level = code->comp_level();
1537   int insts_size = code->insts_size();
1538 
1539   ThreadToNativeFromVM ttn(thread);
1540   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1541   CHECK_JNI_EXCEPTION_(env, NULL);
1542   result = env->NewObjectArray(5, clazz, NULL);
1543   if (result == NULL) {
1544     return result;
1545   }
1546 
1547   CodeBlobStub stub(code);
1548   jobjectArray codeBlob = codeBlob2objectArray(thread, env, &stub);
1549   CHECK_JNI_EXCEPTION_(env, NULL);
1550   env->SetObjectArrayElement(result, 0, codeBlob);
1551 
1552   jobject level = integerBox(thread, env, comp_level);
1553   CHECK_JNI_EXCEPTION_(env, NULL);
1554   env->SetObjectArrayElement(result, 1, level);
1555 
1556   jbyteArray insts = env->NewByteArray(insts_size);
1557   CHECK_JNI_EXCEPTION_(env, NULL);
1558   env->SetByteArrayRegion(insts, 0, insts_size, (jbyte*) code->insts_begin());
1559   env->SetObjectArrayElement(result, 2, insts);
1560 
1561   jobject id = integerBox(thread, env, code->compile_id());
1562   CHECK_JNI_EXCEPTION_(env, NULL);
1563   env->SetObjectArrayElement(result, 3, id);
1564 
1565   jobject entry_point = longBox(thread, env, (jlong) code->entry_point());
1566   CHECK_JNI_EXCEPTION_(env, NULL);
1567   env->SetObjectArrayElement(result, 4, entry_point);
1568 
1569   return result;
1570 WB_END
1571 
1572 CodeBlob* WhiteBox::allocate_code_blob(int size, int blob_type) {
1573   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1574   BufferBlob* blob;
1575   int full_size = CodeBlob::align_code_offset(sizeof(BufferBlob));
1576   if (full_size < size) {
1577     full_size += align_up(size - full_size, oopSize);
1578   }
1579   {
1580     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1581     blob = (BufferBlob*) CodeCache::allocate(full_size, blob_type);
1582     if (blob != NULL) {
1583       ::new (blob) BufferBlob("WB::DummyBlob", full_size);
1584     }
1585   }
1586   // Track memory usage statistic after releasing CodeCache_lock
1587   MemoryService::track_code_cache_memory_usage();
1588   return blob;
1589 }
1590 
1591 WB_ENTRY(jlong, WB_AllocateCodeBlob(JNIEnv* env, jobject o, jint size, jint blob_type))
1592   if (size < 0) {
1593     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1594       err_msg("WB_AllocateCodeBlob: size is negative: " INT32_FORMAT, size));
1595   }
1596   return (jlong) WhiteBox::allocate_code_blob(size, blob_type);
1597 WB_END
1598 
1599 WB_ENTRY(void, WB_FreeCodeBlob(JNIEnv* env, jobject o, jlong addr))
1600   if (addr == 0) {
1601     return;
1602   }
1603   BufferBlob::free((BufferBlob*) addr);
1604 WB_END
1605 
1606 WB_ENTRY(jobjectArray, WB_GetCodeHeapEntries(JNIEnv* env, jobject o, jint blob_type))
1607   ResourceMark rm;
1608   GrowableArray<CodeBlobStub*> blobs;
1609   {
1610     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1611     CodeHeap* heap = WhiteBox::get_code_heap(blob_type);
1612     if (heap == NULL) {
1613       return NULL;
1614     }
1615     for (CodeBlob* cb = (CodeBlob*) heap->first();
1616          cb != NULL; cb = (CodeBlob*) heap->next(cb)) {
1617       CodeBlobStub* stub = NEW_RESOURCE_OBJ(CodeBlobStub);
1618       new (stub) CodeBlobStub(cb);
1619       blobs.append(stub);
1620     }
1621   }
1622   ThreadToNativeFromVM ttn(thread);
1623   jobjectArray result = NULL;
1624   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1625   CHECK_JNI_EXCEPTION_(env, NULL);
1626   result = env->NewObjectArray(blobs.length(), clazz, NULL);
1627   CHECK_JNI_EXCEPTION_(env, NULL);
1628   if (result == NULL) {
1629     return result;
1630   }
1631   int i = 0;
1632   for (GrowableArrayIterator<CodeBlobStub*> it = blobs.begin();
1633        it != blobs.end(); ++it) {
1634     jobjectArray obj = codeBlob2objectArray(thread, env, *it);
1635     CHECK_JNI_EXCEPTION_(env, NULL);
1636     env->SetObjectArrayElement(result, i, obj);
1637     CHECK_JNI_EXCEPTION_(env, NULL);
1638     ++i;
1639   }
1640   return result;
1641 WB_END
1642 
1643 WB_ENTRY(jint, WB_GetCompilationActivityMode(JNIEnv* env, jobject o))
1644   return CompileBroker::get_compilation_activity_mode();
1645 WB_END
1646 
1647 WB_ENTRY(jobjectArray, WB_GetCodeBlob(JNIEnv* env, jobject o, jlong addr))
1648   if (addr == 0) {
1649     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
1650       "WB_GetCodeBlob: addr is null");
1651   }
1652   ThreadToNativeFromVM ttn(thread);
1653   CodeBlobStub stub((CodeBlob*) addr);
1654   return codeBlob2objectArray(thread, env, &stub);
1655 WB_END
1656 
1657 WB_ENTRY(jlong, WB_GetMethodData(JNIEnv* env, jobject wv, jobject method))
1658   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1659   CHECK_JNI_EXCEPTION_(env, 0);
1660   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1661   return (jlong) mh->method_data();
1662 WB_END
1663 
1664 WB_ENTRY(jlong, WB_GetThreadStackSize(JNIEnv* env, jobject o))
1665   return (jlong) thread->stack_size();
1666 WB_END
1667 
1668 WB_ENTRY(jlong, WB_GetThreadRemainingStackSize(JNIEnv* env, jobject o))
1669   return (jlong) thread->stack_overflow_state()->stack_available(
1670                    os::current_stack_pointer()) - (jlong)StackOverflow::stack_shadow_zone_size();
1671 WB_END
1672 
1673 
1674 int WhiteBox::array_bytes_to_length(size_t bytes) {
1675   return Array<u1>::bytes_to_length(bytes);
1676 }
1677 
1678 ///////////////
1679 // MetaspaceTestContext and MetaspaceTestArena
1680 WB_ENTRY(jlong, WB_CreateMetaspaceTestContext(JNIEnv* env, jobject wb, jlong commit_limit, jlong reserve_limit))
1681   metaspace::MetaspaceTestContext* context =
1682       new metaspace::MetaspaceTestContext("whitebox-metaspace-context", (size_t) commit_limit, (size_t) reserve_limit);
1683   return (jlong)p2i(context);
1684 WB_END
1685 
1686 WB_ENTRY(void, WB_DestroyMetaspaceTestContext(JNIEnv* env, jobject wb, jlong context))
1687   delete (metaspace::MetaspaceTestContext*) context;
1688 WB_END
1689 
1690 WB_ENTRY(void, WB_PurgeMetaspaceTestContext(JNIEnv* env, jobject wb, jlong context))
1691   metaspace::MetaspaceTestContext* context0 = (metaspace::MetaspaceTestContext*) context;
1692   context0->purge_area();
1693 WB_END
1694 
1695 WB_ENTRY(void, WB_PrintMetaspaceTestContext(JNIEnv* env, jobject wb, jlong context))
1696   metaspace::MetaspaceTestContext* context0 = (metaspace::MetaspaceTestContext*) context;
1697   context0->print_on(tty);
1698 WB_END
1699 
1700 WB_ENTRY(jlong, WB_GetTotalCommittedWordsInMetaspaceTestContext(JNIEnv* env, jobject wb, jlong context))
1701   metaspace::MetaspaceTestContext* context0 = (metaspace::MetaspaceTestContext*) context;
1702   return context0->committed_words();
1703 WB_END
1704 
1705 WB_ENTRY(jlong, WB_GetTotalUsedWordsInMetaspaceTestContext(JNIEnv* env, jobject wb, jlong context))
1706   metaspace::MetaspaceTestContext* context0 = (metaspace::MetaspaceTestContext*) context;
1707   return context0->used_words();
1708 WB_END
1709 
1710 WB_ENTRY(jlong, WB_CreateArenaInTestContext(JNIEnv* env, jobject wb, jlong context, jboolean is_micro))
1711   const Metaspace::MetaspaceType type = is_micro ? Metaspace::ReflectionMetaspaceType : Metaspace::StandardMetaspaceType;
1712   metaspace::MetaspaceTestContext* context0 = (metaspace::MetaspaceTestContext*) context;
1713   return (jlong)p2i(context0->create_arena(type));
1714 WB_END
1715 
1716 WB_ENTRY(void, WB_DestroyMetaspaceTestArena(JNIEnv* env, jobject wb, jlong arena))
1717   delete (metaspace::MetaspaceTestArena*) arena;
1718 WB_END
1719 
1720 WB_ENTRY(jlong, WB_AllocateFromMetaspaceTestArena(JNIEnv* env, jobject wb, jlong arena, jlong word_size))
1721   metaspace::MetaspaceTestArena* arena0 = (metaspace::MetaspaceTestArena*) arena;
1722   MetaWord* p = arena0->allocate((size_t) word_size);
1723   return (jlong)p2i(p);
1724 WB_END
1725 
1726 WB_ENTRY(void, WB_DeallocateToMetaspaceTestArena(JNIEnv* env, jobject wb, jlong arena, jlong p, jlong word_size))
1727   metaspace::MetaspaceTestArena* arena0 = (metaspace::MetaspaceTestArena*) arena;
1728   arena0->deallocate((MetaWord*)p, (size_t) word_size);
1729 WB_END
1730 
1731 WB_ENTRY(jlong, WB_GetMaxMetaspaceAllocationSize(JNIEnv* env, jobject wb))
1732   return (jlong) Metaspace::max_allocation_word_size() * BytesPerWord;
1733 WB_END
1734 
1735 //////////////
1736 
1737 WB_ENTRY(jlong, WB_AllocateMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong size))
1738   if (size < 0) {
1739     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1740         err_msg("WB_AllocateMetaspace: size is negative: " JLONG_FORMAT, size));
1741   }
1742 
1743   oop class_loader_oop = JNIHandles::resolve(class_loader);
1744   ClassLoaderData* cld = class_loader_oop != NULL
1745       ? java_lang_ClassLoader::loader_data_acquire(class_loader_oop)
1746       : ClassLoaderData::the_null_class_loader_data();
1747 
1748   void* metadata = MetadataFactory::new_array<u1>(cld, WhiteBox::array_bytes_to_length((size_t)size), thread);
1749 
1750   return (jlong)(uintptr_t)metadata;
1751 WB_END
1752 
1753 WB_ENTRY(void, WB_DefineModule(JNIEnv* env, jobject o, jobject module, jboolean is_open,
1754                                 jstring version, jstring location, jobjectArray packages))
1755   Handle h_module (THREAD, JNIHandles::resolve(module));
1756   Modules::define_module(h_module, is_open, version, location, packages, CHECK);
1757 WB_END
1758 
1759 WB_ENTRY(void, WB_AddModuleExports(JNIEnv* env, jobject o, jobject from_module, jstring package, jobject to_module))
1760   Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1761   Handle h_to_module (THREAD, JNIHandles::resolve(to_module));
1762   Modules::add_module_exports_qualified(h_from_module, package, h_to_module, CHECK);
1763 WB_END
1764 
1765 WB_ENTRY(void, WB_AddModuleExportsToAllUnnamed(JNIEnv* env, jobject o, jclass module, jstring package))
1766   Handle h_module (THREAD, JNIHandles::resolve(module));
1767   Modules::add_module_exports_to_all_unnamed(h_module, package, CHECK);
1768 WB_END
1769 
1770 WB_ENTRY(void, WB_AddModuleExportsToAll(JNIEnv* env, jobject o, jclass module, jstring package))
1771   Handle h_module (THREAD, JNIHandles::resolve(module));
1772   Modules::add_module_exports(h_module, package, Handle(), CHECK);
1773 WB_END
1774 
1775 WB_ENTRY(void, WB_AddReadsModule(JNIEnv* env, jobject o, jobject from_module, jobject source_module))
1776   Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1777   Handle h_source_module (THREAD, JNIHandles::resolve(source_module));
1778   Modules::add_reads_module(h_from_module, h_source_module, CHECK);
1779 WB_END
1780 
1781 WB_ENTRY(jlong, WB_IncMetaspaceCapacityUntilGC(JNIEnv* env, jobject wb, jlong inc))
1782   if (inc < 0) {
1783     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1784         err_msg("WB_IncMetaspaceCapacityUntilGC: inc is negative: " JLONG_FORMAT, inc));
1785   }
1786 
1787   jlong max_size_t = (jlong) ((size_t) -1);
1788   if (inc > max_size_t) {
1789     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1790         err_msg("WB_IncMetaspaceCapacityUntilGC: inc does not fit in size_t: " JLONG_FORMAT, inc));
1791   }
1792 
1793   size_t new_cap_until_GC = 0;
1794   size_t aligned_inc = align_down((size_t) inc, Metaspace::commit_alignment());
1795   bool success = MetaspaceGC::inc_capacity_until_GC(aligned_inc, &new_cap_until_GC);
1796   if (!success) {
1797     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(),
1798                 "WB_IncMetaspaceCapacityUntilGC: could not increase capacity until GC "
1799                 "due to contention with another thread");
1800   }
1801   return (jlong) new_cap_until_GC;
1802 WB_END
1803 
1804 WB_ENTRY(jlong, WB_MetaspaceCapacityUntilGC(JNIEnv* env, jobject wb))
1805   return (jlong) MetaspaceGC::capacity_until_GC();
1806 WB_END
1807 
1808 // The function is only valid when CDS is available.
1809 WB_ENTRY(jlong, WB_MetaspaceSharedRegionAlignment(JNIEnv* env, jobject wb))
1810 #if INCLUDE_CDS
1811   return (jlong)MetaspaceShared::core_region_alignment();
1812 #else
1813   ShouldNotReachHere();
1814   return 0L;
1815 #endif
1816 WB_END
1817 
1818 WB_ENTRY(jboolean, WB_IsMonitorInflated(JNIEnv* env, jobject wb, jobject obj))
1819   oop obj_oop = JNIHandles::resolve(obj);
1820   return (jboolean) obj_oop->mark().has_monitor();
1821 WB_END
1822 
1823 WB_ENTRY(jboolean, WB_DeflateIdleMonitors(JNIEnv* env, jobject wb))
1824   log_info(monitorinflation)("WhiteBox initiated DeflateIdleMonitors");
1825   return ObjectSynchronizer::request_deflate_idle_monitors();
1826 WB_END
1827 
1828 WB_ENTRY(void, WB_ForceSafepoint(JNIEnv* env, jobject wb))
1829   VM_ForceSafepoint force_safepoint_op;
1830   VMThread::execute(&force_safepoint_op);
1831 WB_END
1832 
1833 WB_ENTRY(jlong, WB_GetConstantPool(JNIEnv* env, jobject wb, jclass klass))
1834   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1835   return (jlong) ik->constants();
1836 WB_END
1837 
1838 WB_ENTRY(jint, WB_GetConstantPoolCacheIndexTag(JNIEnv* env, jobject wb))
1839   return ConstantPool::CPCACHE_INDEX_TAG;
1840 WB_END
1841 
1842 WB_ENTRY(jint, WB_GetConstantPoolCacheLength(JNIEnv* env, jobject wb, jclass klass))
1843   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1844   ConstantPool* cp = ik->constants();
1845   if (cp->cache() == NULL) {
1846       return -1;
1847   }
1848   return cp->cache()->length();
1849 WB_END
1850 
1851 WB_ENTRY(jint, WB_ConstantPoolRemapInstructionOperandFromCache(JNIEnv* env, jobject wb, jclass klass, jint index))
1852   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1853   ConstantPool* cp = ik->constants();
1854   if (cp->cache() == NULL) {
1855     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(), "Constant pool does not have a cache");
1856   }
1857   jint cpci = index;
1858   jint cpciTag = ConstantPool::CPCACHE_INDEX_TAG;
1859   if (cpciTag > cpci || cpci >= cp->cache()->length() + cpciTag) {
1860     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool cache index is out of range");
1861   }
1862   jint cpi = cp->remap_instruction_operand_from_cache(cpci);
1863   return cpi;
1864 WB_END
1865 
1866 WB_ENTRY(jint, WB_ConstantPoolEncodeIndyIndex(JNIEnv* env, jobject wb, jint index))
1867   return ConstantPool::encode_invokedynamic_index(index);
1868 WB_END
1869 
1870 WB_ENTRY(jobjectArray, WB_getObjectsViaKlassOopMaps(JNIEnv* env, jobject wb, jobject thing))
1871   oop aoop = JNIHandles::resolve(thing);
1872   if (!aoop->is_instance()) {
1873     return NULL;
1874   }
1875   instanceHandle ih(THREAD, (instanceOop) aoop);
1876   InstanceKlass* klass = InstanceKlass::cast(ih->klass());
1877   if (klass->nonstatic_oop_map_count() == 0) {
1878     return NULL;
1879   }
1880   const OopMapBlock* map = klass->start_of_nonstatic_oop_maps();
1881   const OopMapBlock* const end = map + klass->nonstatic_oop_map_count();
1882   int oop_count = 0;
1883   while (map < end) {
1884     oop_count += map->count();
1885     map++;
1886   }
1887 
1888   objArrayHandle result_array =
1889       oopFactory::new_objArray_handle(vmClasses::Object_klass(), oop_count, CHECK_NULL);
1890   map = klass->start_of_nonstatic_oop_maps();
1891   int index = 0;
1892   while (map < end) {
1893     int offset = map->offset();
1894     for (unsigned int j = 0; j < map->count(); j++) {
1895       result_array->obj_at_put(index++, ih->obj_field(offset));
1896       offset += heapOopSize;
1897     }
1898     map++;
1899   }
1900   return (jobjectArray)JNIHandles::make_local(THREAD, result_array());
1901 WB_END
1902 
1903 class CollectOops : public BasicOopIterateClosure {
1904  public:
1905   GrowableArray<Handle>* array;
1906 
1907   jobjectArray create_jni_result(JNIEnv* env, TRAPS) {
1908     objArrayHandle result_array =
1909         oopFactory::new_objArray_handle(vmClasses::Object_klass(), array->length(), CHECK_NULL);
1910     for (int i = 0 ; i < array->length(); i++) {
1911       result_array->obj_at_put(i, array->at(i)());
1912     }
1913     return (jobjectArray)JNIHandles::make_local(THREAD, result_array());
1914   }
1915 
1916   void add_oop(oop o) {
1917     Handle oh = Handle(Thread::current(), o);
1918     // Value might be oop, but JLS can't see as Object, just iterate through it...
1919     if (oh != NULL && oh->is_inline_type()) {
1920       oh->oop_iterate(this);
1921     } else {
1922       array->append(oh);
1923     }
1924   }
1925 
1926   void do_oop(oop* o) { add_oop(HeapAccess<>::oop_load(o)); }
1927   void do_oop(narrowOop* v) { add_oop(HeapAccess<>::oop_load(v)); }
1928 };
1929 
1930 
1931 WB_ENTRY(jobjectArray, WB_getObjectsViaOopIterator(JNIEnv* env, jobject wb, jobject thing))
1932   ResourceMark rm(thread);
1933   Handle objh(thread, JNIHandles::resolve(thing));
1934   GrowableArray<Handle>* array = new GrowableArray<Handle>(128);
1935   CollectOops collectOops;
1936   collectOops.array = array;
1937   objh->oop_iterate(&collectOops);
1938   return collectOops.create_jni_result(env, THREAD);
1939 WB_END
1940 
1941 WB_ENTRY(jobjectArray, WB_getObjectsViaFrameOopIterator(JNIEnv* env, jobject wb, jint depth))
1942   ResourceMark rm(THREAD);
1943   GrowableArray<Handle>* array = new GrowableArray<Handle>(128);
1944   CollectOops collectOops;
1945   collectOops.array = array;
1946   StackFrameStream sfs(thread, false /* update */, true /* process_frames */);
1947   while (depth > 0) { // Skip the native WB API frame
1948     sfs.next();
1949     frame* f = sfs.current();
1950     f->oops_do(&collectOops, NULL, sfs.register_map());
1951     depth--;
1952   }
1953   return collectOops.create_jni_result(env, THREAD);
1954 WB_END
1955 
1956 
1957 WB_ENTRY(void, WB_ClearInlineCaches(JNIEnv* env, jobject wb, jboolean preserve_static_stubs))
1958   VM_ClearICs clear_ics(preserve_static_stubs == JNI_TRUE);
1959   VMThread::execute(&clear_ics);
1960 WB_END
1961 
1962 template <typename T>
1963 static bool GetMethodOption(JavaThread* thread, JNIEnv* env, jobject method, jstring name, T* value) {
1964   assert(value != NULL, "sanity");
1965   if (method == NULL || name == NULL) {
1966     return false;
1967   }
1968   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1969   CHECK_JNI_EXCEPTION_(env, false);
1970   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1971   // can't be in VM when we call JNI
1972   ThreadToNativeFromVM ttnfv(thread);
1973   const char* flag_name = env->GetStringUTFChars(name, NULL);
1974   CHECK_JNI_EXCEPTION_(env, false);
1975   enum CompileCommand option = CompilerOracle::string_to_option(flag_name);
1976   env->ReleaseStringUTFChars(name, flag_name);
1977   if (option == CompileCommand::Unknown) {
1978     return false;
1979   }
1980   if (!CompilerOracle::option_matches_type(option, *value)) {
1981     return false;
1982   }
1983   return CompilerOracle::has_option_value(mh, option, *value);
1984 }
1985 
1986 WB_ENTRY(jobject, WB_GetMethodBooleaneOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1987   bool result;
1988   if (GetMethodOption<bool> (thread, env, method, name, &result)) {
1989     // can't be in VM when we call JNI
1990     ThreadToNativeFromVM ttnfv(thread);
1991     return booleanBox(thread, env, result);
1992   }
1993   return NULL;
1994 WB_END
1995 
1996 WB_ENTRY(jobject, WB_GetMethodIntxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1997   intx result;
1998   if (GetMethodOption <intx> (thread, env, method, name, &result)) {
1999     // can't be in VM when we call JNI
2000     ThreadToNativeFromVM ttnfv(thread);
2001     return longBox(thread, env, result);
2002   }
2003   return NULL;
2004 WB_END
2005 
2006 WB_ENTRY(jobject, WB_GetMethodUintxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
2007   uintx result;
2008   if (GetMethodOption <uintx> (thread, env, method, name, &result)) {
2009     // can't be in VM when we call JNI
2010     ThreadToNativeFromVM ttnfv(thread);
2011     return longBox(thread, env, result);
2012   }
2013   return NULL;
2014 WB_END
2015 
2016 WB_ENTRY(jobject, WB_GetMethodDoubleOption(JNIEnv* env, jobject wb, jobject method, jstring name))
2017   double result;
2018   if (GetMethodOption <double> (thread, env, method, name, &result)) {
2019     // can't be in VM when we call JNI
2020     ThreadToNativeFromVM ttnfv(thread);
2021     return doubleBox(thread, env, result);
2022   }
2023   return NULL;
2024 WB_END
2025 
2026 WB_ENTRY(jobject, WB_GetMethodStringOption(JNIEnv* env, jobject wb, jobject method, jstring name))
2027   ccstr ccstrResult;
2028   if (GetMethodOption <ccstr> (thread, env, method, name, &ccstrResult)) {
2029     // can't be in VM when we call JNI
2030     ThreadToNativeFromVM ttnfv(thread);
2031     jstring result = env->NewStringUTF(ccstrResult);
2032     CHECK_JNI_EXCEPTION_(env, NULL);
2033     return result;
2034   }
2035   return NULL;
2036 WB_END
2037 
2038 WB_ENTRY(jobject, WB_GetDefaultArchivePath(JNIEnv* env, jobject wb))
2039   const char* p = Arguments::get_default_shared_archive_path();
2040   ThreadToNativeFromVM ttn(thread);
2041   jstring path_string = env->NewStringUTF(p);
2042 
2043   CHECK_JNI_EXCEPTION_(env, NULL);
2044 
2045   return path_string;
2046 WB_END
2047 
2048 WB_ENTRY(jboolean, WB_IsSharingEnabled(JNIEnv* env, jobject wb))
2049   return UseSharedSpaces;
2050 WB_END
2051 
2052 WB_ENTRY(jint, WB_GetCDSGenericHeaderMinVersion(JNIEnv* env, jobject wb))
2053 #if INCLUDE_CDS
2054   return (jint)CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION;
2055 #else
2056   ShouldNotReachHere();
2057   return (jint)-1;
2058 #endif
2059 WB_END
2060 
2061 WB_ENTRY(jint, WB_GetCDSCurrentVersion(JNIEnv* env, jobject wb))
2062 #if INCLUDE_CDS
2063   return (jint)CURRENT_CDS_ARCHIVE_VERSION;
2064 #else
2065   ShouldNotReachHere();
2066   return (jint)-1;
2067 #endif
2068 WB_END
2069 
2070 WB_ENTRY(jboolean, WB_CDSMemoryMappingFailed(JNIEnv* env, jobject wb))
2071   return FileMapInfo::memory_mapping_failed();
2072 WB_END
2073 
2074 WB_ENTRY(jboolean, WB_IsShared(JNIEnv* env, jobject wb, jobject obj))
2075   oop obj_oop = JNIHandles::resolve(obj);
2076   return Universe::heap()->is_archived_object(obj_oop);
2077 WB_END
2078 
2079 WB_ENTRY(jboolean, WB_IsSharedInternedString(JNIEnv* env, jobject wb, jobject str))
2080   ResourceMark rm(THREAD);
2081   oop str_oop = JNIHandles::resolve(str);
2082   int length;
2083   jchar* chars = java_lang_String::as_unicode_string(str_oop, length, CHECK_(false));
2084   return StringTable::lookup_shared(chars, length) == str_oop;
2085 WB_END
2086 
2087 WB_ENTRY(jboolean, WB_IsSharedClass(JNIEnv* env, jobject wb, jclass clazz))
2088   return (jboolean)MetaspaceShared::is_in_shared_metaspace(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
2089 WB_END
2090 
2091 WB_ENTRY(jboolean, WB_AreSharedStringsMapped(JNIEnv* env))
2092   return HeapShared::closed_regions_mapped();
2093 WB_END
2094 
2095 WB_ENTRY(jobject, WB_GetResolvedReferences(JNIEnv* env, jobject wb, jclass clazz))
2096   Klass *k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
2097   if (k->is_instance_klass()) {
2098     InstanceKlass *ik = InstanceKlass::cast(k);
2099     ConstantPool *cp = ik->constants();
2100     objArrayOop refs =  cp->resolved_references();
2101     return (jobject)JNIHandles::make_local(THREAD, refs);
2102   } else {
2103     return NULL;
2104   }
2105 WB_END
2106 
2107 WB_ENTRY(void, WB_LinkClass(JNIEnv* env, jobject wb, jclass clazz))
2108   Klass *k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
2109   if (!k->is_instance_klass()) {
2110     return;
2111   }
2112   InstanceKlass *ik = InstanceKlass::cast(k);
2113   ik->link_class(THREAD); // may throw verification error
2114 WB_END
2115 
2116 WB_ENTRY(jboolean, WB_AreOpenArchiveHeapObjectsMapped(JNIEnv* env))
2117   return HeapShared::open_regions_mapped();
2118 WB_END
2119 
2120 WB_ENTRY(jboolean, WB_IsCDSIncluded(JNIEnv* env))
2121 #if INCLUDE_CDS
2122   return true;
2123 #else
2124   return false;
2125 #endif // INCLUDE_CDS
2126 WB_END
2127 
2128 WB_ENTRY(jboolean, WB_isC2OrJVMCIIncluded(JNIEnv* env))
2129 #if COMPILER2_OR_JVMCI
2130   return true;
2131 #else
2132   return false;
2133 #endif
2134 WB_END
2135 
2136 WB_ENTRY(jboolean, WB_IsJVMCISupportedByGC(JNIEnv* env))
2137 #if INCLUDE_JVMCI
2138   return JVMCIGlobals::gc_supports_jvmci();
2139 #else
2140   return false;
2141 #endif
2142 WB_END
2143 
2144 WB_ENTRY(jboolean, WB_CanWriteJavaHeapArchive(JNIEnv* env))
2145   return HeapShared::can_write();
2146 WB_END
2147 
2148 
2149 WB_ENTRY(jboolean, WB_IsJFRIncluded(JNIEnv* env))
2150 #if INCLUDE_JFR
2151   return true;
2152 #else
2153   return false;
2154 #endif // INCLUDE_JFR
2155 WB_END
2156 
2157 WB_ENTRY(jboolean, WB_IsDTraceIncluded(JNIEnv* env))
2158 #if defined(DTRACE_ENABLED)
2159   return true;
2160 #else
2161   return false;
2162 #endif // DTRACE_ENABLED
2163 WB_END
2164 
2165 #if INCLUDE_CDS
2166 
2167 WB_ENTRY(jint, WB_GetCDSOffsetForName(JNIEnv* env, jobject o, jstring name))
2168   ResourceMark rm;
2169   char* c_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
2170   jint result = (jint)CDSConstants::get_cds_offset(c_name);
2171   return result;
2172 WB_END
2173 
2174 WB_ENTRY(jint, WB_GetCDSConstantForName(JNIEnv* env, jobject o, jstring name))
2175   ResourceMark rm;
2176   char* c_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
2177   jint result = (jint)CDSConstants::get_cds_constant(c_name);
2178   return result;
2179 WB_END
2180 
2181 #endif // INCLUDE_CDS
2182 
2183 WB_ENTRY(jboolean, WB_HandshakeReadMonitors(JNIEnv* env, jobject wb, jobject thread_handle))
2184   class ReadMonitorsClosure : public HandshakeClosure {
2185     jboolean _executed;
2186 
2187     void do_thread(Thread* th) {
2188       JavaThread* jt = JavaThread::cast(th);
2189       ResourceMark rm;
2190 
2191       GrowableArray<MonitorInfo*>* info = new GrowableArray<MonitorInfo*>();
2192 
2193       if (!jt->has_last_Java_frame()) {
2194         return;
2195       }
2196       RegisterMap rmap(jt);
2197       for (javaVFrame* vf = jt->last_java_vframe(&rmap); vf != NULL; vf = vf->java_sender()) {
2198         GrowableArray<MonitorInfo*> *monitors = vf->monitors();
2199         if (monitors != NULL) {
2200           int len = monitors->length();
2201           // Walk monitors youngest to oldest
2202           for (int i = len - 1; i >= 0; i--) {
2203             MonitorInfo* mon_info = monitors->at(i);
2204             if (mon_info->eliminated()) continue;
2205             oop owner = mon_info->owner();
2206             if (owner != NULL) {
2207               info->append(mon_info);
2208             }
2209           }
2210         }
2211       }
2212       _executed = true;
2213     }
2214 
2215    public:
2216     ReadMonitorsClosure() : HandshakeClosure("WB_HandshakeReadMonitors"), _executed(false) {}
2217     jboolean executed() const { return _executed; }
2218   };
2219 
2220   ReadMonitorsClosure rmc;
2221   if (thread_handle != NULL) {
2222     ThreadsListHandle tlh;
2223     JavaThread* target = nullptr;
2224     bool is_alive = tlh.cv_internal_thread_to_JavaThread(thread_handle, &target, NULL);
2225     if (is_alive) {
2226       Handshake::execute(&rmc, &tlh, target);
2227     }
2228   }
2229   return rmc.executed();
2230 WB_END
2231 
2232 WB_ENTRY(jint, WB_HandshakeWalkStack(JNIEnv* env, jobject wb, jobject thread_handle, jboolean all_threads))
2233   class TraceSelfClosure : public HandshakeClosure {
2234     jint _num_threads_completed;
2235 
2236     void do_thread(Thread* th) {
2237       JavaThread* jt = JavaThread::cast(th);
2238       ResourceMark rm;
2239 
2240       jt->print_on(tty);
2241       jt->print_stack_on(tty);
2242       tty->cr();
2243       Atomic::inc(&_num_threads_completed);
2244     }
2245 
2246   public:
2247     TraceSelfClosure(Thread* thread) : HandshakeClosure("WB_TraceSelf"), _num_threads_completed(0) {}
2248 
2249     jint num_threads_completed() const { return _num_threads_completed; }
2250   };
2251   TraceSelfClosure tsc(Thread::current());
2252 
2253   if (all_threads) {
2254     Handshake::execute(&tsc);
2255   } else if (thread_handle != NULL) {
2256     ThreadsListHandle tlh;
2257     JavaThread* target = nullptr;
2258     bool is_alive = tlh.cv_internal_thread_to_JavaThread(thread_handle, &target, NULL);
2259     if (is_alive) {
2260       Handshake::execute(&tsc, &tlh, target);
2261     }
2262   }
2263   return tsc.num_threads_completed();
2264 WB_END
2265 
2266 WB_ENTRY(void, WB_AsyncHandshakeWalkStack(JNIEnv* env, jobject wb, jobject thread_handle))
2267   class TraceSelfClosure : public AsyncHandshakeClosure {
2268     JavaThread* _self;
2269     void do_thread(Thread* th) {
2270       assert(th->is_Java_thread(), "sanity");
2271       // AsynchHandshake handshakes are only executed by target.
2272       assert(_self == th, "Must be");
2273       assert(Thread::current() == th, "Must be");
2274       JavaThread* jt = JavaThread::cast(th);
2275       ResourceMark rm;
2276       jt->print_on(tty);
2277       jt->print_stack_on(tty);
2278       tty->cr();
2279     }
2280 
2281   public:
2282     TraceSelfClosure(JavaThread* self_target) : AsyncHandshakeClosure("WB_TraceSelf"), _self(self_target) {}
2283   };
2284   if (thread_handle != NULL) {
2285     ThreadsListHandle tlh;
2286     JavaThread* target = nullptr;
2287     bool is_alive = tlh.cv_internal_thread_to_JavaThread(thread_handle, &target, NULL);
2288     if (is_alive) {
2289       TraceSelfClosure* tsc = new TraceSelfClosure(target);
2290       Handshake::execute(tsc, target);
2291     }
2292   }
2293 WB_END
2294 
2295 static volatile int _emulated_lock = 0;
2296 
2297 WB_ENTRY(void, WB_LockAndBlock(JNIEnv* env, jobject wb, jboolean suspender))
2298   JavaThread* self = JavaThread::current();
2299 
2300   {
2301     // Before trying to acquire the lock transition into a safepoint safe state.
2302     // Otherwise if either suspender or suspendee blocks for a safepoint
2303     // in ~ThreadBlockInVM the other one could loop forever trying to acquire
2304     // the lock without allowing the safepoint to progress.
2305     ThreadBlockInVM tbivm(self);
2306 
2307     // We will deadlock here if we are 'suspender' and 'suspendee'
2308     // suspended in ~ThreadBlockInVM. This verifies we only suspend
2309     // at the right place.
2310     while (Atomic::cmpxchg(&_emulated_lock, 0, 1) != 0) {}
2311     assert(_emulated_lock == 1, "Must be locked");
2312 
2313     // Sleep much longer in suspendee to force situation where
2314     // 'suspender' is waiting above to acquire lock.
2315     os::naked_short_sleep(suspender ? 1 : 10);
2316   }
2317   Atomic::store(&_emulated_lock, 0);
2318 WB_END
2319 
2320 // Some convenience methods to deal with objects from java
2321 int WhiteBox::offset_for_field(const char* field_name, oop object,
2322     Symbol* signature_symbol) {
2323   assert(field_name != NULL && strlen(field_name) > 0, "Field name not valid");
2324 
2325   //Get the class of our object
2326   Klass* arg_klass = object->klass();
2327   //Turn it into an instance-klass
2328   InstanceKlass* ik = InstanceKlass::cast(arg_klass);
2329 
2330   //Create symbols to look for in the class
2331   TempNewSymbol name_symbol = SymbolTable::new_symbol(field_name);
2332 
2333   //To be filled in with an offset of the field we're looking for
2334   fieldDescriptor fd;
2335 
2336   Klass* res = ik->find_field(name_symbol, signature_symbol, &fd);
2337   if (res == NULL) {
2338     tty->print_cr("Invalid layout of %s at %s", ik->external_name(),
2339         name_symbol->as_C_string());
2340     vm_exit_during_initialization("Invalid layout of preloaded class: use -Xlog:class+load=info to see the origin of the problem class");
2341   }
2342 
2343   //fetch the field at the offset we've found
2344   int dest_offset = fd.offset();
2345 
2346   return dest_offset;
2347 }
2348 
2349 
2350 const char* WhiteBox::lookup_jstring(const char* field_name, oop object) {
2351   int offset = offset_for_field(field_name, object,
2352       vmSymbols::string_signature());
2353   oop string = object->obj_field(offset);
2354   if (string == NULL) {
2355     return NULL;
2356   }
2357   const char* ret = java_lang_String::as_utf8_string(string);
2358   return ret;
2359 }
2360 
2361 bool WhiteBox::lookup_bool(const char* field_name, oop object) {
2362   int offset =
2363       offset_for_field(field_name, object, vmSymbols::bool_signature());
2364   bool ret = (object->bool_field(offset) == JNI_TRUE);
2365   return ret;
2366 }
2367 
2368 void WhiteBox::register_methods(JNIEnv* env, jclass wbclass, JavaThread* thread, JNINativeMethod* method_array, int method_count) {
2369   ResourceMark rm;
2370   Klass* klass = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(wbclass));
2371   const char* klass_name = klass->external_name();
2372 
2373   ThreadToNativeFromVM ttnfv(thread); // can't be in VM when we call JNI
2374 
2375   //  one by one registration natives for exception catching
2376   jclass no_such_method_error_klass = env->FindClass(vmSymbols::java_lang_NoSuchMethodError()->as_C_string());
2377   CHECK_JNI_EXCEPTION(env);
2378   for (int i = 0, n = method_count; i < n; ++i) {
2379     // Skip dummy entries
2380     if (method_array[i].fnPtr == NULL) continue;
2381     if (env->RegisterNatives(wbclass, &method_array[i], 1) != 0) {
2382       jthrowable throwable_obj = env->ExceptionOccurred();
2383       if (throwable_obj != NULL) {
2384         env->ExceptionClear();
2385         if (env->IsInstanceOf(throwable_obj, no_such_method_error_klass)) {
2386           // NoSuchMethodError is thrown when a method can't be found or a method is not native.
2387           // Ignoring the exception since it is not preventing use of other WhiteBox methods.
2388           tty->print_cr("Warning: 'NoSuchMethodError' on register of %s::%s%s",
2389               klass_name, method_array[i].name, method_array[i].signature);
2390         }
2391       } else {
2392         // Registration failed unexpectedly.
2393         tty->print_cr("Warning: unexpected error on register of %s::%s%s. All methods will be unregistered",
2394             klass_name, method_array[i].name, method_array[i].signature);
2395         env->UnregisterNatives(wbclass);
2396         break;
2397       }
2398     }
2399   }
2400 }
2401 
2402 WB_ENTRY(jint, WB_AddCompilerDirective(JNIEnv* env, jobject o, jstring compDirect))
2403   // can't be in VM when we call JNI
2404   ThreadToNativeFromVM ttnfv(thread);
2405   const char* dir = env->GetStringUTFChars(compDirect, NULL);
2406   CHECK_JNI_EXCEPTION_(env, 0);
2407   int ret;
2408   {
2409     ThreadInVMfromNative ttvfn(thread); // back to VM
2410     ret = DirectivesParser::parse_string(dir, tty);
2411   }
2412   env->ReleaseStringUTFChars(compDirect, dir);
2413   // -1 for error parsing directive. Return 0 as number of directives added.
2414   if (ret == -1) {
2415     ret = 0;
2416   }
2417   return (jint) ret;
2418 WB_END
2419 
2420 WB_ENTRY(void, WB_RemoveCompilerDirective(JNIEnv* env, jobject o, jint count))
2421   DirectivesStack::pop(count);
2422 WB_END
2423 
2424 // Checks that the library libfile has the noexecstack bit set.
2425 WB_ENTRY(jboolean, WB_CheckLibSpecifiesNoexecstack(JNIEnv* env, jobject o, jstring libfile))
2426   jboolean ret = false;
2427 #ifdef LINUX
2428   // Can't be in VM when we call JNI.
2429   ThreadToNativeFromVM ttnfv(thread);
2430   const char* lf = env->GetStringUTFChars(libfile, NULL);
2431   CHECK_JNI_EXCEPTION_(env, 0);
2432   ret = (jboolean) ElfFile::specifies_noexecstack(lf);
2433   env->ReleaseStringUTFChars(libfile, lf);
2434 #endif
2435   return ret;
2436 WB_END
2437 
2438 WB_ENTRY(jboolean, WB_IsContainerized(JNIEnv* env, jobject o))
2439   LINUX_ONLY(return OSContainer::is_containerized();)
2440   return false;
2441 WB_END
2442 
2443 WB_ENTRY(jint, WB_ValidateCgroup(JNIEnv* env,
2444                                     jobject o,
2445                                     jstring proc_cgroups,
2446                                     jstring proc_self_cgroup,
2447                                     jstring proc_self_mountinfo))
2448   jint ret = 0;
2449 #ifdef LINUX
2450   ThreadToNativeFromVM ttnfv(thread);
2451   const char* p_cgroups = env->GetStringUTFChars(proc_cgroups, NULL);
2452   CHECK_JNI_EXCEPTION_(env, 0);
2453   const char* p_s_cgroup = env->GetStringUTFChars(proc_self_cgroup, NULL);
2454   CHECK_JNI_EXCEPTION_(env, 0);
2455   const char* p_s_mountinfo = env->GetStringUTFChars(proc_self_mountinfo, NULL);
2456   CHECK_JNI_EXCEPTION_(env, 0);
2457   u1 cg_type_flags = 0;
2458   // This sets cg_type_flags
2459   WhiteBox::validate_cgroup(p_cgroups, p_s_cgroup, p_s_mountinfo, &cg_type_flags);
2460   ret = (jint)cg_type_flags;
2461   env->ReleaseStringUTFChars(proc_cgroups, p_cgroups);
2462   env->ReleaseStringUTFChars(proc_self_cgroup, p_s_cgroup);
2463   env->ReleaseStringUTFChars(proc_self_mountinfo, p_s_mountinfo);
2464 #endif
2465   return ret;
2466 WB_END
2467 
2468 WB_ENTRY(void, WB_PrintOsInfo(JNIEnv* env, jobject o))
2469   os::print_os_info(tty);
2470 WB_END
2471 
2472 // Elf decoder
2473 WB_ENTRY(void, WB_DisableElfSectionCache(JNIEnv* env))
2474 #if !defined(_WINDOWS) && !defined(__APPLE__) && !defined(_AIX)
2475   ElfFile::_do_not_cache_elf_section = true;
2476 #endif
2477 WB_END
2478 
2479 WB_ENTRY(jlong, WB_ResolvedMethodItemsCount(JNIEnv* env, jobject o))
2480   return (jlong) ResolvedMethodTable::items_count();
2481 WB_END
2482 
2483 WB_ENTRY(jint, WB_ProtectionDomainRemovedCount(JNIEnv* env, jobject o))
2484   return (jint) SystemDictionary::pd_cache_table()->removed_entries_count();
2485 WB_END
2486 
2487 WB_ENTRY(jint, WB_GetKlassMetadataSize(JNIEnv* env, jobject wb, jclass mirror))
2488   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(mirror));
2489   // Return size in bytes.
2490   return k->size() * wordSize;
2491 WB_END
2492 
2493 // See test/hotspot/jtreg/runtime/Thread/ThreadObjAccessAtExit.java.
2494 // It explains how the thread's priority field is used for test state coordination.
2495 //
2496 WB_ENTRY(void, WB_CheckThreadObjOfTerminatingThread(JNIEnv* env, jobject wb, jobject target_handle))
2497   oop target_oop = JNIHandles::resolve_non_null(target_handle);
2498   jlong tid = java_lang_Thread::thread_id(target_oop);
2499   JavaThread* target = java_lang_Thread::thread(target_oop);
2500 
2501   // Grab a ThreadsListHandle to protect the target thread whilst terminating
2502   ThreadsListHandle tlh;
2503 
2504   // Look up the target thread by tid to ensure it is present
2505   JavaThread* t = tlh.list()->find_JavaThread_from_java_tid(tid);
2506   if (t == NULL) {
2507     THROW_MSG(vmSymbols::java_lang_RuntimeException(), "Target thread not found in ThreadsList!");
2508   }
2509 
2510   tty->print_cr("WB_CheckThreadObjOfTerminatingThread: target thread is protected");
2511   // Allow target to terminate by boosting priority
2512   java_lang_Thread::set_priority(t->threadObj(), ThreadPriority(NormPriority + 1));
2513 
2514   // Now wait for the target to terminate
2515   while (!target->is_terminated()) {
2516     ThreadBlockInVM tbivm(thread);  // just in case target is involved in a safepoint
2517     os::naked_short_sleep(0);
2518   }
2519 
2520   tty->print_cr("WB_CheckThreadObjOfTerminatingThread: target thread is terminated");
2521 
2522   // Now release the GC inducing thread - we have to re-resolve the external oop that
2523   // was passed in as GC may have occurred and we don't know if we can trust t->threadObj() now.
2524   oop original = JNIHandles::resolve_non_null(target_handle);
2525   java_lang_Thread::set_priority(original, ThreadPriority(NormPriority + 2));
2526 
2527   tty->print_cr("WB_CheckThreadObjOfTerminatingThread: GC has been initiated - checking threadObj:");
2528 
2529   // The Java code should be creating garbage and triggering GC, which would potentially move
2530   // the threadObj oop. If the exiting thread is properly protected then its threadObj should
2531   // remain valid and equal to our initial target_handle. Loop a few times to give GC a chance to
2532   // kick in.
2533   for (int i = 0; i < 5; i++) {
2534     oop original = JNIHandles::resolve_non_null(target_handle);
2535     oop current = t->threadObj();
2536     if (original != current) {
2537       tty->print_cr("WB_CheckThreadObjOfTerminatingThread: failed comparison on iteration %d", i);
2538       THROW_MSG(vmSymbols::java_lang_RuntimeException(), "Target thread oop has changed!");
2539     } else {
2540       tty->print_cr("WB_CheckThreadObjOfTerminatingThread: successful comparison on iteration %d", i);
2541       ThreadBlockInVM tbivm(thread);
2542       os::naked_short_sleep(50);
2543     }
2544   }
2545 WB_END
2546 
2547 WB_ENTRY(void, WB_VerifyFrames(JNIEnv* env, jobject wb, jboolean log, jboolean update_map))
2548   ResourceMark rm; // for verify
2549   stringStream st;
2550   for (StackFrameStream fst(JavaThread::current(), update_map, true); !fst.is_done(); fst.next()) {
2551     frame* current_frame = fst.current();
2552     if (log) {
2553       current_frame->print_value_on(&st, NULL);
2554     }
2555     current_frame->verify(fst.register_map());
2556   }
2557   if (log) {
2558     tty->print_cr("[WhiteBox::VerifyFrames] Walking Frames");
2559     tty->print_raw(st.as_string());
2560     tty->print_cr("[WhiteBox::VerifyFrames] Done");
2561   }
2562 WB_END
2563 
2564 WB_ENTRY(jboolean, WB_IsJVMTIIncluded(JNIEnv* env, jobject wb))
2565 #if INCLUDE_JVMTI
2566   return JNI_TRUE;
2567 #else
2568   return JNI_FALSE;
2569 #endif
2570 WB_END
2571 
2572 WB_ENTRY(void, WB_WaitUnsafe(JNIEnv* env, jobject wb, jint time))
2573     os::naked_short_sleep(time);
2574 WB_END
2575 
2576 WB_ENTRY(jstring, WB_GetLibcName(JNIEnv* env, jobject o))
2577   ThreadToNativeFromVM ttn(thread);
2578   jstring info_string = env->NewStringUTF(XSTR(LIBC));
2579   CHECK_JNI_EXCEPTION_(env, NULL);
2580   return info_string;
2581 WB_END
2582 
2583 WB_ENTRY(void, WB_LockCritical(JNIEnv* env, jobject wb))
2584   GCLocker::lock_critical(thread);
2585 WB_END
2586 
2587 WB_ENTRY(void, WB_UnlockCritical(JNIEnv* env, jobject wb))
2588   GCLocker::unlock_critical(thread);
2589 WB_END
2590 
2591 #define CC (char*)
2592 
2593 static JNINativeMethod methods[] = {
2594   {CC"getObjectAddress0",                CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectAddress  },
2595   {CC"getObjectSize0",                   CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectSize     },
2596   {CC"isObjectInOldGen0",                CC"(Ljava/lang/Object;)Z", (void*)&WB_isObjectInOldGen  },
2597   {CC"getHeapOopSize",                   CC"()I",                   (void*)&WB_GetHeapOopSize    },
2598   {CC"getVMPageSize",                    CC"()I",                   (void*)&WB_GetVMPageSize     },
2599   {CC"getVMAllocationGranularity",       CC"()J",                   (void*)&WB_GetVMAllocationGranularity },
2600   {CC"getVMLargePageSize",               CC"()J",                   (void*)&WB_GetVMLargePageSize},
2601   {CC"getHeapSpaceAlignment",            CC"()J",                   (void*)&WB_GetHeapSpaceAlignment},
2602   {CC"getHeapAlignment",                 CC"()J",                   (void*)&WB_GetHeapAlignment},
2603   {CC"countAliveClasses0",               CC"(Ljava/lang/String;)I", (void*)&WB_CountAliveClasses },
2604   {CC"getSymbolRefcount",                CC"(Ljava/lang/String;)I", (void*)&WB_GetSymbolRefcount },
2605   {CC"parseCommandLine0",
2606       CC"(Ljava/lang/String;C[Ljdk/test/whitebox/parser/DiagnosticCommand;)[Ljava/lang/Object;",
2607       (void*) &WB_ParseCommandLine
2608   },
2609   {CC"addToBootstrapClassLoaderSearch0", CC"(Ljava/lang/String;)V",
2610                                                       (void*)&WB_AddToBootstrapClassLoaderSearch},
2611   {CC"addToSystemClassLoaderSearch0",    CC"(Ljava/lang/String;)V",
2612                                                       (void*)&WB_AddToSystemClassLoaderSearch},
2613   {CC"getCompressedOopsMaxHeapSize", CC"()J",
2614       (void*)&WB_GetCompressedOopsMaxHeapSize},
2615   {CC"printHeapSizes",     CC"()V",                   (void*)&WB_PrintHeapSizes    },
2616   {CC"readFromNoaccessArea",CC"()V",                  (void*)&WB_ReadFromNoaccessArea},
2617   {CC"stressVirtualSpaceResize",CC"(JJJ)I",           (void*)&WB_StressVirtualSpaceResize},
2618 #if INCLUDE_CDS
2619   {CC"getCDSOffsetForName0", CC"(Ljava/lang/String;)I",  (void*)&WB_GetCDSOffsetForName},
2620   {CC"getCDSConstantForName0", CC"(Ljava/lang/String;)I",  (void*)&WB_GetCDSConstantForName},
2621 #endif
2622 #if INCLUDE_G1GC
2623   {CC"g1InConcurrentMark", CC"()Z",                   (void*)&WB_G1InConcurrentMark},
2624   {CC"g1IsHumongous0",      CC"(Ljava/lang/Object;)Z", (void*)&WB_G1IsHumongous     },
2625   {CC"g1BelongsToHumongousRegion0", CC"(J)Z",         (void*)&WB_G1BelongsToHumongousRegion},
2626   {CC"g1BelongsToFreeRegion0", CC"(J)Z",              (void*)&WB_G1BelongsToFreeRegion},
2627   {CC"g1NumMaxRegions",    CC"()J",                   (void*)&WB_G1NumMaxRegions  },
2628   {CC"g1NumFreeRegions",   CC"()J",                   (void*)&WB_G1NumFreeRegions  },
2629   {CC"g1RegionSize",       CC"()I",                   (void*)&WB_G1RegionSize      },
2630   {CC"g1StartConcMarkCycle",       CC"()Z",           (void*)&WB_G1StartMarkCycle  },
2631   {CC"g1HasRegionsToUncommit",  CC"()Z",              (void*)&WB_G1HasRegionsToUncommit},
2632   {CC"g1AuxiliaryMemoryUsage", CC"()Ljava/lang/management/MemoryUsage;",
2633                                                       (void*)&WB_G1AuxiliaryMemoryUsage  },
2634   {CC"g1ActiveMemoryNodeCount", CC"()I",              (void*)&WB_G1ActiveMemoryNodeCount },
2635   {CC"g1MemoryNodeIds",    CC"()[I",                  (void*)&WB_G1MemoryNodeIds },
2636   {CC"g1GetMixedGCInfo",   CC"(I)[J",                 (void*)&WB_G1GetMixedGCInfo },
2637 #endif // INCLUDE_G1GC
2638 #if INCLUDE_PARALLELGC
2639   {CC"psVirtualSpaceAlignment",CC"()J",               (void*)&WB_PSVirtualSpaceAlignment},
2640   {CC"psHeapGenerationAlignment",CC"()J",             (void*)&WB_PSHeapGenerationAlignment},
2641 #endif
2642   {CC"NMTMalloc",           CC"(J)J",                 (void*)&WB_NMTMalloc          },
2643   {CC"NMTMallocWithPseudoStack", CC"(JI)J",           (void*)&WB_NMTMallocWithPseudoStack},
2644   {CC"NMTMallocWithPseudoStackAndType", CC"(JII)J",   (void*)&WB_NMTMallocWithPseudoStackAndType},
2645   {CC"NMTFree",             CC"(J)V",                 (void*)&WB_NMTFree            },
2646   {CC"NMTReserveMemory",    CC"(J)J",                 (void*)&WB_NMTReserveMemory   },
2647   {CC"NMTAttemptReserveMemoryAt",    CC"(JJ)J",       (void*)&WB_NMTAttemptReserveMemoryAt },
2648   {CC"NMTCommitMemory",     CC"(JJ)V",                (void*)&WB_NMTCommitMemory    },
2649   {CC"NMTUncommitMemory",   CC"(JJ)V",                (void*)&WB_NMTUncommitMemory  },
2650   {CC"NMTReleaseMemory",    CC"(JJ)V",                (void*)&WB_NMTReleaseMemory   },
2651   {CC"NMTGetHashSize",      CC"()I",                  (void*)&WB_NMTGetHashSize     },
2652   {CC"NMTNewArena",         CC"(J)J",                 (void*)&WB_NMTNewArena        },
2653   {CC"NMTFreeArena",        CC"(J)V",                 (void*)&WB_NMTFreeArena       },
2654   {CC"NMTArenaMalloc",      CC"(JJ)V",                (void*)&WB_NMTArenaMalloc     },
2655   {CC"deoptimizeFrames",   CC"(Z)I",                  (void*)&WB_DeoptimizeFrames  },
2656   {CC"isFrameDeoptimized", CC"(I)Z",                  (void*)&WB_IsFrameDeoptimized},
2657   {CC"deoptimizeAll",      CC"()V",                   (void*)&WB_DeoptimizeAll     },
2658   {CC"deoptimizeMethod0",   CC"(Ljava/lang/reflect/Executable;Z)I",
2659                                                       (void*)&WB_DeoptimizeMethod  },
2660   {CC"isMethodCompiled0",   CC"(Ljava/lang/reflect/Executable;Z)Z",
2661                                                       (void*)&WB_IsMethodCompiled  },
2662   {CC"isMethodCompilable0", CC"(Ljava/lang/reflect/Executable;IZ)Z",
2663                                                       (void*)&WB_IsMethodCompilable},
2664   {CC"isMethodQueuedForCompilation0",
2665       CC"(Ljava/lang/reflect/Executable;)Z",          (void*)&WB_IsMethodQueuedForCompilation},
2666   {CC"isIntrinsicAvailable0",
2667       CC"(Ljava/lang/reflect/Executable;Ljava/lang/reflect/Executable;I)Z",
2668                                                       (void*)&WB_IsIntrinsicAvailable},
2669   {CC"makeMethodNotCompilable0",
2670       CC"(Ljava/lang/reflect/Executable;IZ)V",        (void*)&WB_MakeMethodNotCompilable},
2671   {CC"testSetDontInlineMethod0",
2672       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetDontInlineMethod},
2673   {CC"getMethodCompilationLevel0",
2674       CC"(Ljava/lang/reflect/Executable;Z)I",         (void*)&WB_GetMethodCompilationLevel},
2675   {CC"getMethodDecompileCount0",
2676       CC"(Ljava/lang/reflect/Executable;)I",          (void*)&WB_GetMethodDecompileCount},
2677   {CC"getMethodTrapCount0",
2678       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2679                                                       (void*)&WB_GetMethodTrapCount},
2680   {CC"getDeoptCount0",
2681       CC"(Ljava/lang/String;Ljava/lang/String;)I",    (void*)&WB_GetDeoptCount},
2682   {CC"getMethodEntryBci0",
2683       CC"(Ljava/lang/reflect/Executable;)I",          (void*)&WB_GetMethodEntryBci},
2684   {CC"getCompileQueueSize",
2685       CC"(I)I",                                       (void*)&WB_GetCompileQueueSize},
2686   {CC"testSetForceInlineMethod0",
2687       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetForceInlineMethod},
2688   {CC"enqueueMethodForCompilation0",
2689       CC"(Ljava/lang/reflect/Executable;II)Z",        (void*)&WB_EnqueueMethodForCompilation},
2690   {CC"enqueueInitializerForCompilation0",
2691       CC"(Ljava/lang/Class;I)Z",                      (void*)&WB_EnqueueInitializerForCompilation},
2692   {CC"markMethodProfiled",
2693       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_MarkMethodProfiled},
2694   {CC"clearMethodState0",
2695       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_ClearMethodState},
2696   {CC"lockCompilation",    CC"()V",                   (void*)&WB_LockCompilation},
2697   {CC"unlockCompilation",  CC"()V",                   (void*)&WB_UnlockCompilation},
2698   {CC"matchesMethod",
2699       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2700                                                       (void*)&WB_MatchesMethod},
2701   {CC"matchesInline",
2702       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2703                                                       (void*)&WB_MatchesInline},
2704   {CC"shouldPrintAssembly",
2705         CC"(Ljava/lang/reflect/Executable;I)Z",
2706                                                         (void*)&WB_ShouldPrintAssembly},
2707 
2708   {CC"isConstantVMFlag",   CC"(Ljava/lang/String;)Z", (void*)&WB_IsConstantVMFlag},
2709   {CC"isLockedVMFlag",     CC"(Ljava/lang/String;)Z", (void*)&WB_IsLockedVMFlag},
2710   {CC"setBooleanVMFlag",   CC"(Ljava/lang/String;Z)V",(void*)&WB_SetBooleanVMFlag},
2711   {CC"setIntVMFlag",       CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntVMFlag},
2712   {CC"setUintVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintVMFlag},
2713   {CC"setIntxVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntxVMFlag},
2714   {CC"setUintxVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintxVMFlag},
2715   {CC"setUint64VMFlag",    CC"(Ljava/lang/String;J)V",(void*)&WB_SetUint64VMFlag},
2716   {CC"setSizeTVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetSizeTVMFlag},
2717   {CC"setDoubleVMFlag",    CC"(Ljava/lang/String;D)V",(void*)&WB_SetDoubleVMFlag},
2718   {CC"setStringVMFlag",    CC"(Ljava/lang/String;Ljava/lang/String;)V",
2719                                                       (void*)&WB_SetStringVMFlag},
2720   {CC"getBooleanVMFlag",   CC"(Ljava/lang/String;)Ljava/lang/Boolean;",
2721                                                       (void*)&WB_GetBooleanVMFlag},
2722   {CC"getIntVMFlag",       CC"(Ljava/lang/String;)Ljava/lang/Long;",
2723                                                       (void*)&WB_GetIntVMFlag},
2724   {CC"getUintVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
2725                                                       (void*)&WB_GetUintVMFlag},
2726   {CC"getIntxVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
2727                                                       (void*)&WB_GetIntxVMFlag},
2728   {CC"getUintxVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
2729                                                       (void*)&WB_GetUintxVMFlag},
2730   {CC"getUint64VMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Long;",
2731                                                       (void*)&WB_GetUint64VMFlag},
2732   {CC"getSizeTVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
2733                                                       (void*)&WB_GetSizeTVMFlag},
2734   {CC"getDoubleVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Double;",
2735                                                       (void*)&WB_GetDoubleVMFlag},
2736   {CC"getStringVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/String;",
2737                                                       (void*)&WB_GetStringVMFlag},
2738   {CC"isInStringTable",    CC"(Ljava/lang/String;)Z", (void*)&WB_IsInStringTable  },
2739   {CC"fullGC",   CC"()V",                             (void*)&WB_FullGC },
2740   {CC"youngGC",  CC"()V",                             (void*)&WB_YoungGC },
2741   {CC"readReservedMemory", CC"()V",                   (void*)&WB_ReadReservedMemory },
2742   {CC"allocateMetaspace",
2743      CC"(Ljava/lang/ClassLoader;J)J",                 (void*)&WB_AllocateMetaspace },
2744   {CC"incMetaspaceCapacityUntilGC", CC"(J)J",         (void*)&WB_IncMetaspaceCapacityUntilGC },
2745   {CC"metaspaceCapacityUntilGC", CC"()J",             (void*)&WB_MetaspaceCapacityUntilGC },
2746   {CC"metaspaceSharedRegionAlignment", CC"()J",       (void*)&WB_MetaspaceSharedRegionAlignment },
2747   {CC"getCPUFeatures",     CC"()Ljava/lang/String;",  (void*)&WB_GetCPUFeatures     },
2748   {CC"getNMethod0",         CC"(Ljava/lang/reflect/Executable;Z)[Ljava/lang/Object;",
2749                                                       (void*)&WB_GetNMethod         },
2750   {CC"forceNMethodSweep",  CC"()V",                   (void*)&WB_ForceNMethodSweep  },
2751   {CC"allocateCodeBlob",   CC"(II)J",                 (void*)&WB_AllocateCodeBlob   },
2752   {CC"freeCodeBlob",       CC"(J)V",                  (void*)&WB_FreeCodeBlob       },
2753   {CC"getCodeHeapEntries", CC"(I)[Ljava/lang/Object;",(void*)&WB_GetCodeHeapEntries },
2754   {CC"getCompilationActivityMode",
2755                            CC"()I",                   (void*)&WB_GetCompilationActivityMode},
2756   {CC"getMethodData0",     CC"(Ljava/lang/reflect/Executable;)J",
2757                                                       (void*)&WB_GetMethodData      },
2758   {CC"getCodeBlob",        CC"(J)[Ljava/lang/Object;",(void*)&WB_GetCodeBlob        },
2759   {CC"getThreadStackSize", CC"()J",                   (void*)&WB_GetThreadStackSize },
2760   {CC"getThreadRemainingStackSize", CC"()J",          (void*)&WB_GetThreadRemainingStackSize },
2761   {CC"DefineModule",       CC"(Ljava/lang/Object;ZLjava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V",
2762                                                       (void*)&WB_DefineModule },
2763   {CC"AddModuleExports",   CC"(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V",
2764                                                       (void*)&WB_AddModuleExports },
2765   {CC"AddReadsModule",     CC"(Ljava/lang/Object;Ljava/lang/Object;)V",
2766                                                       (void*)&WB_AddReadsModule },
2767   {CC"AddModuleExportsToAllUnnamed", CC"(Ljava/lang/Object;Ljava/lang/String;)V",
2768                                                       (void*)&WB_AddModuleExportsToAllUnnamed },
2769   {CC"AddModuleExportsToAll", CC"(Ljava/lang/Object;Ljava/lang/String;)V",
2770                                                       (void*)&WB_AddModuleExportsToAll },
2771   {CC"deflateIdleMonitors", CC"()Z",                  (void*)&WB_DeflateIdleMonitors },
2772   {CC"isMonitorInflated0", CC"(Ljava/lang/Object;)Z", (void*)&WB_IsMonitorInflated  },
2773   {CC"forceSafepoint",     CC"()V",                   (void*)&WB_ForceSafepoint     },
2774   {CC"getConstantPool0",   CC"(Ljava/lang/Class;)J",  (void*)&WB_GetConstantPool    },
2775   {CC"getConstantPoolCacheIndexTag0", CC"()I",  (void*)&WB_GetConstantPoolCacheIndexTag},
2776   {CC"getConstantPoolCacheLength0", CC"(Ljava/lang/Class;)I",  (void*)&WB_GetConstantPoolCacheLength},
2777   {CC"remapInstructionOperandFromCPCache0",
2778       CC"(Ljava/lang/Class;I)I",                      (void*)&WB_ConstantPoolRemapInstructionOperandFromCache},
2779   {CC"encodeConstantPoolIndyIndex0",
2780       CC"(I)I",                      (void*)&WB_ConstantPoolEncodeIndyIndex},
2781   {CC"getObjectsViaKlassOopMaps0",
2782       CC"(Ljava/lang/Object;)[Ljava/lang/Object;",    (void*)&WB_getObjectsViaKlassOopMaps},
2783   {CC"getObjectsViaOopIterator0",
2784           CC"(Ljava/lang/Object;)[Ljava/lang/Object;",(void*)&WB_getObjectsViaOopIterator},
2785   {CC"getObjectsViaFrameOopIterator",
2786       CC"(I)[Ljava/lang/Object;",                     (void*)&WB_getObjectsViaFrameOopIterator},
2787   {CC"getMethodBooleanOption",
2788       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Boolean;",
2789                                                       (void*)&WB_GetMethodBooleaneOption},
2790   {CC"getMethodIntxOption",
2791       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
2792                                                       (void*)&WB_GetMethodIntxOption},
2793   {CC"getMethodUintxOption",
2794       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
2795                                                       (void*)&WB_GetMethodUintxOption},
2796   {CC"getMethodDoubleOption",
2797       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Double;",
2798                                                       (void*)&WB_GetMethodDoubleOption},
2799   {CC"getMethodStringOption",
2800       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/String;",
2801                                                       (void*)&WB_GetMethodStringOption},
2802   {CC"getDefaultArchivePath",             CC"()Ljava/lang/String;",
2803                                                       (void*)&WB_GetDefaultArchivePath},
2804   {CC"getCDSGenericHeaderMinVersion",     CC"()I",    (void*)&WB_GetCDSGenericHeaderMinVersion},
2805   {CC"getCurrentCDSVersion",              CC"()I",    (void*)&WB_GetCDSCurrentVersion},
2806   {CC"isSharingEnabled",   CC"()Z",                   (void*)&WB_IsSharingEnabled},
2807   {CC"isShared",           CC"(Ljava/lang/Object;)Z", (void*)&WB_IsShared },
2808   {CC"isSharedInternedString", CC"(Ljava/lang/String;)Z", (void*)&WB_IsSharedInternedString },
2809   {CC"isSharedClass",      CC"(Ljava/lang/Class;)Z",  (void*)&WB_IsSharedClass },
2810   {CC"areSharedStringsMapped",            CC"()Z",    (void*)&WB_AreSharedStringsMapped },
2811   {CC"getResolvedReferences", CC"(Ljava/lang/Class;)Ljava/lang/Object;", (void*)&WB_GetResolvedReferences},
2812   {CC"linkClass",          CC"(Ljava/lang/Class;)V",  (void*)&WB_LinkClass},
2813   {CC"areOpenArchiveHeapObjectsMapped",   CC"()Z",    (void*)&WB_AreOpenArchiveHeapObjectsMapped},
2814   {CC"isCDSIncluded",                     CC"()Z",    (void*)&WB_IsCDSIncluded },
2815   {CC"isJFRIncluded",                     CC"()Z",    (void*)&WB_IsJFRIncluded },
2816   {CC"isDTraceIncluded",                  CC"()Z",    (void*)&WB_IsDTraceIncluded },
2817   {CC"isC2OrJVMCIIncluded",               CC"()Z",    (void*)&WB_isC2OrJVMCIIncluded },
2818   {CC"isJVMCISupportedByGC",              CC"()Z",    (void*)&WB_IsJVMCISupportedByGC},
2819   {CC"canWriteJavaHeapArchive",           CC"()Z",    (void*)&WB_CanWriteJavaHeapArchive },
2820   {CC"cdsMemoryMappingFailed",            CC"()Z",    (void*)&WB_CDSMemoryMappingFailed },
2821 
2822   {CC"clearInlineCaches0",  CC"(Z)V",                 (void*)&WB_ClearInlineCaches },
2823   {CC"handshakeReadMonitors", CC"(Ljava/lang/Thread;)Z", (void*)&WB_HandshakeReadMonitors },
2824   {CC"handshakeWalkStack", CC"(Ljava/lang/Thread;Z)I", (void*)&WB_HandshakeWalkStack },
2825   {CC"asyncHandshakeWalkStack", CC"(Ljava/lang/Thread;)V", (void*)&WB_AsyncHandshakeWalkStack },
2826   {CC"lockAndBlock", CC"(Z)V",                        (void*)&WB_LockAndBlock},
2827   {CC"checkThreadObjOfTerminatingThread", CC"(Ljava/lang/Thread;)V", (void*)&WB_CheckThreadObjOfTerminatingThread },
2828   {CC"verifyFrames",                CC"(ZZ)V",            (void*)&WB_VerifyFrames },
2829   {CC"addCompilerDirective",    CC"(Ljava/lang/String;)I",
2830                                                       (void*)&WB_AddCompilerDirective },
2831   {CC"removeCompilerDirective",   CC"(I)V",           (void*)&WB_RemoveCompilerDirective },
2832   {CC"isGCSupported",             CC"(I)Z",           (void*)&WB_IsGCSupported},
2833   {CC"isGCSupportedByJVMCICompiler", CC"(I)Z",        (void*)&WB_IsGCSupportedByJVMCICompiler},
2834   {CC"isGCSelected",              CC"(I)Z",           (void*)&WB_IsGCSelected},
2835   {CC"isGCSelectedErgonomically", CC"()Z",            (void*)&WB_IsGCSelectedErgonomically},
2836   {CC"supportsConcurrentGCBreakpoints", CC"()Z",      (void*)&WB_SupportsConcurrentGCBreakpoints},
2837   {CC"concurrentGCAcquireControl0", CC"()V",          (void*)&WB_ConcurrentGCAcquireControl},
2838   {CC"concurrentGCReleaseControl0", CC"()V",          (void*)&WB_ConcurrentGCReleaseControl},
2839   {CC"concurrentGCRunToIdle0",    CC"()V",            (void*)&WB_ConcurrentGCRunToIdle},
2840   {CC"concurrentGCRunTo0",        CC"(Ljava/lang/String;)Z",
2841                                                       (void*)&WB_ConcurrentGCRunTo},
2842   {CC"checkLibSpecifiesNoexecstack", CC"(Ljava/lang/String;)Z",
2843                                                       (void*)&WB_CheckLibSpecifiesNoexecstack},
2844   {CC"isContainerized",           CC"()Z",            (void*)&WB_IsContainerized },
2845   {CC"validateCgroup",
2846       CC"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I",
2847                                                       (void*)&WB_ValidateCgroup },
2848   {CC"printOsInfo",               CC"()V",            (void*)&WB_PrintOsInfo },
2849   {CC"disableElfSectionCache",    CC"()V",            (void*)&WB_DisableElfSectionCache },
2850   {CC"resolvedMethodItemsCount",  CC"()J",            (void*)&WB_ResolvedMethodItemsCount },
2851   {CC"protectionDomainRemovedCount",   CC"()I",       (void*)&WB_ProtectionDomainRemovedCount },
2852   {CC"getKlassMetadataSize", CC"(Ljava/lang/Class;)I",(void*)&WB_GetKlassMetadataSize},
2853 
2854   {CC"createMetaspaceTestContext", CC"(JJ)J",         (void*)&WB_CreateMetaspaceTestContext},
2855   {CC"destroyMetaspaceTestContext", CC"(J)V",         (void*)&WB_DestroyMetaspaceTestContext},
2856   {CC"purgeMetaspaceTestContext", CC"(J)V",           (void*)&WB_PurgeMetaspaceTestContext},
2857   {CC"printMetaspaceTestContext", CC"(J)V",           (void*)&WB_PrintMetaspaceTestContext},
2858   {CC"getTotalCommittedWordsInMetaspaceTestContext", CC"(J)J",(void*)&WB_GetTotalCommittedWordsInMetaspaceTestContext},
2859   {CC"getTotalUsedWordsInMetaspaceTestContext", CC"(J)J", (void*)&WB_GetTotalUsedWordsInMetaspaceTestContext},
2860   {CC"createArenaInTestContext", CC"(JZ)J",           (void*)&WB_CreateArenaInTestContext},
2861   {CC"destroyMetaspaceTestArena", CC"(J)V",           (void*)&WB_DestroyMetaspaceTestArena},
2862   {CC"allocateFromMetaspaceTestArena", CC"(JJ)J",     (void*)&WB_AllocateFromMetaspaceTestArena},
2863   {CC"deallocateToMetaspaceTestArena", CC"(JJJ)V",    (void*)&WB_DeallocateToMetaspaceTestArena},
2864   {CC"maxMetaspaceAllocationSize", CC"()J",           (void*)&WB_GetMaxMetaspaceAllocationSize},
2865 
2866   {CC"isJVMTIIncluded", CC"()Z",                      (void*)&WB_IsJVMTIIncluded},
2867   {CC"waitUnsafe", CC"(I)V",                          (void*)&WB_WaitUnsafe},
2868   {CC"getLibcName",     CC"()Ljava/lang/String;",     (void*)&WB_GetLibcName},
2869 
2870   {CC"lockCritical",    CC"()V",                      (void*)&WB_LockCritical},
2871   {CC"unlockCritical",  CC"()V",                      (void*)&WB_UnlockCritical},
2872 };
2873 
2874 
2875 #undef CC
2876 
2877 JVM_ENTRY(void, JVM_RegisterWhiteBoxMethods(JNIEnv* env, jclass wbclass))
2878   {
2879     if (WhiteBoxAPI) {
2880       // Make sure that wbclass is loaded by the null classloader
2881       InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(wbclass)));
2882       Handle loader(THREAD, ik->class_loader());
2883       if (loader.is_null()) {
2884         WhiteBox::register_methods(env, wbclass, thread, methods, sizeof(methods) / sizeof(methods[0]));
2885         WhiteBox::set_used();
2886       }
2887     }
2888   }
2889 JVM_END