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