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