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