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