verifier.cpp revision 6764:b1eb6f5a41ec
1/*
2 * Copyright (c) 1998, 2014, 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/classFileStream.hpp"
27#include "classfile/javaClasses.hpp"
28#include "classfile/stackMapTable.hpp"
29#include "classfile/stackMapFrame.hpp"
30#include "classfile/stackMapTableFormat.hpp"
31#include "classfile/systemDictionary.hpp"
32#include "classfile/verifier.hpp"
33#include "classfile/vmSymbols.hpp"
34#include "interpreter/bytecodes.hpp"
35#include "interpreter/bytecodeStream.hpp"
36#include "memory/oopFactory.hpp"
37#include "memory/resourceArea.hpp"
38#include "oops/instanceKlass.hpp"
39#include "oops/oop.inline.hpp"
40#include "oops/typeArrayOop.hpp"
41#include "prims/jvm.h"
42#include "runtime/fieldDescriptor.hpp"
43#include "runtime/handles.inline.hpp"
44#include "runtime/interfaceSupport.hpp"
45#include "runtime/javaCalls.hpp"
46#include "runtime/orderAccess.inline.hpp"
47#include "runtime/os.hpp"
48#include "utilities/bytes.hpp"
49
50#define NOFAILOVER_MAJOR_VERSION                       51
51#define NONZERO_PADDING_BYTES_IN_SWITCH_MAJOR_VERSION  51
52#define STATIC_METHOD_IN_INTERFACE_MAJOR_VERSION       52
53
54// Access to external entry for VerifyClassCodes - old byte code verifier
55
56extern "C" {
57  typedef jboolean (*verify_byte_codes_fn_t)(JNIEnv *, jclass, char *, jint);
58  typedef jboolean (*verify_byte_codes_fn_new_t)(JNIEnv *, jclass, char *, jint, jint);
59}
60
61static void* volatile _verify_byte_codes_fn = NULL;
62
63static volatile jint _is_new_verify_byte_codes_fn = (jint) true;
64
65static void* verify_byte_codes_fn() {
66  if (_verify_byte_codes_fn == NULL) {
67    void *lib_handle = os::native_java_library();
68    void *func = os::dll_lookup(lib_handle, "VerifyClassCodesForMajorVersion");
69    OrderAccess::release_store_ptr(&_verify_byte_codes_fn, func);
70    if (func == NULL) {
71      OrderAccess::release_store(&_is_new_verify_byte_codes_fn, false);
72      func = os::dll_lookup(lib_handle, "VerifyClassCodes");
73      OrderAccess::release_store_ptr(&_verify_byte_codes_fn, func);
74    }
75  }
76  return (void*)_verify_byte_codes_fn;
77}
78
79
80// Methods in Verifier
81
82bool Verifier::should_verify_for(oop class_loader, bool should_verify_class) {
83  return (class_loader == NULL || !should_verify_class) ?
84    BytecodeVerificationLocal : BytecodeVerificationRemote;
85}
86
87bool Verifier::relax_verify_for(oop loader) {
88  bool trusted = java_lang_ClassLoader::is_trusted_loader(loader);
89  bool need_verify =
90    // verifyAll
91    (BytecodeVerificationLocal && BytecodeVerificationRemote) ||
92    // verifyRemote
93    (!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
94  return !need_verify;
95}
96
97bool Verifier::verify(instanceKlassHandle klass, Verifier::Mode mode, bool should_verify_class, TRAPS) {
98  HandleMark hm;
99  ResourceMark rm(THREAD);
100
101  Symbol* exception_name = NULL;
102  const size_t message_buffer_len = klass->name()->utf8_length() + 1024;
103  char* message_buffer = NEW_RESOURCE_ARRAY(char, message_buffer_len);
104  char* exception_message = message_buffer;
105
106  const char* klassName = klass->external_name();
107  bool can_failover = FailOverToOldVerifier &&
108      klass->major_version() < NOFAILOVER_MAJOR_VERSION;
109
110  // If the class should be verified, first see if we can use the split
111  // verifier.  If not, or if verification fails and FailOverToOldVerifier
112  // is set, then call the inference verifier.
113  if (is_eligible_for_verification(klass, should_verify_class)) {
114    if (TraceClassInitialization) {
115      tty->print_cr("Start class verification for: %s", klassName);
116    }
117    if (klass->major_version() >= STACKMAP_ATTRIBUTE_MAJOR_VERSION) {
118      ClassVerifier split_verifier(klass, THREAD);
119      split_verifier.verify_class(THREAD);
120      exception_name = split_verifier.result();
121      if (can_failover && !HAS_PENDING_EXCEPTION &&
122          (exception_name == vmSymbols::java_lang_VerifyError() ||
123           exception_name == vmSymbols::java_lang_ClassFormatError())) {
124        if (TraceClassInitialization || VerboseVerification) {
125          tty->print_cr(
126            "Fail over class verification to old verifier for: %s", klassName);
127        }
128        exception_name = inference_verify(
129          klass, message_buffer, message_buffer_len, THREAD);
130      }
131      if (exception_name != NULL) {
132        exception_message = split_verifier.exception_message();
133      }
134    } else {
135      exception_name = inference_verify(
136          klass, message_buffer, message_buffer_len, THREAD);
137    }
138
139    if (TraceClassInitialization || VerboseVerification) {
140      if (HAS_PENDING_EXCEPTION) {
141        tty->print("Verification for %s has", klassName);
142        tty->print_cr(" exception pending %s ",
143          InstanceKlass::cast(PENDING_EXCEPTION->klass())->external_name());
144      } else if (exception_name != NULL) {
145        tty->print_cr("Verification for %s failed", klassName);
146      }
147      tty->print_cr("End class verification for: %s", klassName);
148    }
149  }
150
151  if (HAS_PENDING_EXCEPTION) {
152    return false; // use the existing exception
153  } else if (exception_name == NULL) {
154    return true; // verifcation succeeded
155  } else { // VerifyError or ClassFormatError to be created and thrown
156    ResourceMark rm(THREAD);
157    instanceKlassHandle kls =
158      SystemDictionary::resolve_or_fail(exception_name, true, CHECK_false);
159    while (!kls.is_null()) {
160      if (kls == klass) {
161        // If the class being verified is the exception we're creating
162        // or one of it's superclasses, we're in trouble and are going
163        // to infinitely recurse when we try to initialize the exception.
164        // So bail out here by throwing the preallocated VM error.
165        THROW_OOP_(Universe::virtual_machine_error_instance(), false);
166      }
167      kls = kls->super();
168    }
169    message_buffer[message_buffer_len - 1] = '\0'; // just to be sure
170    THROW_MSG_(exception_name, exception_message, false);
171  }
172}
173
174bool Verifier::is_eligible_for_verification(instanceKlassHandle klass, bool should_verify_class) {
175  Symbol* name = klass->name();
176  Klass* refl_magic_klass = SystemDictionary::reflect_MagicAccessorImpl_klass();
177
178  bool is_reflect = refl_magic_klass != NULL && klass->is_subtype_of(refl_magic_klass);
179
180  return (should_verify_for(klass->class_loader(), should_verify_class) &&
181    // return if the class is a bootstrapping class
182    // or defineClass specified not to verify by default (flags override passed arg)
183    // We need to skip the following four for bootstraping
184    name != vmSymbols::java_lang_Object() &&
185    name != vmSymbols::java_lang_Class() &&
186    name != vmSymbols::java_lang_String() &&
187    name != vmSymbols::java_lang_Throwable() &&
188
189    // Can not verify the bytecodes for shared classes because they have
190    // already been rewritten to contain constant pool cache indices,
191    // which the verifier can't understand.
192    // Shared classes shouldn't have stackmaps either.
193    !klass()->is_shared() &&
194
195    // As of the fix for 4486457 we disable verification for all of the
196    // dynamically-generated bytecodes associated with the 1.4
197    // reflection implementation, not just those associated with
198    // sun/reflect/SerializationConstructorAccessor.
199    // NOTE: this is called too early in the bootstrapping process to be
200    // guarded by Universe::is_gte_jdk14x_version().
201    // Also for lambda generated code, gte jdk8
202    (!is_reflect));
203}
204
205Symbol* Verifier::inference_verify(
206    instanceKlassHandle klass, char* message, size_t message_len, TRAPS) {
207  JavaThread* thread = (JavaThread*)THREAD;
208  JNIEnv *env = thread->jni_environment();
209
210  void* verify_func = verify_byte_codes_fn();
211
212  if (verify_func == NULL) {
213    jio_snprintf(message, message_len, "Could not link verifier");
214    return vmSymbols::java_lang_VerifyError();
215  }
216
217  ResourceMark rm(THREAD);
218  if (VerboseVerification) {
219    tty->print_cr("Verifying class %s with old format", klass->external_name());
220  }
221
222  jclass cls = (jclass) JNIHandles::make_local(env, klass->java_mirror());
223  jint result;
224
225  {
226    HandleMark hm(thread);
227    ThreadToNativeFromVM ttn(thread);
228    // ThreadToNativeFromVM takes care of changing thread_state, so safepoint
229    // code knows that we have left the VM
230
231    if (_is_new_verify_byte_codes_fn) {
232      verify_byte_codes_fn_new_t func =
233        CAST_TO_FN_PTR(verify_byte_codes_fn_new_t, verify_func);
234      result = (*func)(env, cls, message, (int)message_len,
235          klass->major_version());
236    } else {
237      verify_byte_codes_fn_t func =
238        CAST_TO_FN_PTR(verify_byte_codes_fn_t, verify_func);
239      result = (*func)(env, cls, message, (int)message_len);
240    }
241  }
242
243  JNIHandles::destroy_local(cls);
244
245  // These numbers are chosen so that VerifyClassCodes interface doesn't need
246  // to be changed (still return jboolean (unsigned char)), and result is
247  // 1 when verification is passed.
248  if (result == 0) {
249    return vmSymbols::java_lang_VerifyError();
250  } else if (result == 1) {
251    return NULL; // verified.
252  } else if (result == 2) {
253    THROW_MSG_(vmSymbols::java_lang_OutOfMemoryError(), message, NULL);
254  } else if (result == 3) {
255    return vmSymbols::java_lang_ClassFormatError();
256  } else {
257    ShouldNotReachHere();
258    return NULL;
259  }
260}
261
262TypeOrigin TypeOrigin::null() {
263  return TypeOrigin();
264}
265TypeOrigin TypeOrigin::local(u2 index, StackMapFrame* frame) {
266  assert(frame != NULL, "Must have a frame");
267  return TypeOrigin(CF_LOCALS, index, StackMapFrame::copy(frame),
268     frame->local_at(index));
269}
270TypeOrigin TypeOrigin::stack(u2 index, StackMapFrame* frame) {
271  assert(frame != NULL, "Must have a frame");
272  return TypeOrigin(CF_STACK, index, StackMapFrame::copy(frame),
273      frame->stack_at(index));
274}
275TypeOrigin TypeOrigin::sm_local(u2 index, StackMapFrame* frame) {
276  assert(frame != NULL, "Must have a frame");
277  return TypeOrigin(SM_LOCALS, index, StackMapFrame::copy(frame),
278      frame->local_at(index));
279}
280TypeOrigin TypeOrigin::sm_stack(u2 index, StackMapFrame* frame) {
281  assert(frame != NULL, "Must have a frame");
282  return TypeOrigin(SM_STACK, index, StackMapFrame::copy(frame),
283      frame->stack_at(index));
284}
285TypeOrigin TypeOrigin::bad_index(u2 index) {
286  return TypeOrigin(BAD_INDEX, index, NULL, VerificationType::bogus_type());
287}
288TypeOrigin TypeOrigin::cp(u2 index, VerificationType vt) {
289  return TypeOrigin(CONST_POOL, index, NULL, vt);
290}
291TypeOrigin TypeOrigin::signature(VerificationType vt) {
292  return TypeOrigin(SIG, 0, NULL, vt);
293}
294TypeOrigin TypeOrigin::implicit(VerificationType t) {
295  return TypeOrigin(IMPLICIT, 0, NULL, t);
296}
297TypeOrigin TypeOrigin::frame(StackMapFrame* frame) {
298  return TypeOrigin(FRAME_ONLY, 0, StackMapFrame::copy(frame),
299                    VerificationType::bogus_type());
300}
301
302void TypeOrigin::reset_frame() {
303  if (_frame != NULL) {
304    _frame->restore();
305  }
306}
307
308void TypeOrigin::details(outputStream* ss) const {
309  _type.print_on(ss);
310  switch (_origin) {
311    case CF_LOCALS:
312      ss->print(" (current frame, locals[%d])", _index);
313      break;
314    case CF_STACK:
315      ss->print(" (current frame, stack[%d])", _index);
316      break;
317    case SM_LOCALS:
318      ss->print(" (stack map, locals[%d])", _index);
319      break;
320    case SM_STACK:
321      ss->print(" (stack map, stack[%d])", _index);
322      break;
323    case CONST_POOL:
324      ss->print(" (constant pool %d)", _index);
325      break;
326    case SIG:
327      ss->print(" (from method signature)");
328      break;
329    case IMPLICIT:
330    case FRAME_ONLY:
331    case NONE:
332    default:
333      ;
334  }
335}
336
337#ifdef ASSERT
338void TypeOrigin::print_on(outputStream* str) const {
339  str->print("{%d,%d,%p:", _origin, _index, _frame);
340  if (_frame != NULL) {
341    _frame->print_on(str);
342  } else {
343    str->print("null");
344  }
345  str->print(",");
346  _type.print_on(str);
347  str->print("}");
348}
349#endif
350
351void ErrorContext::details(outputStream* ss, const Method* method) const {
352  if (is_valid()) {
353    ss->cr();
354    ss->print_cr("Exception Details:");
355    location_details(ss, method);
356    reason_details(ss);
357    frame_details(ss);
358    bytecode_details(ss, method);
359    handler_details(ss, method);
360    stackmap_details(ss, method);
361  }
362}
363
364void ErrorContext::reason_details(outputStream* ss) const {
365  streamIndentor si(ss);
366  ss->indent().print_cr("Reason:");
367  streamIndentor si2(ss);
368  ss->indent().print("%s", "");
369  switch (_fault) {
370    case INVALID_BYTECODE:
371      ss->print("Error exists in the bytecode");
372      break;
373    case WRONG_TYPE:
374      if (_expected.is_valid()) {
375        ss->print("Type ");
376        _type.details(ss);
377        ss->print(" is not assignable to ");
378        _expected.details(ss);
379      } else {
380        ss->print("Invalid type: ");
381        _type.details(ss);
382      }
383      break;
384    case FLAGS_MISMATCH:
385      if (_expected.is_valid()) {
386        ss->print("Current frame's flags are not assignable "
387                  "to stack map frame's.");
388      } else {
389        ss->print("Current frame's flags are invalid in this context.");
390      }
391      break;
392    case BAD_CP_INDEX:
393      ss->print("Constant pool index %d is invalid", _type.index());
394      break;
395    case BAD_LOCAL_INDEX:
396      ss->print("Local index %d is invalid", _type.index());
397      break;
398    case LOCALS_SIZE_MISMATCH:
399      ss->print("Current frame's local size doesn't match stackmap.");
400      break;
401    case STACK_SIZE_MISMATCH:
402      ss->print("Current frame's stack size doesn't match stackmap.");
403      break;
404    case STACK_OVERFLOW:
405      ss->print("Exceeded max stack size.");
406      break;
407    case STACK_UNDERFLOW:
408      ss->print("Attempt to pop empty stack.");
409      break;
410    case MISSING_STACKMAP:
411      ss->print("Expected stackmap frame at this location.");
412      break;
413    case BAD_STACKMAP:
414      ss->print("Invalid stackmap specification.");
415      break;
416    case UNKNOWN:
417    default:
418      ShouldNotReachHere();
419      ss->print_cr("Unknown");
420  }
421  ss->cr();
422}
423
424void ErrorContext::location_details(outputStream* ss, const Method* method) const {
425  if (_bci != -1 && method != NULL) {
426    streamIndentor si(ss);
427    const char* bytecode_name = "<invalid>";
428    if (method->validate_bci(_bci) != -1) {
429      Bytecodes::Code code = Bytecodes::code_or_bp_at(method->bcp_from(_bci));
430      if (Bytecodes::is_defined(code)) {
431          bytecode_name = Bytecodes::name(code);
432      } else {
433          bytecode_name = "<illegal>";
434      }
435    }
436    InstanceKlass* ik = method->method_holder();
437    ss->indent().print_cr("Location:");
438    streamIndentor si2(ss);
439    ss->indent().print_cr("%s.%s%s @%d: %s",
440        ik->name()->as_C_string(), method->name()->as_C_string(),
441        method->signature()->as_C_string(), _bci, bytecode_name);
442  }
443}
444
445void ErrorContext::frame_details(outputStream* ss) const {
446  streamIndentor si(ss);
447  if (_type.is_valid() && _type.frame() != NULL) {
448    ss->indent().print_cr("Current Frame:");
449    streamIndentor si2(ss);
450    _type.frame()->print_on(ss);
451  }
452  if (_expected.is_valid() && _expected.frame() != NULL) {
453    ss->indent().print_cr("Stackmap Frame:");
454    streamIndentor si2(ss);
455    _expected.frame()->print_on(ss);
456  }
457}
458
459void ErrorContext::bytecode_details(outputStream* ss, const Method* method) const {
460  if (method != NULL) {
461    streamIndentor si(ss);
462    ss->indent().print_cr("Bytecode:");
463    streamIndentor si2(ss);
464    ss->print_data(method->code_base(), method->code_size(), false);
465  }
466}
467
468void ErrorContext::handler_details(outputStream* ss, const Method* method) const {
469  if (method != NULL) {
470    streamIndentor si(ss);
471    ExceptionTable table(method);
472    if (table.length() > 0) {
473      ss->indent().print_cr("Exception Handler Table:");
474      streamIndentor si2(ss);
475      for (int i = 0; i < table.length(); ++i) {
476        ss->indent().print_cr("bci [%d, %d] => handler: %d", table.start_pc(i),
477            table.end_pc(i), table.handler_pc(i));
478      }
479    }
480  }
481}
482
483void ErrorContext::stackmap_details(outputStream* ss, const Method* method) const {
484  if (method != NULL && method->has_stackmap_table()) {
485    streamIndentor si(ss);
486    ss->indent().print_cr("Stackmap Table:");
487    Array<u1>* data = method->stackmap_data();
488    stack_map_table* sm_table =
489        stack_map_table::at((address)data->adr_at(0));
490    stack_map_frame* sm_frame = sm_table->entries();
491    streamIndentor si2(ss);
492    int current_offset = -1;
493    for (u2 i = 0; i < sm_table->number_of_entries(); ++i) {
494      ss->indent();
495      sm_frame->print_on(ss, current_offset);
496      ss->cr();
497      current_offset += sm_frame->offset_delta();
498      sm_frame = sm_frame->next();
499    }
500  }
501}
502
503// Methods in ClassVerifier
504
505ClassVerifier::ClassVerifier(
506    instanceKlassHandle klass, TRAPS)
507    : _thread(THREAD), _exception_type(NULL), _message(NULL), _klass(klass) {
508  _this_type = VerificationType::reference_type(klass->name());
509  // Create list to hold symbols in reference area.
510  _symbols = new GrowableArray<Symbol*>(100, 0, NULL);
511}
512
513ClassVerifier::~ClassVerifier() {
514  // Decrement the reference count for any symbols created.
515  for (int i = 0; i < _symbols->length(); i++) {
516    Symbol* s = _symbols->at(i);
517    s->decrement_refcount();
518  }
519}
520
521VerificationType ClassVerifier::object_type() const {
522  return VerificationType::reference_type(vmSymbols::java_lang_Object());
523}
524
525TypeOrigin ClassVerifier::ref_ctx(const char* sig, TRAPS) {
526  VerificationType vt = VerificationType::reference_type(
527      create_temporary_symbol(sig, (int)strlen(sig), THREAD));
528  return TypeOrigin::implicit(vt);
529}
530
531void ClassVerifier::verify_class(TRAPS) {
532  if (VerboseVerification) {
533    tty->print_cr("Verifying class %s with new format",
534      _klass->external_name());
535  }
536
537  Array<Method*>* methods = _klass->methods();
538  int num_methods = methods->length();
539
540  for (int index = 0; index < num_methods; index++) {
541    // Check for recursive re-verification before each method.
542    if (was_recursively_verified())  return;
543
544    Method* m = methods->at(index);
545    if (m->is_native() || m->is_abstract() || m->is_overpass()) {
546      // If m is native or abstract, skip it.  It is checked in class file
547      // parser that methods do not override a final method.  Overpass methods
548      // are trusted since the VM generates them.
549      continue;
550    }
551    verify_method(methodHandle(THREAD, m), CHECK_VERIFY(this));
552  }
553
554  if (VerboseVerification || TraceClassInitialization) {
555    if (was_recursively_verified())
556      tty->print_cr("Recursive verification detected for: %s",
557          _klass->external_name());
558  }
559}
560
561void ClassVerifier::verify_method(methodHandle m, TRAPS) {
562  HandleMark hm(THREAD);
563  _method = m;   // initialize _method
564  if (VerboseVerification) {
565    tty->print_cr("Verifying method %s", m->name_and_sig_as_C_string());
566  }
567
568// For clang, the only good constant format string is a literal constant format string.
569#define bad_type_msg "Bad type on operand stack in %s"
570
571  int32_t max_stack = m->verifier_max_stack();
572  int32_t max_locals = m->max_locals();
573  constantPoolHandle cp(THREAD, m->constants());
574
575  if (!SignatureVerifier::is_valid_method_signature(m->signature())) {
576    class_format_error("Invalid method signature");
577    return;
578  }
579
580  // Initial stack map frame: offset is 0, stack is initially empty.
581  StackMapFrame current_frame(max_locals, max_stack, this);
582  // Set initial locals
583  VerificationType return_type = current_frame.set_locals_from_arg(
584    m, current_type(), CHECK_VERIFY(this));
585
586  int32_t stackmap_index = 0; // index to the stackmap array
587
588  u4 code_length = m->code_size();
589
590  // Scan the bytecode and map each instruction's start offset to a number.
591  char* code_data = generate_code_data(m, code_length, CHECK_VERIFY(this));
592
593  int ex_min = code_length;
594  int ex_max = -1;
595  // Look through each item on the exception table. Each of the fields must refer
596  // to a legal instruction.
597  verify_exception_handler_table(
598    code_length, code_data, ex_min, ex_max, CHECK_VERIFY(this));
599
600  // Look through each entry on the local variable table and make sure
601  // its range of code array offsets is valid. (4169817)
602  if (m->has_localvariable_table()) {
603    verify_local_variable_table(code_length, code_data, CHECK_VERIFY(this));
604  }
605
606  Array<u1>* stackmap_data = m->stackmap_data();
607  StackMapStream stream(stackmap_data);
608  StackMapReader reader(this, &stream, code_data, code_length, THREAD);
609  StackMapTable stackmap_table(&reader, &current_frame, max_locals, max_stack,
610                               code_data, code_length, CHECK_VERIFY(this));
611
612  if (VerboseVerification) {
613    stackmap_table.print_on(tty);
614  }
615
616  RawBytecodeStream bcs(m);
617
618  // Scan the byte code linearly from the start to the end
619  bool no_control_flow = false; // Set to true when there is no direct control
620                                // flow from current instruction to the next
621                                // instruction in sequence
622
623  set_furthest_jump(0);
624
625  Bytecodes::Code opcode;
626  while (!bcs.is_last_bytecode()) {
627    // Check for recursive re-verification before each bytecode.
628    if (was_recursively_verified())  return;
629
630    opcode = bcs.raw_next();
631    u2 bci = bcs.bci();
632
633    // Set current frame's offset to bci
634    current_frame.set_offset(bci);
635    current_frame.set_mark();
636
637    // Make sure every offset in stackmap table point to the beginning to
638    // an instruction. Match current_frame to stackmap_table entry with
639    // the same offset if exists.
640    stackmap_index = verify_stackmap_table(
641      stackmap_index, bci, &current_frame, &stackmap_table,
642      no_control_flow, CHECK_VERIFY(this));
643
644
645    bool this_uninit = false;  // Set to true when invokespecial <init> initialized 'this'
646
647    // Merge with the next instruction
648    {
649      u2 index;
650      int target;
651      VerificationType type, type2;
652      VerificationType atype;
653
654#ifndef PRODUCT
655      if (VerboseVerification) {
656        current_frame.print_on(tty);
657        tty->print_cr("offset = %d,  opcode = %s", bci, Bytecodes::name(opcode));
658      }
659#endif
660
661      // Make sure wide instruction is in correct format
662      if (bcs.is_wide()) {
663        if (opcode != Bytecodes::_iinc   && opcode != Bytecodes::_iload  &&
664            opcode != Bytecodes::_aload  && opcode != Bytecodes::_lload  &&
665            opcode != Bytecodes::_istore && opcode != Bytecodes::_astore &&
666            opcode != Bytecodes::_lstore && opcode != Bytecodes::_fload  &&
667            opcode != Bytecodes::_dload  && opcode != Bytecodes::_fstore &&
668            opcode != Bytecodes::_dstore) {
669          /* Unreachable?  RawBytecodeStream's raw_next() returns 'illegal'
670           * if we encounter a wide instruction that modifies an invalid
671           * opcode (not one of the ones listed above) */
672          verify_error(ErrorContext::bad_code(bci), "Bad wide instruction");
673          return;
674        }
675      }
676
677      switch (opcode) {
678        case Bytecodes::_nop :
679          no_control_flow = false; break;
680        case Bytecodes::_aconst_null :
681          current_frame.push_stack(
682            VerificationType::null_type(), CHECK_VERIFY(this));
683          no_control_flow = false; break;
684        case Bytecodes::_iconst_m1 :
685        case Bytecodes::_iconst_0 :
686        case Bytecodes::_iconst_1 :
687        case Bytecodes::_iconst_2 :
688        case Bytecodes::_iconst_3 :
689        case Bytecodes::_iconst_4 :
690        case Bytecodes::_iconst_5 :
691          current_frame.push_stack(
692            VerificationType::integer_type(), CHECK_VERIFY(this));
693          no_control_flow = false; break;
694        case Bytecodes::_lconst_0 :
695        case Bytecodes::_lconst_1 :
696          current_frame.push_stack_2(
697            VerificationType::long_type(),
698            VerificationType::long2_type(), CHECK_VERIFY(this));
699          no_control_flow = false; break;
700        case Bytecodes::_fconst_0 :
701        case Bytecodes::_fconst_1 :
702        case Bytecodes::_fconst_2 :
703          current_frame.push_stack(
704            VerificationType::float_type(), CHECK_VERIFY(this));
705          no_control_flow = false; break;
706        case Bytecodes::_dconst_0 :
707        case Bytecodes::_dconst_1 :
708          current_frame.push_stack_2(
709            VerificationType::double_type(),
710            VerificationType::double2_type(), CHECK_VERIFY(this));
711          no_control_flow = false; break;
712        case Bytecodes::_sipush :
713        case Bytecodes::_bipush :
714          current_frame.push_stack(
715            VerificationType::integer_type(), CHECK_VERIFY(this));
716          no_control_flow = false; break;
717        case Bytecodes::_ldc :
718          verify_ldc(
719            opcode, bcs.get_index_u1(), &current_frame,
720            cp, bci, CHECK_VERIFY(this));
721          no_control_flow = false; break;
722        case Bytecodes::_ldc_w :
723        case Bytecodes::_ldc2_w :
724          verify_ldc(
725            opcode, bcs.get_index_u2(), &current_frame,
726            cp, bci, CHECK_VERIFY(this));
727          no_control_flow = false; break;
728        case Bytecodes::_iload :
729          verify_iload(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
730          no_control_flow = false; break;
731        case Bytecodes::_iload_0 :
732        case Bytecodes::_iload_1 :
733        case Bytecodes::_iload_2 :
734        case Bytecodes::_iload_3 :
735          index = opcode - Bytecodes::_iload_0;
736          verify_iload(index, &current_frame, CHECK_VERIFY(this));
737          no_control_flow = false; break;
738        case Bytecodes::_lload :
739          verify_lload(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
740          no_control_flow = false; break;
741        case Bytecodes::_lload_0 :
742        case Bytecodes::_lload_1 :
743        case Bytecodes::_lload_2 :
744        case Bytecodes::_lload_3 :
745          index = opcode - Bytecodes::_lload_0;
746          verify_lload(index, &current_frame, CHECK_VERIFY(this));
747          no_control_flow = false; break;
748        case Bytecodes::_fload :
749          verify_fload(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
750          no_control_flow = false; break;
751        case Bytecodes::_fload_0 :
752        case Bytecodes::_fload_1 :
753        case Bytecodes::_fload_2 :
754        case Bytecodes::_fload_3 :
755          index = opcode - Bytecodes::_fload_0;
756          verify_fload(index, &current_frame, CHECK_VERIFY(this));
757          no_control_flow = false; break;
758        case Bytecodes::_dload :
759          verify_dload(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
760          no_control_flow = false; break;
761        case Bytecodes::_dload_0 :
762        case Bytecodes::_dload_1 :
763        case Bytecodes::_dload_2 :
764        case Bytecodes::_dload_3 :
765          index = opcode - Bytecodes::_dload_0;
766          verify_dload(index, &current_frame, CHECK_VERIFY(this));
767          no_control_flow = false; break;
768        case Bytecodes::_aload :
769          verify_aload(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
770          no_control_flow = false; break;
771        case Bytecodes::_aload_0 :
772        case Bytecodes::_aload_1 :
773        case Bytecodes::_aload_2 :
774        case Bytecodes::_aload_3 :
775          index = opcode - Bytecodes::_aload_0;
776          verify_aload(index, &current_frame, CHECK_VERIFY(this));
777          no_control_flow = false; break;
778        case Bytecodes::_iaload :
779          type = current_frame.pop_stack(
780            VerificationType::integer_type(), CHECK_VERIFY(this));
781          atype = current_frame.pop_stack(
782            VerificationType::reference_check(), CHECK_VERIFY(this));
783          if (!atype.is_int_array()) {
784            verify_error(ErrorContext::bad_type(bci,
785                current_frame.stack_top_ctx(), ref_ctx("[I", THREAD)),
786                bad_type_msg, "iaload");
787            return;
788          }
789          current_frame.push_stack(
790            VerificationType::integer_type(), CHECK_VERIFY(this));
791          no_control_flow = false; break;
792        case Bytecodes::_baload :
793          type = current_frame.pop_stack(
794            VerificationType::integer_type(), CHECK_VERIFY(this));
795          atype = current_frame.pop_stack(
796            VerificationType::reference_check(), CHECK_VERIFY(this));
797          if (!atype.is_bool_array() && !atype.is_byte_array()) {
798            verify_error(
799                ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
800                bad_type_msg, "baload");
801            return;
802          }
803          current_frame.push_stack(
804            VerificationType::integer_type(), CHECK_VERIFY(this));
805          no_control_flow = false; break;
806        case Bytecodes::_caload :
807          type = current_frame.pop_stack(
808            VerificationType::integer_type(), CHECK_VERIFY(this));
809          atype = current_frame.pop_stack(
810            VerificationType::reference_check(), CHECK_VERIFY(this));
811          if (!atype.is_char_array()) {
812            verify_error(ErrorContext::bad_type(bci,
813                current_frame.stack_top_ctx(), ref_ctx("[C", THREAD)),
814                bad_type_msg, "caload");
815            return;
816          }
817          current_frame.push_stack(
818            VerificationType::integer_type(), CHECK_VERIFY(this));
819          no_control_flow = false; break;
820        case Bytecodes::_saload :
821          type = current_frame.pop_stack(
822            VerificationType::integer_type(), CHECK_VERIFY(this));
823          atype = current_frame.pop_stack(
824            VerificationType::reference_check(), CHECK_VERIFY(this));
825          if (!atype.is_short_array()) {
826            verify_error(ErrorContext::bad_type(bci,
827                current_frame.stack_top_ctx(), ref_ctx("[S", THREAD)),
828                bad_type_msg, "saload");
829            return;
830          }
831          current_frame.push_stack(
832            VerificationType::integer_type(), CHECK_VERIFY(this));
833          no_control_flow = false; break;
834        case Bytecodes::_laload :
835          type = current_frame.pop_stack(
836            VerificationType::integer_type(), CHECK_VERIFY(this));
837          atype = current_frame.pop_stack(
838            VerificationType::reference_check(), CHECK_VERIFY(this));
839          if (!atype.is_long_array()) {
840            verify_error(ErrorContext::bad_type(bci,
841                current_frame.stack_top_ctx(), ref_ctx("[J", THREAD)),
842                bad_type_msg, "laload");
843            return;
844          }
845          current_frame.push_stack_2(
846            VerificationType::long_type(),
847            VerificationType::long2_type(), CHECK_VERIFY(this));
848          no_control_flow = false; break;
849        case Bytecodes::_faload :
850          type = current_frame.pop_stack(
851            VerificationType::integer_type(), CHECK_VERIFY(this));
852          atype = current_frame.pop_stack(
853            VerificationType::reference_check(), CHECK_VERIFY(this));
854          if (!atype.is_float_array()) {
855            verify_error(ErrorContext::bad_type(bci,
856                current_frame.stack_top_ctx(), ref_ctx("[F", THREAD)),
857                bad_type_msg, "faload");
858            return;
859          }
860          current_frame.push_stack(
861            VerificationType::float_type(), CHECK_VERIFY(this));
862          no_control_flow = false; break;
863        case Bytecodes::_daload :
864          type = current_frame.pop_stack(
865            VerificationType::integer_type(), CHECK_VERIFY(this));
866          atype = current_frame.pop_stack(
867            VerificationType::reference_check(), CHECK_VERIFY(this));
868          if (!atype.is_double_array()) {
869            verify_error(ErrorContext::bad_type(bci,
870                current_frame.stack_top_ctx(), ref_ctx("[D", THREAD)),
871                bad_type_msg, "daload");
872            return;
873          }
874          current_frame.push_stack_2(
875            VerificationType::double_type(),
876            VerificationType::double2_type(), CHECK_VERIFY(this));
877          no_control_flow = false; break;
878        case Bytecodes::_aaload : {
879          type = current_frame.pop_stack(
880            VerificationType::integer_type(), CHECK_VERIFY(this));
881          atype = current_frame.pop_stack(
882            VerificationType::reference_check(), CHECK_VERIFY(this));
883          if (!atype.is_reference_array()) {
884            verify_error(ErrorContext::bad_type(bci,
885                current_frame.stack_top_ctx(),
886                TypeOrigin::implicit(VerificationType::reference_check())),
887                bad_type_msg, "aaload");
888            return;
889          }
890          if (atype.is_null()) {
891            current_frame.push_stack(
892              VerificationType::null_type(), CHECK_VERIFY(this));
893          } else {
894            VerificationType component =
895              atype.get_component(this, CHECK_VERIFY(this));
896            current_frame.push_stack(component, CHECK_VERIFY(this));
897          }
898          no_control_flow = false; break;
899        }
900        case Bytecodes::_istore :
901          verify_istore(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
902          no_control_flow = false; break;
903        case Bytecodes::_istore_0 :
904        case Bytecodes::_istore_1 :
905        case Bytecodes::_istore_2 :
906        case Bytecodes::_istore_3 :
907          index = opcode - Bytecodes::_istore_0;
908          verify_istore(index, &current_frame, CHECK_VERIFY(this));
909          no_control_flow = false; break;
910        case Bytecodes::_lstore :
911          verify_lstore(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
912          no_control_flow = false; break;
913        case Bytecodes::_lstore_0 :
914        case Bytecodes::_lstore_1 :
915        case Bytecodes::_lstore_2 :
916        case Bytecodes::_lstore_3 :
917          index = opcode - Bytecodes::_lstore_0;
918          verify_lstore(index, &current_frame, CHECK_VERIFY(this));
919          no_control_flow = false; break;
920        case Bytecodes::_fstore :
921          verify_fstore(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
922          no_control_flow = false; break;
923        case Bytecodes::_fstore_0 :
924        case Bytecodes::_fstore_1 :
925        case Bytecodes::_fstore_2 :
926        case Bytecodes::_fstore_3 :
927          index = opcode - Bytecodes::_fstore_0;
928          verify_fstore(index, &current_frame, CHECK_VERIFY(this));
929          no_control_flow = false; break;
930        case Bytecodes::_dstore :
931          verify_dstore(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
932          no_control_flow = false; break;
933        case Bytecodes::_dstore_0 :
934        case Bytecodes::_dstore_1 :
935        case Bytecodes::_dstore_2 :
936        case Bytecodes::_dstore_3 :
937          index = opcode - Bytecodes::_dstore_0;
938          verify_dstore(index, &current_frame, CHECK_VERIFY(this));
939          no_control_flow = false; break;
940        case Bytecodes::_astore :
941          verify_astore(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
942          no_control_flow = false; break;
943        case Bytecodes::_astore_0 :
944        case Bytecodes::_astore_1 :
945        case Bytecodes::_astore_2 :
946        case Bytecodes::_astore_3 :
947          index = opcode - Bytecodes::_astore_0;
948          verify_astore(index, &current_frame, CHECK_VERIFY(this));
949          no_control_flow = false; break;
950        case Bytecodes::_iastore :
951          type = current_frame.pop_stack(
952            VerificationType::integer_type(), CHECK_VERIFY(this));
953          type2 = current_frame.pop_stack(
954            VerificationType::integer_type(), CHECK_VERIFY(this));
955          atype = current_frame.pop_stack(
956            VerificationType::reference_check(), CHECK_VERIFY(this));
957          if (!atype.is_int_array()) {
958            verify_error(ErrorContext::bad_type(bci,
959                current_frame.stack_top_ctx(), ref_ctx("[I", THREAD)),
960                bad_type_msg, "iastore");
961            return;
962          }
963          no_control_flow = false; break;
964        case Bytecodes::_bastore :
965          type = current_frame.pop_stack(
966            VerificationType::integer_type(), CHECK_VERIFY(this));
967          type2 = current_frame.pop_stack(
968            VerificationType::integer_type(), CHECK_VERIFY(this));
969          atype = current_frame.pop_stack(
970            VerificationType::reference_check(), CHECK_VERIFY(this));
971          if (!atype.is_bool_array() && !atype.is_byte_array()) {
972            verify_error(
973                ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
974                bad_type_msg, "bastore");
975            return;
976          }
977          no_control_flow = false; break;
978        case Bytecodes::_castore :
979          current_frame.pop_stack(
980            VerificationType::integer_type(), CHECK_VERIFY(this));
981          current_frame.pop_stack(
982            VerificationType::integer_type(), CHECK_VERIFY(this));
983          atype = current_frame.pop_stack(
984            VerificationType::reference_check(), CHECK_VERIFY(this));
985          if (!atype.is_char_array()) {
986            verify_error(ErrorContext::bad_type(bci,
987                current_frame.stack_top_ctx(), ref_ctx("[C", THREAD)),
988                bad_type_msg, "castore");
989            return;
990          }
991          no_control_flow = false; break;
992        case Bytecodes::_sastore :
993          current_frame.pop_stack(
994            VerificationType::integer_type(), CHECK_VERIFY(this));
995          current_frame.pop_stack(
996            VerificationType::integer_type(), CHECK_VERIFY(this));
997          atype = current_frame.pop_stack(
998            VerificationType::reference_check(), CHECK_VERIFY(this));
999          if (!atype.is_short_array()) {
1000            verify_error(ErrorContext::bad_type(bci,
1001                current_frame.stack_top_ctx(), ref_ctx("[S", THREAD)),
1002                bad_type_msg, "sastore");
1003            return;
1004          }
1005          no_control_flow = false; break;
1006        case Bytecodes::_lastore :
1007          current_frame.pop_stack_2(
1008            VerificationType::long2_type(),
1009            VerificationType::long_type(), CHECK_VERIFY(this));
1010          current_frame.pop_stack(
1011            VerificationType::integer_type(), CHECK_VERIFY(this));
1012          atype = current_frame.pop_stack(
1013            VerificationType::reference_check(), CHECK_VERIFY(this));
1014          if (!atype.is_long_array()) {
1015            verify_error(ErrorContext::bad_type(bci,
1016                current_frame.stack_top_ctx(), ref_ctx("[J", THREAD)),
1017                bad_type_msg, "lastore");
1018            return;
1019          }
1020          no_control_flow = false; break;
1021        case Bytecodes::_fastore :
1022          current_frame.pop_stack(
1023            VerificationType::float_type(), CHECK_VERIFY(this));
1024          current_frame.pop_stack
1025            (VerificationType::integer_type(), CHECK_VERIFY(this));
1026          atype = current_frame.pop_stack(
1027            VerificationType::reference_check(), CHECK_VERIFY(this));
1028          if (!atype.is_float_array()) {
1029            verify_error(ErrorContext::bad_type(bci,
1030                current_frame.stack_top_ctx(), ref_ctx("[F", THREAD)),
1031                bad_type_msg, "fastore");
1032            return;
1033          }
1034          no_control_flow = false; break;
1035        case Bytecodes::_dastore :
1036          current_frame.pop_stack_2(
1037            VerificationType::double2_type(),
1038            VerificationType::double_type(), CHECK_VERIFY(this));
1039          current_frame.pop_stack(
1040            VerificationType::integer_type(), CHECK_VERIFY(this));
1041          atype = current_frame.pop_stack(
1042            VerificationType::reference_check(), CHECK_VERIFY(this));
1043          if (!atype.is_double_array()) {
1044            verify_error(ErrorContext::bad_type(bci,
1045                current_frame.stack_top_ctx(), ref_ctx("[D", THREAD)),
1046                bad_type_msg, "dastore");
1047            return;
1048          }
1049          no_control_flow = false; break;
1050        case Bytecodes::_aastore :
1051          type = current_frame.pop_stack(object_type(), CHECK_VERIFY(this));
1052          type2 = current_frame.pop_stack(
1053            VerificationType::integer_type(), CHECK_VERIFY(this));
1054          atype = current_frame.pop_stack(
1055            VerificationType::reference_check(), CHECK_VERIFY(this));
1056          // more type-checking is done at runtime
1057          if (!atype.is_reference_array()) {
1058            verify_error(ErrorContext::bad_type(bci,
1059                current_frame.stack_top_ctx(),
1060                TypeOrigin::implicit(VerificationType::reference_check())),
1061                bad_type_msg, "aastore");
1062            return;
1063          }
1064          // 4938384: relaxed constraint in JVMS 3nd edition.
1065          no_control_flow = false; break;
1066        case Bytecodes::_pop :
1067          current_frame.pop_stack(
1068            VerificationType::category1_check(), CHECK_VERIFY(this));
1069          no_control_flow = false; break;
1070        case Bytecodes::_pop2 :
1071          type = current_frame.pop_stack(CHECK_VERIFY(this));
1072          if (type.is_category1()) {
1073            current_frame.pop_stack(
1074              VerificationType::category1_check(), CHECK_VERIFY(this));
1075          } else if (type.is_category2_2nd()) {
1076            current_frame.pop_stack(
1077              VerificationType::category2_check(), CHECK_VERIFY(this));
1078          } else {
1079            /* Unreachable? Would need a category2_1st on TOS
1080             * which does not appear possible. */
1081            verify_error(
1082                ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
1083                bad_type_msg, "pop2");
1084            return;
1085          }
1086          no_control_flow = false; break;
1087        case Bytecodes::_dup :
1088          type = current_frame.pop_stack(
1089            VerificationType::category1_check(), CHECK_VERIFY(this));
1090          current_frame.push_stack(type, CHECK_VERIFY(this));
1091          current_frame.push_stack(type, CHECK_VERIFY(this));
1092          no_control_flow = false; break;
1093        case Bytecodes::_dup_x1 :
1094          type = current_frame.pop_stack(
1095            VerificationType::category1_check(), CHECK_VERIFY(this));
1096          type2 = current_frame.pop_stack(
1097            VerificationType::category1_check(), CHECK_VERIFY(this));
1098          current_frame.push_stack(type, CHECK_VERIFY(this));
1099          current_frame.push_stack(type2, CHECK_VERIFY(this));
1100          current_frame.push_stack(type, CHECK_VERIFY(this));
1101          no_control_flow = false; break;
1102        case Bytecodes::_dup_x2 :
1103        {
1104          VerificationType type3;
1105          type = current_frame.pop_stack(
1106            VerificationType::category1_check(), CHECK_VERIFY(this));
1107          type2 = current_frame.pop_stack(CHECK_VERIFY(this));
1108          if (type2.is_category1()) {
1109            type3 = current_frame.pop_stack(
1110              VerificationType::category1_check(), CHECK_VERIFY(this));
1111          } else if (type2.is_category2_2nd()) {
1112            type3 = current_frame.pop_stack(
1113              VerificationType::category2_check(), CHECK_VERIFY(this));
1114          } else {
1115            /* Unreachable? Would need a category2_1st at stack depth 2 with
1116             * a category1 on TOS which does not appear possible. */
1117            verify_error(ErrorContext::bad_type(
1118                bci, current_frame.stack_top_ctx()), bad_type_msg, "dup_x2");
1119            return;
1120          }
1121          current_frame.push_stack(type, CHECK_VERIFY(this));
1122          current_frame.push_stack(type3, CHECK_VERIFY(this));
1123          current_frame.push_stack(type2, CHECK_VERIFY(this));
1124          current_frame.push_stack(type, CHECK_VERIFY(this));
1125          no_control_flow = false; break;
1126        }
1127        case Bytecodes::_dup2 :
1128          type = current_frame.pop_stack(CHECK_VERIFY(this));
1129          if (type.is_category1()) {
1130            type2 = current_frame.pop_stack(
1131              VerificationType::category1_check(), CHECK_VERIFY(this));
1132          } else if (type.is_category2_2nd()) {
1133            type2 = current_frame.pop_stack(
1134              VerificationType::category2_check(), CHECK_VERIFY(this));
1135          } else {
1136            /* Unreachable?  Would need a category2_1st on TOS which does not
1137             * appear possible. */
1138            verify_error(
1139                ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
1140                bad_type_msg, "dup2");
1141            return;
1142          }
1143          current_frame.push_stack(type2, CHECK_VERIFY(this));
1144          current_frame.push_stack(type, CHECK_VERIFY(this));
1145          current_frame.push_stack(type2, CHECK_VERIFY(this));
1146          current_frame.push_stack(type, CHECK_VERIFY(this));
1147          no_control_flow = false; break;
1148        case Bytecodes::_dup2_x1 :
1149        {
1150          VerificationType type3;
1151          type = current_frame.pop_stack(CHECK_VERIFY(this));
1152          if (type.is_category1()) {
1153            type2 = current_frame.pop_stack(
1154              VerificationType::category1_check(), CHECK_VERIFY(this));
1155          } else if (type.is_category2_2nd()) {
1156            type2 = current_frame.pop_stack(
1157              VerificationType::category2_check(), CHECK_VERIFY(this));
1158          } else {
1159            /* Unreachable?  Would need a category2_1st on TOS which does
1160             * not appear possible. */
1161            verify_error(
1162                ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
1163                bad_type_msg, "dup2_x1");
1164            return;
1165          }
1166          type3 = current_frame.pop_stack(
1167            VerificationType::category1_check(), CHECK_VERIFY(this));
1168          current_frame.push_stack(type2, CHECK_VERIFY(this));
1169          current_frame.push_stack(type, CHECK_VERIFY(this));
1170          current_frame.push_stack(type3, CHECK_VERIFY(this));
1171          current_frame.push_stack(type2, CHECK_VERIFY(this));
1172          current_frame.push_stack(type, CHECK_VERIFY(this));
1173          no_control_flow = false; break;
1174        }
1175        case Bytecodes::_dup2_x2 :
1176        {
1177          VerificationType type3, type4;
1178          type = current_frame.pop_stack(CHECK_VERIFY(this));
1179          if (type.is_category1()) {
1180            type2 = current_frame.pop_stack(
1181              VerificationType::category1_check(), CHECK_VERIFY(this));
1182          } else if (type.is_category2_2nd()) {
1183            type2 = current_frame.pop_stack(
1184              VerificationType::category2_check(), CHECK_VERIFY(this));
1185          } else {
1186            /* Unreachable?  Would need a category2_1st on TOS which does
1187             * not appear possible. */
1188            verify_error(
1189                ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
1190                bad_type_msg, "dup2_x2");
1191            return;
1192          }
1193          type3 = current_frame.pop_stack(CHECK_VERIFY(this));
1194          if (type3.is_category1()) {
1195            type4 = current_frame.pop_stack(
1196              VerificationType::category1_check(), CHECK_VERIFY(this));
1197          } else if (type3.is_category2_2nd()) {
1198            type4 = current_frame.pop_stack(
1199              VerificationType::category2_check(), CHECK_VERIFY(this));
1200          } else {
1201            /* Unreachable?  Would need a category2_1st on TOS after popping
1202             * a long/double or two category 1's, which does not
1203             * appear possible. */
1204            verify_error(
1205                ErrorContext::bad_type(bci, current_frame.stack_top_ctx()),
1206                bad_type_msg, "dup2_x2");
1207            return;
1208          }
1209          current_frame.push_stack(type2, CHECK_VERIFY(this));
1210          current_frame.push_stack(type, CHECK_VERIFY(this));
1211          current_frame.push_stack(type4, CHECK_VERIFY(this));
1212          current_frame.push_stack(type3, CHECK_VERIFY(this));
1213          current_frame.push_stack(type2, CHECK_VERIFY(this));
1214          current_frame.push_stack(type, CHECK_VERIFY(this));
1215          no_control_flow = false; break;
1216        }
1217        case Bytecodes::_swap :
1218          type = current_frame.pop_stack(
1219            VerificationType::category1_check(), CHECK_VERIFY(this));
1220          type2 = current_frame.pop_stack(
1221            VerificationType::category1_check(), CHECK_VERIFY(this));
1222          current_frame.push_stack(type, CHECK_VERIFY(this));
1223          current_frame.push_stack(type2, CHECK_VERIFY(this));
1224          no_control_flow = false; break;
1225        case Bytecodes::_iadd :
1226        case Bytecodes::_isub :
1227        case Bytecodes::_imul :
1228        case Bytecodes::_idiv :
1229        case Bytecodes::_irem :
1230        case Bytecodes::_ishl :
1231        case Bytecodes::_ishr :
1232        case Bytecodes::_iushr :
1233        case Bytecodes::_ior :
1234        case Bytecodes::_ixor :
1235        case Bytecodes::_iand :
1236          current_frame.pop_stack(
1237            VerificationType::integer_type(), CHECK_VERIFY(this));
1238          // fall through
1239        case Bytecodes::_ineg :
1240          current_frame.pop_stack(
1241            VerificationType::integer_type(), CHECK_VERIFY(this));
1242          current_frame.push_stack(
1243            VerificationType::integer_type(), CHECK_VERIFY(this));
1244          no_control_flow = false; break;
1245        case Bytecodes::_ladd :
1246        case Bytecodes::_lsub :
1247        case Bytecodes::_lmul :
1248        case Bytecodes::_ldiv :
1249        case Bytecodes::_lrem :
1250        case Bytecodes::_land :
1251        case Bytecodes::_lor :
1252        case Bytecodes::_lxor :
1253          current_frame.pop_stack_2(
1254            VerificationType::long2_type(),
1255            VerificationType::long_type(), CHECK_VERIFY(this));
1256          // fall through
1257        case Bytecodes::_lneg :
1258          current_frame.pop_stack_2(
1259            VerificationType::long2_type(),
1260            VerificationType::long_type(), CHECK_VERIFY(this));
1261          current_frame.push_stack_2(
1262            VerificationType::long_type(),
1263            VerificationType::long2_type(), CHECK_VERIFY(this));
1264          no_control_flow = false; break;
1265        case Bytecodes::_lshl :
1266        case Bytecodes::_lshr :
1267        case Bytecodes::_lushr :
1268          current_frame.pop_stack(
1269            VerificationType::integer_type(), CHECK_VERIFY(this));
1270          current_frame.pop_stack_2(
1271            VerificationType::long2_type(),
1272            VerificationType::long_type(), CHECK_VERIFY(this));
1273          current_frame.push_stack_2(
1274            VerificationType::long_type(),
1275            VerificationType::long2_type(), CHECK_VERIFY(this));
1276          no_control_flow = false; break;
1277        case Bytecodes::_fadd :
1278        case Bytecodes::_fsub :
1279        case Bytecodes::_fmul :
1280        case Bytecodes::_fdiv :
1281        case Bytecodes::_frem :
1282          current_frame.pop_stack(
1283            VerificationType::float_type(), CHECK_VERIFY(this));
1284          // fall through
1285        case Bytecodes::_fneg :
1286          current_frame.pop_stack(
1287            VerificationType::float_type(), CHECK_VERIFY(this));
1288          current_frame.push_stack(
1289            VerificationType::float_type(), CHECK_VERIFY(this));
1290          no_control_flow = false; break;
1291        case Bytecodes::_dadd :
1292        case Bytecodes::_dsub :
1293        case Bytecodes::_dmul :
1294        case Bytecodes::_ddiv :
1295        case Bytecodes::_drem :
1296          current_frame.pop_stack_2(
1297            VerificationType::double2_type(),
1298            VerificationType::double_type(), CHECK_VERIFY(this));
1299          // fall through
1300        case Bytecodes::_dneg :
1301          current_frame.pop_stack_2(
1302            VerificationType::double2_type(),
1303            VerificationType::double_type(), CHECK_VERIFY(this));
1304          current_frame.push_stack_2(
1305            VerificationType::double_type(),
1306            VerificationType::double2_type(), CHECK_VERIFY(this));
1307          no_control_flow = false; break;
1308        case Bytecodes::_iinc :
1309          verify_iinc(bcs.get_index(), &current_frame, CHECK_VERIFY(this));
1310          no_control_flow = false; break;
1311        case Bytecodes::_i2l :
1312          type = current_frame.pop_stack(
1313            VerificationType::integer_type(), CHECK_VERIFY(this));
1314          current_frame.push_stack_2(
1315            VerificationType::long_type(),
1316            VerificationType::long2_type(), CHECK_VERIFY(this));
1317          no_control_flow = false; break;
1318       case Bytecodes::_l2i :
1319          current_frame.pop_stack_2(
1320            VerificationType::long2_type(),
1321            VerificationType::long_type(), CHECK_VERIFY(this));
1322          current_frame.push_stack(
1323            VerificationType::integer_type(), CHECK_VERIFY(this));
1324          no_control_flow = false; break;
1325        case Bytecodes::_i2f :
1326          current_frame.pop_stack(
1327            VerificationType::integer_type(), CHECK_VERIFY(this));
1328          current_frame.push_stack(
1329            VerificationType::float_type(), CHECK_VERIFY(this));
1330          no_control_flow = false; break;
1331        case Bytecodes::_i2d :
1332          current_frame.pop_stack(
1333            VerificationType::integer_type(), CHECK_VERIFY(this));
1334          current_frame.push_stack_2(
1335            VerificationType::double_type(),
1336            VerificationType::double2_type(), CHECK_VERIFY(this));
1337          no_control_flow = false; break;
1338        case Bytecodes::_l2f :
1339          current_frame.pop_stack_2(
1340            VerificationType::long2_type(),
1341            VerificationType::long_type(), CHECK_VERIFY(this));
1342          current_frame.push_stack(
1343            VerificationType::float_type(), CHECK_VERIFY(this));
1344          no_control_flow = false; break;
1345        case Bytecodes::_l2d :
1346          current_frame.pop_stack_2(
1347            VerificationType::long2_type(),
1348            VerificationType::long_type(), CHECK_VERIFY(this));
1349          current_frame.push_stack_2(
1350            VerificationType::double_type(),
1351            VerificationType::double2_type(), CHECK_VERIFY(this));
1352          no_control_flow = false; break;
1353        case Bytecodes::_f2i :
1354          current_frame.pop_stack(
1355            VerificationType::float_type(), CHECK_VERIFY(this));
1356          current_frame.push_stack(
1357            VerificationType::integer_type(), CHECK_VERIFY(this));
1358          no_control_flow = false; break;
1359        case Bytecodes::_f2l :
1360          current_frame.pop_stack(
1361            VerificationType::float_type(), CHECK_VERIFY(this));
1362          current_frame.push_stack_2(
1363            VerificationType::long_type(),
1364            VerificationType::long2_type(), CHECK_VERIFY(this));
1365          no_control_flow = false; break;
1366        case Bytecodes::_f2d :
1367          current_frame.pop_stack(
1368            VerificationType::float_type(), CHECK_VERIFY(this));
1369          current_frame.push_stack_2(
1370            VerificationType::double_type(),
1371            VerificationType::double2_type(), CHECK_VERIFY(this));
1372          no_control_flow = false; break;
1373        case Bytecodes::_d2i :
1374          current_frame.pop_stack_2(
1375            VerificationType::double2_type(),
1376            VerificationType::double_type(), CHECK_VERIFY(this));
1377          current_frame.push_stack(
1378            VerificationType::integer_type(), CHECK_VERIFY(this));
1379          no_control_flow = false; break;
1380        case Bytecodes::_d2l :
1381          current_frame.pop_stack_2(
1382            VerificationType::double2_type(),
1383            VerificationType::double_type(), CHECK_VERIFY(this));
1384          current_frame.push_stack_2(
1385            VerificationType::long_type(),
1386            VerificationType::long2_type(), CHECK_VERIFY(this));
1387          no_control_flow = false; break;
1388        case Bytecodes::_d2f :
1389          current_frame.pop_stack_2(
1390            VerificationType::double2_type(),
1391            VerificationType::double_type(), CHECK_VERIFY(this));
1392          current_frame.push_stack(
1393            VerificationType::float_type(), CHECK_VERIFY(this));
1394          no_control_flow = false; break;
1395        case Bytecodes::_i2b :
1396        case Bytecodes::_i2c :
1397        case Bytecodes::_i2s :
1398          current_frame.pop_stack(
1399            VerificationType::integer_type(), CHECK_VERIFY(this));
1400          current_frame.push_stack(
1401            VerificationType::integer_type(), CHECK_VERIFY(this));
1402          no_control_flow = false; break;
1403        case Bytecodes::_lcmp :
1404          current_frame.pop_stack_2(
1405            VerificationType::long2_type(),
1406            VerificationType::long_type(), CHECK_VERIFY(this));
1407          current_frame.pop_stack_2(
1408            VerificationType::long2_type(),
1409            VerificationType::long_type(), CHECK_VERIFY(this));
1410          current_frame.push_stack(
1411            VerificationType::integer_type(), CHECK_VERIFY(this));
1412          no_control_flow = false; break;
1413        case Bytecodes::_fcmpl :
1414        case Bytecodes::_fcmpg :
1415          current_frame.pop_stack(
1416            VerificationType::float_type(), CHECK_VERIFY(this));
1417          current_frame.pop_stack(
1418            VerificationType::float_type(), CHECK_VERIFY(this));
1419          current_frame.push_stack(
1420            VerificationType::integer_type(), CHECK_VERIFY(this));
1421          no_control_flow = false; break;
1422        case Bytecodes::_dcmpl :
1423        case Bytecodes::_dcmpg :
1424          current_frame.pop_stack_2(
1425            VerificationType::double2_type(),
1426            VerificationType::double_type(), CHECK_VERIFY(this));
1427          current_frame.pop_stack_2(
1428            VerificationType::double2_type(),
1429            VerificationType::double_type(), CHECK_VERIFY(this));
1430          current_frame.push_stack(
1431            VerificationType::integer_type(), CHECK_VERIFY(this));
1432          no_control_flow = false; break;
1433        case Bytecodes::_if_icmpeq:
1434        case Bytecodes::_if_icmpne:
1435        case Bytecodes::_if_icmplt:
1436        case Bytecodes::_if_icmpge:
1437        case Bytecodes::_if_icmpgt:
1438        case Bytecodes::_if_icmple:
1439          current_frame.pop_stack(
1440            VerificationType::integer_type(), CHECK_VERIFY(this));
1441          // fall through
1442        case Bytecodes::_ifeq:
1443        case Bytecodes::_ifne:
1444        case Bytecodes::_iflt:
1445        case Bytecodes::_ifge:
1446        case Bytecodes::_ifgt:
1447        case Bytecodes::_ifle:
1448          current_frame.pop_stack(
1449            VerificationType::integer_type(), CHECK_VERIFY(this));
1450          target = bcs.dest();
1451          stackmap_table.check_jump_target(
1452            &current_frame, target, CHECK_VERIFY(this));
1453          no_control_flow = false; break;
1454        case Bytecodes::_if_acmpeq :
1455        case Bytecodes::_if_acmpne :
1456          current_frame.pop_stack(
1457            VerificationType::reference_check(), CHECK_VERIFY(this));
1458          // fall through
1459        case Bytecodes::_ifnull :
1460        case Bytecodes::_ifnonnull :
1461          current_frame.pop_stack(
1462            VerificationType::reference_check(), CHECK_VERIFY(this));
1463          target = bcs.dest();
1464          stackmap_table.check_jump_target
1465            (&current_frame, target, CHECK_VERIFY(this));
1466          no_control_flow = false; break;
1467        case Bytecodes::_goto :
1468          target = bcs.dest();
1469          stackmap_table.check_jump_target(
1470            &current_frame, target, CHECK_VERIFY(this));
1471          no_control_flow = true; break;
1472        case Bytecodes::_goto_w :
1473          target = bcs.dest_w();
1474          stackmap_table.check_jump_target(
1475            &current_frame, target, CHECK_VERIFY(this));
1476          no_control_flow = true; break;
1477        case Bytecodes::_tableswitch :
1478        case Bytecodes::_lookupswitch :
1479          verify_switch(
1480            &bcs, code_length, code_data, &current_frame,
1481            &stackmap_table, CHECK_VERIFY(this));
1482          no_control_flow = true; break;
1483        case Bytecodes::_ireturn :
1484          type = current_frame.pop_stack(
1485            VerificationType::integer_type(), CHECK_VERIFY(this));
1486          verify_return_value(return_type, type, bci,
1487                              &current_frame, CHECK_VERIFY(this));
1488          no_control_flow = true; break;
1489        case Bytecodes::_lreturn :
1490          type2 = current_frame.pop_stack(
1491            VerificationType::long2_type(), CHECK_VERIFY(this));
1492          type = current_frame.pop_stack(
1493            VerificationType::long_type(), CHECK_VERIFY(this));
1494          verify_return_value(return_type, type, bci,
1495                              &current_frame, CHECK_VERIFY(this));
1496          no_control_flow = true; break;
1497        case Bytecodes::_freturn :
1498          type = current_frame.pop_stack(
1499            VerificationType::float_type(), CHECK_VERIFY(this));
1500          verify_return_value(return_type, type, bci,
1501                              &current_frame, CHECK_VERIFY(this));
1502          no_control_flow = true; break;
1503        case Bytecodes::_dreturn :
1504          type2 = current_frame.pop_stack(
1505            VerificationType::double2_type(),  CHECK_VERIFY(this));
1506          type = current_frame.pop_stack(
1507            VerificationType::double_type(), CHECK_VERIFY(this));
1508          verify_return_value(return_type, type, bci,
1509                              &current_frame, CHECK_VERIFY(this));
1510          no_control_flow = true; break;
1511        case Bytecodes::_areturn :
1512          type = current_frame.pop_stack(
1513            VerificationType::reference_check(), CHECK_VERIFY(this));
1514          verify_return_value(return_type, type, bci,
1515                              &current_frame, CHECK_VERIFY(this));
1516          no_control_flow = true; break;
1517        case Bytecodes::_return :
1518          if (return_type != VerificationType::bogus_type()) {
1519            verify_error(ErrorContext::bad_code(bci),
1520                         "Method expects a return value");
1521            return;
1522          }
1523          // Make sure "this" has been initialized if current method is an
1524          // <init>
1525          if (_method->name() == vmSymbols::object_initializer_name() &&
1526              current_frame.flag_this_uninit()) {
1527            verify_error(ErrorContext::bad_code(bci),
1528                         "Constructor must call super() or this() "
1529                         "before return");
1530            return;
1531          }
1532          no_control_flow = true; break;
1533        case Bytecodes::_getstatic :
1534        case Bytecodes::_putstatic :
1535        case Bytecodes::_getfield :
1536        case Bytecodes::_putfield :
1537          verify_field_instructions(
1538            &bcs, &current_frame, cp, CHECK_VERIFY(this));
1539          no_control_flow = false; break;
1540        case Bytecodes::_invokevirtual :
1541        case Bytecodes::_invokespecial :
1542        case Bytecodes::_invokestatic :
1543          verify_invoke_instructions(
1544            &bcs, code_length, &current_frame,
1545            &this_uninit, return_type, cp, CHECK_VERIFY(this));
1546          no_control_flow = false; break;
1547        case Bytecodes::_invokeinterface :
1548        case Bytecodes::_invokedynamic :
1549          verify_invoke_instructions(
1550            &bcs, code_length, &current_frame,
1551            &this_uninit, return_type, cp, CHECK_VERIFY(this));
1552          no_control_flow = false; break;
1553        case Bytecodes::_new :
1554        {
1555          index = bcs.get_index_u2();
1556          verify_cp_class_type(bci, index, cp, CHECK_VERIFY(this));
1557          VerificationType new_class_type =
1558            cp_index_to_type(index, cp, CHECK_VERIFY(this));
1559          if (!new_class_type.is_object()) {
1560            verify_error(ErrorContext::bad_type(bci,
1561                TypeOrigin::cp(index, new_class_type)),
1562                "Illegal new instruction");
1563            return;
1564          }
1565          type = VerificationType::uninitialized_type(bci);
1566          current_frame.push_stack(type, CHECK_VERIFY(this));
1567          no_control_flow = false; break;
1568        }
1569        case Bytecodes::_newarray :
1570          type = get_newarray_type(bcs.get_index(), bci, CHECK_VERIFY(this));
1571          current_frame.pop_stack(
1572            VerificationType::integer_type(),  CHECK_VERIFY(this));
1573          current_frame.push_stack(type, CHECK_VERIFY(this));
1574          no_control_flow = false; break;
1575        case Bytecodes::_anewarray :
1576          verify_anewarray(
1577            bci, bcs.get_index_u2(), cp, &current_frame, CHECK_VERIFY(this));
1578          no_control_flow = false; break;
1579        case Bytecodes::_arraylength :
1580          type = current_frame.pop_stack(
1581            VerificationType::reference_check(), CHECK_VERIFY(this));
1582          if (!(type.is_null() || type.is_array())) {
1583            verify_error(ErrorContext::bad_type(
1584                bci, current_frame.stack_top_ctx()),
1585                bad_type_msg, "arraylength");
1586          }
1587          current_frame.push_stack(
1588            VerificationType::integer_type(), CHECK_VERIFY(this));
1589          no_control_flow = false; break;
1590        case Bytecodes::_checkcast :
1591        {
1592          index = bcs.get_index_u2();
1593          verify_cp_class_type(bci, index, cp, CHECK_VERIFY(this));
1594          current_frame.pop_stack(object_type(), CHECK_VERIFY(this));
1595          VerificationType klass_type = cp_index_to_type(
1596            index, cp, CHECK_VERIFY(this));
1597          current_frame.push_stack(klass_type, CHECK_VERIFY(this));
1598          no_control_flow = false; break;
1599        }
1600        case Bytecodes::_instanceof : {
1601          index = bcs.get_index_u2();
1602          verify_cp_class_type(bci, index, cp, CHECK_VERIFY(this));
1603          current_frame.pop_stack(object_type(), CHECK_VERIFY(this));
1604          current_frame.push_stack(
1605            VerificationType::integer_type(), CHECK_VERIFY(this));
1606          no_control_flow = false; break;
1607        }
1608        case Bytecodes::_monitorenter :
1609        case Bytecodes::_monitorexit :
1610          current_frame.pop_stack(
1611            VerificationType::reference_check(), CHECK_VERIFY(this));
1612          no_control_flow = false; break;
1613        case Bytecodes::_multianewarray :
1614        {
1615          index = bcs.get_index_u2();
1616          u2 dim = *(bcs.bcp()+3);
1617          verify_cp_class_type(bci, index, cp, CHECK_VERIFY(this));
1618          VerificationType new_array_type =
1619            cp_index_to_type(index, cp, CHECK_VERIFY(this));
1620          if (!new_array_type.is_array()) {
1621            verify_error(ErrorContext::bad_type(bci,
1622                TypeOrigin::cp(index, new_array_type)),
1623                "Illegal constant pool index in multianewarray instruction");
1624            return;
1625          }
1626          if (dim < 1 || new_array_type.dimensions() < dim) {
1627            verify_error(ErrorContext::bad_code(bci),
1628                "Illegal dimension in multianewarray instruction: %d", dim);
1629            return;
1630          }
1631          for (int i = 0; i < dim; i++) {
1632            current_frame.pop_stack(
1633              VerificationType::integer_type(), CHECK_VERIFY(this));
1634          }
1635          current_frame.push_stack(new_array_type, CHECK_VERIFY(this));
1636          no_control_flow = false; break;
1637        }
1638        case Bytecodes::_athrow :
1639          type = VerificationType::reference_type(
1640            vmSymbols::java_lang_Throwable());
1641          current_frame.pop_stack(type, CHECK_VERIFY(this));
1642          no_control_flow = true; break;
1643        default:
1644          // We only need to check the valid bytecodes in class file.
1645          // And jsr and ret are not in the new class file format in JDK1.5.
1646          verify_error(ErrorContext::bad_code(bci),
1647              "Bad instruction: %02x", opcode);
1648          no_control_flow = false;
1649          return;
1650      }  // end switch
1651    }  // end Merge with the next instruction
1652
1653    // Look for possible jump target in exception handlers and see if it
1654    // matches current_frame
1655    if (bci >= ex_min && bci < ex_max) {
1656      verify_exception_handler_targets(
1657        bci, this_uninit, &current_frame, &stackmap_table, CHECK_VERIFY(this));
1658    }
1659  } // end while
1660
1661  // Make sure that control flow does not fall through end of the method
1662  if (!no_control_flow) {
1663    verify_error(ErrorContext::bad_code(code_length),
1664        "Control flow falls through code end");
1665    return;
1666  }
1667}
1668
1669#undef bad_type_message
1670
1671char* ClassVerifier::generate_code_data(methodHandle m, u4 code_length, TRAPS) {
1672  char* code_data = NEW_RESOURCE_ARRAY(char, code_length);
1673  memset(code_data, 0, sizeof(char) * code_length);
1674  RawBytecodeStream bcs(m);
1675
1676  while (!bcs.is_last_bytecode()) {
1677    if (bcs.raw_next() != Bytecodes::_illegal) {
1678      int bci = bcs.bci();
1679      if (bcs.raw_code() == Bytecodes::_new) {
1680        code_data[bci] = NEW_OFFSET;
1681      } else {
1682        code_data[bci] = BYTECODE_OFFSET;
1683      }
1684    } else {
1685      verify_error(ErrorContext::bad_code(bcs.bci()), "Bad instruction");
1686      return NULL;
1687    }
1688  }
1689
1690  return code_data;
1691}
1692
1693void ClassVerifier::verify_exception_handler_table(u4 code_length, char* code_data, int& min, int& max, TRAPS) {
1694  ExceptionTable exhandlers(_method());
1695  int exlength = exhandlers.length();
1696  constantPoolHandle cp (THREAD, _method->constants());
1697
1698  for(int i = 0; i < exlength; i++) {
1699    //reacquire the table in case a GC happened
1700    ExceptionTable exhandlers(_method());
1701    u2 start_pc = exhandlers.start_pc(i);
1702    u2 end_pc = exhandlers.end_pc(i);
1703    u2 handler_pc = exhandlers.handler_pc(i);
1704    if (start_pc >= code_length || code_data[start_pc] == 0) {
1705      class_format_error("Illegal exception table start_pc %d", start_pc);
1706      return;
1707    }
1708    if (end_pc != code_length) {   // special case: end_pc == code_length
1709      if (end_pc > code_length || code_data[end_pc] == 0) {
1710        class_format_error("Illegal exception table end_pc %d", end_pc);
1711        return;
1712      }
1713    }
1714    if (handler_pc >= code_length || code_data[handler_pc] == 0) {
1715      class_format_error("Illegal exception table handler_pc %d", handler_pc);
1716      return;
1717    }
1718    int catch_type_index = exhandlers.catch_type_index(i);
1719    if (catch_type_index != 0) {
1720      VerificationType catch_type = cp_index_to_type(
1721        catch_type_index, cp, CHECK_VERIFY(this));
1722      VerificationType throwable =
1723        VerificationType::reference_type(vmSymbols::java_lang_Throwable());
1724      bool is_subclass = throwable.is_assignable_from(
1725        catch_type, this, CHECK_VERIFY(this));
1726      if (!is_subclass) {
1727        // 4286534: should throw VerifyError according to recent spec change
1728        verify_error(ErrorContext::bad_type(handler_pc,
1729            TypeOrigin::cp(catch_type_index, catch_type),
1730            TypeOrigin::implicit(throwable)),
1731            "Catch type is not a subclass "
1732            "of Throwable in exception handler %d", handler_pc);
1733        return;
1734      }
1735    }
1736    if (start_pc < min) min = start_pc;
1737    if (end_pc > max) max = end_pc;
1738  }
1739}
1740
1741void ClassVerifier::verify_local_variable_table(u4 code_length, char* code_data, TRAPS) {
1742  int localvariable_table_length = _method()->localvariable_table_length();
1743  if (localvariable_table_length > 0) {
1744    LocalVariableTableElement* table = _method()->localvariable_table_start();
1745    for (int i = 0; i < localvariable_table_length; i++) {
1746      u2 start_bci = table[i].start_bci;
1747      u2 length = table[i].length;
1748
1749      if (start_bci >= code_length || code_data[start_bci] == 0) {
1750        class_format_error(
1751          "Illegal local variable table start_pc %d", start_bci);
1752        return;
1753      }
1754      u4 end_bci = (u4)(start_bci + length);
1755      if (end_bci != code_length) {
1756        if (end_bci >= code_length || code_data[end_bci] == 0) {
1757          class_format_error( "Illegal local variable table length %d", length);
1758          return;
1759        }
1760      }
1761    }
1762  }
1763}
1764
1765u2 ClassVerifier::verify_stackmap_table(u2 stackmap_index, u2 bci,
1766                                        StackMapFrame* current_frame,
1767                                        StackMapTable* stackmap_table,
1768                                        bool no_control_flow, TRAPS) {
1769  if (stackmap_index < stackmap_table->get_frame_count()) {
1770    u2 this_offset = stackmap_table->get_offset(stackmap_index);
1771    if (no_control_flow && this_offset > bci) {
1772      verify_error(ErrorContext::missing_stackmap(bci),
1773                   "Expecting a stack map frame");
1774      return 0;
1775    }
1776    if (this_offset == bci) {
1777      ErrorContext ctx;
1778      // See if current stack map can be assigned to the frame in table.
1779      // current_frame is the stackmap frame got from the last instruction.
1780      // If matched, current_frame will be updated by this method.
1781      bool matches = stackmap_table->match_stackmap(
1782        current_frame, this_offset, stackmap_index,
1783        !no_control_flow, true, &ctx, CHECK_VERIFY_(this, 0));
1784      if (!matches) {
1785        // report type error
1786        verify_error(ctx, "Instruction type does not match stack map");
1787        return 0;
1788      }
1789      stackmap_index++;
1790    } else if (this_offset < bci) {
1791      // current_offset should have met this_offset.
1792      class_format_error("Bad stack map offset %d", this_offset);
1793      return 0;
1794    }
1795  } else if (no_control_flow) {
1796    verify_error(ErrorContext::bad_code(bci), "Expecting a stack map frame");
1797    return 0;
1798  }
1799  return stackmap_index;
1800}
1801
1802void ClassVerifier::verify_exception_handler_targets(u2 bci, bool this_uninit, StackMapFrame* current_frame,
1803                                                     StackMapTable* stackmap_table, TRAPS) {
1804  constantPoolHandle cp (THREAD, _method->constants());
1805  ExceptionTable exhandlers(_method());
1806  int exlength = exhandlers.length();
1807  for(int i = 0; i < exlength; i++) {
1808    //reacquire the table in case a GC happened
1809    ExceptionTable exhandlers(_method());
1810    u2 start_pc = exhandlers.start_pc(i);
1811    u2 end_pc = exhandlers.end_pc(i);
1812    u2 handler_pc = exhandlers.handler_pc(i);
1813    int catch_type_index = exhandlers.catch_type_index(i);
1814    if(bci >= start_pc && bci < end_pc) {
1815      u1 flags = current_frame->flags();
1816      if (this_uninit) {  flags |= FLAG_THIS_UNINIT; }
1817      StackMapFrame* new_frame = current_frame->frame_in_exception_handler(flags);
1818      if (catch_type_index != 0) {
1819        // We know that this index refers to a subclass of Throwable
1820        VerificationType catch_type = cp_index_to_type(
1821          catch_type_index, cp, CHECK_VERIFY(this));
1822        new_frame->push_stack(catch_type, CHECK_VERIFY(this));
1823      } else {
1824        VerificationType throwable =
1825          VerificationType::reference_type(vmSymbols::java_lang_Throwable());
1826        new_frame->push_stack(throwable, CHECK_VERIFY(this));
1827      }
1828      ErrorContext ctx;
1829      bool matches = stackmap_table->match_stackmap(
1830        new_frame, handler_pc, true, false, &ctx, CHECK_VERIFY(this));
1831      if (!matches) {
1832        verify_error(ctx, "Stack map does not match the one at "
1833            "exception handler %d", handler_pc);
1834        return;
1835      }
1836    }
1837  }
1838}
1839
1840void ClassVerifier::verify_cp_index(
1841    u2 bci, constantPoolHandle cp, int index, TRAPS) {
1842  int nconstants = cp->length();
1843  if ((index <= 0) || (index >= nconstants)) {
1844    verify_error(ErrorContext::bad_cp_index(bci, index),
1845        "Illegal constant pool index %d in class %s",
1846        index, cp->pool_holder()->external_name());
1847    return;
1848  }
1849}
1850
1851void ClassVerifier::verify_cp_type(
1852    u2 bci, int index, constantPoolHandle cp, unsigned int types, TRAPS) {
1853
1854  // In some situations, bytecode rewriting may occur while we're verifying.
1855  // In this case, a constant pool cache exists and some indices refer to that
1856  // instead.  Be sure we don't pick up such indices by accident.
1857  // We must check was_recursively_verified() before we get here.
1858  guarantee(cp->cache() == NULL, "not rewritten yet");
1859
1860  verify_cp_index(bci, cp, index, CHECK_VERIFY(this));
1861  unsigned int tag = cp->tag_at(index).value();
1862  if ((types & (1 << tag)) == 0) {
1863    verify_error(ErrorContext::bad_cp_index(bci, index),
1864      "Illegal type at constant pool entry %d in class %s",
1865      index, cp->pool_holder()->external_name());
1866    return;
1867  }
1868}
1869
1870void ClassVerifier::verify_cp_class_type(
1871    u2 bci, int index, constantPoolHandle cp, TRAPS) {
1872  verify_cp_index(bci, cp, index, CHECK_VERIFY(this));
1873  constantTag tag = cp->tag_at(index);
1874  if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1875    verify_error(ErrorContext::bad_cp_index(bci, index),
1876        "Illegal type at constant pool entry %d in class %s",
1877        index, cp->pool_holder()->external_name());
1878    return;
1879  }
1880}
1881
1882void ClassVerifier::verify_error(ErrorContext ctx, const char* msg, ...) {
1883  stringStream ss;
1884
1885  ctx.reset_frames();
1886  _exception_type = vmSymbols::java_lang_VerifyError();
1887  _error_context = ctx;
1888  va_list va;
1889  va_start(va, msg);
1890  ss.vprint(msg, va);
1891  va_end(va);
1892  _message = ss.as_string();
1893#ifdef ASSERT
1894  ResourceMark rm;
1895  const char* exception_name = _exception_type->as_C_string();
1896  Exceptions::debug_check_abort(exception_name, NULL);
1897#endif // ndef ASSERT
1898}
1899
1900void ClassVerifier::class_format_error(const char* msg, ...) {
1901  stringStream ss;
1902  _exception_type = vmSymbols::java_lang_ClassFormatError();
1903  va_list va;
1904  va_start(va, msg);
1905  ss.vprint(msg, va);
1906  va_end(va);
1907  if (!_method.is_null()) {
1908    ss.print(" in method %s", _method->name_and_sig_as_C_string());
1909  }
1910  _message = ss.as_string();
1911}
1912
1913Klass* ClassVerifier::load_class(Symbol* name, TRAPS) {
1914  // Get current loader and protection domain first.
1915  oop loader = current_class()->class_loader();
1916  oop protection_domain = current_class()->protection_domain();
1917
1918  return SystemDictionary::resolve_or_fail(
1919    name, Handle(THREAD, loader), Handle(THREAD, protection_domain),
1920    true, CHECK_NULL);
1921}
1922
1923bool ClassVerifier::is_protected_access(instanceKlassHandle this_class,
1924                                        Klass* target_class,
1925                                        Symbol* field_name,
1926                                        Symbol* field_sig,
1927                                        bool is_method) {
1928  No_Safepoint_Verifier nosafepoint;
1929
1930  // If target class isn't a super class of this class, we don't worry about this case
1931  if (!this_class->is_subclass_of(target_class)) {
1932    return false;
1933  }
1934  // Check if the specified method or field is protected
1935  InstanceKlass* target_instance = InstanceKlass::cast(target_class);
1936  fieldDescriptor fd;
1937  if (is_method) {
1938    Method* m = target_instance->uncached_lookup_method(field_name, field_sig, Klass::normal);
1939    if (m != NULL && m->is_protected()) {
1940      if (!this_class->is_same_class_package(m->method_holder())) {
1941        return true;
1942      }
1943    }
1944  } else {
1945    Klass* member_klass = target_instance->find_field(field_name, field_sig, &fd);
1946    if (member_klass != NULL && fd.is_protected()) {
1947      if (!this_class->is_same_class_package(member_klass)) {
1948        return true;
1949      }
1950    }
1951  }
1952  return false;
1953}
1954
1955void ClassVerifier::verify_ldc(
1956    int opcode, u2 index, StackMapFrame* current_frame,
1957    constantPoolHandle cp, u2 bci, TRAPS) {
1958  verify_cp_index(bci, cp, index, CHECK_VERIFY(this));
1959  constantTag tag = cp->tag_at(index);
1960  unsigned int types;
1961  if (opcode == Bytecodes::_ldc || opcode == Bytecodes::_ldc_w) {
1962    if (!tag.is_unresolved_klass()) {
1963      types = (1 << JVM_CONSTANT_Integer) | (1 << JVM_CONSTANT_Float)
1964            | (1 << JVM_CONSTANT_String)  | (1 << JVM_CONSTANT_Class)
1965            | (1 << JVM_CONSTANT_MethodHandle) | (1 << JVM_CONSTANT_MethodType);
1966      // Note:  The class file parser already verified the legality of
1967      // MethodHandle and MethodType constants.
1968      verify_cp_type(bci, index, cp, types, CHECK_VERIFY(this));
1969    }
1970  } else {
1971    assert(opcode == Bytecodes::_ldc2_w, "must be ldc2_w");
1972    types = (1 << JVM_CONSTANT_Double) | (1 << JVM_CONSTANT_Long);
1973    verify_cp_type(bci, index, cp, types, CHECK_VERIFY(this));
1974  }
1975  if (tag.is_string() && cp->is_pseudo_string_at(index)) {
1976    current_frame->push_stack(object_type(), CHECK_VERIFY(this));
1977  } else if (tag.is_string()) {
1978    current_frame->push_stack(
1979      VerificationType::reference_type(
1980        vmSymbols::java_lang_String()), CHECK_VERIFY(this));
1981  } else if (tag.is_klass() || tag.is_unresolved_klass()) {
1982    current_frame->push_stack(
1983      VerificationType::reference_type(
1984        vmSymbols::java_lang_Class()), CHECK_VERIFY(this));
1985  } else if (tag.is_int()) {
1986    current_frame->push_stack(
1987      VerificationType::integer_type(), CHECK_VERIFY(this));
1988  } else if (tag.is_float()) {
1989    current_frame->push_stack(
1990      VerificationType::float_type(), CHECK_VERIFY(this));
1991  } else if (tag.is_double()) {
1992    current_frame->push_stack_2(
1993      VerificationType::double_type(),
1994      VerificationType::double2_type(), CHECK_VERIFY(this));
1995  } else if (tag.is_long()) {
1996    current_frame->push_stack_2(
1997      VerificationType::long_type(),
1998      VerificationType::long2_type(), CHECK_VERIFY(this));
1999  } else if (tag.is_method_handle()) {
2000    current_frame->push_stack(
2001      VerificationType::reference_type(
2002        vmSymbols::java_lang_invoke_MethodHandle()), CHECK_VERIFY(this));
2003  } else if (tag.is_method_type()) {
2004    current_frame->push_stack(
2005      VerificationType::reference_type(
2006        vmSymbols::java_lang_invoke_MethodType()), CHECK_VERIFY(this));
2007  } else {
2008    /* Unreachable? verify_cp_type has already validated the cp type. */
2009    verify_error(
2010        ErrorContext::bad_cp_index(bci, index), "Invalid index in ldc");
2011    return;
2012  }
2013}
2014
2015void ClassVerifier::verify_switch(
2016    RawBytecodeStream* bcs, u4 code_length, char* code_data,
2017    StackMapFrame* current_frame, StackMapTable* stackmap_table, TRAPS) {
2018  int bci = bcs->bci();
2019  address bcp = bcs->bcp();
2020  address aligned_bcp = (address) round_to((intptr_t)(bcp + 1), jintSize);
2021
2022  if (_klass->major_version() < NONZERO_PADDING_BYTES_IN_SWITCH_MAJOR_VERSION) {
2023    // 4639449 & 4647081: padding bytes must be 0
2024    u2 padding_offset = 1;
2025    while ((bcp + padding_offset) < aligned_bcp) {
2026      if(*(bcp + padding_offset) != 0) {
2027        verify_error(ErrorContext::bad_code(bci),
2028                     "Nonzero padding byte in lookupswitch or tableswitch");
2029        return;
2030      }
2031      padding_offset++;
2032    }
2033  }
2034
2035  int default_offset = (int) Bytes::get_Java_u4(aligned_bcp);
2036  int keys, delta;
2037  current_frame->pop_stack(
2038    VerificationType::integer_type(), CHECK_VERIFY(this));
2039  if (bcs->raw_code() == Bytecodes::_tableswitch) {
2040    jint low = (jint)Bytes::get_Java_u4(aligned_bcp + jintSize);
2041    jint high = (jint)Bytes::get_Java_u4(aligned_bcp + 2*jintSize);
2042    if (low > high) {
2043      verify_error(ErrorContext::bad_code(bci),
2044          "low must be less than or equal to high in tableswitch");
2045      return;
2046    }
2047    keys = high - low + 1;
2048    if (keys < 0) {
2049      verify_error(ErrorContext::bad_code(bci), "too many keys in tableswitch");
2050      return;
2051    }
2052    delta = 1;
2053  } else {
2054    keys = (int)Bytes::get_Java_u4(aligned_bcp + jintSize);
2055    if (keys < 0) {
2056      verify_error(ErrorContext::bad_code(bci),
2057                   "number of keys in lookupswitch less than 0");
2058      return;
2059    }
2060    delta = 2;
2061    // Make sure that the lookupswitch items are sorted
2062    for (int i = 0; i < (keys - 1); i++) {
2063      jint this_key = Bytes::get_Java_u4(aligned_bcp + (2+2*i)*jintSize);
2064      jint next_key = Bytes::get_Java_u4(aligned_bcp + (2+2*i+2)*jintSize);
2065      if (this_key >= next_key) {
2066        verify_error(ErrorContext::bad_code(bci),
2067                     "Bad lookupswitch instruction");
2068        return;
2069      }
2070    }
2071  }
2072  int target = bci + default_offset;
2073  stackmap_table->check_jump_target(current_frame, target, CHECK_VERIFY(this));
2074  for (int i = 0; i < keys; i++) {
2075    // Because check_jump_target() may safepoint, the bytecode could have
2076    // moved, which means 'aligned_bcp' is no good and needs to be recalculated.
2077    aligned_bcp = (address)round_to((intptr_t)(bcs->bcp() + 1), jintSize);
2078    target = bci + (jint)Bytes::get_Java_u4(aligned_bcp+(3+i*delta)*jintSize);
2079    stackmap_table->check_jump_target(
2080      current_frame, target, CHECK_VERIFY(this));
2081  }
2082  NOT_PRODUCT(aligned_bcp = NULL);  // no longer valid at this point
2083}
2084
2085bool ClassVerifier::name_in_supers(
2086    Symbol* ref_name, instanceKlassHandle current) {
2087  Klass* super = current->super();
2088  while (super != NULL) {
2089    if (super->name() == ref_name) {
2090      return true;
2091    }
2092    super = super->super();
2093  }
2094  return false;
2095}
2096
2097void ClassVerifier::verify_field_instructions(RawBytecodeStream* bcs,
2098                                              StackMapFrame* current_frame,
2099                                              constantPoolHandle cp,
2100                                              TRAPS) {
2101  u2 index = bcs->get_index_u2();
2102  verify_cp_type(bcs->bci(), index, cp,
2103      1 << JVM_CONSTANT_Fieldref, CHECK_VERIFY(this));
2104
2105  // Get field name and signature
2106  Symbol* field_name = cp->name_ref_at(index);
2107  Symbol* field_sig = cp->signature_ref_at(index);
2108
2109  if (!SignatureVerifier::is_valid_type_signature(field_sig)) {
2110    class_format_error(
2111      "Invalid signature for field in class %s referenced "
2112      "from constant pool index %d", _klass->external_name(), index);
2113    return;
2114  }
2115
2116  // Get referenced class type
2117  VerificationType ref_class_type = cp_ref_index_to_type(
2118    index, cp, CHECK_VERIFY(this));
2119  if (!ref_class_type.is_object()) {
2120    /* Unreachable?  Class file parser verifies Fieldref contents */
2121    verify_error(ErrorContext::bad_type(bcs->bci(),
2122        TypeOrigin::cp(index, ref_class_type)),
2123        "Expecting reference to class in class %s at constant pool index %d",
2124        _klass->external_name(), index);
2125    return;
2126  }
2127  VerificationType target_class_type = ref_class_type;
2128
2129  assert(sizeof(VerificationType) == sizeof(uintptr_t),
2130        "buffer type must match VerificationType size");
2131  uintptr_t field_type_buffer[2];
2132  VerificationType* field_type = (VerificationType*)field_type_buffer;
2133  // If we make a VerificationType[2] array directly, the compiler calls
2134  // to the c-runtime library to do the allocation instead of just
2135  // stack allocating it.  Plus it would run constructors.  This shows up
2136  // in performance profiles.
2137
2138  SignatureStream sig_stream(field_sig, false);
2139  VerificationType stack_object_type;
2140  int n = change_sig_to_verificationType(
2141    &sig_stream, field_type, CHECK_VERIFY(this));
2142  u2 bci = bcs->bci();
2143  bool is_assignable;
2144  switch (bcs->raw_code()) {
2145    case Bytecodes::_getstatic: {
2146      for (int i = 0; i < n; i++) {
2147        current_frame->push_stack(field_type[i], CHECK_VERIFY(this));
2148      }
2149      break;
2150    }
2151    case Bytecodes::_putstatic: {
2152      for (int i = n - 1; i >= 0; i--) {
2153        current_frame->pop_stack(field_type[i], CHECK_VERIFY(this));
2154      }
2155      break;
2156    }
2157    case Bytecodes::_getfield: {
2158      stack_object_type = current_frame->pop_stack(
2159        target_class_type, CHECK_VERIFY(this));
2160      for (int i = 0; i < n; i++) {
2161        current_frame->push_stack(field_type[i], CHECK_VERIFY(this));
2162      }
2163      goto check_protected;
2164    }
2165    case Bytecodes::_putfield: {
2166      for (int i = n - 1; i >= 0; i--) {
2167        current_frame->pop_stack(field_type[i], CHECK_VERIFY(this));
2168      }
2169      stack_object_type = current_frame->pop_stack(CHECK_VERIFY(this));
2170
2171      // The JVMS 2nd edition allows field initialization before the superclass
2172      // initializer, if the field is defined within the current class.
2173      fieldDescriptor fd;
2174      if (stack_object_type == VerificationType::uninitialized_this_type() &&
2175          target_class_type.equals(current_type()) &&
2176          _klass->find_local_field(field_name, field_sig, &fd)) {
2177        stack_object_type = current_type();
2178      }
2179      is_assignable = target_class_type.is_assignable_from(
2180        stack_object_type, this, CHECK_VERIFY(this));
2181      if (!is_assignable) {
2182        verify_error(ErrorContext::bad_type(bci,
2183            current_frame->stack_top_ctx(),
2184            TypeOrigin::cp(index, target_class_type)),
2185            "Bad type on operand stack in putfield");
2186        return;
2187      }
2188    }
2189    check_protected: {
2190      if (_this_type == stack_object_type)
2191        break; // stack_object_type must be assignable to _current_class_type
2192      Symbol* ref_class_name =
2193        cp->klass_name_at(cp->klass_ref_index_at(index));
2194      if (!name_in_supers(ref_class_name, current_class()))
2195        // stack_object_type must be assignable to _current_class_type since:
2196        // 1. stack_object_type must be assignable to ref_class.
2197        // 2. ref_class must be _current_class or a subclass of it. It can't
2198        //    be a superclass of it. See revised JVMS 5.4.4.
2199        break;
2200
2201      Klass* ref_class_oop = load_class(ref_class_name, CHECK);
2202      if (is_protected_access(current_class(), ref_class_oop, field_name,
2203                              field_sig, false)) {
2204        // It's protected access, check if stack object is assignable to
2205        // current class.
2206        is_assignable = current_type().is_assignable_from(
2207          stack_object_type, this, CHECK_VERIFY(this));
2208        if (!is_assignable) {
2209          verify_error(ErrorContext::bad_type(bci,
2210              current_frame->stack_top_ctx(),
2211              TypeOrigin::implicit(current_type())),
2212              "Bad access to protected data in getfield");
2213          return;
2214        }
2215      }
2216      break;
2217    }
2218    default: ShouldNotReachHere();
2219  }
2220}
2221
2222void ClassVerifier::verify_invoke_init(
2223    RawBytecodeStream* bcs, u2 ref_class_index, VerificationType ref_class_type,
2224    StackMapFrame* current_frame, u4 code_length, bool *this_uninit,
2225    constantPoolHandle cp, TRAPS) {
2226  u2 bci = bcs->bci();
2227  VerificationType type = current_frame->pop_stack(
2228    VerificationType::reference_check(), CHECK_VERIFY(this));
2229  if (type == VerificationType::uninitialized_this_type()) {
2230    // The method must be an <init> method of this class or its superclass
2231    Klass* superk = current_class()->super();
2232    if (ref_class_type.name() != current_class()->name() &&
2233        ref_class_type.name() != superk->name()) {
2234      verify_error(ErrorContext::bad_type(bci,
2235          TypeOrigin::implicit(ref_class_type),
2236          TypeOrigin::implicit(current_type())),
2237          "Bad <init> method call");
2238      return;
2239    }
2240
2241    // Make sure that this call is not jumped over.
2242    if (bci < furthest_jump()) {
2243      verify_error(ErrorContext::bad_code(bci),
2244                   "Bad <init> method call from inside of a branch");
2245      return;
2246    }
2247
2248    // Make sure that this call is not done from within a TRY block because
2249    // that can result in returning an incomplete object.  Simply checking
2250    // (bci >= start_pc) also ensures that this call is not done after a TRY
2251    // block.  That is also illegal because this call must be the first Java
2252    // statement in the constructor.
2253    ExceptionTable exhandlers(_method());
2254    int exlength = exhandlers.length();
2255    for(int i = 0; i < exlength; i++) {
2256      if (bci >= exhandlers.start_pc(i)) {
2257        verify_error(ErrorContext::bad_code(bci),
2258                     "Bad <init> method call from after the start of a try block");
2259        return;
2260      }
2261    }
2262
2263    current_frame->initialize_object(type, current_type());
2264    *this_uninit = true;
2265  } else if (type.is_uninitialized()) {
2266    u2 new_offset = type.bci();
2267    address new_bcp = bcs->bcp() - bci + new_offset;
2268    if (new_offset > (code_length - 3) || (*new_bcp) != Bytecodes::_new) {
2269      /* Unreachable?  Stack map parsing ensures valid type and new
2270       * instructions have a valid BCI. */
2271      verify_error(ErrorContext::bad_code(new_offset),
2272                   "Expecting new instruction");
2273      return;
2274    }
2275    u2 new_class_index = Bytes::get_Java_u2(new_bcp + 1);
2276    verify_cp_class_type(bci, new_class_index, cp, CHECK_VERIFY(this));
2277
2278    // The method must be an <init> method of the indicated class
2279    VerificationType new_class_type = cp_index_to_type(
2280      new_class_index, cp, CHECK_VERIFY(this));
2281    if (!new_class_type.equals(ref_class_type)) {
2282      verify_error(ErrorContext::bad_type(bci,
2283          TypeOrigin::cp(new_class_index, new_class_type),
2284          TypeOrigin::cp(ref_class_index, ref_class_type)),
2285          "Call to wrong <init> method");
2286      return;
2287    }
2288    // According to the VM spec, if the referent class is a superclass of the
2289    // current class, and is in a different runtime package, and the method is
2290    // protected, then the objectref must be the current class or a subclass
2291    // of the current class.
2292    VerificationType objectref_type = new_class_type;
2293    if (name_in_supers(ref_class_type.name(), current_class())) {
2294      Klass* ref_klass = load_class(
2295        ref_class_type.name(), CHECK_VERIFY(this));
2296      Method* m = InstanceKlass::cast(ref_klass)->uncached_lookup_method(
2297        vmSymbols::object_initializer_name(),
2298        cp->signature_ref_at(bcs->get_index_u2()),
2299        Klass::normal);
2300      // Do nothing if method is not found.  Let resolution detect the error.
2301      if (m != NULL) {
2302        instanceKlassHandle mh(THREAD, m->method_holder());
2303        if (m->is_protected() && !mh->is_same_class_package(_klass())) {
2304          bool assignable = current_type().is_assignable_from(
2305            objectref_type, this, CHECK_VERIFY(this));
2306          if (!assignable) {
2307            verify_error(ErrorContext::bad_type(bci,
2308                TypeOrigin::cp(new_class_index, objectref_type),
2309                TypeOrigin::implicit(current_type())),
2310                "Bad access to protected <init> method");
2311            return;
2312          }
2313        }
2314      }
2315    }
2316    current_frame->initialize_object(type, new_class_type);
2317  } else {
2318    verify_error(ErrorContext::bad_type(bci, current_frame->stack_top_ctx()),
2319        "Bad operand type when invoking <init>");
2320    return;
2321  }
2322}
2323
2324bool ClassVerifier::is_same_or_direct_interface(
2325    instanceKlassHandle klass,
2326    VerificationType klass_type,
2327    VerificationType ref_class_type) {
2328  if (ref_class_type.equals(klass_type)) return true;
2329  Array<Klass*>* local_interfaces = klass->local_interfaces();
2330  if (local_interfaces != NULL) {
2331    for (int x = 0; x < local_interfaces->length(); x++) {
2332      Klass* k = local_interfaces->at(x);
2333      assert (k != NULL && k->is_interface(), "invalid interface");
2334      if (ref_class_type.equals(VerificationType::reference_type(k->name()))) {
2335        return true;
2336      }
2337    }
2338  }
2339  return false;
2340}
2341
2342void ClassVerifier::verify_invoke_instructions(
2343    RawBytecodeStream* bcs, u4 code_length, StackMapFrame* current_frame,
2344    bool *this_uninit, VerificationType return_type,
2345    constantPoolHandle cp, TRAPS) {
2346  // Make sure the constant pool item is the right type
2347  u2 index = bcs->get_index_u2();
2348  Bytecodes::Code opcode = bcs->raw_code();
2349  unsigned int types;
2350  switch (opcode) {
2351    case Bytecodes::_invokeinterface:
2352      types = 1 << JVM_CONSTANT_InterfaceMethodref;
2353      break;
2354    case Bytecodes::_invokedynamic:
2355      types = 1 << JVM_CONSTANT_InvokeDynamic;
2356      break;
2357    case Bytecodes::_invokespecial:
2358    case Bytecodes::_invokestatic:
2359      types = (_klass->major_version() < STATIC_METHOD_IN_INTERFACE_MAJOR_VERSION) ?
2360        (1 << JVM_CONSTANT_Methodref) :
2361        ((1 << JVM_CONSTANT_InterfaceMethodref) | (1 << JVM_CONSTANT_Methodref));
2362      break;
2363    default:
2364      types = 1 << JVM_CONSTANT_Methodref;
2365  }
2366  verify_cp_type(bcs->bci(), index, cp, types, CHECK_VERIFY(this));
2367
2368  // Get method name and signature
2369  Symbol* method_name = cp->name_ref_at(index);
2370  Symbol* method_sig = cp->signature_ref_at(index);
2371
2372  if (!SignatureVerifier::is_valid_method_signature(method_sig)) {
2373    class_format_error(
2374      "Invalid method signature in class %s referenced "
2375      "from constant pool index %d", _klass->external_name(), index);
2376    return;
2377  }
2378
2379  // Get referenced class type
2380  VerificationType ref_class_type;
2381  if (opcode == Bytecodes::_invokedynamic) {
2382    if (_klass->major_version() < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
2383      class_format_error(
2384        "invokedynamic instructions not supported by this class file version (%d), class %s",
2385        _klass->major_version(), _klass->external_name());
2386      return;
2387    }
2388  } else {
2389    ref_class_type = cp_ref_index_to_type(index, cp, CHECK_VERIFY(this));
2390  }
2391
2392  // For a small signature length, we just allocate 128 bytes instead
2393  // of parsing the signature once to find its size.
2394  // -3 is for '(', ')' and return descriptor; multiply by 2 is for
2395  // longs/doubles to be consertive.
2396  assert(sizeof(VerificationType) == sizeof(uintptr_t),
2397        "buffer type must match VerificationType size");
2398  uintptr_t on_stack_sig_types_buffer[128];
2399  // If we make a VerificationType[128] array directly, the compiler calls
2400  // to the c-runtime library to do the allocation instead of just
2401  // stack allocating it.  Plus it would run constructors.  This shows up
2402  // in performance profiles.
2403
2404  VerificationType* sig_types;
2405  int size = (method_sig->utf8_length() - 3) * 2;
2406  if (size > 128) {
2407    // Long and double occupies two slots here.
2408    ArgumentSizeComputer size_it(method_sig);
2409    size = size_it.size();
2410    sig_types = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, VerificationType, size);
2411  } else{
2412    sig_types = (VerificationType*)on_stack_sig_types_buffer;
2413  }
2414  SignatureStream sig_stream(method_sig);
2415  int sig_i = 0;
2416  while (!sig_stream.at_return_type()) {
2417    sig_i += change_sig_to_verificationType(
2418      &sig_stream, &sig_types[sig_i], CHECK_VERIFY(this));
2419    sig_stream.next();
2420  }
2421  int nargs = sig_i;
2422
2423#ifdef ASSERT
2424  {
2425    ArgumentSizeComputer size_it(method_sig);
2426    assert(nargs == size_it.size(), "Argument sizes do not match");
2427    assert(nargs <= (method_sig->utf8_length() - 3) * 2, "estimate of max size isn't conservative enough");
2428  }
2429#endif
2430
2431  // Check instruction operands
2432  u2 bci = bcs->bci();
2433  if (opcode == Bytecodes::_invokeinterface) {
2434    address bcp = bcs->bcp();
2435    // 4905268: count operand in invokeinterface should be nargs+1, not nargs.
2436    // JSR202 spec: The count operand of an invokeinterface instruction is valid if it is
2437    // the difference between the size of the operand stack before and after the instruction
2438    // executes.
2439    if (*(bcp+3) != (nargs+1)) {
2440      verify_error(ErrorContext::bad_code(bci),
2441          "Inconsistent args count operand in invokeinterface");
2442      return;
2443    }
2444    if (*(bcp+4) != 0) {
2445      verify_error(ErrorContext::bad_code(bci),
2446          "Fourth operand byte of invokeinterface must be zero");
2447      return;
2448    }
2449  }
2450
2451  if (opcode == Bytecodes::_invokedynamic) {
2452    address bcp = bcs->bcp();
2453    if (*(bcp+3) != 0 || *(bcp+4) != 0) {
2454      verify_error(ErrorContext::bad_code(bci),
2455          "Third and fourth operand bytes of invokedynamic must be zero");
2456      return;
2457    }
2458  }
2459
2460  if (method_name->byte_at(0) == '<') {
2461    // Make sure <init> can only be invoked by invokespecial
2462    if (opcode != Bytecodes::_invokespecial ||
2463        method_name != vmSymbols::object_initializer_name()) {
2464      verify_error(ErrorContext::bad_code(bci),
2465          "Illegal call to internal method");
2466      return;
2467    }
2468  } else if (opcode == Bytecodes::_invokespecial
2469             && !is_same_or_direct_interface(current_class(), current_type(), ref_class_type)
2470             && !ref_class_type.equals(VerificationType::reference_type(
2471                  current_class()->super()->name()))) {
2472    bool subtype = false;
2473    bool have_imr_indirect = cp->tag_at(index).value() == JVM_CONSTANT_InterfaceMethodref;
2474    if (!current_class()->is_anonymous()) {
2475      subtype = ref_class_type.is_assignable_from(
2476                 current_type(), this, CHECK_VERIFY(this));
2477    } else {
2478      VerificationType host_klass_type =
2479                        VerificationType::reference_type(current_class()->host_klass()->name());
2480      subtype = ref_class_type.is_assignable_from(host_klass_type, this, CHECK_VERIFY(this));
2481
2482      // If invokespecial of IMR, need to recheck for same or
2483      // direct interface relative to the host class
2484      have_imr_indirect = (have_imr_indirect &&
2485                           !is_same_or_direct_interface(
2486                             InstanceKlass::cast(current_class()->host_klass()),
2487                             host_klass_type, ref_class_type));
2488    }
2489    if (!subtype) {
2490      verify_error(ErrorContext::bad_code(bci),
2491          "Bad invokespecial instruction: "
2492          "current class isn't assignable to reference class.");
2493       return;
2494    } else if (have_imr_indirect) {
2495      verify_error(ErrorContext::bad_code(bci),
2496          "Bad invokespecial instruction: "
2497          "interface method reference is in an indirect superinterface.");
2498      return;
2499    }
2500
2501  }
2502  // Match method descriptor with operand stack
2503  for (int i = nargs - 1; i >= 0; i--) {  // Run backwards
2504    current_frame->pop_stack(sig_types[i], CHECK_VERIFY(this));
2505  }
2506  // Check objectref on operand stack
2507  if (opcode != Bytecodes::_invokestatic &&
2508      opcode != Bytecodes::_invokedynamic) {
2509    if (method_name == vmSymbols::object_initializer_name()) {  // <init> method
2510      verify_invoke_init(bcs, index, ref_class_type, current_frame,
2511        code_length, this_uninit, cp, CHECK_VERIFY(this));
2512    } else {   // other methods
2513      // Ensures that target class is assignable to method class.
2514      if (opcode == Bytecodes::_invokespecial) {
2515        if (!current_class()->is_anonymous()) {
2516          current_frame->pop_stack(current_type(), CHECK_VERIFY(this));
2517        } else {
2518          // anonymous class invokespecial calls: check if the
2519          // objectref is a subtype of the host_klass of the current class
2520          // to allow an anonymous class to reference methods in the host_klass
2521          VerificationType top = current_frame->pop_stack(CHECK_VERIFY(this));
2522          VerificationType hosttype =
2523            VerificationType::reference_type(current_class()->host_klass()->name());
2524          bool subtype = hosttype.is_assignable_from(top, this, CHECK_VERIFY(this));
2525          if (!subtype) {
2526            verify_error( ErrorContext::bad_type(current_frame->offset(),
2527              current_frame->stack_top_ctx(),
2528              TypeOrigin::implicit(top)),
2529              "Bad type on operand stack");
2530            return;
2531          }
2532        }
2533      } else if (opcode == Bytecodes::_invokevirtual) {
2534        VerificationType stack_object_type =
2535          current_frame->pop_stack(ref_class_type, CHECK_VERIFY(this));
2536        if (current_type() != stack_object_type) {
2537          assert(cp->cache() == NULL, "not rewritten yet");
2538          Symbol* ref_class_name =
2539            cp->klass_name_at(cp->klass_ref_index_at(index));
2540          // See the comments in verify_field_instructions() for
2541          // the rationale behind this.
2542          if (name_in_supers(ref_class_name, current_class())) {
2543            Klass* ref_class = load_class(ref_class_name, CHECK);
2544            if (is_protected_access(
2545                  _klass, ref_class, method_name, method_sig, true)) {
2546              // It's protected access, check if stack object is
2547              // assignable to current class.
2548              bool is_assignable = current_type().is_assignable_from(
2549                stack_object_type, this, CHECK_VERIFY(this));
2550              if (!is_assignable) {
2551                if (ref_class_type.name() == vmSymbols::java_lang_Object()
2552                    && stack_object_type.is_array()
2553                    && method_name == vmSymbols::clone_name()) {
2554                  // Special case: arrays pretend to implement public Object
2555                  // clone().
2556                } else {
2557                  verify_error(ErrorContext::bad_type(bci,
2558                      current_frame->stack_top_ctx(),
2559                      TypeOrigin::implicit(current_type())),
2560                      "Bad access to protected data in invokevirtual");
2561                  return;
2562                }
2563              }
2564            }
2565          }
2566        }
2567      } else {
2568        assert(opcode == Bytecodes::_invokeinterface, "Unexpected opcode encountered");
2569        current_frame->pop_stack(ref_class_type, CHECK_VERIFY(this));
2570      }
2571    }
2572  }
2573  // Push the result type.
2574  if (sig_stream.type() != T_VOID) {
2575    if (method_name == vmSymbols::object_initializer_name()) {
2576      // <init> method must have a void return type
2577      /* Unreachable?  Class file parser verifies that methods with '<' have
2578       * void return */
2579      verify_error(ErrorContext::bad_code(bci),
2580          "Return type must be void in <init> method");
2581      return;
2582    }
2583    VerificationType return_type[2];
2584    int n = change_sig_to_verificationType(
2585      &sig_stream, return_type, CHECK_VERIFY(this));
2586    for (int i = 0; i < n; i++) {
2587      current_frame->push_stack(return_type[i], CHECK_VERIFY(this)); // push types backwards
2588    }
2589  }
2590}
2591
2592VerificationType ClassVerifier::get_newarray_type(
2593    u2 index, u2 bci, TRAPS) {
2594  const char* from_bt[] = {
2595    NULL, NULL, NULL, NULL, "[Z", "[C", "[F", "[D", "[B", "[S", "[I", "[J",
2596  };
2597  if (index < T_BOOLEAN || index > T_LONG) {
2598    verify_error(ErrorContext::bad_code(bci), "Illegal newarray instruction");
2599    return VerificationType::bogus_type();
2600  }
2601
2602  // from_bt[index] contains the array signature which has a length of 2
2603  Symbol* sig = create_temporary_symbol(
2604    from_bt[index], 2, CHECK_(VerificationType::bogus_type()));
2605  return VerificationType::reference_type(sig);
2606}
2607
2608void ClassVerifier::verify_anewarray(
2609    u2 bci, u2 index, constantPoolHandle cp,
2610    StackMapFrame* current_frame, TRAPS) {
2611  verify_cp_class_type(bci, index, cp, CHECK_VERIFY(this));
2612  current_frame->pop_stack(
2613    VerificationType::integer_type(), CHECK_VERIFY(this));
2614
2615  VerificationType component_type =
2616    cp_index_to_type(index, cp, CHECK_VERIFY(this));
2617  int length;
2618  char* arr_sig_str;
2619  if (component_type.is_array()) {     // it's an array
2620    const char* component_name = component_type.name()->as_utf8();
2621    // add one dimension to component
2622    length = (int)strlen(component_name) + 1;
2623    arr_sig_str = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, length);
2624    arr_sig_str[0] = '[';
2625    strncpy(&arr_sig_str[1], component_name, length - 1);
2626  } else {         // it's an object or interface
2627    const char* component_name = component_type.name()->as_utf8();
2628    // add one dimension to component with 'L' prepended and ';' postpended.
2629    length = (int)strlen(component_name) + 3;
2630    arr_sig_str = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, length);
2631    arr_sig_str[0] = '[';
2632    arr_sig_str[1] = 'L';
2633    strncpy(&arr_sig_str[2], component_name, length - 2);
2634    arr_sig_str[length - 1] = ';';
2635  }
2636  Symbol* arr_sig = create_temporary_symbol(
2637    arr_sig_str, length, CHECK_VERIFY(this));
2638  VerificationType new_array_type = VerificationType::reference_type(arr_sig);
2639  current_frame->push_stack(new_array_type, CHECK_VERIFY(this));
2640}
2641
2642void ClassVerifier::verify_iload(u2 index, StackMapFrame* current_frame, TRAPS) {
2643  current_frame->get_local(
2644    index, VerificationType::integer_type(), CHECK_VERIFY(this));
2645  current_frame->push_stack(
2646    VerificationType::integer_type(), CHECK_VERIFY(this));
2647}
2648
2649void ClassVerifier::verify_lload(u2 index, StackMapFrame* current_frame, TRAPS) {
2650  current_frame->get_local_2(
2651    index, VerificationType::long_type(),
2652    VerificationType::long2_type(), CHECK_VERIFY(this));
2653  current_frame->push_stack_2(
2654    VerificationType::long_type(),
2655    VerificationType::long2_type(), CHECK_VERIFY(this));
2656}
2657
2658void ClassVerifier::verify_fload(u2 index, StackMapFrame* current_frame, TRAPS) {
2659  current_frame->get_local(
2660    index, VerificationType::float_type(), CHECK_VERIFY(this));
2661  current_frame->push_stack(
2662    VerificationType::float_type(), CHECK_VERIFY(this));
2663}
2664
2665void ClassVerifier::verify_dload(u2 index, StackMapFrame* current_frame, TRAPS) {
2666  current_frame->get_local_2(
2667    index, VerificationType::double_type(),
2668    VerificationType::double2_type(), CHECK_VERIFY(this));
2669  current_frame->push_stack_2(
2670    VerificationType::double_type(),
2671    VerificationType::double2_type(), CHECK_VERIFY(this));
2672}
2673
2674void ClassVerifier::verify_aload(u2 index, StackMapFrame* current_frame, TRAPS) {
2675  VerificationType type = current_frame->get_local(
2676    index, VerificationType::reference_check(), CHECK_VERIFY(this));
2677  current_frame->push_stack(type, CHECK_VERIFY(this));
2678}
2679
2680void ClassVerifier::verify_istore(u2 index, StackMapFrame* current_frame, TRAPS) {
2681  current_frame->pop_stack(
2682    VerificationType::integer_type(), CHECK_VERIFY(this));
2683  current_frame->set_local(
2684    index, VerificationType::integer_type(), CHECK_VERIFY(this));
2685}
2686
2687void ClassVerifier::verify_lstore(u2 index, StackMapFrame* current_frame, TRAPS) {
2688  current_frame->pop_stack_2(
2689    VerificationType::long2_type(),
2690    VerificationType::long_type(), CHECK_VERIFY(this));
2691  current_frame->set_local_2(
2692    index, VerificationType::long_type(),
2693    VerificationType::long2_type(), CHECK_VERIFY(this));
2694}
2695
2696void ClassVerifier::verify_fstore(u2 index, StackMapFrame* current_frame, TRAPS) {
2697  current_frame->pop_stack(VerificationType::float_type(), CHECK_VERIFY(this));
2698  current_frame->set_local(
2699    index, VerificationType::float_type(), CHECK_VERIFY(this));
2700}
2701
2702void ClassVerifier::verify_dstore(u2 index, StackMapFrame* current_frame, TRAPS) {
2703  current_frame->pop_stack_2(
2704    VerificationType::double2_type(),
2705    VerificationType::double_type(), CHECK_VERIFY(this));
2706  current_frame->set_local_2(
2707    index, VerificationType::double_type(),
2708    VerificationType::double2_type(), CHECK_VERIFY(this));
2709}
2710
2711void ClassVerifier::verify_astore(u2 index, StackMapFrame* current_frame, TRAPS) {
2712  VerificationType type = current_frame->pop_stack(
2713    VerificationType::reference_check(), CHECK_VERIFY(this));
2714  current_frame->set_local(index, type, CHECK_VERIFY(this));
2715}
2716
2717void ClassVerifier::verify_iinc(u2 index, StackMapFrame* current_frame, TRAPS) {
2718  VerificationType type = current_frame->get_local(
2719    index, VerificationType::integer_type(), CHECK_VERIFY(this));
2720  current_frame->set_local(index, type, CHECK_VERIFY(this));
2721}
2722
2723void ClassVerifier::verify_return_value(
2724    VerificationType return_type, VerificationType type, u2 bci,
2725    StackMapFrame* current_frame, TRAPS) {
2726  if (return_type == VerificationType::bogus_type()) {
2727    verify_error(ErrorContext::bad_type(bci,
2728        current_frame->stack_top_ctx(), TypeOrigin::signature(return_type)),
2729        "Method expects a return value");
2730    return;
2731  }
2732  bool match = return_type.is_assignable_from(type, this, CHECK_VERIFY(this));
2733  if (!match) {
2734    verify_error(ErrorContext::bad_type(bci,
2735        current_frame->stack_top_ctx(), TypeOrigin::signature(return_type)),
2736        "Bad return type");
2737    return;
2738  }
2739}
2740
2741// The verifier creates symbols which are substrings of Symbols.
2742// These are stored in the verifier until the end of verification so that
2743// they can be reference counted.
2744Symbol* ClassVerifier::create_temporary_symbol(const Symbol *s, int begin,
2745                                               int end, TRAPS) {
2746  Symbol* sym = SymbolTable::new_symbol(s, begin, end, CHECK_NULL);
2747  _symbols->push(sym);
2748  return sym;
2749}
2750
2751Symbol* ClassVerifier::create_temporary_symbol(const char *s, int length, TRAPS) {
2752  Symbol* sym = SymbolTable::new_symbol(s, length, CHECK_NULL);
2753  _symbols->push(sym);
2754  return sym;
2755}
2756