1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 
  27 #include "memory/universe.hpp"
  28 #include "oops/oop.inline.hpp"
  29 
  30 #include "classfile/symbolTable.hpp"
  31 #include "classfile/classLoaderData.hpp"
  32 
  33 #include "prims/whitebox.hpp"
  34 #include "prims/wbtestmethods/parserTests.hpp"
  35 
  36 #include "runtime/arguments.hpp"
  37 #include "runtime/interfaceSupport.hpp"
  38 #include "runtime/os.hpp"
  39 #include "utilities/debug.hpp"
  40 #include "utilities/macros.hpp"
  41 #include "utilities/exceptions.hpp"
  42 
  43 #if INCLUDE_ALL_GCS
  44 #include "gc_implementation/g1/concurrentMark.hpp"
  45 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  46 #include "gc_implementation/g1/heapRegionRemSet.hpp"
  47 #endif // INCLUDE_ALL_GCS
  48 
  49 #ifdef INCLUDE_NMT
  50 #include "services/memTracker.hpp"
  51 #endif // INCLUDE_NMT
  52 
  53 #include "compiler/compileBroker.hpp"
  54 #include "runtime/compilationPolicy.hpp"
  55 
  56 #define SIZE_T_MAX_VALUE ((size_t) -1)
  57 
  58 bool WhiteBox::_used = false;
  59 
  60 WB_ENTRY(jlong, WB_GetObjectAddress(JNIEnv* env, jobject o, jobject obj))
  61   return (jlong)(void*)JNIHandles::resolve(obj);
  62 WB_END
  63 
  64 WB_ENTRY(jint, WB_GetHeapOopSize(JNIEnv* env, jobject o))
  65   return heapOopSize;
  66 WB_END
  67 
  68 
  69 class WBIsKlassAliveClosure : public KlassClosure {
  70     Symbol* _name;
  71     bool _found;
  72 public:
  73     WBIsKlassAliveClosure(Symbol* name) : _name(name), _found(false) {}
  74 
  75     void do_klass(Klass* k) {
  76       if (_found) return;
  77       Symbol* ksym = k->name();
  78       if (ksym->fast_compare(_name) == 0) {
  79         _found = true;
  80       }
  81     }
  82 
  83     bool found() const {
  84         return _found;
  85     }
  86 };
  87 
  88 WB_ENTRY(jboolean, WB_IsClassAlive(JNIEnv* env, jobject target, jstring name))
  89   Handle h_name = JNIHandles::resolve(name);
  90   if (h_name.is_null()) return false;
  91   Symbol* sym = java_lang_String::as_symbol(h_name, CHECK_false);
  92   TempNewSymbol tsym(sym); // Make sure to decrement reference count on sym on return
  93 
  94   WBIsKlassAliveClosure closure(sym);
  95   ClassLoaderDataGraph::classes_do(&closure);
  96 
  97   return closure.found();
  98 WB_END
  99 
 100 WB_ENTRY(jlong, WB_GetCompressedOopsMaxHeapSize(JNIEnv* env, jobject o)) {
 101   return (jlong)Arguments::max_heap_for_compressed_oops();
 102 }
 103 WB_END
 104 
 105 WB_ENTRY(void, WB_PrintHeapSizes(JNIEnv* env, jobject o)) {
 106   CollectorPolicy * p = Universe::heap()->collector_policy();
 107   gclog_or_tty->print_cr("Minimum heap "SIZE_FORMAT" Initial heap "SIZE_FORMAT" Maximum heap "SIZE_FORMAT
 108     " Space alignment "SIZE_FORMAT" Heap alignment "SIZE_FORMAT,
 109     p->min_heap_byte_size(), p->initial_heap_byte_size(), p->max_heap_byte_size(),
 110     p->space_alignment(), p->heap_alignment());
 111 }
 112 WB_END
 113 
 114 #ifndef PRODUCT
 115 // Forward declaration
 116 void TestReservedSpace_test();
 117 void TestReserveMemorySpecial_test();
 118 void TestVirtualSpace_test();
 119 void TestMetaspaceAux_test();
 120 #endif
 121 
 122 WB_ENTRY(void, WB_RunMemoryUnitTests(JNIEnv* env, jobject o))
 123 #ifndef PRODUCT
 124   TestReservedSpace_test();
 125   TestReserveMemorySpecial_test();
 126   TestVirtualSpace_test();
 127   TestMetaspaceAux_test();
 128 #endif
 129 WB_END
 130 
 131 WB_ENTRY(void, WB_ReadFromNoaccessArea(JNIEnv* env, jobject o))
 132   size_t granularity = os::vm_allocation_granularity();
 133   ReservedHeapSpace rhs(100 * granularity, granularity, false, NULL);
 134   VirtualSpace vs;
 135   vs.initialize(rhs, 50 * granularity);
 136 
 137   //Check if constraints are complied
 138   if (!( UseCompressedOops && rhs.base() != NULL &&
 139          Universe::narrow_oop_base() != NULL &&
 140          Universe::narrow_oop_use_implicit_null_checks() )) {
 141     tty->print_cr("WB_ReadFromNoaccessArea method is useless:\n "
 142                   "\tUseCompressedOops is %d\n"
 143                   "\trhs.base() is "PTR_FORMAT"\n"
 144                   "\tUniverse::narrow_oop_base() is "PTR_FORMAT"\n"
 145                   "\tUniverse::narrow_oop_use_implicit_null_checks() is %d",
 146                   UseCompressedOops,
 147                   rhs.base(),
 148                   Universe::narrow_oop_base(),
 149                   Universe::narrow_oop_use_implicit_null_checks());
 150     return;
 151   }
 152   tty->print_cr("Reading from no access area... ");
 153   tty->print_cr("*(vs.low_boundary() - rhs.noaccess_prefix() / 2 ) = %c",
 154                 *(vs.low_boundary() - rhs.noaccess_prefix() / 2 ));
 155 WB_END
 156 
 157 static jint wb_stress_virtual_space_resize(size_t reserved_space_size,
 158                                            size_t magnitude, size_t iterations) {
 159   size_t granularity = os::vm_allocation_granularity();
 160   ReservedHeapSpace rhs(reserved_space_size * granularity, granularity, false, NULL);
 161   VirtualSpace vs;
 162   if (!vs.initialize(rhs, 0)) {
 163     tty->print_cr("Failed to initialize VirtualSpace. Can't proceed.");
 164     return 3;
 165   }
 166 
 167   long seed = os::random();
 168   tty->print_cr("Random seed is %ld", seed);
 169   os::init_random(seed);
 170 
 171   for (size_t i = 0; i < iterations; i++) {
 172 
 173     // Whether we will shrink or grow
 174     bool shrink = os::random() % 2L == 0;
 175 
 176     // Get random delta to resize virtual space
 177     size_t delta = (size_t)os::random() % magnitude;
 178 
 179     // If we are about to shrink virtual space below zero, then expand instead
 180     if (shrink && vs.committed_size() < delta) {
 181       shrink = false;
 182     }
 183 
 184     // Resizing by delta
 185     if (shrink) {
 186       vs.shrink_by(delta);
 187     } else {
 188       // If expanding fails expand_by will silently return false
 189       vs.expand_by(delta, true);
 190     }
 191   }
 192   return 0;
 193 }
 194 
 195 WB_ENTRY(jint, WB_StressVirtualSpaceResize(JNIEnv* env, jobject o,
 196         jlong reserved_space_size, jlong magnitude, jlong iterations))
 197   tty->print_cr("reservedSpaceSize="JLONG_FORMAT", magnitude="JLONG_FORMAT", "
 198                 "iterations="JLONG_FORMAT"\n", reserved_space_size, magnitude,
 199                 iterations);
 200   if (reserved_space_size < 0 || magnitude < 0 || iterations < 0) {
 201     tty->print_cr("One of variables printed above is negative. Can't proceed.\n");
 202     return 1;
 203   }
 204 
 205   // sizeof(size_t) depends on whether OS is 32bit or 64bit. sizeof(jlong) is
 206   // always 8 byte. That's why we should avoid overflow in case of 32bit platform.
 207   if (sizeof(size_t) < sizeof(jlong)) {
 208     jlong size_t_max_value = (jlong) SIZE_T_MAX_VALUE;
 209     if (reserved_space_size > size_t_max_value || magnitude > size_t_max_value
 210         || iterations > size_t_max_value) {
 211       tty->print_cr("One of variables printed above overflows size_t. Can't proceed.\n");
 212       return 2;
 213     }
 214   }
 215 
 216   return wb_stress_virtual_space_resize((size_t) reserved_space_size,
 217                                         (size_t) magnitude, (size_t) iterations);
 218 WB_END
 219 
 220 #if INCLUDE_ALL_GCS
 221 WB_ENTRY(jboolean, WB_G1IsHumongous(JNIEnv* env, jobject o, jobject obj))
 222   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 223   oop result = JNIHandles::resolve(obj);
 224   const HeapRegion* hr = g1->heap_region_containing(result);
 225   return hr->isHumongous();
 226 WB_END
 227 
 228 WB_ENTRY(jlong, WB_G1NumFreeRegions(JNIEnv* env, jobject o))
 229   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 230   size_t nr = g1->free_regions();
 231   return (jlong)nr;
 232 WB_END
 233 
 234 WB_ENTRY(jboolean, WB_G1InConcurrentMark(JNIEnv* env, jobject o))
 235   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 236   ConcurrentMark* cm = g1->concurrent_mark();
 237   return cm->concurrent_marking_in_progress();
 238 WB_END
 239 
 240 WB_ENTRY(jint, WB_G1RegionSize(JNIEnv* env, jobject o))
 241   return (jint)HeapRegion::GrainBytes;
 242 WB_END
 243 #endif // INCLUDE_ALL_GCS
 244 
 245 #if INCLUDE_NMT
 246 // Alloc memory using the test memory type so that we can use that to see if
 247 // NMT picks it up correctly
 248 WB_ENTRY(jlong, WB_NMTMalloc(JNIEnv* env, jobject o, jlong size))
 249   jlong addr = 0;
 250 
 251   if (MemTracker::is_on() && !MemTracker::shutdown_in_progress()) {
 252     addr = (jlong)(uintptr_t)os::malloc(size, mtTest);
 253   }
 254 
 255   return addr;
 256 WB_END
 257 
 258 // Free the memory allocated by NMTAllocTest
 259 WB_ENTRY(void, WB_NMTFree(JNIEnv* env, jobject o, jlong mem))
 260   os::free((void*)(uintptr_t)mem, mtTest);
 261 WB_END
 262 
 263 WB_ENTRY(jlong, WB_NMTReserveMemory(JNIEnv* env, jobject o, jlong size))
 264   jlong addr = 0;
 265 
 266   if (MemTracker::is_on() && !MemTracker::shutdown_in_progress()) {
 267     addr = (jlong)(uintptr_t)os::reserve_memory(size);
 268     MemTracker::record_virtual_memory_type((address)addr, mtTest);
 269   }
 270 
 271   return addr;
 272 WB_END
 273 
 274 
 275 WB_ENTRY(void, WB_NMTCommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 276   os::commit_memory((char *)(uintptr_t)addr, size, !ExecMem);
 277   MemTracker::record_virtual_memory_type((address)(uintptr_t)addr, mtTest);
 278 WB_END
 279 
 280 WB_ENTRY(void, WB_NMTUncommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 281   os::uncommit_memory((char *)(uintptr_t)addr, size);
 282 WB_END
 283 
 284 WB_ENTRY(void, WB_NMTReleaseMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
 285   os::release_memory((char *)(uintptr_t)addr, size);
 286 WB_END
 287 
 288 // Block until the current generation of NMT data to be merged, used to reliably test the NMT feature
 289 WB_ENTRY(jboolean, WB_NMTWaitForDataMerge(JNIEnv* env))
 290 
 291   if (!MemTracker::is_on() || MemTracker::shutdown_in_progress()) {
 292     return false;
 293   }
 294 
 295   return MemTracker::wbtest_wait_for_data_merge();
 296 WB_END
 297 
 298 WB_ENTRY(jboolean, WB_NMTIsDetailSupported(JNIEnv* env))
 299   return MemTracker::tracking_level() == MemTracker::NMT_detail;
 300 WB_END
 301 
 302 #endif // INCLUDE_NMT
 303 
 304 static jmethodID reflected_method_to_jmid(JavaThread* thread, JNIEnv* env, jobject method) {
 305   assert(method != NULL, "method should not be null");
 306   ThreadToNativeFromVM ttn(thread);
 307   return env->FromReflectedMethod(method);
 308 }
 309 
 310 WB_ENTRY(void, WB_DeoptimizeAll(JNIEnv* env, jobject o))
 311   MutexLockerEx mu(Compile_lock);
 312   CodeCache::mark_all_nmethods_for_deoptimization();
 313   VM_Deoptimize op;
 314   VMThread::execute(&op);
 315 WB_END
 316 
 317 WB_ENTRY(jint, WB_DeoptimizeMethod(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 318   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 319   MutexLockerEx mu(Compile_lock);
 320   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 321   int result = 0;
 322   nmethod* code;
 323   if (is_osr) {
 324     int bci = InvocationEntryBci;
 325     while ((code = mh->lookup_osr_nmethod_for(bci, CompLevel_none, false)) != NULL) {
 326       code->mark_for_deoptimization();
 327       ++result;
 328       bci = code->osr_entry_bci() + 1;
 329     }
 330   } else {
 331     code = mh->code();
 332   }
 333   if (code != NULL) {
 334     code->mark_for_deoptimization();
 335     ++result;
 336   }
 337   result += CodeCache::mark_for_deoptimization(mh());
 338   if (result > 0) {
 339     VM_Deoptimize op;
 340     VMThread::execute(&op);
 341   }
 342   return result;
 343 WB_END
 344 
 345 WB_ENTRY(jboolean, WB_IsMethodCompiled(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 346   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 347   MutexLockerEx mu(Compile_lock);
 348   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 349   nmethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 350   if (code == NULL) {
 351     return JNI_FALSE;
 352   }
 353   return (code->is_alive() && !code->is_marked_for_deoptimization());
 354 WB_END
 355 
 356 WB_ENTRY(jboolean, WB_IsMethodCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 357   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 358   MutexLockerEx mu(Compile_lock);
 359   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 360   if (is_osr) {
 361     return CompilationPolicy::can_be_osr_compiled(mh, comp_level);
 362   } else {
 363     return CompilationPolicy::can_be_compiled(mh, comp_level);
 364   }
 365 WB_END
 366 
 367 WB_ENTRY(jboolean, WB_IsMethodQueuedForCompilation(JNIEnv* env, jobject o, jobject method))
 368   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 369   MutexLockerEx mu(Compile_lock);
 370   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 371   return mh->queued_for_compilation();
 372 WB_END
 373 
 374 WB_ENTRY(jint, WB_GetMethodCompilationLevel(JNIEnv* env, jobject o, jobject method, jboolean is_osr))
 375   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 376   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 377   nmethod* code = is_osr ? mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false) : mh->code();
 378   return (code != NULL ? code->comp_level() : CompLevel_none);
 379 WB_END
 380 
 381 WB_ENTRY(void, WB_MakeMethodNotCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level, jboolean is_osr))
 382   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 383   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 384   if (is_osr) {
 385     mh->set_not_osr_compilable(comp_level, true /* report */, "WhiteBox");
 386   } else {
 387     mh->set_not_compilable(comp_level, true /* report */, "WhiteBox");
 388   }
 389 WB_END
 390 
 391 WB_ENTRY(jint, WB_GetMethodEntryBci(JNIEnv* env, jobject o, jobject method))
 392   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 393   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 394   nmethod* code = mh->lookup_osr_nmethod_for(InvocationEntryBci, CompLevel_none, false);
 395   return (code != NULL && code->is_osr_method() ? code->osr_entry_bci() : InvocationEntryBci);
 396 WB_END
 397 
 398 WB_ENTRY(jboolean, WB_TestSetDontInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 399   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 400   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 401   bool result = mh->dont_inline();
 402   mh->set_dont_inline(value == JNI_TRUE);
 403   return result;
 404 WB_END
 405 
 406 WB_ENTRY(jint, WB_GetCompileQueueSize(JNIEnv* env, jobject o, jint comp_level))
 407   if (comp_level == CompLevel_any) {
 408     return CompileBroker::queue_size(CompLevel_full_optimization) /* C2 */ +
 409         CompileBroker::queue_size(CompLevel_full_profile) /* C1 */;
 410   } else {
 411     return CompileBroker::queue_size(comp_level);
 412   }
 413 WB_END
 414 
 415 WB_ENTRY(jboolean, WB_TestSetForceInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
 416   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 417   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 418   bool result = mh->force_inline();
 419   mh->set_force_inline(value == JNI_TRUE);
 420   return result;
 421 WB_END
 422 
 423 WB_ENTRY(jboolean, WB_EnqueueMethodForCompilation(JNIEnv* env, jobject o, jobject method, jint comp_level, jint bci))
 424   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 425   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 426   nmethod* nm = CompileBroker::compile_method(mh, bci, comp_level, mh, mh->invocation_count(), "WhiteBox", THREAD);
 427   MutexLockerEx mu(Compile_lock);
 428   return (mh->queued_for_compilation() || nm != NULL);
 429 WB_END
 430 
 431 WB_ENTRY(void, WB_ClearMethodState(JNIEnv* env, jobject o, jobject method))
 432   jmethodID jmid = reflected_method_to_jmid(thread, env, method);
 433   methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
 434   MutexLockerEx mu(Compile_lock);
 435   MethodData* mdo = mh->method_data();
 436   MethodCounters* mcs = mh->method_counters();
 437 
 438   if (mdo != NULL) {
 439     mdo->init();
 440     ResourceMark rm;
 441     int arg_count = mdo->method()->size_of_parameters();
 442     for (int i = 0; i < arg_count; i++) {
 443       mdo->set_arg_modified(i, 0);
 444     }
 445   }
 446 
 447   mh->clear_not_c1_compilable();
 448   mh->clear_not_c2_compilable();
 449   mh->clear_not_c2_osr_compilable();
 450   NOT_PRODUCT(mh->set_compiled_invocation_count(0));
 451   if (mcs != NULL) {
 452     mcs->backedge_counter()->init();
 453     mcs->invocation_counter()->init();
 454     mcs->set_interpreter_invocation_count(0);
 455     mcs->set_interpreter_throwout_count(0);
 456 
 457 #ifdef TIERED
 458     mcs->set_rate(0.0F);
 459     mh->set_prev_event_count(0, THREAD);
 460     mh->set_prev_time(0, THREAD);
 461 #endif
 462   }
 463 WB_END
 464 
 465 WB_ENTRY(jboolean, WB_IsInStringTable(JNIEnv* env, jobject o, jstring javaString))
 466   ResourceMark rm(THREAD);
 467   int len;
 468   jchar* name = java_lang_String::as_unicode_string(JNIHandles::resolve(javaString), len, CHECK_false);
 469   return (StringTable::lookup(name, len) != NULL);
 470 WB_END
 471 
 472 WB_ENTRY(void, WB_FullGC(JNIEnv* env, jobject o))
 473   Universe::heap()->collector_policy()->set_should_clear_all_soft_refs(true);
 474   Universe::heap()->collect(GCCause::_last_ditch_collection);
 475 WB_END
 476 
 477 
 478 WB_ENTRY(void, WB_ReadReservedMemory(JNIEnv* env, jobject o))
 479   // static+volatile in order to force the read to happen
 480   // (not be eliminated by the compiler)
 481   static char c;
 482   static volatile char* p;
 483 
 484   p = os::reserve_memory(os::vm_allocation_granularity(), NULL, 0);
 485   if (p == NULL) {
 486     THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "Failed to reserve memory");
 487   }
 488 
 489   c = *p;
 490 WB_END
 491 
 492 //Some convenience methods to deal with objects from java
 493 int WhiteBox::offset_for_field(const char* field_name, oop object,
 494     Symbol* signature_symbol) {
 495   assert(field_name != NULL && strlen(field_name) > 0, "Field name not valid");
 496   Thread* THREAD = Thread::current();
 497 
 498   //Get the class of our object
 499   Klass* arg_klass = object->klass();
 500   //Turn it into an instance-klass
 501   InstanceKlass* ik = InstanceKlass::cast(arg_klass);
 502 
 503   //Create symbols to look for in the class
 504   TempNewSymbol name_symbol = SymbolTable::lookup(field_name, (int) strlen(field_name),
 505       THREAD);
 506 
 507   //To be filled in with an offset of the field we're looking for
 508   fieldDescriptor fd;
 509 
 510   Klass* res = ik->find_field(name_symbol, signature_symbol, &fd);
 511   if (res == NULL) {
 512     tty->print_cr("Invalid layout of %s at %s", ik->external_name(),
 513         name_symbol->as_C_string());
 514     fatal("Invalid layout of preloaded class");
 515   }
 516 
 517   //fetch the field at the offset we've found
 518   int dest_offset = fd.offset();
 519 
 520   return dest_offset;
 521 }
 522 
 523 
 524 const char* WhiteBox::lookup_jstring(const char* field_name, oop object) {
 525   int offset = offset_for_field(field_name, object,
 526       vmSymbols::string_signature());
 527   oop string = object->obj_field(offset);
 528   if (string == NULL) {
 529     return NULL;
 530   }
 531   const char* ret = java_lang_String::as_utf8_string(string);
 532   return ret;
 533 }
 534 
 535 bool WhiteBox::lookup_bool(const char* field_name, oop object) {
 536   int offset =
 537       offset_for_field(field_name, object, vmSymbols::bool_signature());
 538   bool ret = (object->bool_field(offset) == JNI_TRUE);
 539   return ret;
 540 }
 541 
 542 
 543 #define CC (char*)
 544 
 545 static JNINativeMethod methods[] = {
 546   {CC"getObjectAddress",   CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectAddress  },
 547   {CC"getHeapOopSize",     CC"()I",                   (void*)&WB_GetHeapOopSize    },
 548   {CC"isClassAlive0",      CC"(Ljava/lang/String;)Z", (void*)&WB_IsClassAlive      },
 549   {CC"parseCommandLine",
 550       CC"(Ljava/lang/String;[Lsun/hotspot/parser/DiagnosticCommand;)[Ljava/lang/Object;",
 551       (void*) &WB_ParseCommandLine
 552   },
 553   {CC"getCompressedOopsMaxHeapSize", CC"()J",
 554       (void*)&WB_GetCompressedOopsMaxHeapSize},
 555   {CC"printHeapSizes",     CC"()V",                   (void*)&WB_PrintHeapSizes    },
 556   {CC"runMemoryUnitTests", CC"()V",                   (void*)&WB_RunMemoryUnitTests},
 557   {CC"readFromNoaccessArea",CC"()V",                  (void*)&WB_ReadFromNoaccessArea},
 558   {CC"stressVirtualSpaceResize",CC"(JJJ)I",           (void*)&WB_StressVirtualSpaceResize},
 559 #if INCLUDE_ALL_GCS
 560   {CC"g1InConcurrentMark", CC"()Z",                   (void*)&WB_G1InConcurrentMark},
 561   {CC"g1IsHumongous",      CC"(Ljava/lang/Object;)Z", (void*)&WB_G1IsHumongous     },
 562   {CC"g1NumFreeRegions",   CC"()J",                   (void*)&WB_G1NumFreeRegions  },
 563   {CC"g1RegionSize",       CC"()I",                   (void*)&WB_G1RegionSize      },
 564 #endif // INCLUDE_ALL_GCS
 565 #if INCLUDE_NMT
 566   {CC"NMTMalloc",           CC"(J)J",                 (void*)&WB_NMTMalloc          },
 567   {CC"NMTFree",             CC"(J)V",                 (void*)&WB_NMTFree            },
 568   {CC"NMTReserveMemory",    CC"(J)J",                 (void*)&WB_NMTReserveMemory   },
 569   {CC"NMTCommitMemory",     CC"(JJ)V",                (void*)&WB_NMTCommitMemory    },
 570   {CC"NMTUncommitMemory",   CC"(JJ)V",                (void*)&WB_NMTUncommitMemory  },
 571   {CC"NMTReleaseMemory",    CC"(JJ)V",                (void*)&WB_NMTReleaseMemory   },
 572   {CC"NMTWaitForDataMerge", CC"()Z",                  (void*)&WB_NMTWaitForDataMerge},
 573   {CC"NMTIsDetailSupported",CC"()Z",                  (void*)&WB_NMTIsDetailSupported},
 574 #endif // INCLUDE_NMT
 575   {CC"deoptimizeAll",      CC"()V",                   (void*)&WB_DeoptimizeAll     },
 576   {CC"deoptimizeMethod",   CC"(Ljava/lang/reflect/Executable;Z)I",
 577                                                       (void*)&WB_DeoptimizeMethod  },
 578   {CC"isMethodCompiled",   CC"(Ljava/lang/reflect/Executable;Z)Z",
 579                                                       (void*)&WB_IsMethodCompiled  },
 580   {CC"isMethodCompilable", CC"(Ljava/lang/reflect/Executable;IZ)Z",
 581                                                       (void*)&WB_IsMethodCompilable},
 582   {CC"isMethodQueuedForCompilation",
 583       CC"(Ljava/lang/reflect/Executable;)Z",          (void*)&WB_IsMethodQueuedForCompilation},
 584   {CC"makeMethodNotCompilable",
 585       CC"(Ljava/lang/reflect/Executable;IZ)V",        (void*)&WB_MakeMethodNotCompilable},
 586   {CC"testSetDontInlineMethod",
 587       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetDontInlineMethod},
 588   {CC"getMethodCompilationLevel",
 589       CC"(Ljava/lang/reflect/Executable;Z)I",         (void*)&WB_GetMethodCompilationLevel},
 590   {CC"getMethodEntryBci",
 591       CC"(Ljava/lang/reflect/Executable;)I",          (void*)&WB_GetMethodEntryBci},
 592   {CC"getCompileQueueSize",
 593       CC"(I)I",                                       (void*)&WB_GetCompileQueueSize},
 594   {CC"testSetForceInlineMethod",
 595       CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetForceInlineMethod},
 596   {CC"enqueueMethodForCompilation",
 597       CC"(Ljava/lang/reflect/Executable;II)Z",        (void*)&WB_EnqueueMethodForCompilation},
 598   {CC"clearMethodState",
 599       CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_ClearMethodState},
 600   {CC"isInStringTable",   CC"(Ljava/lang/String;)Z",  (void*)&WB_IsInStringTable  },
 601   {CC"fullGC",   CC"()V",                             (void*)&WB_FullGC },
 602   {CC"readReservedMemory", CC"()V",                   (void*)&WB_ReadReservedMemory },
 603 };
 604 
 605 #undef CC
 606 
 607 JVM_ENTRY(void, JVM_RegisterWhiteBoxMethods(JNIEnv* env, jclass wbclass))
 608   {
 609     if (WhiteBoxAPI) {
 610       // Make sure that wbclass is loaded by the null classloader
 611       instanceKlassHandle ikh = instanceKlassHandle(JNIHandles::resolve(wbclass)->klass());
 612       Handle loader(ikh->class_loader());
 613       if (loader.is_null()) {
 614         ResourceMark rm;
 615         ThreadToNativeFromVM ttnfv(thread); // can't be in VM when we call JNI
 616         bool result = true;
 617         //  one by one registration natives for exception catching
 618         jclass exceptionKlass = env->FindClass(vmSymbols::java_lang_NoSuchMethodError()->as_C_string());
 619         for (int i = 0, n = sizeof(methods) / sizeof(methods[0]); i < n; ++i) {
 620           if (env->RegisterNatives(wbclass, methods + i, 1) != 0) {
 621             result = false;
 622             if (env->ExceptionCheck() && env->IsInstanceOf(env->ExceptionOccurred(), exceptionKlass)) {
 623               // j.l.NoSuchMethodError is thrown when a method can't be found or a method is not native
 624               // ignoring the exception
 625               tty->print_cr("Warning: 'NoSuchMethodError' on register of sun.hotspot.WhiteBox::%s%s", methods[i].name, methods[i].signature);
 626               env->ExceptionClear();
 627             } else {
 628               // register is failed w/o exception or w/ unexpected exception
 629               tty->print_cr("Warning: unexpected error on register of sun.hotspot.WhiteBox::%s%s. All methods will be unregistered", methods[i].name, methods[i].signature);
 630               env->UnregisterNatives(wbclass);
 631               break;
 632             }
 633           }
 634         }
 635 
 636         if (result) {
 637           WhiteBox::set_used();
 638         }
 639       }
 640     }
 641   }
 642 JVM_END