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