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