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