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