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