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