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, ConstantPool::encode_invokedynamic_index(_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 = ConstantPool::decode_invokedynamic_index(
317                         Bytes::get_native_u4(p));
318     int cp_index = _initialized_indy_entries.at(cache_index).constant_pool_index();
319     assert(_pool->tag_at(cp_index).is_invoke_dynamic(), "wrong index");
320     // zero out 4 bytes
321     Bytes::put_Java_u4(p, 0);
322     Bytes::put_Java_u2(p, (u2)cp_index);
323   }
324 }
325 
326 // Rewrite some ldc bytecodes to _fast_aldc
327 void Rewriter::maybe_rewrite_ldc(address bcp, int offset, bool is_wide,
328                                  bool reverse) {
329   if (!reverse) {
330     assert((*bcp) == (is_wide ? Bytecodes::_ldc_w : Bytecodes::_ldc), "not ldc bytecode");
331     address p = bcp + offset;
332     int cp_index = is_wide ? Bytes::get_Java_u2(p) : (u1)(*p);
333     constantTag tag = _pool->tag_at(cp_index).value();
334 
335     if (tag.is_method_handle() ||
336         tag.is_method_type() ||
337         tag.is_string() ||
338         (tag.is_dynamic_constant() &&
339          // keep regular ldc interpreter logic for condy primitives
340          is_reference_type(Signature::basic_type(_pool->uncached_signature_ref_at(cp_index))))
341         ) {
342       int ref_index = cp_entry_to_resolved_references(cp_index);
343       if (is_wide) {
344         (*bcp) = Bytecodes::_fast_aldc_w;
345         assert(ref_index == (u2)ref_index, "index overflow");
346         Bytes::put_native_u2(p, (u2)ref_index);
347       } else {
348         (*bcp) = Bytecodes::_fast_aldc;
349         assert(ref_index == (u1)ref_index, "index overflow");
350         (*p) = (u1)ref_index;
351       }
352     }
353   } else {
354     Bytecodes::Code rewritten_bc =
355               (is_wide ? Bytecodes::_fast_aldc_w : Bytecodes::_fast_aldc);
356     if ((*bcp) == rewritten_bc) {
357       address p = bcp + offset;
358       int ref_index = is_wide ? Bytes::get_native_u2(p) : (u1)(*p);
359       int pool_index = resolved_references_entry_to_pool_index(ref_index);
360       if (is_wide) {
361         (*bcp) = Bytecodes::_ldc_w;
362         assert(pool_index == (u2)pool_index, "index overflow");
363         Bytes::put_Java_u2(p, (u2)pool_index);
364       } else {
365         (*bcp) = Bytecodes::_ldc;
366         assert(pool_index == (u1)pool_index, "index overflow");
367         (*p) = (u1)pool_index;
368       }
369     }
370   }
371 }
372 
373 
374 // Rewrites a method given the index_map information
375 void Rewriter::scan_method(Thread* thread, Method* method, bool reverse, bool* invokespecial_error) {
376 
377   int nof_jsrs = 0;
378   bool has_monitor_bytecodes = false;
379   Bytecodes::Code c;
380 
381   // Bytecodes and their length
382   const address code_base = method->code_base();
383   const int code_length = method->code_size();
384 
385   int bc_length;
386   for (int bci = 0; bci < code_length; bci += bc_length) {
387     address bcp = code_base + bci;
388     int prefix_length = 0;
389     c = (Bytecodes::Code)(*bcp);
390 
391     // Since we have the code, see if we can get the length
392     // directly. Some more complicated bytecodes will report
393     // a length of zero, meaning we need to make another method
394     // call to calculate the length.
395     bc_length = Bytecodes::length_for(c);
396     if (bc_length == 0) {
397       bc_length = Bytecodes::length_at(method, bcp);
398 
399       // length_at will put us at the bytecode after the one modified
400       // by 'wide'. We don't currently examine any of the bytecodes
401       // modified by wide, but in case we do in the future...
402       if (c == Bytecodes::_wide) {
403         prefix_length = 1;
404         c = (Bytecodes::Code)bcp[1];
405       }
406     }
407 
408     // Continuing with an invalid bytecode will fail in the loop below.
409     // So guarantee here.
410     guarantee(bc_length > 0, "Verifier should have caught this invalid bytecode");
411 
412     switch (c) {
413       case Bytecodes::_lookupswitch   : {
414 #ifndef ZERO
415         Bytecode_lookupswitch bc(method, bcp);
416         (*bcp) = (
417           bc.number_of_pairs() < BinarySwitchThreshold
418           ? Bytecodes::_fast_linearswitch
419           : Bytecodes::_fast_binaryswitch
420         );
421 #endif
422         break;
423       }
424       case Bytecodes::_fast_linearswitch:
425       case Bytecodes::_fast_binaryswitch: {
426 #ifndef ZERO
427         (*bcp) = Bytecodes::_lookupswitch;
428 #endif
429         break;
430       }
431 
432       case Bytecodes::_invokespecial  : {
433         rewrite_invokespecial(bcp, prefix_length+1, reverse, invokespecial_error);
434         break;
435       }
436 
437       case Bytecodes::_putstatic      :
438       case Bytecodes::_putfield       : {
439         if (!reverse) {
440           // Check if any final field of the class given as parameter is modified
441           // outside of initializer methods of the class. Fields that are modified
442           // are marked with a flag. For marked fields, the compilers do not perform
443           // constant folding (as the field can be changed after initialization).
444           //
445           // The check is performed after verification and only if verification has
446           // succeeded. Therefore, the class is guaranteed to be well-formed.
447           InstanceKlass* klass = method->method_holder();
448           u2 bc_index = Bytes::get_Java_u2(bcp + prefix_length + 1);
449           constantPoolHandle cp(thread, method->constants());
450           Symbol* ref_class_name = cp->klass_name_at(cp->uncached_klass_ref_index_at(bc_index));
451 
452           if (klass->name() == ref_class_name) {
453             Symbol* field_name = cp->uncached_name_ref_at(bc_index);
454             Symbol* field_sig = cp->uncached_signature_ref_at(bc_index);
455 
456             fieldDescriptor fd;
457             if (klass->find_field(field_name, field_sig, &fd) != nullptr) {
458               if (fd.access_flags().is_final()) {
459                 if (fd.access_flags().is_static()) {
460                   if (!method->is_static_initializer()) {
461                     fd.set_has_initialized_final_update(true);
462                   }
463                 } else {
464                   if (!method->is_object_initializer()) {
465                     fd.set_has_initialized_final_update(true);
466                   }
467                 }
468               }
469             }
470           }
471         }
472       }
473       // fall through
474       case Bytecodes::_getstatic      : // fall through
475       case Bytecodes::_getfield       : // fall through
476         rewrite_field_reference(bcp, prefix_length+1, reverse);
477         break;
478       case Bytecodes::_invokevirtual  : // fall through
479       case Bytecodes::_invokestatic   :
480       case Bytecodes::_invokeinterface:
481       case Bytecodes::_invokehandle   : // if reverse=true
482         rewrite_method_reference(bcp, prefix_length+1, reverse);
483         break;
484       case Bytecodes::_invokedynamic:
485         rewrite_invokedynamic(bcp, prefix_length+1, reverse);
486         break;
487       case Bytecodes::_ldc:
488       case Bytecodes::_fast_aldc:  // if reverse=true
489         maybe_rewrite_ldc(bcp, prefix_length+1, false, reverse);
490         break;
491       case Bytecodes::_ldc_w:
492       case Bytecodes::_fast_aldc_w:  // if reverse=true
493         maybe_rewrite_ldc(bcp, prefix_length+1, true, reverse);
494         break;
495       case Bytecodes::_jsr            : // fall through
496       case Bytecodes::_jsr_w          : nof_jsrs++;                   break;
497       case Bytecodes::_monitorenter   : // fall through
498       case Bytecodes::_monitorexit    : has_monitor_bytecodes = true; break;
499 
500       default: break;
501     }
502   }
503 
504   // Update flags
505   if (has_monitor_bytecodes) {
506     method->set_has_monitor_bytecodes();
507   }
508 
509   // The present of a jsr bytecode implies that the method might potentially
510   // have to be rewritten, so we run the oopMapGenerator on the method
511   if (nof_jsrs > 0) {
512     method->set_has_jsrs();
513   }
514 }
515 
516 // After constant pool is created, revisit methods containing jsrs.
517 methodHandle Rewriter::rewrite_jsrs(const methodHandle& method, TRAPS) {
518   ResourceMark rm(THREAD);
519   ResolveOopMapConflicts romc(method);
520   methodHandle new_method = romc.do_potential_rewrite(CHECK_(methodHandle()));
521   // Update monitor matching info.
522   if (romc.monitor_safe()) {
523     new_method->set_guaranteed_monitor_matching();
524   }
525 
526   return new_method;
527 }
528 
529 void Rewriter::rewrite_bytecodes(TRAPS) {
530   assert(_pool->cache() == nullptr, "constant pool cache must not be set yet");
531 
532   // determine index maps for Method* rewriting
533   compute_index_maps();
534 
535   if (RegisterFinalizersAtInit && _klass->name() == vmSymbols::java_lang_Object()) {
536     bool did_rewrite = false;
537     int i = _methods->length();
538     while (i-- > 0) {
539       Method* method = _methods->at(i);
540       if (method->intrinsic_id() == vmIntrinsics::_Object_init) {
541         // rewrite the return bytecodes of Object.<init> to register the
542         // object for finalization if needed.
543         methodHandle m(THREAD, method);
544         rewrite_Object_init(m, CHECK);
545         did_rewrite = true;
546         break;
547       }
548     }
549     assert(did_rewrite, "must find Object::<init> to rewrite it");
550   }
551 
552   // rewrite methods, in two passes
553   int len = _methods->length();
554   bool invokespecial_error = false;
555 
556   for (int i = len-1; i >= 0; i--) {
557     Method* method = _methods->at(i);
558     scan_method(THREAD, method, false, &invokespecial_error);
559     if (invokespecial_error) {
560       // If you get an error here, there is no reversing bytecodes
561       // This exception is stored for this class and no further attempt is
562       // made at verifying or rewriting.
563       THROW_MSG(vmSymbols::java_lang_InternalError(),
564                 "This classfile overflows invokespecial for interfaces "
565                 "and cannot be loaded");
566       return;
567      }
568   }
569 }
570 
571 void Rewriter::rewrite(InstanceKlass* klass, TRAPS) {
572 #if INCLUDE_CDS
573   if (klass->is_shared()) {
574     assert(!klass->is_rewritten(), "rewritten shared classes cannot be rewritten again");
575   }
576 #endif // INCLUDE_CDS
577   ResourceMark rm(THREAD);
578   constantPoolHandle cpool(THREAD, klass->constants());
579   Rewriter     rw(klass, cpool, klass->methods(), CHECK);
580   // (That's all, folks.)
581 }
582 
583 Rewriter::Rewriter(InstanceKlass* klass, const constantPoolHandle& cpool, Array<Method*>* methods, TRAPS)
584   : _klass(klass),
585     _pool(cpool),
586     _methods(methods),
587     _cp_map(cpool->length()),
588     _reference_map(cpool->length()),
589     _resolved_references_map(cpool->length() / 2),
590     _invokedynamic_references_map(cpool->length() / 2),
591     _method_handle_invokers(cpool->length()),
592     _invokedynamic_index(0),
593     _field_entry_index(0),
594     _method_entry_index(0)
595 {
596 
597   // Rewrite bytecodes - exception here exits.
598   rewrite_bytecodes(CHECK);
599 
600   // Stress restoring bytecodes
601   if (StressRewriter) {
602     restore_bytecodes(THREAD);
603     rewrite_bytecodes(CHECK);
604   }
605 
606   // allocate constant pool cache, now that we've seen all the bytecodes
607   make_constant_pool_cache(THREAD);
608 
609   // Restore bytecodes to their unrewritten state if there are exceptions
610   // rewriting bytecodes or allocating the cpCache
611   if (HAS_PENDING_EXCEPTION) {
612     restore_bytecodes(THREAD);
613     return;
614   }
615 
616   // Relocate after everything, but still do this under the is_rewritten flag,
617   // so methods with jsrs in custom class lists in aren't attempted to be
618   // rewritten in the RO section of the shared archive.
619   // Relocated bytecodes don't have to be restored, only the cp cache entries
620   int len = _methods->length();
621   for (int i = len-1; i >= 0; i--) {
622     methodHandle m(THREAD, _methods->at(i));
623 
624     if (m->has_jsrs()) {
625       m = rewrite_jsrs(m, THREAD);
626       // Restore bytecodes to their unrewritten state if there are exceptions
627       // relocating bytecodes.  If some are relocated, that is ok because that
628       // doesn't affect constant pool to cpCache rewriting.
629       if (HAS_PENDING_EXCEPTION) {
630         restore_bytecodes(THREAD);
631         return;
632       }
633       // Method might have gotten rewritten.
634       methods->at_put(i, m());
635     }
636   }
637 }