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