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