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