1 /*
   2  * Copyright (c) 2012, 2018, 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 
  27 #include <new>
  28 
  29 #include "classfile/classLoaderData.hpp"
  30 #include "classfile/modules.hpp"
  31 #include "classfile/stringTable.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "compiler/methodMatcher.hpp"
  34 #include "compiler/directivesParser.hpp"
  35 #include "jvmtifiles/jvmtiEnv.hpp"
  36 #include "memory/metadataFactory.hpp"
  37 #include "memory/metaspaceShared.hpp"
  38 #include "memory/iterator.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "memory/universe.hpp"
  41 #include "memory/oopFactory.hpp"
  42 #include "oops/array.hpp"
  43 #include "oops/constantPool.inline.hpp"
  44 #include "oops/method.inline.hpp"
  45 #include "oops/objArrayKlass.hpp"
  46 #include "oops/objArrayOop.inline.hpp"
  47 #include "oops/oop.inline.hpp"
  48 #include "oops/typeArrayOop.inline.hpp"
  49 #include "prims/wbtestmethods/parserTests.hpp"
  50 #include "prims/whitebox.hpp"
  51 #include "runtime/arguments.hpp"
  52 #include "runtime/compilationPolicy.hpp"
  53 #include "runtime/deoptimization.hpp"
  54 #include "runtime/handshake.hpp"
  55 #include "runtime/interfaceSupport.hpp"
  56 #include "runtime/javaCalls.hpp"
  57 #include "runtime/jniHandles.inline.hpp"
  58 #include "runtime/os.hpp"
  59 #include "runtime/sweeper.hpp"
  60 #include "runtime/thread.hpp"
  61 #include "runtime/threadSMR.hpp"
  62 #include "runtime/vm_version.hpp"
  63 #include "utilities/align.hpp"
  64 #include "utilities/debug.hpp"
  65 #include "utilities/elfFile.hpp"
  66 #include "utilities/exceptions.hpp"
  67 #include "utilities/macros.hpp"
  68 #if INCLUDE_CDS
  69 #include "prims/cdsoffsets.hpp"
  70 #endif // INCLUDE_CDS
  71 #if INCLUDE_ALL_GCS
  72 #include "gc/g1/concurrentMarkThread.hpp"
  73 #include "gc/g1/g1CollectedHeap.inline.hpp"
  74 #include "gc/g1/g1ConcurrentMark.hpp"
  75 #include "gc/g1/heapRegionRemSet.hpp"
  76 #include "gc/parallel/parallelScavengeHeap.inline.hpp"
  77 #include "gc/parallel/adjoiningGenerations.hpp"
  78 #endif // INCLUDE_ALL_GCS
  79 #if INCLUDE_NMT
  80 #include "services/mallocSiteTable.hpp"
  81 #include "services/memTracker.hpp"
  82 #include "utilities/nativeCallStack.hpp"
  83 #endif // INCLUDE_NMT
  84 
  85 #ifdef LINUX
  86 #include "osContainer_linux.hpp"
  87 #endif
  88 
  89 #define SIZE_T_MAX_VALUE ((size_t) -1)
  90 
  91 bool WhiteBox::_used = false;
  92 volatile bool WhiteBox::compilation_locked = false;
  93 
  94 class VM_WhiteBoxOperation : public VM_Operation {
  95  public:
  96   VM_WhiteBoxOperation()                         { }
  97   VMOp_Type type()                  const        { return VMOp_WhiteBoxOperation; }
  98   bool allow_nested_vm_operations() const        { return true; }
  99 };
 100 
 101 
 102 WB_ENTRY(jlong, WB_GetObjectAddress(JNIEnv* env, jobject o, jobject obj))
 103   return (jlong)(void*)JNIHandles::resolve(obj);
 104 WB_END
 105 
 106 WB_ENTRY(jint, WB_GetHeapOopSize(JNIEnv* env, jobject o))
 107   return heapOopSize;
 108 WB_END
 109 
 110 WB_ENTRY(jint, WB_GetVMPageSize(JNIEnv* env, jobject o))
 111   return os::vm_page_size();
 112 WB_END
 113 
 114 WB_ENTRY(jlong, WB_GetVMAllocationGranularity(JNIEnv* env, jobject o))
 115   return os::vm_allocation_granularity();
 116 WB_END
 117 
 118 WB_ENTRY(jlong, WB_GetVMLargePageSize(JNIEnv* env, jobject o))
 119   return os::large_page_size();
 120 WB_END
 121 
 122 class WBIsKlassAliveClosure : public KlassClosure {
 123     Symbol* _name;
 124     bool _found;
 125 public:
 126     WBIsKlassAliveClosure(Symbol* name) : _name(name), _found(false) {}
 127 
 128     void do_klass(Klass* k) {
 129       if (_found) return;
 130       Symbol* ksym = k->name();
 131       if (ksym->fast_compare(_name) == 0) {
 132         _found = true;
 133       }
 134     }
 135 
 136     bool found() const {
 137         return _found;
 138     }
 139 };
 140 
 141 WB_ENTRY(jboolean, WB_IsClassAlive(JNIEnv* env, jobject target, jstring name))
 142   oop h_name = JNIHandles::resolve(name);
 143   if (h_name == NULL) return false;
 144   Symbol* sym = java_lang_String::as_symbol(h_name, CHECK_false);
 145   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
 146 
 147   WBIsKlassAliveClosure closure(sym);
 148   ClassLoaderDataGraph::classes_do(&closure);
 149 
 150   return closure.found();
 151 WB_END
 152 
 153 WB_ENTRY(void, WB_AddToBootstrapClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 154 #if INCLUDE_JVMTI
 155   ResourceMark rm;
 156   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 157   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 158   jvmtiError err = jvmti_env->AddToBootstrapClassLoaderSearch(seg);
 159   assert(err == JVMTI_ERROR_NONE, "must not fail");
 160 #endif
 161 }
 162 WB_END
 163 
 164 WB_ENTRY(void, WB_AddToSystemClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 165 #if INCLUDE_JVMTI
 166   ResourceMark rm;
 167   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 168   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 169   jvmtiError err = jvmti_env->AddToSystemClassLoaderSearch(seg);
 170   assert(err == JVMTI_ERROR_NONE, "must not fail");
 171 #endif
 172 }
 173 WB_END
 174 
 175 
 176 WB_ENTRY(jlong, WB_GetCompressedOopsMaxHeapSize(JNIEnv* env, jobject o)) {
 177   return (jlong)Arguments::max_heap_for_compressed_oops();
 178 }
 179 WB_END
 180 
 181 WB_ENTRY(void, WB_PrintHeapSizes(JNIEnv* env, jobject o)) {
 182   CollectorPolicy * p = Universe::heap()->collector_policy();
 183   tty->print_cr("Minimum heap " SIZE_FORMAT " Initial heap "
 184     SIZE_FORMAT " Maximum heap " SIZE_FORMAT " Space alignment " SIZE_FORMAT " Heap alignment " SIZE_FORMAT,
 185     p->min_heap_byte_size(), p->initial_heap_byte_size(), p->max_heap_byte_size(),
 186     p->space_alignment(), p->heap_alignment());
 187 }
 188 WB_END
 189 
 190 #ifndef PRODUCT
 191 // Forward declaration
 192 void TestReservedSpace_test();
 193 void TestReserveMemorySpecial_test();
 194 void TestVirtualSpace_test();
 195 void TestMetaspaceUtils_test();
 196 #endif
 197 
 198 WB_ENTRY(void, WB_RunMemoryUnitTests(JNIEnv* env, jobject o))
 199 #ifndef PRODUCT
 200   TestReservedSpace_test();
 201   TestReserveMemorySpecial_test();
 202   TestVirtualSpace_test();
 203   TestMetaspaceUtils_test();
 204 #endif
 205 WB_END
 206 
 207 WB_ENTRY(void, WB_ReadFromNoaccessArea(JNIEnv* env, jobject o))
 208   size_t granularity = os::vm_allocation_granularity();
 209   ReservedHeapSpace rhs(100 * granularity, granularity, false);
 210   VirtualSpace vs;
 211   vs.initialize(rhs, 50 * granularity);
 212 
 213   // Check if constraints are complied
 214   if (!( UseCompressedOops && rhs.base() != NULL &&
 215          Universe::narrow_oop_base() != NULL &&
 216          Universe::narrow_oop_use_implicit_null_checks() )) {
 217     tty->print_cr("WB_ReadFromNoaccessArea method is useless:\n "
 218                   "\tUseCompressedOops is %d\n"
 219                   "\trhs.base() is " PTR_FORMAT "\n"
 220                   "\tUniverse::narrow_oop_base() is " PTR_FORMAT "\n"
 221                   "\tUniverse::narrow_oop_use_implicit_null_checks() is %d",
 222                   UseCompressedOops,
 223                   p2i(rhs.base()),
 224                   p2i(Universe::narrow_oop_base()),
 225                   Universe::narrow_oop_use_implicit_null_checks());
 226     return;
 227   }
 228   tty->print_cr("Reading from no access area... ");
 229   tty->print_cr("*(vs.low_boundary() - rhs.noaccess_prefix() / 2 ) = %c",
 230                 *(vs.low_boundary() - rhs.noaccess_prefix() / 2 ));
 231 WB_END
 232 
 233 static jint wb_stress_virtual_space_resize(size_t reserved_space_size,
 234                                            size_t magnitude, size_t iterations) {
 235   size_t granularity = os::vm_allocation_granularity();
 236   ReservedHeapSpace rhs(reserved_space_size * granularity, granularity, false);
 237   VirtualSpace vs;
 238   if (!vs.initialize(rhs, 0)) {
 239     tty->print_cr("Failed to initialize VirtualSpace. Can't proceed.");
 240     return 3;
 241   }
 242 
 243   int seed = os::random();
 244   tty->print_cr("Random seed is %d", seed);
 245   os::init_random(seed);
 246 
 247   for (size_t i = 0; i < iterations; i++) {
 248 
 249     // Whether we will shrink or grow
 250     bool shrink = os::random() % 2L == 0;
 251 
 252     // Get random delta to resize virtual space
 253     size_t delta = (size_t)os::random() % magnitude;
 254 
 255     // If we are about to shrink virtual space below zero, then expand instead
 256     if (shrink && vs.committed_size() < delta) {
 257       shrink = false;
 258     }
 259 
 260     // Resizing by delta
 261     if (shrink) {
 262       vs.shrink_by(delta);
 263     } else {
 264       // If expanding fails expand_by will silently return false
 265       vs.expand_by(delta, true);
 266     }
 267   }
 268   return 0;
 269 }
 270 
 271 WB_ENTRY(jint, WB_StressVirtualSpaceResize(JNIEnv* env, jobject o,
 272         jlong reserved_space_size, jlong magnitude, jlong iterations))
 273   tty->print_cr("reservedSpaceSize=" JLONG_FORMAT ", magnitude=" JLONG_FORMAT ", "
 274                 "iterations=" JLONG_FORMAT "\n", reserved_space_size, magnitude,
 275                 iterations);
 276   if (reserved_space_size < 0 || magnitude < 0 || iterations < 0) {
 277     tty->print_cr("One of variables printed above is negative. Can't proceed.\n");
 278     return 1;
 279   }
 280 
 281   // sizeof(size_t) depends on whether OS is 32bit or 64bit. sizeof(jlong) is
 282   // always 8 byte. That's why we should avoid overflow in case of 32bit platform.
 283   if (sizeof(size_t) < sizeof(jlong)) {
 284     jlong size_t_max_value = (jlong) SIZE_T_MAX_VALUE;
 285     if (reserved_space_size > size_t_max_value || magnitude > size_t_max_value
 286         || iterations > size_t_max_value) {
 287       tty->print_cr("One of variables printed above overflows size_t. Can't proceed.\n");
 288       return 2;
 289     }
 290   }
 291 
 292   return wb_stress_virtual_space_resize((size_t) reserved_space_size,
 293                                         (size_t) magnitude, (size_t) iterations);
 294 WB_END
 295 
 296 static const jint serial_code   = 1;
 297 static const jint parallel_code = 2;
 298 static const jint cms_code      = 4;
 299 static const jint g1_code       = 8;
 300 
 301 WB_ENTRY(jint, WB_CurrentGC(JNIEnv* env, jobject o, jobject obj))
 302   if (UseSerialGC) {
 303     return serial_code;
 304   } else if (UseParallelGC || UseParallelOldGC) {
 305     return parallel_code;
 306   } if (UseConcMarkSweepGC) {
 307     return cms_code;
 308   } else if (UseG1GC) {
 309     return g1_code;
 310   }
 311   ShouldNotReachHere();
 312   return 0;
 313 WB_END
 314 
 315 WB_ENTRY(jint, WB_AllSupportedGC(JNIEnv* env, jobject o, jobject obj))
 316 #if INCLUDE_ALL_GCS
 317   return serial_code | parallel_code | cms_code | g1_code;
 318 #else
 319   return serial_code;
 320 #endif // INCLUDE_ALL_GCS
 321 WB_END
 322 
 323 WB_ENTRY(jboolean, WB_GCSelectedByErgo(JNIEnv* env, jobject o, jobject obj))
 324   if (UseSerialGC) {
 325     return FLAG_IS_ERGO(UseSerialGC);
 326   } else if (UseParallelGC) {
 327     return FLAG_IS_ERGO(UseParallelGC);
 328   } else if (UseParallelOldGC) {
 329     return FLAG_IS_ERGO(UseParallelOldGC);
 330   } else if (UseConcMarkSweepGC) {
 331     return FLAG_IS_ERGO(UseConcMarkSweepGC);
 332   } else if (UseG1GC) {
 333     return FLAG_IS_ERGO(UseG1GC);
 334   }
 335   ShouldNotReachHere();
 336   return false;
 337 WB_END
 338 
 339 WB_ENTRY(jboolean, WB_isObjectInOldGen(JNIEnv* env, jobject o, jobject obj))
 340   oop p = JNIHandles::resolve(obj);
 341 #if INCLUDE_ALL_GCS
 342   if (UseG1GC) {
 343     G1CollectedHeap* g1 = G1CollectedHeap::heap();
 344     const HeapRegion* hr = g1->heap_region_containing(p);
 345     if (hr == NULL) {
 346       return false;
 347     }
 348     return !(hr->is_young());
 349   } else if (UseParallelGC) {
 350     ParallelScavengeHeap* psh = ParallelScavengeHeap::heap();
 351     return !psh->is_in_young(p);
 352   }
 353 #endif // INCLUDE_ALL_GCS
 354   GenCollectedHeap* gch = GenCollectedHeap::heap();
 355   return !gch->is_in_young(p);
 356 WB_END
 357 
 358 WB_ENTRY(jlong, WB_GetObjectSize(JNIEnv* env, jobject o, jobject obj))
 359   oop p = JNIHandles::resolve(obj);
 360   return p->size() * HeapWordSize;
 361 WB_END
 362 
 363 WB_ENTRY(jlong, WB_GetHeapSpaceAlignment(JNIEnv* env, jobject o))
 364   size_t alignment = Universe::heap()->collector_policy()->space_alignment();
 365   return (jlong)alignment;
 366 WB_END
 367 
 368 WB_ENTRY(jlong, WB_GetHeapAlignment(JNIEnv* env, jobject o))
 369   size_t alignment = Universe::heap()->collector_policy()->heap_alignment();
 370   return (jlong)alignment;
 371 WB_END
 372 
 373 WB_ENTRY(jboolean, WB_SupportsConcurrentGCPhaseControl(JNIEnv* env, jobject o))
 374   return Universe::heap()->supports_concurrent_phase_control();
 375 WB_END
 376 
 377 WB_ENTRY(jobjectArray, WB_GetConcurrentGCPhases(JNIEnv* env, jobject o))
 378   const char* const* phases = Universe::heap()->concurrent_phases();
 379   jint nphases = 0;
 380   for ( ; phases[nphases] != NULL; ++nphases) ;
 381 
 382   ResourceMark rm(thread);
 383   ThreadToNativeFromVM ttn(thread);
 384   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
 385   CHECK_JNI_EXCEPTION_(env, NULL);
 386 
 387   jobjectArray result = env->NewObjectArray(nphases, clazz, NULL);
 388   CHECK_JNI_EXCEPTION_(env, NULL);
 389 
 390   // If push fails, return with pending exception.
 391   if (env->PushLocalFrame(nphases) < 0) return NULL;
 392   for (jint i = 0; i < nphases; ++i) {
 393     jstring phase = env->NewStringUTF(phases[i]);
 394     CHECK_JNI_EXCEPTION_(env, NULL);
 395     env->SetObjectArrayElement(result, i, phase);
 396     CHECK_JNI_EXCEPTION_(env, NULL);
 397   }
 398   env->PopLocalFrame(NULL);
 399 
 400   return result;
 401 WB_END
 402 
 403 WB_ENTRY(jboolean, WB_RequestConcurrentGCPhase(JNIEnv* env, jobject o, jstring name))
 404   Handle h_name(THREAD, JNIHandles::resolve(name));
 405   ResourceMark rm;
 406   const char* c_name = java_lang_String::as_utf8_string(h_name());
 407   return Universe::heap()->request_concurrent_phase(c_name);
 408 WB_END
 409 
 410 #if INCLUDE_ALL_GCS
 411 WB_ENTRY(jboolean, WB_G1IsHumongous(JNIEnv* env, jobject o, jobject obj))
 412   if (UseG1GC) {
 413     G1CollectedHeap* g1 = G1CollectedHeap::heap();
 414     oop result = JNIHandles::resolve(obj);
 415     const HeapRegion* hr = g1->heap_region_containing(result);
 416     return hr->is_humongous();
 417   }
 418   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1IsHumongous: G1 GC is not enabled");
 419 WB_END
 420 
 421 WB_ENTRY(jboolean, WB_G1BelongsToHumongousRegion(JNIEnv* env, jobject o, jlong addr))
 422   if (UseG1GC) {
 423     G1CollectedHeap* g1 = G1CollectedHeap::heap();
 424     const HeapRegion* hr = g1->heap_region_containing((void*) addr);
 425     return hr->is_humongous();
 426   }
 427   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1BelongsToHumongousRegion: G1 GC is not enabled");
 428 WB_END
 429 
 430 WB_ENTRY(jboolean, WB_G1BelongsToFreeRegion(JNIEnv* env, jobject o, jlong addr))
 431   if (UseG1GC) {
 432     G1CollectedHeap* g1 = G1CollectedHeap::heap();
 433     const HeapRegion* hr = g1->heap_region_containing((void*) addr);
 434     return hr->is_free();
 435   }
 436   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1BelongsToFreeRegion: G1 GC is not enabled");
 437 WB_END
 438 
 439 WB_ENTRY(jlong, WB_G1NumMaxRegions(JNIEnv* env, jobject o))
 440   if (UseG1GC) {
 441     G1CollectedHeap* g1 = G1CollectedHeap::heap();
 442     size_t nr = g1->max_regions();
 443     return (jlong)nr;
 444   }
 445   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1NumMaxRegions: G1 GC is not enabled");
 446 WB_END
 447 
 448 WB_ENTRY(jlong, WB_G1NumFreeRegions(JNIEnv* env, jobject o))
 449   if (UseG1GC) {
 450     G1CollectedHeap* g1 = G1CollectedHeap::heap();
 451     size_t nr = g1->num_free_regions();
 452     return (jlong)nr;
 453   }
 454   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1NumFreeRegions: G1 GC is not enabled");
 455 WB_END
 456 
 457 WB_ENTRY(jboolean, WB_G1InConcurrentMark(JNIEnv* env, jobject o))
 458   if (UseG1GC) {
 459     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 460     return g1h->concurrent_mark()->cm_thread()->during_cycle();
 461   }
 462   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1InConcurrentMark: G1 GC is not enabled");
 463 WB_END
 464 
 465 WB_ENTRY(jboolean, WB_G1StartMarkCycle(JNIEnv* env, jobject o))
 466   if (UseG1GC) {
 467     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 468     if (!g1h->concurrent_mark()->cm_thread()->during_cycle()) {
 469       g1h->collect(GCCause::_wb_conc_mark);
 470       return true;
 471     }
 472     return false;
 473   }
 474   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1StartMarkCycle: G1 GC is not enabled");
 475 WB_END
 476 
 477 WB_ENTRY(jint, WB_G1RegionSize(JNIEnv* env, jobject o))
 478   if (UseG1GC) {
 479     return (jint)HeapRegion::GrainBytes;
 480   }
 481   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1RegionSize: G1 GC is not enabled");
 482 WB_END
 483 
 484 WB_ENTRY(jlong, WB_PSVirtualSpaceAlignment(JNIEnv* env, jobject o))
 485 #if INCLUDE_ALL_GCS
 486   if (UseParallelGC) {
 487     return ParallelScavengeHeap::heap()->gens()->virtual_spaces()->alignment();
 488   }
 489 #endif // INCLUDE_ALL_GCS
 490   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_PSVirtualSpaceAlignment: Parallel GC is not enabled");
 491 WB_END
 492 
 493 WB_ENTRY(jlong, WB_PSHeapGenerationAlignment(JNIEnv* env, jobject o))
 494 #if INCLUDE_ALL_GCS
 495   if (UseParallelGC) {
 496     return ParallelScavengeHeap::heap()->generation_alignment();
 497   }
 498 #endif // INCLUDE_ALL_GCS
 499   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_PSHeapGenerationAlignment: Parallel GC is not enabled");
 500 WB_END
 501 
 502 WB_ENTRY(jobject, WB_G1AuxiliaryMemoryUsage(JNIEnv* env))
 503 #if INCLUDE_ALL_GCS
 504   if (UseG1GC) {
 505     ResourceMark rm(THREAD);
 506     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 507     MemoryUsage usage = g1h->get_auxiliary_data_memory_usage();
 508     Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
 509     return JNIHandles::make_local(env, h());
 510   }
 511 #endif // INCLUDE_ALL_GCS
 512   THROW_MSG_0(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1AuxiliaryMemoryUsage: G1 GC is not enabled");
 513 WB_END
 514 
 515 class OldRegionsLivenessClosure: public HeapRegionClosure {
 516 
 517  private:
 518   const int _liveness;
 519   size_t _total_count;
 520   size_t _total_memory;
 521   size_t _total_memory_to_free;
 522 
 523  public:
 524   OldRegionsLivenessClosure(int liveness) :
 525     _liveness(liveness),
 526     _total_count(0),
 527     _total_memory(0),
 528     _total_memory_to_free(0) { }
 529 
 530     size_t total_count() { return _total_count; }
 531     size_t total_memory() { return _total_memory; }
 532     size_t total_memory_to_free() { return _total_memory_to_free; }
 533 
 534   bool do_heap_region(HeapRegion* r) {
 535     if (r->is_old()) {
 536       size_t prev_live = r->marked_bytes();
 537       size_t live = r->live_bytes();
 538       size_t size = r->used();
 539       size_t reg_size = HeapRegion::GrainBytes;
 540       if (size > 0 && ((int)(live * 100 / size) < _liveness)) {
 541         _total_memory += size;
 542         ++_total_count;
 543         if (size == reg_size) {
 544         // we don't include non-full regions since they are unlikely included in mixed gc
 545         // for testing purposes it's enough to have lowest estimation of total memory that is expected to be freed
 546           _total_memory_to_free += size - prev_live;
 547         }
 548       }
 549     }
 550     return false;
 551   }
 552 };
 553 
 554 
 555 WB_ENTRY(jlongArray, WB_G1GetMixedGCInfo(JNIEnv* env, jobject o, jint liveness))
 556   if (!UseG1GC) {
 557     THROW_MSG_NULL(vmSymbols::java_lang_UnsupportedOperationException(), "WB_G1GetMixedGCInfo: G1 GC is not enabled");
 558   }
 559   if (liveness < 0) {
 560     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "liveness value should be non-negative");
 561   }
 562 
 563   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 564   OldRegionsLivenessClosure rli(liveness);
 565   g1h->heap_region_iterate(&rli);
 566 
 567   typeArrayOop result = oopFactory::new_longArray(3, CHECK_NULL);
 568   result->long_at_put(0, rli.total_count());
 569   result->long_at_put(1, rli.total_memory());
 570   result->long_at_put(2, rli.total_memory_to_free());
 571   return (jlongArray) JNIHandles::make_local(env, result);
 572 WB_END
 573 
 574 #endif // INCLUDE_ALL_GCS
 575 
 576 #if INCLUDE_NMT
 577 // Alloc memory using the test memory type so that we can use that to see if
 578 // NMT picks it up correctly
 579 WB_ENTRY(jlong, WB_NMTMalloc(JNIEnv* env, jobject o, jlong size))
 580   jlong addr = 0;
 581   addr = (jlong)(uintptr_t)os::malloc(size, mtTest);
 582   return addr;
 583 WB_END
 584 
 585 // Alloc memory with pseudo call stack. The test can create psudo malloc
 586 // allocation site to stress the malloc tracking.
 587 WB_ENTRY(jlong, WB_NMTMallocWithPseudoStack(JNIEnv* env, jobject o, jlong size, jint pseudo_stack))
 588   address pc = (address)(size_t)pseudo_stack;
 589   NativeCallStack stack(&pc, 1);
 590   return (jlong)(uintptr_t)os::malloc(size, mtTest, stack);
 591 WB_END
 592 
 593 // Free the memory allocated by NMTAllocTest
 594 WB_ENTRY(void, WB_NMTFree(JNIEnv* env, jobject o, jlong mem))
 595   os::free((void*)(uintptr_t)mem);
 596 WB_END
 597 
 598 WB_ENTRY(jlong, WB_NMTReserveMemory(JNIEnv* env, jobject o, jlong size))
 599   jlong addr = 0;
 600 
 601   addr = (jlong)(uintptr_t)os::reserve_memory(size);
 602   MemTracker::record_virtual_memory_type((address)addr, mtTest);
 603 
 604   return addr;
 605 WB_END
 606 
 607 WB_ENTRY(jlong, WB_NMTAttemptReserveMemoryAt(JNIEnv* env, jobject o, jlong addr, jlong size))
 608   addr = (jlong)(uintptr_t)os::attempt_reserve_memory_at((size_t)size, (char*)(uintptr_t)addr);
 609   MemTracker::record_virtual_memory_type((address)addr, mtTest);
 610 
 611   return addr;
 612 WB_END
 613 
 614 WB_ENTRY(void, WB_NMTCommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 615   os::commit_memory((char *)(uintptr_t)addr, size, !ExecMem);
 616   MemTracker::record_virtual_memory_type((address)(uintptr_t)addr, mtTest);
 617 WB_END
 618 
 619 WB_ENTRY(void, WB_NMTUncommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 620   os::uncommit_memory((char *)(uintptr_t)addr, size);
 621 WB_END
 622 
 623 WB_ENTRY(void, WB_NMTReleaseMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 624   os::release_memory((char *)(uintptr_t)addr, size);
 625 WB_END
 626 
 627 WB_ENTRY(jboolean, WB_NMTChangeTrackingLevel(JNIEnv* env))
 628   // Test that we can downgrade NMT levels but not upgrade them.
 629   if (MemTracker::tracking_level() == NMT_off) {
 630     MemTracker::transition_to(NMT_off);
 631     return MemTracker::tracking_level() == NMT_off;
 632   } else {
 633     assert(MemTracker::tracking_level() == NMT_detail, "Should start out as detail tracking");
 634     MemTracker::transition_to(NMT_summary);
 635     assert(MemTracker::tracking_level() == NMT_summary, "Should be summary now");
 636 
 637     // Can't go to detail once NMT is set to summary.
 638     MemTracker::transition_to(NMT_detail);
 639     assert(MemTracker::tracking_level() == NMT_summary, "Should still be summary now");
 640 
 641     // Shutdown sets tracking level to minimal.
 642     MemTracker::shutdown();
 643     assert(MemTracker::tracking_level() == NMT_minimal, "Should be minimal now");
 644 
 645     // Once the tracking level is minimal, we cannot increase to summary.
 646     // The code ignores this request instead of asserting because if the malloc site
 647     // table overflows in another thread, it tries to change the code to summary.
 648     MemTracker::transition_to(NMT_summary);
 649     assert(MemTracker::tracking_level() == NMT_minimal, "Should still be minimal now");
 650 
 651     // Really can never go up to detail, verify that the code would never do this.
 652     MemTracker::transition_to(NMT_detail);
 653     assert(MemTracker::tracking_level() == NMT_minimal, "Should still be minimal now");
 654     return MemTracker::tracking_level() == NMT_minimal;
 655   }
 656 WB_END
 657 
 658 WB_ENTRY(jint, WB_NMTGetHashSize(JNIEnv* env, jobject o))
 659   int hash_size = MallocSiteTable::hash_buckets();
 660   assert(hash_size > 0, "NMT hash_size should be > 0");
 661   return (jint)hash_size;
 662 WB_END
 663 #endif // INCLUDE_NMT
 664 
 665 static jmethodID reflected_method_to_jmid(JavaThread* thread, JNIEnv* env, jobject method) {
 666   assert(method != NULL, "method should not be null");
 667   ThreadToNativeFromVM ttn(thread);
 668   return env->FromReflectedMethod(method);
 669 }
 670 
 671 // Deoptimizes all compiled frames and makes nmethods not entrant if it's requested
 672 class VM_WhiteBoxDeoptimizeFrames : public VM_WhiteBoxOperation {
 673  private:
 674   int _result;
 675   const bool _make_not_entrant;
 676  public:
 677   VM_WhiteBoxDeoptimizeFrames(bool make_not_entrant) :
 678         _result(0), _make_not_entrant(make_not_entrant) { }
 679   int  result() const { return _result; }
 680 
 681   void doit() {
 682     for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
 683       if (t->has_last_Java_frame()) {
 684         for (StackFrameStream fst(t, UseBiasedLocking); !fst.is_done(); fst.next()) {
 685           frame* f = fst.current();
 686           if (f->can_be_deoptimized() && !f->is_deoptimized_frame()) {
 687             RegisterMap* reg_map = fst.register_map();
 688             Deoptimization::deoptimize(t, *f, reg_map);
 689             if (_make_not_entrant) {
 690                 CompiledMethod* cm = CodeCache::find_compiled(f->pc());
 691                 assert(cm != NULL, "sanity check");
 692                 cm->make_not_entrant();
 693             }
 694             ++_result;
 695           }
 696         }
 697       }
 698     }
 699   }
 700 };
 701 
 702 WB_ENTRY(jint, WB_DeoptimizeFrames(JNIEnv* env, jobject o, jboolean make_not_entrant))
 703   VM_WhiteBoxDeoptimizeFrames op(make_not_entrant == JNI_TRUE);
 704   VMThread::execute(&op);
 705   return op.result();
 706 WB_END
 707 
 708 WB_ENTRY(void, WB_DeoptimizeAll(JNIEnv* env, jobject o))
 709   MutexLockerEx mu(Compile_lock);
 710   CodeCache::mark_all_nmethods_for_deoptimization();
 711   VM_Deoptimize op;
 712   VMThread::execute(&op);
 713 WB_END
 714 
 715 WB_ENTRY(jint, WB_DeoptimizeMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 716   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 717   int result = 0;
 718   CHECK_JNI_EXCEPTION_(env, result);
 719   MutexLockerEx mu(Compile_lock);
 720   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 721   if (is_osr) {
 722     result += mh->mark_osr_nmethods();
 723   } else if (mh->code() != NULL) {
 724     mh->code()->mark_for_deoptimization();
 725     ++result;
 726   }
 727   result += CodeCache::mark_for_deoptimization(mh());
 728   if (result > 0) {
 729     VM_Deoptimize op;
 730     VMThread::execute(&op);
 731   }
 732   return result;
 733 WB_END
 734 
 735 WB_ENTRY(jboolean, WB_IsMethodCompiled(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 736   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 737   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 738   MutexLockerEx mu(Compile_lock);
 739   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 740   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 741   if (code == NULL) {
 742     return JNI_FALSE;
 743   }
 744   return (code->is_alive() && !code->is_marked_for_deoptimization());
 745 WB_END
 746 
 747 WB_ENTRY(jboolean, WB_IsMethodCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 748   if (method == NULL || comp_level > MIN2((CompLevel) TieredStopAtLevel, CompLevel_highest_tier)) {
 749     return false;
 750   }
 751   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 752   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 753   MutexLockerEx mu(Compile_lock);
 754   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 755   if (is_osr) {
 756     return CompilationPolicy::can_be_osr_compiled(mh, comp_level);
 757   } else {
 758     return CompilationPolicy::can_be_compiled(mh, comp_level);
 759   }
 760 WB_END
 761 
 762 WB_ENTRY(jboolean, WB_IsMethodQueuedForCompilation(JNIEnv* env, jobject o, jobject method))
 763   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 764   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 765   MutexLockerEx mu(Compile_lock);
 766   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 767   return mh->queued_for_compilation();
 768 WB_END
 769 
 770 WB_ENTRY(jboolean, WB_IsIntrinsicAvailable(JNIEnv* env, jobject o, jobject method, jobject compilation_context, jint compLevel))
 771   if (compLevel < CompLevel_none || compLevel > MIN2((CompLevel) TieredStopAtLevel, CompLevel_highest_tier)) {
 772     return false; // Intrinsic is not available on a non-existent compilation level.
 773   }
 774   jmethodID method_id, compilation_context_id;
 775   method_id = reflected_method_to_jmid(thread, env, method);
 776   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 777   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(method_id));
 778 
 779   DirectiveSet* directive;
 780   AbstractCompiler* comp = CompileBroker::compiler((int)compLevel);
 781   assert(comp != NULL, "compiler not available");
 782   if (compilation_context != NULL) {
 783     compilation_context_id = reflected_method_to_jmid(thread, env, compilation_context);
 784     CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 785     methodHandle cch(THREAD, Method::checked_resolve_jmethod_id(compilation_context_id));
 786     directive = DirectivesStack::getMatchingDirective(cch, comp);
 787   } else {
 788     // Calling with NULL matches default directive
 789     directive = DirectivesStack::getDefaultDirective(comp);
 790   }
 791   bool result = comp->is_intrinsic_available(mh, directive);
 792   DirectivesStack::release(directive);
 793   return result;
 794 WB_END
 795 
 796 WB_ENTRY(jint, WB_GetMethodCompilationLevel(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 797   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 798   CHECK_JNI_EXCEPTION_(env, CompLevel_none);
 799   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 800   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 801   return (code != NULL ? code->comp_level() : CompLevel_none);
 802 WB_END
 803 
 804 WB_ENTRY(void, WB_MakeMethodNotCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 805   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 806   CHECK_JNI_EXCEPTION(env);
 807   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 808   if (is_osr) {
 809     mh->set_not_osr_compilable(comp_level, true /* report */, "WhiteBox");
 810   } else {
 811     mh->set_not_compilable(comp_level, true /* report */, "WhiteBox");
 812   }
 813 WB_END
 814 
 815 WB_ENTRY(jint, WB_GetMethodEntryBci(JNIEnv* env, jobject o, jobject method))
 816   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 817   CHECK_JNI_EXCEPTION_(env, InvocationEntryBci);
 818   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 819   CompiledMethod* code = mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false);
 820   return (code != NULL && code->is_osr_method() ? code->osr_entry_bci() : InvocationEntryBci);
 821 WB_END
 822 
 823 WB_ENTRY(jboolean, WB_TestSetDontInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 824   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 825   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 826   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 827   bool result = mh->dont_inline();
 828   mh->set_dont_inline(value == JNI_TRUE);
 829   return result;
 830 WB_END
 831 
 832 WB_ENTRY(jint, WB_GetCompileQueueSize(JNIEnv* env, jobject o, jint comp_level))
 833   if (comp_level == CompLevel_any) {
 834     return CompileBroker::queue_size(CompLevel_full_optimization) /* C2 */ +
 835         CompileBroker::queue_size(CompLevel_full_profile) /* C1 */;
 836   } else {
 837     return CompileBroker::queue_size(comp_level);
 838   }
 839 WB_END
 840 
 841 WB_ENTRY(jboolean, WB_TestSetForceInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 842   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 843   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 844   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 845   bool result = mh->force_inline();
 846   mh->set_force_inline(value == JNI_TRUE);
 847   return result;
 848 WB_END
 849 
 850 bool WhiteBox::compile_method(Method* method, int comp_level, int bci, Thread* THREAD) {
 851   // Screen for unavailable/bad comp level or null method
 852   if (method == NULL || comp_level > MIN2((CompLevel) TieredStopAtLevel, CompLevel_highest_tier) ||
 853       CompileBroker::compiler(comp_level) == NULL) {
 854     return false;
 855   }
 856   methodHandle mh(THREAD, method);
 857   nmethod* nm = CompileBroker::compile_method(mh, bci, comp_level, mh, mh->invocation_count(), CompileTask::Reason_Whitebox, THREAD);
 858   MutexLockerEx mu(Compile_lock);
 859   return (mh->queued_for_compilation() || nm != NULL);
 860 }
 861 
 862 WB_ENTRY(jboolean, WB_EnqueueMethodForCompilation(JNIEnv* env, jobject o, jobject method, jint comp_level, jint bci))
 863   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 864   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 865   return WhiteBox::compile_method(Method::checked_resolve_jmethod_id(jmid), comp_level, bci, THREAD);
 866 WB_END
 867 
 868 WB_ENTRY(jboolean, WB_EnqueueInitializerForCompilation(JNIEnv* env, jobject o, jclass klass, jint comp_level))
 869   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
 870   return WhiteBox::compile_method(ik->class_initializer(), comp_level, InvocationEntryBci, THREAD);
 871 WB_END
 872 
 873 WB_ENTRY(jboolean, WB_ShouldPrintAssembly(JNIEnv* env, jobject o, jobject method, jint comp_level))
 874   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 875   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 876 
 877   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 878   DirectiveSet* directive = DirectivesStack::getMatchingDirective(mh, CompileBroker::compiler(comp_level));
 879   bool result = directive->PrintAssemblyOption;
 880   DirectivesStack::release(directive);
 881 
 882   return result;
 883 WB_END
 884 
 885 WB_ENTRY(jint, WB_MatchesInline(JNIEnv* env, jobject o, jobject method, jstring pattern))
 886   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 887   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 888 
 889   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 890 
 891   ResourceMark rm;
 892   const char* error_msg = NULL;
 893   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
 894   InlineMatcher* m = InlineMatcher::parse_inline_pattern(method_str, error_msg);
 895 
 896   if (m == NULL) {
 897     assert(error_msg != NULL, "Always have an error message");
 898     tty->print_cr("Got error: %s", error_msg);
 899     return -1; // Pattern failed
 900   }
 901 
 902   // Pattern works - now check if it matches
 903   int result;
 904   if (m->match(mh, InlineMatcher::force_inline)) {
 905     result = 2; // Force inline match
 906   } else if (m->match(mh, InlineMatcher::dont_inline)) {
 907     result = 1; // Dont inline match
 908   } else {
 909     result = 0; // No match
 910   }
 911   delete m;
 912   return result;
 913 WB_END
 914 
 915 WB_ENTRY(jint, WB_MatchesMethod(JNIEnv* env, jobject o, jobject method, jstring pattern))
 916   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 917   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 918 
 919   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 920 
 921   ResourceMark rm;
 922   char* method_str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(pattern));
 923 
 924   const char* error_msg = NULL;
 925 
 926   BasicMatcher* m = BasicMatcher::parse_method_pattern(method_str, error_msg);
 927   if (m == NULL) {
 928     assert(error_msg != NULL, "Must have error_msg");
 929     tty->print_cr("Got error: %s", error_msg);
 930     return -1;
 931   }
 932 
 933   // Pattern works - now check if it matches
 934   int result = m->matches(mh);
 935   delete m;
 936   assert(result == 0 || result == 1, "Result out of range");
 937   return result;
 938 WB_END
 939 
 940 static AlwaysFalseClosure always_false;
 941 
 942 WB_ENTRY(void, WB_ClearMethodState(JNIEnv* env, jobject o, jobject method))
 943   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 944   CHECK_JNI_EXCEPTION(env);
 945   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 946   MutexLockerEx mu(Compile_lock);
 947   MethodData* mdo = mh->method_data();
 948   MethodCounters* mcs = mh->method_counters();
 949 
 950   if (mdo != NULL) {
 951     mdo->init();
 952     ResourceMark rm;
 953     int arg_count = mdo->method()->size_of_parameters();
 954     for (int i = 0; i < arg_count; i++) {
 955       mdo->set_arg_modified(i, 0);
 956     }
 957     MutexLockerEx mu(mdo->extra_data_lock());
 958     mdo->clean_method_data(&always_false);
 959   }
 960 
 961   mh->clear_not_c1_compilable();
 962   mh->clear_not_c2_compilable();
 963   mh->clear_not_c2_osr_compilable();
 964   NOT_PRODUCT(mh->set_compiled_invocation_count(0));
 965   if (mcs != NULL) {
 966     mcs->backedge_counter()->init();
 967     mcs->invocation_counter()->init();
 968     mcs->set_interpreter_invocation_count(0);
 969     mcs->set_interpreter_throwout_count(0);
 970 
 971 #ifdef TIERED
 972     mcs->set_rate(0.0F);
 973     mh->set_prev_event_count(0);
 974     mh->set_prev_time(0);
 975 #endif
 976   }
 977 WB_END
 978 
 979 template <typename T>
 980 static bool GetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, Flag::Error (*TAt)(const char*, T*, bool, bool)) {
 981   if (name == NULL) {
 982     return false;
 983   }
 984   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 985   const char* flag_name = env->GetStringUTFChars(name, NULL);
 986   CHECK_JNI_EXCEPTION_(env, false);
 987   Flag::Error result = (*TAt)(flag_name, value, true, true);
 988   env->ReleaseStringUTFChars(name, flag_name);
 989   return (result == Flag::SUCCESS);
 990 }
 991 
 992 template <typename T>
 993 static bool SetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, Flag::Error (*TAtPut)(const char*, T*, Flag::Flags)) {
 994   if (name == NULL) {
 995     return false;
 996   }
 997   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 998   const char* flag_name = env->GetStringUTFChars(name, NULL);
 999   CHECK_JNI_EXCEPTION_(env, false);
1000   Flag::Error result = (*TAtPut)(flag_name, value, Flag::INTERNAL);
1001   env->ReleaseStringUTFChars(name, flag_name);
1002   return (result == Flag::SUCCESS);
1003 }
1004 
1005 template <typename T>
1006 static jobject box(JavaThread* thread, JNIEnv* env, Symbol* name, Symbol* sig, T value) {
1007   ResourceMark rm(thread);
1008   jclass clazz = env->FindClass(name->as_C_string());
1009   CHECK_JNI_EXCEPTION_(env, NULL);
1010   jmethodID methodID = env->GetStaticMethodID(clazz,
1011         vmSymbols::valueOf_name()->as_C_string(),
1012         sig->as_C_string());
1013   CHECK_JNI_EXCEPTION_(env, NULL);
1014   jobject result = env->CallStaticObjectMethod(clazz, methodID, value);
1015   CHECK_JNI_EXCEPTION_(env, NULL);
1016   return result;
1017 }
1018 
1019 static jobject booleanBox(JavaThread* thread, JNIEnv* env, jboolean value) {
1020   return box(thread, env, vmSymbols::java_lang_Boolean(), vmSymbols::Boolean_valueOf_signature(), value);
1021 }
1022 static jobject integerBox(JavaThread* thread, JNIEnv* env, jint value) {
1023   return box(thread, env, vmSymbols::java_lang_Integer(), vmSymbols::Integer_valueOf_signature(), value);
1024 }
1025 static jobject longBox(JavaThread* thread, JNIEnv* env, jlong value) {
1026   return box(thread, env, vmSymbols::java_lang_Long(), vmSymbols::Long_valueOf_signature(), value);
1027 }
1028 /* static jobject floatBox(JavaThread* thread, JNIEnv* env, jfloat value) {
1029   return box(thread, env, vmSymbols::java_lang_Float(), vmSymbols::Float_valueOf_signature(), value);
1030 }*/
1031 static jobject doubleBox(JavaThread* thread, JNIEnv* env, jdouble value) {
1032   return box(thread, env, vmSymbols::java_lang_Double(), vmSymbols::Double_valueOf_signature(), value);
1033 }
1034 
1035 static Flag* getVMFlag(JavaThread* thread, JNIEnv* env, jstring name) {
1036   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1037   const char* flag_name = env->GetStringUTFChars(name, NULL);
1038   CHECK_JNI_EXCEPTION_(env, NULL);
1039   Flag* result = Flag::find_flag(flag_name, strlen(flag_name), true, true);
1040   env->ReleaseStringUTFChars(name, flag_name);
1041   return result;
1042 }
1043 
1044 WB_ENTRY(jboolean, WB_IsConstantVMFlag(JNIEnv* env, jobject o, jstring name))
1045   Flag* flag = getVMFlag(thread, env, name);
1046   return (flag != NULL) && flag->is_constant_in_binary();
1047 WB_END
1048 
1049 WB_ENTRY(jboolean, WB_IsLockedVMFlag(JNIEnv* env, jobject o, jstring name))
1050   Flag* flag = getVMFlag(thread, env, name);
1051   return (flag != NULL) && !(flag->is_unlocked() || flag->is_unlocker());
1052 WB_END
1053 
1054 WB_ENTRY(jobject, WB_GetBooleanVMFlag(JNIEnv* env, jobject o, jstring name))
1055   bool result;
1056   if (GetVMFlag <bool> (thread, env, name, &result, &CommandLineFlags::boolAt)) {
1057     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1058     return booleanBox(thread, env, result);
1059   }
1060   return NULL;
1061 WB_END
1062 
1063 WB_ENTRY(jobject, WB_GetIntVMFlag(JNIEnv* env, jobject o, jstring name))
1064   int result;
1065   if (GetVMFlag <int> (thread, env, name, &result, &CommandLineFlags::intAt)) {
1066     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1067     return longBox(thread, env, result);
1068   }
1069   return NULL;
1070 WB_END
1071 
1072 WB_ENTRY(jobject, WB_GetUintVMFlag(JNIEnv* env, jobject o, jstring name))
1073   uint result;
1074   if (GetVMFlag <uint> (thread, env, name, &result, &CommandLineFlags::uintAt)) {
1075     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1076     return longBox(thread, env, result);
1077   }
1078   return NULL;
1079 WB_END
1080 
1081 WB_ENTRY(jobject, WB_GetIntxVMFlag(JNIEnv* env, jobject o, jstring name))
1082   intx result;
1083   if (GetVMFlag <intx> (thread, env, name, &result, &CommandLineFlags::intxAt)) {
1084     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1085     return longBox(thread, env, result);
1086   }
1087   return NULL;
1088 WB_END
1089 
1090 WB_ENTRY(jobject, WB_GetUintxVMFlag(JNIEnv* env, jobject o, jstring name))
1091   uintx result;
1092   if (GetVMFlag <uintx> (thread, env, name, &result, &CommandLineFlags::uintxAt)) {
1093     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1094     return longBox(thread, env, result);
1095   }
1096   return NULL;
1097 WB_END
1098 
1099 WB_ENTRY(jobject, WB_GetUint64VMFlag(JNIEnv* env, jobject o, jstring name))
1100   uint64_t result;
1101   if (GetVMFlag <uint64_t> (thread, env, name, &result, &CommandLineFlags::uint64_tAt)) {
1102     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1103     return longBox(thread, env, result);
1104   }
1105   return NULL;
1106 WB_END
1107 
1108 WB_ENTRY(jobject, WB_GetSizeTVMFlag(JNIEnv* env, jobject o, jstring name))
1109   uintx result;
1110   if (GetVMFlag <size_t> (thread, env, name, &result, &CommandLineFlags::size_tAt)) {
1111     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1112     return longBox(thread, env, result);
1113   }
1114   return NULL;
1115 WB_END
1116 
1117 WB_ENTRY(jobject, WB_GetDoubleVMFlag(JNIEnv* env, jobject o, jstring name))
1118   double result;
1119   if (GetVMFlag <double> (thread, env, name, &result, &CommandLineFlags::doubleAt)) {
1120     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1121     return doubleBox(thread, env, result);
1122   }
1123   return NULL;
1124 WB_END
1125 
1126 WB_ENTRY(jstring, WB_GetStringVMFlag(JNIEnv* env, jobject o, jstring name))
1127   ccstr ccstrResult;
1128   if (GetVMFlag <ccstr> (thread, env, name, &ccstrResult, &CommandLineFlags::ccstrAt)) {
1129     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1130     jstring result = env->NewStringUTF(ccstrResult);
1131     CHECK_JNI_EXCEPTION_(env, NULL);
1132     return result;
1133   }
1134   return NULL;
1135 WB_END
1136 
1137 WB_ENTRY(void, WB_SetBooleanVMFlag(JNIEnv* env, jobject o, jstring name, jboolean value))
1138   bool result = value == JNI_TRUE ? true : false;
1139   SetVMFlag <bool> (thread, env, name, &result, &CommandLineFlags::boolAtPut);
1140 WB_END
1141 
1142 WB_ENTRY(void, WB_SetIntVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1143   int result = value;
1144   SetVMFlag <int> (thread, env, name, &result, &CommandLineFlags::intAtPut);
1145 WB_END
1146 
1147 WB_ENTRY(void, WB_SetUintVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1148   uint result = value;
1149   SetVMFlag <uint> (thread, env, name, &result, &CommandLineFlags::uintAtPut);
1150 WB_END
1151 
1152 WB_ENTRY(void, WB_SetIntxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1153   intx result = value;
1154   SetVMFlag <intx> (thread, env, name, &result, &CommandLineFlags::intxAtPut);
1155 WB_END
1156 
1157 WB_ENTRY(void, WB_SetUintxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1158   uintx result = value;
1159   SetVMFlag <uintx> (thread, env, name, &result, &CommandLineFlags::uintxAtPut);
1160 WB_END
1161 
1162 WB_ENTRY(void, WB_SetUint64VMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1163   uint64_t result = value;
1164   SetVMFlag <uint64_t> (thread, env, name, &result, &CommandLineFlags::uint64_tAtPut);
1165 WB_END
1166 
1167 WB_ENTRY(void, WB_SetSizeTVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
1168   size_t result = value;
1169   SetVMFlag <size_t> (thread, env, name, &result, &CommandLineFlags::size_tAtPut);
1170 WB_END
1171 
1172 WB_ENTRY(void, WB_SetDoubleVMFlag(JNIEnv* env, jobject o, jstring name, jdouble value))
1173   double result = value;
1174   SetVMFlag <double> (thread, env, name, &result, &CommandLineFlags::doubleAtPut);
1175 WB_END
1176 
1177 WB_ENTRY(void, WB_SetStringVMFlag(JNIEnv* env, jobject o, jstring name, jstring value))
1178   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
1179   const char* ccstrValue;
1180   if (value == NULL) {
1181     ccstrValue = NULL;
1182   }
1183   else {
1184     ccstrValue = env->GetStringUTFChars(value, NULL);
1185     CHECK_JNI_EXCEPTION(env);
1186   }
1187   ccstr ccstrResult = ccstrValue;
1188   bool needFree;
1189   {
1190     ThreadInVMfromNative ttvfn(thread); // back to VM
1191     needFree = SetVMFlag <ccstr> (thread, env, name, &ccstrResult, &CommandLineFlags::ccstrAtPut);
1192   }
1193   if (value != NULL) {
1194     env->ReleaseStringUTFChars(value, ccstrValue);
1195   }
1196   if (needFree) {
1197     FREE_C_HEAP_ARRAY(char, ccstrResult);
1198   }
1199 WB_END
1200 
1201 WB_ENTRY(void, WB_LockCompilation(JNIEnv* env, jobject o, jlong timeout))
1202   WhiteBox::compilation_locked = true;
1203 WB_END
1204 
1205 WB_ENTRY(void, WB_UnlockCompilation(JNIEnv* env, jobject o))
1206   MonitorLockerEx mo(Compilation_lock, Mutex::_no_safepoint_check_flag);
1207   WhiteBox::compilation_locked = false;
1208   mo.notify_all();
1209 WB_END
1210 
1211 WB_ENTRY(void, WB_ForceNMethodSweep(JNIEnv* env, jobject o))
1212   // Force a code cache sweep and block until it finished
1213   NMethodSweeper::force_sweep();
1214 WB_END
1215 
1216 WB_ENTRY(jboolean, WB_IsInStringTable(JNIEnv* env, jobject o, jstring javaString))
1217   ResourceMark rm(THREAD);
1218   int len;
1219   jchar* name = java_lang_String::as_unicode_string(JNIHandles::resolve(javaString), len, CHECK_false);
1220   return (StringTable::lookup(name, len) != NULL);
1221 WB_END
1222 
1223 WB_ENTRY(void, WB_FullGC(JNIEnv* env, jobject o))
1224   Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(true);
1225   Universe::heap()->collect(GCCause::_wb_full_gc);
1226 #if INCLUDE_ALL_GCS
1227   if (UseG1GC) {
1228     // Needs to be cleared explicitly for G1
1229     Universe::heap()->soft_ref_policy()->set_should_clear_all_soft_refs(false);
1230   }
1231 #endif // INCLUDE_ALL_GCS
1232 WB_END
1233 
1234 WB_ENTRY(void, WB_YoungGC(JNIEnv* env, jobject o))
1235   Universe::heap()->collect(GCCause::_wb_young_gc);
1236 WB_END
1237 
1238 WB_ENTRY(void, WB_ReadReservedMemory(JNIEnv* env, jobject o))
1239   // static+volatile in order to force the read to happen
1240   // (not be eliminated by the compiler)
1241   static char c;
1242   static volatile char* p;
1243 
1244   p = os::reserve_memory(os::vm_allocation_granularity(), NULL, 0);
1245   if (p == NULL) {
1246     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "Failed to reserve memory");
1247   }
1248 
1249   c = *p;
1250 WB_END
1251 
1252 WB_ENTRY(jstring, WB_GetCPUFeatures(JNIEnv* env, jobject o))
1253   const char* features = VM_Version::features_string();
1254   ThreadToNativeFromVM ttn(thread);
1255   jstring features_string = env->NewStringUTF(features);
1256 
1257   CHECK_JNI_EXCEPTION_(env, NULL);
1258 
1259   return features_string;
1260 WB_END
1261 
1262 int WhiteBox::get_blob_type(const CodeBlob* code) {
1263   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1264   if (code->is_aot()) {
1265     return -1;
1266   }
1267   return CodeCache::get_code_heap(code)->code_blob_type();
1268 }
1269 
1270 CodeHeap* WhiteBox::get_code_heap(int blob_type) {
1271   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1272   return CodeCache::get_code_heap(blob_type);
1273 }
1274 
1275 struct CodeBlobStub {
1276   CodeBlobStub(const CodeBlob* blob) :
1277       name(os::strdup(blob->name())),
1278       size(blob->size()),
1279       blob_type(WhiteBox::get_blob_type(blob)),
1280       address((jlong) blob) { }
1281   ~CodeBlobStub() { os::free((void*) name); }
1282   const char* const name;
1283   const jint        size;
1284   const jint        blob_type;
1285   const jlong       address;
1286 };
1287 
1288 static jobjectArray codeBlob2objectArray(JavaThread* thread, JNIEnv* env, CodeBlobStub* cb) {
1289   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1290   CHECK_JNI_EXCEPTION_(env, NULL);
1291   jobjectArray result = env->NewObjectArray(4, clazz, NULL);
1292 
1293   jstring name = env->NewStringUTF(cb->name);
1294   CHECK_JNI_EXCEPTION_(env, NULL);
1295   env->SetObjectArrayElement(result, 0, name);
1296 
1297   jobject obj = integerBox(thread, env, cb->size);
1298   CHECK_JNI_EXCEPTION_(env, NULL);
1299   env->SetObjectArrayElement(result, 1, obj);
1300 
1301   obj = integerBox(thread, env, cb->blob_type);
1302   CHECK_JNI_EXCEPTION_(env, NULL);
1303   env->SetObjectArrayElement(result, 2, obj);
1304 
1305   obj = longBox(thread, env, cb->address);
1306   CHECK_JNI_EXCEPTION_(env, NULL);
1307   env->SetObjectArrayElement(result, 3, obj);
1308 
1309   return result;
1310 }
1311 
1312 WB_ENTRY(jobjectArray, WB_GetNMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
1313   ResourceMark rm(THREAD);
1314   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1315   CHECK_JNI_EXCEPTION_(env, NULL);
1316   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
1317   CompiledMethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
1318   jobjectArray result = NULL;
1319   if (code == NULL) {
1320     return result;
1321   }
1322   int comp_level = code->comp_level();
1323   int insts_size = comp_level == CompLevel_aot ? code->code_end() - code->code_begin() : code->insts_size();
1324 
1325   ThreadToNativeFromVM ttn(thread);
1326   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1327   CHECK_JNI_EXCEPTION_(env, NULL);
1328   result = env->NewObjectArray(5, clazz, NULL);
1329   if (result == NULL) {
1330     return result;
1331   }
1332 
1333   CodeBlobStub stub(code);
1334   jobjectArray codeBlob = codeBlob2objectArray(thread, env, &stub);
1335   CHECK_JNI_EXCEPTION_(env, NULL);
1336   env->SetObjectArrayElement(result, 0, codeBlob);
1337 
1338   jobject level = integerBox(thread, env, comp_level);
1339   CHECK_JNI_EXCEPTION_(env, NULL);
1340   env->SetObjectArrayElement(result, 1, level);
1341 
1342   jbyteArray insts = env->NewByteArray(insts_size);
1343   CHECK_JNI_EXCEPTION_(env, NULL);
1344   env->SetByteArrayRegion(insts, 0, insts_size, (jbyte*) code->insts_begin());
1345   env->SetObjectArrayElement(result, 2, insts);
1346 
1347   jobject id = integerBox(thread, env, code->compile_id());
1348   CHECK_JNI_EXCEPTION_(env, NULL);
1349   env->SetObjectArrayElement(result, 3, id);
1350 
1351   jobject entry_point = longBox(thread, env, (jlong) code->entry_point());
1352   CHECK_JNI_EXCEPTION_(env, NULL);
1353   env->SetObjectArrayElement(result, 4, entry_point);
1354 
1355   return result;
1356 WB_END
1357 
1358 CodeBlob* WhiteBox::allocate_code_blob(int size, int blob_type) {
1359   guarantee(WhiteBoxAPI, "internal testing API :: WhiteBox has to be enabled");
1360   BufferBlob* blob;
1361   int full_size = CodeBlob::align_code_offset(sizeof(BufferBlob));
1362   if (full_size < size) {
1363     full_size += align_up(size - full_size, oopSize);
1364   }
1365   {
1366     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1367     blob = (BufferBlob*) CodeCache::allocate(full_size, blob_type);
1368     ::new (blob) BufferBlob("WB::DummyBlob", full_size);
1369   }
1370   // Track memory usage statistic after releasing CodeCache_lock
1371   MemoryService::track_code_cache_memory_usage();
1372   return blob;
1373 }
1374 
1375 WB_ENTRY(jlong, WB_AllocateCodeBlob(JNIEnv* env, jobject o, jint size, jint blob_type))
1376   if (size < 0) {
1377     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1378       err_msg("WB_AllocateCodeBlob: size is negative: " INT32_FORMAT, size));
1379   }
1380   return (jlong) WhiteBox::allocate_code_blob(size, blob_type);
1381 WB_END
1382 
1383 WB_ENTRY(void, WB_FreeCodeBlob(JNIEnv* env, jobject o, jlong addr))
1384   if (addr == 0) {
1385     return;
1386   }
1387   BufferBlob::free((BufferBlob*) addr);
1388 WB_END
1389 
1390 WB_ENTRY(jobjectArray, WB_GetCodeHeapEntries(JNIEnv* env, jobject o, jint blob_type))
1391   ResourceMark rm;
1392   GrowableArray<CodeBlobStub*> blobs;
1393   {
1394     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1395     CodeHeap* heap = WhiteBox::get_code_heap(blob_type);
1396     if (heap == NULL) {
1397       return NULL;
1398     }
1399     for (CodeBlob* cb = (CodeBlob*) heap->first();
1400          cb != NULL; cb = (CodeBlob*) heap->next(cb)) {
1401       CodeBlobStub* stub = NEW_RESOURCE_OBJ(CodeBlobStub);
1402       new (stub) CodeBlobStub(cb);
1403       blobs.append(stub);
1404     }
1405   }
1406   if (blobs.length() == 0) {
1407     return NULL;
1408   }
1409   ThreadToNativeFromVM ttn(thread);
1410   jobjectArray result = NULL;
1411   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
1412   CHECK_JNI_EXCEPTION_(env, NULL);
1413   result = env->NewObjectArray(blobs.length(), clazz, NULL);
1414   CHECK_JNI_EXCEPTION_(env, NULL);
1415   if (result == NULL) {
1416     return result;
1417   }
1418   int i = 0;
1419   for (GrowableArrayIterator<CodeBlobStub*> it = blobs.begin();
1420        it != blobs.end(); ++it) {
1421     jobjectArray obj = codeBlob2objectArray(thread, env, *it);
1422     CHECK_JNI_EXCEPTION_(env, NULL);
1423     env->SetObjectArrayElement(result, i, obj);
1424     CHECK_JNI_EXCEPTION_(env, NULL);
1425     ++i;
1426   }
1427   return result;
1428 WB_END
1429 
1430 WB_ENTRY(jint, WB_GetCompilationActivityMode(JNIEnv* env, jobject o))
1431   return CompileBroker::get_compilation_activity_mode();
1432 WB_END
1433 
1434 WB_ENTRY(jobjectArray, WB_GetCodeBlob(JNIEnv* env, jobject o, jlong addr))
1435   if (addr == 0) {
1436     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(),
1437       "WB_GetCodeBlob: addr is null");
1438   }
1439   ThreadToNativeFromVM ttn(thread);
1440   CodeBlobStub stub((CodeBlob*) addr);
1441   return codeBlob2objectArray(thread, env, &stub);
1442 WB_END
1443 
1444 WB_ENTRY(jlong, WB_GetMethodData(JNIEnv* env, jobject wv, jobject method))
1445   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1446   CHECK_JNI_EXCEPTION_(env, 0);
1447   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1448   return (jlong) mh->method_data();
1449 WB_END
1450 
1451 WB_ENTRY(jlong, WB_GetThreadStackSize(JNIEnv* env, jobject o))
1452   return (jlong) Thread::current()->stack_size();
1453 WB_END
1454 
1455 WB_ENTRY(jlong, WB_GetThreadRemainingStackSize(JNIEnv* env, jobject o))
1456   JavaThread* t = JavaThread::current();
1457   return (jlong) t->stack_available(os::current_stack_pointer()) - (jlong)JavaThread::stack_shadow_zone_size();
1458 WB_END
1459 
1460 
1461 int WhiteBox::array_bytes_to_length(size_t bytes) {
1462   return Array<u1>::bytes_to_length(bytes);
1463 }
1464 
1465 WB_ENTRY(jlong, WB_AllocateMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong size))
1466   if (size < 0) {
1467     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1468         err_msg("WB_AllocateMetaspace: size is negative: " JLONG_FORMAT, size));
1469   }
1470 
1471   oop class_loader_oop = JNIHandles::resolve(class_loader);
1472   ClassLoaderData* cld = class_loader_oop != NULL
1473       ? java_lang_ClassLoader::loader_data(class_loader_oop)
1474       : ClassLoaderData::the_null_class_loader_data();
1475 
1476   void* metadata = MetadataFactory::new_array<u1>(cld, WhiteBox::array_bytes_to_length((size_t)size), thread);
1477 
1478   return (jlong)(uintptr_t)metadata;
1479 WB_END
1480 
1481 WB_ENTRY(void, WB_FreeMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong addr, jlong size))
1482   oop class_loader_oop = JNIHandles::resolve(class_loader);
1483   ClassLoaderData* cld = class_loader_oop != NULL
1484       ? java_lang_ClassLoader::loader_data(class_loader_oop)
1485       : ClassLoaderData::the_null_class_loader_data();
1486 
1487   MetadataFactory::free_array(cld, (Array<u1>*)(uintptr_t)addr);
1488 WB_END
1489 
1490 WB_ENTRY(void, WB_DefineModule(JNIEnv* env, jobject o, jobject module, jboolean is_open,
1491                                 jstring version, jstring location, jobjectArray packages))
1492   ResourceMark rm(THREAD);
1493 
1494   objArrayOop packages_oop = objArrayOop(JNIHandles::resolve(packages));
1495   objArrayHandle packages_h(THREAD, packages_oop);
1496   int num_packages = (packages_h == NULL ? 0 : packages_h->length());
1497 
1498   char** pkgs = NULL;
1499   if (num_packages > 0) {
1500     pkgs = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char*, num_packages);
1501     for (int x = 0; x < num_packages; x++) {
1502       oop pkg_str = packages_h->obj_at(x);
1503       if (pkg_str == NULL || !pkg_str->is_a(SystemDictionary::String_klass())) {
1504         THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1505                   err_msg("Bad package name"));
1506       }
1507       pkgs[x] = java_lang_String::as_utf8_string(pkg_str);
1508     }
1509   }
1510   Modules::define_module(module, is_open, version, location, (const char* const*)pkgs, num_packages, CHECK);
1511 WB_END
1512 
1513 WB_ENTRY(void, WB_AddModuleExports(JNIEnv* env, jobject o, jobject from_module, jstring package, jobject to_module))
1514   ResourceMark rm(THREAD);
1515   char* package_name = NULL;
1516   if (package != NULL) {
1517       package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
1518   }
1519   Modules::add_module_exports_qualified(from_module, package_name, to_module, CHECK);
1520 WB_END
1521 
1522 WB_ENTRY(void, WB_AddModuleExportsToAllUnnamed(JNIEnv* env, jobject o, jclass module, jstring package))
1523   ResourceMark rm(THREAD);
1524   char* package_name = NULL;
1525   if (package != NULL) {
1526       package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
1527   }
1528   Modules::add_module_exports_to_all_unnamed(module, package_name, CHECK);
1529 WB_END
1530 
1531 WB_ENTRY(void, WB_AddModuleExportsToAll(JNIEnv* env, jobject o, jclass module, jstring package))
1532   ResourceMark rm(THREAD);
1533   char* package_name = NULL;
1534   if (package != NULL) {
1535       package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
1536   }
1537   Modules::add_module_exports(module, package_name, NULL, CHECK);
1538 WB_END
1539 
1540 WB_ENTRY(void, WB_AddReadsModule(JNIEnv* env, jobject o, jobject from_module, jobject source_module))
1541   Modules::add_reads_module(from_module, source_module, CHECK);
1542 WB_END
1543 
1544 WB_ENTRY(jlong, WB_IncMetaspaceCapacityUntilGC(JNIEnv* env, jobject wb, jlong inc))
1545   if (inc < 0) {
1546     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1547         err_msg("WB_IncMetaspaceCapacityUntilGC: inc is negative: " JLONG_FORMAT, inc));
1548   }
1549 
1550   jlong max_size_t = (jlong) ((size_t) -1);
1551   if (inc > max_size_t) {
1552     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1553         err_msg("WB_IncMetaspaceCapacityUntilGC: inc does not fit in size_t: " JLONG_FORMAT, inc));
1554   }
1555 
1556   size_t new_cap_until_GC = 0;
1557   size_t aligned_inc = align_down((size_t) inc, Metaspace::commit_alignment());
1558   bool success = MetaspaceGC::inc_capacity_until_GC(aligned_inc, &new_cap_until_GC);
1559   if (!success) {
1560     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(),
1561                 "WB_IncMetaspaceCapacityUntilGC: could not increase capacity until GC "
1562                 "due to contention with another thread");
1563   }
1564   return (jlong) new_cap_until_GC;
1565 WB_END
1566 
1567 WB_ENTRY(jlong, WB_MetaspaceCapacityUntilGC(JNIEnv* env, jobject wb))
1568   return (jlong) MetaspaceGC::capacity_until_GC();
1569 WB_END
1570 
1571 WB_ENTRY(jboolean, WB_MetaspaceShouldConcurrentCollect(JNIEnv* env, jobject wb))
1572   return MetaspaceGC::should_concurrent_collect();
1573 WB_END
1574 
1575 WB_ENTRY(jlong, WB_MetaspaceReserveAlignment(JNIEnv* env, jobject wb))
1576   return (jlong)Metaspace::reserve_alignment();
1577 WB_END
1578 
1579 WB_ENTRY(void, WB_AssertMatchingSafepointCalls(JNIEnv* env, jobject o, jboolean mutexSafepointValue, jboolean attemptedNoSafepointValue))
1580   Monitor::SafepointCheckRequired sfpt_check_required = mutexSafepointValue ?
1581                                            Monitor::_safepoint_check_always :
1582                                            Monitor::_safepoint_check_never;
1583   MutexLockerEx ml(new Mutex(Mutex::leaf, "SFPT_Test_lock", true, sfpt_check_required),
1584                    attemptedNoSafepointValue == JNI_TRUE);
1585 WB_END
1586 
1587 WB_ENTRY(jboolean, WB_IsMonitorInflated(JNIEnv* env, jobject wb, jobject obj))
1588   oop obj_oop = JNIHandles::resolve(obj);
1589   return (jboolean) obj_oop->mark()->has_monitor();
1590 WB_END
1591 
1592 WB_ENTRY(void, WB_ForceSafepoint(JNIEnv* env, jobject wb))
1593   VM_ForceSafepoint force_safepoint_op;
1594   VMThread::execute(&force_safepoint_op);
1595 WB_END
1596 
1597 WB_ENTRY(jlong, WB_GetConstantPool(JNIEnv* env, jobject wb, jclass klass))
1598   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1599   return (jlong) ik->constants();
1600 WB_END
1601 
1602 WB_ENTRY(jint, WB_GetConstantPoolCacheIndexTag(JNIEnv* env, jobject wb))
1603   return ConstantPool::CPCACHE_INDEX_TAG;
1604 WB_END
1605 
1606 WB_ENTRY(jint, WB_GetConstantPoolCacheLength(JNIEnv* env, jobject wb, jclass klass))
1607   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1608   ConstantPool* cp = ik->constants();
1609   if (cp->cache() == NULL) {
1610       return -1;
1611   }
1612   return cp->cache()->length();
1613 WB_END
1614 
1615 WB_ENTRY(jint, WB_ConstantPoolRemapInstructionOperandFromCache(JNIEnv* env, jobject wb, jclass klass, jint index))
1616   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve(klass)));
1617   ConstantPool* cp = ik->constants();
1618   if (cp->cache() == NULL) {
1619     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(), "Constant pool does not have a cache");
1620   }
1621   jint cpci = index;
1622   jint cpciTag = ConstantPool::CPCACHE_INDEX_TAG;
1623   if (cpciTag > cpci || cpci >= cp->cache()->length() + cpciTag) {
1624     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool cache index is out of range");
1625   }
1626   jint cpi = cp->remap_instruction_operand_from_cache(cpci);
1627   return cpi;
1628 WB_END
1629 
1630 WB_ENTRY(jint, WB_ConstantPoolEncodeIndyIndex(JNIEnv* env, jobject wb, jint index))
1631   return ConstantPool::encode_invokedynamic_index(index);
1632 WB_END
1633 
1634 WB_ENTRY(void, WB_ClearInlineCaches(JNIEnv* env, jobject wb, jboolean preserve_static_stubs))
1635   VM_ClearICs clear_ics(preserve_static_stubs == JNI_TRUE);
1636   VMThread::execute(&clear_ics);
1637 WB_END
1638 
1639 template <typename T>
1640 static bool GetMethodOption(JavaThread* thread, JNIEnv* env, jobject method, jstring name, T* value) {
1641   assert(value != NULL, "sanity");
1642   if (method == NULL || name == NULL) {
1643     return false;
1644   }
1645   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
1646   CHECK_JNI_EXCEPTION_(env, false);
1647   methodHandle mh(thread, Method::checked_resolve_jmethod_id(jmid));
1648   // can't be in VM when we call JNI
1649   ThreadToNativeFromVM ttnfv(thread);
1650   const char* flag_name = env->GetStringUTFChars(name, NULL);
1651   CHECK_JNI_EXCEPTION_(env, false);
1652   bool result =  CompilerOracle::has_option_value(mh, flag_name, *value);
1653   env->ReleaseStringUTFChars(name, flag_name);
1654   return result;
1655 }
1656 
1657 WB_ENTRY(jobject, WB_GetMethodBooleaneOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1658   bool result;
1659   if (GetMethodOption<bool> (thread, env, method, name, &result)) {
1660     // can't be in VM when we call JNI
1661     ThreadToNativeFromVM ttnfv(thread);
1662     return booleanBox(thread, env, result);
1663   }
1664   return NULL;
1665 WB_END
1666 
1667 WB_ENTRY(jobject, WB_GetMethodIntxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1668   intx result;
1669   if (GetMethodOption <intx> (thread, env, method, name, &result)) {
1670     // can't be in VM when we call JNI
1671     ThreadToNativeFromVM ttnfv(thread);
1672     return longBox(thread, env, result);
1673   }
1674   return NULL;
1675 WB_END
1676 
1677 WB_ENTRY(jobject, WB_GetMethodUintxOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1678   uintx result;
1679   if (GetMethodOption <uintx> (thread, env, method, name, &result)) {
1680     // can't be in VM when we call JNI
1681     ThreadToNativeFromVM ttnfv(thread);
1682     return longBox(thread, env, result);
1683   }
1684   return NULL;
1685 WB_END
1686 
1687 WB_ENTRY(jobject, WB_GetMethodDoubleOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1688   double result;
1689   if (GetMethodOption <double> (thread, env, method, name, &result)) {
1690     // can't be in VM when we call JNI
1691     ThreadToNativeFromVM ttnfv(thread);
1692     return doubleBox(thread, env, result);
1693   }
1694   return NULL;
1695 WB_END
1696 
1697 WB_ENTRY(jobject, WB_GetMethodStringOption(JNIEnv* env, jobject wb, jobject method, jstring name))
1698   ccstr ccstrResult;
1699   if (GetMethodOption <ccstr> (thread, env, method, name, &ccstrResult)) {
1700     // can't be in VM when we call JNI
1701     ThreadToNativeFromVM ttnfv(thread);
1702     jstring result = env->NewStringUTF(ccstrResult);
1703     CHECK_JNI_EXCEPTION_(env, NULL);
1704     return result;
1705   }
1706   return NULL;
1707 WB_END
1708 
1709 WB_ENTRY(jboolean, WB_IsShared(JNIEnv* env, jobject wb, jobject obj))
1710   oop obj_oop = JNIHandles::resolve(obj);
1711   return oopDesc::is_archive_object(obj_oop);
1712 WB_END
1713 
1714 WB_ENTRY(jboolean, WB_IsSharedClass(JNIEnv* env, jobject wb, jclass clazz))
1715   return (jboolean)MetaspaceShared::is_in_shared_metaspace(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
1716 WB_END
1717 
1718 WB_ENTRY(jboolean, WB_AreSharedStringsIgnored(JNIEnv* env))
1719   return !StringTable::shared_string_mapped();
1720 WB_END
1721 
1722 WB_ENTRY(jobject, WB_GetResolvedReferences(JNIEnv* env, jobject wb, jclass clazz))
1723   Klass *k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
1724   if (k->is_instance_klass()) {
1725     InstanceKlass *ik = InstanceKlass::cast(k);
1726     ConstantPool *cp = ik->constants();
1727     objArrayOop refs =  cp->resolved_references();
1728     return (jobject)JNIHandles::make_local(env, refs);
1729   } else {
1730     return NULL;
1731   }
1732 WB_END
1733 
1734 WB_ENTRY(jboolean, WB_AreOpenArchiveHeapObjectsMapped(JNIEnv* env))
1735   return MetaspaceShared::open_archive_heap_region_mapped();
1736 WB_END
1737 
1738 WB_ENTRY(jboolean, WB_IsCDSIncludedInVmBuild(JNIEnv* env))
1739 #if INCLUDE_CDS
1740 # ifdef _LP64
1741     if (!UseCompressedOops || !UseCompressedClassPointers) {
1742       // On 64-bit VMs, CDS is supported only with compressed oops/pointers
1743       return false;
1744     }
1745 # endif // _LP64
1746   return true;
1747 #else
1748   return false;
1749 #endif // INCLUDE_CDS
1750 WB_END
1751 
1752 WB_ENTRY(jboolean, WB_IsJavaHeapArchiveSupported(JNIEnv* env))
1753   return MetaspaceShared::is_heap_object_archiving_allowed();
1754 WB_END
1755 
1756 
1757 #if INCLUDE_CDS
1758 
1759 WB_ENTRY(jint, WB_GetOffsetForName(JNIEnv* env, jobject o, jstring name))
1760   ResourceMark rm;
1761   char* c_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
1762   int result = CDSOffsets::find_offset(c_name);
1763   return (jint)result;
1764 WB_END
1765 
1766 #endif // INCLUDE_CDS
1767 
1768 WB_ENTRY(jint, WB_HandshakeWalkStack(JNIEnv* env, jobject wb, jobject thread_handle, jboolean all_threads))
1769   class TraceSelfClosure : public ThreadClosure {
1770     jint _num_threads_completed;
1771 
1772     void do_thread(Thread* th) {
1773       assert(th->is_Java_thread(), "sanity");
1774       JavaThread* jt = (JavaThread*)th;
1775       ResourceMark rm;
1776 
1777       jt->print_on(tty);
1778       jt->print_stack_on(tty);
1779       tty->cr();
1780       Atomic::inc(&_num_threads_completed);
1781     }
1782 
1783   public:
1784     TraceSelfClosure() : _num_threads_completed(0) {}
1785 
1786     jint num_threads_completed() const { return _num_threads_completed; }
1787   };
1788   TraceSelfClosure tsc;
1789 
1790   if (all_threads) {
1791     Handshake::execute(&tsc);
1792   } else {
1793     oop thread_oop = JNIHandles::resolve(thread_handle);
1794     if (thread_oop != NULL) {
1795       JavaThread* target = java_lang_Thread::thread(thread_oop);
1796       Handshake::execute(&tsc, target);
1797     }
1798   }
1799   return tsc.num_threads_completed();
1800 WB_END
1801 
1802 //Some convenience methods to deal with objects from java
1803 int WhiteBox::offset_for_field(const char* field_name, oop object,
1804     Symbol* signature_symbol) {
1805   assert(field_name != NULL && strlen(field_name) > 0, "Field name not valid");
1806   Thread* THREAD = Thread::current();
1807 
1808   //Get the class of our object
1809   Klass* arg_klass = object->klass();
1810   //Turn it into an instance-klass
1811   InstanceKlass* ik = InstanceKlass::cast(arg_klass);
1812 
1813   //Create symbols to look for in the class
1814   TempNewSymbol name_symbol = SymbolTable::lookup(field_name, (int) strlen(field_name),
1815       THREAD);
1816 
1817   //To be filled in with an offset of the field we're looking for
1818   fieldDescriptor fd;
1819 
1820   Klass* res = ik->find_field(name_symbol, signature_symbol, &fd);
1821   if (res == NULL) {
1822     tty->print_cr("Invalid layout of %s at %s", ik->external_name(),
1823         name_symbol->as_C_string());
1824     vm_exit_during_initialization("Invalid layout of preloaded class: use -Xlog:class+load=info to see the origin of the problem class");
1825   }
1826 
1827   //fetch the field at the offset we've found
1828   int dest_offset = fd.offset();
1829 
1830   return dest_offset;
1831 }
1832 
1833 
1834 const char* WhiteBox::lookup_jstring(const char* field_name, oop object) {
1835   int offset = offset_for_field(field_name, object,
1836       vmSymbols::string_signature());
1837   oop string = object->obj_field(offset);
1838   if (string == NULL) {
1839     return NULL;
1840   }
1841   const char* ret = java_lang_String::as_utf8_string(string);
1842   return ret;
1843 }
1844 
1845 bool WhiteBox::lookup_bool(const char* field_name, oop object) {
1846   int offset =
1847       offset_for_field(field_name, object, vmSymbols::bool_signature());
1848   bool ret = (object->bool_field(offset) == JNI_TRUE);
1849   return ret;
1850 }
1851 
1852 void WhiteBox::register_methods(JNIEnv* env, jclass wbclass, JavaThread* thread, JNINativeMethod* method_array, int method_count) {
1853   ResourceMark rm;
1854   ThreadToNativeFromVM ttnfv(thread); // can't be in VM when we call JNI
1855 
1856   //  one by one registration natives for exception catching
1857   jclass no_such_method_error_klass = env->FindClass(vmSymbols::java_lang_NoSuchMethodError()->as_C_string());
1858   CHECK_JNI_EXCEPTION(env);
1859   for (int i = 0, n = method_count; i < n; ++i) {
1860     // Skip dummy entries
1861     if (method_array[i].fnPtr == NULL) continue;
1862     if (env->RegisterNatives(wbclass, &method_array[i], 1) != 0) {
1863       jthrowable throwable_obj = env->ExceptionOccurred();
1864       if (throwable_obj != NULL) {
1865         env->ExceptionClear();
1866         if (env->IsInstanceOf(throwable_obj, no_such_method_error_klass)) {
1867           // NoSuchMethodError is thrown when a method can't be found or a method is not native.
1868           // Ignoring the exception since it is not preventing use of other WhiteBox methods.
1869           tty->print_cr("Warning: 'NoSuchMethodError' on register of sun.hotspot.WhiteBox::%s%s",
1870               method_array[i].name, method_array[i].signature);
1871         }
1872       } else {
1873         // Registration failed unexpectedly.
1874         tty->print_cr("Warning: unexpected error on register of sun.hotspot.WhiteBox::%s%s. All methods will be unregistered",
1875             method_array[i].name, method_array[i].signature);
1876         env->UnregisterNatives(wbclass);
1877         break;
1878       }
1879     }
1880   }
1881 }
1882 
1883 WB_ENTRY(jint, WB_AddCompilerDirective(JNIEnv* env, jobject o, jstring compDirect))
1884   // can't be in VM when we call JNI
1885   ThreadToNativeFromVM ttnfv(thread);
1886   const char* dir = env->GetStringUTFChars(compDirect, NULL);
1887   CHECK_JNI_EXCEPTION_(env, 0);
1888   int ret;
1889   {
1890     ThreadInVMfromNative ttvfn(thread); // back to VM
1891     ret = DirectivesParser::parse_string(dir, tty);
1892   }
1893   env->ReleaseStringUTFChars(compDirect, dir);
1894   // -1 for error parsing directive. Return 0 as number of directives added.
1895   if (ret == -1) {
1896     ret = 0;
1897   }
1898   return (jint) ret;
1899 WB_END
1900 
1901 WB_ENTRY(void, WB_RemoveCompilerDirective(JNIEnv* env, jobject o, jint count))
1902   DirectivesStack::pop(count);
1903 WB_END
1904 
1905 // Checks that the library libfile has the noexecstack bit set.
1906 WB_ENTRY(jboolean, WB_CheckLibSpecifiesNoexecstack(JNIEnv* env, jobject o, jstring libfile))
1907   jboolean ret = false;
1908 #ifdef LINUX
1909   // Can't be in VM when we call JNI.
1910   ThreadToNativeFromVM ttnfv(thread);
1911   const char* lf = env->GetStringUTFChars(libfile, NULL);
1912   CHECK_JNI_EXCEPTION_(env, 0);
1913   ret = (jboolean) ElfFile::specifies_noexecstack(lf);
1914   env->ReleaseStringUTFChars(libfile, lf);
1915 #endif
1916   return ret;
1917 WB_END
1918 
1919 WB_ENTRY(jboolean, WB_IsContainerized(JNIEnv* env, jobject o))
1920   LINUX_ONLY(return OSContainer::is_containerized();)
1921   return false;
1922 WB_END
1923 
1924 WB_ENTRY(void, WB_PrintOsInfo(JNIEnv* env, jobject o))
1925   os::print_os_info(tty);
1926 WB_END
1927 
1928 // Elf decoder
1929 WB_ENTRY(void, WB_DisableElfSectionCache(JNIEnv* env))
1930 #if !defined(_WINDOWS) && !defined(__APPLE__) && !defined(_AIX)
1931   ElfFile::_do_not_cache_elf_section = true;
1932 #endif
1933 WB_END
1934 
1935 
1936 #define CC (char*)
1937 
1938 static JNINativeMethod methods[] = {
1939   {CC"getObjectAddress0",                CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectAddress  },
1940   {CC"getObjectSize0",                   CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectSize     },
1941   {CC"isObjectInOldGen0",                CC"(Ljava/lang/Object;)Z", (void*)&WB_isObjectInOldGen  },
1942   {CC"getHeapOopSize",                   CC"()I",                   (void*)&WB_GetHeapOopSize    },
1943   {CC"getVMPageSize",                    CC"()I",                   (void*)&WB_GetVMPageSize     },
1944   {CC"getVMAllocationGranularity",       CC"()J",                   (void*)&WB_GetVMAllocationGranularity },
1945   {CC"getVMLargePageSize",               CC"()J",                   (void*)&WB_GetVMLargePageSize},
1946   {CC"getHeapSpaceAlignment",            CC"()J",                   (void*)&WB_GetHeapSpaceAlignment},
1947   {CC"getHeapAlignment",                 CC"()J",                   (void*)&WB_GetHeapAlignment},
1948   {CC"isClassAlive0",                    CC"(Ljava/lang/String;)Z", (void*)&WB_IsClassAlive      },
1949   {CC"parseCommandLine0",
1950       CC"(Ljava/lang/String;C[Lsun/hotspot/parser/DiagnosticCommand;)[Ljava/lang/Object;",
1951       (void*) &WB_ParseCommandLine
1952   },
1953   {CC"addToBootstrapClassLoaderSearch0", CC"(Ljava/lang/String;)V",
1954                                                       (void*)&WB_AddToBootstrapClassLoaderSearch},
1955   {CC"addToSystemClassLoaderSearch0",    CC"(Ljava/lang/String;)V",
1956                                                       (void*)&WB_AddToSystemClassLoaderSearch},
1957   {CC"getCompressedOopsMaxHeapSize", CC"()J",
1958       (void*)&WB_GetCompressedOopsMaxHeapSize},
1959   {CC"printHeapSizes",     CC"()V",                   (void*)&WB_PrintHeapSizes    },
1960   {CC"runMemoryUnitTests", CC"()V",                   (void*)&WB_RunMemoryUnitTests},
1961   {CC"readFromNoaccessArea",CC"()V",                  (void*)&WB_ReadFromNoaccessArea},
1962   {CC"stressVirtualSpaceResize",CC"(JJJ)I",           (void*)&WB_StressVirtualSpaceResize},
1963 #if INCLUDE_CDS
1964   {CC"getOffsetForName0", CC"(Ljava/lang/String;)I",  (void*)&WB_GetOffsetForName},
1965 #endif
1966 #if INCLUDE_ALL_GCS
1967   {CC"g1InConcurrentMark", CC"()Z",                   (void*)&WB_G1InConcurrentMark},
1968   {CC"g1IsHumongous0",      CC"(Ljava/lang/Object;)Z", (void*)&WB_G1IsHumongous     },
1969   {CC"g1BelongsToHumongousRegion0", CC"(J)Z",         (void*)&WB_G1BelongsToHumongousRegion},
1970   {CC"g1BelongsToFreeRegion0", CC"(J)Z",              (void*)&WB_G1BelongsToFreeRegion},
1971   {CC"g1NumMaxRegions",    CC"()J",                   (void*)&WB_G1NumMaxRegions  },
1972   {CC"g1NumFreeRegions",   CC"()J",                   (void*)&WB_G1NumFreeRegions  },
1973   {CC"g1RegionSize",       CC"()I",                   (void*)&WB_G1RegionSize      },
1974   {CC"g1StartConcMarkCycle",       CC"()Z",           (void*)&WB_G1StartMarkCycle  },
1975   {CC"g1AuxiliaryMemoryUsage", CC"()Ljava/lang/management/MemoryUsage;",
1976                                                       (void*)&WB_G1AuxiliaryMemoryUsage  },
1977   {CC"psVirtualSpaceAlignment",CC"()J",               (void*)&WB_PSVirtualSpaceAlignment},
1978   {CC"psHeapGenerationAlignment",CC"()J",             (void*)&WB_PSHeapGenerationAlignment},
1979   {CC"g1GetMixedGCInfo",   CC"(I)[J",                 (void*)&WB_G1GetMixedGCInfo },
1980 #endif // INCLUDE_ALL_GCS
1981 #if INCLUDE_NMT
1982   {CC"NMTMalloc",           CC"(J)J",                 (void*)&WB_NMTMalloc          },
1983   {CC"NMTMallocWithPseudoStack", CC"(JI)J",           (void*)&WB_NMTMallocWithPseudoStack},
1984   {CC"NMTFree",             CC"(J)V",                 (void*)&WB_NMTFree            },
1985   {CC"NMTReserveMemory",    CC"(J)J",                 (void*)&WB_NMTReserveMemory   },
1986   {CC"NMTAttemptReserveMemoryAt",    CC"(JJ)J",       (void*)&WB_NMTAttemptReserveMemoryAt },
1987   {CC"NMTCommitMemory",     CC"(JJ)V",                (void*)&WB_NMTCommitMemory    },
1988   {CC"NMTUncommitMemory",   CC"(JJ)V",                (void*)&WB_NMTUncommitMemory  },
1989   {CC"NMTReleaseMemory",    CC"(JJ)V",                (void*)&WB_NMTReleaseMemory   },
1990   {CC"NMTChangeTrackingLevel", CC"()Z",               (void*)&WB_NMTChangeTrackingLevel},
1991   {CC"NMTGetHashSize",      CC"()I",                  (void*)&WB_NMTGetHashSize     },
1992 #endif // INCLUDE_NMT
1993   {CC"deoptimizeFrames",   CC"(Z)I",                  (void*)&WB_DeoptimizeFrames  },
1994   {CC"deoptimizeAll",      CC"()V",                   (void*)&WB_DeoptimizeAll     },
1995   {CC"deoptimizeMethod0",   CC"(Ljava/lang/reflect/Executable;Z)I",
1996                                                       (void*)&WB_DeoptimizeMethod  },
1997   {CC"isMethodCompiled0",   CC"(Ljava/lang/reflect/Executable;Z)Z",
1998                                                       (void*)&WB_IsMethodCompiled  },
1999   {CC"isMethodCompilable0", CC"(Ljava/lang/reflect/Executable;IZ)Z",
2000                                                       (void*)&WB_IsMethodCompilable},
2001   {CC"isMethodQueuedForCompilation0",
2002       CC"(Ljava/lang/reflect/Executable;)Z",          (void*)&WB_IsMethodQueuedForCompilation},
2003   {CC"isIntrinsicAvailable0",
2004       CC"(Ljava/lang/reflect/Executable;Ljava/lang/reflect/Executable;I)Z",
2005                                                       (void*)&WB_IsIntrinsicAvailable},
2006   {CC"makeMethodNotCompilable0",
2007       CC"(Ljava/lang/reflect/Executable;IZ)V",        (void*)&WB_MakeMethodNotCompilable},
2008   {CC"testSetDontInlineMethod0",
2009       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetDontInlineMethod},
2010   {CC"getMethodCompilationLevel0",
2011       CC"(Ljava/lang/reflect/Executable;Z)I",         (void*)&WB_GetMethodCompilationLevel},
2012   {CC"getMethodEntryBci0",
2013       CC"(Ljava/lang/reflect/Executable;)I",          (void*)&WB_GetMethodEntryBci},
2014   {CC"getCompileQueueSize",
2015       CC"(I)I",                                       (void*)&WB_GetCompileQueueSize},
2016   {CC"testSetForceInlineMethod0",
2017       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetForceInlineMethod},
2018   {CC"enqueueMethodForCompilation0",
2019       CC"(Ljava/lang/reflect/Executable;II)Z",        (void*)&WB_EnqueueMethodForCompilation},
2020   {CC"enqueueInitializerForCompilation0",
2021       CC"(Ljava/lang/Class;I)Z",                      (void*)&WB_EnqueueInitializerForCompilation},
2022   {CC"clearMethodState0",
2023       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_ClearMethodState},
2024   {CC"lockCompilation",    CC"()V",                   (void*)&WB_LockCompilation},
2025   {CC"unlockCompilation",  CC"()V",                   (void*)&WB_UnlockCompilation},
2026   {CC"matchesMethod",
2027       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2028                                                       (void*)&WB_MatchesMethod},
2029   {CC"matchesInline",
2030       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)I",
2031                                                       (void*)&WB_MatchesInline},
2032   {CC"shouldPrintAssembly",
2033         CC"(Ljava/lang/reflect/Executable;I)Z",
2034                                                         (void*)&WB_ShouldPrintAssembly},
2035 
2036   {CC"isConstantVMFlag",   CC"(Ljava/lang/String;)Z", (void*)&WB_IsConstantVMFlag},
2037   {CC"isLockedVMFlag",     CC"(Ljava/lang/String;)Z", (void*)&WB_IsLockedVMFlag},
2038   {CC"setBooleanVMFlag",   CC"(Ljava/lang/String;Z)V",(void*)&WB_SetBooleanVMFlag},
2039   {CC"setIntVMFlag",       CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntVMFlag},
2040   {CC"setUintVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintVMFlag},
2041   {CC"setIntxVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntxVMFlag},
2042   {CC"setUintxVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintxVMFlag},
2043   {CC"setUint64VMFlag",    CC"(Ljava/lang/String;J)V",(void*)&WB_SetUint64VMFlag},
2044   {CC"setSizeTVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetSizeTVMFlag},
2045   {CC"setDoubleVMFlag",    CC"(Ljava/lang/String;D)V",(void*)&WB_SetDoubleVMFlag},
2046   {CC"setStringVMFlag",    CC"(Ljava/lang/String;Ljava/lang/String;)V",
2047                                                       (void*)&WB_SetStringVMFlag},
2048   {CC"getBooleanVMFlag",   CC"(Ljava/lang/String;)Ljava/lang/Boolean;",
2049                                                       (void*)&WB_GetBooleanVMFlag},
2050   {CC"getIntVMFlag",       CC"(Ljava/lang/String;)Ljava/lang/Long;",
2051                                                       (void*)&WB_GetIntVMFlag},
2052   {CC"getUintVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
2053                                                       (void*)&WB_GetUintVMFlag},
2054   {CC"getIntxVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
2055                                                       (void*)&WB_GetIntxVMFlag},
2056   {CC"getUintxVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
2057                                                       (void*)&WB_GetUintxVMFlag},
2058   {CC"getUint64VMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Long;",
2059                                                       (void*)&WB_GetUint64VMFlag},
2060   {CC"getSizeTVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
2061                                                       (void*)&WB_GetSizeTVMFlag},
2062   {CC"getDoubleVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Double;",
2063                                                       (void*)&WB_GetDoubleVMFlag},
2064   {CC"getStringVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/String;",
2065                                                       (void*)&WB_GetStringVMFlag},
2066   {CC"isInStringTable",    CC"(Ljava/lang/String;)Z", (void*)&WB_IsInStringTable  },
2067   {CC"fullGC",   CC"()V",                             (void*)&WB_FullGC },
2068   {CC"youngGC",  CC"()V",                             (void*)&WB_YoungGC },
2069   {CC"readReservedMemory", CC"()V",                   (void*)&WB_ReadReservedMemory },
2070   {CC"allocateMetaspace",
2071      CC"(Ljava/lang/ClassLoader;J)J",                 (void*)&WB_AllocateMetaspace },
2072   {CC"freeMetaspace",
2073      CC"(Ljava/lang/ClassLoader;JJ)V",                (void*)&WB_FreeMetaspace },
2074   {CC"incMetaspaceCapacityUntilGC", CC"(J)J",         (void*)&WB_IncMetaspaceCapacityUntilGC },
2075   {CC"metaspaceCapacityUntilGC", CC"()J",             (void*)&WB_MetaspaceCapacityUntilGC },
2076   {CC"metaspaceShouldConcurrentCollect", CC"()Z",     (void*)&WB_MetaspaceShouldConcurrentCollect },
2077   {CC"metaspaceReserveAlignment", CC"()J",            (void*)&WB_MetaspaceReserveAlignment },
2078   {CC"getCPUFeatures",     CC"()Ljava/lang/String;",  (void*)&WB_GetCPUFeatures     },
2079   {CC"getNMethod0",         CC"(Ljava/lang/reflect/Executable;Z)[Ljava/lang/Object;",
2080                                                       (void*)&WB_GetNMethod         },
2081   {CC"forceNMethodSweep",  CC"()V",                   (void*)&WB_ForceNMethodSweep  },
2082   {CC"allocateCodeBlob",   CC"(II)J",                 (void*)&WB_AllocateCodeBlob   },
2083   {CC"freeCodeBlob",       CC"(J)V",                  (void*)&WB_FreeCodeBlob       },
2084   {CC"getCodeHeapEntries", CC"(I)[Ljava/lang/Object;",(void*)&WB_GetCodeHeapEntries },
2085   {CC"getCompilationActivityMode",
2086                            CC"()I",                   (void*)&WB_GetCompilationActivityMode},
2087   {CC"getMethodData0",     CC"(Ljava/lang/reflect/Executable;)J",
2088                                                       (void*)&WB_GetMethodData      },
2089   {CC"getCodeBlob",        CC"(J)[Ljava/lang/Object;",(void*)&WB_GetCodeBlob        },
2090   {CC"getThreadStackSize", CC"()J",                   (void*)&WB_GetThreadStackSize },
2091   {CC"getThreadRemainingStackSize", CC"()J",          (void*)&WB_GetThreadRemainingStackSize },
2092   {CC"DefineModule",       CC"(Ljava/lang/Object;ZLjava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)V",
2093                                                       (void*)&WB_DefineModule },
2094   {CC"AddModuleExports",   CC"(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V",
2095                                                       (void*)&WB_AddModuleExports },
2096   {CC"AddReadsModule",     CC"(Ljava/lang/Object;Ljava/lang/Object;)V",
2097                                                       (void*)&WB_AddReadsModule },
2098   {CC"AddModuleExportsToAllUnnamed", CC"(Ljava/lang/Object;Ljava/lang/String;)V",
2099                                                       (void*)&WB_AddModuleExportsToAllUnnamed },
2100   {CC"AddModuleExportsToAll", CC"(Ljava/lang/Object;Ljava/lang/String;)V",
2101                                                       (void*)&WB_AddModuleExportsToAll },
2102   {CC"assertMatchingSafepointCalls", CC"(ZZ)V",       (void*)&WB_AssertMatchingSafepointCalls },
2103   {CC"isMonitorInflated0", CC"(Ljava/lang/Object;)Z", (void*)&WB_IsMonitorInflated  },
2104   {CC"forceSafepoint",     CC"()V",                   (void*)&WB_ForceSafepoint     },
2105   {CC"getConstantPool0",   CC"(Ljava/lang/Class;)J",  (void*)&WB_GetConstantPool    },
2106   {CC"getConstantPoolCacheIndexTag0", CC"()I",  (void*)&WB_GetConstantPoolCacheIndexTag},
2107   {CC"getConstantPoolCacheLength0", CC"(Ljava/lang/Class;)I",  (void*)&WB_GetConstantPoolCacheLength},
2108   {CC"remapInstructionOperandFromCPCache0",
2109       CC"(Ljava/lang/Class;I)I",                      (void*)&WB_ConstantPoolRemapInstructionOperandFromCache},
2110   {CC"encodeConstantPoolIndyIndex0",
2111       CC"(I)I",                      (void*)&WB_ConstantPoolEncodeIndyIndex},
2112   {CC"getMethodBooleanOption",
2113       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Boolean;",
2114                                                       (void*)&WB_GetMethodBooleaneOption},
2115   {CC"getMethodIntxOption",
2116       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
2117                                                       (void*)&WB_GetMethodIntxOption},
2118   {CC"getMethodUintxOption",
2119       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Long;",
2120                                                       (void*)&WB_GetMethodUintxOption},
2121   {CC"getMethodDoubleOption",
2122       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/Double;",
2123                                                       (void*)&WB_GetMethodDoubleOption},
2124   {CC"getMethodStringOption",
2125       CC"(Ljava/lang/reflect/Executable;Ljava/lang/String;)Ljava/lang/String;",
2126                                                       (void*)&WB_GetMethodStringOption},
2127   {CC"isShared",           CC"(Ljava/lang/Object;)Z", (void*)&WB_IsShared },
2128   {CC"isSharedClass",      CC"(Ljava/lang/Class;)Z",  (void*)&WB_IsSharedClass },
2129   {CC"areSharedStringsIgnored",           CC"()Z",    (void*)&WB_AreSharedStringsIgnored },
2130   {CC"getResolvedReferences", CC"(Ljava/lang/Class;)Ljava/lang/Object;", (void*)&WB_GetResolvedReferences},
2131   {CC"areOpenArchiveHeapObjectsMapped",   CC"()Z",    (void*)&WB_AreOpenArchiveHeapObjectsMapped},
2132   {CC"isCDSIncludedInVmBuild",            CC"()Z",    (void*)&WB_IsCDSIncludedInVmBuild },
2133   {CC"isJavaHeapArchiveSupported",      CC"()Z",      (void*)&WB_IsJavaHeapArchiveSupported },
2134 
2135   {CC"clearInlineCaches0",  CC"(Z)V",                 (void*)&WB_ClearInlineCaches },
2136   {CC"handshakeWalkStack", CC"(Ljava/lang/Thread;Z)I", (void*)&WB_HandshakeWalkStack },
2137   {CC"addCompilerDirective",    CC"(Ljava/lang/String;)I",
2138                                                       (void*)&WB_AddCompilerDirective },
2139   {CC"removeCompilerDirective",   CC"(I)V",             (void*)&WB_RemoveCompilerDirective },
2140   {CC"currentGC",                 CC"()I",            (void*)&WB_CurrentGC},
2141   {CC"allSupportedGC",            CC"()I",            (void*)&WB_AllSupportedGC},
2142   {CC"gcSelectedByErgo",          CC"()Z",            (void*)&WB_GCSelectedByErgo},
2143   {CC"supportsConcurrentGCPhaseControl", CC"()Z",     (void*)&WB_SupportsConcurrentGCPhaseControl},
2144   {CC"getConcurrentGCPhases",     CC"()[Ljava/lang/String;",
2145                                                       (void*)&WB_GetConcurrentGCPhases},
2146   {CC"requestConcurrentGCPhase0", CC"(Ljava/lang/String;)Z",
2147                                                       (void*)&WB_RequestConcurrentGCPhase},
2148   {CC"checkLibSpecifiesNoexecstack", CC"(Ljava/lang/String;)Z",
2149                                                       (void*)&WB_CheckLibSpecifiesNoexecstack},
2150   {CC"isContainerized",           CC"()Z",            (void*)&WB_IsContainerized },
2151   {CC"printOsInfo",               CC"()V",            (void*)&WB_PrintOsInfo },
2152   {CC"disableElfSectionCache",    CC"()V",            (void*)&WB_DisableElfSectionCache },
2153 };
2154 
2155 
2156 #undef CC
2157 
2158 JVM_ENTRY(void, JVM_RegisterWhiteBoxMethods(JNIEnv* env, jclass wbclass))
2159   {
2160     if (WhiteBoxAPI) {
2161       // Make sure that wbclass is loaded by the null classloader
2162       InstanceKlass* ik = InstanceKlass::cast(JNIHandles::resolve(wbclass)->klass());
2163       Handle loader(THREAD, ik->class_loader());
2164       if (loader.is_null()) {
2165         WhiteBox::register_methods(env, wbclass, thread, methods, sizeof(methods) / sizeof(methods[0]));
2166         WhiteBox::set_used();
2167       }
2168     }
2169   }
2170 JVM_END