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