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