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