1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #ifndef SHARE_VM_OOPS_CONSTANTPOOLOOP_HPP
  26 #define SHARE_VM_OOPS_CONSTANTPOOLOOP_HPP
  27 
  28 #include "oops/arrayOop.hpp"
  29 #include "oops/cpCache.hpp"
  30 #include "oops/objArrayOop.hpp"
  31 #include "oops/symbol.hpp"
  32 #include "oops/typeArrayOop.hpp"
  33 #include "runtime/handles.hpp"
  34 #include "utilities/constantTag.hpp"
  35 #ifdef TARGET_ARCH_x86
  36 # include "bytes_x86.hpp"
  37 #endif
  38 #ifdef TARGET_ARCH_aarch64
  39 # include "bytes_aarch64.hpp"
  40 #endif
  41 #ifdef TARGET_ARCH_sparc
  42 # include "bytes_sparc.hpp"
  43 #endif
  44 #ifdef TARGET_ARCH_zero
  45 # include "bytes_zero.hpp"
  46 #endif
  47 #ifdef TARGET_ARCH_arm
  48 # include "bytes_arm.hpp"
  49 #endif
  50 #ifdef TARGET_ARCH_ppc
  51 # include "bytes_ppc.hpp"
  52 #endif
  53 
  54 // A constantPool is an array containing class constants as described in the
  55 // class file.
  56 //
  57 // Most of the constant pool entries are written during class parsing, which
  58 // is safe.  For klass types, the constant pool entry is
  59 // modified when the entry is resolved.  If a klass constant pool
  60 // entry is read without a lock, only the resolved state guarantees that
  61 // the entry in the constant pool is a klass object and not a Symbol*.
  62 
  63 class SymbolHashMap;
  64 
  65 class CPSlot VALUE_OBJ_CLASS_SPEC {
  66   intptr_t _ptr;
  67  public:
  68   CPSlot(intptr_t ptr): _ptr(ptr) {}
  69   CPSlot(Klass* ptr): _ptr((intptr_t)ptr) {}
  70   CPSlot(Symbol* ptr): _ptr((intptr_t)ptr | 1) {}
  71 
  72   intptr_t value()   { return _ptr; }
  73   bool is_resolved()   { return (_ptr & 1) == 0; }
  74   bool is_unresolved() { return (_ptr & 1) == 1; }
  75 
  76   Symbol* get_symbol() {
  77     assert(is_unresolved(), "bad call");
  78     return (Symbol*)(_ptr & ~1);
  79   }
  80   Klass* get_klass() {
  81     assert(is_resolved(), "bad call");
  82     return (Klass*)_ptr;
  83   }
  84 };
  85 
  86 class KlassSizeStats;
  87 class ConstantPool : public Metadata {
  88   friend class VMStructs;
  89   friend class BytecodeInterpreter;  // Directly extracts an oop in the pool for fast instanceof/checkcast
  90   friend class Universe;             // For null constructor
  91  private:
  92   Array<u1>*           _tags;        // the tag array describing the constant pool's contents
  93   ConstantPoolCache*   _cache;       // the cache holding interpreter runtime information
  94   InstanceKlass*       _pool_holder; // the corresponding class
  95   Array<u2>*           _operands;    // for variable-sized (InvokeDynamic) nodes, usually empty
  96 
  97   // Array of resolved objects from the constant pool and map from resolved
  98   // object index to original constant pool index
  99   jobject              _resolved_references;
 100   Array<u2>*           _reference_map;
 101 
 102   enum {
 103     _has_preresolution = 1,           // Flags
 104     _on_stack          = 2
 105   };
 106 
 107   int                  _flags;  // old fashioned bit twiddling
 108   int                  _length; // number of elements in the array
 109 
 110   union {
 111     // set for CDS to restore resolved references
 112     int                _resolved_reference_length;
 113     // keeps version number for redefined classes (used in backtrace)
 114     int                _version;
 115   } _saved;
 116 
 117   Monitor*             _lock;
 118 
 119   void set_tags(Array<u1>* tags)               { _tags = tags; }
 120   void tag_at_put(int which, jbyte t)          { tags()->at_put(which, t); }
 121   void release_tag_at_put(int which, jbyte t)  { tags()->release_at_put(which, t); }
 122 
 123   void set_operands(Array<u2>* operands)       { _operands = operands; }
 124 
 125   int flags() const                            { return _flags; }
 126   void set_flags(int f)                        { _flags = f; }
 127 
 128  private:
 129   intptr_t* base() const { return (intptr_t*) (((char*) this) + sizeof(ConstantPool)); }
 130 
 131   CPSlot slot_at(int which) {
 132     assert(is_within_bounds(which), "index out of bounds");
 133     // Uses volatile because the klass slot changes without a lock.
 134     volatile intptr_t adr = (intptr_t)OrderAccess::load_ptr_acquire(obj_at_addr_raw(which));
 135     assert(adr != 0 || which == 0, "cp entry for klass should not be zero");
 136     return CPSlot(adr);
 137   }
 138 
 139   void slot_at_put(int which, CPSlot s) const {
 140     assert(is_within_bounds(which), "index out of bounds");
 141     assert(s.value() != 0, "Caught something");
 142     *(intptr_t*)&base()[which] = s.value();
 143   }
 144   intptr_t* obj_at_addr_raw(int which) const {
 145     assert(is_within_bounds(which), "index out of bounds");
 146     return (intptr_t*) &base()[which];
 147   }
 148 
 149   jint* int_at_addr(int which) const {
 150     assert(is_within_bounds(which), "index out of bounds");
 151     return (jint*) &base()[which];
 152   }
 153 
 154   jlong* long_at_addr(int which) const {
 155     assert(is_within_bounds(which), "index out of bounds");
 156     return (jlong*) &base()[which];
 157   }
 158 
 159   jfloat* float_at_addr(int which) const {
 160     assert(is_within_bounds(which), "index out of bounds");
 161     return (jfloat*) &base()[which];
 162   }
 163 
 164   jdouble* double_at_addr(int which) const {
 165     assert(is_within_bounds(which), "index out of bounds");
 166     return (jdouble*) &base()[which];
 167   }
 168 
 169   ConstantPool(Array<u1>* tags);
 170   ConstantPool() { assert(DumpSharedSpaces || UseSharedSpaces, "only for CDS"); }
 171  public:
 172   static ConstantPool* allocate(ClassLoaderData* loader_data, int length, TRAPS);
 173 
 174   bool is_constantPool() const volatile     { return true; }
 175 
 176   Array<u1>* tags() const                   { return _tags; }
 177   Array<u2>* operands() const               { return _operands; }
 178 
 179   bool has_preresolution() const            { return (_flags & _has_preresolution) != 0; }
 180   void set_has_preresolution()              { _flags |= _has_preresolution; }
 181 
 182   // Redefine classes support.  If a method refering to this constant pool
 183   // is on the executing stack, or as a handle in vm code, this constant pool
 184   // can't be removed from the set of previous versions saved in the instance
 185   // class.
 186   bool on_stack() const                      { return (_flags &_on_stack) != 0; }
 187   void set_on_stack(const bool value);
 188 
 189   // Klass holding pool
 190   InstanceKlass* pool_holder() const      { return _pool_holder; }
 191   void set_pool_holder(InstanceKlass* k)  { _pool_holder = k; }
 192   InstanceKlass** pool_holder_addr()      { return &_pool_holder; }
 193 
 194   // Interpreter runtime support
 195   ConstantPoolCache* cache() const        { return _cache; }
 196   void set_cache(ConstantPoolCache* cache){ _cache = cache; }
 197 
 198   // Create object cache in the constant pool
 199   void initialize_resolved_references(ClassLoaderData* loader_data,
 200                                       intStack reference_map,
 201                                       int constant_pool_map_length,
 202                                       TRAPS);
 203 
 204   // resolved strings, methodHandles and callsite objects from the constant pool
 205   objArrayOop resolved_references()  const;
 206   objArrayOop resolved_references_or_null()  const;
 207   // mapping resolved object array indexes to cp indexes and back.
 208   int object_to_cp_index(int index)         { return _reference_map->at(index); }
 209   int cp_to_object_index(int index);
 210 
 211   // Invokedynamic indexes.
 212   // They must look completely different from normal indexes.
 213   // The main reason is that byte swapping is sometimes done on normal indexes.
 214   // Finally, it is helpful for debugging to tell the two apart.
 215   static bool is_invokedynamic_index(int i) { return (i < 0); }
 216   static int  decode_invokedynamic_index(int i) { assert(is_invokedynamic_index(i),  ""); return ~i; }
 217   static int  encode_invokedynamic_index(int i) { assert(!is_invokedynamic_index(i), ""); return ~i; }
 218 
 219 
 220   // The invokedynamic points at a CP cache entry.  This entry points back
 221   // at the original CP entry (CONSTANT_InvokeDynamic) and also (via f2) at an entry
 222   // in the resolved_references array (which provides the appendix argument).
 223   int invokedynamic_cp_cache_index(int index) const {
 224     assert (is_invokedynamic_index(index), "should be a invokedynamic index");
 225     int cache_index = decode_invokedynamic_index(index);
 226     return cache_index;
 227   }
 228   ConstantPoolCacheEntry* invokedynamic_cp_cache_entry_at(int index) const {
 229     // decode index that invokedynamic points to.
 230     int cp_cache_index = invokedynamic_cp_cache_index(index);
 231     return cache()->entry_at(cp_cache_index);
 232   }
 233 
 234   // Assembly code support
 235   static int tags_offset_in_bytes()         { return offset_of(ConstantPool, _tags); }
 236   static int cache_offset_in_bytes()        { return offset_of(ConstantPool, _cache); }
 237   static int pool_holder_offset_in_bytes()  { return offset_of(ConstantPool, _pool_holder); }
 238   static int resolved_references_offset_in_bytes() { return offset_of(ConstantPool, _resolved_references); }
 239 
 240   // Storing constants
 241 
 242   void klass_at_put(int which, Klass* k) {
 243     assert(k != NULL, "resolved class shouldn't be null");
 244     assert(is_within_bounds(which), "index out of bounds");
 245     OrderAccess::release_store_ptr((Klass* volatile *)obj_at_addr_raw(which), k);
 246     // The interpreter assumes when the tag is stored, the klass is resolved
 247     // and the Klass* is a klass rather than a Symbol*, so we need
 248     // hardware store ordering here.
 249     release_tag_at_put(which, JVM_CONSTANT_Class);
 250   }
 251 
 252   // For temporary use while constructing constant pool
 253   void klass_index_at_put(int which, int name_index) {
 254     tag_at_put(which, JVM_CONSTANT_ClassIndex);
 255     *int_at_addr(which) = name_index;
 256   }
 257 
 258   // Temporary until actual use
 259   void unresolved_klass_at_put(int which, Symbol* s) {
 260     release_tag_at_put(which, JVM_CONSTANT_UnresolvedClass);
 261     slot_at_put(which, s);
 262   }
 263 
 264   void method_handle_index_at_put(int which, int ref_kind, int ref_index) {
 265     tag_at_put(which, JVM_CONSTANT_MethodHandle);
 266     *int_at_addr(which) = ((jint) ref_index<<16) | ref_kind;
 267   }
 268 
 269   void method_type_index_at_put(int which, int ref_index) {
 270     tag_at_put(which, JVM_CONSTANT_MethodType);
 271     *int_at_addr(which) = ref_index;
 272   }
 273 
 274   void invoke_dynamic_at_put(int which, int bootstrap_specifier_index, int name_and_type_index) {
 275     tag_at_put(which, JVM_CONSTANT_InvokeDynamic);
 276     *int_at_addr(which) = ((jint) name_and_type_index<<16) | bootstrap_specifier_index;
 277   }
 278 
 279   void unresolved_string_at_put(int which, Symbol* s) {
 280     release_tag_at_put(which, JVM_CONSTANT_String);
 281     *symbol_at_addr(which) = s;
 282   }
 283 
 284   void int_at_put(int which, jint i) {
 285     tag_at_put(which, JVM_CONSTANT_Integer);
 286     *int_at_addr(which) = i;
 287   }
 288 
 289   void long_at_put(int which, jlong l) {
 290     tag_at_put(which, JVM_CONSTANT_Long);
 291     // *long_at_addr(which) = l;
 292     Bytes::put_native_u8((address)long_at_addr(which), *((u8*) &l));
 293   }
 294 
 295   void float_at_put(int which, jfloat f) {
 296     tag_at_put(which, JVM_CONSTANT_Float);
 297     *float_at_addr(which) = f;
 298   }
 299 
 300   void double_at_put(int which, jdouble d) {
 301     tag_at_put(which, JVM_CONSTANT_Double);
 302     // *double_at_addr(which) = d;
 303     // u8 temp = *(u8*) &d;
 304     Bytes::put_native_u8((address) double_at_addr(which), *((u8*) &d));
 305   }
 306 
 307   Symbol** symbol_at_addr(int which) const {
 308     assert(is_within_bounds(which), "index out of bounds");
 309     return (Symbol**) &base()[which];
 310   }
 311 
 312   void symbol_at_put(int which, Symbol* s) {
 313     assert(s->refcount() != 0, "should have nonzero refcount");
 314     tag_at_put(which, JVM_CONSTANT_Utf8);
 315     *symbol_at_addr(which) = s;
 316   }
 317 
 318   void string_at_put(int which, int obj_index, oop str) {
 319     resolved_references()->obj_at_put(obj_index, str);
 320   }
 321 
 322   // For temporary use while constructing constant pool
 323   void string_index_at_put(int which, int string_index) {
 324     tag_at_put(which, JVM_CONSTANT_StringIndex);
 325     *int_at_addr(which) = string_index;
 326   }
 327 
 328   void field_at_put(int which, int class_index, int name_and_type_index) {
 329     tag_at_put(which, JVM_CONSTANT_Fieldref);
 330     *int_at_addr(which) = ((jint) name_and_type_index<<16) | class_index;
 331   }
 332 
 333   void method_at_put(int which, int class_index, int name_and_type_index) {
 334     tag_at_put(which, JVM_CONSTANT_Methodref);
 335     *int_at_addr(which) = ((jint) name_and_type_index<<16) | class_index;
 336   }
 337 
 338   void interface_method_at_put(int which, int class_index, int name_and_type_index) {
 339     tag_at_put(which, JVM_CONSTANT_InterfaceMethodref);
 340     *int_at_addr(which) = ((jint) name_and_type_index<<16) | class_index;  // Not so nice
 341   }
 342 
 343   void name_and_type_at_put(int which, int name_index, int signature_index) {
 344     tag_at_put(which, JVM_CONSTANT_NameAndType);
 345     *int_at_addr(which) = ((jint) signature_index<<16) | name_index;  // Not so nice
 346   }
 347 
 348   // Tag query
 349 
 350   constantTag tag_at(int which) const { return (constantTag)tags()->at_acquire(which); }
 351 
 352   // Fetching constants
 353 
 354   Klass* klass_at(int which, TRAPS) {
 355     constantPoolHandle h_this(THREAD, this);
 356     return klass_at_impl(h_this, which, CHECK_NULL);
 357   }
 358 
 359   Symbol* klass_name_at(int which);  // Returns the name, w/o resolving.
 360 
 361   Klass* resolved_klass_at(int which) const {  // Used by Compiler
 362     guarantee(tag_at(which).is_klass(), "Corrupted constant pool");
 363     // Must do an acquire here in case another thread resolved the klass
 364     // behind our back, lest we later load stale values thru the oop.
 365     return CPSlot((Klass*)OrderAccess::load_ptr_acquire(obj_at_addr_raw(which))).get_klass();
 366   }
 367 
 368   // This method should only be used with a cpool lock or during parsing or gc
 369   Symbol* unresolved_klass_at(int which) {     // Temporary until actual use
 370     Symbol* s = CPSlot((Symbol*)OrderAccess::load_ptr_acquire(obj_at_addr_raw(which))).get_symbol();
 371     // check that the klass is still unresolved.
 372     assert(tag_at(which).is_unresolved_klass(), "Corrupted constant pool");
 373     return s;
 374   }
 375 
 376   // RedefineClasses() API support:
 377   Symbol* klass_at_noresolve(int which) { return klass_name_at(which); }
 378 
 379   jint int_at(int which) {
 380     assert(tag_at(which).is_int(), "Corrupted constant pool");
 381     return *int_at_addr(which);
 382   }
 383 
 384   jlong long_at(int which) {
 385     assert(tag_at(which).is_long(), "Corrupted constant pool");
 386     // return *long_at_addr(which);
 387     u8 tmp = Bytes::get_native_u8((address)&base()[which]);
 388     return *((jlong*)&tmp);
 389   }
 390 
 391   jfloat float_at(int which) {
 392     assert(tag_at(which).is_float(), "Corrupted constant pool");
 393     return *float_at_addr(which);
 394   }
 395 
 396   jdouble double_at(int which) {
 397     assert(tag_at(which).is_double(), "Corrupted constant pool");
 398     u8 tmp = Bytes::get_native_u8((address)&base()[which]);
 399     return *((jdouble*)&tmp);
 400   }
 401 
 402   Symbol* symbol_at(int which) {
 403     assert(tag_at(which).is_utf8(), "Corrupted constant pool");
 404     return *symbol_at_addr(which);
 405   }
 406 
 407   oop string_at(int which, int obj_index, TRAPS) {
 408     constantPoolHandle h_this(THREAD, this);
 409     return string_at_impl(h_this, which, obj_index, THREAD);
 410   }
 411   oop string_at(int which, TRAPS) {
 412     int obj_index = cp_to_object_index(which);
 413     return string_at(which, obj_index, THREAD);
 414   }
 415 
 416   // Version that can be used before string oop array is created.
 417   oop uncached_string_at(int which, TRAPS);
 418 
 419   // A "pseudo-string" is an non-string oop that has found is way into
 420   // a String entry.
 421   // Under EnableInvokeDynamic this can happen if the user patches a live
 422   // object into a CONSTANT_String entry of an anonymous class.
 423   // Method oops internally created for method handles may also
 424   // use pseudo-strings to link themselves to related metaobjects.
 425 
 426   bool is_pseudo_string_at(int which) {
 427     // A pseudo string is a string that doesn't have a symbol in the cpSlot
 428     return unresolved_string_at(which) == NULL;
 429   }
 430 
 431   oop pseudo_string_at(int which, int obj_index) {
 432     assert(tag_at(which).is_string(), "Corrupted constant pool");
 433     assert(unresolved_string_at(which) == NULL, "shouldn't have symbol");
 434     oop s = resolved_references()->obj_at(obj_index);
 435     return s;
 436   }
 437 
 438   oop pseudo_string_at(int which) {
 439     assert(tag_at(which).is_string(), "Corrupted constant pool");
 440     assert(unresolved_string_at(which) == NULL, "shouldn't have symbol");
 441     int obj_index = cp_to_object_index(which);
 442     oop s = resolved_references()->obj_at(obj_index);
 443     return s;
 444   }
 445 
 446   void pseudo_string_at_put(int which, int obj_index, oop x) {
 447     assert(EnableInvokeDynamic, "");
 448     assert(tag_at(which).is_string(), "Corrupted constant pool");
 449     unresolved_string_at_put(which, NULL); // indicates patched string
 450     string_at_put(which, obj_index, x);    // this works just fine
 451   }
 452 
 453   // only called when we are sure a string entry is already resolved (via an
 454   // earlier string_at call.
 455   oop resolved_string_at(int which) {
 456     assert(tag_at(which).is_string(), "Corrupted constant pool");
 457     // Must do an acquire here in case another thread resolved the klass
 458     // behind our back, lest we later load stale values thru the oop.
 459     // we might want a volatile_obj_at in ObjArrayKlass.
 460     int obj_index = cp_to_object_index(which);
 461     return resolved_references()->obj_at(obj_index);
 462   }
 463 
 464   Symbol* unresolved_string_at(int which) {
 465     assert(tag_at(which).is_string(), "Corrupted constant pool");
 466     Symbol* s = *symbol_at_addr(which);
 467     return s;
 468   }
 469 
 470   // Returns an UTF8 for a CONSTANT_String entry at a given index.
 471   // UTF8 char* representation was chosen to avoid conversion of
 472   // java_lang_Strings at resolved entries into Symbol*s
 473   // or vice versa.
 474   // Caller is responsible for checking for pseudo-strings.
 475   char* string_at_noresolve(int which);
 476 
 477   jint name_and_type_at(int which) {
 478     assert(tag_at(which).is_name_and_type(), "Corrupted constant pool");
 479     return *int_at_addr(which);
 480   }
 481 
 482  private:
 483   int method_handle_ref_kind_at(int which, bool error_ok) {
 484     assert(tag_at(which).is_method_handle() ||
 485            (error_ok && tag_at(which).is_method_handle_in_error()), "Corrupted constant pool");
 486     return extract_low_short_from_int(*int_at_addr(which));  // mask out unwanted ref_index bits
 487   }
 488   int method_handle_index_at(int which, bool error_ok) {
 489     assert(tag_at(which).is_method_handle() ||
 490            (error_ok && tag_at(which).is_method_handle_in_error()), "Corrupted constant pool");
 491     return extract_high_short_from_int(*int_at_addr(which));  // shift out unwanted ref_kind bits
 492   }
 493   int method_type_index_at(int which, bool error_ok) {
 494     assert(tag_at(which).is_method_type() ||
 495            (error_ok && tag_at(which).is_method_type_in_error()), "Corrupted constant pool");
 496     return *int_at_addr(which);
 497   }
 498  public:
 499   int method_handle_ref_kind_at(int which) {
 500     return method_handle_ref_kind_at(which, false);
 501   }
 502   int method_handle_ref_kind_at_error_ok(int which) {
 503     return method_handle_ref_kind_at(which, true);
 504   }
 505   int method_handle_index_at(int which) {
 506     return method_handle_index_at(which, false);
 507   }
 508   int method_handle_index_at_error_ok(int which) {
 509     return method_handle_index_at(which, true);
 510   }
 511   int method_type_index_at(int which) {
 512     return method_type_index_at(which, false);
 513   }
 514   int method_type_index_at_error_ok(int which) {
 515     return method_type_index_at(which, true);
 516   }
 517 
 518   // Derived queries:
 519   Symbol* method_handle_name_ref_at(int which) {
 520     int member = method_handle_index_at(which);
 521     return impl_name_ref_at(member, true);
 522   }
 523   Symbol* method_handle_signature_ref_at(int which) {
 524     int member = method_handle_index_at(which);
 525     return impl_signature_ref_at(member, true);
 526   }
 527   int method_handle_klass_index_at(int which) {
 528     int member = method_handle_index_at(which);
 529     return impl_klass_ref_index_at(member, true);
 530   }
 531   Symbol* method_type_signature_at(int which) {
 532     int sym = method_type_index_at(which);
 533     return symbol_at(sym);
 534   }
 535 
 536   int invoke_dynamic_name_and_type_ref_index_at(int which) {
 537     assert(tag_at(which).is_invoke_dynamic(), "Corrupted constant pool");
 538     return extract_high_short_from_int(*int_at_addr(which));
 539   }
 540   int invoke_dynamic_bootstrap_specifier_index(int which) {
 541     assert(tag_at(which).value() == JVM_CONSTANT_InvokeDynamic, "Corrupted constant pool");
 542     return extract_low_short_from_int(*int_at_addr(which));
 543   }
 544   int invoke_dynamic_operand_base(int which) {
 545     int bootstrap_specifier_index = invoke_dynamic_bootstrap_specifier_index(which);
 546     return operand_offset_at(operands(), bootstrap_specifier_index);
 547   }
 548   // The first part of the operands array consists of an index into the second part.
 549   // Extract a 32-bit index value from the first part.
 550   static int operand_offset_at(Array<u2>* operands, int bootstrap_specifier_index) {
 551     int n = (bootstrap_specifier_index * 2);
 552     assert(n >= 0 && n+2 <= operands->length(), "oob");
 553     // The first 32-bit index points to the beginning of the second part
 554     // of the operands array.  Make sure this index is in the first part.
 555     DEBUG_ONLY(int second_part = build_int_from_shorts(operands->at(0),
 556                                                        operands->at(1)));
 557     assert(second_part == 0 || n+2 <= second_part, "oob (2)");
 558     int offset = build_int_from_shorts(operands->at(n+0),
 559                                        operands->at(n+1));
 560     // The offset itself must point into the second part of the array.
 561     assert(offset == 0 || offset >= second_part && offset <= operands->length(), "oob (3)");
 562     return offset;
 563   }
 564   static void operand_offset_at_put(Array<u2>* operands, int bootstrap_specifier_index, int offset) {
 565     int n = bootstrap_specifier_index * 2;
 566     assert(n >= 0 && n+2 <= operands->length(), "oob");
 567     operands->at_put(n+0, extract_low_short_from_int(offset));
 568     operands->at_put(n+1, extract_high_short_from_int(offset));
 569   }
 570   static int operand_array_length(Array<u2>* operands) {
 571     if (operands == NULL || operands->length() == 0)  return 0;
 572     int second_part = operand_offset_at(operands, 0);
 573     return (second_part / 2);
 574   }
 575 
 576 #ifdef ASSERT
 577   // operand tuples fit together exactly, end to end
 578   static int operand_limit_at(Array<u2>* operands, int bootstrap_specifier_index) {
 579     int nextidx = bootstrap_specifier_index + 1;
 580     if (nextidx == operand_array_length(operands))
 581       return operands->length();
 582     else
 583       return operand_offset_at(operands, nextidx);
 584   }
 585   int invoke_dynamic_operand_limit(int which) {
 586     int bootstrap_specifier_index = invoke_dynamic_bootstrap_specifier_index(which);
 587     return operand_limit_at(operands(), bootstrap_specifier_index);
 588   }
 589 #endif //ASSERT
 590 
 591   // layout of InvokeDynamic bootstrap method specifier (in second part of operands array):
 592   enum {
 593          _indy_bsm_offset  = 0,  // CONSTANT_MethodHandle bsm
 594          _indy_argc_offset = 1,  // u2 argc
 595          _indy_argv_offset = 2   // u2 argv[argc]
 596   };
 597 
 598   // These functions are used in RedefineClasses for CP merge
 599 
 600   int operand_offset_at(int bootstrap_specifier_index) {
 601     assert(0 <= bootstrap_specifier_index &&
 602            bootstrap_specifier_index < operand_array_length(operands()),
 603            "Corrupted CP operands");
 604     return operand_offset_at(operands(), bootstrap_specifier_index);
 605   }
 606   int operand_bootstrap_method_ref_index_at(int bootstrap_specifier_index) {
 607     int offset = operand_offset_at(bootstrap_specifier_index);
 608     return operands()->at(offset + _indy_bsm_offset);
 609   }
 610   int operand_argument_count_at(int bootstrap_specifier_index) {
 611     int offset = operand_offset_at(bootstrap_specifier_index);
 612     int argc = operands()->at(offset + _indy_argc_offset);
 613     return argc;
 614   }
 615   int operand_argument_index_at(int bootstrap_specifier_index, int j) {
 616     int offset = operand_offset_at(bootstrap_specifier_index);
 617     return operands()->at(offset + _indy_argv_offset + j);
 618   }
 619   int operand_next_offset_at(int bootstrap_specifier_index) {
 620     int offset = operand_offset_at(bootstrap_specifier_index) + _indy_argv_offset
 621                    + operand_argument_count_at(bootstrap_specifier_index);
 622     return offset;
 623   }
 624   // Compare a bootsrap specifier in the operands arrays
 625   bool compare_operand_to(int bootstrap_specifier_index1, constantPoolHandle cp2,
 626                           int bootstrap_specifier_index2, TRAPS);
 627   // Find a bootsrap specifier in the operands array
 628   int find_matching_operand(int bootstrap_specifier_index, constantPoolHandle search_cp,
 629                             int operands_cur_len, TRAPS);
 630   // Resize the operands array with delta_len and delta_size
 631   void resize_operands(int delta_len, int delta_size, TRAPS);
 632   // Extend the operands array with the length and size of the ext_cp operands
 633   void extend_operands(constantPoolHandle ext_cp, TRAPS);
 634   // Shrink the operands array to a smaller array with new_len length
 635   void shrink_operands(int new_len, TRAPS);
 636 
 637 
 638   int invoke_dynamic_bootstrap_method_ref_index_at(int which) {
 639     assert(tag_at(which).is_invoke_dynamic(), "Corrupted constant pool");
 640     int op_base = invoke_dynamic_operand_base(which);
 641     return operands()->at(op_base + _indy_bsm_offset);
 642   }
 643   int invoke_dynamic_argument_count_at(int which) {
 644     assert(tag_at(which).is_invoke_dynamic(), "Corrupted constant pool");
 645     int op_base = invoke_dynamic_operand_base(which);
 646     int argc = operands()->at(op_base + _indy_argc_offset);
 647     DEBUG_ONLY(int end_offset = op_base + _indy_argv_offset + argc;
 648                int next_offset = invoke_dynamic_operand_limit(which));
 649     assert(end_offset == next_offset, "matched ending");
 650     return argc;
 651   }
 652   int invoke_dynamic_argument_index_at(int which, int j) {
 653     int op_base = invoke_dynamic_operand_base(which);
 654     DEBUG_ONLY(int argc = operands()->at(op_base + _indy_argc_offset));
 655     assert((uint)j < (uint)argc, "oob");
 656     return operands()->at(op_base + _indy_argv_offset + j);
 657   }
 658 
 659   // The following methods (name/signature/klass_ref_at, klass_ref_at_noresolve,
 660   // name_and_type_ref_index_at) all expect to be passed indices obtained
 661   // directly from the bytecode.
 662   // If the indices are meant to refer to fields or methods, they are
 663   // actually rewritten constant pool cache indices.
 664   // The routine remap_instruction_operand_from_cache manages the adjustment
 665   // of these values back to constant pool indices.
 666 
 667   // There are also "uncached" versions which do not adjust the operand index; see below.
 668 
 669   // FIXME: Consider renaming these with a prefix "cached_" to make the distinction clear.
 670   // In a few cases (the verifier) there are uses before a cpcache has been built,
 671   // which are handled by a dynamic check in remap_instruction_operand_from_cache.
 672   // FIXME: Remove the dynamic check, and adjust all callers to specify the correct mode.
 673 
 674   // Lookup for entries consisting of (klass_index, name_and_type index)
 675   Klass* klass_ref_at(int which, TRAPS);
 676   Symbol* klass_ref_at_noresolve(int which);
 677   Symbol* name_ref_at(int which)                { return impl_name_ref_at(which, false); }
 678   Symbol* signature_ref_at(int which)           { return impl_signature_ref_at(which, false); }
 679 
 680   int klass_ref_index_at(int which)               { return impl_klass_ref_index_at(which, false); }
 681   int name_and_type_ref_index_at(int which)       { return impl_name_and_type_ref_index_at(which, false); }
 682 
 683   // Lookup for entries consisting of (name_index, signature_index)
 684   int name_ref_index_at(int which_nt);            // ==  low-order jshort of name_and_type_at(which_nt)
 685   int signature_ref_index_at(int which_nt);       // == high-order jshort of name_and_type_at(which_nt)
 686 
 687   BasicType basic_type_for_signature_at(int which);
 688 
 689   // Resolve string constants (to prevent allocation during compilation)
 690   void resolve_string_constants(TRAPS) {
 691     constantPoolHandle h_this(THREAD, this);
 692     resolve_string_constants_impl(h_this, CHECK);
 693   }
 694 
 695   // CDS support
 696   void remove_unshareable_info();
 697   void restore_unshareable_info(TRAPS);
 698   bool resolve_class_constants(TRAPS);
 699   // The ConstantPool vtable is restored by this call when the ConstantPool is
 700   // in the shared archive.  See patch_klass_vtables() in metaspaceShared.cpp for
 701   // all the gory details.  SA, dtrace and pstack helpers distinguish metadata
 702   // by their vtable.
 703   void restore_vtable() { guarantee(is_constantPool(), "vtable restored by this call"); }
 704 
 705  private:
 706   enum { _no_index_sentinel = -1, _possible_index_sentinel = -2 };
 707  public:
 708 
 709   // Resolve late bound constants.
 710   oop resolve_constant_at(int index, TRAPS) {
 711     constantPoolHandle h_this(THREAD, this);
 712     return resolve_constant_at_impl(h_this, index, _no_index_sentinel, THREAD);
 713   }
 714 
 715   oop resolve_cached_constant_at(int cache_index, TRAPS) {
 716     constantPoolHandle h_this(THREAD, this);
 717     return resolve_constant_at_impl(h_this, _no_index_sentinel, cache_index, THREAD);
 718   }
 719 
 720   oop resolve_possibly_cached_constant_at(int pool_index, TRAPS) {
 721     constantPoolHandle h_this(THREAD, this);
 722     return resolve_constant_at_impl(h_this, pool_index, _possible_index_sentinel, THREAD);
 723   }
 724 
 725   oop resolve_bootstrap_specifier_at(int index, TRAPS) {
 726     constantPoolHandle h_this(THREAD, this);
 727     return resolve_bootstrap_specifier_at_impl(h_this, index, THREAD);
 728   }
 729 
 730   // Klass name matches name at offset
 731   bool klass_name_at_matches(instanceKlassHandle k, int which);
 732 
 733   // Sizing
 734   int length() const                   { return _length; }
 735   void set_length(int length)          { _length = length; }
 736 
 737   // Tells whether index is within bounds.
 738   bool is_within_bounds(int index) const {
 739     return 0 <= index && index < length();
 740   }
 741 
 742   // Sizing (in words)
 743   static int header_size()             { return sizeof(ConstantPool)/HeapWordSize; }
 744   static int size(int length)          { return align_object_size(header_size() + length); }
 745   int size() const                     { return size(length()); }
 746 #if INCLUDE_SERVICES
 747   void collect_statistics(KlassSizeStats *sz) const;
 748 #endif
 749 
 750   friend class ClassFileParser;
 751   friend class SystemDictionary;
 752 
 753   // Used by compiler to prevent classloading.
 754   static Method*          method_at_if_loaded      (constantPoolHandle this_oop, int which);
 755   static bool       has_appendix_at_if_loaded      (constantPoolHandle this_oop, int which);
 756   static oop            appendix_at_if_loaded      (constantPoolHandle this_oop, int which);
 757   static bool    has_method_type_at_if_loaded      (constantPoolHandle this_oop, int which);
 758   static oop         method_type_at_if_loaded      (constantPoolHandle this_oop, int which);
 759   static Klass*            klass_at_if_loaded      (constantPoolHandle this_oop, int which);
 760   static Klass*        klass_ref_at_if_loaded      (constantPoolHandle this_oop, int which);
 761 
 762   // Routines currently used for annotations (only called by jvm.cpp) but which might be used in the
 763   // future by other Java code. These take constant pool indices rather than
 764   // constant pool cache indices as do the peer methods above.
 765   Symbol* uncached_klass_ref_at_noresolve(int which);
 766   Symbol* uncached_name_ref_at(int which)                 { return impl_name_ref_at(which, true); }
 767   Symbol* uncached_signature_ref_at(int which)            { return impl_signature_ref_at(which, true); }
 768   int       uncached_klass_ref_index_at(int which)          { return impl_klass_ref_index_at(which, true); }
 769   int       uncached_name_and_type_ref_index_at(int which)  { return impl_name_and_type_ref_index_at(which, true); }
 770 
 771   // Sharing
 772   int pre_resolve_shared_klasses(TRAPS);
 773 
 774   // Debugging
 775   const char* printable_name_at(int which) PRODUCT_RETURN0;
 776 
 777 #ifdef ASSERT
 778   enum { CPCACHE_INDEX_TAG = 0x10000 };  // helps keep CP cache indices distinct from CP indices
 779 #else
 780   enum { CPCACHE_INDEX_TAG = 0 };        // in product mode, this zero value is a no-op
 781 #endif //ASSERT
 782 
 783   static int decode_cpcache_index(int raw_index, bool invokedynamic_ok = false) {
 784     if (invokedynamic_ok && is_invokedynamic_index(raw_index))
 785       return decode_invokedynamic_index(raw_index);
 786     else
 787       return raw_index - CPCACHE_INDEX_TAG;
 788   }
 789 
 790  private:
 791 
 792   void set_resolved_references(jobject s) { _resolved_references = s; }
 793   Array<u2>* reference_map() const        { return _reference_map; }
 794   void set_reference_map(Array<u2>* o)    { _reference_map = o; }
 795 
 796   // patch JSR 292 resolved references after the class is linked.
 797   void patch_resolved_references(GrowableArray<Handle>* cp_patches);
 798 
 799   Symbol* impl_name_ref_at(int which, bool uncached);
 800   Symbol* impl_signature_ref_at(int which, bool uncached);
 801   int       impl_klass_ref_index_at(int which, bool uncached);
 802   int       impl_name_and_type_ref_index_at(int which, bool uncached);
 803 
 804   int remap_instruction_operand_from_cache(int operand);  // operand must be biased by CPCACHE_INDEX_TAG
 805 
 806   // Used while constructing constant pool (only by ClassFileParser)
 807   jint klass_index_at(int which) {
 808     assert(tag_at(which).is_klass_index(), "Corrupted constant pool");
 809     return *int_at_addr(which);
 810   }
 811 
 812   jint string_index_at(int which) {
 813     assert(tag_at(which).is_string_index(), "Corrupted constant pool");
 814     return *int_at_addr(which);
 815   }
 816 
 817   // Performs the LinkResolver checks
 818   static void verify_constant_pool_resolve(constantPoolHandle this_oop, KlassHandle klass, TRAPS);
 819 
 820   // Implementation of methods that needs an exposed 'this' pointer, in order to
 821   // handle GC while executing the method
 822   static Klass* klass_at_impl(constantPoolHandle this_oop, int which, TRAPS);
 823   static oop string_at_impl(constantPoolHandle this_oop, int which, int obj_index, TRAPS);
 824 
 825   // Resolve string constants (to prevent allocation during compilation)
 826   static void resolve_string_constants_impl(constantPoolHandle this_oop, TRAPS);
 827 
 828   static oop resolve_constant_at_impl(constantPoolHandle this_oop, int index, int cache_index, TRAPS);
 829   static oop resolve_bootstrap_specifier_at_impl(constantPoolHandle this_oop, int index, TRAPS);
 830 
 831   // Exception handling
 832   static void throw_resolution_error(constantPoolHandle this_oop, int which, TRAPS);
 833   static Symbol* exception_message(constantPoolHandle this_oop, int which, constantTag tag, oop pending_exception);
 834   static void save_and_throw_exception(constantPoolHandle this_oop, int which, constantTag tag, TRAPS);
 835 
 836  public:
 837   // Merging ConstantPool* support:
 838   bool compare_entry_to(int index1, constantPoolHandle cp2, int index2, TRAPS);
 839   void copy_cp_to(int start_i, int end_i, constantPoolHandle to_cp, int to_i, TRAPS) {
 840     constantPoolHandle h_this(THREAD, this);
 841     copy_cp_to_impl(h_this, start_i, end_i, to_cp, to_i, THREAD);
 842   }
 843   static void copy_cp_to_impl(constantPoolHandle from_cp, int start_i, int end_i, constantPoolHandle to_cp, int to_i, TRAPS);
 844   static void copy_entry_to(constantPoolHandle from_cp, int from_i, constantPoolHandle to_cp, int to_i, TRAPS);
 845   static void copy_operands(constantPoolHandle from_cp, constantPoolHandle to_cp, TRAPS);
 846   int  find_matching_entry(int pattern_i, constantPoolHandle search_cp, TRAPS);
 847   int  version() const                    { return _saved._version; }
 848   void set_version(int version)           { _saved._version = version; }
 849   void increment_and_save_version(int version) {
 850     _saved._version = version >= 0 ? (version + 1) : version;  // keep overflow
 851   }
 852 
 853   void set_resolved_reference_length(int length) { _saved._resolved_reference_length = length; }
 854   int  resolved_reference_length() const  { return _saved._resolved_reference_length; }
 855   void set_lock(Monitor* lock)            { _lock = lock; }
 856   Monitor* lock()                         { return _lock; }
 857 
 858   // Decrease ref counts of symbols that are in the constant pool
 859   // when the holder class is unloaded
 860   void unreference_symbols();
 861 
 862   // Deallocate constant pool for RedefineClasses
 863   void deallocate_contents(ClassLoaderData* loader_data);
 864   void release_C_heap_structures();
 865 
 866   // JVMTI accesss - GetConstantPool, RetransformClasses, ...
 867   friend class JvmtiConstantPoolReconstituter;
 868 
 869  private:
 870   jint cpool_entry_size(jint idx);
 871   jint hash_entries_to(SymbolHashMap *symmap, SymbolHashMap *classmap);
 872 
 873   // Copy cpool bytes into byte array.
 874   // Returns:
 875   //  int > 0, count of the raw cpool bytes that have been copied
 876   //        0, OutOfMemory error
 877   //       -1, Internal error
 878   int  copy_cpool_bytes(int cpool_size,
 879                         SymbolHashMap* tbl,
 880                         unsigned char *bytes);
 881 
 882  public:
 883   // Verify
 884   void verify_on(outputStream* st);
 885 
 886   // Printing
 887   void print_on(outputStream* st) const;
 888   void print_value_on(outputStream* st) const;
 889   void print_entry_on(int index, outputStream* st);
 890 
 891   const char* internal_name() const { return "{constant pool}"; }
 892 
 893 #ifndef PRODUCT
 894   // Compile the world support
 895   static void preload_and_initialize_all_classes(ConstantPool* constant_pool, TRAPS);
 896 #endif
 897 };
 898 
 899 class SymbolHashMapEntry : public CHeapObj<mtSymbol> {
 900  private:
 901   unsigned int        _hash;   // 32-bit hash for item
 902   SymbolHashMapEntry* _next;   // Next element in the linked list for this bucket
 903   Symbol*             _symbol; // 1-st part of the mapping: symbol => value
 904   u2                  _value;  // 2-nd part of the mapping: symbol => value
 905 
 906  public:
 907   unsigned   int hash() const             { return _hash;   }
 908   void       set_hash(unsigned int hash)  { _hash = hash;   }
 909 
 910   SymbolHashMapEntry* next() const        { return _next;   }
 911   void set_next(SymbolHashMapEntry* next) { _next = next;   }
 912 
 913   Symbol*    symbol() const               { return _symbol; }
 914   void       set_symbol(Symbol* sym)      { _symbol = sym;  }
 915 
 916   u2         value() const                {  return _value; }
 917   void       set_value(u2 value)          { _value = value; }
 918 
 919   SymbolHashMapEntry(unsigned int hash, Symbol* symbol, u2 value)
 920     : _hash(hash), _symbol(symbol), _value(value), _next(NULL) {}
 921 
 922 }; // End SymbolHashMapEntry class
 923 
 924 
 925 class SymbolHashMapBucket : public CHeapObj<mtSymbol> {
 926 
 927 private:
 928   SymbolHashMapEntry*    _entry;
 929 
 930 public:
 931   SymbolHashMapEntry* entry() const         {  return _entry; }
 932   void set_entry(SymbolHashMapEntry* entry) { _entry = entry; }
 933   void clear()                              { _entry = NULL;  }
 934 
 935 }; // End SymbolHashMapBucket class
 936 
 937 
 938 class SymbolHashMap: public CHeapObj<mtSymbol> {
 939 
 940  private:
 941   // Default number of entries in the table
 942   enum SymbolHashMap_Constants {
 943     _Def_HashMap_Size = 256
 944   };
 945 
 946   int                   _table_size;
 947   SymbolHashMapBucket*  _buckets;
 948 
 949   void initialize_table(int table_size) {
 950     _table_size = table_size;
 951     _buckets = NEW_C_HEAP_ARRAY(SymbolHashMapBucket, table_size, mtSymbol);
 952     for (int index = 0; index < table_size; index++) {
 953       _buckets[index].clear();
 954     }
 955   }
 956 
 957  public:
 958 
 959   int table_size() const        { return _table_size; }
 960 
 961   SymbolHashMap()               { initialize_table(_Def_HashMap_Size); }
 962   SymbolHashMap(int table_size) { initialize_table(table_size); }
 963 
 964   // hash P(31) from Kernighan & Ritchie
 965   static unsigned int compute_hash(const char* str, int len) {
 966     unsigned int hash = 0;
 967     while (len-- > 0) {
 968       hash = 31*hash + (unsigned) *str;
 969       str++;
 970     }
 971     return hash;
 972   }
 973 
 974   SymbolHashMapEntry* bucket(int i) {
 975     return _buckets[i].entry();
 976   }
 977 
 978   void add_entry(Symbol* sym, u2 value);
 979   SymbolHashMapEntry* find_entry(Symbol* sym);
 980 
 981   u2 symbol_to_value(Symbol* sym) {
 982     SymbolHashMapEntry *entry = find_entry(sym);
 983     return (entry == NULL) ? 0 : entry->value();
 984   }
 985 
 986   ~SymbolHashMap() {
 987     SymbolHashMapEntry* next;
 988     for (int i = 0; i < _table_size; i++) {
 989       for (SymbolHashMapEntry* cur = bucket(i); cur != NULL; cur = next) {
 990         next = cur->next();
 991         delete(cur);
 992       }
 993     }
 994     FREE_C_HEAP_ARRAY(SymbolHashMapBucket, _buckets, mtSymbol);
 995   }
 996 }; // End SymbolHashMap class
 997 
 998 #endif // SHARE_VM_OOPS_CONSTANTPOOLOOP_HPP