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