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