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