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/cdsConfig.hpp"
 27 #include "cds/metaspaceShared.hpp"
 28 #include "classfile/vmClasses.hpp"
 29 #include "interpreter/bytecodes.hpp"
 30 #include "interpreter/bytecodeStream.hpp"
 31 #include "interpreter/interpreter.hpp"
 32 #include "interpreter/rewriter.hpp"
 33 #include "memory/metadataFactory.hpp"
 34 #include "memory/resourceArea.hpp"
 35 #include "oops/generateOopMap.hpp"
 36 #include "oops/resolvedFieldEntry.hpp"
 37 #include "oops/resolvedIndyEntry.hpp"
 38 #include "oops/resolvedMethodEntry.hpp"
 39 #include "prims/methodHandles.hpp"
 40 #include "runtime/fieldDescriptor.inline.hpp"
 41 #include "runtime/handles.inline.hpp"
 42 #include "utilities/checkedCast.hpp"
 43 
 44 // Computes a CPC map (new_index -> original_index) for constant pool entries
 45 // that are referred to by the interpreter at runtime via the constant pool cache.
 46 // Also computes a CP map (original_index -> new_index).
 47 // Marks entries in CP which require additional processing.
 48 void Rewriter::compute_index_maps() {
 49   const int length  = _pool->length();
 50   init_maps(length);
 51   bool saw_mh_symbol = false;
 52   for (int i = 0; i < length; i++) {
 53     int tag = _pool->tag_at(i).value();
 54     switch (tag) {
 55       case JVM_CONSTANT_Fieldref          :
 56         _cp_map.at_put(i, _field_entry_index);
 57         _field_entry_index++;
 58         _initialized_field_entries.push(ResolvedFieldEntry((u2)i));
 59         break;
 60       case JVM_CONSTANT_InterfaceMethodref: // fall through
 61       case JVM_CONSTANT_Methodref         :
 62         _cp_map.at_put(i, _method_entry_index);
 63         _method_entry_index++;
 64         _initialized_method_entries.push(ResolvedMethodEntry((u2)i));
 65         break;
 66       case JVM_CONSTANT_Dynamic:
 67         assert(_pool->has_dynamic_constant(), "constant pool's _has_dynamic_constant flag not set");
 68         add_resolved_references_entry(i);
 69         break;
 70       case JVM_CONSTANT_String            : // fall through
 71       case JVM_CONSTANT_MethodHandle      : // fall through
 72       case JVM_CONSTANT_MethodType        : // fall through
 73         add_resolved_references_entry(i);
 74         break;
 75       case JVM_CONSTANT_Utf8:
 76         if (_pool->symbol_at(i) == vmSymbols::java_lang_invoke_MethodHandle() ||
 77             _pool->symbol_at(i) == vmSymbols::java_lang_invoke_VarHandle()) {
 78           saw_mh_symbol = true;
 79         }
 80         break;
 81     }
 82   }
 83 
 84   // Record limits of resolved reference map for constant pool cache indices
 85   record_map_limits();
 86 
 87   guarantee(_initialized_field_entries.length() - 1 <= (int)((u2)-1), "All resolved field indices fit in a u2");
 88   guarantee(_initialized_method_entries.length() - 1 <= (int)((u2)-1), "All resolved method indices fit in a u2");
 89 
 90   if (saw_mh_symbol) {
 91     _method_handle_invokers.at_grow(length, 0);
 92   }
 93 }
 94 
 95 // Unrewrite the bytecodes if an error occurs.
 96 void Rewriter::restore_bytecodes(Thread* thread) {
 97   int len = _methods->length();
 98   bool invokespecial_error = false;
 99 
100   for (int i = len-1; i >= 0; i--) {
101     Method* method = _methods->at(i);
102     scan_method(thread, method, true, &invokespecial_error);
103     assert(!invokespecial_error, "reversing should not get an invokespecial error");
104   }
105 }
106 
107 // Creates a constant pool cache given a CPC map
108 void Rewriter::make_constant_pool_cache(TRAPS) {
109   ClassLoaderData* loader_data = _pool->pool_holder()->class_loader_data();
110   assert(_field_entry_index == _initialized_field_entries.length(), "Field entry size mismatch");
111   assert(_method_entry_index == _initialized_method_entries.length(), "Method entry size mismatch");
112   ConstantPoolCache* cache =
113       ConstantPoolCache::allocate(loader_data, _invokedynamic_references_map,
114                                   _initialized_indy_entries, _initialized_field_entries, _initialized_method_entries,
115                                   CHECK);
116 
117   // initialize object cache in constant pool
118   _pool->set_cache(cache);
119   cache->set_constant_pool(_pool());
120 
121   // _resolved_references is stored in pool->cache(), so need to be done after
122   // the above lines.
123   _pool->initialize_resolved_references(loader_data, _resolved_references_map,
124                                         _resolved_reference_limit,
125                                         THREAD);
126 #if INCLUDE_CDS
127   if (!HAS_PENDING_EXCEPTION && CDSConfig::is_dumping_archive()) {
128     if (_pool->pool_holder()->is_shared()) {
129       assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
130       // We are linking a shared class from the base archive. This
131       // class won't be written into the dynamic archive, so there's no
132       // need to save its CpCaches.
133     }
134   }
135 #endif
136 
137   // Clean up constant pool cache if initialize_resolved_references() failed.
138   if (HAS_PENDING_EXCEPTION) {
139     MetadataFactory::free_metadata(loader_data, cache);
140     _pool->set_cache(nullptr);  // so the verifier isn't confused
141   }
142 }
143 
144 
145 
146 // The new finalization semantics says that registration of
147 // finalizable objects must be performed on successful return from the
148 // Object.<init> constructor.  We could implement this trivially if
149 // <init> were never rewritten but since JVMTI allows this to occur, a
150 // more complicated solution is required.  A special return bytecode
151 // is used only by Object.<init> to signal the finalization
152 // registration point.  Additionally local 0 must be preserved so it's
153 // available to pass to the registration function.  For simplicity we
154 // require that local 0 is never overwritten so it's available as an
155 // argument for registration.
156 
157 void Rewriter::rewrite_Object_init(const methodHandle& method, TRAPS) {
158   RawBytecodeStream bcs(method);
159   while (!bcs.is_last_bytecode()) {
160     Bytecodes::Code opcode = bcs.raw_next();
161     switch (opcode) {
162       case Bytecodes::_return: *bcs.bcp() = Bytecodes::_return_register_finalizer; break;
163 
164       case Bytecodes::_istore:
165       case Bytecodes::_lstore:
166       case Bytecodes::_fstore:
167       case Bytecodes::_dstore:
168       case Bytecodes::_astore:
169         if (bcs.get_index() != 0) continue;
170 
171         // fall through
172       case Bytecodes::_istore_0:
173       case Bytecodes::_lstore_0:
174       case Bytecodes::_fstore_0:
175       case Bytecodes::_dstore_0:
176       case Bytecodes::_astore_0:
177         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
178                   "can't overwrite local 0 in Object.<init>");
179         break;
180 
181       default:
182         break;
183     }
184   }
185 }
186 
187 
188 void Rewriter::rewrite_field_reference(address bcp, int offset, bool reverse) {
189   address p = bcp + offset;
190   if (!reverse) {
191     int cp_index = Bytes::get_Java_u2(p);
192     int field_entry_index = _cp_map.at(cp_index);
193     Bytes::put_native_u2(p, checked_cast<u2>(field_entry_index));
194   } else {
195     int field_entry_index = Bytes::get_native_u2(p);
196     int pool_index = _initialized_field_entries.at(field_entry_index).constant_pool_index();
197     Bytes::put_Java_u2(p, checked_cast<u2>(pool_index));
198   }
199 }
200 
201 void Rewriter::rewrite_method_reference(address bcp, int offset, bool reverse) {
202   address p = bcp + offset;
203   if (!reverse) {
204     int  cp_index    = Bytes::get_Java_u2(p);
205     int  method_entry_index = _cp_map.at(cp_index);
206     Bytes::put_native_u2(p, (u2)method_entry_index);
207     if (!_method_handle_invokers.is_empty()) {
208       maybe_rewrite_invokehandle(p - 1, cp_index, method_entry_index, reverse);
209     }
210   } else {
211     int method_entry_index = Bytes::get_native_u2(p);
212     int pool_index = _initialized_method_entries.at(method_entry_index).constant_pool_index();
213     Bytes::put_Java_u2(p, (u2)pool_index);
214     if (!_method_handle_invokers.is_empty()) {
215       maybe_rewrite_invokehandle(p - 1, pool_index, method_entry_index, reverse);
216     }
217   }
218 }
219 
220 // If the constant pool entry for invokespecial is InterfaceMethodref,
221 // we need to add a separate cpCache entry for its resolution, because it is
222 // different than the resolution for invokeinterface with InterfaceMethodref.
223 // These cannot share cpCache entries.
224 void Rewriter::rewrite_invokespecial(address bcp, int offset, bool reverse, bool* invokespecial_error) {
225   address p = bcp + offset;
226   if (!reverse) {
227     int cp_index = Bytes::get_Java_u2(p);
228     if (_pool->tag_at(cp_index).is_interface_method()) {
229       _initialized_method_entries.push(ResolvedMethodEntry((u2)cp_index));
230       Bytes::put_native_u2(p, (u2)_method_entry_index);
231       _method_entry_index++;
232       if (_method_entry_index != (int)(u2)_method_entry_index) {
233         *invokespecial_error = true;
234       }
235     } else {
236       rewrite_method_reference(bcp, offset, reverse);
237     }
238   } else {
239     rewrite_method_reference(bcp, offset, reverse);
240   }
241 }
242 
243 // Adjust the invocation bytecode for a signature-polymorphic method (MethodHandle.invoke, etc.)
244 void Rewriter::maybe_rewrite_invokehandle(address opc, int cp_index, int cache_index, bool reverse) {
245   if (!reverse) {
246     if ((*opc) == (u1)Bytecodes::_invokevirtual ||
247         // allow invokespecial as an alias, although it would be very odd:
248         ((*opc) == (u1)Bytecodes::_invokespecial)) {
249           assert(_pool->tag_at(cp_index).is_method(), "wrong index");
250       // Determine whether this is a signature-polymorphic method.
251       if (cp_index >= _method_handle_invokers.length())  return;
252       int status = _method_handle_invokers.at(cp_index);
253       assert(status >= -1 && status <= 1, "oob tri-state");
254       if (status == 0) {
255         if (_pool->uncached_klass_ref_at_noresolve(cp_index) == vmSymbols::java_lang_invoke_MethodHandle() &&
256             MethodHandles::is_signature_polymorphic_name(vmClasses::MethodHandle_klass(),
257                                                          _pool->uncached_name_ref_at(cp_index))) {
258           // we may need a resolved_refs entry for the appendix
259           int resolved_index = add_invokedynamic_resolved_references_entry(cp_index, cache_index);
260           _initialized_method_entries.at(cache_index).set_resolved_references_index((u2)resolved_index);
261           status = +1;
262         } else if (_pool->uncached_klass_ref_at_noresolve(cp_index) == vmSymbols::java_lang_invoke_VarHandle() &&
263                    MethodHandles::is_signature_polymorphic_name(vmClasses::VarHandle_klass(),
264                                                                 _pool->uncached_name_ref_at(cp_index))) {
265           // we may need a resolved_refs entry for the appendix
266           int resolved_index = add_invokedynamic_resolved_references_entry(cp_index, cache_index);
267           _initialized_method_entries.at(cache_index).set_resolved_references_index((u2)resolved_index);
268           status = +1;
269         } else {
270           status = -1;
271         }
272         _method_handle_invokers.at(cp_index) = status;
273       }
274       // We use a special internal bytecode for such methods (if non-static).
275       // The basic reason for this is that such methods need an extra "appendix" argument
276       // to transmit the call site's intended call type.
277       if (status > 0) {
278         (*opc) = (u1)Bytecodes::_invokehandle;
279       }
280     }
281   } else {
282     // Do not need to look at cp_index.
283     if ((*opc) == (u1)Bytecodes::_invokehandle) {
284       (*opc) = (u1)Bytecodes::_invokevirtual;
285       // Ignore corner case of original _invokespecial instruction.
286       // This is safe because (a) the signature polymorphic method was final, and
287       // (b) the implementation of MethodHandle will not call invokespecial on it.
288     }
289   }
290 }
291 
292 
293 void Rewriter::rewrite_invokedynamic(address bcp, int offset, bool reverse) {
294   address p = bcp + offset;
295   assert(p[-1] == Bytecodes::_invokedynamic, "not invokedynamic bytecode");
296   if (!reverse) {
297     int cp_index = Bytes::get_Java_u2(p);
298     int resolved_index = add_invokedynamic_resolved_references_entry(cp_index, -1); // Indy no longer has a CPCE
299     // Replace the trailing four bytes with an index to the array of
300     // indy resolution information in the CPC. There is one entry for
301     // each bytecode, even if they make the same call. In other words,
302     // the CPC-to-CP relation is many-to-one for invokedynamic entries.
303     // This means we must use a larger index size than u2 to address
304     // all these entries.  That is the main reason invokedynamic
305     // must have a five-byte instruction format.  (Of course, other JVM
306     // implementations can use the bytes for other purposes.)
307     // Note: We use native_u4 format exclusively for 4-byte indexes.
308     Bytes::put_native_u4(p, ConstantPool::encode_invokedynamic_index(_invokedynamic_index));
309     _invokedynamic_index++;
310 
311     // Collect invokedynamic information before creating ResolvedInvokeDynamicInfo array
312     _initialized_indy_entries.push(ResolvedIndyEntry((u2)resolved_index, (u2)cp_index));
313   } else {
314     // Should do nothing since we are not patching this bytecode
315     int cache_index = ConstantPool::decode_invokedynamic_index(
316                         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 (RegisterFinalizersAtInit && _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 }