1 /* 2 * Copyright (c) 1998, 2014, 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 "interpreter/bytecodes.hpp" 27 #include "interpreter/interpreter.hpp" 28 #include "interpreter/rewriter.hpp" 29 #include "memory/gcLocker.hpp" 30 #include "memory/resourceArea.hpp" 31 #include "oops/generateOopMap.hpp" 32 #include "prims/methodHandles.hpp" 33 34 // Computes a CPC map (new_index -> original_index) for constant pool entries 35 // that are referred to by the interpreter at runtime via the constant pool cache. 36 // Also computes a CP map (original_index -> new_index). 37 // Marks entries in CP which require additional processing. 38 void Rewriter::compute_index_maps() { 39 const int length = _pool->length(); 40 init_maps(length); 41 bool saw_mh_symbol = false; 42 for (int i = 0; i < length; i++) { 43 int tag = _pool->tag_at(i).value(); 44 switch (tag) { 45 case JVM_CONSTANT_InterfaceMethodref: 46 case JVM_CONSTANT_Fieldref : // fall through 47 case JVM_CONSTANT_Methodref : // fall through 48 add_cp_cache_entry(i); 49 break; 50 case JVM_CONSTANT_String: 51 case JVM_CONSTANT_MethodHandle : // fall through 52 case JVM_CONSTANT_MethodType : // fall through 53 add_resolved_references_entry(i); 54 break; 55 case JVM_CONSTANT_Utf8: 56 if (_pool->symbol_at(i) == vmSymbols::java_lang_invoke_MethodHandle()) 57 saw_mh_symbol = true; 58 break; 59 } 60 } 61 62 // Record limits of resolved reference map for constant pool cache indices 63 record_map_limits(); 64 65 guarantee((int)_cp_cache_map.length()-1 <= (int)((u2)-1), 66 "all cp cache indexes fit in a u2"); 67 68 if (saw_mh_symbol) 69 _method_handle_invokers.initialize(length, (int)0); 70 } 71 72 // Unrewrite the bytecodes if an error occurs. 73 void Rewriter::restore_bytecodes() { 74 int len = _methods->length(); 75 bool invokespecial_error = false; 76 77 for (int i = len-1; i >= 0; i--) { 78 Method* method = _methods->at(i); 79 scan_method(method, true, &invokespecial_error); 80 assert(!invokespecial_error, "reversing should not get an invokespecial error"); 81 } 82 } 83 84 // Creates a constant pool cache given a CPC map 85 void Rewriter::make_constant_pool_cache(TRAPS) { 86 ClassLoaderData* loader_data = _pool->pool_holder()->class_loader_data(); 87 ConstantPoolCache* cache = 88 ConstantPoolCache::allocate(loader_data, _cp_cache_map, 89 _invokedynamic_cp_cache_map, 90 _invokedynamic_references_map, CHECK); 91 92 // initialize object cache in constant pool 93 _pool->initialize_resolved_references(loader_data, _resolved_references_map, 94 _resolved_reference_limit, 95 CHECK); 96 _pool->set_cache(cache); 97 cache->set_constant_pool(_pool()); 98 } 99 100 101 102 // The new finalization semantics says that registration of 103 // finalizable objects must be performed on successful return from the 104 // Object.<init> constructor. We could implement this trivially if 105 // <init> were never rewritten but since JVMTI allows this to occur, a 106 // more complicated solution is required. A special return bytecode 107 // is used only by Object.<init> to signal the finalization 108 // registration point. Additionally local 0 must be preserved so it's 109 // available to pass to the registration function. For simplicty we 110 // require that local 0 is never overwritten so it's available as an 111 // argument for registration. 112 113 void Rewriter::rewrite_Object_init(methodHandle method, TRAPS) { 114 RawBytecodeStream bcs(method); 115 while (!bcs.is_last_bytecode()) { 116 Bytecodes::Code opcode = bcs.raw_next(); 117 switch (opcode) { 118 case Bytecodes::_return: *bcs.bcp() = Bytecodes::_return_register_finalizer; break; 119 120 case Bytecodes::_istore: 121 case Bytecodes::_lstore: 122 case Bytecodes::_fstore: 123 case Bytecodes::_dstore: 124 case Bytecodes::_astore: 125 if (bcs.get_index() != 0) continue; 126 127 // fall through 128 case Bytecodes::_istore_0: 129 case Bytecodes::_lstore_0: 130 case Bytecodes::_fstore_0: 131 case Bytecodes::_dstore_0: 132 case Bytecodes::_astore_0: 133 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(), 134 "can't overwrite local 0 in Object.<init>"); 135 break; 136 } 137 } 138 } 139 140 141 // Rewrite a classfile-order CP index into a native-order CPC index. 142 void Rewriter::rewrite_member_reference(address bcp, int offset, bool reverse) { 143 address p = bcp + offset; 144 if (!reverse) { 145 int cp_index = Bytes::get_Java_u2(p); 146 int cache_index = cp_entry_to_cp_cache(cp_index); 147 Bytes::put_native_u2(p, cache_index); 148 if (!_method_handle_invokers.is_empty()) 149 maybe_rewrite_invokehandle(p - 1, cp_index, cache_index, reverse); 150 } else { 151 int cache_index = Bytes::get_native_u2(p); 152 int pool_index = cp_cache_entry_pool_index(cache_index); 153 Bytes::put_Java_u2(p, pool_index); 154 if (!_method_handle_invokers.is_empty()) 155 maybe_rewrite_invokehandle(p - 1, pool_index, cache_index, reverse); 156 } 157 } 158 159 // If the constant pool entry for invokespecial is InterfaceMethodref, 160 // we need to add a separate cpCache entry for its resolution, because it is 161 // different than the resolution for invokeinterface with InterfaceMethodref. 162 // These cannot share cpCache entries. It's unclear if all invokespecial to 163 // InterfaceMethodrefs would resolve to the same thing so a new cpCache entry 164 // is created for each one. This was added with lambda. 165 void Rewriter::rewrite_invokespecial(address bcp, int offset, bool reverse, bool* invokespecial_error) { 166 address p = bcp + offset; 167 if (!reverse) { 168 int cp_index = Bytes::get_Java_u2(p); 169 if (_pool->tag_at(cp_index).is_interface_method()) { 170 int cache_index = add_invokespecial_cp_cache_entry(cp_index); 171 if (cache_index != (int)(jushort) cache_index) { 172 *invokespecial_error = true; 173 } 174 Bytes::put_native_u2(p, cache_index); 175 } else { 176 rewrite_member_reference(bcp, offset, reverse); 177 } 178 } else { 179 rewrite_member_reference(bcp, offset, reverse); 180 } 181 } 182 183 184 // Adjust the invocation bytecode for a signature-polymorphic method (MethodHandle.invoke, etc.) 185 void Rewriter::maybe_rewrite_invokehandle(address opc, int cp_index, int cache_index, bool reverse) { 186 if (!reverse) { 187 if ((*opc) == (u1)Bytecodes::_invokevirtual || 188 // allow invokespecial as an alias, although it would be very odd: 189 (*opc) == (u1)Bytecodes::_invokespecial) { 190 assert(_pool->tag_at(cp_index).is_method(), "wrong index"); 191 // Determine whether this is a signature-polymorphic method. 192 if (cp_index >= _method_handle_invokers.length()) return; 193 int status = _method_handle_invokers[cp_index]; 194 assert(status >= -1 && status <= 1, "oob tri-state"); 195 if (status == 0) { 196 if (_pool->klass_ref_at_noresolve(cp_index) == vmSymbols::java_lang_invoke_MethodHandle() && 197 MethodHandles::is_signature_polymorphic_name(SystemDictionary::MethodHandle_klass(), 198 _pool->name_ref_at(cp_index))) { 199 // we may need a resolved_refs entry for the appendix 200 add_invokedynamic_resolved_references_entries(cp_index, cache_index); 201 status = +1; 202 } else { 203 status = -1; 204 } 205 _method_handle_invokers[cp_index] = status; 206 } 207 // We use a special internal bytecode for such methods (if non-static). 208 // The basic reason for this is that such methods need an extra "appendix" argument 209 // to transmit the call site's intended call type. 210 if (status > 0) { 211 (*opc) = (u1)Bytecodes::_invokehandle; 212 } 213 } 214 } else { 215 // Do not need to look at cp_index. 216 if ((*opc) == (u1)Bytecodes::_invokehandle) { 217 (*opc) = (u1)Bytecodes::_invokevirtual; 218 // Ignore corner case of original _invokespecial instruction. 219 // This is safe because (a) the signature polymorphic method was final, and 220 // (b) the implementation of MethodHandle will not call invokespecial on it. 221 } 222 } 223 } 224 225 226 void Rewriter::rewrite_invokedynamic(address bcp, int offset, bool reverse) { 227 address p = bcp + offset; 228 assert(p[-1] == Bytecodes::_invokedynamic, "not invokedynamic bytecode"); 229 if (!reverse) { 230 int cp_index = Bytes::get_Java_u2(p); 231 int cache_index = add_invokedynamic_cp_cache_entry(cp_index); 232 int resolved_index = add_invokedynamic_resolved_references_entries(cp_index, cache_index); 233 // Replace the trailing four bytes with a CPC index for the dynamic 234 // call site. Unlike other CPC entries, there is one per bytecode, 235 // not just one per distinct CP entry. In other words, the 236 // CPC-to-CP relation is many-to-one for invokedynamic entries. 237 // This means we must use a larger index size than u2 to address 238 // all these entries. That is the main reason invokedynamic 239 // must have a five-byte instruction format. (Of course, other JVM 240 // implementations can use the bytes for other purposes.) 241 // Note: We use native_u4 format exclusively for 4-byte indexes. 242 Bytes::put_native_u4(p, ConstantPool::encode_invokedynamic_index(cache_index)); 243 // add the bcp in case we need to patch this bytecode if we also find a 244 // invokespecial/InterfaceMethodref in the bytecode stream 245 _patch_invokedynamic_bcps->push(p); 246 _patch_invokedynamic_refs->push(resolved_index); 247 } else { 248 int cache_index = ConstantPool::decode_invokedynamic_index( 249 Bytes::get_native_u4(p)); 250 // We will reverse the bytecode rewriting _after_ adjusting them. 251 // Adjust the cache index by offset to the invokedynamic entries in the 252 // cpCache plus the delta if the invokedynamic bytecodes were adjusted. 253 int adjustment = cp_cache_delta() + _first_iteration_cp_cache_limit; 254 int cp_index = invokedynamic_cp_cache_entry_pool_index(cache_index - adjustment); 255 assert(_pool->tag_at(cp_index).is_invoke_dynamic(), "wrong index"); 256 // zero out 4 bytes 257 Bytes::put_Java_u4(p, 0); 258 Bytes::put_Java_u2(p, cp_index); 259 } 260 } 261 262 void Rewriter::patch_invokedynamic_bytecodes() { 263 // If the end of the cp_cache is the same as after initializing with the 264 // cpool, nothing needs to be done. Invokedynamic bytecodes are at the 265 // correct offsets. ie. no invokespecials added 266 int delta = cp_cache_delta(); 267 if (delta > 0) { 268 int length = _patch_invokedynamic_bcps->length(); 269 assert(length == _patch_invokedynamic_refs->length(), 270 "lengths should match"); 271 for (int i = 0; i < length; i++) { 272 address p = _patch_invokedynamic_bcps->at(i); 273 int cache_index = ConstantPool::decode_invokedynamic_index( 274 Bytes::get_native_u4(p)); 275 Bytes::put_native_u4(p, ConstantPool::encode_invokedynamic_index(cache_index + delta)); 276 277 // invokedynamic resolved references map also points to cp cache and must 278 // add delta to each. 279 int resolved_index = _patch_invokedynamic_refs->at(i); 280 for (int entry = 0; entry < ConstantPoolCacheEntry::_indy_resolved_references_entries; entry++) { 281 assert(_invokedynamic_references_map[resolved_index+entry] == cache_index, 282 "should be the same index"); 283 _invokedynamic_references_map.at_put(resolved_index+entry, 284 cache_index + delta); 285 } 286 } 287 } 288 } 289 290 291 // Rewrite some ldc bytecodes to _fast_aldc 292 void Rewriter::maybe_rewrite_ldc(address bcp, int offset, bool is_wide, 293 bool reverse) { 294 if (!reverse) { 295 assert((*bcp) == (is_wide ? Bytecodes::_ldc_w : Bytecodes::_ldc), "not ldc bytecode"); 296 address p = bcp + offset; 297 int cp_index = is_wide ? Bytes::get_Java_u2(p) : (u1)(*p); 298 constantTag tag = _pool->tag_at(cp_index).value(); 299 if (tag.is_method_handle() || tag.is_method_type() || tag.is_string()) { 300 int ref_index = cp_entry_to_resolved_references(cp_index); 301 if (is_wide) { 302 (*bcp) = Bytecodes::_fast_aldc_w; 303 assert(ref_index == (u2)ref_index, "index overflow"); 304 Bytes::put_native_u2(p, ref_index); 305 } else { 306 (*bcp) = Bytecodes::_fast_aldc; 307 assert(ref_index == (u1)ref_index, "index overflow"); 308 (*p) = (u1)ref_index; 309 } 310 } 311 } else { 312 Bytecodes::Code rewritten_bc = 313 (is_wide ? Bytecodes::_fast_aldc_w : Bytecodes::_fast_aldc); 314 if ((*bcp) == rewritten_bc) { 315 address p = bcp + offset; 316 int ref_index = is_wide ? Bytes::get_native_u2(p) : (u1)(*p); 317 int pool_index = resolved_references_entry_to_pool_index(ref_index); 318 if (is_wide) { 319 (*bcp) = Bytecodes::_ldc_w; 320 assert(pool_index == (u2)pool_index, "index overflow"); 321 Bytes::put_Java_u2(p, pool_index); 322 } else { 323 (*bcp) = Bytecodes::_ldc; 324 assert(pool_index == (u1)pool_index, "index overflow"); 325 (*p) = (u1)pool_index; 326 } 327 } 328 } 329 } 330 331 332 // Rewrites a method given the index_map information 333 void Rewriter::scan_method(Method* method, bool reverse, bool* invokespecial_error) { 334 335 int nof_jsrs = 0; 336 bool has_monitor_bytecodes = false; 337 338 { 339 // We cannot tolerate a GC in this block, because we've 340 // cached the bytecodes in 'code_base'. If the Method* 341 // moves, the bytecodes will also move. 342 No_Safepoint_Verifier nsv; 343 Bytecodes::Code c; 344 345 // Bytecodes and their length 346 const address code_base = method->code_base(); 347 const int code_length = method->code_size(); 348 349 int bc_length; 350 for (int bci = 0; bci < code_length; bci += bc_length) { 351 address bcp = code_base + bci; 352 int prefix_length = 0; 353 c = (Bytecodes::Code)(*bcp); 354 355 // Since we have the code, see if we can get the length 356 // directly. Some more complicated bytecodes will report 357 // a length of zero, meaning we need to make another method 358 // call to calculate the length. 359 bc_length = Bytecodes::length_for(c); 360 if (bc_length == 0) { 361 bc_length = Bytecodes::length_at(method, bcp); 362 363 // length_at will put us at the bytecode after the one modified 364 // by 'wide'. We don't currently examine any of the bytecodes 365 // modified by wide, but in case we do in the future... 366 if (c == Bytecodes::_wide) { 367 prefix_length = 1; 368 c = (Bytecodes::Code)bcp[1]; 369 } 370 } 371 372 assert(bc_length != 0, "impossible bytecode length"); 373 374 switch (c) { 375 case Bytecodes::_lookupswitch : { 376 #ifndef CC_INTERP 377 Bytecode_lookupswitch bc(method, bcp); 378 (*bcp) = ( 379 bc.number_of_pairs() < BinarySwitchThreshold 380 ? Bytecodes::_fast_linearswitch 381 : Bytecodes::_fast_binaryswitch 382 ); 383 #endif 384 break; 385 } 386 case Bytecodes::_fast_linearswitch: 387 case Bytecodes::_fast_binaryswitch: { 388 #ifndef CC_INTERP 389 (*bcp) = Bytecodes::_lookupswitch; 390 #endif 391 break; 392 } 393 394 case Bytecodes::_invokespecial : { 395 rewrite_invokespecial(bcp, prefix_length+1, reverse, invokespecial_error); 396 break; 397 } 398 399 case Bytecodes::_getstatic : // fall through 400 case Bytecodes::_putstatic : // fall through 401 case Bytecodes::_getfield : // fall through 402 case Bytecodes::_putfield : // fall through 403 case Bytecodes::_invokevirtual : // fall through 404 case Bytecodes::_invokestatic : 405 case Bytecodes::_invokeinterface: 406 case Bytecodes::_invokehandle : // if reverse=true 407 rewrite_member_reference(bcp, prefix_length+1, reverse); 408 break; 409 case Bytecodes::_invokedynamic: 410 rewrite_invokedynamic(bcp, prefix_length+1, reverse); 411 break; 412 case Bytecodes::_ldc: 413 case Bytecodes::_fast_aldc: // if reverse=true 414 maybe_rewrite_ldc(bcp, prefix_length+1, false, reverse); 415 break; 416 case Bytecodes::_ldc_w: 417 case Bytecodes::_fast_aldc_w: // if reverse=true 418 maybe_rewrite_ldc(bcp, prefix_length+1, true, reverse); 419 break; 420 case Bytecodes::_jsr : // fall through 421 case Bytecodes::_jsr_w : nof_jsrs++; break; 422 case Bytecodes::_monitorenter : // fall through 423 case Bytecodes::_monitorexit : has_monitor_bytecodes = true; break; 424 } 425 } 426 } 427 428 // Update access flags 429 if (has_monitor_bytecodes) { 430 method->set_has_monitor_bytecodes(); 431 } 432 433 // The present of a jsr bytecode implies that the method might potentially 434 // have to be rewritten, so we run the oopMapGenerator on the method 435 if (nof_jsrs > 0) { 436 method->set_has_jsrs(); 437 // Second pass will revisit this method. 438 assert(method->has_jsrs(), "didn't we just set this?"); 439 } 440 } 441 442 // After constant pool is created, revisit methods containing jsrs. 443 methodHandle Rewriter::rewrite_jsrs(methodHandle method, TRAPS) { 444 ResourceMark rm(THREAD); 445 ResolveOopMapConflicts romc(method); 446 methodHandle original_method = method; 447 method = romc.do_potential_rewrite(CHECK_(methodHandle())); 448 // Update monitor matching info. 449 if (romc.monitor_safe()) { 450 method->set_guaranteed_monitor_matching(); 451 } 452 453 return method; 454 } 455 456 void Rewriter::rewrite_bytecodes(TRAPS) { 457 assert(_pool->cache() == NULL, "constant pool cache must not be set yet"); 458 459 // determine index maps for Method* rewriting 460 compute_index_maps(); 461 462 if (RegisterFinalizersAtInit && _klass->name() == vmSymbols::java_lang_Object()) { 463 bool did_rewrite = false; 464 int i = _methods->length(); 465 while (i-- > 0) { 466 Method* method = _methods->at(i); 467 if (method->intrinsic_id() == vmIntrinsics::_Object_init) { 468 // rewrite the return bytecodes of Object.<init> to register the 469 // object for finalization if needed. 470 methodHandle m(THREAD, method); 471 rewrite_Object_init(m, CHECK); 472 did_rewrite = true; 473 break; 474 } 475 } 476 assert(did_rewrite, "must find Object::<init> to rewrite it"); 477 } 478 479 // rewrite methods, in two passes 480 int len = _methods->length(); 481 bool invokespecial_error = false; 482 483 for (int i = len-1; i >= 0; i--) { 484 Method* method = _methods->at(i); 485 scan_method(method, false, &invokespecial_error); 486 if (invokespecial_error) { 487 // If you get an error here, there is no reversing bytecodes 488 // This exception is stored for this class and no further attempt is 489 // made at verifying or rewriting. 490 THROW_MSG(vmSymbols::java_lang_InternalError(), 491 "This classfile overflows invokespecial for interfaces " 492 "and cannot be loaded"); 493 return; 494 } 495 } 496 497 // May have to fix invokedynamic bytecodes if invokestatic/InterfaceMethodref 498 // entries had to be added. 499 patch_invokedynamic_bytecodes(); 500 } 501 502 void Rewriter::rewrite(instanceKlassHandle klass, TRAPS) { 503 ResourceMark rm(THREAD); 504 Rewriter rw(klass, klass->constants(), klass->methods(), CHECK); 505 // (That's all, folks.) 506 } 507 508 509 Rewriter::Rewriter(instanceKlassHandle klass, constantPoolHandle cpool, Array<Method*>* methods, TRAPS) 510 : _klass(klass), 511 _pool(cpool), 512 _methods(methods) 513 { 514 515 // Rewrite bytecodes - exception here exits. 516 rewrite_bytecodes(CHECK); 517 518 // Stress restoring bytecodes 519 if (StressRewriter) { 520 restore_bytecodes(); 521 rewrite_bytecodes(CHECK); 522 } 523 524 // allocate constant pool cache, now that we've seen all the bytecodes 525 make_constant_pool_cache(THREAD); 526 527 // Restore bytecodes to their unrewritten state if there are exceptions 528 // rewriting bytecodes or allocating the cpCache 529 if (HAS_PENDING_EXCEPTION) { 530 restore_bytecodes(); 531 return; 532 } 533 534 // Relocate after everything, but still do this under the is_rewritten flag, 535 // so methods with jsrs in custom class lists in aren't attempted to be 536 // rewritten in the RO section of the shared archive. 537 // Relocated bytecodes don't have to be restored, only the cp cache entries 538 int len = _methods->length(); 539 for (int i = len-1; i >= 0; i--) { 540 methodHandle m(THREAD, _methods->at(i)); 541 542 if (m->has_jsrs()) { 543 m = rewrite_jsrs(m, THREAD); 544 // Restore bytecodes to their unrewritten state if there are exceptions 545 // relocating bytecodes. If some are relocated, that is ok because that 546 // doesn't affect constant pool to cpCache rewriting. 547 if (HAS_PENDING_EXCEPTION) { 548 restore_bytecodes(); 549 return; 550 } 551 // Method might have gotten rewritten. 552 methods->at_put(i, m()); 553 } 554 } 555 }