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