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