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