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