1 /* 2 * Copyright (c) 1999, 2016, 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 #include "jvmci/jvmciEnv.hpp" 27 #include "classfile/javaAssertions.hpp" 28 #include "classfile/systemDictionary.hpp" 29 #include "classfile/vmSymbols.hpp" 30 #include "code/codeCache.hpp" 31 #include "code/scopeDesc.hpp" 32 #include "runtime/sweeper.hpp" 33 #include "compiler/compileBroker.hpp" 34 #include "compiler/compileLog.hpp" 35 #include "compiler/compilerOracle.hpp" 36 #include "interpreter/linkResolver.hpp" 37 #include "memory/allocation.inline.hpp" 38 #include "memory/oopFactory.hpp" 39 #include "memory/resourceArea.hpp" 40 #include "memory/universe.inline.hpp" 41 #include "oops/methodData.hpp" 42 #include "oops/objArrayKlass.hpp" 43 #include "oops/oop.inline.hpp" 44 #include "prims/jvmtiExport.hpp" 45 #include "runtime/init.hpp" 46 #include "runtime/reflection.hpp" 47 #include "runtime/sharedRuntime.hpp" 48 #include "utilities/dtrace.hpp" 49 #include "jvmci/jvmciRuntime.hpp" 50 #include "jvmci/jvmciJavaClasses.hpp" 51 52 JVMCIEnv::JVMCIEnv(CompileTask* task, int system_dictionary_modification_counter): 53 _task(task), 54 _system_dictionary_modification_counter(system_dictionary_modification_counter), 55 _failure_reason(NULL), 56 _retryable(true) 57 { 58 // Get Jvmti capabilities under lock to get consistent values. 59 MutexLocker mu(JvmtiThreadState_lock); 60 _jvmti_can_hotswap_or_post_breakpoint = JvmtiExport::can_hotswap_or_post_breakpoint(); 61 _jvmti_can_access_local_variables = JvmtiExport::can_access_local_variables(); 62 _jvmti_can_post_on_exceptions = JvmtiExport::can_post_on_exceptions(); 63 } 64 65 // ------------------------------------------------------------------ 66 // Note: the logic of this method should mirror the logic of 67 // constantPoolOopDesc::verify_constant_pool_resolve. 68 bool JVMCIEnv::check_klass_accessibility(KlassHandle accessing_klass, KlassHandle resolved_klass) { 69 if (accessing_klass->is_objArray_klass()) { 70 accessing_klass = ObjArrayKlass::cast(accessing_klass())->bottom_klass(); 71 } 72 if (!accessing_klass->is_instance_klass()) { 73 return true; 74 } 75 76 if (resolved_klass->is_objArray_klass()) { 77 // Find the element klass, if this is an array. 78 resolved_klass = ObjArrayKlass::cast(resolved_klass())->bottom_klass(); 79 } 80 if (resolved_klass->is_instance_klass()) { 81 Reflection::VerifyClassAccessResults result = 82 Reflection::verify_class_access(accessing_klass(), resolved_klass(), true); 83 return result == Reflection::ACCESS_OK; 84 } 85 return true; 86 } 87 88 // ------------------------------------------------------------------ 89 KlassHandle JVMCIEnv::get_klass_by_name_impl(KlassHandle& accessing_klass, 90 const constantPoolHandle& cpool, 91 Symbol* sym, 92 bool require_local) { 93 JVMCI_EXCEPTION_CONTEXT; 94 95 // Now we need to check the SystemDictionary 96 if (sym->byte_at(0) == 'L' && 97 sym->byte_at(sym->utf8_length()-1) == ';') { 98 // This is a name from a signature. Strip off the trimmings. 99 // Call recursive to keep scope of strippedsym. 100 TempNewSymbol strippedsym = SymbolTable::new_symbol(sym->as_utf8()+1, 101 sym->utf8_length()-2, 102 CHECK_(KlassHandle())); 103 return get_klass_by_name_impl(accessing_klass, cpool, strippedsym, require_local); 104 } 105 106 Handle loader(THREAD, (oop)NULL); 107 Handle domain(THREAD, (oop)NULL); 108 if (!accessing_klass.is_null()) { 109 loader = Handle(THREAD, accessing_klass->class_loader()); 110 domain = Handle(THREAD, accessing_klass->protection_domain()); 111 } 112 113 KlassHandle found_klass; 114 { 115 ttyUnlocker ttyul; // release tty lock to avoid ordering problems 116 MutexLocker ml(Compile_lock); 117 Klass* kls; 118 if (!require_local) { 119 kls = SystemDictionary::find_constrained_instance_or_array_klass(sym, loader, CHECK_(KlassHandle())); 120 } else { 121 kls = SystemDictionary::find_instance_or_array_klass(sym, loader, domain, CHECK_(KlassHandle())); 122 } 123 found_klass = KlassHandle(THREAD, kls); 124 } 125 126 // If we fail to find an array klass, look again for its element type. 127 // The element type may be available either locally or via constraints. 128 // In either case, if we can find the element type in the system dictionary, 129 // we must build an array type around it. The CI requires array klasses 130 // to be loaded if their element klasses are loaded, except when memory 131 // is exhausted. 132 if (sym->byte_at(0) == '[' && 133 (sym->byte_at(1) == '[' || sym->byte_at(1) == 'L')) { 134 // We have an unloaded array. 135 // Build it on the fly if the element class exists. 136 TempNewSymbol elem_sym = SymbolTable::new_symbol(sym->as_utf8()+1, 137 sym->utf8_length()-1, 138 CHECK_(KlassHandle())); 139 140 // Get element Klass recursively. 141 KlassHandle elem_klass = 142 get_klass_by_name_impl(accessing_klass, 143 cpool, 144 elem_sym, 145 require_local); 146 if (!elem_klass.is_null()) { 147 // Now make an array for it 148 return elem_klass->array_klass(CHECK_(KlassHandle())); 149 } 150 } 151 152 if (found_klass.is_null() && !cpool.is_null() && cpool->has_preresolution()) { 153 // Look inside the constant pool for pre-resolved class entries. 154 for (int i = cpool->length() - 1; i >= 1; i--) { 155 if (cpool->tag_at(i).is_klass()) { 156 Klass* kls = cpool->resolved_klass_at(i); 157 if (kls->name() == sym) { 158 return kls; 159 } 160 } 161 } 162 } 163 164 return found_klass(); 165 } 166 167 // ------------------------------------------------------------------ 168 KlassHandle JVMCIEnv::get_klass_by_name(KlassHandle accessing_klass, 169 Symbol* klass_name, 170 bool require_local) { 171 ResourceMark rm; 172 constantPoolHandle cpool; 173 return get_klass_by_name_impl(accessing_klass, 174 cpool, 175 klass_name, 176 require_local); 177 } 178 179 // ------------------------------------------------------------------ 180 // Implementation of get_klass_by_index. 181 KlassHandle JVMCIEnv::get_klass_by_index_impl(const constantPoolHandle& cpool, 182 int index, 183 bool& is_accessible, 184 KlassHandle accessor) { 185 JVMCI_EXCEPTION_CONTEXT; 186 KlassHandle klass (THREAD, ConstantPool::klass_at_if_loaded(cpool, index)); 187 Symbol* klass_name = NULL; 188 if (klass.is_null()) { 189 klass_name = cpool->klass_name_at(index); 190 } 191 192 if (klass.is_null()) { 193 // Not found in constant pool. Use the name to do the lookup. 194 KlassHandle k = get_klass_by_name_impl(accessor, 195 cpool, 196 klass_name, 197 false); 198 // Calculate accessibility the hard way. 199 if (k.is_null()) { 200 is_accessible = false; 201 } else if (k->class_loader() != accessor->class_loader() && 202 get_klass_by_name_impl(accessor, cpool, k->name(), true).is_null()) { 203 // Loaded only remotely. Not linked yet. 204 is_accessible = false; 205 } else { 206 // Linked locally, and we must also check public/private, etc. 207 is_accessible = check_klass_accessibility(accessor, k); 208 } 209 if (!is_accessible) { 210 return KlassHandle(); 211 } 212 return k; 213 } 214 215 // It is known to be accessible, since it was found in the constant pool. 216 is_accessible = true; 217 return klass; 218 } 219 220 // ------------------------------------------------------------------ 221 // Get a klass from the constant pool. 222 KlassHandle JVMCIEnv::get_klass_by_index(const constantPoolHandle& cpool, 223 int index, 224 bool& is_accessible, 225 KlassHandle accessor) { 226 ResourceMark rm; 227 KlassHandle result = get_klass_by_index_impl(cpool, index, is_accessible, accessor); 228 return result; 229 } 230 231 // ------------------------------------------------------------------ 232 // Implementation of get_field_by_index. 233 // 234 // Implementation note: the results of field lookups are cached 235 // in the accessor klass. 236 void JVMCIEnv::get_field_by_index_impl(instanceKlassHandle klass, fieldDescriptor& field_desc, 237 int index) { 238 JVMCI_EXCEPTION_CONTEXT; 239 240 assert(klass->is_linked(), "must be linked before using its constant-pool"); 241 242 constantPoolHandle cpool(thread, klass->constants()); 243 244 // Get the field's name, signature, and type. 245 Symbol* name = cpool->name_ref_at(index); 246 247 int nt_index = cpool->name_and_type_ref_index_at(index); 248 int sig_index = cpool->signature_ref_index_at(nt_index); 249 Symbol* signature = cpool->symbol_at(sig_index); 250 251 // Get the field's declared holder. 252 int holder_index = cpool->klass_ref_index_at(index); 253 bool holder_is_accessible; 254 KlassHandle declared_holder = get_klass_by_index(cpool, holder_index, 255 holder_is_accessible, 256 klass); 257 258 // The declared holder of this field may not have been loaded. 259 // Bail out with partial field information. 260 if (!holder_is_accessible) { 261 return; 262 } 263 264 265 // Perform the field lookup. 266 Klass* canonical_holder = 267 InstanceKlass::cast(declared_holder())->find_field(name, signature, &field_desc); 268 if (canonical_holder == NULL) { 269 return; 270 } 271 272 assert(canonical_holder == field_desc.field_holder(), "just checking"); 273 } 274 275 // ------------------------------------------------------------------ 276 // Get a field by index from a klass's constant pool. 277 void JVMCIEnv::get_field_by_index(instanceKlassHandle accessor, fieldDescriptor& fd, int index) { 278 ResourceMark rm; 279 return get_field_by_index_impl(accessor, fd, index); 280 } 281 282 // ------------------------------------------------------------------ 283 // Perform an appropriate method lookup based on accessor, holder, 284 // name, signature, and bytecode. 285 methodHandle JVMCIEnv::lookup_method(instanceKlassHandle h_accessor, 286 instanceKlassHandle h_holder, 287 Symbol* name, 288 Symbol* sig, 289 Bytecodes::Code bc) { 290 JVMCI_EXCEPTION_CONTEXT; 291 LinkResolver::check_klass_accessability(h_accessor, h_holder, KILL_COMPILE_ON_FATAL_(NULL)); 292 methodHandle dest_method; 293 LinkInfo link_info(h_holder, name, sig, h_accessor, NULL, /*check_access*/true); 294 switch (bc) { 295 case Bytecodes::_invokestatic: 296 dest_method = 297 LinkResolver::resolve_static_call_or_null(link_info); 298 break; 299 case Bytecodes::_invokespecial: 300 dest_method = 301 LinkResolver::resolve_special_call_or_null(link_info); 302 break; 303 case Bytecodes::_invokeinterface: 304 dest_method = 305 LinkResolver::linktime_resolve_interface_method_or_null(link_info); 306 break; 307 case Bytecodes::_invokevirtual: 308 dest_method = 309 LinkResolver::linktime_resolve_virtual_method_or_null(link_info); 310 break; 311 default: ShouldNotReachHere(); 312 } 313 314 return dest_method; 315 } 316 317 318 // ------------------------------------------------------------------ 319 methodHandle JVMCIEnv::get_method_by_index_impl(const constantPoolHandle& cpool, 320 int index, Bytecodes::Code bc, 321 instanceKlassHandle accessor) { 322 if (bc == Bytecodes::_invokedynamic) { 323 ConstantPoolCacheEntry* cpce = cpool->invokedynamic_cp_cache_entry_at(index); 324 bool is_resolved = !cpce->is_f1_null(); 325 if (is_resolved) { 326 // Get the invoker Method* from the constant pool. 327 // (The appendix argument, if any, will be noted in the method's signature.) 328 Method* adapter = cpce->f1_as_method(); 329 return methodHandle(adapter); 330 } 331 332 return NULL; 333 } 334 335 int holder_index = cpool->klass_ref_index_at(index); 336 bool holder_is_accessible; 337 KlassHandle holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor); 338 339 // Get the method's name and signature. 340 Symbol* name_sym = cpool->name_ref_at(index); 341 Symbol* sig_sym = cpool->signature_ref_at(index); 342 343 if (cpool->has_preresolution() 344 || (holder() == SystemDictionary::MethodHandle_klass() && 345 MethodHandles::is_signature_polymorphic_name(holder(), name_sym))) { 346 // Short-circuit lookups for JSR 292-related call sites. 347 // That is, do not rely only on name-based lookups, because they may fail 348 // if the names are not resolvable in the boot class loader (7056328). 349 switch (bc) { 350 case Bytecodes::_invokevirtual: 351 case Bytecodes::_invokeinterface: 352 case Bytecodes::_invokespecial: 353 case Bytecodes::_invokestatic: 354 { 355 Method* m = ConstantPool::method_at_if_loaded(cpool, index); 356 if (m != NULL) { 357 return m; 358 } 359 } 360 break; 361 } 362 } 363 364 if (holder_is_accessible) { // Our declared holder is loaded. 365 instanceKlassHandle lookup = get_instance_klass_for_declared_method_holder(holder); 366 methodHandle m = lookup_method(accessor, lookup, name_sym, sig_sym, bc); 367 if (!m.is_null() && 368 (bc == Bytecodes::_invokestatic 369 ? InstanceKlass::cast(m->method_holder())->is_not_initialized() 370 : !InstanceKlass::cast(m->method_holder())->is_loaded())) { 371 m = NULL; 372 } 373 if (!m.is_null()) { 374 // We found the method. 375 return m; 376 } 377 } 378 379 // Either the declared holder was not loaded, or the method could 380 // not be found. 381 382 return NULL; 383 } 384 385 // ------------------------------------------------------------------ 386 instanceKlassHandle JVMCIEnv::get_instance_klass_for_declared_method_holder(KlassHandle method_holder) { 387 // For the case of <array>.clone(), the method holder can be an ArrayKlass* 388 // instead of an InstanceKlass*. For that case simply pretend that the 389 // declared holder is Object.clone since that's where the call will bottom out. 390 if (method_holder->is_instance_klass()) { 391 return instanceKlassHandle(method_holder()); 392 } else if (method_holder->is_array_klass()) { 393 return instanceKlassHandle(SystemDictionary::Object_klass()); 394 } else { 395 ShouldNotReachHere(); 396 } 397 return NULL; 398 } 399 400 401 // ------------------------------------------------------------------ 402 methodHandle JVMCIEnv::get_method_by_index(const constantPoolHandle& cpool, 403 int index, Bytecodes::Code bc, 404 instanceKlassHandle accessor) { 405 ResourceMark rm; 406 return get_method_by_index_impl(cpool, index, bc, accessor); 407 } 408 409 // ------------------------------------------------------------------ 410 // Check for changes to the system dictionary during compilation 411 // class loads, evolution, breakpoints 412 JVMCIEnv::CodeInstallResult JVMCIEnv::check_for_system_dictionary_modification(Dependencies* dependencies, Handle compiled_code, 413 JVMCIEnv* env, char** failure_detail) { 414 // If JVMTI capabilities were enabled during compile, the compilation is invalidated. 415 if (env != NULL) { 416 if (!env->_jvmti_can_hotswap_or_post_breakpoint && JvmtiExport::can_hotswap_or_post_breakpoint()) { 417 *failure_detail = (char*) "Hotswapping or breakpointing was enabled during compilation"; 418 return JVMCIEnv::dependencies_failed; 419 } 420 } 421 422 // Dependencies must be checked when the system dictionary changes 423 // or if we don't know whether it has changed (i.e., env == NULL). 424 // In debug mode, always check dependencies. 425 bool counter_changed = env != NULL && env->_system_dictionary_modification_counter != SystemDictionary::number_of_modifications(); 426 bool verify_deps = env == NULL || trueInDebug || JavaAssertions::enabled(SystemDictionary::HotSpotInstalledCode_klass()->name()->as_C_string(), true); 427 if (!counter_changed && !verify_deps) { 428 return JVMCIEnv::ok; 429 } 430 431 for (Dependencies::DepStream deps(dependencies); deps.next(); ) { 432 Klass* witness = deps.check_dependency(); 433 if (witness != NULL) { 434 // Use a fixed size buffer to prevent the string stream from 435 // resizing in the context of an inner resource mark. 436 char* buffer = NEW_RESOURCE_ARRAY(char, O_BUFLEN); 437 stringStream st(buffer, O_BUFLEN); 438 deps.print_dependency(witness, true, &st); 439 *failure_detail = st.as_string(); 440 if (env == NULL || counter_changed || deps.type() == Dependencies::evol_method) { 441 return JVMCIEnv::dependencies_failed; 442 } else { 443 // The dependencies were invalid at the time of installation 444 // without any intervening modification of the system 445 // dictionary. That means they were invalidly constructed. 446 return JVMCIEnv::dependencies_invalid; 447 } 448 } 449 if (LogCompilation) { 450 deps.log_dependency(); 451 } 452 } 453 454 return JVMCIEnv::ok; 455 } 456 457 // ------------------------------------------------------------------ 458 JVMCIEnv::CodeInstallResult JVMCIEnv::register_method( 459 const methodHandle& method, 460 nmethod*& nm, 461 int entry_bci, 462 CodeOffsets* offsets, 463 int orig_pc_offset, 464 CodeBuffer* code_buffer, 465 int frame_words, 466 OopMapSet* oop_map_set, 467 ExceptionHandlerTable* handler_table, 468 AbstractCompiler* compiler, 469 DebugInformationRecorder* debug_info, 470 Dependencies* dependencies, 471 JVMCIEnv* env, 472 int compile_id, 473 bool has_unsafe_access, 474 bool has_wide_vector, 475 Handle installed_code, 476 Handle compiled_code, 477 Handle speculation_log) { 478 JVMCI_EXCEPTION_CONTEXT; 479 nm = NULL; 480 int comp_level = CompLevel_full_optimization; 481 char* failure_detail = NULL; 482 JVMCIEnv::CodeInstallResult result; 483 { 484 // To prevent compile queue updates. 485 MutexLocker locker(MethodCompileQueue_lock, THREAD); 486 487 // Prevent SystemDictionary::add_to_hierarchy from running 488 // and invalidating our dependencies until we install this method. 489 MutexLocker ml(Compile_lock); 490 491 // Encode the dependencies now, so we can check them right away. 492 dependencies->encode_content_bytes(); 493 494 // Check for {class loads, evolution, breakpoints} during compilation 495 result = check_for_system_dictionary_modification(dependencies, compiled_code, env, &failure_detail); 496 if (result != JVMCIEnv::ok) { 497 // While not a true deoptimization, it is a preemptive decompile. 498 MethodData* mdp = method()->method_data(); 499 if (mdp != NULL) { 500 mdp->inc_decompile_count(); 501 #ifdef ASSERT 502 if (mdp->decompile_count() > (uint)PerMethodRecompilationCutoff) { 503 ResourceMark m; 504 tty->print_cr("WARN: endless recompilation of %s. Method was set to not compilable.", method()->name_and_sig_as_C_string()); 505 } 506 #endif 507 } 508 509 // All buffers in the CodeBuffer are allocated in the CodeCache. 510 // If the code buffer is created on each compile attempt 511 // as in C2, then it must be freed. 512 //code_buffer->free_blob(); 513 } else { 514 ImplicitExceptionTable implicit_tbl; 515 nm = nmethod::new_nmethod(method, 516 compile_id, 517 entry_bci, 518 offsets, 519 orig_pc_offset, 520 debug_info, dependencies, code_buffer, 521 frame_words, oop_map_set, 522 handler_table, &implicit_tbl, 523 compiler, comp_level, installed_code, speculation_log); 524 525 // Free codeBlobs 526 //code_buffer->free_blob(); 527 if (nm == NULL) { 528 // The CodeCache is full. Print out warning and disable compilation. 529 { 530 MutexUnlocker ml(Compile_lock); 531 MutexUnlocker locker(MethodCompileQueue_lock); 532 CompileBroker::handle_full_code_cache(CodeCache::get_code_blob_type(comp_level)); 533 } 534 } else { 535 nm->set_has_unsafe_access(has_unsafe_access); 536 nm->set_has_wide_vectors(has_wide_vector); 537 538 // Record successful registration. 539 // (Put nm into the task handle *before* publishing to the Java heap.) 540 CompileTask* task = env == NULL ? NULL : env->task(); 541 if (task != NULL) { 542 task->set_code(nm); 543 } 544 545 if (installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(installed_code())) { 546 if (entry_bci == InvocationEntryBci) { 547 if (TieredCompilation) { 548 // If there is an old version we're done with it 549 CompiledMethod* old = method->code(); 550 if (TraceMethodReplacement && old != NULL) { 551 ResourceMark rm; 552 char *method_name = method->name_and_sig_as_C_string(); 553 tty->print_cr("Replacing method %s", method_name); 554 } 555 if (old != NULL ) { 556 old->make_not_entrant(); 557 } 558 } 559 if (TraceNMethodInstalls) { 560 ResourceMark rm; 561 char *method_name = method->name_and_sig_as_C_string(); 562 ttyLocker ttyl; 563 tty->print_cr("Installing method (%d) %s [entry point: %p]", 564 comp_level, 565 method_name, nm->entry_point()); 566 } 567 // Allow the code to be executed 568 method->set_code(method, nm); 569 } else { 570 if (TraceNMethodInstalls ) { 571 ResourceMark rm; 572 char *method_name = method->name_and_sig_as_C_string(); 573 ttyLocker ttyl; 574 tty->print_cr("Installing osr method (%d) %s @ %d", 575 comp_level, 576 method_name, 577 entry_bci); 578 } 579 InstanceKlass::cast(method->method_holder())->add_osr_nmethod(nm); 580 } 581 } 582 } 583 result = nm != NULL ? JVMCIEnv::ok :JVMCIEnv::cache_full; 584 } 585 } 586 587 // String creation must be done outside lock 588 if (failure_detail != NULL) { 589 // A failure to allocate the string is silently ignored. 590 Handle message = java_lang_String::create_from_str(failure_detail, THREAD); 591 HotSpotCompiledNmethod::set_installationFailureMessage(compiled_code, message()); 592 } 593 594 // JVMTI -- compiled method notification (must be done outside lock) 595 if (nm != NULL) { 596 nm->post_compiled_method_load_event(); 597 598 if (env == NULL) { 599 // This compile didn't come through the CompileBroker so perform the printing here 600 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, compiler); 601 nm->maybe_print_nmethod(directive); 602 DirectivesStack::release(directive); 603 } 604 } 605 606 return result; 607 } 608