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