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