1 /*
   2  * Copyright (c) 1997, 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/archiveHeapLoader.hpp"
  27 #include "cds/archiveBuilder.hpp"
  28 #include "cds/classPrelinker.hpp"
  29 #include "cds/heapShared.hpp"
  30 #include "classfile/classLoaderData.hpp"
  31 #include "classfile/javaClasses.inline.hpp"
  32 #include "classfile/metadataOnStackMark.hpp"
  33 #include "classfile/stringTable.hpp"
  34 #include "classfile/systemDictionary.hpp"
  35 #include "classfile/vmClasses.hpp"
  36 #include "classfile/vmSymbols.hpp"
  37 #include "code/codeCache.hpp"
  38 #include "interpreter/bootstrapInfo.hpp"
  39 #include "interpreter/linkResolver.hpp"
  40 #include "jvm.h"
  41 #include "logging/log.hpp"
  42 #include "logging/logStream.hpp"
  43 #include "memory/allocation.inline.hpp"
  44 #include "memory/metadataFactory.hpp"
  45 #include "memory/metaspaceClosure.hpp"
  46 #include "memory/oopFactory.hpp"
  47 #include "memory/resourceArea.hpp"
  48 #include "memory/universe.hpp"
  49 #include "oops/array.hpp"
  50 #include "oops/constantPool.inline.hpp"
  51 #include "oops/cpCache.inline.hpp"
  52 #include "oops/flatArrayKlass.hpp"
  53 #include "oops/instanceKlass.hpp"
  54 #include "oops/klass.inline.hpp"
  55 #include "oops/objArrayKlass.hpp"
  56 #include "oops/objArrayOop.inline.hpp"
  57 #include "oops/oop.inline.hpp"
  58 #include "oops/typeArrayOop.inline.hpp"
  59 #include "prims/jvmtiExport.hpp"
  60 #include "runtime/atomic.hpp"
  61 #include "runtime/handles.inline.hpp"
  62 #include "runtime/init.hpp"
  63 #include "runtime/javaCalls.hpp"
  64 #include "runtime/javaThread.hpp"
  65 #include "runtime/signature.hpp"
  66 #include "runtime/vframe.inline.hpp"
  67 #include "utilities/copy.hpp"
  68 
  69 ConstantPool* ConstantPool::allocate(ClassLoaderData* loader_data, int length, TRAPS) {
  70   Array<u1>* tags = MetadataFactory::new_array<u1>(loader_data, length, 0, CHECK_NULL);
  71   int size = ConstantPool::size(length);
  72   return new (loader_data, size, MetaspaceObj::ConstantPoolType, THREAD) ConstantPool(tags);
  73 }
  74 
  75 void ConstantPool::copy_fields(const ConstantPool* orig) {
  76   // Preserve dynamic constant information from the original pool
  77   if (orig->has_dynamic_constant()) {
  78     set_has_dynamic_constant();
  79   }
  80 
  81   set_major_version(orig->major_version());
  82   set_minor_version(orig->minor_version());
  83 
  84   set_source_file_name_index(orig->source_file_name_index());
  85   set_generic_signature_index(orig->generic_signature_index());
  86 }
  87 
  88 #ifdef ASSERT
  89 
  90 // MetaspaceObj allocation invariant is calloc equivalent memory
  91 // simple verification of this here (JVM_CONSTANT_Invalid == 0 )
  92 static bool tag_array_is_zero_initialized(Array<u1>* tags) {
  93   assert(tags != NULL, "invariant");
  94   const int length = tags->length();
  95   for (int index = 0; index < length; ++index) {
  96     if (JVM_CONSTANT_Invalid != tags->at(index)) {
  97       return false;
  98     }
  99   }
 100   return true;
 101 }
 102 
 103 #endif
 104 
 105 ConstantPool::ConstantPool(Array<u1>* tags) :
 106   _tags(tags),
 107   _length(tags->length()) {
 108 
 109     assert(_tags != NULL, "invariant");
 110     assert(tags->length() == _length, "invariant");
 111     assert(tag_array_is_zero_initialized(tags), "invariant");
 112     assert(0 == flags(), "invariant");
 113     assert(0 == version(), "invariant");
 114     assert(NULL == _pool_holder, "invariant");
 115 }
 116 
 117 void ConstantPool::deallocate_contents(ClassLoaderData* loader_data) {
 118   if (cache() != NULL) {
 119     MetadataFactory::free_metadata(loader_data, cache());
 120     set_cache(NULL);
 121   }
 122 
 123   MetadataFactory::free_array<Klass*>(loader_data, resolved_klasses());
 124   set_resolved_klasses(NULL);
 125 
 126   MetadataFactory::free_array<jushort>(loader_data, operands());
 127   set_operands(NULL);
 128 
 129   release_C_heap_structures();
 130 
 131   // free tag array
 132   MetadataFactory::free_array<u1>(loader_data, tags());
 133   set_tags(NULL);
 134 }
 135 
 136 void ConstantPool::release_C_heap_structures() {
 137   // walk constant pool and decrement symbol reference counts
 138   unreference_symbols();
 139 }
 140 
 141 void ConstantPool::metaspace_pointers_do(MetaspaceClosure* it) {
 142   log_trace(cds)("Iter(ConstantPool): %p", this);
 143 
 144   it->push(&_tags, MetaspaceClosure::_writable);
 145   it->push(&_cache);
 146   it->push(&_pool_holder);
 147   it->push(&_operands);
 148   it->push(&_resolved_klasses, MetaspaceClosure::_writable);
 149 
 150   for (int i = 0; i < length(); i++) {
 151     // The only MSO's embedded in the CP entries are Symbols:
 152     //   JVM_CONSTANT_String (normal and pseudo)
 153     //   JVM_CONSTANT_Utf8
 154     constantTag ctag = tag_at(i);
 155     if (ctag.is_string() || ctag.is_utf8()) {
 156       it->push(symbol_at_addr(i));
 157     }
 158   }
 159 }
 160 
 161 objArrayOop ConstantPool::resolved_references() const {
 162   return _cache->resolved_references();
 163 }
 164 
 165 // Called from outside constant pool resolution where a resolved_reference array
 166 // may not be present.
 167 objArrayOop ConstantPool::resolved_references_or_null() const {
 168   if (_cache == NULL) {
 169     return NULL;
 170   } else {
 171     return _cache->resolved_references();
 172   }
 173 }
 174 
 175 oop ConstantPool::resolved_reference_at(int index) const {
 176   oop result = resolved_references()->obj_at(index);
 177   assert(oopDesc::is_oop_or_null(result), "Must be oop");
 178   return result;
 179 }
 180 
 181 // Use a CAS for multithreaded access
 182 oop ConstantPool::set_resolved_reference_at(int index, oop new_result) {
 183   assert(oopDesc::is_oop_or_null(new_result), "Must be oop");
 184   return resolved_references()->replace_if_null(index, new_result);
 185 }
 186 
 187 // Create resolved_references array and mapping array for original cp indexes
 188 // The ldc bytecode was rewritten to have the resolved reference array index so need a way
 189 // to map it back for resolving and some unlikely miscellaneous uses.
 190 // The objects created by invokedynamic are appended to this list.
 191 void ConstantPool::initialize_resolved_references(ClassLoaderData* loader_data,
 192                                                   const intStack& reference_map,
 193                                                   int constant_pool_map_length,
 194                                                   TRAPS) {
 195   // Initialized the resolved object cache.
 196   int map_length = reference_map.length();
 197   if (map_length > 0) {
 198     // Only need mapping back to constant pool entries.  The map isn't used for
 199     // invokedynamic resolved_reference entries.  For invokedynamic entries,
 200     // the constant pool cache index has the mapping back to both the constant
 201     // pool and to the resolved reference index.
 202     if (constant_pool_map_length > 0) {
 203       Array<u2>* om = MetadataFactory::new_array<u2>(loader_data, constant_pool_map_length, CHECK);
 204 
 205       for (int i = 0; i < constant_pool_map_length; i++) {
 206         int x = reference_map.at(i);
 207         assert(x == (int)(jushort) x, "klass index is too big");
 208         om->at_put(i, (jushort)x);
 209       }
 210       set_reference_map(om);
 211     }
 212 
 213     // Create Java array for holding resolved strings, methodHandles,
 214     // methodTypes, invokedynamic and invokehandle appendix objects, etc.
 215     objArrayOop stom = oopFactory::new_objArray(vmClasses::Object_klass(), map_length, CHECK);
 216     Handle refs_handle (THREAD, stom);  // must handleize.
 217     set_resolved_references(loader_data->add_handle(refs_handle));
 218   }
 219 }
 220 
 221 void ConstantPool::allocate_resolved_klasses(ClassLoaderData* loader_data, int num_klasses, TRAPS) {
 222   // A ConstantPool can't possibly have 0xffff valid class entries,
 223   // because entry #0 must be CONSTANT_Invalid, and each class entry must refer to a UTF8
 224   // entry for the class's name. So at most we will have 0xfffe class entries.
 225   // This allows us to use 0xffff (ConstantPool::_temp_resolved_klass_index) to indicate
 226   // UnresolvedKlass entries that are temporarily created during class redefinition.
 227   assert(num_klasses < CPKlassSlot::_temp_resolved_klass_index, "sanity");
 228   assert(resolved_klasses() == NULL, "sanity");
 229   Array<Klass*>* rk = MetadataFactory::new_array<Klass*>(loader_data, num_klasses, CHECK);
 230   set_resolved_klasses(rk);
 231 }
 232 
 233 void ConstantPool::initialize_unresolved_klasses(ClassLoaderData* loader_data, TRAPS) {
 234   int len = length();
 235   int num_klasses = 0;
 236   for (int i = 1; i <len; i++) {
 237     switch (tag_at(i).value()) {
 238     case JVM_CONSTANT_ClassIndex:
 239       {
 240         const int class_index = klass_index_at(i);
 241         unresolved_klass_at_put(i, class_index, num_klasses++);
 242       }
 243       break;
 244 #ifndef PRODUCT
 245     case JVM_CONSTANT_Class:
 246     case JVM_CONSTANT_UnresolvedClass:
 247     case JVM_CONSTANT_UnresolvedClassInError:
 248       // All of these should have been reverted back to Unresolved before calling
 249       // this function.
 250       ShouldNotReachHere();
 251 #endif
 252     }
 253   }
 254   allocate_resolved_klasses(loader_data, num_klasses, THREAD);
 255 }
 256 
 257 // Hidden class support:
 258 void ConstantPool::klass_at_put(int class_index, Klass* k) {
 259   assert(k != NULL, "must be valid klass");
 260   CPKlassSlot kslot = klass_slot_at(class_index);
 261   int resolved_klass_index = kslot.resolved_klass_index();
 262   Klass** adr = resolved_klasses()->adr_at(resolved_klass_index);
 263   Atomic::release_store(adr, k);
 264 
 265   // The interpreter assumes when the tag is stored, the klass is resolved
 266   // and the Klass* non-NULL, so we need hardware store ordering here.
 267   assert(!k->name()->is_Q_signature(), "Q-type without JVM_CONSTANT_QDescBit");
 268   release_tag_at_put(class_index, JVM_CONSTANT_Class);
 269 }
 270 
 271 #if INCLUDE_CDS_JAVA_HEAP
 272 // Archive the resolved references
 273 void ConstantPool::archive_resolved_references() {
 274   if (_cache == NULL) {
 275     return; // nothing to do
 276   }
 277 
 278   InstanceKlass *ik = pool_holder();
 279   if (!(ik->is_shared_boot_class() || ik->is_shared_platform_class() ||
 280         ik->is_shared_app_class())) {
 281     // Archiving resolved references for classes from non-builtin loaders
 282     // is not yet supported.
 283     return;
 284   }
 285 
 286   objArrayOop rr = resolved_references();
 287   Array<u2>* ref_map = reference_map();
 288   if (rr != NULL) {
 289     int ref_map_len = ref_map == NULL ? 0 : ref_map->length();
 290     int rr_len = rr->length();
 291     for (int i = 0; i < rr_len; i++) {
 292       oop obj = rr->obj_at(i);
 293       rr->obj_at_put(i, NULL);
 294       if (obj != NULL && i < ref_map_len) {
 295         int index = object_to_cp_index(i);
 296         if (tag_at(index).is_string()) {
 297           oop archived_string = HeapShared::find_archived_heap_object(obj);
 298           // Update the reference to point to the archived copy
 299           // of this string.
 300           // If the string is too large to archive, NULL is
 301           // stored into rr. At run time, string_at_impl() will create and intern
 302           // the string.
 303           rr->obj_at_put(i, archived_string);
 304         }
 305       }
 306     }
 307 
 308     oop archived = HeapShared::archive_object(rr);
 309     // If the resolved references array is not archived (too large),
 310     // the 'archived' object is NULL. No need to explicitly check
 311     // the return value of archive_object() here. At runtime, the
 312     // resolved references will be created using the normal process
 313     // when there is no archived value.
 314     _cache->set_archived_references(archived);
 315   }
 316 }
 317 
 318 void ConstantPool::add_dumped_interned_strings() {
 319   objArrayOop rr = resolved_references();
 320   if (rr != NULL) {
 321     int rr_len = rr->length();
 322     for (int i = 0; i < rr_len; i++) {
 323       oop p = rr->obj_at(i);
 324       if (java_lang_String::is_instance(p)) {
 325         HeapShared::add_to_dumped_interned_strings(p);
 326       }
 327     }
 328   }
 329 }
 330 #endif
 331 
 332 #if INCLUDE_CDS
 333 // CDS support. Create a new resolved_references array.
 334 void ConstantPool::restore_unshareable_info(TRAPS) {
 335   if (!_pool_holder->is_linked() && !_pool_holder->is_rewritten()) {
 336     return;
 337   }
 338   assert(is_constantPool(), "ensure C++ vtable is restored");
 339   assert(on_stack(), "should always be set for shared constant pools");
 340   assert(is_shared(), "should always be set for shared constant pools");
 341   assert(_cache != NULL, "constant pool _cache should not be NULL");
 342 
 343   // Only create the new resolved references array if it hasn't been attempted before
 344   if (resolved_references() != NULL) return;
 345 
 346   if (vmClasses::Object_klass_loaded()) {
 347     ClassLoaderData* loader_data = pool_holder()->class_loader_data();
 348 #if INCLUDE_CDS_JAVA_HEAP
 349     if (ArchiveHeapLoader::is_fully_available() &&
 350         _cache->archived_references() != NULL) {
 351       oop archived = _cache->archived_references();
 352       // Create handle for the archived resolved reference array object
 353       Handle refs_handle(THREAD, archived);
 354       set_resolved_references(loader_data->add_handle(refs_handle));
 355       _cache->clear_archived_references();
 356     } else
 357 #endif
 358     {
 359       // No mapped archived resolved reference array
 360       // Recreate the object array and add to ClassLoaderData.
 361       int map_length = resolved_reference_length();
 362       if (map_length > 0) {
 363         objArrayOop stom = oopFactory::new_objArray(vmClasses::Object_klass(), map_length, CHECK);
 364         Handle refs_handle(THREAD, stom);  // must handleize.
 365         set_resolved_references(loader_data->add_handle(refs_handle));
 366       }
 367     }
 368   }
 369 }
 370 
 371 void ConstantPool::remove_unshareable_info() {
 372   // Shared ConstantPools are in the RO region, so the _flags cannot be modified.
 373   // The _on_stack flag is used to prevent ConstantPools from deallocation during
 374   // class redefinition. Since shared ConstantPools cannot be deallocated anyway,
 375   // we always set _on_stack to true to avoid having to change _flags during runtime.
 376   _flags |= (_on_stack | _is_shared);
 377 
 378   if (!_pool_holder->is_linked() && !_pool_holder->verified_at_dump_time()) {
 379     return;
 380   }
 381   // Resolved references are not in the shared archive.
 382   // Save the length for restoration.  It is not necessarily the same length
 383   // as reference_map.length() if invokedynamic is saved. It is needed when
 384   // re-creating the resolved reference array if archived heap data cannot be map
 385   // at runtime.
 386   set_resolved_reference_length(
 387     resolved_references() != NULL ? resolved_references()->length() : 0);
 388   set_resolved_references(OopHandle());
 389 
 390   bool archived = false;
 391   for (int index = 1; index < length(); index++) { // Index 0 is unused
 392     switch (tag_at(index).value()) {
 393     case JVM_CONSTANT_UnresolvedClassInError:
 394       {
 395         jbyte qdesc_bit = tag_at(index).is_Qdescriptor_klass() ? (jbyte) JVM_CONSTANT_QDescBit : 0;
 396         tag_at_put(index, JVM_CONSTANT_UnresolvedClass | qdesc_bit);
 397       }
 398       break;
 399     case JVM_CONSTANT_MethodHandleInError:
 400       tag_at_put(index, JVM_CONSTANT_MethodHandle);
 401       break;
 402     case JVM_CONSTANT_MethodTypeInError:
 403       tag_at_put(index, JVM_CONSTANT_MethodType);
 404       break;
 405     case JVM_CONSTANT_DynamicInError:
 406       tag_at_put(index, JVM_CONSTANT_Dynamic);
 407       break;
 408     case JVM_CONSTANT_Class:
 409       archived = maybe_archive_resolved_klass_at(index);
 410       ArchiveBuilder::alloc_stats()->record_klass_cp_entry(archived);
 411       break;
 412     }
 413   }
 414 
 415   if (cache() != NULL) {
 416     // cache() is NULL if this class is not yet linked.
 417     cache()->remove_unshareable_info();
 418   }
 419 }
 420 
 421 bool ConstantPool::maybe_archive_resolved_klass_at(int cp_index) {
 422   assert(ArchiveBuilder::current()->is_in_buffer_space(this), "must be");
 423   assert(tag_at(cp_index).is_klass(), "must be resolved");
 424 
 425   if (pool_holder()->is_hidden() && cp_index == pool_holder()->this_class_index()) {
 426     // All references to a hidden class's own field/methods are through this
 427     // index, which was resolved in ClassFileParser::fill_instance_klass. We
 428     // must preserve it.
 429     return true;
 430   }
 431 
 432   CPKlassSlot kslot = klass_slot_at(cp_index);
 433   int resolved_klass_index = kslot.resolved_klass_index();
 434   Klass* k = resolved_klasses()->at(resolved_klass_index);
 435   // k could be NULL if the referenced class has been excluded via
 436   // SystemDictionaryShared::is_excluded_class().
 437 
 438   if (k != NULL) {
 439     ConstantPool* src_cp = ArchiveBuilder::current()->get_source_addr(this);
 440     if (ClassPrelinker::can_archive_resolved_klass(src_cp, cp_index)) {
 441       if (log_is_enabled(Debug, cds, resolve)) {
 442         ResourceMark rm;
 443         log_debug(cds, resolve)("Resolved klass CP entry [%d]: %s => %s", cp_index,
 444                                 pool_holder()->external_name(), k->external_name());
 445       }
 446       return true;
 447     }
 448   }
 449 
 450   // This referenced class cannot be archived. Revert the tag to UnresolvedClass,
 451   // so that the proper class loading and initialization can happen at runtime.
 452   resolved_klasses()->at_put(resolved_klass_index, NULL);
 453   jbyte qdesc_bit = tag_at(cp_index).is_Qdescriptor_klass() ? (jbyte) JVM_CONSTANT_QDescBit : 0;
 454   tag_at_put(cp_index, JVM_CONSTANT_UnresolvedClass | qdesc_bit);
 455   return false;
 456 }
 457 #endif // INCLUDE_CDS
 458 
 459 int ConstantPool::cp_to_object_index(int cp_index) {
 460   // this is harder don't do this so much.
 461   int i = reference_map()->find(cp_index);
 462   // We might not find the index for jsr292 call.
 463   return (i < 0) ? _no_index_sentinel : i;
 464 }
 465 
 466 void ConstantPool::string_at_put(int which, int obj_index, oop str) {
 467   oop result = set_resolved_reference_at(obj_index, str);
 468   assert(result == nullptr || result == str, "Only set once or to the same string.");
 469 }
 470 
 471 void ConstantPool::trace_class_resolution(const constantPoolHandle& this_cp, Klass* k) {
 472   ResourceMark rm;
 473   int line_number = -1;
 474   const char * source_file = NULL;
 475   if (JavaThread::current()->has_last_Java_frame()) {
 476     // try to identify the method which called this function.
 477     vframeStream vfst(JavaThread::current());
 478     if (!vfst.at_end()) {
 479       line_number = vfst.method()->line_number_from_bci(vfst.bci());
 480       Symbol* s = vfst.method()->method_holder()->source_file_name();
 481       if (s != NULL) {
 482         source_file = s->as_C_string();
 483       }
 484     }
 485   }
 486   if (k != this_cp->pool_holder()) {
 487     // only print something if the classes are different
 488     if (source_file != NULL) {
 489       log_debug(class, resolve)("%s %s %s:%d",
 490                  this_cp->pool_holder()->external_name(),
 491                  k->external_name(), source_file, line_number);
 492     } else {
 493       log_debug(class, resolve)("%s %s",
 494                  this_cp->pool_holder()->external_name(),
 495                  k->external_name());
 496     }
 497   }
 498 }
 499 
 500 void check_is_inline_type(Klass* k, TRAPS) {
 501   if (!k->is_inline_klass()) {
 502     THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
 503   }
 504 }
 505 
 506 Klass* ConstantPool::klass_at_impl(const constantPoolHandle& this_cp, int which,
 507                                    TRAPS) {
 508   JavaThread* javaThread = THREAD;
 509 
 510   // A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.
 511   // It is not safe to rely on the tag bit's here, since we don't have a lock, and
 512   // the entry and tag is not updated atomically.
 513   CPKlassSlot kslot = this_cp->klass_slot_at(which);
 514   int resolved_klass_index = kslot.resolved_klass_index();
 515   int name_index = kslot.name_index();
 516   assert(this_cp->tag_at(name_index).is_symbol(), "sanity");
 517 
 518   // The tag must be JVM_CONSTANT_Class in order to read the correct value from
 519   // the unresolved_klasses() array.
 520   if (this_cp->tag_at(which).is_klass()) {
 521     Klass* klass = this_cp->resolved_klasses()->at(resolved_klass_index);
 522     if (klass != NULL) {
 523       return klass;
 524     }
 525   }
 526 
 527   // This tag doesn't change back to unresolved class unless at a safepoint.
 528   if (this_cp->tag_at(which).is_unresolved_klass_in_error()) {
 529     // The original attempt to resolve this constant pool entry failed so find the
 530     // class of the original error and throw another error of the same class
 531     // (JVMS 5.4.3).
 532     // If there is a detail message, pass that detail message to the error.
 533     // The JVMS does not strictly require us to duplicate the same detail message,
 534     // or any internal exception fields such as cause or stacktrace.  But since the
 535     // detail message is often a class name or other literal string, we will repeat it
 536     // if we can find it in the symbol table.
 537     throw_resolution_error(this_cp, which, CHECK_NULL);
 538     ShouldNotReachHere();
 539   }
 540 
 541   Handle mirror_handle;
 542   Symbol* name = this_cp->symbol_at(name_index);
 543   bool inline_type_signature = false;
 544   if (name->is_Q_signature()) {
 545     name = name->fundamental_name(THREAD);
 546     inline_type_signature = true;
 547   }
 548   Handle loader (THREAD, this_cp->pool_holder()->class_loader());
 549   Handle protection_domain (THREAD, this_cp->pool_holder()->protection_domain());
 550 
 551   Klass* k;
 552   {
 553     // Turn off the single stepping while doing class resolution
 554     JvmtiHideSingleStepping jhss(javaThread);
 555     k = SystemDictionary::resolve_or_fail(name, loader, protection_domain, true, THREAD);
 556   } //  JvmtiHideSingleStepping jhss(javaThread);
 557   if (inline_type_signature) {
 558     name->decrement_refcount();
 559   }
 560 
 561   if (!HAS_PENDING_EXCEPTION) {
 562     // preserve the resolved klass from unloading
 563     mirror_handle = Handle(THREAD, k->java_mirror());
 564     // Do access check for klasses
 565     verify_constant_pool_resolve(this_cp, k, THREAD);
 566   }
 567 
 568   if (!HAS_PENDING_EXCEPTION && inline_type_signature) {
 569     check_is_inline_type(k, THREAD);
 570   }
 571 
 572   if (!HAS_PENDING_EXCEPTION) {
 573     Klass* bottom_klass = NULL;
 574     if (k->is_objArray_klass()) {
 575       bottom_klass = ObjArrayKlass::cast(k)->bottom_klass();
 576       assert(bottom_klass != NULL, "Should be set");
 577       assert(bottom_klass->is_instance_klass() || bottom_klass->is_typeArray_klass(), "Sanity check");
 578     } else if (k->is_flatArray_klass()) {
 579       bottom_klass = FlatArrayKlass::cast(k)->element_klass();
 580       assert(bottom_klass != NULL, "Should be set");
 581     }
 582   }
 583 
 584   // Failed to resolve class. We must record the errors so that subsequent attempts
 585   // to resolve this constant pool entry fail with the same error (JVMS 5.4.3).
 586   if (HAS_PENDING_EXCEPTION) {
 587     jbyte tag = JVM_CONSTANT_UnresolvedClass;
 588     if (this_cp->tag_at(which).is_Qdescriptor_klass()) {
 589       tag |= JVM_CONSTANT_QDescBit;
 590     }
 591     save_and_throw_exception(this_cp, which, constantTag(tag), CHECK_NULL);
 592     // If CHECK_NULL above doesn't return the exception, that means that
 593     // some other thread has beaten us and has resolved the class.
 594     // To preserve old behavior, we return the resolved class.
 595     Klass* klass = this_cp->resolved_klasses()->at(resolved_klass_index);
 596     assert(klass != NULL, "must be resolved if exception was cleared");
 597     return klass;
 598   }
 599 
 600   // logging for class+resolve.
 601   if (log_is_enabled(Debug, class, resolve)){
 602     trace_class_resolution(this_cp, k);
 603   }
 604 
 605   Klass** adr = this_cp->resolved_klasses()->adr_at(resolved_klass_index);
 606   Atomic::release_store(adr, k);
 607   // The interpreter assumes when the tag is stored, the klass is resolved
 608   // and the Klass* stored in _resolved_klasses is non-NULL, so we need
 609   // hardware store ordering here.
 610   jbyte tag = JVM_CONSTANT_Class;
 611   if (this_cp->tag_at(which).is_Qdescriptor_klass()) {
 612     tag |= JVM_CONSTANT_QDescBit;
 613   }
 614   // We also need to CAS to not overwrite an error from a racing thread.
 615 
 616   jbyte old_tag = Atomic::cmpxchg((jbyte*)this_cp->tag_addr_at(which),
 617                                   (jbyte)JVM_CONSTANT_UnresolvedClass,
 618                                   tag);
 619 
 620   // We need to recheck exceptions from racing thread and return the same.
 621   if (old_tag == JVM_CONSTANT_UnresolvedClassInError) {
 622     // Remove klass.
 623     this_cp->resolved_klasses()->at_put(resolved_klass_index, NULL);
 624     throw_resolution_error(this_cp, which, CHECK_NULL);
 625   }
 626 
 627   return k;
 628 }
 629 
 630 
 631 // Does not update ConstantPool* - to avoid any exception throwing. Used
 632 // by compiler and exception handling.  Also used to avoid classloads for
 633 // instanceof operations. Returns NULL if the class has not been loaded or
 634 // if the verification of constant pool failed
 635 Klass* ConstantPool::klass_at_if_loaded(const constantPoolHandle& this_cp, int which) {
 636   CPKlassSlot kslot = this_cp->klass_slot_at(which);
 637   int resolved_klass_index = kslot.resolved_klass_index();
 638   int name_index = kslot.name_index();
 639   assert(this_cp->tag_at(name_index).is_symbol(), "sanity");
 640 
 641   if (this_cp->tag_at(which).is_klass()) {
 642     Klass* k = this_cp->resolved_klasses()->at(resolved_klass_index);
 643     assert(k != NULL, "should be resolved");
 644     return k;
 645   } else if (this_cp->tag_at(which).is_unresolved_klass_in_error()) {
 646     return NULL;
 647   } else {
 648     Thread* current = Thread::current();
 649     Symbol* name = this_cp->symbol_at(name_index);
 650     oop loader = this_cp->pool_holder()->class_loader();
 651     oop protection_domain = this_cp->pool_holder()->protection_domain();
 652     Handle h_prot (current, protection_domain);
 653     Handle h_loader (current, loader);
 654     Klass* k = SystemDictionary::find_instance_klass(current, name, h_loader, h_prot);
 655 
 656     // Avoid constant pool verification at a safepoint, as it takes the Module_lock.
 657     if (k != NULL && current->is_Java_thread()) {
 658       // Make sure that resolving is legal
 659       JavaThread* THREAD = JavaThread::cast(current); // For exception macros.
 660       ExceptionMark em(THREAD);
 661       // return NULL if verification fails
 662       verify_constant_pool_resolve(this_cp, k, THREAD);
 663       if (HAS_PENDING_EXCEPTION) {
 664         CLEAR_PENDING_EXCEPTION;
 665         return NULL;
 666       }
 667       return k;
 668     } else {
 669       return k;
 670     }
 671   }
 672 }
 673 
 674 Method* ConstantPool::method_at_if_loaded(const constantPoolHandle& cpool,
 675                                                    int which) {
 676   if (cpool->cache() == NULL)  return NULL;  // nothing to load yet
 677   int cache_index = decode_cpcache_index(which, true);
 678   if (!(cache_index >= 0 && cache_index < cpool->cache()->length())) {
 679     // FIXME: should be an assert
 680     log_debug(class, resolve)("bad operand %d in:", which); cpool->print();
 681     return NULL;
 682   }
 683   ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
 684   return e->method_if_resolved(cpool);
 685 }
 686 
 687 
 688 bool ConstantPool::has_appendix_at_if_loaded(const constantPoolHandle& cpool, int which) {
 689   if (cpool->cache() == NULL)  return false;  // nothing to load yet
 690   int cache_index = decode_cpcache_index(which, true);
 691   ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
 692   return e->has_appendix();
 693 }
 694 
 695 oop ConstantPool::appendix_at_if_loaded(const constantPoolHandle& cpool, int which) {
 696   if (cpool->cache() == NULL)  return NULL;  // nothing to load yet
 697   int cache_index = decode_cpcache_index(which, true);
 698   ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
 699   return e->appendix_if_resolved(cpool);
 700 }
 701 
 702 
 703 bool ConstantPool::has_local_signature_at_if_loaded(const constantPoolHandle& cpool, int which) {
 704   if (cpool->cache() == NULL)  return false;  // nothing to load yet
 705   int cache_index = decode_cpcache_index(which, true);
 706   ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
 707   return e->has_local_signature();
 708 }
 709 
 710 Symbol* ConstantPool::impl_name_ref_at(int which, bool uncached) {
 711   int name_index = name_ref_index_at(impl_name_and_type_ref_index_at(which, uncached));
 712   return symbol_at(name_index);
 713 }
 714 
 715 
 716 Symbol* ConstantPool::impl_signature_ref_at(int which, bool uncached) {
 717   int signature_index = signature_ref_index_at(impl_name_and_type_ref_index_at(which, uncached));
 718   return symbol_at(signature_index);
 719 }
 720 
 721 int ConstantPool::impl_name_and_type_ref_index_at(int which, bool uncached) {
 722   int i = which;
 723   if (!uncached && cache() != NULL) {
 724     if (ConstantPool::is_invokedynamic_index(which)) {
 725       // Invokedynamic index is index into the constant pool cache
 726       int pool_index = invokedynamic_bootstrap_ref_index_at(which);
 727       pool_index = bootstrap_name_and_type_ref_index_at(pool_index);
 728       assert(tag_at(pool_index).is_name_and_type(), "");
 729       return pool_index;
 730     }
 731     // change byte-ordering and go via cache
 732     i = remap_instruction_operand_from_cache(which);
 733   } else {
 734     if (tag_at(which).has_bootstrap()) {
 735       int pool_index = bootstrap_name_and_type_ref_index_at(which);
 736       assert(tag_at(pool_index).is_name_and_type(), "");
 737       return pool_index;
 738     }
 739   }
 740   assert(tag_at(i).is_field_or_method(), "Corrupted constant pool");
 741   assert(!tag_at(i).has_bootstrap(), "Must be handled above");
 742   jint ref_index = *int_at_addr(i);
 743   return extract_high_short_from_int(ref_index);
 744 }
 745 
 746 constantTag ConstantPool::impl_tag_ref_at(int which, bool uncached) {
 747   int pool_index = which;
 748   if (!uncached && cache() != NULL) {
 749     if (ConstantPool::is_invokedynamic_index(which)) {
 750       // Invokedynamic index is index into resolved_references
 751       pool_index = invokedynamic_bootstrap_ref_index_at(which);
 752     } else {
 753       // change byte-ordering and go via cache
 754       pool_index = remap_instruction_operand_from_cache(which);
 755     }
 756   }
 757   return tag_at(pool_index);
 758 }
 759 
 760 int ConstantPool::impl_klass_ref_index_at(int which, bool uncached) {
 761   guarantee(!ConstantPool::is_invokedynamic_index(which),
 762             "an invokedynamic instruction does not have a klass");
 763   int i = which;
 764   if (!uncached && cache() != NULL) {
 765     // change byte-ordering and go via cache
 766     i = remap_instruction_operand_from_cache(which);
 767   }
 768   assert(tag_at(i).is_field_or_method(), "Corrupted constant pool");
 769   jint ref_index = *int_at_addr(i);
 770   return extract_low_short_from_int(ref_index);
 771 }
 772 
 773 
 774 
 775 int ConstantPool::remap_instruction_operand_from_cache(int operand) {
 776   int cpc_index = operand;
 777   DEBUG_ONLY(cpc_index -= CPCACHE_INDEX_TAG);
 778   assert((int)(u2)cpc_index == cpc_index, "clean u2");
 779   int member_index = cache()->entry_at(cpc_index)->constant_pool_index();
 780   return member_index;
 781 }
 782 
 783 
 784 void ConstantPool::verify_constant_pool_resolve(const constantPoolHandle& this_cp, Klass* k, TRAPS) {
 785   if (!(k->is_instance_klass() || k->is_objArray_klass())) {
 786     return;  // short cut, typeArray klass is always accessible
 787   }
 788   Klass* holder = this_cp->pool_holder();
 789   LinkResolver::check_klass_accessibility(holder, k, CHECK);
 790 }
 791 
 792 
 793 int ConstantPool::name_ref_index_at(int which_nt) {
 794   jint ref_index = name_and_type_at(which_nt);
 795   return extract_low_short_from_int(ref_index);
 796 }
 797 
 798 
 799 int ConstantPool::signature_ref_index_at(int which_nt) {
 800   jint ref_index = name_and_type_at(which_nt);
 801   return extract_high_short_from_int(ref_index);
 802 }
 803 
 804 
 805 Klass* ConstantPool::klass_ref_at(int which, TRAPS) {
 806   return klass_at(klass_ref_index_at(which), THREAD);
 807 }
 808 
 809 Symbol* ConstantPool::klass_name_at(int which) const {
 810   return symbol_at(klass_slot_at(which).name_index());
 811 }
 812 
 813 Symbol* ConstantPool::klass_ref_at_noresolve(int which) {
 814   jint ref_index = klass_ref_index_at(which);
 815   return klass_at_noresolve(ref_index);
 816 }
 817 
 818 Symbol* ConstantPool::uncached_klass_ref_at_noresolve(int which) {
 819   jint ref_index = uncached_klass_ref_index_at(which);
 820   return klass_at_noresolve(ref_index);
 821 }
 822 
 823 char* ConstantPool::string_at_noresolve(int which) {
 824   return unresolved_string_at(which)->as_C_string();
 825 }
 826 
 827 BasicType ConstantPool::basic_type_for_signature_at(int which) const {
 828   return Signature::basic_type(symbol_at(which));
 829 }
 830 
 831 
 832 void ConstantPool::resolve_string_constants_impl(const constantPoolHandle& this_cp, TRAPS) {
 833   for (int index = 1; index < this_cp->length(); index++) { // Index 0 is unused
 834     if (this_cp->tag_at(index).is_string()) {
 835       this_cp->string_at(index, CHECK);
 836     }
 837   }
 838 }
 839 
 840 static Symbol* exception_message(const constantPoolHandle& this_cp, int which, constantTag tag, oop pending_exception) {
 841   // Dig out the detailed message to reuse if possible
 842   Symbol* message = java_lang_Throwable::detail_message(pending_exception);
 843   if (message != NULL) {
 844     return message;
 845   }
 846 
 847   // Return specific message for the tag
 848   switch (tag.value()) {
 849   case JVM_CONSTANT_UnresolvedClass:
 850     // return the class name in the error message
 851     message = this_cp->klass_name_at(which);
 852     break;
 853   case JVM_CONSTANT_MethodHandle:
 854     // return the method handle name in the error message
 855     message = this_cp->method_handle_name_ref_at(which);
 856     break;
 857   case JVM_CONSTANT_MethodType:
 858     // return the method type signature in the error message
 859     message = this_cp->method_type_signature_at(which);
 860     break;
 861   case JVM_CONSTANT_Dynamic:
 862     // return the name of the condy in the error message
 863     message = this_cp->uncached_name_ref_at(which);
 864     break;
 865   default:
 866     ShouldNotReachHere();
 867   }
 868 
 869   return message;
 870 }
 871 
 872 static void add_resolution_error(const constantPoolHandle& this_cp, int which,
 873                                  constantTag tag, oop pending_exception) {
 874 
 875   Symbol* error = pending_exception->klass()->name();
 876   oop cause = java_lang_Throwable::cause(pending_exception);
 877 
 878   // Also dig out the exception cause, if present.
 879   Symbol* cause_sym = NULL;
 880   Symbol* cause_msg = NULL;
 881   if (cause != NULL && cause != pending_exception) {
 882     cause_sym = cause->klass()->name();
 883     cause_msg = java_lang_Throwable::detail_message(cause);
 884   }
 885 
 886   Symbol* message = exception_message(this_cp, which, tag, pending_exception);
 887   SystemDictionary::add_resolution_error(this_cp, which, error, message, cause_sym, cause_msg);
 888 }
 889 
 890 
 891 void ConstantPool::throw_resolution_error(const constantPoolHandle& this_cp, int which, TRAPS) {
 892   ResourceMark rm(THREAD);
 893   Symbol* message = NULL;
 894   Symbol* cause = NULL;
 895   Symbol* cause_msg = NULL;
 896   Symbol* error = SystemDictionary::find_resolution_error(this_cp, which, &message, &cause, &cause_msg);
 897   assert(error != NULL, "checking");
 898   const char* cause_str = cause_msg != NULL ? cause_msg->as_C_string() : NULL;
 899 
 900   CLEAR_PENDING_EXCEPTION;
 901   if (message != NULL) {
 902     char* msg = message->as_C_string();
 903     if (cause != NULL) {
 904       Handle h_cause = Exceptions::new_exception(THREAD, cause, cause_str);
 905       THROW_MSG_CAUSE(error, msg, h_cause);
 906     } else {
 907       THROW_MSG(error, msg);
 908     }
 909   } else {
 910     if (cause != NULL) {
 911       Handle h_cause = Exceptions::new_exception(THREAD, cause, cause_str);
 912       THROW_CAUSE(error, h_cause);
 913     } else {
 914       THROW(error);
 915     }
 916   }
 917 }
 918 
 919 // If resolution for Class, Dynamic constant, MethodHandle or MethodType fails, save the
 920 // exception in the resolution error table, so that the same exception is thrown again.
 921 void ConstantPool::save_and_throw_exception(const constantPoolHandle& this_cp, int which,
 922                                             constantTag tag, TRAPS) {
 923 
 924   int error_tag = tag.error_value();
 925 
 926   if (!PENDING_EXCEPTION->
 927     is_a(vmClasses::LinkageError_klass())) {
 928     // Just throw the exception and don't prevent these classes from
 929     // being loaded due to virtual machine errors like StackOverflow
 930     // and OutOfMemoryError, etc, or if the thread was hit by stop()
 931     // Needs clarification to section 5.4.3 of the VM spec (see 6308271)
 932   } else if (this_cp->tag_at(which).value() != error_tag) {
 933     add_resolution_error(this_cp, which, tag, PENDING_EXCEPTION);
 934     // CAS in the tag.  If a thread beat us to registering this error that's fine.
 935     // If another thread resolved the reference, this is a race condition. This
 936     // thread may have had a security manager or something temporary.
 937     // This doesn't deterministically get an error.   So why do we save this?
 938     // We save this because jvmti can add classes to the bootclass path after
 939     // this error, so it needs to get the same error if the error is first.
 940     jbyte old_tag = Atomic::cmpxchg((jbyte*)this_cp->tag_addr_at(which),
 941                                     (jbyte)tag.value(),
 942                                     (jbyte)error_tag);
 943     if (old_tag != error_tag && old_tag != tag.value()) {
 944       // MethodHandles and MethodType doesn't change to resolved version.
 945       assert(this_cp->tag_at(which).is_klass(), "Wrong tag value");
 946       // Forget the exception and use the resolved class.
 947       CLEAR_PENDING_EXCEPTION;
 948     }
 949   } else {
 950     // some other thread put this in error state
 951     throw_resolution_error(this_cp, which, CHECK);
 952   }
 953 }
 954 
 955 constantTag ConstantPool::constant_tag_at(int which) {
 956   constantTag tag = tag_at(which);
 957   if (tag.is_dynamic_constant()) {
 958     BasicType bt = basic_type_for_constant_at(which);
 959     return constantTag(constantTag::type2tag(bt));
 960   }
 961   return tag;
 962 }
 963 
 964 BasicType ConstantPool::basic_type_for_constant_at(int which) {
 965   constantTag tag = tag_at(which);
 966   if (tag.is_dynamic_constant() ||
 967       tag.is_dynamic_constant_in_error()) {
 968     // have to look at the signature for this one
 969     Symbol* constant_type = uncached_signature_ref_at(which);
 970     return Signature::basic_type(constant_type);
 971   }
 972   return tag.basic_type();
 973 }
 974 
 975 // Called to resolve constants in the constant pool and return an oop.
 976 // Some constant pool entries cache their resolved oop. This is also
 977 // called to create oops from constants to use in arguments for invokedynamic
 978 oop ConstantPool::resolve_constant_at_impl(const constantPoolHandle& this_cp,
 979                                            int index, int cache_index,
 980                                            bool* status_return, TRAPS) {
 981   oop result_oop = NULL;
 982   Handle throw_exception;
 983 
 984   if (cache_index == _possible_index_sentinel) {
 985     // It is possible that this constant is one which is cached in the objects.
 986     // We'll do a linear search.  This should be OK because this usage is rare.
 987     // FIXME: If bootstrap specifiers stress this code, consider putting in
 988     // a reverse index.  Binary search over a short array should do it.
 989     assert(index > 0, "valid index");
 990     cache_index = this_cp->cp_to_object_index(index);
 991   }
 992   assert(cache_index == _no_index_sentinel || cache_index >= 0, "");
 993   assert(index == _no_index_sentinel || index >= 0, "");
 994 
 995   if (cache_index >= 0) {
 996     result_oop = this_cp->resolved_reference_at(cache_index);
 997     if (result_oop != NULL) {
 998       if (result_oop == Universe::the_null_sentinel()) {
 999         DEBUG_ONLY(int temp_index = (index >= 0 ? index : this_cp->object_to_cp_index(cache_index)));
1000         assert(this_cp->tag_at(temp_index).is_dynamic_constant(), "only condy uses the null sentinel");
1001         result_oop = NULL;
1002       }
1003       if (status_return != NULL)  (*status_return) = true;
1004       return result_oop;
1005       // That was easy...
1006     }
1007     index = this_cp->object_to_cp_index(cache_index);
1008   }
1009 
1010   jvalue prim_value;  // temp used only in a few cases below
1011 
1012   constantTag tag = this_cp->tag_at(index);
1013 
1014   if (status_return != NULL) {
1015     // don't trigger resolution if the constant might need it
1016     switch (tag.value()) {
1017     case JVM_CONSTANT_Class:
1018     {
1019       CPKlassSlot kslot = this_cp->klass_slot_at(index);
1020       int resolved_klass_index = kslot.resolved_klass_index();
1021       if (this_cp->resolved_klasses()->at(resolved_klass_index) == NULL) {
1022         (*status_return) = false;
1023         return NULL;
1024       }
1025       // the klass is waiting in the CP; go get it
1026       break;
1027     }
1028     case JVM_CONSTANT_String:
1029     case JVM_CONSTANT_Integer:
1030     case JVM_CONSTANT_Float:
1031     case JVM_CONSTANT_Long:
1032     case JVM_CONSTANT_Double:
1033       // these guys trigger OOM at worst
1034       break;
1035     default:
1036       (*status_return) = false;
1037       return NULL;
1038     }
1039     // from now on there is either success or an OOME
1040     (*status_return) = true;
1041   }
1042 
1043   switch (tag.value()) {
1044 
1045   case JVM_CONSTANT_UnresolvedClass:
1046   case JVM_CONSTANT_Class:
1047     {
1048       assert(cache_index == _no_index_sentinel, "should not have been set");
1049       Klass* resolved = klass_at_impl(this_cp, index, CHECK_NULL);
1050       // ldc wants the java mirror.
1051       result_oop = tag.is_Qdescriptor_klass()
1052                       ? InlineKlass::cast(resolved)->val_mirror()
1053                       : resolved->java_mirror();
1054       break;
1055     }
1056 
1057   case JVM_CONSTANT_Dynamic:
1058     {
1059       // Resolve the Dynamically-Computed constant to invoke the BSM in order to obtain the resulting oop.
1060       BootstrapInfo bootstrap_specifier(this_cp, index);
1061 
1062       // The initial step in resolving an unresolved symbolic reference to a
1063       // dynamically-computed constant is to resolve the symbolic reference to a
1064       // method handle which will be the bootstrap method for the dynamically-computed
1065       // constant. If resolution of the java.lang.invoke.MethodHandle for the bootstrap
1066       // method fails, then a MethodHandleInError is stored at the corresponding
1067       // bootstrap method's CP index for the CONSTANT_MethodHandle_info. No need to
1068       // set a DynamicConstantInError here since any subsequent use of this
1069       // bootstrap method will encounter the resolution of MethodHandleInError.
1070       // Both the first, (resolution of the BSM and its static arguments), and the second tasks,
1071       // (invocation of the BSM), of JVMS Section 5.4.3.6 occur within invoke_bootstrap_method()
1072       // for the bootstrap_specifier created above.
1073       SystemDictionary::invoke_bootstrap_method(bootstrap_specifier, THREAD);
1074       Exceptions::wrap_dynamic_exception(/* is_indy */ false, THREAD);
1075       if (HAS_PENDING_EXCEPTION) {
1076         // Resolution failure of the dynamically-computed constant, save_and_throw_exception
1077         // will check for a LinkageError and store a DynamicConstantInError.
1078         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1079       }
1080       result_oop = bootstrap_specifier.resolved_value()();
1081       BasicType type = Signature::basic_type(bootstrap_specifier.signature());
1082       if (!is_reference_type(type)) {
1083         // Make sure the primitive value is properly boxed.
1084         // This is a JDK responsibility.
1085         const char* fail = NULL;
1086         if (result_oop == NULL) {
1087           fail = "null result instead of box";
1088         } else if (!is_java_primitive(type)) {
1089           // FIXME: support value types via unboxing
1090           fail = "can only handle references and primitives";
1091         } else if (!java_lang_boxing_object::is_instance(result_oop, type)) {
1092           fail = "primitive is not properly boxed";
1093         }
1094         if (fail != NULL) {
1095           // Since this exception is not a LinkageError, throw exception
1096           // but do not save a DynamicInError resolution result.
1097           // See section 5.4.3 of the VM spec.
1098           THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), fail);
1099         }
1100       }
1101 
1102       LogTarget(Debug, methodhandles, condy) lt_condy;
1103       if (lt_condy.is_enabled()) {
1104         LogStream ls(lt_condy);
1105         bootstrap_specifier.print_msg_on(&ls, "resolve_constant_at_impl");
1106       }
1107       break;
1108     }
1109 
1110   case JVM_CONSTANT_String:
1111     assert(cache_index != _no_index_sentinel, "should have been set");
1112     result_oop = string_at_impl(this_cp, index, cache_index, CHECK_NULL);
1113     break;
1114 
1115   case JVM_CONSTANT_MethodHandle:
1116     {
1117       int ref_kind                 = this_cp->method_handle_ref_kind_at(index);
1118       int callee_index             = this_cp->method_handle_klass_index_at(index);
1119       Symbol*  name =      this_cp->method_handle_name_ref_at(index);
1120       Symbol*  signature = this_cp->method_handle_signature_ref_at(index);
1121       constantTag m_tag  = this_cp->tag_at(this_cp->method_handle_index_at(index));
1122       { ResourceMark rm(THREAD);
1123         log_debug(class, resolve)("resolve JVM_CONSTANT_MethodHandle:%d [%d/%d/%d] %s.%s",
1124                               ref_kind, index, this_cp->method_handle_index_at(index),
1125                               callee_index, name->as_C_string(), signature->as_C_string());
1126       }
1127 
1128       Klass* callee = klass_at_impl(this_cp, callee_index, THREAD);
1129       if (HAS_PENDING_EXCEPTION) {
1130         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1131       }
1132 
1133       // Check constant pool method consistency
1134       if ((callee->is_interface() && m_tag.is_method()) ||
1135           (!callee->is_interface() && m_tag.is_interface_method())) {
1136         ResourceMark rm(THREAD);
1137         stringStream ss;
1138         ss.print("Inconsistent constant pool data in classfile for class %s. "
1139                  "Method '", callee->name()->as_C_string());
1140         signature->print_as_signature_external_return_type(&ss);
1141         ss.print(" %s(", name->as_C_string());
1142         signature->print_as_signature_external_parameters(&ss);
1143         ss.print(")' at index %d is %s and should be %s",
1144                  index,
1145                  callee->is_interface() ? "CONSTANT_MethodRef" : "CONSTANT_InterfaceMethodRef",
1146                  callee->is_interface() ? "CONSTANT_InterfaceMethodRef" : "CONSTANT_MethodRef");
1147         Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IncompatibleClassChangeError(), "%s", ss.as_string());
1148         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1149       }
1150 
1151       Klass* klass = this_cp->pool_holder();
1152       Handle value = SystemDictionary::link_method_handle_constant(klass, ref_kind,
1153                                                                    callee, name, signature,
1154                                                                    THREAD);
1155       if (HAS_PENDING_EXCEPTION) {
1156         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1157       }
1158       result_oop = value();
1159       break;
1160     }
1161 
1162   case JVM_CONSTANT_MethodType:
1163     {
1164       Symbol*  signature = this_cp->method_type_signature_at(index);
1165       { ResourceMark rm(THREAD);
1166         log_debug(class, resolve)("resolve JVM_CONSTANT_MethodType [%d/%d] %s",
1167                               index, this_cp->method_type_index_at(index),
1168                               signature->as_C_string());
1169       }
1170       Klass* klass = this_cp->pool_holder();
1171       Handle value = SystemDictionary::find_method_handle_type(signature, klass, THREAD);
1172       result_oop = value();
1173       if (HAS_PENDING_EXCEPTION) {
1174         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1175       }
1176       break;
1177     }
1178 
1179   case JVM_CONSTANT_Integer:
1180     assert(cache_index == _no_index_sentinel, "should not have been set");
1181     prim_value.i = this_cp->int_at(index);
1182     result_oop = java_lang_boxing_object::create(T_INT, &prim_value, CHECK_NULL);
1183     break;
1184 
1185   case JVM_CONSTANT_Float:
1186     assert(cache_index == _no_index_sentinel, "should not have been set");
1187     prim_value.f = this_cp->float_at(index);
1188     result_oop = java_lang_boxing_object::create(T_FLOAT, &prim_value, CHECK_NULL);
1189     break;
1190 
1191   case JVM_CONSTANT_Long:
1192     assert(cache_index == _no_index_sentinel, "should not have been set");
1193     prim_value.j = this_cp->long_at(index);
1194     result_oop = java_lang_boxing_object::create(T_LONG, &prim_value, CHECK_NULL);
1195     break;
1196 
1197   case JVM_CONSTANT_Double:
1198     assert(cache_index == _no_index_sentinel, "should not have been set");
1199     prim_value.d = this_cp->double_at(index);
1200     result_oop = java_lang_boxing_object::create(T_DOUBLE, &prim_value, CHECK_NULL);
1201     break;
1202 
1203   case JVM_CONSTANT_UnresolvedClassInError:
1204   case JVM_CONSTANT_DynamicInError:
1205   case JVM_CONSTANT_MethodHandleInError:
1206   case JVM_CONSTANT_MethodTypeInError:
1207     throw_resolution_error(this_cp, index, CHECK_NULL);
1208     break;
1209 
1210   default:
1211     fatal("unexpected constant tag at CP %p[%d/%d] = %d", this_cp(), index, cache_index, tag.value());
1212     break;
1213   }
1214 
1215   if (cache_index >= 0) {
1216     // Benign race condition:  resolved_references may already be filled in.
1217     // The important thing here is that all threads pick up the same result.
1218     // It doesn't matter which racing thread wins, as long as only one
1219     // result is used by all threads, and all future queries.
1220     oop new_result = (result_oop == NULL ? Universe::the_null_sentinel() : result_oop);
1221     oop old_result = this_cp->set_resolved_reference_at(cache_index, new_result);
1222     if (old_result == nullptr) {
1223       return result_oop;  // was installed
1224     } else {
1225       // Return the winning thread's result.  This can be different than
1226       // the result here for MethodHandles.
1227       if (old_result == Universe::the_null_sentinel())
1228         old_result = NULL;
1229       return old_result;
1230     }
1231   } else {
1232     assert(result_oop != Universe::the_null_sentinel(), "");
1233     return result_oop;
1234   }
1235 }
1236 
1237 oop ConstantPool::uncached_string_at(int which, TRAPS) {
1238   Symbol* sym = unresolved_string_at(which);
1239   oop str = StringTable::intern(sym, CHECK_(NULL));
1240   assert(java_lang_String::is_instance(str), "must be string");
1241   return str;
1242 }
1243 
1244 void ConstantPool::copy_bootstrap_arguments_at_impl(const constantPoolHandle& this_cp, int index,
1245                                                     int start_arg, int end_arg,
1246                                                     objArrayHandle info, int pos,
1247                                                     bool must_resolve, Handle if_not_available,
1248                                                     TRAPS) {
1249   int limit = pos + end_arg - start_arg;
1250   // checks: index in range [0..this_cp->length),
1251   // tag at index, start..end in range [0..this_cp->bootstrap_argument_count],
1252   // info array non-null, pos..limit in [0..info.length]
1253   if ((0 >= index    || index >= this_cp->length())  ||
1254       !(this_cp->tag_at(index).is_invoke_dynamic()    ||
1255         this_cp->tag_at(index).is_dynamic_constant()) ||
1256       (0 > start_arg || start_arg > end_arg) ||
1257       (end_arg > this_cp->bootstrap_argument_count_at(index)) ||
1258       (0 > pos       || pos > limit)         ||
1259       (info.is_null() || limit > info->length())) {
1260     // An index or something else went wrong; throw an error.
1261     // Since this is an internal API, we don't expect this,
1262     // so we don't bother to craft a nice message.
1263     THROW_MSG(vmSymbols::java_lang_LinkageError(), "bad BSM argument access");
1264   }
1265   // now we can loop safely
1266   int info_i = pos;
1267   for (int i = start_arg; i < end_arg; i++) {
1268     int arg_index = this_cp->bootstrap_argument_index_at(index, i);
1269     oop arg_oop;
1270     if (must_resolve) {
1271       arg_oop = this_cp->resolve_possibly_cached_constant_at(arg_index, CHECK);
1272     } else {
1273       bool found_it = false;
1274       arg_oop = this_cp->find_cached_constant_at(arg_index, found_it, CHECK);
1275       if (!found_it)  arg_oop = if_not_available();
1276     }
1277     info->obj_at_put(info_i++, arg_oop);
1278   }
1279 }
1280 
1281 oop ConstantPool::string_at_impl(const constantPoolHandle& this_cp, int which, int obj_index, TRAPS) {
1282   // If the string has already been interned, this entry will be non-null
1283   oop str = this_cp->resolved_reference_at(obj_index);
1284   assert(str != Universe::the_null_sentinel(), "");
1285   if (str != NULL) return str;
1286   Symbol* sym = this_cp->unresolved_string_at(which);
1287   str = StringTable::intern(sym, CHECK_(NULL));
1288   this_cp->string_at_put(which, obj_index, str);
1289   assert(java_lang_String::is_instance(str), "must be string");
1290   return str;
1291 }
1292 
1293 
1294 bool ConstantPool::klass_name_at_matches(const InstanceKlass* k, int which) {
1295   // Names are interned, so we can compare Symbol*s directly
1296   Symbol* cp_name = klass_name_at(which);
1297   return (cp_name == k->name());
1298 }
1299 
1300 
1301 // Iterate over symbols and decrement ones which are Symbol*s
1302 // This is done during GC.
1303 // Only decrement the UTF8 symbols. Strings point to
1304 // these symbols but didn't increment the reference count.
1305 void ConstantPool::unreference_symbols() {
1306   for (int index = 1; index < length(); index++) { // Index 0 is unused
1307     constantTag tag = tag_at(index);
1308     if (tag.is_symbol()) {
1309       symbol_at(index)->decrement_refcount();
1310     }
1311   }
1312 }
1313 
1314 
1315 // Compare this constant pool's entry at index1 to the constant pool
1316 // cp2's entry at index2.
1317 bool ConstantPool::compare_entry_to(int index1, const constantPoolHandle& cp2,
1318        int index2) {
1319 
1320   // The error tags are equivalent to non-error tags when comparing
1321   jbyte t1 = tag_at(index1).non_error_value();
1322   jbyte t2 = cp2->tag_at(index2).non_error_value();
1323 
1324   if (t1 != t2) {
1325     // Not the same entry type so there is nothing else to check. Note
1326     // that this style of checking will consider resolved/unresolved
1327     // class pairs as different.
1328     // From the ConstantPool* API point of view, this is correct
1329     // behavior. See VM_RedefineClasses::merge_constant_pools() to see how this
1330     // plays out in the context of ConstantPool* merging.
1331     return false;
1332   }
1333 
1334   switch (t1) {
1335   case JVM_CONSTANT_Class:
1336   {
1337     Klass* k1 = resolved_klass_at(index1);
1338     Klass* k2 = cp2->resolved_klass_at(index2);
1339     if (k1 == k2) {
1340       return true;
1341     }
1342   } break;
1343 
1344   case JVM_CONSTANT_ClassIndex:
1345   {
1346     int recur1 = klass_index_at(index1);
1347     int recur2 = cp2->klass_index_at(index2);
1348     if (compare_entry_to(recur1, cp2, recur2)) {
1349       return true;
1350     }
1351   } break;
1352 
1353   case JVM_CONSTANT_Double:
1354   {
1355     jdouble d1 = double_at(index1);
1356     jdouble d2 = cp2->double_at(index2);
1357     if (d1 == d2) {
1358       return true;
1359     }
1360   } break;
1361 
1362   case JVM_CONSTANT_Fieldref:
1363   case JVM_CONSTANT_InterfaceMethodref:
1364   case JVM_CONSTANT_Methodref:
1365   {
1366     int recur1 = uncached_klass_ref_index_at(index1);
1367     int recur2 = cp2->uncached_klass_ref_index_at(index2);
1368     bool match = compare_entry_to(recur1, cp2, recur2);
1369     if (match) {
1370       recur1 = uncached_name_and_type_ref_index_at(index1);
1371       recur2 = cp2->uncached_name_and_type_ref_index_at(index2);
1372       if (compare_entry_to(recur1, cp2, recur2)) {
1373         return true;
1374       }
1375     }
1376   } break;
1377 
1378   case JVM_CONSTANT_Float:
1379   {
1380     jfloat f1 = float_at(index1);
1381     jfloat f2 = cp2->float_at(index2);
1382     if (f1 == f2) {
1383       return true;
1384     }
1385   } break;
1386 
1387   case JVM_CONSTANT_Integer:
1388   {
1389     jint i1 = int_at(index1);
1390     jint i2 = cp2->int_at(index2);
1391     if (i1 == i2) {
1392       return true;
1393     }
1394   } break;
1395 
1396   case JVM_CONSTANT_Long:
1397   {
1398     jlong l1 = long_at(index1);
1399     jlong l2 = cp2->long_at(index2);
1400     if (l1 == l2) {
1401       return true;
1402     }
1403   } break;
1404 
1405   case JVM_CONSTANT_NameAndType:
1406   {
1407     int recur1 = name_ref_index_at(index1);
1408     int recur2 = cp2->name_ref_index_at(index2);
1409     if (compare_entry_to(recur1, cp2, recur2)) {
1410       recur1 = signature_ref_index_at(index1);
1411       recur2 = cp2->signature_ref_index_at(index2);
1412       if (compare_entry_to(recur1, cp2, recur2)) {
1413         return true;
1414       }
1415     }
1416   } break;
1417 
1418   case JVM_CONSTANT_StringIndex:
1419   {
1420     int recur1 = string_index_at(index1);
1421     int recur2 = cp2->string_index_at(index2);
1422     if (compare_entry_to(recur1, cp2, recur2)) {
1423       return true;
1424     }
1425   } break;
1426 
1427   case JVM_CONSTANT_UnresolvedClass:
1428   {
1429     Symbol* k1 = klass_name_at(index1);
1430     Symbol* k2 = cp2->klass_name_at(index2);
1431     if (k1 == k2) {
1432       return true;
1433     }
1434   } break;
1435 
1436   case JVM_CONSTANT_MethodType:
1437   {
1438     int k1 = method_type_index_at(index1);
1439     int k2 = cp2->method_type_index_at(index2);
1440     if (compare_entry_to(k1, cp2, k2)) {
1441       return true;
1442     }
1443   } break;
1444 
1445   case JVM_CONSTANT_MethodHandle:
1446   {
1447     int k1 = method_handle_ref_kind_at(index1);
1448     int k2 = cp2->method_handle_ref_kind_at(index2);
1449     if (k1 == k2) {
1450       int i1 = method_handle_index_at(index1);
1451       int i2 = cp2->method_handle_index_at(index2);
1452       if (compare_entry_to(i1, cp2, i2)) {
1453         return true;
1454       }
1455     }
1456   } break;
1457 
1458   case JVM_CONSTANT_Dynamic:
1459   {
1460     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1461     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1462     int i1 = bootstrap_methods_attribute_index(index1);
1463     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1464     bool match_entry = compare_entry_to(k1, cp2, k2);
1465     bool match_operand = compare_operand_to(i1, cp2, i2);
1466     return (match_entry && match_operand);
1467   } break;
1468 
1469   case JVM_CONSTANT_InvokeDynamic:
1470   {
1471     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1472     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1473     int i1 = bootstrap_methods_attribute_index(index1);
1474     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1475     bool match_entry = compare_entry_to(k1, cp2, k2);
1476     bool match_operand = compare_operand_to(i1, cp2, i2);
1477     return (match_entry && match_operand);
1478   } break;
1479 
1480   case JVM_CONSTANT_String:
1481   {
1482     Symbol* s1 = unresolved_string_at(index1);
1483     Symbol* s2 = cp2->unresolved_string_at(index2);
1484     if (s1 == s2) {
1485       return true;
1486     }
1487   } break;
1488 
1489   case JVM_CONSTANT_Utf8:
1490   {
1491     Symbol* s1 = symbol_at(index1);
1492     Symbol* s2 = cp2->symbol_at(index2);
1493     if (s1 == s2) {
1494       return true;
1495     }
1496   } break;
1497 
1498   // Invalid is used as the tag for the second constant pool entry
1499   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1500   // not be seen by itself.
1501   case JVM_CONSTANT_Invalid: // fall through
1502 
1503   default:
1504     ShouldNotReachHere();
1505     break;
1506   }
1507 
1508   return false;
1509 } // end compare_entry_to()
1510 
1511 
1512 // Resize the operands array with delta_len and delta_size.
1513 // Used in RedefineClasses for CP merge.
1514 void ConstantPool::resize_operands(int delta_len, int delta_size, TRAPS) {
1515   int old_len  = operand_array_length(operands());
1516   int new_len  = old_len + delta_len;
1517   int min_len  = (delta_len > 0) ? old_len : new_len;
1518 
1519   int old_size = operands()->length();
1520   int new_size = old_size + delta_size;
1521   int min_size = (delta_size > 0) ? old_size : new_size;
1522 
1523   ClassLoaderData* loader_data = pool_holder()->class_loader_data();
1524   Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, new_size, CHECK);
1525 
1526   // Set index in the resized array for existing elements only
1527   for (int idx = 0; idx < min_len; idx++) {
1528     int offset = operand_offset_at(idx);                       // offset in original array
1529     operand_offset_at_put(new_ops, idx, offset + 2*delta_len); // offset in resized array
1530   }
1531   // Copy the bootstrap specifiers only
1532   Copy::conjoint_memory_atomic(operands()->adr_at(2*old_len),
1533                                new_ops->adr_at(2*new_len),
1534                                (min_size - 2*min_len) * sizeof(u2));
1535   // Explicitly deallocate old operands array.
1536   // Note, it is not needed for 7u backport.
1537   if ( operands() != NULL) { // the safety check
1538     MetadataFactory::free_array<u2>(loader_data, operands());
1539   }
1540   set_operands(new_ops);
1541 } // end resize_operands()
1542 
1543 
1544 // Extend the operands array with the length and size of the ext_cp operands.
1545 // Used in RedefineClasses for CP merge.
1546 void ConstantPool::extend_operands(const constantPoolHandle& ext_cp, TRAPS) {
1547   int delta_len = operand_array_length(ext_cp->operands());
1548   if (delta_len == 0) {
1549     return; // nothing to do
1550   }
1551   int delta_size = ext_cp->operands()->length();
1552 
1553   assert(delta_len  > 0 && delta_size > 0, "extended operands array must be bigger");
1554 
1555   if (operand_array_length(operands()) == 0) {
1556     ClassLoaderData* loader_data = pool_holder()->class_loader_data();
1557     Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, delta_size, CHECK);
1558     // The first element index defines the offset of second part
1559     operand_offset_at_put(new_ops, 0, 2*delta_len); // offset in new array
1560     set_operands(new_ops);
1561   } else {
1562     resize_operands(delta_len, delta_size, CHECK);
1563   }
1564 
1565 } // end extend_operands()
1566 
1567 
1568 // Shrink the operands array to a smaller array with new_len length.
1569 // Used in RedefineClasses for CP merge.
1570 void ConstantPool::shrink_operands(int new_len, TRAPS) {
1571   int old_len = operand_array_length(operands());
1572   if (new_len == old_len) {
1573     return; // nothing to do
1574   }
1575   assert(new_len < old_len, "shrunken operands array must be smaller");
1576 
1577   int free_base  = operand_next_offset_at(new_len - 1);
1578   int delta_len  = new_len - old_len;
1579   int delta_size = 2*delta_len + free_base - operands()->length();
1580 
1581   resize_operands(delta_len, delta_size, CHECK);
1582 
1583 } // end shrink_operands()
1584 
1585 
1586 void ConstantPool::copy_operands(const constantPoolHandle& from_cp,
1587                                  const constantPoolHandle& to_cp,
1588                                  TRAPS) {
1589 
1590   int from_oplen = operand_array_length(from_cp->operands());
1591   int old_oplen  = operand_array_length(to_cp->operands());
1592   if (from_oplen != 0) {
1593     ClassLoaderData* loader_data = to_cp->pool_holder()->class_loader_data();
1594     // append my operands to the target's operands array
1595     if (old_oplen == 0) {
1596       // Can't just reuse from_cp's operand list because of deallocation issues
1597       int len = from_cp->operands()->length();
1598       Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, len, CHECK);
1599       Copy::conjoint_memory_atomic(
1600           from_cp->operands()->adr_at(0), new_ops->adr_at(0), len * sizeof(u2));
1601       to_cp->set_operands(new_ops);
1602     } else {
1603       int old_len  = to_cp->operands()->length();
1604       int from_len = from_cp->operands()->length();
1605       int old_off  = old_oplen * sizeof(u2);
1606       int from_off = from_oplen * sizeof(u2);
1607       // Use the metaspace for the destination constant pool
1608       Array<u2>* new_operands = MetadataFactory::new_array<u2>(loader_data, old_len + from_len, CHECK);
1609       int fillp = 0, len = 0;
1610       // first part of dest
1611       Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(0),
1612                                    new_operands->adr_at(fillp),
1613                                    (len = old_off) * sizeof(u2));
1614       fillp += len;
1615       // first part of src
1616       Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(0),
1617                                    new_operands->adr_at(fillp),
1618                                    (len = from_off) * sizeof(u2));
1619       fillp += len;
1620       // second part of dest
1621       Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(old_off),
1622                                    new_operands->adr_at(fillp),
1623                                    (len = old_len - old_off) * sizeof(u2));
1624       fillp += len;
1625       // second part of src
1626       Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(from_off),
1627                                    new_operands->adr_at(fillp),
1628                                    (len = from_len - from_off) * sizeof(u2));
1629       fillp += len;
1630       assert(fillp == new_operands->length(), "");
1631 
1632       // Adjust indexes in the first part of the copied operands array.
1633       for (int j = 0; j < from_oplen; j++) {
1634         int offset = operand_offset_at(new_operands, old_oplen + j);
1635         assert(offset == operand_offset_at(from_cp->operands(), j), "correct copy");
1636         offset += old_len;  // every new tuple is preceded by old_len extra u2's
1637         operand_offset_at_put(new_operands, old_oplen + j, offset);
1638       }
1639 
1640       // replace target operands array with combined array
1641       to_cp->set_operands(new_operands);
1642     }
1643   }
1644 } // end copy_operands()
1645 
1646 
1647 // Copy this constant pool's entries at start_i to end_i (inclusive)
1648 // to the constant pool to_cp's entries starting at to_i. A total of
1649 // (end_i - start_i) + 1 entries are copied.
1650 void ConstantPool::copy_cp_to_impl(const constantPoolHandle& from_cp, int start_i, int end_i,
1651        const constantPoolHandle& to_cp, int to_i, TRAPS) {
1652 
1653 
1654   int dest_i = to_i;  // leave original alone for debug purposes
1655 
1656   for (int src_i = start_i; src_i <= end_i; /* see loop bottom */ ) {
1657     copy_entry_to(from_cp, src_i, to_cp, dest_i);
1658 
1659     switch (from_cp->tag_at(src_i).value()) {
1660     case JVM_CONSTANT_Double:
1661     case JVM_CONSTANT_Long:
1662       // double and long take two constant pool entries
1663       src_i += 2;
1664       dest_i += 2;
1665       break;
1666 
1667     default:
1668       // all others take one constant pool entry
1669       src_i++;
1670       dest_i++;
1671       break;
1672     }
1673   }
1674   copy_operands(from_cp, to_cp, CHECK);
1675 
1676 } // end copy_cp_to_impl()
1677 
1678 
1679 // Copy this constant pool's entry at from_i to the constant pool
1680 // to_cp's entry at to_i.
1681 void ConstantPool::copy_entry_to(const constantPoolHandle& from_cp, int from_i,
1682                                         const constantPoolHandle& to_cp, int to_i) {
1683 
1684   int tag = from_cp->tag_at(from_i).value();
1685   switch (tag) {
1686   case JVM_CONSTANT_ClassIndex:
1687   {
1688     jint ki = from_cp->klass_index_at(from_i);
1689     to_cp->klass_index_at_put(to_i, ki);
1690   } break;
1691 
1692   case JVM_CONSTANT_Double:
1693   {
1694     jdouble d = from_cp->double_at(from_i);
1695     to_cp->double_at_put(to_i, d);
1696     // double takes two constant pool entries so init second entry's tag
1697     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1698   } break;
1699 
1700   case JVM_CONSTANT_Fieldref:
1701   {
1702     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1703     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1704     to_cp->field_at_put(to_i, class_index, name_and_type_index);
1705   } break;
1706 
1707   case JVM_CONSTANT_Float:
1708   {
1709     jfloat f = from_cp->float_at(from_i);
1710     to_cp->float_at_put(to_i, f);
1711   } break;
1712 
1713   case JVM_CONSTANT_Integer:
1714   {
1715     jint i = from_cp->int_at(from_i);
1716     to_cp->int_at_put(to_i, i);
1717   } break;
1718 
1719   case JVM_CONSTANT_InterfaceMethodref:
1720   {
1721     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1722     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1723     to_cp->interface_method_at_put(to_i, class_index, name_and_type_index);
1724   } break;
1725 
1726   case JVM_CONSTANT_Long:
1727   {
1728     jlong l = from_cp->long_at(from_i);
1729     to_cp->long_at_put(to_i, l);
1730     // long takes two constant pool entries so init second entry's tag
1731     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1732   } break;
1733 
1734   case JVM_CONSTANT_Methodref:
1735   {
1736     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1737     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1738     to_cp->method_at_put(to_i, class_index, name_and_type_index);
1739   } break;
1740 
1741   case JVM_CONSTANT_NameAndType:
1742   {
1743     int name_ref_index = from_cp->name_ref_index_at(from_i);
1744     int signature_ref_index = from_cp->signature_ref_index_at(from_i);
1745     to_cp->name_and_type_at_put(to_i, name_ref_index, signature_ref_index);
1746   } break;
1747 
1748   case JVM_CONSTANT_StringIndex:
1749   {
1750     jint si = from_cp->string_index_at(from_i);
1751     to_cp->string_index_at_put(to_i, si);
1752   } break;
1753 
1754   case JVM_CONSTANT_Class:
1755   case JVM_CONSTANT_UnresolvedClass:
1756   case JVM_CONSTANT_UnresolvedClassInError:
1757   {
1758     // Revert to JVM_CONSTANT_ClassIndex
1759     int name_index = from_cp->klass_slot_at(from_i).name_index();
1760     assert(from_cp->tag_at(name_index).is_symbol(), "sanity");
1761     to_cp->klass_index_at_put(to_i, name_index);
1762   } break;
1763 
1764   case JVM_CONSTANT_String:
1765   {
1766     Symbol* s = from_cp->unresolved_string_at(from_i);
1767     to_cp->unresolved_string_at_put(to_i, s);
1768   } break;
1769 
1770   case JVM_CONSTANT_Utf8:
1771   {
1772     Symbol* s = from_cp->symbol_at(from_i);
1773     // Need to increase refcount, the old one will be thrown away and deferenced
1774     s->increment_refcount();
1775     to_cp->symbol_at_put(to_i, s);
1776   } break;
1777 
1778   case JVM_CONSTANT_MethodType:
1779   case JVM_CONSTANT_MethodTypeInError:
1780   {
1781     jint k = from_cp->method_type_index_at(from_i);
1782     to_cp->method_type_index_at_put(to_i, k);
1783   } break;
1784 
1785   case JVM_CONSTANT_MethodHandle:
1786   case JVM_CONSTANT_MethodHandleInError:
1787   {
1788     int k1 = from_cp->method_handle_ref_kind_at(from_i);
1789     int k2 = from_cp->method_handle_index_at(from_i);
1790     to_cp->method_handle_index_at_put(to_i, k1, k2);
1791   } break;
1792 
1793   case JVM_CONSTANT_Dynamic:
1794   case JVM_CONSTANT_DynamicInError:
1795   {
1796     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1797     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1798     k1 += operand_array_length(to_cp->operands());  // to_cp might already have operands
1799     to_cp->dynamic_constant_at_put(to_i, k1, k2);
1800   } break;
1801 
1802   case JVM_CONSTANT_InvokeDynamic:
1803   {
1804     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1805     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1806     k1 += operand_array_length(to_cp->operands());  // to_cp might already have operands
1807     to_cp->invoke_dynamic_at_put(to_i, k1, k2);
1808   } break;
1809 
1810   // Invalid is used as the tag for the second constant pool entry
1811   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1812   // not be seen by itself.
1813   case JVM_CONSTANT_Invalid: // fall through
1814 
1815   default:
1816   {
1817     ShouldNotReachHere();
1818   } break;
1819   }
1820 } // end copy_entry_to()
1821 
1822 // Search constant pool search_cp for an entry that matches this
1823 // constant pool's entry at pattern_i. Returns the index of a
1824 // matching entry or zero (0) if there is no matching entry.
1825 int ConstantPool::find_matching_entry(int pattern_i,
1826       const constantPoolHandle& search_cp) {
1827 
1828   // index zero (0) is not used
1829   for (int i = 1; i < search_cp->length(); i++) {
1830     bool found = compare_entry_to(pattern_i, search_cp, i);
1831     if (found) {
1832       return i;
1833     }
1834   }
1835 
1836   return 0;  // entry not found; return unused index zero (0)
1837 } // end find_matching_entry()
1838 
1839 
1840 // Compare this constant pool's bootstrap specifier at idx1 to the constant pool
1841 // cp2's bootstrap specifier at idx2.
1842 bool ConstantPool::compare_operand_to(int idx1, const constantPoolHandle& cp2, int idx2) {
1843   int k1 = operand_bootstrap_method_ref_index_at(idx1);
1844   int k2 = cp2->operand_bootstrap_method_ref_index_at(idx2);
1845   bool match = compare_entry_to(k1, cp2, k2);
1846 
1847   if (!match) {
1848     return false;
1849   }
1850   int argc = operand_argument_count_at(idx1);
1851   if (argc == cp2->operand_argument_count_at(idx2)) {
1852     for (int j = 0; j < argc; j++) {
1853       k1 = operand_argument_index_at(idx1, j);
1854       k2 = cp2->operand_argument_index_at(idx2, j);
1855       match = compare_entry_to(k1, cp2, k2);
1856       if (!match) {
1857         return false;
1858       }
1859     }
1860     return true;           // got through loop; all elements equal
1861   }
1862   return false;
1863 } // end compare_operand_to()
1864 
1865 // Search constant pool search_cp for a bootstrap specifier that matches
1866 // this constant pool's bootstrap specifier data at pattern_i index.
1867 // Return the index of a matching bootstrap attribute record or (-1) if there is no match.
1868 int ConstantPool::find_matching_operand(int pattern_i,
1869                     const constantPoolHandle& search_cp, int search_len) {
1870   for (int i = 0; i < search_len; i++) {
1871     bool found = compare_operand_to(pattern_i, search_cp, i);
1872     if (found) {
1873       return i;
1874     }
1875   }
1876   return -1;  // bootstrap specifier data not found; return unused index (-1)
1877 } // end find_matching_operand()
1878 
1879 
1880 #ifndef PRODUCT
1881 
1882 const char* ConstantPool::printable_name_at(int which) {
1883 
1884   constantTag tag = tag_at(which);
1885 
1886   if (tag.is_string()) {
1887     return string_at_noresolve(which);
1888   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
1889     return klass_name_at(which)->as_C_string();
1890   } else if (tag.is_symbol()) {
1891     return symbol_at(which)->as_C_string();
1892   }
1893   return "";
1894 }
1895 
1896 #endif // PRODUCT
1897 
1898 
1899 // JVMTI GetConstantPool support
1900 
1901 // For debugging of constant pool
1902 const bool debug_cpool = false;
1903 
1904 #define DBG(code) do { if (debug_cpool) { (code); } } while(0)
1905 
1906 static void print_cpool_bytes(jint cnt, u1 *bytes) {
1907   const char* WARN_MSG = "Must not be such entry!";
1908   jint size = 0;
1909   u2   idx1, idx2;
1910 
1911   for (jint idx = 1; idx < cnt; idx++) {
1912     jint ent_size = 0;
1913     u1   tag  = *bytes++;
1914     size++;                       // count tag
1915 
1916     printf("const #%03d, tag: %02d ", idx, tag);
1917     switch(tag) {
1918       case JVM_CONSTANT_Invalid: {
1919         printf("Invalid");
1920         break;
1921       }
1922       case JVM_CONSTANT_Unicode: {
1923         printf("Unicode      %s", WARN_MSG);
1924         break;
1925       }
1926       case JVM_CONSTANT_Utf8: {
1927         u2 len = Bytes::get_Java_u2(bytes);
1928         char str[128];
1929         if (len > 127) {
1930            len = 127;
1931         }
1932         strncpy(str, (char *) (bytes+2), len);
1933         str[len] = '\0';
1934         printf("Utf8          \"%s\"", str);
1935         ent_size = 2 + len;
1936         break;
1937       }
1938       case JVM_CONSTANT_Integer: {
1939         u4 val = Bytes::get_Java_u4(bytes);
1940         printf("int          %d", *(int *) &val);
1941         ent_size = 4;
1942         break;
1943       }
1944       case JVM_CONSTANT_Float: {
1945         u4 val = Bytes::get_Java_u4(bytes);
1946         printf("float        %5.3ff", *(float *) &val);
1947         ent_size = 4;
1948         break;
1949       }
1950       case JVM_CONSTANT_Long: {
1951         u8 val = Bytes::get_Java_u8(bytes);
1952         printf("long         " INT64_FORMAT, (int64_t) *(jlong *) &val);
1953         ent_size = 8;
1954         idx++; // Long takes two cpool slots
1955         break;
1956       }
1957       case JVM_CONSTANT_Double: {
1958         u8 val = Bytes::get_Java_u8(bytes);
1959         printf("double       %5.3fd", *(jdouble *)&val);
1960         ent_size = 8;
1961         idx++; // Double takes two cpool slots
1962         break;
1963       }
1964       case JVM_CONSTANT_Class: {
1965         idx1 = Bytes::get_Java_u2(bytes);
1966         printf("class        #%03d", idx1);
1967         ent_size = 2;
1968         break;
1969       }
1970       case (JVM_CONSTANT_Class | JVM_CONSTANT_QDescBit): {
1971         idx1 = Bytes::get_Java_u2(bytes);
1972         printf("qclass        #%03d", idx1);
1973         ent_size = 2;
1974         break;
1975       }
1976       case JVM_CONSTANT_String: {
1977         idx1 = Bytes::get_Java_u2(bytes);
1978         printf("String       #%03d", idx1);
1979         ent_size = 2;
1980         break;
1981       }
1982       case JVM_CONSTANT_Fieldref: {
1983         idx1 = Bytes::get_Java_u2(bytes);
1984         idx2 = Bytes::get_Java_u2(bytes+2);
1985         printf("Field        #%03d, #%03d", (int) idx1, (int) idx2);
1986         ent_size = 4;
1987         break;
1988       }
1989       case JVM_CONSTANT_Methodref: {
1990         idx1 = Bytes::get_Java_u2(bytes);
1991         idx2 = Bytes::get_Java_u2(bytes+2);
1992         printf("Method       #%03d, #%03d", idx1, idx2);
1993         ent_size = 4;
1994         break;
1995       }
1996       case JVM_CONSTANT_InterfaceMethodref: {
1997         idx1 = Bytes::get_Java_u2(bytes);
1998         idx2 = Bytes::get_Java_u2(bytes+2);
1999         printf("InterfMethod #%03d, #%03d", idx1, idx2);
2000         ent_size = 4;
2001         break;
2002       }
2003       case JVM_CONSTANT_NameAndType: {
2004         idx1 = Bytes::get_Java_u2(bytes);
2005         idx2 = Bytes::get_Java_u2(bytes+2);
2006         printf("NameAndType  #%03d, #%03d", idx1, idx2);
2007         ent_size = 4;
2008         break;
2009       }
2010       case JVM_CONSTANT_ClassIndex: {
2011         printf("ClassIndex  %s", WARN_MSG);
2012         break;
2013       }
2014       case JVM_CONSTANT_UnresolvedClass: {
2015         printf("UnresolvedClass: %s", WARN_MSG);
2016         break;
2017       }
2018       case (JVM_CONSTANT_UnresolvedClass | JVM_CONSTANT_QDescBit): {
2019         printf("UnresolvedQClass: %s", WARN_MSG);
2020         break;
2021       }
2022       case JVM_CONSTANT_UnresolvedClassInError: {
2023         printf("UnresolvedClassInErr: %s", WARN_MSG);
2024         break;
2025       }
2026       case JVM_CONSTANT_StringIndex: {
2027         printf("StringIndex: %s", WARN_MSG);
2028         break;
2029       }
2030     }
2031     printf(";\n");
2032     bytes += ent_size;
2033     size  += ent_size;
2034   }
2035   printf("Cpool size: %d\n", size);
2036   fflush(0);
2037   return;
2038 } /* end print_cpool_bytes */
2039 
2040 
2041 // Returns size of constant pool entry.
2042 jint ConstantPool::cpool_entry_size(jint idx) {
2043   switch(tag_at(idx).value()) {
2044     case JVM_CONSTANT_Invalid:
2045     case JVM_CONSTANT_Unicode:
2046       return 1;
2047 
2048     case JVM_CONSTANT_Utf8:
2049       return 3 + symbol_at(idx)->utf8_length();
2050 
2051     case JVM_CONSTANT_Class:
2052     case JVM_CONSTANT_String:
2053     case JVM_CONSTANT_ClassIndex:
2054     case JVM_CONSTANT_UnresolvedClass:
2055     case JVM_CONSTANT_UnresolvedClassInError:
2056     case JVM_CONSTANT_StringIndex:
2057     case JVM_CONSTANT_MethodType:
2058     case JVM_CONSTANT_MethodTypeInError:
2059       return 3;
2060 
2061     case JVM_CONSTANT_MethodHandle:
2062     case JVM_CONSTANT_MethodHandleInError:
2063       return 4; //tag, ref_kind, ref_index
2064 
2065     case JVM_CONSTANT_Integer:
2066     case JVM_CONSTANT_Float:
2067     case JVM_CONSTANT_Fieldref:
2068     case JVM_CONSTANT_Methodref:
2069     case JVM_CONSTANT_InterfaceMethodref:
2070     case JVM_CONSTANT_NameAndType:
2071       return 5;
2072 
2073     case JVM_CONSTANT_Dynamic:
2074     case JVM_CONSTANT_DynamicInError:
2075     case JVM_CONSTANT_InvokeDynamic:
2076       // u1 tag, u2 bsm, u2 nt
2077       return 5;
2078 
2079     case JVM_CONSTANT_Long:
2080     case JVM_CONSTANT_Double:
2081       return 9;
2082   }
2083   assert(false, "cpool_entry_size: Invalid constant pool entry tag");
2084   return 1;
2085 } /* end cpool_entry_size */
2086 
2087 
2088 // SymbolHash is used to find a constant pool index from a string.
2089 // This function fills in SymbolHashs, one for utf8s and one for
2090 // class names, returns size of the cpool raw bytes.
2091 jint ConstantPool::hash_entries_to(SymbolHash *symmap,
2092                                    SymbolHash *classmap) {
2093   jint size = 0;
2094 
2095   for (u2 idx = 1; idx < length(); idx++) {
2096     u2 tag = tag_at(idx).value();
2097     size += cpool_entry_size(idx);
2098 
2099     switch(tag) {
2100       case JVM_CONSTANT_Utf8: {
2101         Symbol* sym = symbol_at(idx);
2102         symmap->add_if_absent(sym, idx);
2103         DBG(printf("adding symbol entry %s = %d\n", sym->as_utf8(), idx));
2104         break;
2105       }
2106       case JVM_CONSTANT_Class:
2107       case JVM_CONSTANT_UnresolvedClass:
2108       case JVM_CONSTANT_UnresolvedClassInError: {
2109         Symbol* sym = klass_name_at(idx);
2110         classmap->add_if_absent(sym, idx);
2111         DBG(printf("adding class entry %s = %d\n", sym->as_utf8(), idx));
2112         break;
2113       }
2114       case JVM_CONSTANT_Long:
2115       case JVM_CONSTANT_Double: {
2116         idx++; // Both Long and Double take two cpool slots
2117         break;
2118       }
2119     }
2120   }
2121   return size;
2122 } /* end hash_utf8_entries_to */
2123 
2124 
2125 // Copy cpool bytes.
2126 // Returns:
2127 //    0, in case of OutOfMemoryError
2128 //   -1, in case of internal error
2129 //  > 0, count of the raw cpool bytes that have been copied
2130 int ConstantPool::copy_cpool_bytes(int cpool_size,
2131                                    SymbolHash* tbl,
2132                                    unsigned char *bytes) {
2133   u2   idx1, idx2;
2134   jint size  = 0;
2135   jint cnt   = length();
2136   unsigned char *start_bytes = bytes;
2137 
2138   for (jint idx = 1; idx < cnt; idx++) {
2139     u1   tag      = tag_at(idx).value();
2140     jint ent_size = cpool_entry_size(idx);
2141 
2142     assert(size + ent_size <= cpool_size, "Size mismatch");
2143 
2144     *bytes = tag;
2145     DBG(printf("#%03hd tag=%03hd, ", (short)idx, (short)tag));
2146     switch(tag) {
2147       case JVM_CONSTANT_Invalid: {
2148         DBG(printf("JVM_CONSTANT_Invalid"));
2149         break;
2150       }
2151       case JVM_CONSTANT_Unicode: {
2152         assert(false, "Wrong constant pool tag: JVM_CONSTANT_Unicode");
2153         DBG(printf("JVM_CONSTANT_Unicode"));
2154         break;
2155       }
2156       case JVM_CONSTANT_Utf8: {
2157         Symbol* sym = symbol_at(idx);
2158         char*     str = sym->as_utf8();
2159         // Warning! It's crashing on x86 with len = sym->utf8_length()
2160         int       len = (int) strlen(str);
2161         Bytes::put_Java_u2((address) (bytes+1), (u2) len);
2162         for (int i = 0; i < len; i++) {
2163             bytes[3+i] = (u1) str[i];
2164         }
2165         DBG(printf("JVM_CONSTANT_Utf8: %s ", str));
2166         break;
2167       }
2168       case JVM_CONSTANT_Integer: {
2169         jint val = int_at(idx);
2170         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2171         break;
2172       }
2173       case JVM_CONSTANT_Float: {
2174         jfloat val = float_at(idx);
2175         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2176         break;
2177       }
2178       case JVM_CONSTANT_Long: {
2179         jlong val = long_at(idx);
2180         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2181         idx++;             // Long takes two cpool slots
2182         break;
2183       }
2184       case JVM_CONSTANT_Double: {
2185         jdouble val = double_at(idx);
2186         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2187         idx++;             // Double takes two cpool slots
2188         break;
2189       }
2190       case JVM_CONSTANT_Class:
2191       case JVM_CONSTANT_UnresolvedClass:
2192       case JVM_CONSTANT_UnresolvedClassInError: {
2193         *bytes = JVM_CONSTANT_Class;
2194         Symbol* sym = klass_name_at(idx);
2195         idx1 = tbl->symbol_to_value(sym);
2196         assert(idx1 != 0, "Have not found a hashtable entry");
2197         Bytes::put_Java_u2((address) (bytes+1), idx1);
2198         DBG(printf("JVM_CONSTANT_Class: idx=#%03hd, %s", idx1, sym->as_utf8()));
2199         break;
2200       }
2201       case JVM_CONSTANT_String: {
2202         *bytes = JVM_CONSTANT_String;
2203         Symbol* sym = unresolved_string_at(idx);
2204         idx1 = tbl->symbol_to_value(sym);
2205         assert(idx1 != 0, "Have not found a hashtable entry");
2206         Bytes::put_Java_u2((address) (bytes+1), idx1);
2207         DBG(printf("JVM_CONSTANT_String: idx=#%03hd, %s", idx1, sym->as_utf8()));
2208         break;
2209       }
2210       case JVM_CONSTANT_Fieldref:
2211       case JVM_CONSTANT_Methodref:
2212       case JVM_CONSTANT_InterfaceMethodref: {
2213         idx1 = uncached_klass_ref_index_at(idx);
2214         idx2 = uncached_name_and_type_ref_index_at(idx);
2215         Bytes::put_Java_u2((address) (bytes+1), idx1);
2216         Bytes::put_Java_u2((address) (bytes+3), idx2);
2217         DBG(printf("JVM_CONSTANT_Methodref: %hd %hd", idx1, idx2));
2218         break;
2219       }
2220       case JVM_CONSTANT_NameAndType: {
2221         idx1 = name_ref_index_at(idx);
2222         idx2 = signature_ref_index_at(idx);
2223         Bytes::put_Java_u2((address) (bytes+1), idx1);
2224         Bytes::put_Java_u2((address) (bytes+3), idx2);
2225         DBG(printf("JVM_CONSTANT_NameAndType: %hd %hd", idx1, idx2));
2226         break;
2227       }
2228       case JVM_CONSTANT_ClassIndex: {
2229         *bytes = JVM_CONSTANT_Class;
2230         idx1 = klass_index_at(idx);
2231         Bytes::put_Java_u2((address) (bytes+1), idx1);
2232         DBG(printf("JVM_CONSTANT_ClassIndex: %hd", idx1));
2233         break;
2234       }
2235       case JVM_CONSTANT_StringIndex: {
2236         *bytes = JVM_CONSTANT_String;
2237         idx1 = string_index_at(idx);
2238         Bytes::put_Java_u2((address) (bytes+1), idx1);
2239         DBG(printf("JVM_CONSTANT_StringIndex: %hd", idx1));
2240         break;
2241       }
2242       case JVM_CONSTANT_MethodHandle:
2243       case JVM_CONSTANT_MethodHandleInError: {
2244         *bytes = JVM_CONSTANT_MethodHandle;
2245         int kind = method_handle_ref_kind_at(idx);
2246         idx1 = method_handle_index_at(idx);
2247         *(bytes+1) = (unsigned char) kind;
2248         Bytes::put_Java_u2((address) (bytes+2), idx1);
2249         DBG(printf("JVM_CONSTANT_MethodHandle: %d %hd", kind, idx1));
2250         break;
2251       }
2252       case JVM_CONSTANT_MethodType:
2253       case JVM_CONSTANT_MethodTypeInError: {
2254         *bytes = JVM_CONSTANT_MethodType;
2255         idx1 = method_type_index_at(idx);
2256         Bytes::put_Java_u2((address) (bytes+1), idx1);
2257         DBG(printf("JVM_CONSTANT_MethodType: %hd", idx1));
2258         break;
2259       }
2260       case JVM_CONSTANT_Dynamic:
2261       case JVM_CONSTANT_DynamicInError: {
2262         *bytes = tag;
2263         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2264         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2265         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2266         Bytes::put_Java_u2((address) (bytes+1), idx1);
2267         Bytes::put_Java_u2((address) (bytes+3), idx2);
2268         DBG(printf("JVM_CONSTANT_Dynamic: %hd %hd", idx1, idx2));
2269         break;
2270       }
2271       case JVM_CONSTANT_InvokeDynamic: {
2272         *bytes = tag;
2273         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2274         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2275         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2276         Bytes::put_Java_u2((address) (bytes+1), idx1);
2277         Bytes::put_Java_u2((address) (bytes+3), idx2);
2278         DBG(printf("JVM_CONSTANT_InvokeDynamic: %hd %hd", idx1, idx2));
2279         break;
2280       }
2281     }
2282     DBG(printf("\n"));
2283     bytes += ent_size;
2284     size  += ent_size;
2285   }
2286   assert(size == cpool_size, "Size mismatch");
2287 
2288   // Keep temporarily for debugging until it's stable.
2289   DBG(print_cpool_bytes(cnt, start_bytes));
2290   return (int)(bytes - start_bytes);
2291 } /* end copy_cpool_bytes */
2292 
2293 #undef DBG
2294 
2295 bool ConstantPool::is_maybe_on_stack() const {
2296   // This method uses the similar logic as nmethod::is_maybe_on_stack()
2297   if (!Continuations::enabled()) {
2298     return false;
2299   }
2300 
2301   // If the condition below is true, it means that the nmethod was found to
2302   // be alive the previous completed marking cycle.
2303   return cache()->gc_epoch() >= CodeCache::previous_completed_gc_marking_cycle();
2304 }
2305 
2306 // For redefinition, if any methods found in loom stack chunks, the gc_epoch is
2307 // recorded in their constant pool cache. The on_stack-ness of the constant pool controls whether
2308 // memory for the method is reclaimed.
2309 bool ConstantPool::on_stack() const {
2310   if ((_flags &_on_stack) != 0) {
2311     return true;
2312   }
2313 
2314   if (_cache == nullptr) {
2315     return false;
2316   }
2317 
2318   return is_maybe_on_stack();
2319 }
2320 
2321 void ConstantPool::set_on_stack(const bool value) {
2322   if (value) {
2323     // Only record if it's not already set.
2324     if (!on_stack()) {
2325       assert(!is_shared(), "should always be set for shared constant pools");
2326       _flags |= _on_stack;
2327       MetadataOnStackMark::record(this);
2328     }
2329   } else {
2330     // Clearing is done single-threadedly.
2331     if (!is_shared()) {
2332       _flags &= ~_on_stack;
2333     }
2334   }
2335 }
2336 
2337 // Printing
2338 
2339 void ConstantPool::print_on(outputStream* st) const {
2340   assert(is_constantPool(), "must be constantPool");
2341   st->print_cr("%s", internal_name());
2342   if (flags() != 0) {
2343     st->print(" - flags: 0x%x", flags());
2344     if (has_preresolution()) st->print(" has_preresolution");
2345     if (on_stack()) st->print(" on_stack");
2346     st->cr();
2347   }
2348   if (pool_holder() != NULL) {
2349     st->print_cr(" - holder: " PTR_FORMAT, p2i(pool_holder()));
2350   }
2351   st->print_cr(" - cache: " PTR_FORMAT, p2i(cache()));
2352   st->print_cr(" - resolved_references: " PTR_FORMAT, p2i(resolved_references_or_null()));
2353   st->print_cr(" - reference_map: " PTR_FORMAT, p2i(reference_map()));
2354   st->print_cr(" - resolved_klasses: " PTR_FORMAT, p2i(resolved_klasses()));
2355   st->print_cr(" - cp length: %d", length());
2356 
2357   for (int index = 1; index < length(); index++) {      // Index 0 is unused
2358     ((ConstantPool*)this)->print_entry_on(index, st);
2359     switch (tag_at(index).value()) {
2360       case JVM_CONSTANT_Long :
2361       case JVM_CONSTANT_Double :
2362         index++;   // Skip entry following eigth-byte constant
2363     }
2364 
2365   }
2366   st->cr();
2367 }
2368 
2369 // Print one constant pool entry
2370 void ConstantPool::print_entry_on(const int index, outputStream* st) {
2371   EXCEPTION_MARK;
2372   st->print(" - %3d : ", index);
2373   tag_at(index).print_on(st);
2374   st->print(" : ");
2375   switch (tag_at(index).value()) {
2376     case JVM_CONSTANT_Class :
2377       { Klass* k = klass_at(index, CATCH);
2378         guarantee(k != NULL, "need klass");
2379         k->print_value_on(st);
2380         st->print(" {" PTR_FORMAT "}", p2i(k));
2381       }
2382       break;
2383     case JVM_CONSTANT_Fieldref :
2384     case JVM_CONSTANT_Methodref :
2385     case JVM_CONSTANT_InterfaceMethodref :
2386       st->print("klass_index=%d", uncached_klass_ref_index_at(index));
2387       st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(index));
2388       break;
2389     case JVM_CONSTANT_String :
2390       unresolved_string_at(index)->print_value_on(st);
2391       break;
2392     case JVM_CONSTANT_Integer :
2393       st->print("%d", int_at(index));
2394       break;
2395     case JVM_CONSTANT_Float :
2396       st->print("%f", float_at(index));
2397       break;
2398     case JVM_CONSTANT_Long :
2399       st->print_jlong(long_at(index));
2400       break;
2401     case JVM_CONSTANT_Double :
2402       st->print("%lf", double_at(index));
2403       break;
2404     case JVM_CONSTANT_NameAndType :
2405       st->print("name_index=%d", name_ref_index_at(index));
2406       st->print(" signature_index=%d", signature_ref_index_at(index));
2407       break;
2408     case JVM_CONSTANT_Utf8 :
2409       symbol_at(index)->print_value_on(st);
2410       break;
2411     case JVM_CONSTANT_ClassIndex: {
2412         int name_index = *int_at_addr(index);
2413         st->print("klass_index=%d ", name_index);
2414         symbol_at(name_index)->print_value_on(st);
2415       }
2416       break;
2417     case JVM_CONSTANT_UnresolvedClass :               // fall-through
2418     case JVM_CONSTANT_UnresolvedClassInError: {
2419         CPKlassSlot kslot = klass_slot_at(index);
2420         int resolved_klass_index = kslot.resolved_klass_index();
2421         int name_index = kslot.name_index();
2422         assert(tag_at(name_index).is_symbol(), "sanity");
2423         symbol_at(name_index)->print_value_on(st);
2424       }
2425       break;
2426     case JVM_CONSTANT_MethodHandle :
2427     case JVM_CONSTANT_MethodHandleInError :
2428       st->print("ref_kind=%d", method_handle_ref_kind_at(index));
2429       st->print(" ref_index=%d", method_handle_index_at(index));
2430       break;
2431     case JVM_CONSTANT_MethodType :
2432     case JVM_CONSTANT_MethodTypeInError :
2433       st->print("signature_index=%d", method_type_index_at(index));
2434       break;
2435     case JVM_CONSTANT_Dynamic :
2436     case JVM_CONSTANT_DynamicInError :
2437       {
2438         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));
2439         st->print(" type_index=%d", bootstrap_name_and_type_ref_index_at(index));
2440         int argc = bootstrap_argument_count_at(index);
2441         if (argc > 0) {
2442           for (int arg_i = 0; arg_i < argc; arg_i++) {
2443             int arg = bootstrap_argument_index_at(index, arg_i);
2444             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2445           }
2446           st->print("}");
2447         }
2448       }
2449       break;
2450     case JVM_CONSTANT_InvokeDynamic :
2451       {
2452         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));
2453         st->print(" name_and_type_index=%d", bootstrap_name_and_type_ref_index_at(index));
2454         int argc = bootstrap_argument_count_at(index);
2455         if (argc > 0) {
2456           for (int arg_i = 0; arg_i < argc; arg_i++) {
2457             int arg = bootstrap_argument_index_at(index, arg_i);
2458             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2459           }
2460           st->print("}");
2461         }
2462       }
2463       break;
2464     default:
2465       ShouldNotReachHere();
2466       break;
2467   }
2468   st->cr();
2469 }
2470 
2471 void ConstantPool::print_value_on(outputStream* st) const {
2472   assert(is_constantPool(), "must be constantPool");
2473   st->print("constant pool [%d]", length());
2474   if (has_preresolution()) st->print("/preresolution");
2475   if (operands() != NULL)  st->print("/operands[%d]", operands()->length());
2476   print_address_on(st);
2477   if (pool_holder() != NULL) {
2478     st->print(" for ");
2479     pool_holder()->print_value_on(st);
2480     bool extra = (pool_holder()->constants() != this);
2481     if (extra)  st->print(" (extra)");
2482   }
2483   if (cache() != NULL) {
2484     st->print(" cache=" PTR_FORMAT, p2i(cache()));
2485   }
2486 }
2487 
2488 // Verification
2489 
2490 void ConstantPool::verify_on(outputStream* st) {
2491   guarantee(is_constantPool(), "object must be constant pool");
2492   for (int i = 0; i< length();  i++) {
2493     constantTag tag = tag_at(i);
2494     if (tag.is_klass() || tag.is_unresolved_klass()) {
2495       guarantee(klass_name_at(i)->refcount() != 0, "should have nonzero reference count");
2496     } else if (tag.is_symbol()) {
2497       Symbol* entry = symbol_at(i);
2498       guarantee(entry->refcount() != 0, "should have nonzero reference count");
2499     } else if (tag.is_string()) {
2500       Symbol* entry = unresolved_string_at(i);
2501       guarantee(entry->refcount() != 0, "should have nonzero reference count");
2502     }
2503   }
2504   if (pool_holder() != NULL) {
2505     // Note: pool_holder() can be NULL in temporary constant pools
2506     // used during constant pool merging
2507     guarantee(pool_holder()->is_klass(),    "should be klass");
2508   }
2509 }