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