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