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