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