constantPool.cpp 72.9 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25
#include "precompiled.hpp"
26
#include "classfile/classLoaderData.hpp"
27
#include "classfile/javaClasses.hpp"
28
#include "classfile/metadataOnStackMark.hpp"
29 30 31 32
#include "classfile/symbolTable.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "interpreter/linkResolver.hpp"
33
#include "memory/heapInspection.hpp"
34
#include "memory/metadataFactory.hpp"
35
#include "memory/oopFactory.hpp"
36
#include "oops/constantPool.hpp"
37 38 39 40
#include "oops/instanceKlass.hpp"
#include "oops/objArrayKlass.hpp"
#include "runtime/fieldType.hpp"
#include "runtime/init.hpp"
41
#include "runtime/javaCalls.hpp"
42 43
#include "runtime/signature.hpp"
#include "runtime/vframe.hpp"
D
duke 已提交
44

45 46
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

47 48 49 50 51 52 53 54 55 56 57 58
ConstantPool* ConstantPool::allocate(ClassLoaderData* loader_data, int length, TRAPS) {
  // Tags are RW but comment below applies to tags also.
  Array<u1>* tags = MetadataFactory::new_writeable_array<u1>(loader_data, length, 0, CHECK_NULL);

  int size = ConstantPool::size(length);

  // CDS considerations:
  // Allocate read-write but may be able to move to read-only at dumping time
  // if all the klasses are resolved.  The only other field that is writable is
  // the resolved_references array, which is recreated at startup time.
  // But that could be moved to InstanceKlass (although a pain to access from
  // assembly code).  Maybe it could be moved to the cpCache which is RW.
59
  return new (loader_data, size, false, MetaspaceObj::ConstantPoolType, THREAD) ConstantPool(tags);
60 61 62 63 64 65 66 67 68 69 70
}

ConstantPool::ConstantPool(Array<u1>* tags) {
  set_length(tags->length());
  set_tags(NULL);
  set_cache(NULL);
  set_reference_map(NULL);
  set_resolved_references(NULL);
  set_operands(NULL);
  set_pool_holder(NULL);
  set_flags(0);
71

72
  // only set to non-zero if constant pool is merged by RedefineClasses
73
  set_version(0);
74
  set_lock(new Monitor(Monitor::nonleaf + 2, "A constant pool lock"));
75 76 77 78 79 80 81 82 83 84 85 86

  // initialize tag array
  int length = tags->length();
  for (int index = 0; index < length; index++) {
    tags->at_put(index, JVM_CONSTANT_Invalid);
  }
  set_tags(tags);
}

void ConstantPool::deallocate_contents(ClassLoaderData* loader_data) {
  MetadataFactory::free_metadata(loader_data, cache());
  set_cache(NULL);
87 88 89
  MetadataFactory::free_array<u2>(loader_data, reference_map());
  set_reference_map(NULL);

90 91 92 93 94 95 96 97 98 99 100 101 102
  MetadataFactory::free_array<jushort>(loader_data, operands());
  set_operands(NULL);

  release_C_heap_structures();

  // free tag array
  MetadataFactory::free_array<u1>(loader_data, tags());
  set_tags(NULL);
}

void ConstantPool::release_C_heap_structures() {
  // walk constant pool and decrement symbol reference counts
  unreference_symbols();
103 104 105

  delete _lock;
  set_lock(NULL);
106 107 108 109 110 111
}

objArrayOop ConstantPool::resolved_references() const {
  return (objArrayOop)JNIHandles::resolve(_resolved_references);
}

112 113 114 115 116 117 118 119 120 121
// Called from outside constant pool resolution where a resolved_reference array
// may not be present.
objArrayOop ConstantPool::resolved_references_or_null() const {
  if (_cache == NULL) {
    return NULL;
  } else {
    return (objArrayOop)JNIHandles::resolve(_resolved_references);
  }
}

122 123 124 125 126 127 128
// Create resolved_references array and mapping array for original cp indexes
// The ldc bytecode was rewritten to have the resolved reference array index so need a way
// to map it back for resolving and some unlikely miscellaneous uses.
// The objects created by invokedynamic are appended to this list.
void ConstantPool::initialize_resolved_references(ClassLoaderData* loader_data,
                                                  intStack reference_map,
                                                  int constant_pool_map_length,
129
                                                  TRAPS) {
130 131 132 133
  // Initialized the resolved object cache.
  int map_length = reference_map.length();
  if (map_length > 0) {
    // Only need mapping back to constant pool entries.  The map isn't used for
134 135 136
    // invokedynamic resolved_reference entries.  For invokedynamic entries,
    // the constant pool cache index has the mapping back to both the constant
    // pool and to the resolved reference index.
137
    if (constant_pool_map_length > 0) {
138
      Array<u2>* om = MetadataFactory::new_array<u2>(loader_data, constant_pool_map_length, CHECK);
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

      for (int i = 0; i < constant_pool_map_length; i++) {
        int x = reference_map.at(i);
        assert(x == (int)(jushort) x, "klass index is too big");
        om->at_put(i, (jushort)x);
      }
      set_reference_map(om);
    }

    // Create Java array for holding resolved strings, methodHandles,
    // methodTypes, invokedynamic and invokehandle appendix objects, etc.
    objArrayOop stom = oopFactory::new_objArray(SystemDictionary::Object_klass(), map_length, CHECK);
    Handle refs_handle (THREAD, (oop)stom);  // must handleize.
    set_resolved_references(loader_data->add_handle(refs_handle));
  }
}

// CDS support. Create a new resolved_references array.
void ConstantPool::restore_unshareable_info(TRAPS) {
158

159 160 161 162
  // Only create the new resolved references array and lock if it hasn't been
  // attempted before
  if (resolved_references() != NULL) return;

163 164 165
  // restore the C++ vtable from the shared archive
  restore_vtable();

166 167 168 169 170 171 172 173 174 175
  if (SystemDictionary::Object_klass_loaded()) {
    // Recreate the object array and add to ClassLoaderData.
    int map_length = resolved_reference_length();
    if (map_length > 0) {
      objArrayOop stom = oopFactory::new_objArray(SystemDictionary::Object_klass(), map_length, CHECK);
      Handle refs_handle (THREAD, (oop)stom);  // must handleize.

      ClassLoaderData* loader_data = pool_holder()->class_loader_data();
      set_resolved_references(loader_data->add_handle(refs_handle));
    }
176 177 178

    // Also need to recreate the mutex.  Make sure this matches the constructor
    set_lock(new Monitor(Monitor::nonleaf + 2, "A constant pool lock"));
179 180 181 182 183 184 185 186 187 188
  }
}

void ConstantPool::remove_unshareable_info() {
  // Resolved references are not in the shared archive.
  // Save the length for restoration.  It is not necessarily the same length
  // as reference_map.length() if invokedynamic is saved.
  set_resolved_reference_length(
    resolved_references() != NULL ? resolved_references()->length() : 0);
  set_resolved_references(NULL);
189
  set_lock(NULL);
190 191 192 193
}

int ConstantPool::cp_to_object_index(int cp_index) {
  // this is harder don't do this so much.
194 195 196
  int i = reference_map()->find(cp_index);
  // We might not find the index for jsr292 call.
  return (i < 0) ? _no_index_sentinel : i;
197 198 199 200
}

Klass* ConstantPool::klass_at_impl(constantPoolHandle this_oop, int which, TRAPS) {
  // A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.
D
duke 已提交
201 202
  // It is not safe to rely on the tag bit's here, since we don't have a lock, and the entry and
  // tag is not updated atomicly.
203

204
  CPSlot entry = this_oop->slot_at(which);
205 206
  if (entry.is_resolved()) {
    assert(entry.get_klass()->is_klass(), "must be");
D
duke 已提交
207
    // Already resolved - return entry.
208
    return entry.get_klass();
D
duke 已提交
209 210 211 212 213 214 215 216
  }

  // Acquire lock on constant oop while doing update. After we get the lock, we check if another object
  // already has updated the object
  assert(THREAD->is_Java_thread(), "must be a Java thread");
  bool do_resolve = false;
  bool in_error = false;

217 218 219 220
  // Create a handle for the mirror. This will preserve the resolved class
  // until the loader_data is registered.
  Handle mirror_handle;

221
  Symbol* name = NULL;
D
duke 已提交
222
  Handle       loader;
223
  {  MonitorLockerEx ml(this_oop->lock());
D
duke 已提交
224 225 226 227 228 229

    if (this_oop->tag_at(which).is_unresolved_klass()) {
      if (this_oop->tag_at(which).is_unresolved_klass_in_error()) {
        in_error = true;
      } else {
        do_resolve = true;
230
        name   = this_oop->unresolved_klass_at(which);
231
        loader = Handle(THREAD, this_oop->pool_holder()->class_loader());
D
duke 已提交
232 233 234 235 236 237 238 239
      }
    }
  } // unlocking constantPool


  // The original attempt to resolve this constant pool entry failed so find the
  // original error and throw it again (JVMS 5.4.3).
  if (in_error) {
240 241
    Symbol* error = SystemDictionary::find_resolution_error(this_oop, which);
    guarantee(error != (Symbol*)NULL, "tag mismatch with resolution error table");
D
duke 已提交
242 243 244 245 246 247 248 249
    ResourceMark rm;
    // exception text will be the class name
    const char* className = this_oop->unresolved_klass_at(which)->as_C_string();
    THROW_MSG_0(error, className);
  }

  if (do_resolve) {
    // this_oop must be unlocked during resolve_or_fail
250
    oop protection_domain = this_oop->pool_holder()->protection_domain();
D
duke 已提交
251
    Handle h_prot (THREAD, protection_domain);
252
    Klass* k_oop = SystemDictionary::resolve_or_fail(name, loader, h_prot, true, THREAD);
D
duke 已提交
253 254 255
    KlassHandle k;
    if (!HAS_PENDING_EXCEPTION) {
      k = KlassHandle(THREAD, k_oop);
256 257
      // preserve the resolved klass.
      mirror_handle = Handle(THREAD, k_oop->java_mirror());
D
duke 已提交
258 259 260 261 262 263 264 265
      // Do access check for klasses
      verify_constant_pool_resolve(this_oop, k, THREAD);
    }

    // Failed to resolve class. We must record the errors so that subsequent attempts
    // to resolve this constant pool entry fail with the same error (JVMS 5.4.3).
    if (HAS_PENDING_EXCEPTION) {
      ResourceMark rm;
266
      Symbol* error = PENDING_EXCEPTION->klass()->name();
D
duke 已提交
267 268 269

      bool throw_orig_error = false;
      {
270
        MonitorLockerEx ml(this_oop->lock());
D
duke 已提交
271 272 273 274 275

        // some other thread has beaten us and has resolved the class.
        if (this_oop->tag_at(which).is_klass()) {
          CLEAR_PENDING_EXCEPTION;
          entry = this_oop->resolved_klass_at(which);
276
          return entry.get_klass();
D
duke 已提交
277 278 279
        }

        if (!PENDING_EXCEPTION->
280
              is_a(SystemDictionary::LinkageError_klass())) {
D
duke 已提交
281 282 283 284 285 286 287 288 289 290
          // Just throw the exception and don't prevent these classes from
          // being loaded due to virtual machine errors like StackOverflow
          // and OutOfMemoryError, etc, or if the thread was hit by stop()
          // Needs clarification to section 5.4.3 of the VM spec (see 6308271)
        }
        else if (!this_oop->tag_at(which).is_unresolved_klass_in_error()) {
          SystemDictionary::add_resolution_error(this_oop, which, error);
          this_oop->tag_at_put(which, JVM_CONSTANT_UnresolvedClassInError);
        } else {
          // some other thread has put the class in error state.
291 292
          error = SystemDictionary::find_resolution_error(this_oop, which);
          assert(error != NULL, "checking");
D
duke 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306
          throw_orig_error = true;
        }
      } // unlocked

      if (throw_orig_error) {
        CLEAR_PENDING_EXCEPTION;
        ResourceMark rm;
        const char* className = this_oop->unresolved_klass_at(which)->as_C_string();
        THROW_MSG_0(error, className);
      }

      return 0;
    }

307
    if (TraceClassResolution && !k()->oop_is_array()) {
D
duke 已提交
308 309 310 311 312 313 314 315 316 317
      // skip resolving the constant pool so that this code get's
      // called the next time some bytecodes refer to this class.
      ResourceMark rm;
      int line_number = -1;
      const char * source_file = NULL;
      if (JavaThread::current()->has_last_Java_frame()) {
        // try to identify the method which called this function.
        vframeStream vfst(JavaThread::current());
        if (!vfst.at_end()) {
          line_number = vfst.method()->line_number_from_bci(vfst.bci());
318
          Symbol* s = vfst.method()->method_holder()->source_file_name();
D
duke 已提交
319 320 321 322 323 324 325 326 327
          if (s != NULL) {
            source_file = s->as_C_string();
          }
        }
      }
      if (k() != this_oop->pool_holder()) {
        // only print something if the classes are different
        if (source_file != NULL) {
          tty->print("RESOLVE %s %s %s:%d\n",
328
                     this_oop->pool_holder()->external_name(),
329
                     InstanceKlass::cast(k())->external_name(), source_file, line_number);
D
duke 已提交
330 331
        } else {
          tty->print("RESOLVE %s %s\n",
332
                     this_oop->pool_holder()->external_name(),
333
                     InstanceKlass::cast(k())->external_name());
D
duke 已提交
334 335 336 337
        }
      }
      return k();
    } else {
338
      MonitorLockerEx ml(this_oop->lock());
D
duke 已提交
339 340 341
      // Only updated constant pool - if it is resolved.
      do_resolve = this_oop->tag_at(which).is_unresolved_klass();
      if (do_resolve) {
342
        ClassLoaderData* this_key = this_oop->pool_holder()->class_loader_data();
343
        this_key->record_dependency(k(), CHECK_NULL); // Can throw OOM
D
duke 已提交
344 345 346 347 348 349
        this_oop->klass_at_put(which, k());
      }
    }
  }

  entry = this_oop->resolved_klass_at(which);
350 351
  assert(entry.is_resolved() && entry.get_klass()->is_klass(), "must be resolved at this point");
  return entry.get_klass();
D
duke 已提交
352 353 354
}


355
// Does not update ConstantPool* - to avoid any exception throwing. Used
D
duke 已提交
356 357 358
// by compiler and exception handling.  Also used to avoid classloads for
// instanceof operations. Returns NULL if the class has not been loaded or
// if the verification of constant pool failed
359
Klass* ConstantPool::klass_at_if_loaded(constantPoolHandle this_oop, int which) {
360
  CPSlot entry = this_oop->slot_at(which);
361 362 363
  if (entry.is_resolved()) {
    assert(entry.get_klass()->is_klass(), "must be");
    return entry.get_klass();
D
duke 已提交
364
  } else {
365
    assert(entry.is_unresolved(), "must be either symbol or klass");
D
duke 已提交
366
    Thread *thread = Thread::current();
367
    Symbol* name = entry.get_symbol();
368 369
    oop loader = this_oop->pool_holder()->class_loader();
    oop protection_domain = this_oop->pool_holder()->protection_domain();
D
duke 已提交
370 371
    Handle h_prot (thread, protection_domain);
    Handle h_loader (thread, loader);
372
    Klass* k = SystemDictionary::find(name, h_loader, h_prot, thread);
D
duke 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391

    if (k != NULL) {
      // Make sure that resolving is legal
      EXCEPTION_MARK;
      KlassHandle klass(THREAD, k);
      // return NULL if verification fails
      verify_constant_pool_resolve(this_oop, klass, THREAD);
      if (HAS_PENDING_EXCEPTION) {
        CLEAR_PENDING_EXCEPTION;
        return NULL;
      }
      return klass();
    } else {
      return k;
    }
  }
}


392
Klass* ConstantPool::klass_ref_at_if_loaded(constantPoolHandle this_oop, int which) {
D
duke 已提交
393 394 395 396
  return klass_at_if_loaded(this_oop, this_oop->klass_ref_index_at(which));
}


397
Method* ConstantPool::method_at_if_loaded(constantPoolHandle cpool,
398
                                                   int which) {
399
  if (cpool->cache() == NULL)  return NULL;  // nothing to load yet
400
  int cache_index = decode_cpcache_index(which, true);
401
  if (!(cache_index >= 0 && cache_index < cpool->cache()->length())) {
402
    // FIXME: should be an assert
403
    if (PrintMiscellaneous && (Verbose||WizardMode)) {
404
      tty->print_cr("bad operand %d in:", which); cpool->print();
405 406 407 408
    }
    return NULL;
  }
  ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
409 410 411 412
  return e->method_if_resolved(cpool);
}


413
bool ConstantPool::has_appendix_at_if_loaded(constantPoolHandle cpool, int which) {
414
  if (cpool->cache() == NULL)  return false;  // nothing to load yet
415 416
  int cache_index = decode_cpcache_index(which, true);
  ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
417 418 419
  return e->has_appendix();
}

420
oop ConstantPool::appendix_at_if_loaded(constantPoolHandle cpool, int which) {
421
  if (cpool->cache() == NULL)  return NULL;  // nothing to load yet
422 423 424
  int cache_index = decode_cpcache_index(which, true);
  ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
  return e->appendix_if_resolved(cpool);
425 426 427
}


428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
bool ConstantPool::has_method_type_at_if_loaded(constantPoolHandle cpool, int which) {
  if (cpool->cache() == NULL)  return false;  // nothing to load yet
  int cache_index = decode_cpcache_index(which, true);
  ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
  return e->has_method_type();
}

oop ConstantPool::method_type_at_if_loaded(constantPoolHandle cpool, int which) {
  if (cpool->cache() == NULL)  return NULL;  // nothing to load yet
  int cache_index = decode_cpcache_index(which, true);
  ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);
  return e->method_type_if_resolved(cpool);
}


443
Symbol* ConstantPool::impl_name_ref_at(int which, bool uncached) {
444
  int name_index = name_ref_index_at(impl_name_and_type_ref_index_at(which, uncached));
D
duke 已提交
445 446 447 448
  return symbol_at(name_index);
}


449
Symbol* ConstantPool::impl_signature_ref_at(int which, bool uncached) {
450
  int signature_index = signature_ref_index_at(impl_name_and_type_ref_index_at(which, uncached));
D
duke 已提交
451 452 453 454
  return symbol_at(signature_index);
}


455
int ConstantPool::impl_name_and_type_ref_index_at(int which, bool uncached) {
456 457
  int i = which;
  if (!uncached && cache() != NULL) {
458 459 460
    if (ConstantPool::is_invokedynamic_index(which)) {
      // Invokedynamic index is index into resolved_references
      int pool_index = invokedynamic_cp_cache_entry_at(which)->constant_pool_index();
461
      pool_index = invoke_dynamic_name_and_type_ref_index_at(pool_index);
462 463 464
      assert(tag_at(pool_index).is_name_and_type(), "");
      return pool_index;
    }
465 466 467
    // change byte-ordering and go via cache
    i = remap_instruction_operand_from_cache(which);
  } else {
468 469 470 471 472
    if (tag_at(which).is_invoke_dynamic()) {
      int pool_index = invoke_dynamic_name_and_type_ref_index_at(which);
      assert(tag_at(pool_index).is_name_and_type(), "");
      return pool_index;
    }
473 474
  }
  assert(tag_at(i).is_field_or_method(), "Corrupted constant pool");
475
  assert(!tag_at(i).is_invoke_dynamic(), "Must be handled above");
476
  jint ref_index = *int_at_addr(i);
D
duke 已提交
477 478 479 480
  return extract_high_short_from_int(ref_index);
}


481 482
int ConstantPool::impl_klass_ref_index_at(int which, bool uncached) {
  guarantee(!ConstantPool::is_invokedynamic_index(which),
483 484 485 486 487 488 489 490
            "an invokedynamic instruction does not have a klass");
  int i = which;
  if (!uncached && cache() != NULL) {
    // change byte-ordering and go via cache
    i = remap_instruction_operand_from_cache(which);
  }
  assert(tag_at(i).is_field_or_method(), "Corrupted constant pool");
  jint ref_index = *int_at_addr(i);
D
duke 已提交
491 492 493 494
  return extract_low_short_from_int(ref_index);
}


495

496
int ConstantPool::remap_instruction_operand_from_cache(int operand) {
497 498 499
  int cpc_index = operand;
  DEBUG_ONLY(cpc_index -= CPCACHE_INDEX_TAG);
  assert((int)(u2)cpc_index == cpc_index, "clean u2");
500 501
  int member_index = cache()->entry_at(cpc_index)->constant_pool_index();
  return member_index;
502 503 504
}


505
void ConstantPool::verify_constant_pool_resolve(constantPoolHandle this_oop, KlassHandle k, TRAPS) {
D
duke 已提交
506 507
 if (k->oop_is_instance() || k->oop_is_objArray()) {
    instanceKlassHandle holder (THREAD, this_oop->pool_holder());
508
    Klass* elem_oop = k->oop_is_instance() ? k() : ObjArrayKlass::cast(k())->bottom_klass();
D
duke 已提交
509 510 511 512 513 514 515 516 517 518 519
    KlassHandle element (THREAD, elem_oop);

    // The element type could be a typeArray - we only need the access check if it is
    // an reference to another class
    if (element->oop_is_instance()) {
      LinkResolver::check_klass_accessability(holder, element, CHECK);
    }
  }
}


520
int ConstantPool::name_ref_index_at(int which_nt) {
521
  jint ref_index = name_and_type_at(which_nt);
D
duke 已提交
522 523 524 525
  return extract_low_short_from_int(ref_index);
}


526
int ConstantPool::signature_ref_index_at(int which_nt) {
527
  jint ref_index = name_and_type_at(which_nt);
D
duke 已提交
528 529 530 531
  return extract_high_short_from_int(ref_index);
}


532
Klass* ConstantPool::klass_ref_at(int which, TRAPS) {
533
  return klass_at(klass_ref_index_at(which), THREAD);
D
duke 已提交
534 535 536
}


537
Symbol* ConstantPool::klass_name_at(int which) {
D
duke 已提交
538 539
  assert(tag_at(which).is_unresolved_klass() || tag_at(which).is_klass(),
         "Corrupted constant pool");
540
  // A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.
D
duke 已提交
541 542
  // It is not safe to rely on the tag bit's here, since we don't have a lock, and the entry and
  // tag is not updated atomicly.
543
  CPSlot entry = slot_at(which);
544
  if (entry.is_resolved()) {
D
duke 已提交
545
    // Already resolved - return entry's name.
546 547
    assert(entry.get_klass()->is_klass(), "must be");
    return entry.get_klass()->name();
D
duke 已提交
548
  } else {
549
    assert(entry.is_unresolved(), "must be either symbol or klass");
550
    return entry.get_symbol();
D
duke 已提交
551 552 553
  }
}

554
Symbol* ConstantPool::klass_ref_at_noresolve(int which) {
D
duke 已提交
555 556 557 558
  jint ref_index = klass_ref_index_at(which);
  return klass_at_noresolve(ref_index);
}

559
Symbol* ConstantPool::uncached_klass_ref_at_noresolve(int which) {
560 561 562 563
  jint ref_index = uncached_klass_ref_index_at(which);
  return klass_at_noresolve(ref_index);
}

564 565 566
char* ConstantPool::string_at_noresolve(int which) {
  Symbol* s = unresolved_string_at(which);
  if (s == NULL) {
567
    return (char*)"<pseudo-string>";
568 569
  } else {
    return unresolved_string_at(which)->as_C_string();
D
duke 已提交
570 571 572
  }
}

573
BasicType ConstantPool::basic_type_for_signature_at(int which) {
D
duke 已提交
574 575 576 577
  return FieldType::basic_type(symbol_at(which));
}


578
void ConstantPool::resolve_string_constants_impl(constantPoolHandle this_oop, TRAPS) {
D
duke 已提交
579
  for (int index = 1; index < this_oop->length(); index++) { // Index 0 is unused
580
    if (this_oop->tag_at(index).is_string()) {
D
duke 已提交
581 582 583 584 585
      this_oop->string_at(index, CHECK);
    }
  }
}

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
// Resolve all the classes in the constant pool.  If they are all resolved,
// the constant pool is read-only.  Enhancement: allocate cp entries to
// another metaspace, and copy to read-only or read-write space if this
// bit is set.
bool ConstantPool::resolve_class_constants(TRAPS) {
  constantPoolHandle cp(THREAD, this);
  for (int index = 1; index < length(); index++) { // Index 0 is unused
    if (tag_at(index).is_unresolved_klass() &&
        klass_at_if_loaded(cp, index) == NULL) {
      return false;
  }
  }
  // set_preresolution(); or some bit for future use
  return true;
}
601

602 603 604 605 606 607
// If resolution for MethodHandle or MethodType fails, save the exception
// in the resolution error table, so that the same exception is thrown again.
void ConstantPool::save_and_throw_exception(constantPoolHandle this_oop, int which,
                                     int tag, TRAPS) {
  ResourceMark rm;
  Symbol* error = PENDING_EXCEPTION->klass()->name();
608
  MonitorLockerEx ml(this_oop->lock());  // lock cpool to change tag.
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

  int error_tag = (tag == JVM_CONSTANT_MethodHandle) ?
           JVM_CONSTANT_MethodHandleInError : JVM_CONSTANT_MethodTypeInError;

  if (!PENDING_EXCEPTION->
    is_a(SystemDictionary::LinkageError_klass())) {
    // Just throw the exception and don't prevent these classes from
    // being loaded due to virtual machine errors like StackOverflow
    // and OutOfMemoryError, etc, or if the thread was hit by stop()
    // Needs clarification to section 5.4.3 of the VM spec (see 6308271)

  } else if (this_oop->tag_at(which).value() != error_tag) {
    SystemDictionary::add_resolution_error(this_oop, which, error);
    this_oop->tag_at_put(which, error_tag);
  } else {
    // some other thread has put the class in error state.
    error = SystemDictionary::find_resolution_error(this_oop, which);
    assert(error != NULL, "checking");
    CLEAR_PENDING_EXCEPTION;
    THROW_MSG(error, "");
629 630 631
  }
}

632 633 634 635 636

// Called to resolve constants in the constant pool and return an oop.
// Some constant pool entries cache their resolved oop. This is also
// called to create oops from constants to use in arguments for invokedynamic
oop ConstantPool::resolve_constant_at_impl(constantPoolHandle this_oop, int index, int cache_index, TRAPS) {
637
  oop result_oop = NULL;
638 639 640
  Handle throw_exception;

  if (cache_index == _possible_index_sentinel) {
641
    // It is possible that this constant is one which is cached in the objects.
642 643
    // We'll do a linear search.  This should be OK because this usage is rare.
    assert(index > 0, "valid index");
644
    cache_index = this_oop->cp_to_object_index(index);
645 646 647 648
  }
  assert(cache_index == _no_index_sentinel || cache_index >= 0, "");
  assert(index == _no_index_sentinel || index >= 0, "");

649
  if (cache_index >= 0) {
650
    result_oop = this_oop->resolved_references()->obj_at(cache_index);
651
    if (result_oop != NULL) {
652
      return result_oop;
653
      // That was easy...
654
    }
655
    index = this_oop->object_to_cp_index(cache_index);
656 657
  }

658 659
  jvalue prim_value;  // temp used only in a few cases below

660
  int tag_value = this_oop->tag_at(index).value();
661

662 663 664 665 666 667
  switch (tag_value) {

  case JVM_CONSTANT_UnresolvedClass:
  case JVM_CONSTANT_UnresolvedClassInError:
  case JVM_CONSTANT_Class:
    {
668 669
      assert(cache_index == _no_index_sentinel, "should not have been set");
      Klass* resolved = klass_at_impl(this_oop, index, CHECK_NULL);
670
      // ldc wants the java mirror.
671
      result_oop = resolved->java_mirror();
672 673 674 675
      break;
    }

  case JVM_CONSTANT_String:
676
    assert(cache_index != _no_index_sentinel, "should have been set");
677
    if (this_oop->is_pseudo_string_at(index)) {
678
      result_oop = this_oop->pseudo_string_at(index, cache_index);
679 680
      break;
    }
681
    result_oop = string_at_impl(this_oop, index, cache_index, CHECK_NULL);
682 683
    break;

684 685 686 687 688 689 690 691 692 693
  case JVM_CONSTANT_MethodHandleInError:
  case JVM_CONSTANT_MethodTypeInError:
    {
      Symbol* error = SystemDictionary::find_resolution_error(this_oop, index);
      guarantee(error != (Symbol*)NULL, "tag mismatch with resolution error table");
      ResourceMark rm;
      THROW_MSG_0(error, "");
      break;
    }

694 695 696 697
  case JVM_CONSTANT_MethodHandle:
    {
      int ref_kind                 = this_oop->method_handle_ref_kind_at(index);
      int callee_index             = this_oop->method_handle_klass_index_at(index);
698 699
      Symbol*  name =      this_oop->method_handle_name_ref_at(index);
      Symbol*  signature = this_oop->method_handle_signature_ref_at(index);
700 701 702 703 704
      if (PrintMiscellaneous)
        tty->print_cr("resolve JVM_CONSTANT_MethodHandle:%d [%d/%d/%d] %s.%s",
                      ref_kind, index, this_oop->method_handle_index_at(index),
                      callee_index, name->as_C_string(), signature->as_C_string());
      KlassHandle callee;
705
      { Klass* k = klass_at_impl(this_oop, callee_index, CHECK_NULL);
706 707 708 709 710
        callee = KlassHandle(THREAD, k);
      }
      KlassHandle klass(THREAD, this_oop->pool_holder());
      Handle value = SystemDictionary::link_method_handle_constant(klass, ref_kind,
                                                                   callee, name, signature,
711
                                                                   THREAD);
712
      result_oop = value();
713
      if (HAS_PENDING_EXCEPTION) {
714
        save_and_throw_exception(this_oop, index, tag_value, CHECK_NULL);
715
      }
716 717 718 719 720
      break;
    }

  case JVM_CONSTANT_MethodType:
    {
721
      Symbol*  signature = this_oop->method_type_signature_at(index);
722 723 724 725 726
      if (PrintMiscellaneous)
        tty->print_cr("resolve JVM_CONSTANT_MethodType [%d/%d] %s",
                      index, this_oop->method_type_index_at(index),
                      signature->as_C_string());
      KlassHandle klass(THREAD, this_oop->pool_holder());
727
      Handle value = SystemDictionary::find_method_handle_type(signature, klass, THREAD);
728
      result_oop = value();
729
      if (HAS_PENDING_EXCEPTION) {
730
        save_and_throw_exception(this_oop, index, tag_value, CHECK_NULL);
731
      }
732 733 734 735
      break;
    }

  case JVM_CONSTANT_Integer:
736
    assert(cache_index == _no_index_sentinel, "should not have been set");
737 738 739 740
    prim_value.i = this_oop->int_at(index);
    result_oop = java_lang_boxing_object::create(T_INT, &prim_value, CHECK_NULL);
    break;

741
  case JVM_CONSTANT_Float:
742
    assert(cache_index == _no_index_sentinel, "should not have been set");
743 744 745 746
    prim_value.f = this_oop->float_at(index);
    result_oop = java_lang_boxing_object::create(T_FLOAT, &prim_value, CHECK_NULL);
    break;

747
  case JVM_CONSTANT_Long:
748
    assert(cache_index == _no_index_sentinel, "should not have been set");
749 750 751 752
    prim_value.j = this_oop->long_at(index);
    result_oop = java_lang_boxing_object::create(T_LONG, &prim_value, CHECK_NULL);
    break;

753
  case JVM_CONSTANT_Double:
754
    assert(cache_index == _no_index_sentinel, "should not have been set");
755 756
    prim_value.d = this_oop->double_at(index);
    result_oop = java_lang_boxing_object::create(T_DOUBLE, &prim_value, CHECK_NULL);
757 758 759 760 761 762 763 764 765 766 767
    break;

  default:
    DEBUG_ONLY( tty->print_cr("*** %p: tag at CP[%d/%d] = %d",
                              this_oop(), index, cache_index, tag_value) );
    assert(false, "unexpected constant tag");
    break;
  }

  if (cache_index >= 0) {
    // Cache the oop here also.
768
    Handle result_handle(THREAD, result_oop);
769
    MonitorLockerEx ml(this_oop->lock());  // don't know if we really need this
770 771
    oop result = this_oop->resolved_references()->obj_at(cache_index);
    // Benign race condition:  resolved_references may already be filled in while we were trying to lock.
772 773 774 775
    // The important thing here is that all threads pick up the same result.
    // It doesn't matter which racing thread wins, as long as only one
    // result is used by all threads, and all future queries.
    // That result may be either a resolved constant or a failure exception.
776 777 778 779 780 781 782
    if (result == NULL) {
      this_oop->resolved_references()->obj_at_put(cache_index, result_handle());
      return result_handle();
    } else {
      // Return the winning thread's result.  This can be different than
      // result_handle() for MethodHandles.
      return result;
783 784 785 786 787 788
    }
  } else {
    return result_oop;
  }
}

789 790 791 792 793 794 795
oop ConstantPool::uncached_string_at(int which, TRAPS) {
  Symbol* sym = unresolved_string_at(which);
  oop str = StringTable::intern(sym, CHECK_(NULL));
  assert(java_lang_String::is_instance(str), "must be string");
  return str;
}

796

797
oop ConstantPool::resolve_bootstrap_specifier_at_impl(constantPoolHandle this_oop, int index, TRAPS) {
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
  assert(this_oop->tag_at(index).is_invoke_dynamic(), "Corrupted constant pool");

  Handle bsm;
  int argc;
  {
    // JVM_CONSTANT_InvokeDynamic is an ordered pair of [bootm, name&type], plus optional arguments
    // The bootm, being a JVM_CONSTANT_MethodHandle, has its own cache entry.
    // It is accompanied by the optional arguments.
    int bsm_index = this_oop->invoke_dynamic_bootstrap_method_ref_index_at(index);
    oop bsm_oop = this_oop->resolve_possibly_cached_constant_at(bsm_index, CHECK_NULL);
    if (!java_lang_invoke_MethodHandle::is_instance(bsm_oop)) {
      THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "BSM not an MethodHandle");
    }

    // Extract the optional static arguments.
    argc = this_oop->invoke_dynamic_argument_count_at(index);
    if (argc == 0)  return bsm_oop;

    bsm = Handle(THREAD, bsm_oop);
  }

  objArrayHandle info;
  {
    objArrayOop info_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(), 1+argc, CHECK_NULL);
    info = objArrayHandle(THREAD, info_oop);
  }

  info->obj_at_put(0, bsm());
  for (int i = 0; i < argc; i++) {
    int arg_index = this_oop->invoke_dynamic_argument_index_at(index, i);
    oop arg_oop = this_oop->resolve_possibly_cached_constant_at(arg_index, CHECK_NULL);
    info->obj_at_put(1+i, arg_oop);
  }

  return info();
}

835 836 837 838
oop ConstantPool::string_at_impl(constantPoolHandle this_oop, int which, int obj_index, TRAPS) {
  // If the string has already been interned, this entry will be non-null
  oop str = this_oop->resolved_references()->obj_at(obj_index);
  if (str != NULL) return str;
839
  Symbol* sym = this_oop->unresolved_string_at(which);
840 841
  str = StringTable::intern(sym, CHECK_(NULL));
  this_oop->string_at_put(which, obj_index, str);
842 843
  assert(java_lang_String::is_instance(str), "must be string");
  return str;
D
duke 已提交
844 845 846
}


847
bool ConstantPool::klass_name_at_matches(instanceKlassHandle k,
D
duke 已提交
848
                                                int which) {
849 850
  // Names are interned, so we can compare Symbol*s directly
  Symbol* cp_name = klass_name_at(which);
D
duke 已提交
851 852 853 854
  return (cp_name == k->name());
}


855 856 857 858 859
// Iterate over symbols and decrement ones which are Symbol*s.
// This is done during GC so do not need to lock constantPool unless we
// have per-thread safepoints.
// Only decrement the UTF8 symbols. Unresolved classes and strings point to
// these symbols but didn't increment the reference count.
860
void ConstantPool::unreference_symbols() {
861 862 863 864 865 866 867
  for (int index = 1; index < length(); index++) { // Index 0 is unused
    constantTag tag = tag_at(index);
    if (tag.is_symbol()) {
      symbol_at(index)->decrement_refcount();
    }
  }
}
D
duke 已提交
868 869 870 871


// Compare this constant pool's entry at index1 to the constant pool
// cp2's entry at index2.
872
bool ConstantPool::compare_entry_to(int index1, constantPoolHandle cp2,
D
duke 已提交
873 874
       int index2, TRAPS) {

875 876 877
  // The error tags are equivalent to non-error tags when comparing
  jbyte t1 = tag_at(index1).non_error_value();
  jbyte t2 = cp2->tag_at(index2).non_error_value();
D
duke 已提交
878 879 880 881

  if (t1 != t2) {
    // Not the same entry type so there is nothing else to check. Note
    // that this style of checking will consider resolved/unresolved
882 883 884 885
    // class pairs as different.
    // From the ConstantPool* API point of view, this is correct
    // behavior. See VM_RedefineClasses::merge_constant_pools() to see how this
    // plays out in the context of ConstantPool* merging.
D
duke 已提交
886 887 888 889 890 891
    return false;
  }

  switch (t1) {
  case JVM_CONSTANT_Class:
  {
892 893
    Klass* k1 = klass_at(index1, CHECK_false);
    Klass* k2 = cp2->klass_at(index2, CHECK_false);
D
duke 已提交
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
    if (k1 == k2) {
      return true;
    }
  } break;

  case JVM_CONSTANT_ClassIndex:
  {
    int recur1 = klass_index_at(index1);
    int recur2 = cp2->klass_index_at(index2);
    bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
    if (match) {
      return true;
    }
  } break;

  case JVM_CONSTANT_Double:
  {
    jdouble d1 = double_at(index1);
    jdouble d2 = cp2->double_at(index2);
    if (d1 == d2) {
      return true;
    }
  } break;

  case JVM_CONSTANT_Fieldref:
  case JVM_CONSTANT_InterfaceMethodref:
  case JVM_CONSTANT_Methodref:
  {
    int recur1 = uncached_klass_ref_index_at(index1);
    int recur2 = cp2->uncached_klass_ref_index_at(index2);
    bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
    if (match) {
      recur1 = uncached_name_and_type_ref_index_at(index1);
      recur2 = cp2->uncached_name_and_type_ref_index_at(index2);
      match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
      if (match) {
        return true;
      }
    }
  } break;

  case JVM_CONSTANT_Float:
  {
    jfloat f1 = float_at(index1);
    jfloat f2 = cp2->float_at(index2);
    if (f1 == f2) {
      return true;
    }
  } break;

  case JVM_CONSTANT_Integer:
  {
    jint i1 = int_at(index1);
    jint i2 = cp2->int_at(index2);
    if (i1 == i2) {
      return true;
    }
  } break;

  case JVM_CONSTANT_Long:
  {
    jlong l1 = long_at(index1);
    jlong l2 = cp2->long_at(index2);
    if (l1 == l2) {
      return true;
    }
  } break;

  case JVM_CONSTANT_NameAndType:
  {
    int recur1 = name_ref_index_at(index1);
    int recur2 = cp2->name_ref_index_at(index2);
    bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
    if (match) {
      recur1 = signature_ref_index_at(index1);
      recur2 = cp2->signature_ref_index_at(index2);
      match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
      if (match) {
        return true;
      }
    }
  } break;

  case JVM_CONSTANT_StringIndex:
  {
    int recur1 = string_index_at(index1);
    int recur2 = cp2->string_index_at(index2);
    bool match = compare_entry_to(recur1, cp2, recur2, CHECK_false);
    if (match) {
      return true;
    }
  } break;

  case JVM_CONSTANT_UnresolvedClass:
  {
989 990
    Symbol* k1 = unresolved_klass_at(index1);
    Symbol* k2 = cp2->unresolved_klass_at(index2);
D
duke 已提交
991 992 993 994 995
    if (k1 == k2) {
      return true;
    }
  } break;

996 997
  case JVM_CONSTANT_MethodType:
  {
998 999
    int k1 = method_type_index_at_error_ok(index1);
    int k2 = cp2->method_type_index_at_error_ok(index2);
1000 1001
    bool match = compare_entry_to(k1, cp2, k2, CHECK_false);
    if (match) {
1002 1003 1004 1005 1006 1007
      return true;
    }
  } break;

  case JVM_CONSTANT_MethodHandle:
  {
1008 1009
    int k1 = method_handle_ref_kind_at_error_ok(index1);
    int k2 = cp2->method_handle_ref_kind_at_error_ok(index2);
1010
    if (k1 == k2) {
1011 1012
      int i1 = method_handle_index_at_error_ok(index1);
      int i2 = cp2->method_handle_index_at_error_ok(index2);
1013 1014
      bool match = compare_entry_to(i1, cp2, i2, CHECK_false);
      if (match) {
1015 1016 1017 1018 1019
        return true;
      }
    }
  } break;

1020 1021
  case JVM_CONSTANT_InvokeDynamic:
  {
1022 1023 1024 1025
    int k1 = invoke_dynamic_name_and_type_ref_index_at(index1);
    int k2 = cp2->invoke_dynamic_name_and_type_ref_index_at(index2);
    int i1 = invoke_dynamic_bootstrap_specifier_index(index1);
    int i2 = cp2->invoke_dynamic_bootstrap_specifier_index(index2);
C
ccheung 已提交
1026 1027 1028 1029
    // separate statements and variables because CHECK_false is used
    bool match_entry = compare_entry_to(k1, cp2, k2, CHECK_false);
    bool match_operand = compare_operand_to(i1, cp2, i2, CHECK_false);
    return (match_entry && match_operand);
1030 1031
  } break;

1032
  case JVM_CONSTANT_String:
D
duke 已提交
1033
  {
1034 1035
    Symbol* s1 = unresolved_string_at(index1);
    Symbol* s2 = cp2->unresolved_string_at(index2);
D
duke 已提交
1036 1037 1038 1039 1040 1041 1042
    if (s1 == s2) {
      return true;
    }
  } break;

  case JVM_CONSTANT_Utf8:
  {
1043 1044
    Symbol* s1 = symbol_at(index1);
    Symbol* s2 = cp2->symbol_at(index2);
D
duke 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
    if (s1 == s2) {
      return true;
    }
  } break;

  // Invalid is used as the tag for the second constant pool entry
  // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
  // not be seen by itself.
  case JVM_CONSTANT_Invalid: // fall through

  default:
    ShouldNotReachHere();
    break;
  }

  return false;
} // end compare_entry_to()


1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
// Resize the operands array with delta_len and delta_size.
// Used in RedefineClasses for CP merge.
void ConstantPool::resize_operands(int delta_len, int delta_size, TRAPS) {
  int old_len  = operand_array_length(operands());
  int new_len  = old_len + delta_len;
  int min_len  = (delta_len > 0) ? old_len : new_len;

  int old_size = operands()->length();
  int new_size = old_size + delta_size;
  int min_size = (delta_size > 0) ? old_size : new_size;

  ClassLoaderData* loader_data = pool_holder()->class_loader_data();
  Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, new_size, CHECK);

  // Set index in the resized array for existing elements only
  for (int idx = 0; idx < min_len; idx++) {
    int offset = operand_offset_at(idx);                       // offset in original array
    operand_offset_at_put(new_ops, idx, offset + 2*delta_len); // offset in resized array
  }
  // Copy the bootstrap specifiers only
  Copy::conjoint_memory_atomic(operands()->adr_at(2*old_len),
                               new_ops->adr_at(2*new_len),
                               (min_size - 2*min_len) * sizeof(u2));
  // Explicitly deallocate old operands array.
  // Note, it is not needed for 7u backport.
  if ( operands() != NULL) { // the safety check
    MetadataFactory::free_array<u2>(loader_data, operands());
  }
  set_operands(new_ops);
} // end resize_operands()


// Extend the operands array with the length and size of the ext_cp operands.
// Used in RedefineClasses for CP merge.
void ConstantPool::extend_operands(constantPoolHandle ext_cp, TRAPS) {
  int delta_len = operand_array_length(ext_cp->operands());
  if (delta_len == 0) {
    return; // nothing to do
  }
  int delta_size = ext_cp->operands()->length();

  assert(delta_len  > 0 && delta_size > 0, "extended operands array must be bigger");

  if (operand_array_length(operands()) == 0) {
    ClassLoaderData* loader_data = pool_holder()->class_loader_data();
    Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, delta_size, CHECK);
    // The first element index defines the offset of second part
    operand_offset_at_put(new_ops, 0, 2*delta_len); // offset in new array
    set_operands(new_ops);
  } else {
    resize_operands(delta_len, delta_size, CHECK);
  }

} // end extend_operands()


// Shrink the operands array to a smaller array with new_len length.
// Used in RedefineClasses for CP merge.
void ConstantPool::shrink_operands(int new_len, TRAPS) {
  int old_len = operand_array_length(operands());
  if (new_len == old_len) {
    return; // nothing to do
  }
  assert(new_len < old_len, "shrunken operands array must be smaller");

  int free_base  = operand_next_offset_at(new_len - 1);
  int delta_len  = new_len - old_len;
  int delta_size = 2*delta_len + free_base - operands()->length();

  resize_operands(delta_len, delta_size, CHECK);

} // end shrink_operands()


1138 1139 1140
void ConstantPool::copy_operands(constantPoolHandle from_cp,
                                 constantPoolHandle to_cp,
                                 TRAPS) {
1141 1142 1143 1144

  int from_oplen = operand_array_length(from_cp->operands());
  int old_oplen  = operand_array_length(to_cp->operands());
  if (from_oplen != 0) {
1145
    ClassLoaderData* loader_data = to_cp->pool_holder()->class_loader_data();
1146 1147
    // append my operands to the target's operands array
    if (old_oplen == 0) {
1148 1149 1150 1151 1152 1153
      // Can't just reuse from_cp's operand list because of deallocation issues
      int len = from_cp->operands()->length();
      Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, len, CHECK);
      Copy::conjoint_memory_atomic(
          from_cp->operands()->adr_at(0), new_ops->adr_at(0), len * sizeof(u2));
      to_cp->set_operands(new_ops);
1154 1155 1156 1157 1158
    } else {
      int old_len  = to_cp->operands()->length();
      int from_len = from_cp->operands()->length();
      int old_off  = old_oplen * sizeof(u2);
      int from_off = from_oplen * sizeof(u2);
1159 1160
      // Use the metaspace for the destination constant pool
      Array<u2>* new_operands = MetadataFactory::new_array<u2>(loader_data, old_len + from_len, CHECK);
1161 1162
      int fillp = 0, len = 0;
      // first part of dest
1163 1164
      Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(0),
                                   new_operands->adr_at(fillp),
1165 1166 1167
                                   (len = old_off) * sizeof(u2));
      fillp += len;
      // first part of src
1168
      Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(0),
1169
                                   new_operands->adr_at(fillp),
1170 1171 1172
                                   (len = from_off) * sizeof(u2));
      fillp += len;
      // second part of dest
1173 1174
      Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(old_off),
                                   new_operands->adr_at(fillp),
1175 1176 1177
                                   (len = old_len - old_off) * sizeof(u2));
      fillp += len;
      // second part of src
1178
      Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(from_off),
1179
                                   new_operands->adr_at(fillp),
1180 1181 1182 1183 1184 1185
                                   (len = from_len - from_off) * sizeof(u2));
      fillp += len;
      assert(fillp == new_operands->length(), "");

      // Adjust indexes in the first part of the copied operands array.
      for (int j = 0; j < from_oplen; j++) {
1186
        int offset = operand_offset_at(new_operands, old_oplen + j);
1187 1188
        assert(offset == operand_offset_at(from_cp->operands(), j), "correct copy");
        offset += old_len;  // every new tuple is preceded by old_len extra u2's
1189
        operand_offset_at_put(new_operands, old_oplen + j, offset);
1190 1191 1192
      }

      // replace target operands array with combined array
1193
      to_cp->set_operands(new_operands);
1194 1195
    }
  }
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
} // end copy_operands()


// Copy this constant pool's entries at start_i to end_i (inclusive)
// to the constant pool to_cp's entries starting at to_i. A total of
// (end_i - start_i) + 1 entries are copied.
void ConstantPool::copy_cp_to_impl(constantPoolHandle from_cp, int start_i, int end_i,
       constantPoolHandle to_cp, int to_i, TRAPS) {


  int dest_i = to_i;  // leave original alone for debug purposes

  for (int src_i = start_i; src_i <= end_i; /* see loop bottom */ ) {
    copy_entry_to(from_cp, src_i, to_cp, dest_i, CHECK);

    switch (from_cp->tag_at(src_i).value()) {
    case JVM_CONSTANT_Double:
    case JVM_CONSTANT_Long:
      // double and long take two constant pool entries
      src_i += 2;
      dest_i += 2;
      break;

    default:
      // all others take one constant pool entry
      src_i++;
      dest_i++;
      break;
    }
  }
  copy_operands(from_cp, to_cp, CHECK);
1227

1228
} // end copy_cp_to_impl()
D
duke 已提交
1229 1230 1231 1232


// Copy this constant pool's entry at from_i to the constant pool
// to_cp's entry at to_i.
1233
void ConstantPool::copy_entry_to(constantPoolHandle from_cp, int from_i,
1234 1235
                                        constantPoolHandle to_cp, int to_i,
                                        TRAPS) {
D
duke 已提交
1236

1237 1238
  int tag = from_cp->tag_at(from_i).value();
  switch (tag) {
D
duke 已提交
1239 1240
  case JVM_CONSTANT_Class:
  {
1241
    Klass* k = from_cp->klass_at(from_i, CHECK);
D
duke 已提交
1242 1243 1244 1245 1246
    to_cp->klass_at_put(to_i, k);
  } break;

  case JVM_CONSTANT_ClassIndex:
  {
1247
    jint ki = from_cp->klass_index_at(from_i);
D
duke 已提交
1248 1249 1250 1251 1252
    to_cp->klass_index_at_put(to_i, ki);
  } break;

  case JVM_CONSTANT_Double:
  {
1253
    jdouble d = from_cp->double_at(from_i);
D
duke 已提交
1254 1255 1256 1257 1258 1259 1260
    to_cp->double_at_put(to_i, d);
    // double takes two constant pool entries so init second entry's tag
    to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
  } break;

  case JVM_CONSTANT_Fieldref:
  {
1261 1262
    int class_index = from_cp->uncached_klass_ref_index_at(from_i);
    int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
D
duke 已提交
1263 1264 1265 1266 1267
    to_cp->field_at_put(to_i, class_index, name_and_type_index);
  } break;

  case JVM_CONSTANT_Float:
  {
1268
    jfloat f = from_cp->float_at(from_i);
D
duke 已提交
1269 1270 1271 1272 1273
    to_cp->float_at_put(to_i, f);
  } break;

  case JVM_CONSTANT_Integer:
  {
1274
    jint i = from_cp->int_at(from_i);
D
duke 已提交
1275 1276 1277 1278 1279
    to_cp->int_at_put(to_i, i);
  } break;

  case JVM_CONSTANT_InterfaceMethodref:
  {
1280 1281
    int class_index = from_cp->uncached_klass_ref_index_at(from_i);
    int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
D
duke 已提交
1282 1283 1284 1285 1286
    to_cp->interface_method_at_put(to_i, class_index, name_and_type_index);
  } break;

  case JVM_CONSTANT_Long:
  {
1287
    jlong l = from_cp->long_at(from_i);
D
duke 已提交
1288 1289 1290 1291 1292 1293 1294
    to_cp->long_at_put(to_i, l);
    // long takes two constant pool entries so init second entry's tag
    to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);
  } break;

  case JVM_CONSTANT_Methodref:
  {
1295 1296
    int class_index = from_cp->uncached_klass_ref_index_at(from_i);
    int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);
D
duke 已提交
1297 1298 1299 1300 1301
    to_cp->method_at_put(to_i, class_index, name_and_type_index);
  } break;

  case JVM_CONSTANT_NameAndType:
  {
1302 1303
    int name_ref_index = from_cp->name_ref_index_at(from_i);
    int signature_ref_index = from_cp->signature_ref_index_at(from_i);
D
duke 已提交
1304 1305 1306 1307 1308
    to_cp->name_and_type_at_put(to_i, name_ref_index, signature_ref_index);
  } break;

  case JVM_CONSTANT_StringIndex:
  {
1309
    jint si = from_cp->string_index_at(from_i);
D
duke 已提交
1310 1311 1312 1313
    to_cp->string_index_at_put(to_i, si);
  } break;

  case JVM_CONSTANT_UnresolvedClass:
1314
  case JVM_CONSTANT_UnresolvedClassInError:
D
duke 已提交
1315
  {
1316 1317
    // Can be resolved after checking tag, so check the slot first.
    CPSlot entry = from_cp->slot_at(from_i);
1318 1319
    if (entry.is_resolved()) {
      assert(entry.get_klass()->is_klass(), "must be");
1320
      // Already resolved
1321
      to_cp->klass_at_put(to_i, entry.get_klass());
1322 1323 1324
    } else {
      to_cp->unresolved_klass_at_put(to_i, entry.get_symbol());
    }
D
duke 已提交
1325 1326
  } break;

1327
  case JVM_CONSTANT_String:
D
duke 已提交
1328
  {
1329 1330
    Symbol* s = from_cp->unresolved_string_at(from_i);
    to_cp->unresolved_string_at_put(to_i, s);
D
duke 已提交
1331 1332 1333 1334
  } break;

  case JVM_CONSTANT_Utf8:
  {
1335
    Symbol* s = from_cp->symbol_at(from_i);
1336 1337
    // Need to increase refcount, the old one will be thrown away and deferenced
    s->increment_refcount();
D
duke 已提交
1338 1339 1340
    to_cp->symbol_at_put(to_i, s);
  } break;

1341
  case JVM_CONSTANT_MethodType:
1342
  case JVM_CONSTANT_MethodTypeInError:
1343
  {
1344
    jint k = from_cp->method_type_index_at_error_ok(from_i);
1345 1346 1347 1348
    to_cp->method_type_index_at_put(to_i, k);
  } break;

  case JVM_CONSTANT_MethodHandle:
1349
  case JVM_CONSTANT_MethodHandleInError:
1350
  {
1351 1352
    int k1 = from_cp->method_handle_ref_kind_at_error_ok(from_i);
    int k2 = from_cp->method_handle_index_at_error_ok(from_i);
1353 1354 1355
    to_cp->method_handle_index_at_put(to_i, k1, k2);
  } break;

1356 1357
  case JVM_CONSTANT_InvokeDynamic:
  {
1358 1359 1360 1361
    int k1 = from_cp->invoke_dynamic_bootstrap_specifier_index(from_i);
    int k2 = from_cp->invoke_dynamic_name_and_type_ref_index_at(from_i);
    k1 += operand_array_length(to_cp->operands());  // to_cp might already have operands
    to_cp->invoke_dynamic_at_put(to_i, k1, k2);
1362 1363
  } break;

D
duke 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
  // Invalid is used as the tag for the second constant pool entry
  // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
  // not be seen by itself.
  case JVM_CONSTANT_Invalid: // fall through

  default:
  {
    ShouldNotReachHere();
  } break;
  }
} // end copy_entry_to()


// Search constant pool search_cp for an entry that matches this
// constant pool's entry at pattern_i. Returns the index of a
// matching entry or zero (0) if there is no matching entry.
1380
int ConstantPool::find_matching_entry(int pattern_i,
D
duke 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
      constantPoolHandle search_cp, TRAPS) {

  // index zero (0) is not used
  for (int i = 1; i < search_cp->length(); i++) {
    bool found = compare_entry_to(pattern_i, search_cp, i, CHECK_0);
    if (found) {
      return i;
    }
  }

  return 0;  // entry not found; return unused index zero (0)
} // end find_matching_entry()


1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
// Compare this constant pool's bootstrap specifier at idx1 to the constant pool
// cp2's bootstrap specifier at idx2.
bool ConstantPool::compare_operand_to(int idx1, constantPoolHandle cp2, int idx2, TRAPS) {
  int k1 = operand_bootstrap_method_ref_index_at(idx1);
  int k2 = cp2->operand_bootstrap_method_ref_index_at(idx2);
  bool match = compare_entry_to(k1, cp2, k2, CHECK_false);

  if (!match) {
    return false;
  }
  int argc = operand_argument_count_at(idx1);
  if (argc == cp2->operand_argument_count_at(idx2)) {
    for (int j = 0; j < argc; j++) {
      k1 = operand_argument_index_at(idx1, j);
      k2 = cp2->operand_argument_index_at(idx2, j);
      match = compare_entry_to(k1, cp2, k2, CHECK_false);
      if (!match) {
        return false;
      }
    }
    return true;           // got through loop; all elements equal
  }
  return false;
} // end compare_operand_to()

// Search constant pool search_cp for a bootstrap specifier that matches
// this constant pool's bootstrap specifier at pattern_i index.
// Return the index of a matching bootstrap specifier or (-1) if there is no match.
int ConstantPool::find_matching_operand(int pattern_i,
                    constantPoolHandle search_cp, int search_len, TRAPS) {
  for (int i = 0; i < search_len; i++) {
    bool found = compare_operand_to(pattern_i, search_cp, i, CHECK_(-1));
    if (found) {
      return i;
    }
  }
  return -1;  // bootstrap specifier not found; return unused index (-1)
} // end find_matching_operand()


D
duke 已提交
1435 1436
#ifndef PRODUCT

1437
const char* ConstantPool::printable_name_at(int which) {
D
duke 已提交
1438 1439 1440

  constantTag tag = tag_at(which);

1441
  if (tag.is_string()) {
D
duke 已提交
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
    return string_at_noresolve(which);
  } else if (tag.is_klass() || tag.is_unresolved_klass()) {
    return klass_name_at(which)->as_C_string();
  } else if (tag.is_symbol()) {
    return symbol_at(which)->as_C_string();
  }
  return "";
}

#endif // PRODUCT


// JVMTI GetConstantPool support

1456 1457
// For debugging of constant pool
const bool debug_cpool = false;
D
duke 已提交
1458

1459
#define DBG(code) do { if (debug_cpool) { (code); } } while(0)
D
duke 已提交
1460 1461

static void print_cpool_bytes(jint cnt, u1 *bytes) {
1462
  const char* WARN_MSG = "Must not be such entry!";
D
duke 已提交
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
  jint size = 0;
  u2   idx1, idx2;

  for (jint idx = 1; idx < cnt; idx++) {
    jint ent_size = 0;
    u1   tag  = *bytes++;
    size++;                       // count tag

    printf("const #%03d, tag: %02d ", idx, tag);
    switch(tag) {
      case JVM_CONSTANT_Invalid: {
        printf("Invalid");
        break;
      }
      case JVM_CONSTANT_Unicode: {
        printf("Unicode      %s", WARN_MSG);
        break;
      }
      case JVM_CONSTANT_Utf8: {
        u2 len = Bytes::get_Java_u2(bytes);
        char str[128];
        if (len > 127) {
           len = 127;
        }
        strncpy(str, (char *) (bytes+2), len);
        str[len] = '\0';
        printf("Utf8          \"%s\"", str);
        ent_size = 2 + len;
        break;
      }
      case JVM_CONSTANT_Integer: {
        u4 val = Bytes::get_Java_u4(bytes);
        printf("int          %d", *(int *) &val);
        ent_size = 4;
        break;
      }
      case JVM_CONSTANT_Float: {
        u4 val = Bytes::get_Java_u4(bytes);
        printf("float        %5.3ff", *(float *) &val);
        ent_size = 4;
        break;
      }
      case JVM_CONSTANT_Long: {
        u8 val = Bytes::get_Java_u8(bytes);
1507
        printf("long         " INT64_FORMAT, (int64_t) *(jlong *) &val);
D
duke 已提交
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
        ent_size = 8;
        idx++; // Long takes two cpool slots
        break;
      }
      case JVM_CONSTANT_Double: {
        u8 val = Bytes::get_Java_u8(bytes);
        printf("double       %5.3fd", *(jdouble *)&val);
        ent_size = 8;
        idx++; // Double takes two cpool slots
        break;
      }
      case JVM_CONSTANT_Class: {
        idx1 = Bytes::get_Java_u2(bytes);
        printf("class        #%03d", idx1);
        ent_size = 2;
        break;
      }
      case JVM_CONSTANT_String: {
        idx1 = Bytes::get_Java_u2(bytes);
        printf("String       #%03d", idx1);
        ent_size = 2;
        break;
      }
      case JVM_CONSTANT_Fieldref: {
        idx1 = Bytes::get_Java_u2(bytes);
        idx2 = Bytes::get_Java_u2(bytes+2);
        printf("Field        #%03d, #%03d", (int) idx1, (int) idx2);
        ent_size = 4;
        break;
      }
      case JVM_CONSTANT_Methodref: {
        idx1 = Bytes::get_Java_u2(bytes);
        idx2 = Bytes::get_Java_u2(bytes+2);
        printf("Method       #%03d, #%03d", idx1, idx2);
        ent_size = 4;
        break;
      }
      case JVM_CONSTANT_InterfaceMethodref: {
        idx1 = Bytes::get_Java_u2(bytes);
        idx2 = Bytes::get_Java_u2(bytes+2);
        printf("InterfMethod #%03d, #%03d", idx1, idx2);
        ent_size = 4;
        break;
      }
      case JVM_CONSTANT_NameAndType: {
        idx1 = Bytes::get_Java_u2(bytes);
        idx2 = Bytes::get_Java_u2(bytes+2);
        printf("NameAndType  #%03d, #%03d", idx1, idx2);
        ent_size = 4;
        break;
      }
      case JVM_CONSTANT_ClassIndex: {
        printf("ClassIndex  %s", WARN_MSG);
        break;
      }
      case JVM_CONSTANT_UnresolvedClass: {
        printf("UnresolvedClass: %s", WARN_MSG);
        break;
      }
      case JVM_CONSTANT_UnresolvedClassInError: {
        printf("UnresolvedClassInErr: %s", WARN_MSG);
        break;
      }
      case JVM_CONSTANT_StringIndex: {
        printf("StringIndex: %s", WARN_MSG);
        break;
      }
    }
    printf(";\n");
    bytes += ent_size;
    size  += ent_size;
  }
  printf("Cpool size: %d\n", size);
  fflush(0);
  return;
} /* end print_cpool_bytes */


// Returns size of constant pool entry.
1587
jint ConstantPool::cpool_entry_size(jint idx) {
D
duke 已提交
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
  switch(tag_at(idx).value()) {
    case JVM_CONSTANT_Invalid:
    case JVM_CONSTANT_Unicode:
      return 1;

    case JVM_CONSTANT_Utf8:
      return 3 + symbol_at(idx)->utf8_length();

    case JVM_CONSTANT_Class:
    case JVM_CONSTANT_String:
    case JVM_CONSTANT_ClassIndex:
    case JVM_CONSTANT_UnresolvedClass:
    case JVM_CONSTANT_UnresolvedClassInError:
    case JVM_CONSTANT_StringIndex:
1602
    case JVM_CONSTANT_MethodType:
1603
    case JVM_CONSTANT_MethodTypeInError:
D
duke 已提交
1604 1605
      return 3;

1606
    case JVM_CONSTANT_MethodHandle:
1607
    case JVM_CONSTANT_MethodHandleInError:
1608 1609
      return 4; //tag, ref_kind, ref_index

D
duke 已提交
1610 1611 1612 1613 1614 1615 1616 1617
    case JVM_CONSTANT_Integer:
    case JVM_CONSTANT_Float:
    case JVM_CONSTANT_Fieldref:
    case JVM_CONSTANT_Methodref:
    case JVM_CONSTANT_InterfaceMethodref:
    case JVM_CONSTANT_NameAndType:
      return 5;

1618
    case JVM_CONSTANT_InvokeDynamic:
1619 1620
      // u1 tag, u2 bsm, u2 nt
      return 5;
1621

D
duke 已提交
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
    case JVM_CONSTANT_Long:
    case JVM_CONSTANT_Double:
      return 9;
  }
  assert(false, "cpool_entry_size: Invalid constant pool entry tag");
  return 1;
} /* end cpool_entry_size */


// SymbolHashMap is used to find a constant pool index from a string.
// This function fills in SymbolHashMaps, one for utf8s and one for
// class names, returns size of the cpool raw bytes.
1634
jint ConstantPool::hash_entries_to(SymbolHashMap *symmap,
D
duke 已提交
1635 1636 1637 1638 1639 1640 1641 1642 1643
                                          SymbolHashMap *classmap) {
  jint size = 0;

  for (u2 idx = 1; idx < length(); idx++) {
    u2 tag = tag_at(idx).value();
    size += cpool_entry_size(idx);

    switch(tag) {
      case JVM_CONSTANT_Utf8: {
1644
        Symbol* sym = symbol_at(idx);
D
duke 已提交
1645 1646 1647 1648 1649 1650 1651
        symmap->add_entry(sym, idx);
        DBG(printf("adding symbol entry %s = %d\n", sym->as_utf8(), idx));
        break;
      }
      case JVM_CONSTANT_Class:
      case JVM_CONSTANT_UnresolvedClass:
      case JVM_CONSTANT_UnresolvedClassInError: {
1652
        Symbol* sym = klass_name_at(idx);
D
duke 已提交
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
        classmap->add_entry(sym, idx);
        DBG(printf("adding class entry %s = %d\n", sym->as_utf8(), idx));
        break;
      }
      case JVM_CONSTANT_Long:
      case JVM_CONSTANT_Double: {
        idx++; // Both Long and Double take two cpool slots
        break;
      }
    }
  }
  return size;
} /* end hash_utf8_entries_to */


// Copy cpool bytes.
// Returns:
//    0, in case of OutOfMemoryError
//   -1, in case of internal error
//  > 0, count of the raw cpool bytes that have been copied
1673
int ConstantPool::copy_cpool_bytes(int cpool_size,
D
duke 已提交
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
                                          SymbolHashMap* tbl,
                                          unsigned char *bytes) {
  u2   idx1, idx2;
  jint size  = 0;
  jint cnt   = length();
  unsigned char *start_bytes = bytes;

  for (jint idx = 1; idx < cnt; idx++) {
    u1   tag      = tag_at(idx).value();
    jint ent_size = cpool_entry_size(idx);

    assert(size + ent_size <= cpool_size, "Size mismatch");

    *bytes = tag;
    DBG(printf("#%03hd tag=%03hd, ", idx, tag));
    switch(tag) {
      case JVM_CONSTANT_Invalid: {
        DBG(printf("JVM_CONSTANT_Invalid"));
        break;
      }
      case JVM_CONSTANT_Unicode: {
        assert(false, "Wrong constant pool tag: JVM_CONSTANT_Unicode");
        DBG(printf("JVM_CONSTANT_Unicode"));
        break;
      }
      case JVM_CONSTANT_Utf8: {
1700
        Symbol* sym = symbol_at(idx);
D
duke 已提交
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
        char*     str = sym->as_utf8();
        // Warning! It's crashing on x86 with len = sym->utf8_length()
        int       len = (int) strlen(str);
        Bytes::put_Java_u2((address) (bytes+1), (u2) len);
        for (int i = 0; i < len; i++) {
            bytes[3+i] = (u1) str[i];
        }
        DBG(printf("JVM_CONSTANT_Utf8: %s ", str));
        break;
      }
      case JVM_CONSTANT_Integer: {
        jint val = int_at(idx);
        Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
        break;
      }
      case JVM_CONSTANT_Float: {
        jfloat val = float_at(idx);
        Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);
        break;
      }
      case JVM_CONSTANT_Long: {
        jlong val = long_at(idx);
        Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
        idx++;             // Long takes two cpool slots
        break;
      }
      case JVM_CONSTANT_Double: {
        jdouble val = double_at(idx);
        Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);
        idx++;             // Double takes two cpool slots
        break;
      }
      case JVM_CONSTANT_Class:
      case JVM_CONSTANT_UnresolvedClass:
      case JVM_CONSTANT_UnresolvedClassInError: {
        *bytes = JVM_CONSTANT_Class;
1737
        Symbol* sym = klass_name_at(idx);
D
duke 已提交
1738 1739 1740 1741 1742 1743 1744 1745
        idx1 = tbl->symbol_to_value(sym);
        assert(idx1 != 0, "Have not found a hashtable entry");
        Bytes::put_Java_u2((address) (bytes+1), idx1);
        DBG(printf("JVM_CONSTANT_Class: idx=#%03hd, %s", idx1, sym->as_utf8()));
        break;
      }
      case JVM_CONSTANT_String: {
        *bytes = JVM_CONSTANT_String;
1746
        Symbol* sym = unresolved_string_at(idx);
D
duke 已提交
1747 1748 1749
        idx1 = tbl->symbol_to_value(sym);
        assert(idx1 != 0, "Have not found a hashtable entry");
        Bytes::put_Java_u2((address) (bytes+1), idx1);
1750
        DBG(printf("JVM_CONSTANT_String: idx=#%03hd, %s", idx1, sym->as_utf8()));
D
duke 已提交
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
        break;
      }
      case JVM_CONSTANT_Fieldref:
      case JVM_CONSTANT_Methodref:
      case JVM_CONSTANT_InterfaceMethodref: {
        idx1 = uncached_klass_ref_index_at(idx);
        idx2 = uncached_name_and_type_ref_index_at(idx);
        Bytes::put_Java_u2((address) (bytes+1), idx1);
        Bytes::put_Java_u2((address) (bytes+3), idx2);
        DBG(printf("JVM_CONSTANT_Methodref: %hd %hd", idx1, idx2));
        break;
      }
      case JVM_CONSTANT_NameAndType: {
        idx1 = name_ref_index_at(idx);
        idx2 = signature_ref_index_at(idx);
        Bytes::put_Java_u2((address) (bytes+1), idx1);
        Bytes::put_Java_u2((address) (bytes+3), idx2);
        DBG(printf("JVM_CONSTANT_NameAndType: %hd %hd", idx1, idx2));
        break;
      }
      case JVM_CONSTANT_ClassIndex: {
        *bytes = JVM_CONSTANT_Class;
        idx1 = klass_index_at(idx);
        Bytes::put_Java_u2((address) (bytes+1), idx1);
        DBG(printf("JVM_CONSTANT_ClassIndex: %hd", idx1));
        break;
      }
      case JVM_CONSTANT_StringIndex: {
        *bytes = JVM_CONSTANT_String;
        idx1 = string_index_at(idx);
        Bytes::put_Java_u2((address) (bytes+1), idx1);
        DBG(printf("JVM_CONSTANT_StringIndex: %hd", idx1));
        break;
      }
1785 1786
      case JVM_CONSTANT_MethodHandle:
      case JVM_CONSTANT_MethodHandleInError: {
1787
        *bytes = JVM_CONSTANT_MethodHandle;
1788 1789
        int kind = method_handle_ref_kind_at_error_ok(idx);
        idx1 = method_handle_index_at_error_ok(idx);
1790 1791 1792 1793 1794
        *(bytes+1) = (unsigned char) kind;
        Bytes::put_Java_u2((address) (bytes+2), idx1);
        DBG(printf("JVM_CONSTANT_MethodHandle: %d %hd", kind, idx1));
        break;
      }
1795 1796
      case JVM_CONSTANT_MethodType:
      case JVM_CONSTANT_MethodTypeInError: {
1797
        *bytes = JVM_CONSTANT_MethodType;
1798
        idx1 = method_type_index_at_error_ok(idx);
1799 1800 1801 1802
        Bytes::put_Java_u2((address) (bytes+1), idx1);
        DBG(printf("JVM_CONSTANT_MethodType: %hd", idx1));
        break;
      }
1803
      case JVM_CONSTANT_InvokeDynamic: {
1804 1805 1806 1807
        *bytes = tag;
        idx1 = extract_low_short_from_int(*int_at_addr(idx));
        idx2 = extract_high_short_from_int(*int_at_addr(idx));
        assert(idx2 == invoke_dynamic_name_and_type_ref_index_at(idx), "correct half of u4");
1808 1809
        Bytes::put_Java_u2((address) (bytes+1), idx1);
        Bytes::put_Java_u2((address) (bytes+3), idx2);
1810
        DBG(printf("JVM_CONSTANT_InvokeDynamic: %hd %hd", idx1, idx2));
1811 1812
        break;
      }
D
duke 已提交
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
    }
    DBG(printf("\n"));
    bytes += ent_size;
    size  += ent_size;
  }
  assert(size == cpool_size, "Size mismatch");

  // Keep temorarily for debugging until it's stable.
  DBG(print_cpool_bytes(cnt, start_bytes));
  return (int)(bytes - start_bytes);
} /* end copy_cpool_bytes */

1825 1826
#undef DBG

D
duke 已提交
1827

1828
void ConstantPool::set_on_stack(const bool value) {
1829
  if (value) {
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
    int old_flags = *const_cast<volatile int *>(&_flags);
    while ((old_flags & _on_stack) == 0) {
      int new_flags = old_flags | _on_stack;
      int result = Atomic::cmpxchg(new_flags, &_flags, old_flags);

      if (result == old_flags) {
        // Succeeded.
        MetadataOnStackMark::record(this, Thread::current());
        return;
      }
      old_flags = result;
    }
1842
  } else {
1843
    // Clearing is done single-threadedly.
1844 1845
    _flags &= ~_on_stack;
  }
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
}

// JSR 292 support for patching constant pool oops after the class is linked and
// the oop array for resolved references are created.
// We can't do this during classfile parsing, which is how the other indexes are
// patched.  The other patches are applied early for some error checking
// so only defer the pseudo_strings.
void ConstantPool::patch_resolved_references(
                                            GrowableArray<Handle>* cp_patches) {
  assert(EnableInvokeDynamic, "");
  for (int index = 1; index < cp_patches->length(); index++) { // Index 0 is unused
    Handle patch = cp_patches->at(index);
    if (patch.not_null()) {
      assert (tag_at(index).is_string(), "should only be string left");
      // Patching a string means pre-resolving it.
      // The spelling in the constant pool is ignored.
      // The constant reference may be any object whatever.
      // If it is not a real interned string, the constant is referred
      // to as a "pseudo-string", and must be presented to the CP
      // explicitly, because it may require scavenging.
      int obj_index = cp_to_object_index(index);
      pseudo_string_at_put(index, obj_index, patch());
      DEBUG_ONLY(cp_patches->at_put(index, Handle());)
    }
  }
#ifdef ASSERT
  // Ensure that all the patches have been used.
  for (int index = 0; index < cp_patches->length(); index++) {
    assert(cp_patches->at(index).is_null(),
           err_msg("Unused constant pool patch at %d in class file %s",
                   index,
1877
                   pool_holder()->external_name()));
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
  }
#endif // ASSERT
}

#ifndef PRODUCT

// CompileTheWorld support. Preload all classes loaded references in the passed in constantpool
void ConstantPool::preload_and_initialize_all_classes(ConstantPool* obj, TRAPS) {
  guarantee(obj->is_constantPool(), "object must be constant pool");
  constantPoolHandle cp(THREAD, (ConstantPool*)obj);
  guarantee(cp->pool_holder() != NULL, "must be fully loaded");

  for (int i = 0; i< cp->length();  i++) {
    if (cp->tag_at(i).is_unresolved_klass()) {
      // This will force loading of the class
      Klass* klass = cp->klass_at(i, CHECK);
      if (klass->oop_is_instance()) {
        // Force initialization of class
        InstanceKlass::cast(klass)->initialize(CHECK);
      }
    }
  }
}

#endif


// Printing

void ConstantPool::print_on(outputStream* st) const {
  EXCEPTION_MARK;
  assert(is_constantPool(), "must be constantPool");
1910
  st->print_cr("%s", internal_name());
1911 1912 1913
  if (flags() != 0) {
    st->print(" - flags: 0x%x", flags());
    if (has_preresolution()) st->print(" has_preresolution");
1914
    if (on_stack()) st->print(" on_stack");
1915 1916 1917 1918 1919 1920
    st->cr();
  }
  if (pool_holder() != NULL) {
    st->print_cr(" - holder: " INTPTR_FORMAT, pool_holder());
  }
  st->print_cr(" - cache: " INTPTR_FORMAT, cache());
1921
  st->print_cr(" - resolved_references: " INTPTR_FORMAT, (void *)resolved_references());
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
  st->print_cr(" - reference_map: " INTPTR_FORMAT, reference_map());

  for (int index = 1; index < length(); index++) {      // Index 0 is unused
    ((ConstantPool*)this)->print_entry_on(index, st);
    switch (tag_at(index).value()) {
      case JVM_CONSTANT_Long :
      case JVM_CONSTANT_Double :
        index++;   // Skip entry following eigth-byte constant
    }

  }
  st->cr();
}

// Print one constant pool entry
void ConstantPool::print_entry_on(const int index, outputStream* st) {
  EXCEPTION_MARK;
  st->print(" - %3d : ", index);
  tag_at(index).print_on(st);
  st->print(" : ");
  switch (tag_at(index).value()) {
    case JVM_CONSTANT_Class :
      { Klass* k = klass_at(index, CATCH);
1945
        guarantee(k != NULL, "need klass");
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
        k->print_value_on(st);
        st->print(" {0x%lx}", (address)k);
      }
      break;
    case JVM_CONSTANT_Fieldref :
    case JVM_CONSTANT_Methodref :
    case JVM_CONSTANT_InterfaceMethodref :
      st->print("klass_index=%d", uncached_klass_ref_index_at(index));
      st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(index));
      break;
    case JVM_CONSTANT_String :
1957 1958 1959 1960 1961 1962 1963
      if (is_pseudo_string_at(index)) {
        oop anObj = pseudo_string_at(index);
        anObj->print_value_on(st);
        st->print(" {0x%lx}", (address)anObj);
      } else {
        unresolved_string_at(index)->print_value_on(st);
      }
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
      break;
    case JVM_CONSTANT_Integer :
      st->print("%d", int_at(index));
      break;
    case JVM_CONSTANT_Float :
      st->print("%f", float_at(index));
      break;
    case JVM_CONSTANT_Long :
      st->print_jlong(long_at(index));
      break;
    case JVM_CONSTANT_Double :
      st->print("%lf", double_at(index));
      break;
    case JVM_CONSTANT_NameAndType :
      st->print("name_index=%d", name_ref_index_at(index));
      st->print(" signature_index=%d", signature_ref_index_at(index));
      break;
    case JVM_CONSTANT_Utf8 :
      symbol_at(index)->print_value_on(st);
      break;
    case JVM_CONSTANT_UnresolvedClass :               // fall-through
    case JVM_CONSTANT_UnresolvedClassInError: {
      // unresolved_klass_at requires lock or safe world.
      CPSlot entry = slot_at(index);
      if (entry.is_resolved()) {
        entry.get_klass()->print_value_on(st);
      } else {
        entry.get_symbol()->print_value_on(st);
      }
      }
      break;
    case JVM_CONSTANT_MethodHandle :
    case JVM_CONSTANT_MethodHandleInError :
1997 1998
      st->print("ref_kind=%d", method_handle_ref_kind_at_error_ok(index));
      st->print(" ref_index=%d", method_handle_index_at_error_ok(index));
1999 2000 2001
      break;
    case JVM_CONSTANT_MethodType :
    case JVM_CONSTANT_MethodTypeInError :
2002
      st->print("signature_index=%d", method_type_index_at_error_ok(index));
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
      break;
    case JVM_CONSTANT_InvokeDynamic :
      {
        st->print("bootstrap_method_index=%d", invoke_dynamic_bootstrap_method_ref_index_at(index));
        st->print(" name_and_type_index=%d", invoke_dynamic_name_and_type_ref_index_at(index));
        int argc = invoke_dynamic_argument_count_at(index);
        if (argc > 0) {
          for (int arg_i = 0; arg_i < argc; arg_i++) {
            int arg = invoke_dynamic_argument_index_at(index, arg_i);
            st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);
          }
          st->print("}");
        }
      }
      break;
    default:
      ShouldNotReachHere();
      break;
  }
  st->cr();
}

void ConstantPool::print_value_on(outputStream* st) const {
  assert(is_constantPool(), "must be constantPool");
  st->print("constant pool [%d]", length());
  if (has_preresolution()) st->print("/preresolution");
  if (operands() != NULL)  st->print("/operands[%d]", operands()->length());
  print_address_on(st);
  st->print(" for ");
  pool_holder()->print_value_on(st);
  if (pool_holder() != NULL) {
2034
    bool extra = (pool_holder()->constants() != this);
2035 2036 2037 2038 2039 2040 2041
    if (extra)  st->print(" (extra)");
  }
  if (cache() != NULL) {
    st->print(" cache=" PTR_FORMAT, cache());
  }
}

2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
#if INCLUDE_SERVICES
// Size Statistics
void ConstantPool::collect_statistics(KlassSizeStats *sz) const {
  sz->_cp_all_bytes += (sz->_cp_bytes          = sz->count(this));
  sz->_cp_all_bytes += (sz->_cp_tags_bytes     = sz->count_array(tags()));
  sz->_cp_all_bytes += (sz->_cp_cache_bytes    = sz->count(cache()));
  sz->_cp_all_bytes += (sz->_cp_operands_bytes = sz->count_array(operands()));
  sz->_cp_all_bytes += (sz->_cp_refmap_bytes   = sz->count_array(reference_map()));

  sz->_ro_bytes += sz->_cp_operands_bytes + sz->_cp_tags_bytes +
                   sz->_cp_refmap_bytes;
  sz->_rw_bytes += sz->_cp_bytes + sz->_cp_cache_bytes;
}
#endif // INCLUDE_SERVICES
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090

// Verification

void ConstantPool::verify_on(outputStream* st) {
  guarantee(is_constantPool(), "object must be constant pool");
  for (int i = 0; i< length();  i++) {
    constantTag tag = tag_at(i);
    CPSlot entry = slot_at(i);
    if (tag.is_klass()) {
      if (entry.is_resolved()) {
        guarantee(entry.get_klass()->is_klass(),    "should be klass");
      }
    } else if (tag.is_unresolved_klass()) {
      if (entry.is_resolved()) {
        guarantee(entry.get_klass()->is_klass(),    "should be klass");
      }
    } else if (tag.is_symbol()) {
      guarantee(entry.get_symbol()->refcount() != 0, "should have nonzero reference count");
    } else if (tag.is_string()) {
      guarantee(entry.get_symbol()->refcount() != 0, "should have nonzero reference count");
    }
  }
  if (cache() != NULL) {
    // Note: cache() can be NULL before a class is completely setup or
    // in temporary constant pools used during constant pool merging
    guarantee(cache()->is_constantPoolCache(), "should be constant pool cache");
  }
  if (pool_holder() != NULL) {
    // Note: pool_holder() can be NULL in temporary constant pools
    // used during constant pool merging
    guarantee(pool_holder()->is_klass(),    "should be klass");
  }
}


2091
void SymbolHashMap::add_entry(Symbol* sym, u2 value) {
D
duke 已提交
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
  char *str = sym->as_utf8();
  unsigned int hash = compute_hash(str, sym->utf8_length());
  unsigned int index = hash % table_size();

  // check if already in map
  // we prefer the first entry since it is more likely to be what was used in
  // the class file
  for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {
    assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
    if (en->hash() == hash && en->symbol() == sym) {
        return;  // already there
    }
  }

  SymbolHashMapEntry* entry = new SymbolHashMapEntry(hash, sym, value);
  entry->set_next(bucket(index));
  _buckets[index].set_entry(entry);
  assert(entry->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
}

2112
SymbolHashMapEntry* SymbolHashMap::find_entry(Symbol* sym) {
D
duke 已提交
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
  assert(sym != NULL, "SymbolHashMap::find_entry - symbol is NULL");
  char *str = sym->as_utf8();
  int   len = sym->utf8_length();
  unsigned int hash = SymbolHashMap::compute_hash(str, len);
  unsigned int index = hash % table_size();
  for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {
    assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");
    if (en->hash() == hash && en->symbol() == sym) {
      return en;
    }
  }
  return NULL;
}