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