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