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