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