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