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