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. Used during a retransform/class redefinition as well.
 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_qdescriptor_at_put(int which, int name_index, int resolved_klass_index) {
 294       release_tag_at_put(which, JVM_CONSTANT_UnresolvedClass | (jbyte) JVM_CONSTANT_QDescBit);
 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 unresolved_klass_at_put(int which, int name_index, int resolved_klass_index) {
 303     release_tag_at_put(which, JVM_CONSTANT_UnresolvedClass);
 304 
 305     assert((name_index & 0xffff0000) == 0, "must be");
 306     assert((resolved_klass_index & 0xffff0000) == 0, "must be");
 307     *int_at_addr(which) =
 308       build_int_from_shorts((jushort)resolved_klass_index, (jushort)name_index);
 309   }
 310 
 311   void method_handle_index_at_put(int which, int ref_kind, int ref_index) {
 312     tag_at_put(which, JVM_CONSTANT_MethodHandle);
 313     *int_at_addr(which) = ((jint) ref_index<<16) | ref_kind;
 314   }
 315 
 316   void method_type_index_at_put(int which, int ref_index) {
 317     tag_at_put(which, JVM_CONSTANT_MethodType);
 318     *int_at_addr(which) = ref_index;
 319   }
 320 
 321   void dynamic_constant_at_put(int which, int bsms_attribute_index, int name_and_type_index) {
 322     tag_at_put(which, JVM_CONSTANT_Dynamic);
 323     *int_at_addr(which) = ((jint) name_and_type_index<<16) | bsms_attribute_index;
 324   }
 325 
 326   void invoke_dynamic_at_put(int which, int bsms_attribute_index, int name_and_type_index) {
 327     tag_at_put(which, JVM_CONSTANT_InvokeDynamic);
 328     *int_at_addr(which) = ((jint) name_and_type_index<<16) | bsms_attribute_index;
 329   }
 330 
 331   void unresolved_string_at_put(int which, Symbol* s) {
 332     assert(s->refcount() != 0, "should have nonzero refcount");
 333     // Note that release_tag_at_put is not needed here because this is called only
 334     // when constructing a ConstantPool in a single thread, with no possibility
 335     // of concurrent access.
 336     tag_at_put(which, JVM_CONSTANT_String);
 337     *symbol_at_addr(which) = s;
 338   }
 339 
 340   void int_at_put(int which, jint i) {
 341     tag_at_put(which, JVM_CONSTANT_Integer);
 342     *int_at_addr(which) = i;
 343   }
 344 
 345   void long_at_put(int which, jlong l) {
 346     tag_at_put(which, JVM_CONSTANT_Long);
 347     // *long_at_addr(which) = l;
 348     Bytes::put_native_u8((address)long_at_addr(which), *((u8*) &l));
 349   }
 350 
 351   void float_at_put(int which, jfloat f) {
 352     tag_at_put(which, JVM_CONSTANT_Float);
 353     *float_at_addr(which) = f;
 354   }
 355 
 356   void double_at_put(int which, jdouble d) {
 357     tag_at_put(which, JVM_CONSTANT_Double);
 358     // *double_at_addr(which) = d;
 359     // u8 temp = *(u8*) &d;
 360     Bytes::put_native_u8((address) double_at_addr(which), *((u8*) &d));
 361   }
 362 
 363   Symbol** symbol_at_addr(int which) const {
 364     assert(is_within_bounds(which), "index out of bounds");
 365     return (Symbol**) &base()[which];
 366   }
 367 
 368   void symbol_at_put(int which, Symbol* s) {
 369     assert(s->refcount() != 0, "should have nonzero refcount");
 370     tag_at_put(which, JVM_CONSTANT_Utf8);
 371     *symbol_at_addr(which) = s;
 372   }
 373 
 374   void string_at_put(int which, int obj_index, oop str);
 375 
 376   // For temporary use while constructing constant pool
 377   void string_index_at_put(int which, int string_index) {
 378     tag_at_put(which, JVM_CONSTANT_StringIndex);
 379     *int_at_addr(which) = string_index;
 380   }
 381 
 382   void field_at_put(int which, int class_index, int name_and_type_index) {
 383     tag_at_put(which, JVM_CONSTANT_Fieldref);
 384     *int_at_addr(which) = ((jint) name_and_type_index<<16) | class_index;
 385   }
 386 
 387   void method_at_put(int which, int class_index, int name_and_type_index) {
 388     tag_at_put(which, JVM_CONSTANT_Methodref);
 389     *int_at_addr(which) = ((jint) name_and_type_index<<16) | class_index;
 390   }
 391 
 392   void interface_method_at_put(int which, int class_index, int name_and_type_index) {
 393     tag_at_put(which, JVM_CONSTANT_InterfaceMethodref);
 394     *int_at_addr(which) = ((jint) name_and_type_index<<16) | class_index;  // Not so nice
 395   }
 396 
 397   void name_and_type_at_put(int which, int name_index, int signature_index) {
 398     tag_at_put(which, JVM_CONSTANT_NameAndType);
 399     *int_at_addr(which) = ((jint) signature_index<<16) | name_index;  // Not so nice
 400   }
 401 
 402   // Tag query
 403 
 404   constantTag tag_at(int which) const { return (constantTag)tags()->at_acquire(which); }
 405 
 406   // Fetching constants
 407 
 408   Klass* klass_at(int which, TRAPS) {
 409     constantPoolHandle h_this(THREAD, this);
 410     return klass_at_impl(h_this, which, THREAD);
 411   }
 412 
 413   CPKlassSlot klass_slot_at(int which) const {
 414     assert(tag_at(which).is_unresolved_klass() || tag_at(which).is_klass(),
 415            "Corrupted constant pool");
 416     int value = *int_at_addr(which);
 417     int name_index = extract_high_short_from_int(value);
 418     int resolved_klass_index = extract_low_short_from_int(value);
 419     return CPKlassSlot(name_index, resolved_klass_index);
 420   }
 421 
 422   Symbol* klass_name_at(int which) const;  // Returns the name, w/o resolving.
 423   int klass_name_index_at(int which) const {
 424     return klass_slot_at(which).name_index();
 425   }
 426 
 427   Klass* resolved_klass_at(int which) const;  // Used by Compiler
 428 
 429   // RedefineClasses() API support:
 430   Symbol* klass_at_noresolve(int which) { return klass_name_at(which); }
 431   void temp_unresolved_klass_at_put(int which, int name_index) {
 432     // Used only during constant pool merging for class redefinition. The resolved klass index
 433     // will be initialized later by a call to initialize_unresolved_klasses().
 434     unresolved_klass_at_put(which, name_index, CPKlassSlot::_temp_resolved_klass_index);
 435   }
 436 
 437   jint int_at(int which) {
 438     assert(tag_at(which).is_int(), "Corrupted constant pool");
 439     return *int_at_addr(which);
 440   }
 441 
 442   jlong long_at(int which) {
 443     assert(tag_at(which).is_long(), "Corrupted constant pool");
 444     // return *long_at_addr(which);
 445     u8 tmp = Bytes::get_native_u8((address)&base()[which]);
 446     return *((jlong*)&tmp);
 447   }
 448 
 449   jfloat float_at(int which) {
 450     assert(tag_at(which).is_float(), "Corrupted constant pool");
 451     return *float_at_addr(which);
 452   }
 453 
 454   jdouble double_at(int which) {
 455     assert(tag_at(which).is_double(), "Corrupted constant pool");
 456     u8 tmp = Bytes::get_native_u8((address)&base()[which]);
 457     return *((jdouble*)&tmp);
 458   }
 459 
 460   Symbol* symbol_at(int which) const {
 461     assert(tag_at(which).is_utf8(), "Corrupted constant pool");
 462     return *symbol_at_addr(which);
 463   }
 464 
 465   oop string_at(int which, int obj_index, TRAPS) {
 466     constantPoolHandle h_this(THREAD, this);
 467     return string_at_impl(h_this, which, obj_index, THREAD);
 468   }
 469   oop string_at(int which, TRAPS) {
 470     int obj_index = cp_to_object_index(which);
 471     return string_at(which, obj_index, THREAD);
 472   }
 473 
 474   // Version that can be used before string oop array is created.
 475   oop uncached_string_at(int which, TRAPS);
 476 
 477   // only called when we are sure a string entry is already resolved (via an
 478   // earlier string_at call.
 479   oop resolved_string_at(int which) {
 480     assert(tag_at(which).is_string(), "Corrupted constant pool");
 481     // Must do an acquire here in case another thread resolved the klass
 482     // behind our back, lest we later load stale values thru the oop.
 483     // we might want a volatile_obj_at in ObjArrayKlass.
 484     int obj_index = cp_to_object_index(which);
 485     return resolved_references()->obj_at(obj_index);
 486   }
 487 
 488   Symbol* unresolved_string_at(int which) {
 489     assert(tag_at(which).is_string(), "Corrupted constant pool");
 490     return *symbol_at_addr(which);
 491   }
 492 
 493   // Returns an UTF8 for a CONSTANT_String entry at a given index.
 494   // UTF8 char* representation was chosen to avoid conversion of
 495   // java_lang_Strings at resolved entries into Symbol*s
 496   // or vice versa.
 497   char* string_at_noresolve(int which);
 498 
 499   jint name_and_type_at(int which) {
 500     assert(tag_at(which).is_name_and_type(), "Corrupted constant pool");
 501     return *int_at_addr(which);
 502   }
 503 
 504   int method_handle_ref_kind_at(int which) {
 505     assert(tag_at(which).is_method_handle() ||
 506            tag_at(which).is_method_handle_in_error(), "Corrupted constant pool");
 507     return extract_low_short_from_int(*int_at_addr(which));  // mask out unwanted ref_index bits
 508   }
 509   int method_handle_index_at(int which) {
 510     assert(tag_at(which).is_method_handle() ||
 511            tag_at(which).is_method_handle_in_error(), "Corrupted constant pool");
 512     return extract_high_short_from_int(*int_at_addr(which));  // shift out unwanted ref_kind bits
 513   }
 514   int method_type_index_at(int which) {
 515     assert(tag_at(which).is_method_type() ||
 516            tag_at(which).is_method_type_in_error(), "Corrupted constant pool");
 517     return *int_at_addr(which);
 518   }
 519 
 520   // Derived queries:
 521   Symbol* method_handle_name_ref_at(int which) {
 522     int member = method_handle_index_at(which);
 523     return impl_name_ref_at(member, true);
 524   }
 525   Symbol* method_handle_signature_ref_at(int which) {
 526     int member = method_handle_index_at(which);
 527     return impl_signature_ref_at(member, true);
 528   }
 529   int method_handle_klass_index_at(int which) {
 530     int member = method_handle_index_at(which);
 531     return impl_klass_ref_index_at(member, true);
 532   }
 533   Symbol* method_type_signature_at(int which) {
 534     int sym = method_type_index_at(which);
 535     return symbol_at(sym);
 536   }
 537 
 538   int bootstrap_name_and_type_ref_index_at(int which) {
 539     assert(tag_at(which).has_bootstrap(), "Corrupted constant pool");
 540     return extract_high_short_from_int(*int_at_addr(which));
 541   }
 542   int bootstrap_methods_attribute_index(int which) {
 543     assert(tag_at(which).has_bootstrap(), "Corrupted constant pool");
 544     return extract_low_short_from_int(*int_at_addr(which));
 545   }
 546   int bootstrap_operand_base(int which) {
 547     int bsms_attribute_index = bootstrap_methods_attribute_index(which);
 548     return operand_offset_at(operands(), bsms_attribute_index);
 549   }
 550   // The first part of the operands array consists of an index into the second part.
 551   // Extract a 32-bit index value from the first part.
 552   static int operand_offset_at(Array<u2>* operands, int bsms_attribute_index) {
 553     int n = (bsms_attribute_index * 2);
 554     assert(n >= 0 && n+2 <= operands->length(), "oob");
 555     // The first 32-bit index points to the beginning of the second part
 556     // of the operands array.  Make sure this index is in the first part.
 557     DEBUG_ONLY(int second_part = build_int_from_shorts(operands->at(0),
 558                                                        operands->at(1)));
 559     assert(second_part == 0 || n+2 <= second_part, "oob (2)");
 560     int offset = build_int_from_shorts(operands->at(n+0),
 561                                        operands->at(n+1));
 562     // The offset itself must point into the second part of the array.
 563     assert(offset == 0 || offset >= second_part && offset <= operands->length(), "oob (3)");
 564     return offset;
 565   }
 566   static void operand_offset_at_put(Array<u2>* operands, int bsms_attribute_index, int offset) {
 567     int n = bsms_attribute_index * 2;
 568     assert(n >= 0 && n+2 <= operands->length(), "oob");
 569     operands->at_put(n+0, extract_low_short_from_int(offset));
 570     operands->at_put(n+1, extract_high_short_from_int(offset));
 571   }
 572   static int operand_array_length(Array<u2>* operands) {
 573     if (operands == NULL || operands->length() == 0)  return 0;
 574     int second_part = operand_offset_at(operands, 0);
 575     return (second_part / 2);
 576   }
 577 
 578 #ifdef ASSERT
 579   // operand tuples fit together exactly, end to end
 580   static int operand_limit_at(Array<u2>* operands, int bsms_attribute_index) {
 581     int nextidx = bsms_attribute_index + 1;
 582     if (nextidx == operand_array_length(operands))
 583       return operands->length();
 584     else
 585       return operand_offset_at(operands, nextidx);
 586   }
 587   int bootstrap_operand_limit(int which) {
 588     int bsms_attribute_index = bootstrap_methods_attribute_index(which);
 589     return operand_limit_at(operands(), bsms_attribute_index);
 590   }
 591 #endif //ASSERT
 592 
 593   // Layout of InvokeDynamic and Dynamic bootstrap method specifier
 594   // data in second part of operands array.  This encodes one record in
 595   // the BootstrapMethods attribute.  The whole specifier also includes
 596   // the name and type information from the main constant pool entry.
 597   enum {
 598          _indy_bsm_offset  = 0,  // CONSTANT_MethodHandle bsm
 599          _indy_argc_offset = 1,  // u2 argc
 600          _indy_argv_offset = 2   // u2 argv[argc]
 601   };
 602 
 603   // These functions are used in RedefineClasses for CP merge
 604 
 605   int operand_offset_at(int bsms_attribute_index) {
 606     assert(0 <= bsms_attribute_index &&
 607            bsms_attribute_index < operand_array_length(operands()),
 608            "Corrupted CP operands");
 609     return operand_offset_at(operands(), bsms_attribute_index);
 610   }
 611   int operand_bootstrap_method_ref_index_at(int bsms_attribute_index) {
 612     int offset = operand_offset_at(bsms_attribute_index);
 613     return operands()->at(offset + _indy_bsm_offset);
 614   }
 615   int operand_argument_count_at(int bsms_attribute_index) {
 616     int offset = operand_offset_at(bsms_attribute_index);
 617     int argc = operands()->at(offset + _indy_argc_offset);
 618     return argc;
 619   }
 620   int operand_argument_index_at(int bsms_attribute_index, int j) {
 621     int offset = operand_offset_at(bsms_attribute_index);
 622     return operands()->at(offset + _indy_argv_offset + j);
 623   }
 624   int operand_next_offset_at(int bsms_attribute_index) {
 625     int offset = operand_offset_at(bsms_attribute_index) + _indy_argv_offset
 626                    + operand_argument_count_at(bsms_attribute_index);
 627     return offset;
 628   }
 629   // Compare a bootstrap specifier data in the operands arrays
 630   bool compare_operand_to(int bsms_attribute_index1, const constantPoolHandle& cp2,
 631                           int bsms_attribute_index2);
 632   // Find a bootstrap specifier data in the operands array
 633   int find_matching_operand(int bsms_attribute_index, const constantPoolHandle& search_cp,
 634                             int operands_cur_len);
 635   // Resize the operands array with delta_len and delta_size
 636   void resize_operands(int delta_len, int delta_size, TRAPS);
 637   // Extend the operands array with the length and size of the ext_cp operands
 638   void extend_operands(const constantPoolHandle& ext_cp, TRAPS);
 639   // Shrink the operands array to a smaller array with new_len length
 640   void shrink_operands(int new_len, TRAPS);
 641 
 642   int bootstrap_method_ref_index_at(int which) {
 643     assert(tag_at(which).has_bootstrap(), "Corrupted constant pool");
 644     int op_base = bootstrap_operand_base(which);
 645     return operands()->at(op_base + _indy_bsm_offset);
 646   }
 647   int bootstrap_argument_count_at(int which) {
 648     assert(tag_at(which).has_bootstrap(), "Corrupted constant pool");
 649     int op_base = bootstrap_operand_base(which);
 650     int argc = operands()->at(op_base + _indy_argc_offset);
 651     DEBUG_ONLY(int end_offset = op_base + _indy_argv_offset + argc;
 652                int next_offset = bootstrap_operand_limit(which));
 653     assert(end_offset == next_offset, "matched ending");
 654     return argc;
 655   }
 656   int bootstrap_argument_index_at(int which, int j) {
 657     int op_base = bootstrap_operand_base(which);
 658     DEBUG_ONLY(int argc = operands()->at(op_base + _indy_argc_offset));
 659     assert((uint)j < (uint)argc, "oob");
 660     return operands()->at(op_base + _indy_argv_offset + j);
 661   }
 662 
 663   // The following methods (name/signature/klass_ref_at, klass_ref_at_noresolve,
 664   // name_and_type_ref_index_at) all expect to be passed indices obtained
 665   // directly from the bytecode.
 666   // If the indices are meant to refer to fields or methods, they are
 667   // actually rewritten constant pool cache indices.
 668   // The routine remap_instruction_operand_from_cache manages the adjustment
 669   // of these values back to constant pool indices.
 670 
 671   // There are also "uncached" versions which do not adjust the operand index; see below.
 672 
 673   // FIXME: Consider renaming these with a prefix "cached_" to make the distinction clear.
 674   // In a few cases (the verifier) there are uses before a cpcache has been built,
 675   // which are handled by a dynamic check in remap_instruction_operand_from_cache.
 676   // FIXME: Remove the dynamic check, and adjust all callers to specify the correct mode.
 677 
 678   // Lookup for entries consisting of (klass_index, name_and_type index)
 679   Klass* klass_ref_at(int which, TRAPS);
 680   Symbol* klass_ref_at_noresolve(int which);
 681   Symbol* name_ref_at(int which)                { return impl_name_ref_at(which, false); }
 682   Symbol* signature_ref_at(int which)           { return impl_signature_ref_at(which, false); }
 683 
 684   int klass_ref_index_at(int which)               { return impl_klass_ref_index_at(which, false); }
 685   int name_and_type_ref_index_at(int which)       { return impl_name_and_type_ref_index_at(which, false); }
 686 
 687   int remap_instruction_operand_from_cache(int operand);  // operand must be biased by CPCACHE_INDEX_TAG
 688 
 689   constantTag tag_ref_at(int cp_cache_index)      { return impl_tag_ref_at(cp_cache_index, false); }
 690 
 691   // Lookup for entries consisting of (name_index, signature_index)
 692   int name_ref_index_at(int which_nt);            // ==  low-order jshort of name_and_type_at(which_nt)
 693   int signature_ref_index_at(int which_nt);       // == high-order jshort of name_and_type_at(which_nt)
 694 
 695   BasicType basic_type_for_signature_at(int which) const;
 696 
 697   // Resolve string constants (to prevent allocation during compilation)
 698   void resolve_string_constants(TRAPS) {
 699     constantPoolHandle h_this(THREAD, this);
 700     resolve_string_constants_impl(h_this, CHECK);
 701   }
 702 
 703   // CDS support
 704   void archive_resolved_references() NOT_CDS_JAVA_HEAP_RETURN;
 705   void add_dumped_interned_strings() NOT_CDS_JAVA_HEAP_RETURN;
 706   void resolve_class_constants(TRAPS) NOT_CDS_JAVA_HEAP_RETURN;
 707   void remove_unshareable_info();
 708   void restore_unshareable_info(TRAPS);
 709   // The ConstantPool vtable is restored by this call when the ConstantPool is
 710   // in the shared archive.  See patch_klass_vtables() in metaspaceShared.cpp for
 711   // all the gory details.  SA, dtrace and pstack helpers distinguish metadata
 712   // by their vtable.
 713   void restore_vtable() { guarantee(is_constantPool(), "vtable restored by this call"); }
 714 
 715  private:
 716   enum { _no_index_sentinel = -1, _possible_index_sentinel = -2 };
 717  public:
 718 
 719   // Get the tag for a constant, which may involve a constant dynamic
 720   constantTag constant_tag_at(int which);
 721   // Get the basic type for a constant, which may involve a constant dynamic
 722   BasicType basic_type_for_constant_at(int which);
 723 
 724   // Resolve late bound constants.
 725   oop resolve_constant_at(int index, TRAPS) {
 726     constantPoolHandle h_this(THREAD, this);
 727     return resolve_constant_at_impl(h_this, index, _no_index_sentinel, NULL, THREAD);
 728   }
 729 
 730   oop resolve_cached_constant_at(int cache_index, TRAPS) {
 731     constantPoolHandle h_this(THREAD, this);
 732     return resolve_constant_at_impl(h_this, _no_index_sentinel, cache_index, NULL, THREAD);
 733   }
 734 
 735   oop resolve_possibly_cached_constant_at(int pool_index, TRAPS) {
 736     constantPoolHandle h_this(THREAD, this);
 737     return resolve_constant_at_impl(h_this, pool_index, _possible_index_sentinel, NULL, THREAD);
 738   }
 739 
 740   oop find_cached_constant_at(int pool_index, bool& found_it, TRAPS) {
 741     constantPoolHandle h_this(THREAD, this);
 742     return resolve_constant_at_impl(h_this, pool_index, _possible_index_sentinel, &found_it, THREAD);
 743   }
 744 
 745   void copy_bootstrap_arguments_at(int index,
 746                                    int start_arg, int end_arg,
 747                                    objArrayHandle info, int pos,
 748                                    bool must_resolve, Handle if_not_available, TRAPS) {
 749     constantPoolHandle h_this(THREAD, this);
 750     copy_bootstrap_arguments_at_impl(h_this, index, start_arg, end_arg,
 751                                      info, pos, must_resolve, if_not_available, THREAD);
 752   }
 753 
 754   // Klass name matches name at offset
 755   bool klass_name_at_matches(const InstanceKlass* k, int which);
 756 
 757   // Sizing
 758   int length() const                   { return _length; }
 759   void set_length(int length)          { _length = length; }
 760 
 761   // Tells whether index is within bounds.
 762   bool is_within_bounds(int index) const {
 763     return 0 <= index && index < length();
 764   }
 765 
 766   // Sizing (in words)
 767   static int header_size()             {
 768     return align_up((int)sizeof(ConstantPool), wordSize) / wordSize;
 769   }
 770   static int size(int length)          { return align_metadata_size(header_size() + length); }
 771   int size() const                     { return size(length()); }
 772 
 773   // ConstantPools should be stored in the read-only region of CDS archive.
 774   static bool is_read_only_by_default() { return true; }
 775 
 776   friend class ClassFileParser;
 777   friend class SystemDictionary;
 778 
 779   // Used by CDS. These classes need to access the private ConstantPool() constructor.
 780   template <class T> friend class CppVtableTesterA;
 781   template <class T> friend class CppVtableTesterB;
 782   template <class T> friend class CppVtableCloner;
 783 
 784   // Used by compiler to prevent classloading.
 785   static Method*          method_at_if_loaded      (const constantPoolHandle& this_cp, int which);
 786   static bool       has_appendix_at_if_loaded      (const constantPoolHandle& this_cp, int which);
 787   static oop            appendix_at_if_loaded      (const constantPoolHandle& this_cp, int which);
 788   static bool has_local_signature_at_if_loaded     (const constantPoolHandle& this_cp, int which);
 789   static Klass*            klass_at_if_loaded      (const constantPoolHandle& this_cp, int which);
 790 
 791   // Routines currently used for annotations (only called by jvm.cpp) but which might be used in the
 792   // future by other Java code. These take constant pool indices rather than
 793   // constant pool cache indices as do the peer methods above.
 794   Symbol* uncached_klass_ref_at_noresolve(int which);
 795   Symbol* uncached_name_ref_at(int which)                 { return impl_name_ref_at(which, true); }
 796   Symbol* uncached_signature_ref_at(int which)            { return impl_signature_ref_at(which, true); }
 797   int       uncached_klass_ref_index_at(int which)          { return impl_klass_ref_index_at(which, true); }
 798   int       uncached_name_and_type_ref_index_at(int which)  { return impl_name_and_type_ref_index_at(which, true); }
 799 
 800   // Sharing
 801   int pre_resolve_shared_klasses(TRAPS);
 802 
 803   // Debugging
 804   const char* printable_name_at(int which) PRODUCT_RETURN0;
 805 
 806 #ifdef ASSERT
 807   enum { CPCACHE_INDEX_TAG = 0x10000 };  // helps keep CP cache indices distinct from CP indices
 808 #else
 809   enum { CPCACHE_INDEX_TAG = 0 };        // in product mode, this zero value is a no-op
 810 #endif //ASSERT
 811 
 812   static int decode_cpcache_index(int raw_index, bool invokedynamic_ok = false) {
 813     if (invokedynamic_ok && is_invokedynamic_index(raw_index))
 814       return decode_invokedynamic_index(raw_index);
 815     else
 816       return raw_index - CPCACHE_INDEX_TAG;
 817   }
 818 
 819  private:
 820 
 821   void set_resolved_references(OopHandle s) { _cache->set_resolved_references(s); }
 822   Array<u2>* reference_map() const        {  return (_cache == NULL) ? NULL :  _cache->reference_map(); }
 823   void set_reference_map(Array<u2>* o)    { _cache->set_reference_map(o); }
 824 
 825   Symbol* impl_name_ref_at(int which, bool uncached);
 826   Symbol* impl_signature_ref_at(int which, bool uncached);
 827 
 828   int       impl_klass_ref_index_at(int which, bool uncached);
 829   int       impl_name_and_type_ref_index_at(int which, bool uncached);
 830   constantTag impl_tag_ref_at(int which, bool uncached);
 831 
 832   // Used while constructing constant pool (only by ClassFileParser)
 833   jint klass_index_at(int which) {
 834     assert(tag_at(which).is_klass_index(), "Corrupted constant pool");
 835     return *int_at_addr(which);
 836   }
 837 
 838   jint string_index_at(int which) {
 839     assert(tag_at(which).is_string_index(), "Corrupted constant pool");
 840     return *int_at_addr(which);
 841   }
 842 
 843   // Performs the LinkResolver checks
 844   static void verify_constant_pool_resolve(const constantPoolHandle& this_cp, Klass* klass, TRAPS);
 845 
 846   // Implementation of methods that needs an exposed 'this' pointer, in order to
 847   // handle GC while executing the method
 848   static Klass* klass_at_impl(const constantPoolHandle& this_cp, int which, TRAPS);
 849   static oop string_at_impl(const constantPoolHandle& this_cp, int which, int obj_index, TRAPS);
 850 
 851   static void trace_class_resolution(const constantPoolHandle& this_cp, Klass* k);
 852 
 853   // Resolve string constants (to prevent allocation during compilation)
 854   static void resolve_string_constants_impl(const constantPoolHandle& this_cp, TRAPS);
 855 
 856   static oop resolve_constant_at_impl(const constantPoolHandle& this_cp, int index, int cache_index,
 857                                       bool* status_return, TRAPS);
 858   static void copy_bootstrap_arguments_at_impl(const constantPoolHandle& this_cp, int index,
 859                                                int start_arg, int end_arg,
 860                                                objArrayHandle info, int pos,
 861                                                bool must_resolve, Handle if_not_available, TRAPS);
 862 
 863   // Exception handling
 864   static void save_and_throw_exception(const constantPoolHandle& this_cp, int which, constantTag tag, TRAPS);
 865 
 866  public:
 867   // Exception handling
 868   static void throw_resolution_error(const constantPoolHandle& this_cp, int which, TRAPS);
 869 
 870   // Merging ConstantPool* support:
 871   bool compare_entry_to(int index1, const constantPoolHandle& cp2, int index2);
 872   void copy_cp_to(int start_i, int end_i, const constantPoolHandle& to_cp, int to_i, TRAPS) {
 873     constantPoolHandle h_this(THREAD, this);
 874     copy_cp_to_impl(h_this, start_i, end_i, to_cp, to_i, THREAD);
 875   }
 876   static void copy_cp_to_impl(const constantPoolHandle& from_cp, int start_i, int end_i, const constantPoolHandle& to_cp, int to_i, TRAPS);
 877   static void copy_entry_to(const constantPoolHandle& from_cp, int from_i, const constantPoolHandle& to_cp, int to_i);
 878   static void copy_operands(const constantPoolHandle& from_cp, const constantPoolHandle& to_cp, TRAPS);
 879   int  find_matching_entry(int pattern_i, const constantPoolHandle& search_cp);
 880   int  version() const                    { return _saved._version; }
 881   void set_version(int version)           { _saved._version = version; }
 882   void increment_and_save_version(int version) {
 883     _saved._version = version >= 0 ? (version + 1) : version;  // keep overflow
 884   }
 885 
 886   void set_resolved_reference_length(int length) { _saved._resolved_reference_length = length; }
 887   int  resolved_reference_length() const  { return _saved._resolved_reference_length; }
 888 
 889   // Decrease ref counts of symbols that are in the constant pool
 890   // when the holder class is unloaded
 891   void unreference_symbols();
 892 
 893   // Deallocate constant pool for RedefineClasses
 894   void deallocate_contents(ClassLoaderData* loader_data);
 895   void release_C_heap_structures();
 896 
 897   // JVMTI accesss - GetConstantPool, RetransformClasses, ...
 898   friend class JvmtiConstantPoolReconstituter;
 899 
 900  private:
 901   jint cpool_entry_size(jint idx);
 902   jint hash_entries_to(SymbolHashMap *symmap, SymbolHashMap *classmap);
 903 
 904   // Copy cpool bytes into byte array.
 905   // Returns:
 906   //  int > 0, count of the raw cpool bytes that have been copied
 907   //        0, OutOfMemory error
 908   //       -1, Internal error
 909   int  copy_cpool_bytes(int cpool_size,
 910                         SymbolHashMap* tbl,
 911                         unsigned char *bytes);
 912 
 913  public:
 914   // Verify
 915   void verify_on(outputStream* st);
 916 
 917   // Printing
 918   void print_on(outputStream* st) const;
 919   void print_value_on(outputStream* st) const;
 920   void print_entry_on(int index, outputStream* st);
 921 
 922   const char* internal_name() const { return "{constant pool}"; }
 923 };
 924 
 925 class SymbolHashMapEntry : public CHeapObj<mtSymbol> {
 926  private:
 927   SymbolHashMapEntry* _next;   // Next element in the linked list for this bucket
 928   Symbol*             _symbol; // 1-st part of the mapping: symbol => value
 929   unsigned int        _hash;   // 32-bit hash for item
 930   u2                  _value;  // 2-nd part of the mapping: symbol => value
 931 
 932  public:
 933   unsigned   int hash() const             { return _hash;   }
 934   void       set_hash(unsigned int hash)  { _hash = hash;   }
 935 
 936   SymbolHashMapEntry* next() const        { return _next;   }
 937   void set_next(SymbolHashMapEntry* next) { _next = next;   }
 938 
 939   Symbol*    symbol() const               { return _symbol; }
 940   void       set_symbol(Symbol* sym)      { _symbol = sym;  }
 941 
 942   u2         value() const                {  return _value; }
 943   void       set_value(u2 value)          { _value = value; }
 944 
 945   SymbolHashMapEntry(unsigned int hash, Symbol* symbol, u2 value)
 946     : _next(NULL), _symbol(symbol), _hash(hash), _value(value) {}
 947 
 948 }; // End SymbolHashMapEntry class
 949 
 950 
 951 class SymbolHashMapBucket : public CHeapObj<mtSymbol> {
 952 
 953 private:
 954   SymbolHashMapEntry*    _entry;
 955 
 956 public:
 957   SymbolHashMapEntry* entry() const         {  return _entry; }
 958   void set_entry(SymbolHashMapEntry* entry) { _entry = entry; }
 959   void clear()                              { _entry = NULL;  }
 960 
 961 }; // End SymbolHashMapBucket class
 962 
 963 
 964 class SymbolHashMap: public CHeapObj<mtSymbol> {
 965 
 966  private:
 967   // Default number of entries in the table
 968   enum SymbolHashMap_Constants {
 969     _Def_HashMap_Size = 256
 970   };
 971 
 972   int                   _table_size;
 973   SymbolHashMapBucket*  _buckets;
 974 
 975   void initialize_table(int table_size);
 976 
 977  public:
 978 
 979   int table_size() const        { return _table_size; }
 980 
 981   SymbolHashMap()               { initialize_table(_Def_HashMap_Size); }
 982   SymbolHashMap(int table_size) { initialize_table(table_size); }
 983 
 984   // hash P(31) from Kernighan & Ritchie
 985   static unsigned int compute_hash(const char* str, int len) {
 986     unsigned int hash = 0;
 987     while (len-- > 0) {
 988       hash = 31*hash + (unsigned) *str;
 989       str++;
 990     }
 991     return hash;
 992   }
 993 
 994   SymbolHashMapEntry* bucket(int i) {
 995     return _buckets[i].entry();
 996   }
 997 
 998   void add_entry(Symbol* sym, u2 value);
 999   SymbolHashMapEntry* find_entry(Symbol* sym);
1000 
1001   u2 symbol_to_value(Symbol* sym) {
1002     SymbolHashMapEntry *entry = find_entry(sym);
1003     return (entry == NULL) ? 0 : entry->value();
1004   }
1005 
1006   ~SymbolHashMap();
1007 }; // End SymbolHashMap class
1008 
1009 #endif // SHARE_OOPS_CONSTANTPOOL_HPP