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