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