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 "memory/metadataFactory.hpp"
  28 #include "memory/metaspaceShared.hpp"
  29 #include "memory/universe.hpp"
  30 #include "oops/oop.inline.hpp"
  31 
  32 #include "classfile/symbolTable.hpp"
  33 #include "classfile/classLoaderData.hpp"
  34 
  35 #include "prims/whitebox.hpp"
  36 #include "prims/wbtestmethods/parserTests.hpp"
  37 
  38 #include "runtime/arguments.hpp"
  39 #include "runtime/interfaceSupport.hpp"
  40 #include "runtime/os.hpp"
  41 #include "utilities/array.hpp"
  42 #include "utilities/debug.hpp"
  43 #include "utilities/macros.hpp"
  44 #include "utilities/exceptions.hpp"
  45 
  46 #if INCLUDE_ALL_GCS
  47 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
  48 #include "gc_implementation/g1/concurrentMark.hpp"
  49 #include "gc_implementation/g1/concurrentMarkThread.hpp"
  50 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  51 #include "gc_implementation/g1/heapRegionRemSet.hpp"
  52 #endif // INCLUDE_ALL_GCS
  53 
  54 #if INCLUDE_NMT
  55 #include "services/mallocSiteTable.hpp"
  56 #include "services/memTracker.hpp"
  57 #include "utilities/nativeCallStack.hpp"
  58 #endif // INCLUDE_NMT
  59 
  60 #include "compiler/compileBroker.hpp"
  61 #include "jvmtifiles/jvmtiEnv.hpp"
  62 #include "runtime/compilationPolicy.hpp"
  63 
  64 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  65 
  66 #define SIZE_T_MAX_VALUE ((size_t) -1)
  67 
  68 bool WhiteBox::_used = false;
  69 
  70 WB_ENTRY(jlong, WB_GetObjectAddress(JNIEnv* env, jobject o, jobject obj))
  71   return (jlong)(void*)JNIHandles::resolve(obj);
  72 WB_END
  73 
  74 WB_ENTRY(jint, WB_GetHeapOopSize(JNIEnv* env, jobject o))
  75   return heapOopSize;
  76 WB_END
  77 
  78 WB_ENTRY(jint, WB_GetVMPageSize(JNIEnv* env, jobject o))
  79   return os::vm_page_size();
  80 WB_END
  81 
  82 WB_ENTRY(jlong, WB_GetVMLargePageSize(JNIEnv* env, jobject o))
  83   return os::large_page_size();
  84 WB_END
  85 
  86 class WBIsKlassAliveClosure : public KlassClosure {
  87     Symbol* _name;
  88     bool _found;
  89 public:
  90     WBIsKlassAliveClosure(Symbol* name) : _name(name), _found(false) {}
  91 
  92     void do_klass(Klass* k) {
  93       if (_found) return;
  94       Symbol* ksym = k->name();
  95       if (ksym->fast_compare(_name) == 0) {
  96         _found = true;
  97       }
  98     }
  99 
 100     bool found() const {
 101         return _found;
 102     }
 103 };
 104 
 105 WB_ENTRY(jboolean, WB_IsClassAlive(JNIEnv* env, jobject target, jstring name))
 106   Handle h_name = JNIHandles::resolve(name);
 107   if (h_name.is_null()) return false;
 108   Symbol* sym = java_lang_String::as_symbol(h_name, CHECK_false);
 109   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
 110 
 111   WBIsKlassAliveClosure closure(sym);
 112   ClassLoaderDataGraph::classes_do(&closure);
 113 
 114   return closure.found();
 115 WB_END
 116 
 117 WB_ENTRY(jboolean, WB_ClassKnownToNotExist(JNIEnv* env, jobject o, jobject loader, jstring name))
 118   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 119   const char* class_name = env->GetStringUTFChars(name, NULL);
 120   jboolean result = JVM_KnownToNotExist(env, loader, class_name);
 121   env->ReleaseStringUTFChars(name, class_name);
 122   return result;
 123 WB_END
 124 
 125 WB_ENTRY(jobjectArray, WB_GetLookupCacheURLs(JNIEnv* env, jobject o, jobject loader))
 126   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 127   return JVM_GetResourceLookupCacheURLs(env, loader);
 128 WB_END
 129 
 130 WB_ENTRY(jintArray, WB_GetLookupCacheMatches(JNIEnv* env, jobject o, jobject loader, jstring name))
 131   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 132   const char* resource_name = env->GetStringUTFChars(name, NULL);
 133   jintArray result = JVM_GetResourceLookupCache(env, loader, resource_name);
 134 
 135   env->ReleaseStringUTFChars(name, resource_name);
 136   return result;
 137 WB_END
 138 
 139 WB_ENTRY(void, WB_AddToBootstrapClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 140 #if INCLUDE_JVMTI
 141   ResourceMark rm;
 142   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 143   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 144   jvmtiError err = jvmti_env->AddToBootstrapClassLoaderSearch(seg);
 145   assert(err == JVMTI_ERROR_NONE, "must not fail");
 146 #endif
 147 }
 148 WB_END
 149 
 150 WB_ENTRY(void, WB_AddToSystemClassLoaderSearch(JNIEnv* env, jobject o, jstring segment)) {
 151 #if INCLUDE_JVMTI
 152   ResourceMark rm;
 153   const char* seg = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(segment));
 154   JvmtiEnv* jvmti_env = JvmtiEnv::create_a_jvmti(JVMTI_VERSION);
 155   jvmtiError err = jvmti_env->AddToSystemClassLoaderSearch(seg);
 156   assert(err == JVMTI_ERROR_NONE, "must not fail");
 157 #endif
 158 }
 159 WB_END
 160 
 161 #ifdef LINUX
 162 #include "utilities/elfFile.hpp"
 163 #include "osContainer_linux.hpp"
 164 #endif
 165 
 166 WB_ENTRY(jlong, WB_GetCompressedOopsMaxHeapSize(JNIEnv* env, jobject o)) {
 167   return (jlong)Arguments::max_heap_for_compressed_oops();
 168 }
 169 WB_END
 170 
 171 WB_ENTRY(void, WB_PrintHeapSizes(JNIEnv* env, jobject o)) {
 172   CollectorPolicy * p = Universe::heap()->collector_policy();
 173   gclog_or_tty->print_cr("Minimum heap " SIZE_FORMAT " Initial heap "
 174     SIZE_FORMAT " Maximum heap " SIZE_FORMAT " Space alignment " SIZE_FORMAT " Heap alignment " SIZE_FORMAT,
 175     p->min_heap_byte_size(), p->initial_heap_byte_size(), p->max_heap_byte_size(),
 176     p->space_alignment(), p->heap_alignment());
 177 }
 178 WB_END
 179 
 180 #ifndef PRODUCT
 181 // Forward declaration
 182 void TestReservedSpace_test();
 183 void TestReserveMemorySpecial_test();
 184 void TestVirtualSpace_test();
 185 void TestMetaspaceAux_test();
 186 #endif
 187 
 188 WB_ENTRY(void, WB_RunMemoryUnitTests(JNIEnv* env, jobject o))
 189 #ifndef PRODUCT
 190   TestReservedSpace_test();
 191   TestReserveMemorySpecial_test();
 192   TestVirtualSpace_test();
 193   TestMetaspaceAux_test();
 194 #endif
 195 WB_END
 196 
 197 WB_ENTRY(void, WB_ReadFromNoaccessArea(JNIEnv* env, jobject o))
 198   size_t granularity = os::vm_allocation_granularity();
 199   ReservedHeapSpace rhs(100 * granularity, granularity, false, NULL);
 200   VirtualSpace vs;
 201   vs.initialize(rhs, 50 * granularity);
 202 
 203   //Check if constraints are complied
 204   if (!( UseCompressedOops && rhs.base() != NULL &&
 205          Universe::narrow_oop_base() != NULL &&
 206          Universe::narrow_oop_use_implicit_null_checks() )) {
 207     tty->print_cr("WB_ReadFromNoaccessArea method is useless:\n "
 208                   "\tUseCompressedOops is %d\n"
 209                   "\trhs.base() is " PTR_FORMAT "\n"
 210                   "\tUniverse::narrow_oop_base() is " PTR_FORMAT "\n"
 211                   "\tUniverse::narrow_oop_use_implicit_null_checks() is %d",
 212                   UseCompressedOops,
 213                   rhs.base(),
 214                   Universe::narrow_oop_base(),
 215                   Universe::narrow_oop_use_implicit_null_checks());
 216     return;
 217   }
 218   tty->print_cr("Reading from no access area... ");
 219   tty->print_cr("*(vs.low_boundary() - rhs.noaccess_prefix() / 2 ) = %c",
 220                 *(vs.low_boundary() - rhs.noaccess_prefix() / 2 ));
 221 WB_END
 222 
 223 static jint wb_stress_virtual_space_resize(size_t reserved_space_size,
 224                                            size_t magnitude, size_t iterations) {
 225   size_t granularity = os::vm_allocation_granularity();
 226   ReservedHeapSpace rhs(reserved_space_size * granularity, granularity, false, NULL);
 227   VirtualSpace vs;
 228   if (!vs.initialize(rhs, 0)) {
 229     tty->print_cr("Failed to initialize VirtualSpace. Can't proceed.");
 230     return 3;
 231   }
 232 
 233   long seed = os::random();
 234   tty->print_cr("Random seed is %ld", seed);
 235   os::init_random(seed);
 236 
 237   for (size_t i = 0; i < iterations; i++) {
 238 
 239     // Whether we will shrink or grow
 240     bool shrink = os::random() % 2L == 0;
 241 
 242     // Get random delta to resize virtual space
 243     size_t delta = (size_t)os::random() % magnitude;
 244 
 245     // If we are about to shrink virtual space below zero, then expand instead
 246     if (shrink && vs.committed_size() < delta) {
 247       shrink = false;
 248     }
 249 
 250     // Resizing by delta
 251     if (shrink) {
 252       vs.shrink_by(delta);
 253     } else {
 254       // If expanding fails expand_by will silently return false
 255       vs.expand_by(delta, true);
 256     }
 257   }
 258   return 0;
 259 }
 260 
 261 WB_ENTRY(jint, WB_StressVirtualSpaceResize(JNIEnv* env, jobject o,
 262         jlong reserved_space_size, jlong magnitude, jlong iterations))
 263   tty->print_cr("reservedSpaceSize=" JLONG_FORMAT ", magnitude=" JLONG_FORMAT ", "
 264                 "iterations=" JLONG_FORMAT "\n", reserved_space_size, magnitude,
 265                 iterations);
 266   if (reserved_space_size < 0 || magnitude < 0 || iterations < 0) {
 267     tty->print_cr("One of variables printed above is negative. Can't proceed.\n");
 268     return 1;
 269   }
 270 
 271   // sizeof(size_t) depends on whether OS is 32bit or 64bit. sizeof(jlong) is
 272   // always 8 byte. That's why we should avoid overflow in case of 32bit platform.
 273   if (sizeof(size_t) < sizeof(jlong)) {
 274     jlong size_t_max_value = (jlong) SIZE_T_MAX_VALUE;
 275     if (reserved_space_size > size_t_max_value || magnitude > size_t_max_value
 276         || iterations > size_t_max_value) {
 277       tty->print_cr("One of variables printed above overflows size_t. Can't proceed.\n");
 278       return 2;
 279     }
 280   }
 281 
 282   return wb_stress_virtual_space_resize((size_t) reserved_space_size,
 283                                         (size_t) magnitude, (size_t) iterations);
 284 WB_END
 285 
 286 WB_ENTRY(jboolean, WB_isObjectInOldGen(JNIEnv* env, jobject o, jobject obj))
 287   oop p = JNIHandles::resolve(obj);
 288 #if INCLUDE_ALL_GCS
 289   if (UseG1GC) {
 290     G1CollectedHeap* g1 = G1CollectedHeap::heap();
 291     const HeapRegion* hr = g1->heap_region_containing(p);
 292     if (hr == NULL) {
 293       return false;
 294     }
 295     return !(hr->is_young());
 296   } else if (UseParallelGC) {
 297     ParallelScavengeHeap* psh = ParallelScavengeHeap::heap();
 298     return !psh->is_in_young(p);
 299   }
 300 #endif // INCLUDE_ALL_GCS
 301   GenCollectedHeap* gch = GenCollectedHeap::heap();
 302   return !gch->is_in_young(p);
 303 WB_END
 304 
 305 WB_ENTRY(jlong, WB_GetObjectSize(JNIEnv* env, jobject o, jobject obj))
 306   oop p = JNIHandles::resolve(obj);
 307   return p->size() * HeapWordSize;
 308 WB_END
 309 
 310 #if INCLUDE_ALL_GCS
 311 WB_ENTRY(jboolean, WB_G1IsHumongous(JNIEnv* env, jobject o, jobject obj))
 312   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 313   oop result = JNIHandles::resolve(obj);
 314   const HeapRegion* hr = g1->heap_region_containing(result);
 315   return hr->isHumongous();
 316 WB_END
 317 
 318 WB_ENTRY(jlong, WB_G1NumMaxRegions(JNIEnv* env, jobject o))
 319   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 320   size_t nr = g1->max_regions();
 321   return (jlong)nr;
 322 WB_END
 323 
 324 WB_ENTRY(jlong, WB_G1NumFreeRegions(JNIEnv* env, jobject o))
 325   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 326   size_t nr = g1->num_free_regions();
 327   return (jlong)nr;
 328 WB_END
 329 
 330 WB_ENTRY(jboolean, WB_G1InConcurrentMark(JNIEnv* env, jobject o))
 331   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 332   return g1->concurrent_mark()->cmThread()->during_cycle();
 333 WB_END
 334 
 335 WB_ENTRY(jboolean, WB_G1StartMarkCycle(JNIEnv* env, jobject o))
 336   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 337   if (!g1h->concurrent_mark()->cmThread()->during_cycle()) {
 338     g1h->collect(GCCause::_wb_conc_mark);
 339     return true;
 340   }
 341   return false;
 342 WB_END
 343 
 344 WB_ENTRY(jint, WB_G1RegionSize(JNIEnv* env, jobject o))
 345   return (jint)HeapRegion::GrainBytes;
 346 WB_END
 347 
 348 WB_ENTRY(jobject, WB_G1AuxiliaryMemoryUsage(JNIEnv* env))
 349   ResourceMark rm(THREAD);
 350   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 351   MemoryUsage usage = g1h->get_auxiliary_data_memory_usage();
 352   Handle h = MemoryService::create_MemoryUsage_obj(usage, CHECK_NULL);
 353   return JNIHandles::make_local(env, h());
 354 WB_END
 355 #endif // INCLUDE_ALL_GCS
 356 
 357 #if INCLUDE_NMT
 358 // Alloc memory using the test memory type so that we can use that to see if
 359 // NMT picks it up correctly
 360 WB_ENTRY(jlong, WB_NMTMalloc(JNIEnv* env, jobject o, jlong size))
 361   jlong addr = 0;
 362   addr = (jlong)(uintptr_t)os::malloc(size, mtTest);
 363   return addr;
 364 WB_END
 365 
 366 // Alloc memory with pseudo call stack. The test can create psudo malloc
 367 // allocation site to stress the malloc tracking.
 368 WB_ENTRY(jlong, WB_NMTMallocWithPseudoStack(JNIEnv* env, jobject o, jlong size, jint pseudo_stack))
 369   address pc = (address)(size_t)pseudo_stack;
 370   NativeCallStack stack(&pc, 1);
 371   return (jlong)(uintptr_t)os::malloc(size, mtTest, stack);
 372 WB_END
 373 
 374 // Free the memory allocated by NMTAllocTest
 375 WB_ENTRY(void, WB_NMTFree(JNIEnv* env, jobject o, jlong mem))
 376   os::free((void*)(uintptr_t)mem, mtTest);
 377 WB_END
 378 
 379 WB_ENTRY(jlong, WB_NMTReserveMemory(JNIEnv* env, jobject o, jlong size))
 380   jlong addr = 0;
 381 
 382     addr = (jlong)(uintptr_t)os::reserve_memory(size);
 383     MemTracker::record_virtual_memory_type((address)addr, mtTest);
 384 
 385   return addr;
 386 WB_END
 387 
 388 
 389 WB_ENTRY(void, WB_NMTCommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 390   os::commit_memory((char *)(uintptr_t)addr, size, !ExecMem);
 391   MemTracker::record_virtual_memory_type((address)(uintptr_t)addr, mtTest);
 392 WB_END
 393 
 394 WB_ENTRY(void, WB_NMTUncommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 395   os::uncommit_memory((char *)(uintptr_t)addr, size);
 396 WB_END
 397 
 398 WB_ENTRY(void, WB_NMTReleaseMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 399   os::release_memory((char *)(uintptr_t)addr, size);
 400 WB_END
 401 
 402 WB_ENTRY(jboolean, WB_NMTIsDetailSupported(JNIEnv* env))
 403   return MemTracker::tracking_level() == NMT_detail;
 404 WB_END
 405 
 406 WB_ENTRY(jboolean, WB_NMTChangeTrackingLevel(JNIEnv* env))
 407   // Test that we can downgrade NMT levels but not upgrade them.
 408   if (MemTracker::tracking_level() == NMT_off) {
 409     MemTracker::transition_to(NMT_off);
 410     return MemTracker::tracking_level() == NMT_off;
 411   } else {
 412     assert(MemTracker::tracking_level() == NMT_detail, "Should start out as detail tracking");
 413     MemTracker::transition_to(NMT_summary);
 414     assert(MemTracker::tracking_level() == NMT_summary, "Should be summary now");
 415 
 416     // Can't go to detail once NMT is set to summary.
 417     MemTracker::transition_to(NMT_detail);
 418     assert(MemTracker::tracking_level() == NMT_summary, "Should still be summary now");
 419 
 420     // Shutdown sets tracking level to minimal.
 421     MemTracker::shutdown();
 422     assert(MemTracker::tracking_level() == NMT_minimal, "Should be minimal now");
 423 
 424     // Once the tracking level is minimal, we cannot increase to summary.
 425     // The code ignores this request instead of asserting because if the malloc site
 426     // table overflows in another thread, it tries to change the code to summary.
 427     MemTracker::transition_to(NMT_summary);
 428     assert(MemTracker::tracking_level() == NMT_minimal, "Should still be minimal now");
 429 
 430     // Really can never go up to detail, verify that the code would never do this.
 431     MemTracker::transition_to(NMT_detail);
 432     assert(MemTracker::tracking_level() == NMT_minimal, "Should still be minimal now");
 433     return MemTracker::tracking_level() == NMT_minimal;
 434   }
 435 WB_END
 436 
 437 WB_ENTRY(jint, WB_NMTGetHashSize(JNIEnv* env, jobject o))
 438   int hash_size = MallocSiteTable::hash_buckets();
 439   assert(hash_size > 0, "NMT hash_size should be > 0");
 440   return (jint)hash_size;
 441 WB_END
 442 #endif // INCLUDE_NMT
 443 
 444 static jmethodID reflected_method_to_jmid(JavaThread* thread, JNIEnv* env, jobject method) {
 445   assert(method != NULL, "method should not be null");
 446   ThreadToNativeFromVM ttn(thread);
 447   return env->FromReflectedMethod(method);
 448 }
 449 
 450 WB_ENTRY(void, WB_DeoptimizeAll(JNIEnv* env, jobject o))
 451   MutexLockerEx mu(Compile_lock);
 452   CodeCache::mark_all_nmethods_for_deoptimization();
 453   VM_Deoptimize op;
 454   VMThread::execute(&op);
 455 WB_END
 456 
 457 WB_ENTRY(jint, WB_DeoptimizeMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 458   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 459   int result = 0;
 460   CHECK_JNI_EXCEPTION_(env, result);
 461   MutexLockerEx mu(Compile_lock);
 462   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 463   if (is_osr) {
 464     result += mh->mark_osr_nmethods();
 465   } else if (mh->code() != NULL) {
 466     mh->code()->mark_for_deoptimization();
 467     ++result;
 468   }
 469   result += CodeCache::mark_for_deoptimization(mh());
 470   if (result > 0) {
 471     VM_Deoptimize op;
 472     VMThread::execute(&op);
 473   }
 474   return result;
 475 WB_END
 476 
 477 WB_ENTRY(jboolean, WB_IsMethodCompiled(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 478   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 479   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 480   MutexLockerEx mu(Compile_lock);
 481   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 482   nmethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 483   if (code == NULL) {
 484     return JNI_FALSE;
 485   }
 486   return (code->is_alive() && !code->is_marked_for_deoptimization());
 487 WB_END
 488 
 489 WB_ENTRY(jboolean, WB_IsMethodCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 490   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 491   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 492   MutexLockerEx mu(Compile_lock);
 493   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 494   if (is_osr) {
 495     return CompilationPolicy::can_be_osr_compiled(mh, comp_level);
 496   } else {
 497     return CompilationPolicy::can_be_compiled(mh, comp_level);
 498   }
 499 WB_END
 500 
 501 WB_ENTRY(jboolean, WB_IsMethodQueuedForCompilation(JNIEnv* env, jobject o, jobject method))
 502   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 503   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 504   MutexLockerEx mu(Compile_lock);
 505   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 506   return mh->queued_for_compilation();
 507 WB_END
 508 
 509 WB_ENTRY(jint, WB_GetMethodCompilationLevel(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 510   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 511   CHECK_JNI_EXCEPTION_(env, CompLevel_none);
 512   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 513   nmethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 514   return (code != NULL ? code->comp_level() : CompLevel_none);
 515 WB_END
 516 
 517 WB_ENTRY(void, WB_MakeMethodNotCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 518   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 519   CHECK_JNI_EXCEPTION(env);
 520   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 521   if (is_osr) {
 522     mh->set_not_osr_compilable(comp_level, true /* report */, "WhiteBox");
 523   } else {
 524     mh->set_not_compilable(comp_level, true /* report */, "WhiteBox");
 525   }
 526 WB_END
 527 
 528 WB_ENTRY(jint, WB_GetMethodEntryBci(JNIEnv* env, jobject o, jobject method))
 529   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 530   CHECK_JNI_EXCEPTION_(env, InvocationEntryBci);
 531   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 532   nmethod* code = mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false);
 533   return (code != NULL && code->is_osr_method() ? code->osr_entry_bci() : InvocationEntryBci);
 534 WB_END
 535 
 536 WB_ENTRY(jboolean, WB_TestSetDontInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 537   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 538   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 539   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 540   bool result = mh->dont_inline();
 541   mh->set_dont_inline(value == JNI_TRUE);
 542   return result;
 543 WB_END
 544 
 545 WB_ENTRY(jint, WB_GetCompileQueueSize(JNIEnv* env, jobject o, jint comp_level))
 546   if (comp_level == CompLevel_any) {
 547     return CompileBroker::queue_size(CompLevel_full_optimization) /* C2 */ +
 548         CompileBroker::queue_size(CompLevel_full_profile) /* C1 */;
 549   } else {
 550     return CompileBroker::queue_size(comp_level);
 551   }
 552 WB_END
 553 
 554 WB_ENTRY(jboolean, WB_TestSetForceInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 555   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 556   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 557   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 558   bool result = mh->force_inline();
 559   mh->set_force_inline(value == JNI_TRUE);
 560   return result;
 561 WB_END
 562 
 563 WB_ENTRY(jboolean, WB_EnqueueMethodForCompilation(JNIEnv* env, jobject o, jobject method, jint comp_level, jint bci))
 564   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 565   CHECK_JNI_EXCEPTION_(env, JNI_FALSE);
 566   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 567   nmethod* nm = CompileBroker::compile_method(mh, bci, comp_level, mh, mh->invocation_count(), "WhiteBox", THREAD);
 568   MutexLockerEx mu(Compile_lock);
 569   return (mh->queued_for_compilation() || nm != NULL);
 570 WB_END
 571 
 572 class VM_WhiteBoxOperation : public VM_Operation {
 573  public:
 574   VM_WhiteBoxOperation()                         { }
 575   VMOp_Type type()                  const        { return VMOp_WhiteBoxOperation; }
 576   bool allow_nested_vm_operations() const        { return true; }
 577 };
 578 
 579 class AlwaysFalseClosure : public BoolObjectClosure {
 580  public:
 581   bool do_object_b(oop p) { return false; }
 582 };
 583 
 584 static AlwaysFalseClosure always_false;
 585 
 586 class VM_WhiteBoxCleanMethodData : public VM_WhiteBoxOperation {
 587  public:
 588   VM_WhiteBoxCleanMethodData(MethodData* mdo) : _mdo(mdo) { }
 589   void doit() {
 590     _mdo->clean_method_data(&always_false);
 591   }
 592  private:
 593   MethodData* _mdo;
 594 };
 595 
 596 WB_ENTRY(void, WB_ClearMethodState(JNIEnv* env, jobject o, jobject method))
 597   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 598   CHECK_JNI_EXCEPTION(env);
 599   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 600   MutexLockerEx mu(Compile_lock);
 601   MethodData* mdo = mh->method_data();
 602   MethodCounters* mcs = mh->method_counters();
 603 
 604   if (mdo != NULL) {
 605     mdo->init();
 606     ResourceMark rm;
 607     int arg_count = mdo->method()->size_of_parameters();
 608     for (int i = 0; i < arg_count; i++) {
 609       mdo->set_arg_modified(i, 0);
 610     }
 611     VM_WhiteBoxCleanMethodData op(mdo);
 612     VMThread::execute(&op);
 613   }
 614 
 615   mh->clear_not_c1_compilable();
 616   mh->clear_not_c2_compilable();
 617   mh->clear_not_c2_osr_compilable();
 618   NOT_PRODUCT(mh->set_compiled_invocation_count(0));
 619   if (mcs != NULL) {
 620     mcs->backedge_counter()->init();
 621     mcs->invocation_counter()->init();
 622     mcs->set_interpreter_invocation_count(0);
 623     mcs->set_interpreter_throwout_count(0);
 624 
 625 #ifdef TIERED
 626     mcs->set_rate(0.0F);
 627     mh->set_prev_event_count(0);
 628     mh->set_prev_time(0);
 629 #endif
 630   }
 631 WB_END
 632 
 633 template <typename T>
 634 static bool GetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, bool (*TAt)(const char*, T*)) {
 635   if (name == NULL) {
 636     return false;
 637   }
 638   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 639   const char* flag_name = env->GetStringUTFChars(name, NULL);
 640   bool result = (*TAt)(flag_name, value);
 641   env->ReleaseStringUTFChars(name, flag_name);
 642   return result;
 643 }
 644 
 645 template <typename T>
 646 static bool SetVMFlag(JavaThread* thread, JNIEnv* env, jstring name, T* value, bool (*TAtPut)(const char*, T*, Flag::Flags)) {
 647   if (name == NULL) {
 648     return false;
 649   }
 650   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 651   const char* flag_name = env->GetStringUTFChars(name, NULL);
 652   bool result = (*TAtPut)(flag_name, value, Flag::INTERNAL);
 653   env->ReleaseStringUTFChars(name, flag_name);
 654   return result;
 655 }
 656 
 657 template <typename T>
 658 static jobject box(JavaThread* thread, JNIEnv* env, Symbol* name, Symbol* sig, T value) {
 659   ResourceMark rm(thread);
 660   jclass clazz = env->FindClass(name->as_C_string());
 661   CHECK_JNI_EXCEPTION_(env, NULL);
 662   jmethodID methodID = env->GetStaticMethodID(clazz,
 663         vmSymbols::valueOf_name()->as_C_string(),
 664         sig->as_C_string());
 665   CHECK_JNI_EXCEPTION_(env, NULL);
 666   jobject result = env->CallStaticObjectMethod(clazz, methodID, value);
 667   CHECK_JNI_EXCEPTION_(env, NULL);
 668   return result;
 669 }
 670 
 671 static jobject booleanBox(JavaThread* thread, JNIEnv* env, jboolean value) {
 672   return box(thread, env, vmSymbols::java_lang_Boolean(), vmSymbols::Boolean_valueOf_signature(), value);
 673 }
 674 static jobject integerBox(JavaThread* thread, JNIEnv* env, jint value) {
 675   return box(thread, env, vmSymbols::java_lang_Integer(), vmSymbols::Integer_valueOf_signature(), value);
 676 }
 677 static jobject longBox(JavaThread* thread, JNIEnv* env, jlong value) {
 678   return box(thread, env, vmSymbols::java_lang_Long(), vmSymbols::Long_valueOf_signature(), value);
 679 }
 680 /* static jobject floatBox(JavaThread* thread, JNIEnv* env, jfloat value) {
 681   return box(thread, env, vmSymbols::java_lang_Float(), vmSymbols::Float_valueOf_signature(), value);
 682 }*/
 683 static jobject doubleBox(JavaThread* thread, JNIEnv* env, jdouble value) {
 684   return box(thread, env, vmSymbols::java_lang_Double(), vmSymbols::Double_valueOf_signature(), value);
 685 }
 686 
 687 WB_ENTRY(jobject, WB_GetBooleanVMFlag(JNIEnv* env, jobject o, jstring name))
 688   bool result;
 689   if (GetVMFlag <bool> (thread, env, name, &result, &CommandLineFlags::boolAt)) {
 690     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 691     return booleanBox(thread, env, result);
 692   }
 693   return NULL;
 694 WB_END
 695 
 696 WB_ENTRY(jobject, WB_GetIntxVMFlag(JNIEnv* env, jobject o, jstring name))
 697   intx result;
 698   if (GetVMFlag <intx> (thread, env, name, &result, &CommandLineFlags::intxAt)) {
 699     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 700     return longBox(thread, env, result);
 701   }
 702   return NULL;
 703 WB_END
 704 
 705 WB_ENTRY(jobject, WB_GetUintxVMFlag(JNIEnv* env, jobject o, jstring name))
 706   uintx result;
 707   if (GetVMFlag <uintx> (thread, env, name, &result, &CommandLineFlags::uintxAt)) {
 708     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 709     return longBox(thread, env, result);
 710   }
 711   return NULL;
 712 WB_END
 713 
 714 WB_ENTRY(jobject, WB_GetUint64VMFlag(JNIEnv* env, jobject o, jstring name))
 715   uint64_t result;
 716   if (GetVMFlag <uint64_t> (thread, env, name, &result, &CommandLineFlags::uint64_tAt)) {
 717     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 718     return longBox(thread, env, result);
 719   }
 720   return NULL;
 721 WB_END
 722 
 723 WB_ENTRY(jobject, WB_GetDoubleVMFlag(JNIEnv* env, jobject o, jstring name))
 724   double result;
 725   if (GetVMFlag <double> (thread, env, name, &result, &CommandLineFlags::doubleAt)) {
 726     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 727     return doubleBox(thread, env, result);
 728   }
 729   return NULL;
 730 WB_END
 731 
 732 WB_ENTRY(jstring, WB_GetStringVMFlag(JNIEnv* env, jobject o, jstring name))
 733   ccstr ccstrResult;
 734   if (GetVMFlag <ccstr> (thread, env, name, &ccstrResult, &CommandLineFlags::ccstrAt)) {
 735     ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 736     jstring result = env->NewStringUTF(ccstrResult);
 737     CHECK_JNI_EXCEPTION_(env, NULL);
 738     return result;
 739   }
 740   return NULL;
 741 WB_END
 742 
 743 WB_ENTRY(void, WB_SetBooleanVMFlag(JNIEnv* env, jobject o, jstring name, jboolean value))
 744   bool result = value == JNI_TRUE ? true : false;
 745   SetVMFlag <bool> (thread, env, name, &result, &CommandLineFlags::boolAtPut);
 746 WB_END
 747 
 748 WB_ENTRY(void, WB_SetIntxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
 749   intx result = value;
 750   SetVMFlag <intx> (thread, env, name, &result, &CommandLineFlags::intxAtPut);
 751 WB_END
 752 
 753 WB_ENTRY(void, WB_SetUintxVMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
 754   uintx result = value;
 755   SetVMFlag <uintx> (thread, env, name, &result, &CommandLineFlags::uintxAtPut);
 756 WB_END
 757 
 758 WB_ENTRY(void, WB_SetUint64VMFlag(JNIEnv* env, jobject o, jstring name, jlong value))
 759   uint64_t result = value;
 760   SetVMFlag <uint64_t> (thread, env, name, &result, &CommandLineFlags::uint64_tAtPut);
 761 WB_END
 762 
 763 WB_ENTRY(void, WB_SetDoubleVMFlag(JNIEnv* env, jobject o, jstring name, jdouble value))
 764   double result = value;
 765   SetVMFlag <double> (thread, env, name, &result, &CommandLineFlags::doubleAtPut);
 766 WB_END
 767 
 768 WB_ENTRY(void, WB_SetStringVMFlag(JNIEnv* env, jobject o, jstring name, jstring value))
 769   ThreadToNativeFromVM ttnfv(thread);   // can't be in VM when we call JNI
 770   const char* ccstrValue = (value == NULL) ? NULL : env->GetStringUTFChars(value, NULL);
 771   ccstr ccstrResult = ccstrValue;
 772   bool needFree;
 773   {
 774     ThreadInVMfromNative ttvfn(thread); // back to VM
 775     needFree = SetVMFlag <ccstr> (thread, env, name, &ccstrResult, &CommandLineFlags::ccstrAtPut);
 776   }
 777   if (value != NULL) {
 778     env->ReleaseStringUTFChars(value, ccstrValue);
 779   }
 780   if (needFree) {
 781     FREE_C_HEAP_ARRAY(char, ccstrResult, mtInternal);
 782   }
 783 WB_END
 784 
 785 
 786 WB_ENTRY(jboolean, WB_IsInStringTable(JNIEnv* env, jobject o, jstring javaString))
 787   ResourceMark rm(THREAD);
 788   int len;
 789   jchar* name = java_lang_String::as_unicode_string(JNIHandles::resolve(javaString), len, CHECK_false);
 790   return (StringTable::lookup(name, len) != NULL);
 791 WB_END
 792 
 793 WB_ENTRY(void, WB_FullGC(JNIEnv* env, jobject o))
 794   Universe::heap()->collector_policy()->set_should_clear_all_soft_refs(true);
 795   Universe::heap()->collect(GCCause::_last_ditch_collection);
 796 #if INCLUDE_ALL_GCS
 797   if (UseG1GC) {
 798     // Needs to be cleared explicitly for G1
 799     Universe::heap()->collector_policy()->set_should_clear_all_soft_refs(false);
 800   }
 801 #endif // INCLUDE_ALL_GCS
 802 WB_END
 803 
 804 WB_ENTRY(void, WB_YoungGC(JNIEnv* env, jobject o))
 805   Universe::heap()->collect(GCCause::_wb_young_gc);
 806 WB_END
 807 
 808 WB_ENTRY(void, WB_ReadReservedMemory(JNIEnv* env, jobject o))
 809   // static+volatile in order to force the read to happen
 810   // (not be eliminated by the compiler)
 811   static char c;
 812   static volatile char* p;
 813 
 814   p = os::reserve_memory(os::vm_allocation_granularity(), NULL, 0);
 815   if (p == NULL) {
 816     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "Failed to reserve memory");
 817   }
 818 
 819   c = *p;
 820 WB_END
 821 
 822 WB_ENTRY(jstring, WB_GetCPUFeatures(JNIEnv* env, jobject o))
 823   const char* cpu_features = VM_Version::cpu_features();
 824   ThreadToNativeFromVM ttn(thread);
 825   jstring features_string = env->NewStringUTF(cpu_features);
 826 
 827   CHECK_JNI_EXCEPTION_(env, NULL);
 828 
 829   return features_string;
 830 WB_END
 831 
 832 
 833 WB_ENTRY(jobjectArray, WB_GetNMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 834   ResourceMark rm(THREAD);
 835   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 836   CHECK_JNI_EXCEPTION_(env, NULL);
 837   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 838   nmethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 839   jobjectArray result = NULL;
 840   if (code == NULL) {
 841     return result;
 842   }
 843   int insts_size = code->insts_size();
 844 
 845   ThreadToNativeFromVM ttn(thread);
 846   jclass clazz = env->FindClass(vmSymbols::java_lang_Object()->as_C_string());
 847   CHECK_JNI_EXCEPTION_(env, NULL);
 848   result = env->NewObjectArray(2, clazz, NULL);
 849   if (result == NULL) {
 850     return result;
 851   }
 852 
 853   jobject obj = integerBox(thread, env, code->comp_level());
 854   CHECK_JNI_EXCEPTION_(env, NULL);
 855   env->SetObjectArrayElement(result, 0, obj);
 856 
 857   jbyteArray insts = env->NewByteArray(insts_size);
 858   CHECK_JNI_EXCEPTION_(env, NULL);
 859   env->SetByteArrayRegion(insts, 0, insts_size, (jbyte*) code->insts_begin());
 860   env->SetObjectArrayElement(result, 1, insts);
 861 
 862   return result;
 863 WB_END
 864 
 865 
 866 int WhiteBox::array_bytes_to_length(size_t bytes) {
 867   return Array<u1>::bytes_to_length(bytes);
 868 }
 869 
 870 WB_ENTRY(jlong, WB_AllocateMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong size))
 871   if (size < 0) {
 872     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 873         err_msg("WB_AllocateMetaspace: size is negative: " JLONG_FORMAT, size));
 874   }
 875 
 876   oop class_loader_oop = JNIHandles::resolve(class_loader);
 877   ClassLoaderData* cld = class_loader_oop != NULL
 878       ? java_lang_ClassLoader::loader_data(class_loader_oop)
 879       : ClassLoaderData::the_null_class_loader_data();
 880 
 881   void* metadata = MetadataFactory::new_writeable_array<u1>(cld, WhiteBox::array_bytes_to_length((size_t)size), thread);
 882 
 883   return (jlong)(uintptr_t)metadata;
 884 WB_END
 885 
 886 WB_ENTRY(void, WB_FreeMetaspace(JNIEnv* env, jobject wb, jobject class_loader, jlong addr, jlong size))
 887   oop class_loader_oop = JNIHandles::resolve(class_loader);
 888   ClassLoaderData* cld = class_loader_oop != NULL
 889       ? java_lang_ClassLoader::loader_data(class_loader_oop)
 890       : ClassLoaderData::the_null_class_loader_data();
 891 
 892   MetadataFactory::free_array(cld, (Array<u1>*)(uintptr_t)addr);
 893 WB_END
 894 
 895 WB_ENTRY(jlong, WB_IncMetaspaceCapacityUntilGC(JNIEnv* env, jobject wb, jlong inc))
 896   if (inc < 0) {
 897     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 898         err_msg("WB_IncMetaspaceCapacityUntilGC: inc is negative: " JLONG_FORMAT, inc));
 899   }
 900 
 901   jlong max_size_t = (jlong) ((size_t) -1);
 902   if (inc > max_size_t) {
 903     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 904         err_msg("WB_IncMetaspaceCapacityUntilGC: inc does not fit in size_t: " JLONG_FORMAT, inc));
 905   }
 906 
 907   size_t new_cap_until_GC = 0;
 908   size_t aligned_inc = align_size_down((size_t) inc, Metaspace::commit_alignment());
 909   bool success = MetaspaceGC::inc_capacity_until_GC(aligned_inc, &new_cap_until_GC);
 910   if (!success) {
 911     THROW_MSG_0(vmSymbols::java_lang_IllegalStateException(),
 912                 "WB_IncMetaspaceCapacityUntilGC: could not increase capacity until GC "
 913                 "due to contention with another thread");
 914   }
 915   return (jlong) new_cap_until_GC;
 916 WB_END
 917 
 918 WB_ENTRY(jlong, WB_MetaspaceCapacityUntilGC(JNIEnv* env, jobject wb))
 919   return (jlong) MetaspaceGC::capacity_until_GC();
 920 WB_END
 921 
 922 WB_ENTRY(jboolean, WB_IsSharedClass(JNIEnv* env, jobject wb, jclass clazz))
 923   return (jboolean)MetaspaceShared::is_in_shared_space(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
 924 WB_END
 925 
 926 WB_ENTRY(jboolean, WB_IsMonitorInflated(JNIEnv* env, jobject wb, jobject obj))
 927   oop obj_oop = JNIHandles::resolve(obj);
 928   return (jboolean) obj_oop->mark()->has_monitor();
 929 WB_END
 930 
 931 WB_ENTRY(void, WB_ForceSafepoint(JNIEnv* env, jobject wb))
 932   VM_ForceSafepoint force_safepoint_op;
 933   VMThread::execute(&force_safepoint_op);
 934 WB_END
 935 
 936 //Some convenience methods to deal with objects from java
 937 int WhiteBox::offset_for_field(const char* field_name, oop object,
 938     Symbol* signature_symbol) {
 939   assert(field_name != NULL && strlen(field_name) > 0, "Field name not valid");
 940   Thread* THREAD = Thread::current();
 941 
 942   //Get the class of our object
 943   Klass* arg_klass = object->klass();
 944   //Turn it into an instance-klass
 945   InstanceKlass* ik = InstanceKlass::cast(arg_klass);
 946 
 947   //Create symbols to look for in the class
 948   TempNewSymbol name_symbol = SymbolTable::lookup(field_name, (int) strlen(field_name),
 949       THREAD);
 950 
 951   //To be filled in with an offset of the field we're looking for
 952   fieldDescriptor fd;
 953 
 954   Klass* res = ik->find_field(name_symbol, signature_symbol, &fd);
 955   if (res == NULL) {
 956     tty->print_cr("Invalid layout of %s at %s", ik->external_name(),
 957         name_symbol->as_C_string());
 958     vm_exit_during_initialization("Invalid layout of preloaded class: use -XX:+TraceClassLoading to see the origin of the problem class");
 959   }
 960 
 961   //fetch the field at the offset we've found
 962   int dest_offset = fd.offset();
 963 
 964   return dest_offset;
 965 }
 966 
 967 
 968 const char* WhiteBox::lookup_jstring(const char* field_name, oop object) {
 969   int offset = offset_for_field(field_name, object,
 970       vmSymbols::string_signature());
 971   oop string = object->obj_field(offset);
 972   if (string == NULL) {
 973     return NULL;
 974   }
 975   const char* ret = java_lang_String::as_utf8_string(string);
 976   return ret;
 977 }
 978 
 979 bool WhiteBox::lookup_bool(const char* field_name, oop object) {
 980   int offset =
 981       offset_for_field(field_name, object, vmSymbols::bool_signature());
 982   bool ret = (object->bool_field(offset) == JNI_TRUE);
 983   return ret;
 984 }
 985 
 986 void WhiteBox::register_methods(JNIEnv* env, jclass wbclass, JavaThread* thread, JNINativeMethod* method_array, int method_count) {
 987   ResourceMark rm;
 988   ThreadToNativeFromVM ttnfv(thread); // can't be in VM when we call JNI
 989 
 990   //  one by one registration natives for exception catching
 991   jclass no_such_method_error_klass = env->FindClass(vmSymbols::java_lang_NoSuchMethodError()->as_C_string());
 992   CHECK_JNI_EXCEPTION(env);
 993   for (int i = 0, n = method_count; i < n; ++i) {
 994     // Skip dummy entries
 995     if (method_array[i].fnPtr == NULL) continue;
 996     if (env->RegisterNatives(wbclass, &method_array[i], 1) != 0) {
 997       jthrowable throwable_obj = env->ExceptionOccurred();
 998       if (throwable_obj != NULL) {
 999         env->ExceptionClear();
1000         if (env->IsInstanceOf(throwable_obj, no_such_method_error_klass)) {
1001           // NoSuchMethodError is thrown when a method can't be found or a method is not native.
1002           // Ignoring the exception since it is not preventing use of other WhiteBox methods.
1003           tty->print_cr("Warning: 'NoSuchMethodError' on register of sun.hotspot.WhiteBox::%s%s",
1004               method_array[i].name, method_array[i].signature);
1005         }
1006       } else {
1007         // Registration failed unexpectedly.
1008         tty->print_cr("Warning: unexpected error on register of sun.hotspot.WhiteBox::%s%s. All methods will be unregistered",
1009             method_array[i].name, method_array[i].signature);
1010         env->UnregisterNatives(wbclass);
1011         break;
1012       }
1013     }
1014   }
1015 }
1016 
1017 // Checks that the library libfile has the noexecstack bit set.
1018 WB_ENTRY(jboolean, WB_CheckLibSpecifiesNoexecstack(JNIEnv* env, jobject o, jstring libfile))
1019   jboolean ret = false;
1020 #ifdef LINUX
1021   // Can't be in VM when we call JNI.
1022   ThreadToNativeFromVM ttnfv(thread);
1023   const char* lf = env->GetStringUTFChars(libfile, NULL);
1024   CHECK_JNI_EXCEPTION_(env, 0);
1025   ElfFile ef(lf);
1026   ret = (jboolean) ef.specifies_noexecstack();
1027   env->ReleaseStringUTFChars(libfile, lf);
1028 #endif
1029   return ret;
1030 WB_END
1031 
1032 WB_ENTRY(jboolean, WB_IsContainerized(JNIEnv* env, jobject o))
1033   LINUX_ONLY(return OSContainer::is_containerized();)
1034   return false;
1035 WB_END
1036 
1037 WB_ENTRY(void, WB_PrintOsInfo(JNIEnv* env, jobject o))
1038   os::print_os_info(tty);
1039 WB_END
1040 
1041 #define CC (char*)
1042 
1043 static JNINativeMethod methods[] = {
1044   {CC"getObjectAddress",   CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectAddress  },
1045   {CC"getObjectSize",      CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectSize     },
1046   {CC"isObjectInOldGen",   CC"(Ljava/lang/Object;)Z", (void*)&WB_isObjectInOldGen  },
1047   {CC"getHeapOopSize",     CC"()I",                   (void*)&WB_GetHeapOopSize    },
1048   {CC"getVMPageSize",      CC"()I",                   (void*)&WB_GetVMPageSize     },
1049   {CC"getVMLargePageSize", CC"()J",                   (void*)&WB_GetVMLargePageSize},
1050   {CC"isClassAlive0",      CC"(Ljava/lang/String;)Z", (void*)&WB_IsClassAlive      },
1051   {CC"classKnownToNotExist",
1052                            CC"(Ljava/lang/ClassLoader;Ljava/lang/String;)Z",(void*)&WB_ClassKnownToNotExist},
1053   {CC"getLookupCacheURLs", CC"(Ljava/lang/ClassLoader;)[Ljava/net/URL;",    (void*)&WB_GetLookupCacheURLs},
1054   {CC"getLookupCacheMatches", CC"(Ljava/lang/ClassLoader;Ljava/lang/String;)[I",
1055                                                       (void*)&WB_GetLookupCacheMatches},
1056   {CC"parseCommandLine",
1057       CC"(Ljava/lang/String;[Lsun/hotspot/parser/DiagnosticCommand;)[Ljava/lang/Object;",
1058       (void*) &WB_ParseCommandLine
1059   },
1060   {CC"addToBootstrapClassLoaderSearch", CC"(Ljava/lang/String;)V",
1061                                                       (void*)&WB_AddToBootstrapClassLoaderSearch},
1062   {CC"addToSystemClassLoaderSearch",    CC"(Ljava/lang/String;)V",
1063                                                       (void*)&WB_AddToSystemClassLoaderSearch},
1064   {CC"getCompressedOopsMaxHeapSize", CC"()J",
1065       (void*)&WB_GetCompressedOopsMaxHeapSize},
1066   {CC"printHeapSizes",     CC"()V",                   (void*)&WB_PrintHeapSizes    },
1067   {CC"runMemoryUnitTests", CC"()V",                   (void*)&WB_RunMemoryUnitTests},
1068   {CC"readFromNoaccessArea",CC"()V",                  (void*)&WB_ReadFromNoaccessArea},
1069   {CC"stressVirtualSpaceResize",CC"(JJJ)I",           (void*)&WB_StressVirtualSpaceResize},
1070   {CC"isSharedClass", CC"(Ljava/lang/Class;)Z",       (void*)&WB_IsSharedClass },
1071 #if INCLUDE_ALL_GCS
1072   {CC"g1InConcurrentMark", CC"()Z",                   (void*)&WB_G1InConcurrentMark},
1073   {CC"g1IsHumongous",      CC"(Ljava/lang/Object;)Z", (void*)&WB_G1IsHumongous     },
1074   {CC"g1NumMaxRegions",    CC"()J",                   (void*)&WB_G1NumMaxRegions  },
1075   {CC"g1NumFreeRegions",   CC"()J",                   (void*)&WB_G1NumFreeRegions  },
1076   {CC"g1RegionSize",       CC"()I",                   (void*)&WB_G1RegionSize      },
1077   {CC"g1StartConcMarkCycle",       CC"()Z",           (void*)&WB_G1StartMarkCycle  },
1078   {CC"g1AuxiliaryMemoryUsage", CC"()Ljava/lang/management/MemoryUsage;",
1079                                                       (void*)&WB_G1AuxiliaryMemoryUsage  },
1080 #endif // INCLUDE_ALL_GCS
1081 #if INCLUDE_NMT
1082   {CC"NMTMalloc",           CC"(J)J",                 (void*)&WB_NMTMalloc          },
1083   {CC"NMTMallocWithPseudoStack", CC"(JI)J",           (void*)&WB_NMTMallocWithPseudoStack},
1084   {CC"NMTFree",             CC"(J)V",                 (void*)&WB_NMTFree            },
1085   {CC"NMTReserveMemory",    CC"(J)J",                 (void*)&WB_NMTReserveMemory   },
1086   {CC"NMTCommitMemory",     CC"(JJ)V",                (void*)&WB_NMTCommitMemory    },
1087   {CC"NMTUncommitMemory",   CC"(JJ)V",                (void*)&WB_NMTUncommitMemory  },
1088   {CC"NMTReleaseMemory",    CC"(JJ)V",                (void*)&WB_NMTReleaseMemory   },
1089   {CC"NMTIsDetailSupported",CC"()Z",                  (void*)&WB_NMTIsDetailSupported},
1090   {CC"NMTChangeTrackingLevel", CC"()Z",               (void*)&WB_NMTChangeTrackingLevel},
1091   {CC"NMTGetHashSize",      CC"()I",                  (void*)&WB_NMTGetHashSize     },
1092 #endif // INCLUDE_NMT
1093   {CC"deoptimizeAll",      CC"()V",                   (void*)&WB_DeoptimizeAll     },
1094   {CC"deoptimizeMethod",   CC"(Ljava/lang/reflect/Executable;Z)I",
1095                                                       (void*)&WB_DeoptimizeMethod  },
1096   {CC"isMethodCompiled",   CC"(Ljava/lang/reflect/Executable;Z)Z",
1097                                                       (void*)&WB_IsMethodCompiled  },
1098   {CC"isMethodCompilable", CC"(Ljava/lang/reflect/Executable;IZ)Z",
1099                                                       (void*)&WB_IsMethodCompilable},
1100   {CC"isMethodQueuedForCompilation",
1101       CC"(Ljava/lang/reflect/Executable;)Z",          (void*)&WB_IsMethodQueuedForCompilation},
1102   {CC"makeMethodNotCompilable",
1103       CC"(Ljava/lang/reflect/Executable;IZ)V",        (void*)&WB_MakeMethodNotCompilable},
1104   {CC"testSetDontInlineMethod",
1105       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetDontInlineMethod},
1106   {CC"getMethodCompilationLevel",
1107       CC"(Ljava/lang/reflect/Executable;Z)I",         (void*)&WB_GetMethodCompilationLevel},
1108   {CC"getMethodEntryBci",
1109       CC"(Ljava/lang/reflect/Executable;)I",          (void*)&WB_GetMethodEntryBci},
1110   {CC"getCompileQueueSize",
1111       CC"(I)I",                                       (void*)&WB_GetCompileQueueSize},
1112   {CC"testSetForceInlineMethod",
1113       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetForceInlineMethod},
1114   {CC"enqueueMethodForCompilation",
1115       CC"(Ljava/lang/reflect/Executable;II)Z",        (void*)&WB_EnqueueMethodForCompilation},
1116   {CC"clearMethodState",
1117       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_ClearMethodState},
1118   {CC"setBooleanVMFlag",   CC"(Ljava/lang/String;Z)V",(void*)&WB_SetBooleanVMFlag},
1119   {CC"setIntxVMFlag",      CC"(Ljava/lang/String;J)V",(void*)&WB_SetIntxVMFlag},
1120   {CC"setUintxVMFlag",     CC"(Ljava/lang/String;J)V",(void*)&WB_SetUintxVMFlag},
1121   {CC"setUint64VMFlag",    CC"(Ljava/lang/String;J)V",(void*)&WB_SetUint64VMFlag},
1122   {CC"setDoubleVMFlag",    CC"(Ljava/lang/String;D)V",(void*)&WB_SetDoubleVMFlag},
1123   {CC"setStringVMFlag",    CC"(Ljava/lang/String;Ljava/lang/String;)V",
1124                                                       (void*)&WB_SetStringVMFlag},
1125   {CC"getBooleanVMFlag",   CC"(Ljava/lang/String;)Ljava/lang/Boolean;",
1126                                                       (void*)&WB_GetBooleanVMFlag},
1127   {CC"getIntxVMFlag",      CC"(Ljava/lang/String;)Ljava/lang/Long;",
1128                                                       (void*)&WB_GetIntxVMFlag},
1129   {CC"getUintxVMFlag",     CC"(Ljava/lang/String;)Ljava/lang/Long;",
1130                                                       (void*)&WB_GetUintxVMFlag},
1131   {CC"getUint64VMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Long;",
1132                                                       (void*)&WB_GetUint64VMFlag},
1133   {CC"getDoubleVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/Double;",
1134                                                       (void*)&WB_GetDoubleVMFlag},
1135   {CC"getStringVMFlag",    CC"(Ljava/lang/String;)Ljava/lang/String;",
1136                                                       (void*)&WB_GetStringVMFlag},
1137   {CC"isInStringTable",    CC"(Ljava/lang/String;)Z", (void*)&WB_IsInStringTable  },
1138   {CC"fullGC",   CC"()V",                             (void*)&WB_FullGC },
1139   {CC"youngGC",  CC"()V",                             (void*)&WB_YoungGC },
1140   {CC"readReservedMemory", CC"()V",                   (void*)&WB_ReadReservedMemory },
1141   {CC"allocateMetaspace",
1142      CC"(Ljava/lang/ClassLoader;J)J",                 (void*)&WB_AllocateMetaspace },
1143   {CC"freeMetaspace",
1144      CC"(Ljava/lang/ClassLoader;JJ)V",                (void*)&WB_FreeMetaspace },
1145   {CC"incMetaspaceCapacityUntilGC", CC"(J)J",         (void*)&WB_IncMetaspaceCapacityUntilGC },
1146   {CC"metaspaceCapacityUntilGC", CC"()J",             (void*)&WB_MetaspaceCapacityUntilGC },
1147   {CC"getCPUFeatures",     CC"()Ljava/lang/String;",  (void*)&WB_GetCPUFeatures     },
1148   {CC"getNMethod",         CC"(Ljava/lang/reflect/Executable;Z)[Ljava/lang/Object;",
1149                                                       (void*)&WB_GetNMethod         },
1150   {CC"isMonitorInflated",  CC"(Ljava/lang/Object;)Z", (void*)&WB_IsMonitorInflated  },
1151   {CC"forceSafepoint",     CC"()V",                   (void*)&WB_ForceSafepoint     },
1152   {CC"checkLibSpecifiesNoexecstack", CC"(Ljava/lang/String;)Z",
1153                                                       (void*)&WB_CheckLibSpecifiesNoexecstack},
1154   {CC"isContainerized",           CC"()Z",            (void*)&WB_IsContainerized },
1155   {CC"printOsInfo",               CC"()V",            (void*)&WB_PrintOsInfo },
1156 };
1157 
1158 #undef CC
1159 
1160 JVM_ENTRY(void, JVM_RegisterWhiteBoxMethods(JNIEnv* env, jclass wbclass))
1161   {
1162     if (WhiteBoxAPI) {
1163       // Make sure that wbclass is loaded by the null classloader
1164       instanceKlassHandle ikh = instanceKlassHandle(JNIHandles::resolve(wbclass)->klass());
1165       Handle loader(ikh->class_loader());
1166       if (loader.is_null()) {
1167         WhiteBox::register_methods(env, wbclass, thread, methods, sizeof(methods) / sizeof(methods[0]));
1168         WhiteBox::register_extended(env, wbclass, thread);
1169         WhiteBox::set_used();
1170       }
1171     }
1172   }
1173 JVM_END