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