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