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