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     BasicType bt = basic_type_for_constant_at(which);
 931     return constantTag(constantTag::type2tag(bt));
 932   }
 933   return tag;
 934 }
 935 
 936 BasicType ConstantPool::basic_type_for_constant_at(int which) {
 937   constantTag tag = tag_at(which);
 938   if (tag.is_dynamic_constant() ||
 939       tag.is_dynamic_constant_in_error()) {
 940     // have to look at the signature for this one
 941     Symbol* constant_type = uncached_signature_ref_at(which);
 942     return Signature::basic_type(constant_type);
 943   }
 944   return tag.basic_type();
 945 }
 946 
 947 // Called to resolve constants in the constant pool and return an oop.
 948 // Some constant pool entries cache their resolved oop. This is also
 949 // called to create oops from constants to use in arguments for invokedynamic
 950 oop ConstantPool::resolve_constant_at_impl(const constantPoolHandle& this_cp,
 951                                            int index, int cache_index,
 952                                            bool* status_return, TRAPS) {
 953   oop result_oop = NULL;
 954   Handle throw_exception;
 955 
 956   if (cache_index == _possible_index_sentinel) {
 957     // It is possible that this constant is one which is cached in the objects.
 958     // We'll do a linear search.  This should be OK because this usage is rare.
 959     // FIXME: If bootstrap specifiers stress this code, consider putting in
 960     // a reverse index.  Binary search over a short array should do it.
 961     assert(index > 0, "valid index");
 962     cache_index = this_cp->cp_to_object_index(index);
 963   }
 964   assert(cache_index == _no_index_sentinel || cache_index >= 0, "");
 965   assert(index == _no_index_sentinel || index >= 0, "");
 966 
 967   if (cache_index >= 0) {
 968     result_oop = this_cp->resolved_references()->obj_at(cache_index);
 969     if (result_oop != NULL) {
 970       if (result_oop == Universe::the_null_sentinel()) {
 971         DEBUG_ONLY(int temp_index = (index >= 0 ? index : this_cp->object_to_cp_index(cache_index)));
 972         assert(this_cp->tag_at(temp_index).is_dynamic_constant(), "only condy uses the null sentinel");
 973         result_oop = NULL;
 974       }
 975       if (status_return != NULL)  (*status_return) = true;
 976       return result_oop;
 977       // That was easy...
 978     }
 979     index = this_cp->object_to_cp_index(cache_index);
 980   }
 981 
 982   jvalue prim_value;  // temp used only in a few cases below
 983 
 984   constantTag tag = this_cp->tag_at(index);
 985 
 986   if (status_return != NULL) {
 987     // don't trigger resolution if the constant might need it
 988     switch (tag.value()) {
 989     case JVM_CONSTANT_Class:
 990     {
 991       CPKlassSlot kslot = this_cp->klass_slot_at(index);
 992       int resolved_klass_index = kslot.resolved_klass_index();
 993       if (this_cp->resolved_klasses()->at(resolved_klass_index) == NULL) {
 994         (*status_return) = false;
 995         return NULL;
 996       }
 997       // the klass is waiting in the CP; go get it
 998       break;
 999     }
1000     case JVM_CONSTANT_String:
1001     case JVM_CONSTANT_Integer:
1002     case JVM_CONSTANT_Float:
1003     case JVM_CONSTANT_Long:
1004     case JVM_CONSTANT_Double:
1005       // these guys trigger OOM at worst
1006       break;
1007     default:
1008       (*status_return) = false;
1009       return NULL;
1010     }
1011     // from now on there is either success or an OOME
1012     (*status_return) = true;
1013   }
1014 
1015   switch (tag.value()) {
1016 
1017   case JVM_CONSTANT_UnresolvedClass:
1018   case JVM_CONSTANT_Class:
1019     {
1020       assert(cache_index == _no_index_sentinel, "should not have been set");
1021       Klass* resolved = klass_at_impl(this_cp, index, CHECK_NULL);
1022       // ldc wants the java mirror.
1023       result_oop = tag.is_Qdescriptor_klass()
1024                       ? InlineKlass::cast(resolved)->val_mirror()
1025                       : resolved->java_mirror();
1026       break;
1027     }
1028 
1029   case JVM_CONSTANT_Dynamic:
1030     {
1031       // Resolve the Dynamically-Computed constant to invoke the BSM in order to obtain the resulting oop.
1032       BootstrapInfo bootstrap_specifier(this_cp, index);
1033 
1034       // The initial step in resolving an unresolved symbolic reference to a
1035       // dynamically-computed constant is to resolve the symbolic reference to a
1036       // method handle which will be the bootstrap method for the dynamically-computed
1037       // constant. If resolution of the java.lang.invoke.MethodHandle for the bootstrap
1038       // method fails, then a MethodHandleInError is stored at the corresponding
1039       // bootstrap method's CP index for the CONSTANT_MethodHandle_info. No need to
1040       // set a DynamicConstantInError here since any subsequent use of this
1041       // bootstrap method will encounter the resolution of MethodHandleInError.
1042       // Both the first, (resolution of the BSM and its static arguments), and the second tasks,
1043       // (invocation of the BSM), of JVMS Section 5.4.3.6 occur within invoke_bootstrap_method()
1044       // for the bootstrap_specifier created above.
1045       SystemDictionary::invoke_bootstrap_method(bootstrap_specifier, THREAD);
1046       Exceptions::wrap_dynamic_exception(/* is_indy */ false, THREAD);
1047       if (HAS_PENDING_EXCEPTION) {
1048         // Resolution failure of the dynamically-computed constant, save_and_throw_exception
1049         // will check for a LinkageError and store a DynamicConstantInError.
1050         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1051       }
1052       result_oop = bootstrap_specifier.resolved_value()();
1053       BasicType type = Signature::basic_type(bootstrap_specifier.signature());
1054       if (!is_reference_type(type)) {
1055         // Make sure the primitive value is properly boxed.
1056         // This is a JDK responsibility.
1057         const char* fail = NULL;
1058         if (result_oop == NULL) {
1059           fail = "null result instead of box";
1060         } else if (!is_java_primitive(type)) {
1061           // FIXME: support value types via unboxing
1062           fail = "can only handle references and primitives";
1063         } else if (!java_lang_boxing_object::is_instance(result_oop, type)) {
1064           fail = "primitive is not properly boxed";
1065         }
1066         if (fail != NULL) {
1067           // Since this exception is not a LinkageError, throw exception
1068           // but do not save a DynamicInError resolution result.
1069           // See section 5.4.3 of the VM spec.
1070           THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), fail);
1071         }
1072       }
1073 
1074       LogTarget(Debug, methodhandles, condy) lt_condy;
1075       if (lt_condy.is_enabled()) {
1076         LogStream ls(lt_condy);
1077         bootstrap_specifier.print_msg_on(&ls, "resolve_constant_at_impl");
1078       }
1079       break;
1080     }
1081 
1082   case JVM_CONSTANT_String:
1083     assert(cache_index != _no_index_sentinel, "should have been set");
1084     result_oop = string_at_impl(this_cp, index, cache_index, CHECK_NULL);
1085     break;
1086 
1087   case JVM_CONSTANT_MethodHandle:
1088     {
1089       int ref_kind                 = this_cp->method_handle_ref_kind_at(index);
1090       int callee_index             = this_cp->method_handle_klass_index_at(index);
1091       Symbol*  name =      this_cp->method_handle_name_ref_at(index);
1092       Symbol*  signature = this_cp->method_handle_signature_ref_at(index);
1093       constantTag m_tag  = this_cp->tag_at(this_cp->method_handle_index_at(index));
1094       { ResourceMark rm(THREAD);
1095         log_debug(class, resolve)("resolve JVM_CONSTANT_MethodHandle:%d [%d/%d/%d] %s.%s",
1096                               ref_kind, index, this_cp->method_handle_index_at(index),
1097                               callee_index, name->as_C_string(), signature->as_C_string());
1098       }
1099 
1100       Klass* callee = klass_at_impl(this_cp, callee_index, THREAD);
1101       if (HAS_PENDING_EXCEPTION) {
1102         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1103       }
1104 
1105       // Check constant pool method consistency
1106       if ((callee->is_interface() && m_tag.is_method()) ||
1107           (!callee->is_interface() && m_tag.is_interface_method())) {
1108         ResourceMark rm(THREAD);
1109         stringStream ss;
1110         ss.print("Inconsistent constant pool data in classfile for class %s. "
1111                  "Method '", callee->name()->as_C_string());
1112         signature->print_as_signature_external_return_type(&ss);
1113         ss.print(" %s(", name->as_C_string());
1114         signature->print_as_signature_external_parameters(&ss);
1115         ss.print(")' at index %d is %s and should be %s",
1116                  index,
1117                  callee->is_interface() ? "CONSTANT_MethodRef" : "CONSTANT_InterfaceMethodRef",
1118                  callee->is_interface() ? "CONSTANT_InterfaceMethodRef" : "CONSTANT_MethodRef");
1119         Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IncompatibleClassChangeError(), "%s", ss.as_string());
1120         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1121       }
1122 
1123       Klass* klass = this_cp->pool_holder();
1124       Handle value = SystemDictionary::link_method_handle_constant(klass, ref_kind,
1125                                                                    callee, name, signature,
1126                                                                    THREAD);
1127       if (HAS_PENDING_EXCEPTION) {
1128         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1129       }
1130       result_oop = value();
1131       break;
1132     }
1133 
1134   case JVM_CONSTANT_MethodType:
1135     {
1136       Symbol*  signature = this_cp->method_type_signature_at(index);
1137       { ResourceMark rm(THREAD);
1138         log_debug(class, resolve)("resolve JVM_CONSTANT_MethodType [%d/%d] %s",
1139                               index, this_cp->method_type_index_at(index),
1140                               signature->as_C_string());
1141       }
1142       Klass* klass = this_cp->pool_holder();
1143       Handle value = SystemDictionary::find_method_handle_type(signature, klass, THREAD);
1144       result_oop = value();
1145       if (HAS_PENDING_EXCEPTION) {
1146         save_and_throw_exception(this_cp, index, tag, CHECK_NULL);
1147       }
1148       break;
1149     }
1150 
1151   case JVM_CONSTANT_Integer:
1152     assert(cache_index == _no_index_sentinel, "should not have been set");
1153     prim_value.i = this_cp->int_at(index);
1154     result_oop = java_lang_boxing_object::create(T_INT, &prim_value, CHECK_NULL);
1155     break;
1156 
1157   case JVM_CONSTANT_Float:
1158     assert(cache_index == _no_index_sentinel, "should not have been set");
1159     prim_value.f = this_cp->float_at(index);
1160     result_oop = java_lang_boxing_object::create(T_FLOAT, &prim_value, CHECK_NULL);
1161     break;
1162 
1163   case JVM_CONSTANT_Long:
1164     assert(cache_index == _no_index_sentinel, "should not have been set");
1165     prim_value.j = this_cp->long_at(index);
1166     result_oop = java_lang_boxing_object::create(T_LONG, &prim_value, CHECK_NULL);
1167     break;
1168 
1169   case JVM_CONSTANT_Double:
1170     assert(cache_index == _no_index_sentinel, "should not have been set");
1171     prim_value.d = this_cp->double_at(index);
1172     result_oop = java_lang_boxing_object::create(T_DOUBLE, &prim_value, CHECK_NULL);
1173     break;
1174 
1175   case JVM_CONSTANT_UnresolvedClassInError:
1176   case JVM_CONSTANT_DynamicInError:
1177   case JVM_CONSTANT_MethodHandleInError:
1178   case JVM_CONSTANT_MethodTypeInError:
1179     throw_resolution_error(this_cp, index, CHECK_NULL);
1180     break;
1181 
1182   default:
1183     fatal("unexpected constant tag at CP %p[%d/%d] = %d", this_cp(), index, cache_index, tag.value());
1184     break;
1185   }
1186 
1187   if (cache_index >= 0) {
1188     // Benign race condition:  resolved_references may already be filled in.
1189     // The important thing here is that all threads pick up the same result.
1190     // It doesn't matter which racing thread wins, as long as only one
1191     // result is used by all threads, and all future queries.
1192     oop new_result = (result_oop == NULL ? Universe::the_null_sentinel() : result_oop);
1193     oop old_result = this_cp->resolved_references()
1194       ->atomic_compare_exchange_oop(cache_index, new_result, NULL);
1195     if (old_result == NULL) {
1196       return result_oop;  // was installed
1197     } else {
1198       // Return the winning thread's result.  This can be different than
1199       // the result here for MethodHandles.
1200       if (old_result == Universe::the_null_sentinel())
1201         old_result = NULL;
1202       return old_result;
1203     }
1204   } else {
1205     assert(result_oop != Universe::the_null_sentinel(), "");
1206     return result_oop;
1207   }
1208 }
1209 
1210 oop ConstantPool::uncached_string_at(int which, TRAPS) {
1211   Symbol* sym = unresolved_string_at(which);
1212   oop str = StringTable::intern(sym, CHECK_(NULL));
1213   assert(java_lang_String::is_instance(str), "must be string");
1214   return str;
1215 }
1216 
1217 void ConstantPool::copy_bootstrap_arguments_at_impl(const constantPoolHandle& this_cp, int index,
1218                                                     int start_arg, int end_arg,
1219                                                     objArrayHandle info, int pos,
1220                                                     bool must_resolve, Handle if_not_available,
1221                                                     TRAPS) {
1222   int limit = pos + end_arg - start_arg;
1223   // checks: index in range [0..this_cp->length),
1224   // tag at index, start..end in range [0..this_cp->bootstrap_argument_count],
1225   // info array non-null, pos..limit in [0..info.length]
1226   if ((0 >= index    || index >= this_cp->length())  ||
1227       !(this_cp->tag_at(index).is_invoke_dynamic()    ||
1228         this_cp->tag_at(index).is_dynamic_constant()) ||
1229       (0 > start_arg || start_arg > end_arg) ||
1230       (end_arg > this_cp->bootstrap_argument_count_at(index)) ||
1231       (0 > pos       || pos > limit)         ||
1232       (info.is_null() || limit > info->length())) {
1233     // An index or something else went wrong; throw an error.
1234     // Since this is an internal API, we don't expect this,
1235     // so we don't bother to craft a nice message.
1236     THROW_MSG(vmSymbols::java_lang_LinkageError(), "bad BSM argument access");
1237   }
1238   // now we can loop safely
1239   int info_i = pos;
1240   for (int i = start_arg; i < end_arg; i++) {
1241     int arg_index = this_cp->bootstrap_argument_index_at(index, i);
1242     oop arg_oop;
1243     if (must_resolve) {
1244       arg_oop = this_cp->resolve_possibly_cached_constant_at(arg_index, CHECK);
1245     } else {
1246       bool found_it = false;
1247       arg_oop = this_cp->find_cached_constant_at(arg_index, found_it, CHECK);
1248       if (!found_it)  arg_oop = if_not_available();
1249     }
1250     info->obj_at_put(info_i++, arg_oop);
1251   }
1252 }
1253 
1254 oop ConstantPool::string_at_impl(const constantPoolHandle& this_cp, int which, int obj_index, TRAPS) {
1255   // If the string has already been interned, this entry will be non-null
1256   oop str = this_cp->resolved_references()->obj_at(obj_index);
1257   assert(str != Universe::the_null_sentinel(), "");
1258   if (str != NULL) return str;
1259   Symbol* sym = this_cp->unresolved_string_at(which);
1260   str = StringTable::intern(sym, CHECK_(NULL));
1261   this_cp->string_at_put(which, obj_index, str);
1262   assert(java_lang_String::is_instance(str), "must be string");
1263   return str;
1264 }
1265 
1266 
1267 bool ConstantPool::klass_name_at_matches(const InstanceKlass* k, int which) {
1268   // Names are interned, so we can compare Symbol*s directly
1269   Symbol* cp_name = klass_name_at(which);
1270   return (cp_name == k->name());
1271 }
1272 
1273 
1274 // Iterate over symbols and decrement ones which are Symbol*s
1275 // This is done during GC.
1276 // Only decrement the UTF8 symbols. Strings point to
1277 // these symbols but didn't increment the reference count.
1278 void ConstantPool::unreference_symbols() {
1279   for (int index = 1; index < length(); index++) { // Index 0 is unused
1280     constantTag tag = tag_at(index);
1281     if (tag.is_symbol()) {
1282       symbol_at(index)->decrement_refcount();
1283     }
1284   }
1285 }
1286 
1287 
1288 // Compare this constant pool's entry at index1 to the constant pool
1289 // cp2's entry at index2.
1290 bool ConstantPool::compare_entry_to(int index1, const constantPoolHandle& cp2,
1291        int index2) {
1292 
1293   // The error tags are equivalent to non-error tags when comparing
1294   jbyte t1 = tag_at(index1).non_error_value();
1295   jbyte t2 = cp2->tag_at(index2).non_error_value();
1296 
1297   if (t1 != t2) {
1298     // Not the same entry type so there is nothing else to check. Note
1299     // that this style of checking will consider resolved/unresolved
1300     // class pairs as different.
1301     // From the ConstantPool* API point of view, this is correct
1302     // behavior. See VM_RedefineClasses::merge_constant_pools() to see how this
1303     // plays out in the context of ConstantPool* merging.
1304     return false;
1305   }
1306 
1307   switch (t1) {
1308   case JVM_CONSTANT_Class:
1309   {
1310     Klass* k1 = resolved_klass_at(index1);
1311     Klass* k2 = cp2->resolved_klass_at(index2);
1312     if (k1 == k2) {
1313       return true;
1314     }
1315   } break;
1316 
1317   case JVM_CONSTANT_ClassIndex:
1318   {
1319     int recur1 = klass_index_at(index1);
1320     int recur2 = cp2->klass_index_at(index2);
1321     if (compare_entry_to(recur1, cp2, recur2)) {
1322       return true;
1323     }
1324   } break;
1325 
1326   case JVM_CONSTANT_Double:
1327   {
1328     jdouble d1 = double_at(index1);
1329     jdouble d2 = cp2->double_at(index2);
1330     if (d1 == d2) {
1331       return true;
1332     }
1333   } break;
1334 
1335   case JVM_CONSTANT_Fieldref:
1336   case JVM_CONSTANT_InterfaceMethodref:
1337   case JVM_CONSTANT_Methodref:
1338   {
1339     int recur1 = uncached_klass_ref_index_at(index1);
1340     int recur2 = cp2->uncached_klass_ref_index_at(index2);
1341     bool match = compare_entry_to(recur1, cp2, recur2);
1342     if (match) {
1343       recur1 = uncached_name_and_type_ref_index_at(index1);
1344       recur2 = cp2->uncached_name_and_type_ref_index_at(index2);
1345       if (compare_entry_to(recur1, cp2, recur2)) {
1346         return true;
1347       }
1348     }
1349   } break;
1350 
1351   case JVM_CONSTANT_Float:
1352   {
1353     jfloat f1 = float_at(index1);
1354     jfloat f2 = cp2->float_at(index2);
1355     if (f1 == f2) {
1356       return true;
1357     }
1358   } break;
1359 
1360   case JVM_CONSTANT_Integer:
1361   {
1362     jint i1 = int_at(index1);
1363     jint i2 = cp2->int_at(index2);
1364     if (i1 == i2) {
1365       return true;
1366     }
1367   } break;
1368 
1369   case JVM_CONSTANT_Long:
1370   {
1371     jlong l1 = long_at(index1);
1372     jlong l2 = cp2->long_at(index2);
1373     if (l1 == l2) {
1374       return true;
1375     }
1376   } break;
1377 
1378   case JVM_CONSTANT_NameAndType:
1379   {
1380     int recur1 = name_ref_index_at(index1);
1381     int recur2 = cp2->name_ref_index_at(index2);
1382     if (compare_entry_to(recur1, cp2, recur2)) {
1383       recur1 = signature_ref_index_at(index1);
1384       recur2 = cp2->signature_ref_index_at(index2);
1385       if (compare_entry_to(recur1, cp2, recur2)) {
1386         return true;
1387       }
1388     }
1389   } break;
1390 
1391   case JVM_CONSTANT_StringIndex:
1392   {
1393     int recur1 = string_index_at(index1);
1394     int recur2 = cp2->string_index_at(index2);
1395     if (compare_entry_to(recur1, cp2, recur2)) {
1396       return true;
1397     }
1398   } break;
1399 
1400   case JVM_CONSTANT_UnresolvedClass:
1401   {
1402     Symbol* k1 = klass_name_at(index1);
1403     Symbol* k2 = cp2->klass_name_at(index2);
1404     if (k1 == k2) {
1405       return true;
1406     }
1407   } break;
1408 
1409   case JVM_CONSTANT_MethodType:
1410   {
1411     int k1 = method_type_index_at(index1);
1412     int k2 = cp2->method_type_index_at(index2);
1413     if (compare_entry_to(k1, cp2, k2)) {
1414       return true;
1415     }
1416   } break;
1417 
1418   case JVM_CONSTANT_MethodHandle:
1419   {
1420     int k1 = method_handle_ref_kind_at(index1);
1421     int k2 = cp2->method_handle_ref_kind_at(index2);
1422     if (k1 == k2) {
1423       int i1 = method_handle_index_at(index1);
1424       int i2 = cp2->method_handle_index_at(index2);
1425       if (compare_entry_to(i1, cp2, i2)) {
1426         return true;
1427       }
1428     }
1429   } break;
1430 
1431   case JVM_CONSTANT_Dynamic:
1432   {
1433     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1434     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1435     int i1 = bootstrap_methods_attribute_index(index1);
1436     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1437     bool match_entry = compare_entry_to(k1, cp2, k2);
1438     bool match_operand = compare_operand_to(i1, cp2, i2);
1439     return (match_entry && match_operand);
1440   } break;
1441 
1442   case JVM_CONSTANT_InvokeDynamic:
1443   {
1444     int k1 = bootstrap_name_and_type_ref_index_at(index1);
1445     int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);
1446     int i1 = bootstrap_methods_attribute_index(index1);
1447     int i2 = cp2->bootstrap_methods_attribute_index(index2);
1448     bool match_entry = compare_entry_to(k1, cp2, k2);
1449     bool match_operand = compare_operand_to(i1, cp2, i2);
1450     return (match_entry && match_operand);
1451   } break;
1452 
1453   case JVM_CONSTANT_String:
1454   {
1455     Symbol* s1 = unresolved_string_at(index1);
1456     Symbol* s2 = cp2->unresolved_string_at(index2);
1457     if (s1 == s2) {
1458       return true;
1459     }
1460   } break;
1461 
1462   case JVM_CONSTANT_Utf8:
1463   {
1464     Symbol* s1 = symbol_at(index1);
1465     Symbol* s2 = cp2->symbol_at(index2);
1466     if (s1 == s2) {
1467       return true;
1468     }
1469   } break;
1470 
1471   // Invalid is used as the tag for the second constant pool entry
1472   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1473   // not be seen by itself.
1474   case JVM_CONSTANT_Invalid: // fall through
1475 
1476   default:
1477     ShouldNotReachHere();
1478     break;
1479   }
1480 
1481   return false;
1482 } // end compare_entry_to()
1483 
1484 
1485 // Resize the operands array with delta_len and delta_size.
1486 // Used in RedefineClasses for CP merge.
1487 void ConstantPool::resize_operands(int delta_len, int delta_size, TRAPS) {
1488   int old_len  = operand_array_length(operands());
1489   int new_len  = old_len + delta_len;
1490   int min_len  = (delta_len > 0) ? old_len : new_len;
1491 
1492   int old_size = operands()->length();
1493   int new_size = old_size + delta_size;
1494   int min_size = (delta_size > 0) ? old_size : new_size;
1495 
1496   ClassLoaderData* loader_data = pool_holder()->class_loader_data();
1497   Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, new_size, CHECK);
1498 
1499   // Set index in the resized array for existing elements only
1500   for (int idx = 0; idx < min_len; idx++) {
1501     int offset = operand_offset_at(idx);                       // offset in original array
1502     operand_offset_at_put(new_ops, idx, offset + 2*delta_len); // offset in resized array
1503   }
1504   // Copy the bootstrap specifiers only
1505   Copy::conjoint_memory_atomic(operands()->adr_at(2*old_len),
1506                                new_ops->adr_at(2*new_len),
1507                                (min_size - 2*min_len) * sizeof(u2));
1508   // Explicitly deallocate old operands array.
1509   // Note, it is not needed for 7u backport.
1510   if ( operands() != NULL) { // the safety check
1511     MetadataFactory::free_array<u2>(loader_data, operands());
1512   }
1513   set_operands(new_ops);
1514 } // end resize_operands()
1515 
1516 
1517 // Extend the operands array with the length and size of the ext_cp operands.
1518 // Used in RedefineClasses for CP merge.
1519 void ConstantPool::extend_operands(const constantPoolHandle& ext_cp, TRAPS) {
1520   int delta_len = operand_array_length(ext_cp->operands());
1521   if (delta_len == 0) {
1522     return; // nothing to do
1523   }
1524   int delta_size = ext_cp->operands()->length();
1525 
1526   assert(delta_len  > 0 && delta_size > 0, "extended operands array must be bigger");
1527 
1528   if (operand_array_length(operands()) == 0) {
1529     ClassLoaderData* loader_data = pool_holder()->class_loader_data();
1530     Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, delta_size, CHECK);
1531     // The first element index defines the offset of second part
1532     operand_offset_at_put(new_ops, 0, 2*delta_len); // offset in new array
1533     set_operands(new_ops);
1534   } else {
1535     resize_operands(delta_len, delta_size, CHECK);
1536   }
1537 
1538 } // end extend_operands()
1539 
1540 
1541 // Shrink the operands array to a smaller array with new_len length.
1542 // Used in RedefineClasses for CP merge.
1543 void ConstantPool::shrink_operands(int new_len, TRAPS) {
1544   int old_len = operand_array_length(operands());
1545   if (new_len == old_len) {
1546     return; // nothing to do
1547   }
1548   assert(new_len < old_len, "shrunken operands array must be smaller");
1549 
1550   int free_base  = operand_next_offset_at(new_len - 1);
1551   int delta_len  = new_len - old_len;
1552   int delta_size = 2*delta_len + free_base - operands()->length();
1553 
1554   resize_operands(delta_len, delta_size, CHECK);
1555 
1556 } // end shrink_operands()
1557 
1558 
1559 void ConstantPool::copy_operands(const constantPoolHandle& from_cp,
1560                                  const constantPoolHandle& to_cp,
1561                                  TRAPS) {
1562 
1563   int from_oplen = operand_array_length(from_cp->operands());
1564   int old_oplen  = operand_array_length(to_cp->operands());
1565   if (from_oplen != 0) {
1566     ClassLoaderData* loader_data = to_cp->pool_holder()->class_loader_data();
1567     // append my operands to the target's operands array
1568     if (old_oplen == 0) {
1569       // Can't just reuse from_cp's operand list because of deallocation issues
1570       int len = from_cp->operands()->length();
1571       Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, len, CHECK);
1572       Copy::conjoint_memory_atomic(
1573           from_cp->operands()->adr_at(0), new_ops->adr_at(0), len * sizeof(u2));
1574       to_cp->set_operands(new_ops);
1575     } else {
1576       int old_len  = to_cp->operands()->length();
1577       int from_len = from_cp->operands()->length();
1578       int old_off  = old_oplen * sizeof(u2);
1579       int from_off = from_oplen * sizeof(u2);
1580       // Use the metaspace for the destination constant pool
1581       Array<u2>* new_operands = MetadataFactory::new_array<u2>(loader_data, old_len + from_len, CHECK);
1582       int fillp = 0, len = 0;
1583       // first part of dest
1584       Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(0),
1585                                    new_operands->adr_at(fillp),
1586                                    (len = old_off) * sizeof(u2));
1587       fillp += len;
1588       // first part of src
1589       Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(0),
1590                                    new_operands->adr_at(fillp),
1591                                    (len = from_off) * sizeof(u2));
1592       fillp += len;
1593       // second part of dest
1594       Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(old_off),
1595                                    new_operands->adr_at(fillp),
1596                                    (len = old_len - old_off) * sizeof(u2));
1597       fillp += len;
1598       // second part of src
1599       Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(from_off),
1600                                    new_operands->adr_at(fillp),
1601                                    (len = from_len - from_off) * sizeof(u2));
1602       fillp += len;
1603       assert(fillp == new_operands->length(), "");
1604 
1605       // Adjust indexes in the first part of the copied operands array.
1606       for (int j = 0; j < from_oplen; j++) {
1607         int offset = operand_offset_at(new_operands, old_oplen + j);
1608         assert(offset == operand_offset_at(from_cp->operands(), j), "correct copy");
1609         offset += old_len;  // every new tuple is preceded by old_len extra u2's
1610         operand_offset_at_put(new_operands, old_oplen + j, offset);
1611       }
1612 
1613       // replace target operands array with combined array
1614       to_cp->set_operands(new_operands);
1615     }
1616   }
1617 } // end copy_operands()
1618 
1619 
1620 // Copy this constant pool's entries at start_i to end_i (inclusive)
1621 // to the constant pool to_cp's entries starting at to_i. A total of
1622 // (end_i - start_i) + 1 entries are copied.
1623 void ConstantPool::copy_cp_to_impl(const constantPoolHandle& from_cp, int start_i, int end_i,
1624        const constantPoolHandle& to_cp, int to_i, TRAPS) {
1625 
1626 
1627   int dest_i = to_i;  // leave original alone for debug purposes
1628 
1629   for (int src_i = start_i; src_i <= end_i; /* see loop bottom */ ) {
1630     copy_entry_to(from_cp, src_i, to_cp, dest_i);
1631 
1632     switch (from_cp->tag_at(src_i).value()) {
1633     case JVM_CONSTANT_Double:
1634     case JVM_CONSTANT_Long:
1635       // double and long take two constant pool entries
1636       src_i += 2;
1637       dest_i += 2;
1638       break;
1639 
1640     default:
1641       // all others take one constant pool entry
1642       src_i++;
1643       dest_i++;
1644       break;
1645     }
1646   }
1647   copy_operands(from_cp, to_cp, CHECK);
1648 
1649 } // end copy_cp_to_impl()
1650 
1651 
1652 // Copy this constant pool's entry at from_i to the constant pool
1653 // to_cp's entry at to_i.
1654 void ConstantPool::copy_entry_to(const constantPoolHandle& from_cp, int from_i,
1655                                         const constantPoolHandle& to_cp, int to_i) {
1656 
1657   int tag = from_cp->tag_at(from_i).value();
1658   switch (tag) {
1659   case JVM_CONSTANT_ClassIndex:
1660   {
1661     jint ki = from_cp->klass_index_at(from_i);
1662     to_cp->klass_index_at_put(to_i, ki);
1663   } break;
1664 
1665   case JVM_CONSTANT_Double:
1666   {
1667     jdouble d = from_cp->double_at(from_i);
1668     to_cp->double_at_put(to_i, d);
1669     // double takes two constant pool entries so init second entry's tag
1670     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1671   } break;
1672 
1673   case JVM_CONSTANT_Fieldref:
1674   {
1675     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1676     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1677     to_cp->field_at_put(to_i, class_index, name_and_type_index);
1678   } break;
1679 
1680   case JVM_CONSTANT_Float:
1681   {
1682     jfloat f = from_cp->float_at(from_i);
1683     to_cp->float_at_put(to_i, f);
1684   } break;
1685 
1686   case JVM_CONSTANT_Integer:
1687   {
1688     jint i = from_cp->int_at(from_i);
1689     to_cp->int_at_put(to_i, i);
1690   } break;
1691 
1692   case JVM_CONSTANT_InterfaceMethodref:
1693   {
1694     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1695     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1696     to_cp->interface_method_at_put(to_i, class_index, name_and_type_index);
1697   } break;
1698 
1699   case JVM_CONSTANT_Long:
1700   {
1701     jlong l = from_cp->long_at(from_i);
1702     to_cp->long_at_put(to_i, l);
1703     // long takes two constant pool entries so init second entry's tag
1704     to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
1705   } break;
1706 
1707   case JVM_CONSTANT_Methodref:
1708   {
1709     int class_index = from_cp->uncached_klass_ref_index_at(from_i);
1710     int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
1711     to_cp->method_at_put(to_i, class_index, name_and_type_index);
1712   } break;
1713 
1714   case JVM_CONSTANT_NameAndType:
1715   {
1716     int name_ref_index = from_cp->name_ref_index_at(from_i);
1717     int signature_ref_index = from_cp->signature_ref_index_at(from_i);
1718     to_cp->name_and_type_at_put(to_i, name_ref_index, signature_ref_index);
1719   } break;
1720 
1721   case JVM_CONSTANT_StringIndex:
1722   {
1723     jint si = from_cp->string_index_at(from_i);
1724     to_cp->string_index_at_put(to_i, si);
1725   } break;
1726 
1727   case JVM_CONSTANT_Class:
1728   case JVM_CONSTANT_UnresolvedClass:
1729   case JVM_CONSTANT_UnresolvedClassInError:
1730   {
1731     // Revert to JVM_CONSTANT_ClassIndex
1732     int name_index = from_cp->klass_slot_at(from_i).name_index();
1733     assert(from_cp->tag_at(name_index).is_symbol(), "sanity");
1734     to_cp->klass_index_at_put(to_i, name_index);
1735   } break;
1736 
1737   case JVM_CONSTANT_String:
1738   {
1739     Symbol* s = from_cp->unresolved_string_at(from_i);
1740     to_cp->unresolved_string_at_put(to_i, s);
1741   } break;
1742 
1743   case JVM_CONSTANT_Utf8:
1744   {
1745     Symbol* s = from_cp->symbol_at(from_i);
1746     // Need to increase refcount, the old one will be thrown away and deferenced
1747     s->increment_refcount();
1748     to_cp->symbol_at_put(to_i, s);
1749   } break;
1750 
1751   case JVM_CONSTANT_MethodType:
1752   case JVM_CONSTANT_MethodTypeInError:
1753   {
1754     jint k = from_cp->method_type_index_at(from_i);
1755     to_cp->method_type_index_at_put(to_i, k);
1756   } break;
1757 
1758   case JVM_CONSTANT_MethodHandle:
1759   case JVM_CONSTANT_MethodHandleInError:
1760   {
1761     int k1 = from_cp->method_handle_ref_kind_at(from_i);
1762     int k2 = from_cp->method_handle_index_at(from_i);
1763     to_cp->method_handle_index_at_put(to_i, k1, k2);
1764   } break;
1765 
1766   case JVM_CONSTANT_Dynamic:
1767   case JVM_CONSTANT_DynamicInError:
1768   {
1769     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1770     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1771     k1 += operand_array_length(to_cp->operands());  // to_cp might already have operands
1772     to_cp->dynamic_constant_at_put(to_i, k1, k2);
1773   } break;
1774 
1775   case JVM_CONSTANT_InvokeDynamic:
1776   {
1777     int k1 = from_cp->bootstrap_methods_attribute_index(from_i);
1778     int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);
1779     k1 += operand_array_length(to_cp->operands());  // to_cp might already have operands
1780     to_cp->invoke_dynamic_at_put(to_i, k1, k2);
1781   } break;
1782 
1783   // Invalid is used as the tag for the second constant pool entry
1784   // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
1785   // not be seen by itself.
1786   case JVM_CONSTANT_Invalid: // fall through
1787 
1788   default:
1789   {
1790     ShouldNotReachHere();
1791   } break;
1792   }
1793 } // end copy_entry_to()
1794 
1795 // Search constant pool search_cp for an entry that matches this
1796 // constant pool's entry at pattern_i. Returns the index of a
1797 // matching entry or zero (0) if there is no matching entry.
1798 int ConstantPool::find_matching_entry(int pattern_i,
1799       const constantPoolHandle& search_cp) {
1800 
1801   // index zero (0) is not used
1802   for (int i = 1; i < search_cp->length(); i++) {
1803     bool found = compare_entry_to(pattern_i, search_cp, i);
1804     if (found) {
1805       return i;
1806     }
1807   }
1808 
1809   return 0;  // entry not found; return unused index zero (0)
1810 } // end find_matching_entry()
1811 
1812 
1813 // Compare this constant pool's bootstrap specifier at idx1 to the constant pool
1814 // cp2's bootstrap specifier at idx2.
1815 bool ConstantPool::compare_operand_to(int idx1, const constantPoolHandle& cp2, int idx2) {
1816   int k1 = operand_bootstrap_method_ref_index_at(idx1);
1817   int k2 = cp2->operand_bootstrap_method_ref_index_at(idx2);
1818   bool match = compare_entry_to(k1, cp2, k2);
1819 
1820   if (!match) {
1821     return false;
1822   }
1823   int argc = operand_argument_count_at(idx1);
1824   if (argc == cp2->operand_argument_count_at(idx2)) {
1825     for (int j = 0; j < argc; j++) {
1826       k1 = operand_argument_index_at(idx1, j);
1827       k2 = cp2->operand_argument_index_at(idx2, j);
1828       match = compare_entry_to(k1, cp2, k2);
1829       if (!match) {
1830         return false;
1831       }
1832     }
1833     return true;           // got through loop; all elements equal
1834   }
1835   return false;
1836 } // end compare_operand_to()
1837 
1838 // Search constant pool search_cp for a bootstrap specifier that matches
1839 // this constant pool's bootstrap specifier data at pattern_i index.
1840 // Return the index of a matching bootstrap attribute record or (-1) if there is no match.
1841 int ConstantPool::find_matching_operand(int pattern_i,
1842                     const constantPoolHandle& search_cp, int search_len) {
1843   for (int i = 0; i < search_len; i++) {
1844     bool found = compare_operand_to(pattern_i, search_cp, i);
1845     if (found) {
1846       return i;
1847     }
1848   }
1849   return -1;  // bootstrap specifier data not found; return unused index (-1)
1850 } // end find_matching_operand()
1851 
1852 
1853 #ifndef PRODUCT
1854 
1855 const char* ConstantPool::printable_name_at(int which) {
1856 
1857   constantTag tag = tag_at(which);
1858 
1859   if (tag.is_string()) {
1860     return string_at_noresolve(which);
1861   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
1862     return klass_name_at(which)->as_C_string();
1863   } else if (tag.is_symbol()) {
1864     return symbol_at(which)->as_C_string();
1865   }
1866   return "";
1867 }
1868 
1869 #endif // PRODUCT
1870 
1871 
1872 // JVMTI GetConstantPool support
1873 
1874 // For debugging of constant pool
1875 const bool debug_cpool = false;
1876 
1877 #define DBG(code) do { if (debug_cpool) { (code); } } while(0)
1878 
1879 static void print_cpool_bytes(jint cnt, u1 *bytes) {
1880   const char* WARN_MSG = "Must not be such entry!";
1881   jint size = 0;
1882   u2   idx1, idx2;
1883 
1884   for (jint idx = 1; idx < cnt; idx++) {
1885     jint ent_size = 0;
1886     u1   tag  = *bytes++;
1887     size++;                       // count tag
1888 
1889     printf("const #%03d, tag: %02d ", idx, tag);
1890     switch(tag) {
1891       case JVM_CONSTANT_Invalid: {
1892         printf("Invalid");
1893         break;
1894       }
1895       case JVM_CONSTANT_Unicode: {
1896         printf("Unicode      %s", WARN_MSG);
1897         break;
1898       }
1899       case JVM_CONSTANT_Utf8: {
1900         u2 len = Bytes::get_Java_u2(bytes);
1901         char str[128];
1902         if (len > 127) {
1903            len = 127;
1904         }
1905         strncpy(str, (char *) (bytes+2), len);
1906         str[len] = '\0';
1907         printf("Utf8          \"%s\"", str);
1908         ent_size = 2 + len;
1909         break;
1910       }
1911       case JVM_CONSTANT_Integer: {
1912         u4 val = Bytes::get_Java_u4(bytes);
1913         printf("int          %d", *(int *) &val);
1914         ent_size = 4;
1915         break;
1916       }
1917       case JVM_CONSTANT_Float: {
1918         u4 val = Bytes::get_Java_u4(bytes);
1919         printf("float        %5.3ff", *(float *) &val);
1920         ent_size = 4;
1921         break;
1922       }
1923       case JVM_CONSTANT_Long: {
1924         u8 val = Bytes::get_Java_u8(bytes);
1925         printf("long         " INT64_FORMAT, (int64_t) *(jlong *) &val);
1926         ent_size = 8;
1927         idx++; // Long takes two cpool slots
1928         break;
1929       }
1930       case JVM_CONSTANT_Double: {
1931         u8 val = Bytes::get_Java_u8(bytes);
1932         printf("double       %5.3fd", *(jdouble *)&val);
1933         ent_size = 8;
1934         idx++; // Double takes two cpool slots
1935         break;
1936       }
1937       case JVM_CONSTANT_Class: {
1938         idx1 = Bytes::get_Java_u2(bytes);
1939         printf("class        #%03d", idx1);
1940         ent_size = 2;
1941         break;
1942       }
1943       case (JVM_CONSTANT_Class | JVM_CONSTANT_QDescBit): {
1944         idx1 = Bytes::get_Java_u2(bytes);
1945         printf("qclass        #%03d", idx1);
1946         ent_size = 2;
1947         break;
1948       }
1949       case JVM_CONSTANT_String: {
1950         idx1 = Bytes::get_Java_u2(bytes);
1951         printf("String       #%03d", idx1);
1952         ent_size = 2;
1953         break;
1954       }
1955       case JVM_CONSTANT_Fieldref: {
1956         idx1 = Bytes::get_Java_u2(bytes);
1957         idx2 = Bytes::get_Java_u2(bytes+2);
1958         printf("Field        #%03d, #%03d", (int) idx1, (int) idx2);
1959         ent_size = 4;
1960         break;
1961       }
1962       case JVM_CONSTANT_Methodref: {
1963         idx1 = Bytes::get_Java_u2(bytes);
1964         idx2 = Bytes::get_Java_u2(bytes+2);
1965         printf("Method       #%03d, #%03d", idx1, idx2);
1966         ent_size = 4;
1967         break;
1968       }
1969       case JVM_CONSTANT_InterfaceMethodref: {
1970         idx1 = Bytes::get_Java_u2(bytes);
1971         idx2 = Bytes::get_Java_u2(bytes+2);
1972         printf("InterfMethod #%03d, #%03d", idx1, idx2);
1973         ent_size = 4;
1974         break;
1975       }
1976       case JVM_CONSTANT_NameAndType: {
1977         idx1 = Bytes::get_Java_u2(bytes);
1978         idx2 = Bytes::get_Java_u2(bytes+2);
1979         printf("NameAndType  #%03d, #%03d", idx1, idx2);
1980         ent_size = 4;
1981         break;
1982       }
1983       case JVM_CONSTANT_ClassIndex: {
1984         printf("ClassIndex  %s", WARN_MSG);
1985         break;
1986       }
1987       case JVM_CONSTANT_UnresolvedClass: {
1988         printf("UnresolvedClass: %s", WARN_MSG);
1989         break;
1990       }
1991       case (JVM_CONSTANT_UnresolvedClass | JVM_CONSTANT_QDescBit): {
1992         printf("UnresolvedQClass: %s", WARN_MSG);
1993         break;
1994       }
1995       case JVM_CONSTANT_UnresolvedClassInError: {
1996         printf("UnresolvedClassInErr: %s", WARN_MSG);
1997         break;
1998       }
1999       case JVM_CONSTANT_StringIndex: {
2000         printf("StringIndex: %s", WARN_MSG);
2001         break;
2002       }
2003     }
2004     printf(";\n");
2005     bytes += ent_size;
2006     size  += ent_size;
2007   }
2008   printf("Cpool size: %d\n", size);
2009   fflush(0);
2010   return;
2011 } /* end print_cpool_bytes */
2012 
2013 
2014 // Returns size of constant pool entry.
2015 jint ConstantPool::cpool_entry_size(jint idx) {
2016   switch(tag_at(idx).value()) {
2017     case JVM_CONSTANT_Invalid:
2018     case JVM_CONSTANT_Unicode:
2019       return 1;
2020 
2021     case JVM_CONSTANT_Utf8:
2022       return 3 + symbol_at(idx)->utf8_length();
2023 
2024     case JVM_CONSTANT_Class:
2025     case JVM_CONSTANT_String:
2026     case JVM_CONSTANT_ClassIndex:
2027     case JVM_CONSTANT_UnresolvedClass:
2028     case JVM_CONSTANT_UnresolvedClassInError:
2029     case JVM_CONSTANT_StringIndex:
2030     case JVM_CONSTANT_MethodType:
2031     case JVM_CONSTANT_MethodTypeInError:
2032       return 3;
2033 
2034     case JVM_CONSTANT_MethodHandle:
2035     case JVM_CONSTANT_MethodHandleInError:
2036       return 4; //tag, ref_kind, ref_index
2037 
2038     case JVM_CONSTANT_Integer:
2039     case JVM_CONSTANT_Float:
2040     case JVM_CONSTANT_Fieldref:
2041     case JVM_CONSTANT_Methodref:
2042     case JVM_CONSTANT_InterfaceMethodref:
2043     case JVM_CONSTANT_NameAndType:
2044       return 5;
2045 
2046     case JVM_CONSTANT_Dynamic:
2047     case JVM_CONSTANT_DynamicInError:
2048     case JVM_CONSTANT_InvokeDynamic:
2049       // u1 tag, u2 bsm, u2 nt
2050       return 5;
2051 
2052     case JVM_CONSTANT_Long:
2053     case JVM_CONSTANT_Double:
2054       return 9;
2055   }
2056   assert(false, "cpool_entry_size: Invalid constant pool entry tag");
2057   return 1;
2058 } /* end cpool_entry_size */
2059 
2060 
2061 // SymbolHashMap is used to find a constant pool index from a string.
2062 // This function fills in SymbolHashMaps, one for utf8s and one for
2063 // class names, returns size of the cpool raw bytes.
2064 jint ConstantPool::hash_entries_to(SymbolHashMap *symmap,
2065                                           SymbolHashMap *classmap) {
2066   jint size = 0;
2067 
2068   for (u2 idx = 1; idx < length(); idx++) {
2069     u2 tag = tag_at(idx).value();
2070     size += cpool_entry_size(idx);
2071 
2072     switch(tag) {
2073       case JVM_CONSTANT_Utf8: {
2074         Symbol* sym = symbol_at(idx);
2075         symmap->add_entry(sym, idx);
2076         DBG(printf("adding symbol entry %s = %d\n", sym->as_utf8(), idx));
2077         break;
2078       }
2079       case JVM_CONSTANT_Class:
2080       case JVM_CONSTANT_UnresolvedClass:
2081       case JVM_CONSTANT_UnresolvedClassInError: {
2082         Symbol* sym = klass_name_at(idx);
2083         classmap->add_entry(sym, idx);
2084         DBG(printf("adding class entry %s = %d\n", sym->as_utf8(), idx));
2085         break;
2086       }
2087       case JVM_CONSTANT_Long:
2088       case JVM_CONSTANT_Double: {
2089         idx++; // Both Long and Double take two cpool slots
2090         break;
2091       }
2092     }
2093   }
2094   return size;
2095 } /* end hash_utf8_entries_to */
2096 
2097 
2098 // Copy cpool bytes.
2099 // Returns:
2100 //    0, in case of OutOfMemoryError
2101 //   -1, in case of internal error
2102 //  > 0, count of the raw cpool bytes that have been copied
2103 int ConstantPool::copy_cpool_bytes(int cpool_size,
2104                                           SymbolHashMap* tbl,
2105                                           unsigned char *bytes) {
2106   u2   idx1, idx2;
2107   jint size  = 0;
2108   jint cnt   = length();
2109   unsigned char *start_bytes = bytes;
2110 
2111   for (jint idx = 1; idx < cnt; idx++) {
2112     u1   tag      = tag_at(idx).value();
2113     jint ent_size = cpool_entry_size(idx);
2114 
2115     assert(size + ent_size <= cpool_size, "Size mismatch");
2116 
2117     *bytes = tag;
2118     DBG(printf("#%03hd tag=%03hd, ", (short)idx, (short)tag));
2119     switch(tag) {
2120       case JVM_CONSTANT_Invalid: {
2121         DBG(printf("JVM_CONSTANT_Invalid"));
2122         break;
2123       }
2124       case JVM_CONSTANT_Unicode: {
2125         assert(false, "Wrong constant pool tag: JVM_CONSTANT_Unicode");
2126         DBG(printf("JVM_CONSTANT_Unicode"));
2127         break;
2128       }
2129       case JVM_CONSTANT_Utf8: {
2130         Symbol* sym = symbol_at(idx);
2131         char*     str = sym->as_utf8();
2132         // Warning! It's crashing on x86 with len = sym->utf8_length()
2133         int       len = (int) strlen(str);
2134         Bytes::put_Java_u2((address) (bytes+1), (u2) len);
2135         for (int i = 0; i < len; i++) {
2136             bytes[3+i] = (u1) str[i];
2137         }
2138         DBG(printf("JVM_CONSTANT_Utf8: %s ", str));
2139         break;
2140       }
2141       case JVM_CONSTANT_Integer: {
2142         jint val = int_at(idx);
2143         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2144         break;
2145       }
2146       case JVM_CONSTANT_Float: {
2147         jfloat val = float_at(idx);
2148         Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
2149         break;
2150       }
2151       case JVM_CONSTANT_Long: {
2152         jlong val = long_at(idx);
2153         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2154         idx++;             // Long takes two cpool slots
2155         break;
2156       }
2157       case JVM_CONSTANT_Double: {
2158         jdouble val = double_at(idx);
2159         Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
2160         idx++;             // Double takes two cpool slots
2161         break;
2162       }
2163       case JVM_CONSTANT_Class:
2164       case JVM_CONSTANT_UnresolvedClass:
2165       case JVM_CONSTANT_UnresolvedClassInError: {
2166         *bytes = JVM_CONSTANT_Class;
2167         Symbol* sym = klass_name_at(idx);
2168         idx1 = tbl->symbol_to_value(sym);
2169         assert(idx1 != 0, "Have not found a hashtable entry");
2170         Bytes::put_Java_u2((address) (bytes+1), idx1);
2171         DBG(printf("JVM_CONSTANT_Class: idx=#%03hd, %s", idx1, sym->as_utf8()));
2172         break;
2173       }
2174       case JVM_CONSTANT_String: {
2175         *bytes = JVM_CONSTANT_String;
2176         Symbol* sym = unresolved_string_at(idx);
2177         idx1 = tbl->symbol_to_value(sym);
2178         assert(idx1 != 0, "Have not found a hashtable entry");
2179         Bytes::put_Java_u2((address) (bytes+1), idx1);
2180         DBG(printf("JVM_CONSTANT_String: idx=#%03hd, %s", idx1, sym->as_utf8()));
2181         break;
2182       }
2183       case JVM_CONSTANT_Fieldref:
2184       case JVM_CONSTANT_Methodref:
2185       case JVM_CONSTANT_InterfaceMethodref: {
2186         idx1 = uncached_klass_ref_index_at(idx);
2187         idx2 = uncached_name_and_type_ref_index_at(idx);
2188         Bytes::put_Java_u2((address) (bytes+1), idx1);
2189         Bytes::put_Java_u2((address) (bytes+3), idx2);
2190         DBG(printf("JVM_CONSTANT_Methodref: %hd %hd", idx1, idx2));
2191         break;
2192       }
2193       case JVM_CONSTANT_NameAndType: {
2194         idx1 = name_ref_index_at(idx);
2195         idx2 = signature_ref_index_at(idx);
2196         Bytes::put_Java_u2((address) (bytes+1), idx1);
2197         Bytes::put_Java_u2((address) (bytes+3), idx2);
2198         DBG(printf("JVM_CONSTANT_NameAndType: %hd %hd", idx1, idx2));
2199         break;
2200       }
2201       case JVM_CONSTANT_ClassIndex: {
2202         *bytes = JVM_CONSTANT_Class;
2203         idx1 = klass_index_at(idx);
2204         Bytes::put_Java_u2((address) (bytes+1), idx1);
2205         DBG(printf("JVM_CONSTANT_ClassIndex: %hd", idx1));
2206         break;
2207       }
2208       case JVM_CONSTANT_StringIndex: {
2209         *bytes = JVM_CONSTANT_String;
2210         idx1 = string_index_at(idx);
2211         Bytes::put_Java_u2((address) (bytes+1), idx1);
2212         DBG(printf("JVM_CONSTANT_StringIndex: %hd", idx1));
2213         break;
2214       }
2215       case JVM_CONSTANT_MethodHandle:
2216       case JVM_CONSTANT_MethodHandleInError: {
2217         *bytes = JVM_CONSTANT_MethodHandle;
2218         int kind = method_handle_ref_kind_at(idx);
2219         idx1 = method_handle_index_at(idx);
2220         *(bytes+1) = (unsigned char) kind;
2221         Bytes::put_Java_u2((address) (bytes+2), idx1);
2222         DBG(printf("JVM_CONSTANT_MethodHandle: %d %hd", kind, idx1));
2223         break;
2224       }
2225       case JVM_CONSTANT_MethodType:
2226       case JVM_CONSTANT_MethodTypeInError: {
2227         *bytes = JVM_CONSTANT_MethodType;
2228         idx1 = method_type_index_at(idx);
2229         Bytes::put_Java_u2((address) (bytes+1), idx1);
2230         DBG(printf("JVM_CONSTANT_MethodType: %hd", idx1));
2231         break;
2232       }
2233       case JVM_CONSTANT_Dynamic:
2234       case JVM_CONSTANT_DynamicInError: {
2235         *bytes = tag;
2236         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2237         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2238         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2239         Bytes::put_Java_u2((address) (bytes+1), idx1);
2240         Bytes::put_Java_u2((address) (bytes+3), idx2);
2241         DBG(printf("JVM_CONSTANT_Dynamic: %hd %hd", idx1, idx2));
2242         break;
2243       }
2244       case JVM_CONSTANT_InvokeDynamic: {
2245         *bytes = tag;
2246         idx1 = extract_low_short_from_int(*int_at_addr(idx));
2247         idx2 = extract_high_short_from_int(*int_at_addr(idx));
2248         assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");
2249         Bytes::put_Java_u2((address) (bytes+1), idx1);
2250         Bytes::put_Java_u2((address) (bytes+3), idx2);
2251         DBG(printf("JVM_CONSTANT_InvokeDynamic: %hd %hd", idx1, idx2));
2252         break;
2253       }
2254     }
2255     DBG(printf("\n"));
2256     bytes += ent_size;
2257     size  += ent_size;
2258   }
2259   assert(size == cpool_size, "Size mismatch");
2260 
2261   // Keep temorarily for debugging until it's stable.
2262   DBG(print_cpool_bytes(cnt, start_bytes));
2263   return (int)(bytes - start_bytes);
2264 } /* end copy_cpool_bytes */
2265 
2266 #undef DBG
2267 
2268 
2269 void ConstantPool::set_on_stack(const bool value) {
2270   if (value) {
2271     // Only record if it's not already set.
2272     if (!on_stack()) {
2273       assert(!is_shared(), "should always be set for shared constant pools");
2274       _flags |= _on_stack;
2275       MetadataOnStackMark::record(this);
2276     }
2277   } else {
2278     // Clearing is done single-threadedly.
2279     if (!is_shared()) {
2280       _flags &= ~_on_stack;
2281     }
2282   }
2283 }
2284 
2285 // Printing
2286 
2287 void ConstantPool::print_on(outputStream* st) const {
2288   assert(is_constantPool(), "must be constantPool");
2289   st->print_cr("%s", internal_name());
2290   if (flags() != 0) {
2291     st->print(" - flags: 0x%x", flags());
2292     if (has_preresolution()) st->print(" has_preresolution");
2293     if (on_stack()) st->print(" on_stack");
2294     st->cr();
2295   }
2296   if (pool_holder() != NULL) {
2297     st->print_cr(" - holder: " INTPTR_FORMAT, p2i(pool_holder()));
2298   }
2299   st->print_cr(" - cache: " INTPTR_FORMAT, p2i(cache()));
2300   st->print_cr(" - resolved_references: " INTPTR_FORMAT, p2i(resolved_references()));
2301   st->print_cr(" - reference_map: " INTPTR_FORMAT, p2i(reference_map()));
2302   st->print_cr(" - resolved_klasses: " INTPTR_FORMAT, p2i(resolved_klasses()));
2303 
2304   for (int index = 1; index < length(); index++) {      // Index 0 is unused
2305     ((ConstantPool*)this)->print_entry_on(index, st);
2306     switch (tag_at(index).value()) {
2307       case JVM_CONSTANT_Long :
2308       case JVM_CONSTANT_Double :
2309         index++;   // Skip entry following eigth-byte constant
2310     }
2311 
2312   }
2313   st->cr();
2314 }
2315 
2316 // Print one constant pool entry
2317 void ConstantPool::print_entry_on(const int index, outputStream* st) {
2318   EXCEPTION_MARK;
2319   st->print(" - %3d : ", index);
2320   tag_at(index).print_on(st);
2321   st->print(" : ");
2322   switch (tag_at(index).value()) {
2323     case JVM_CONSTANT_Class :
2324       { Klass* k = klass_at(index, CATCH);
2325         guarantee(k != NULL, "need klass");
2326         k->print_value_on(st);
2327         st->print(" {" PTR_FORMAT "}", p2i(k));
2328       }
2329       break;
2330     case JVM_CONSTANT_Fieldref :
2331     case JVM_CONSTANT_Methodref :
2332     case JVM_CONSTANT_InterfaceMethodref :
2333       st->print("klass_index=%d", uncached_klass_ref_index_at(index));
2334       st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(index));
2335       break;
2336     case JVM_CONSTANT_String :
2337       unresolved_string_at(index)->print_value_on(st);
2338       break;
2339     case JVM_CONSTANT_Integer :
2340       st->print("%d", int_at(index));
2341       break;
2342     case JVM_CONSTANT_Float :
2343       st->print("%f", float_at(index));
2344       break;
2345     case JVM_CONSTANT_Long :
2346       st->print_jlong(long_at(index));
2347       break;
2348     case JVM_CONSTANT_Double :
2349       st->print("%lf", double_at(index));
2350       break;
2351     case JVM_CONSTANT_NameAndType :
2352       st->print("name_index=%d", name_ref_index_at(index));
2353       st->print(" signature_index=%d", signature_ref_index_at(index));
2354       break;
2355     case JVM_CONSTANT_Utf8 :
2356       symbol_at(index)->print_value_on(st);
2357       break;
2358     case JVM_CONSTANT_ClassIndex: {
2359         int name_index = *int_at_addr(index);
2360         st->print("klass_index=%d ", name_index);
2361         symbol_at(name_index)->print_value_on(st);
2362       }
2363       break;
2364     case JVM_CONSTANT_UnresolvedClass :               // fall-through
2365     case JVM_CONSTANT_UnresolvedClassInError: {
2366         CPKlassSlot kslot = klass_slot_at(index);
2367         int resolved_klass_index = kslot.resolved_klass_index();
2368         int name_index = kslot.name_index();
2369         assert(tag_at(name_index).is_symbol(), "sanity");
2370         symbol_at(name_index)->print_value_on(st);
2371       }
2372       break;
2373     case JVM_CONSTANT_MethodHandle :
2374     case JVM_CONSTANT_MethodHandleInError :
2375       st->print("ref_kind=%d", method_handle_ref_kind_at(index));
2376       st->print(" ref_index=%d", method_handle_index_at(index));
2377       break;
2378     case JVM_CONSTANT_MethodType :
2379     case JVM_CONSTANT_MethodTypeInError :
2380       st->print("signature_index=%d", method_type_index_at(index));
2381       break;
2382     case JVM_CONSTANT_Dynamic :
2383     case JVM_CONSTANT_DynamicInError :
2384       {
2385         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));
2386         st->print(" type_index=%d", bootstrap_name_and_type_ref_index_at(index));
2387         int argc = bootstrap_argument_count_at(index);
2388         if (argc > 0) {
2389           for (int arg_i = 0; arg_i < argc; arg_i++) {
2390             int arg = bootstrap_argument_index_at(index, arg_i);
2391             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2392           }
2393           st->print("}");
2394         }
2395       }
2396       break;
2397     case JVM_CONSTANT_InvokeDynamic :
2398       {
2399         st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));
2400         st->print(" name_and_type_index=%d", bootstrap_name_and_type_ref_index_at(index));
2401         int argc = bootstrap_argument_count_at(index);
2402         if (argc > 0) {
2403           for (int arg_i = 0; arg_i < argc; arg_i++) {
2404             int arg = bootstrap_argument_index_at(index, arg_i);
2405             st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
2406           }
2407           st->print("}");
2408         }
2409       }
2410       break;
2411     default:
2412       ShouldNotReachHere();
2413       break;
2414   }
2415   st->cr();
2416 }
2417 
2418 void ConstantPool::print_value_on(outputStream* st) const {
2419   assert(is_constantPool(), "must be constantPool");
2420   st->print("constant pool [%d]", length());
2421   if (has_preresolution()) st->print("/preresolution");
2422   if (operands() != NULL)  st->print("/operands[%d]", operands()->length());
2423   print_address_on(st);
2424   if (pool_holder() != NULL) {
2425     st->print(" for ");
2426     pool_holder()->print_value_on(st);
2427     bool extra = (pool_holder()->constants() != this);
2428     if (extra)  st->print(" (extra)");
2429   }
2430   if (cache() != NULL) {
2431     st->print(" cache=" PTR_FORMAT, p2i(cache()));
2432   }
2433 }
2434 
2435 // Verification
2436 
2437 void ConstantPool::verify_on(outputStream* st) {
2438   guarantee(is_constantPool(), "object must be constant pool");
2439   for (int i = 0; i< length();  i++) {
2440     constantTag tag = tag_at(i);
2441     if (tag.is_klass() || tag.is_unresolved_klass()) {
2442       guarantee(klass_name_at(i)->refcount() != 0, "should have nonzero reference count");
2443     } else if (tag.is_symbol()) {
2444       Symbol* entry = symbol_at(i);
2445       guarantee(entry->refcount() != 0, "should have nonzero reference count");
2446     } else if (tag.is_string()) {
2447       Symbol* entry = unresolved_string_at(i);
2448       guarantee(entry->refcount() != 0, "should have nonzero reference count");
2449     }
2450   }
2451   if (pool_holder() != NULL) {
2452     // Note: pool_holder() can be NULL in temporary constant pools
2453     // used during constant pool merging
2454     guarantee(pool_holder()->is_klass(),    "should be klass");
2455   }
2456 }
2457 
2458 
2459 SymbolHashMap::~SymbolHashMap() {
2460   SymbolHashMapEntry* next;
2461   for (int i = 0; i < _table_size; i++) {
2462     for (SymbolHashMapEntry* cur = bucket(i); cur != NULL; cur = next) {
2463       next = cur->next();
2464       delete(cur);
2465     }
2466   }
2467   FREE_C_HEAP_ARRAY(SymbolHashMapBucket, _buckets);
2468 }
2469 
2470 void SymbolHashMap::add_entry(Symbol* sym, u2 value) {
2471   char *str = sym->as_utf8();
2472   unsigned int hash = compute_hash(str, sym->utf8_length());
2473   unsigned int index = hash % table_size();
2474 
2475   // check if already in map
2476   // we prefer the first entry since it is more likely to be what was used in
2477   // the class file
2478   for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {
2479     assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
2480     if (en->hash() == hash && en->symbol() == sym) {
2481         return;  // already there
2482     }
2483   }
2484 
2485   SymbolHashMapEntry* entry = new SymbolHashMapEntry(hash, sym, value);
2486   entry->set_next(bucket(index));
2487   _buckets[index].set_entry(entry);
2488   assert(entry->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
2489 }
2490 
2491 SymbolHashMapEntry* SymbolHashMap::find_entry(Symbol* sym) {
2492   assert(sym != NULL, "SymbolHashMap::find_entry - symbol is NULL");
2493   char *str = sym->as_utf8();
2494   int   len = sym->utf8_length();
2495   unsigned int hash = SymbolHashMap::compute_hash(str, len);
2496   unsigned int index = hash % table_size();
2497   for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {
2498     assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
2499     if (en->hash() == hash && en->symbol() == sym) {
2500       return en;
2501     }
2502   }
2503   return NULL;
2504 }
2505 
2506 void SymbolHashMap::initialize_table(int table_size) {
2507   _table_size = table_size;
2508   _buckets = NEW_C_HEAP_ARRAY(SymbolHashMapBucket, table_size, mtSymbol);
2509   for (int index = 0; index < table_size; index++) {
2510     _buckets[index].clear();
2511   }
2512 }