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