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 constantTag tag) { 291 JVMCI_EXCEPTION_CONTEXT; 292 LinkResolver::check_klass_accessability(h_accessor, h_holder, KILL_COMPILE_ON_FATAL_(NULL)); 293 methodHandle dest_method; 294 LinkInfo link_info(h_holder, name, sig, h_accessor, LinkInfo::needs_access_check, tag); 295 switch (bc) { 296 case Bytecodes::_invokestatic: 297 dest_method = 298 LinkResolver::resolve_static_call_or_null(link_info); 299 break; 300 case Bytecodes::_invokespecial: 301 dest_method = 302 LinkResolver::resolve_special_call_or_null(link_info); 303 break; 304 case Bytecodes::_invokeinterface: 305 dest_method = 306 LinkResolver::linktime_resolve_interface_method_or_null(link_info); 307 break; 308 case Bytecodes::_invokevirtual: 309 dest_method = 310 LinkResolver::linktime_resolve_virtual_method_or_null(link_info); 311 break; 312 default: ShouldNotReachHere(); 313 } 314 315 return dest_method; 316 } 317 318 319 // ------------------------------------------------------------------ 320 methodHandle JVMCIEnv::get_method_by_index_impl(const constantPoolHandle& cpool, 321 int index, Bytecodes::Code bc, 322 instanceKlassHandle accessor) { 323 if (bc == Bytecodes::_invokedynamic) { 324 ConstantPoolCacheEntry* cpce = cpool->invokedynamic_cp_cache_entry_at(index); 325 bool is_resolved = !cpce->is_f1_null(); 326 if (is_resolved) { 327 // Get the invoker Method* from the constant pool. 328 // (The appendix argument, if any, will be noted in the method's signature.) 329 Method* adapter = cpce->f1_as_method(); 330 return methodHandle(adapter); 331 } 332 333 return NULL; 334 } 335 336 int holder_index = cpool->klass_ref_index_at(index); 337 bool holder_is_accessible; 338 KlassHandle holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor); 339 340 // Get the method's name and signature. 341 Symbol* name_sym = cpool->name_ref_at(index); 342 Symbol* sig_sym = cpool->signature_ref_at(index); 343 344 if (cpool->has_preresolution() 345 || ((holder() == SystemDictionary::MethodHandle_klass() || holder() == SystemDictionary::VarHandle_klass()) && 346 MethodHandles::is_signature_polymorphic_name(holder(), name_sym))) { 347 // Short-circuit lookups for JSR 292-related call sites. 348 // That is, do not rely only on name-based lookups, because they may fail 349 // if the names are not resolvable in the boot class loader (7056328). 350 switch (bc) { 351 case Bytecodes::_invokevirtual: 352 case Bytecodes::_invokeinterface: 353 case Bytecodes::_invokespecial: 354 case Bytecodes::_invokestatic: 355 { 356 Method* m = ConstantPool::method_at_if_loaded(cpool, index); 357 if (m != NULL) { 358 return m; 359 } 360 } 361 break; 362 } 363 } 364 365 if (holder_is_accessible) { // Our declared holder is loaded. 366 instanceKlassHandle lookup = get_instance_klass_for_declared_method_holder(holder); 367 constantTag tag = cpool->tag_ref_at(index); 368 methodHandle m = lookup_method(accessor, lookup, name_sym, sig_sym, bc, tag); 369 if (!m.is_null() && 370 (bc == Bytecodes::_invokestatic 371 ? InstanceKlass::cast(m->method_holder())->is_not_initialized() 372 : !InstanceKlass::cast(m->method_holder())->is_loaded())) { 373 m = NULL; 374 } 375 if (!m.is_null()) { 376 // We found the method. 377 return m; 378 } 379 } 380 381 // Either the declared holder was not loaded, or the method could 382 // not be found. 383 384 return NULL; 385 } 386 387 // ------------------------------------------------------------------ 388 instanceKlassHandle JVMCIEnv::get_instance_klass_for_declared_method_holder(KlassHandle method_holder) { 389 // For the case of <array>.clone(), the method holder can be an ArrayKlass* 390 // instead of an InstanceKlass*. For that case simply pretend that the 391 // declared holder is Object.clone since that's where the call will bottom out. 392 if (method_holder->is_instance_klass()) { 393 return instanceKlassHandle(method_holder()); 394 } else if (method_holder->is_array_klass()) { 395 return instanceKlassHandle(SystemDictionary::Object_klass()); 396 } else { 397 ShouldNotReachHere(); 398 } 399 return NULL; 400 } 401 402 403 // ------------------------------------------------------------------ 404 methodHandle JVMCIEnv::get_method_by_index(const constantPoolHandle& cpool, 405 int index, Bytecodes::Code bc, 406 instanceKlassHandle accessor) { 407 ResourceMark rm; 408 return get_method_by_index_impl(cpool, index, bc, accessor); 409 } 410 411 // ------------------------------------------------------------------ 412 // Check for changes to the system dictionary during compilation 413 // class loads, evolution, breakpoints 414 JVMCIEnv::CodeInstallResult JVMCIEnv::check_for_system_dictionary_modification(Dependencies* dependencies, Handle compiled_code, 415 JVMCIEnv* env, char** failure_detail) { 416 // If JVMTI capabilities were enabled during compile, the compilation is invalidated. 417 if (env != NULL) { 418 if (!env->_jvmti_can_hotswap_or_post_breakpoint && JvmtiExport::can_hotswap_or_post_breakpoint()) { 419 *failure_detail = (char*) "Hotswapping or breakpointing was enabled during compilation"; 420 return JVMCIEnv::dependencies_failed; 421 } 422 } 423 424 // Dependencies must be checked when the system dictionary changes 425 // or if we don't know whether it has changed (i.e., env == NULL). 426 // In debug mode, always check dependencies. 427 bool counter_changed = env != NULL && env->_system_dictionary_modification_counter != SystemDictionary::number_of_modifications(); 428 bool verify_deps = env == NULL || trueInDebug || JavaAssertions::enabled(SystemDictionary::HotSpotInstalledCode_klass()->name()->as_C_string(), true); 429 if (!counter_changed && !verify_deps) { 430 return JVMCIEnv::ok; 431 } 432 433 for (Dependencies::DepStream deps(dependencies); deps.next(); ) { 434 Klass* witness = deps.check_dependency(); 435 if (witness != NULL) { 436 // Use a fixed size buffer to prevent the string stream from 437 // resizing in the context of an inner resource mark. 438 char* buffer = NEW_RESOURCE_ARRAY(char, O_BUFLEN); 439 stringStream st(buffer, O_BUFLEN); 440 deps.print_dependency(witness, true, &st); 441 *failure_detail = st.as_string(); 442 if (env == NULL || counter_changed || deps.type() == Dependencies::evol_method) { 443 return JVMCIEnv::dependencies_failed; 444 } else { 445 // The dependencies were invalid at the time of installation 446 // without any intervening modification of the system 447 // dictionary. That means they were invalidly constructed. 448 return JVMCIEnv::dependencies_invalid; 449 } 450 } 451 if (LogCompilation) { 452 deps.log_dependency(); 453 } 454 } 455 456 return JVMCIEnv::ok; 457 } 458 459 // ------------------------------------------------------------------ 460 JVMCIEnv::CodeInstallResult JVMCIEnv::register_method( 461 const methodHandle& method, 462 nmethod*& nm, 463 int entry_bci, 464 CodeOffsets* offsets, 465 int orig_pc_offset, 466 CodeBuffer* code_buffer, 467 int frame_words, 468 OopMapSet* oop_map_set, 469 ExceptionHandlerTable* handler_table, 470 AbstractCompiler* compiler, 471 DebugInformationRecorder* debug_info, 472 Dependencies* dependencies, 473 JVMCIEnv* env, 474 int compile_id, 475 bool has_unsafe_access, 476 bool has_wide_vector, 477 Handle installed_code, 478 Handle compiled_code, 479 Handle speculation_log) { 480 JVMCI_EXCEPTION_CONTEXT; 481 nm = NULL; 482 int comp_level = CompLevel_full_optimization; 483 char* failure_detail = NULL; 484 JVMCIEnv::CodeInstallResult result; 485 { 486 // To prevent compile queue updates. 487 MutexLocker locker(MethodCompileQueue_lock, THREAD); 488 489 // Prevent SystemDictionary::add_to_hierarchy from running 490 // and invalidating our dependencies until we install this method. 491 MutexLocker ml(Compile_lock); 492 493 // Encode the dependencies now, so we can check them right away. 494 dependencies->encode_content_bytes(); 495 496 // Check for {class loads, evolution, breakpoints} during compilation 497 result = check_for_system_dictionary_modification(dependencies, compiled_code, env, &failure_detail); 498 if (result != JVMCIEnv::ok) { 499 // While not a true deoptimization, it is a preemptive decompile. 500 MethodData* mdp = method()->method_data(); 501 if (mdp != NULL) { 502 mdp->inc_decompile_count(); 503 #ifdef ASSERT 504 if (mdp->decompile_count() > (uint)PerMethodRecompilationCutoff) { 505 ResourceMark m; 506 tty->print_cr("WARN: endless recompilation of %s. Method was set to not compilable.", method()->name_and_sig_as_C_string()); 507 } 508 #endif 509 } 510 511 // All buffers in the CodeBuffer are allocated in the CodeCache. 512 // If the code buffer is created on each compile attempt 513 // as in C2, then it must be freed. 514 //code_buffer->free_blob(); 515 } else { 516 ImplicitExceptionTable implicit_tbl; 517 nm = nmethod::new_nmethod(method, 518 compile_id, 519 entry_bci, 520 offsets, 521 orig_pc_offset, 522 debug_info, dependencies, code_buffer, 523 frame_words, oop_map_set, 524 handler_table, &implicit_tbl, 525 compiler, comp_level, installed_code, speculation_log); 526 527 // Free codeBlobs 528 //code_buffer->free_blob(); 529 if (nm == NULL) { 530 // The CodeCache is full. Print out warning and disable compilation. 531 { 532 MutexUnlocker ml(Compile_lock); 533 MutexUnlocker locker(MethodCompileQueue_lock); 534 CompileBroker::handle_full_code_cache(CodeCache::get_code_blob_type(comp_level)); 535 } 536 } else { 537 nm->set_has_unsafe_access(has_unsafe_access); 538 nm->set_has_wide_vectors(has_wide_vector); 539 540 // Record successful registration. 541 // (Put nm into the task handle *before* publishing to the Java heap.) 542 CompileTask* task = env == NULL ? NULL : env->task(); 543 if (task != NULL) { 544 task->set_code(nm); 545 } 546 547 if (installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(installed_code())) { 548 if (entry_bci == InvocationEntryBci) { 549 if (TieredCompilation) { 550 // If there is an old version we're done with it 551 CompiledMethod* old = method->code(); 552 if (TraceMethodReplacement && old != NULL) { 553 ResourceMark rm; 554 char *method_name = method->name_and_sig_as_C_string(); 555 tty->print_cr("Replacing method %s", method_name); 556 } 557 if (old != NULL ) { 558 old->make_not_entrant(); 559 } 560 } 561 if (TraceNMethodInstalls) { 562 ResourceMark rm; 563 char *method_name = method->name_and_sig_as_C_string(); 564 ttyLocker ttyl; 565 tty->print_cr("Installing method (%d) %s [entry point: %p]", 566 comp_level, 567 method_name, nm->entry_point()); 568 } 569 // Allow the code to be executed 570 method->set_code(method, nm); 571 } else { 572 if (TraceNMethodInstalls ) { 573 ResourceMark rm; 574 char *method_name = method->name_and_sig_as_C_string(); 575 ttyLocker ttyl; 576 tty->print_cr("Installing osr method (%d) %s @ %d", 577 comp_level, 578 method_name, 579 entry_bci); 580 } 581 InstanceKlass::cast(method->method_holder())->add_osr_nmethod(nm); 582 } 583 } 584 } 585 result = nm != NULL ? JVMCIEnv::ok :JVMCIEnv::cache_full; 586 } 587 } 588 589 // String creation must be done outside lock 590 if (failure_detail != NULL) { 591 // A failure to allocate the string is silently ignored. 592 Handle message = java_lang_String::create_from_str(failure_detail, THREAD); 593 HotSpotCompiledNmethod::set_installationFailureMessage(compiled_code, message()); 594 } 595 596 // JVMTI -- compiled method notification (must be done outside lock) 597 if (nm != NULL) { 598 nm->post_compiled_method_load_event(); 599 600 if (env == NULL) { 601 // This compile didn't come through the CompileBroker so perform the printing here 602 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, compiler); 603 nm->maybe_print_nmethod(directive); 604 DirectivesStack::release(directive); 605 } 606 } 607 608 return result; 609 } 610