1 /*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "method_verifier-inl.h"
18
19 #include <ostream>
20
21 #include "android-base/stringprintf.h"
22
23 #include "art_field-inl.h"
24 #include "art_method-inl.h"
25 #include "base/aborting.h"
26 #include "base/leb128.h"
27 #include "base/indenter.h"
28 #include "base/logging.h" // For VLOG.
29 #include "base/mutex-inl.h"
30 #include "base/pointer_size.h"
31 #include "base/sdk_version.h"
32 #include "base/stl_util.h"
33 #include "base/systrace.h"
34 #include "base/time_utils.h"
35 #include "base/utils.h"
36 #include "class_linker.h"
37 #include "class_root-inl.h"
38 #include "dex/class_accessor-inl.h"
39 #include "dex/descriptors_names.h"
40 #include "dex/dex_file-inl.h"
41 #include "dex/dex_file_exception_helpers.h"
42 #include "dex/dex_instruction-inl.h"
43 #include "dex/dex_instruction_list.h"
44 #include "dex/dex_instruction_utils.h"
45 #include "experimental_flags.h"
46 #include "gc/accounting/card_table-inl.h"
47 #include "handle_scope-inl.h"
48 #include "intern_table.h"
49 #include "mirror/class-inl.h"
50 #include "mirror/class.h"
51 #include "mirror/class_loader.h"
52 #include "mirror/dex_cache-inl.h"
53 #include "mirror/method_handle_impl.h"
54 #include "mirror/method_type.h"
55 #include "mirror/object-inl.h"
56 #include "mirror/object_array-inl.h"
57 #include "mirror/var_handle.h"
58 #include "obj_ptr-inl.h"
59 #include "reg_type-inl.h"
60 #include "reg_type_cache.h"
61 #include "register_line-inl.h"
62 #include "runtime.h"
63 #include "scoped_newline.h"
64 #include "scoped_thread_state_change-inl.h"
65 #include "stack.h"
66 #include "vdex_file.h"
67 #include "verifier/method_verifier.h"
68 #include "verifier_compiler_binding.h"
69 #include "verifier_deps.h"
70
71 namespace art HIDDEN {
72 namespace verifier {
73
74 using android::base::StringPrintf;
75
76 static constexpr bool kTimeVerifyMethod = !kIsDebugBuild;
77
PcToRegisterLineTable(ArenaAllocator & allocator)78 PcToRegisterLineTable::PcToRegisterLineTable(ArenaAllocator& allocator)
79 : register_lines_(allocator.Adapter(kArenaAllocVerifier)) {}
80
Init(InstructionFlags * flags,uint32_t insns_size,uint16_t registers_size,ArenaAllocator & allocator,uint32_t interesting_dex_pc)81 void PcToRegisterLineTable::Init(InstructionFlags* flags,
82 uint32_t insns_size,
83 uint16_t registers_size,
84 ArenaAllocator& allocator,
85 uint32_t interesting_dex_pc) {
86 DCHECK_GT(insns_size, 0U);
87 register_lines_.resize(insns_size);
88 for (uint32_t i = 0; i < insns_size; i++) {
89 if ((i == interesting_dex_pc) || flags[i].IsBranchTarget()) {
90 register_lines_[i].reset(RegisterLine::Create(registers_size, allocator));
91 }
92 }
93 }
94
~PcToRegisterLineTable()95 PcToRegisterLineTable::~PcToRegisterLineTable() {}
96
97 namespace impl {
98 namespace {
99
100 enum class CheckAccess {
101 kNo,
102 kOnResolvedClass,
103 kYes,
104 };
105
106 enum class FieldAccessType {
107 kAccGet,
108 kAccPut
109 };
110
111 // Instruction types that are not marked as throwing (because they normally would not), but for
112 // historical reasons may do so. These instructions cannot be marked kThrow as that would introduce
113 // a general flow that is unwanted.
114 //
115 // Note: Not implemented as Instruction::Flags value as that set is full and we'd need to increase
116 // the struct size (making it a non-power-of-two) for a single element.
117 //
118 // Note: This should eventually be removed.
IsCompatThrow(Instruction::Code opcode)119 constexpr bool IsCompatThrow(Instruction::Code opcode) {
120 return opcode == Instruction::Code::RETURN_OBJECT || opcode == Instruction::Code::MOVE_EXCEPTION;
121 }
122
123 class MethodVerifierImpl : public ::art::verifier::MethodVerifier {
124 public:
IsInstanceConstructor() const125 bool IsInstanceConstructor() const {
126 return IsConstructor() && !IsStatic();
127 }
128
129 protected:
MethodVerifierImpl(Thread * self,ArenaPool * arena_pool,RegTypeCache * reg_types,VerifierDeps * verifier_deps,const dex::CodeItem * code_item,uint32_t method_idx,bool aot_mode,Handle<mirror::DexCache> dex_cache,const dex::ClassDef & class_def,uint32_t access_flags,bool verify_to_dump,uint32_t api_level)130 MethodVerifierImpl(Thread* self,
131 ArenaPool* arena_pool,
132 RegTypeCache* reg_types,
133 VerifierDeps* verifier_deps,
134 const dex::CodeItem* code_item,
135 uint32_t method_idx,
136 bool aot_mode,
137 Handle<mirror::DexCache> dex_cache,
138 const dex::ClassDef& class_def,
139 uint32_t access_flags,
140 bool verify_to_dump,
141 uint32_t api_level) REQUIRES_SHARED(Locks::mutator_lock_)
142 : ::art::verifier::MethodVerifier(self,
143 arena_pool,
144 reg_types,
145 verifier_deps,
146 class_def,
147 code_item,
148 method_idx,
149 aot_mode),
150 method_access_flags_(access_flags),
151 return_type_(nullptr),
152 dex_cache_(dex_cache),
153 class_loader_(reg_types->GetClassLoader()),
154 declaring_class_(nullptr),
155 interesting_dex_pc_(-1),
156 monitor_enter_dex_pcs_(nullptr),
157 verify_to_dump_(verify_to_dump),
158 allow_thread_suspension_(reg_types->CanSuspend()),
159 is_constructor_(false),
160 api_level_(api_level == 0 ? std::numeric_limits<uint32_t>::max() : api_level) {
161 DCHECK_EQ(dex_cache->GetDexFile(), reg_types->GetDexFile())
162 << dex_cache->GetDexFile()->GetLocation() << " / "
163 << reg_types->GetDexFile()->GetLocation();
164 }
165
FinalAbstractClassError(ObjPtr<mirror::Class> klass)166 void FinalAbstractClassError(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
167 // Note: We reuse NO_CLASS as the instruction we're checking shall throw an exception at
168 // runtime if executed. A final abstract class shall fail verification, so no instances can
169 // be created and therefore instance field or method access can be reached only for a null
170 // reference and throw NPE. All other instructions where we check for final abstract class
171 // shall throw `VerifyError`. (But we can also hit OOME/SOE while creating the exception.)
172 std::string temp;
173 const char* descriptor = klass->GetDescriptor(&temp);
174 Fail(VerifyError::VERIFY_ERROR_NO_CLASS)
175 << "Final abstract class used in a context that requires a verified class: " << descriptor;
176 }
177
CheckForFinalAbstractClass(ObjPtr<mirror::Class> klass)178 void CheckForFinalAbstractClass(ObjPtr<mirror::Class> klass)
179 REQUIRES_SHARED(Locks::mutator_lock_) {
180 if (UNLIKELY(klass->IsFinal() &&
181 klass->IsAbstract() &&
182 !klass->IsInterface() &&
183 !klass->IsPrimitive() &&
184 !klass->IsArrayClass())) {
185 FinalAbstractClassError(klass);
186 }
187 }
188
189 // Is the method being verified a constructor? See the comment on the field.
IsConstructor() const190 bool IsConstructor() const {
191 return is_constructor_;
192 }
193
194 // Is the method verified static?
IsStatic() const195 bool IsStatic() const {
196 return (method_access_flags_ & kAccStatic) != 0;
197 }
198
199 // Adds the given string to the beginning of the last failure message.
PrependToLastFailMessage(std::string prepend)200 void PrependToLastFailMessage(std::string prepend) {
201 MessageOStream* last_fail_message = &LastFailureMessageStream();
202 prepend += last_fail_message->view();
203 last_fail_message->str(std::move(prepend));
204 }
205
206 // Return the last failure message stream for appending.
LastFailureMessageStream()207 MessageOStream& LastFailureMessageStream() {
208 DCHECK(!failures_.empty());
209 return failures_.back().message;
210 }
211
212 /*
213 * Compute the width of the instruction at each address in the instruction stream, and store it in
214 * insn_flags_. Addresses that are in the middle of an instruction, or that are part of switch
215 * table data, are not touched (so the caller should probably initialize "insn_flags" to zero).
216 *
217 * The "new_instance_count_" and "monitor_enter_count_" fields in vdata are also set.
218 *
219 * Performs some static checks, notably:
220 * - opcode of first instruction begins at index 0
221 * - only documented instructions may appear
222 * - each instruction follows the last
223 * - last byte of last instruction is at (code_length-1)
224 *
225 * Logs an error and returns "false" on failure.
226 */
227 bool ComputeWidthsAndCountOps();
228
229 /*
230 * Set the "in try" flags for all instructions protected by "try" statements. Also sets the
231 * "branch target" flags for exception handlers.
232 *
233 * Call this after widths have been set in "insn_flags".
234 *
235 * Returns "false" if something in the exception table looks fishy, but we're expecting the
236 * exception table to be valid.
237 */
238 bool ScanTryCatchBlocks() REQUIRES_SHARED(Locks::mutator_lock_);
239
240 /*
241 * Perform static verification on all instructions in a method.
242 *
243 * Walks through instructions in a method calling VerifyInstruction on each.
244 */
245 bool VerifyInstructions();
246
247 /*
248 * Perform static verification on an instruction.
249 *
250 * As a side effect, this sets the "branch target" flags in InsnFlags.
251 *
252 * "(CF)" items are handled during code-flow analysis.
253 *
254 * v3 4.10.1
255 * - target of each jump and branch instruction must be valid
256 * - targets of switch statements must be valid
257 * - operands referencing constant pool entries must be valid
258 * - (CF) operands of getfield, putfield, getstatic, putstatic must be valid
259 * - (CF) operands of method invocation instructions must be valid
260 * - (CF) only invoke-direct can call a method starting with '<'
261 * - (CF) <clinit> must never be called explicitly
262 * - operands of instanceof, checkcast, new (and variants) must be valid
263 * - new-array[-type] limited to 255 dimensions
264 * - can't use "new" on an array class
265 * - (?) limit dimensions in multi-array creation
266 * - local variable load/store register values must be in valid range
267 *
268 * v3 4.11.1.2
269 * - branches must be within the bounds of the code array
270 * - targets of all control-flow instructions are the start of an instruction
271 * - register accesses fall within range of allocated registers
272 * - (N/A) access to constant pool must be of appropriate type
273 * - code does not end in the middle of an instruction
274 * - execution cannot fall off the end of the code
275 * - (earlier) for each exception handler, the "try" area must begin and
276 * end at the start of an instruction (end can be at the end of the code)
277 * - (earlier) for each exception handler, the handler must start at a valid
278 * instruction
279 */
280 template <Instruction::Code kDispatchOpcode>
281 ALWAYS_INLINE bool VerifyInstruction(uint32_t dex_pc,
282 uint32_t end_dex_pc,
283 const Instruction* inst,
284 uint16_t inst_data);
285
286 /* Ensure that the register index is valid for this code item. */
CheckRegisterIndex(uint32_t idx)287 bool CheckRegisterIndex(uint32_t idx) {
288 if (UNLIKELY(idx >= code_item_accessor_.RegistersSize())) {
289 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register index out of range (" << idx << " >= "
290 << code_item_accessor_.RegistersSize() << ")";
291 return false;
292 }
293 return true;
294 }
295
296 /* Ensure that the wide register index is valid for this code item. */
CheckWideRegisterIndex(uint32_t idx)297 bool CheckWideRegisterIndex(uint32_t idx) {
298 if (UNLIKELY(idx + 1 >= code_item_accessor_.RegistersSize())) {
299 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "wide register index out of range (" << idx
300 << "+1 >= " << code_item_accessor_.RegistersSize() << ")";
301 return false;
302 }
303 return true;
304 }
305
306 // Perform static checks on an instruction referencing a CallSite. All we do here is ensure that
307 // the call site index is in the valid range.
CheckCallSiteIndex(uint32_t idx)308 bool CheckCallSiteIndex(uint32_t idx) {
309 uint32_t limit = dex_file_->NumCallSiteIds();
310 if (UNLIKELY(idx >= limit)) {
311 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad call site index " << idx << " (max "
312 << limit << ")";
313 return false;
314 }
315 return true;
316 }
317
318 // Perform static checks on a field Get or set instruction. We ensure that the field index
319 // is in the valid range and we check that the field descriptor matches the instruction.
CheckFieldIndex(const Instruction * inst,uint16_t inst_data,uint32_t field_idx)320 ALWAYS_INLINE bool CheckFieldIndex(const Instruction* inst,
321 uint16_t inst_data,
322 uint32_t field_idx) {
323 if (UNLIKELY(field_idx >= dex_file_->NumFieldIds())) {
324 FailBadFieldIndex(field_idx);
325 return false;
326 }
327
328 // Prepare a table with permitted descriptors, evaluated at compile time.
329 static constexpr uint32_t kVerifyFieldIndexFlags =
330 Instruction::kVerifyRegBField | Instruction::kVerifyRegCField;
331 static constexpr uint32_t kMinFieldAccessOpcode = []() constexpr {
332 for (uint32_t opcode = 0u; opcode != 256u; ++opcode) {
333 uint32_t verify_flags = Instruction::VerifyFlagsOf(enum_cast<Instruction::Code>(opcode));
334 if ((verify_flags & kVerifyFieldIndexFlags) != 0u) {
335 return opcode;
336 }
337 }
338 LOG(FATAL) << "Compile time error if we reach this.";
339 return 0u;
340 }();
341 static constexpr uint32_t kMaxFieldAccessOpcode = []() constexpr {
342 for (uint32_t opcode = 256u; opcode != 0u; ) {
343 --opcode;
344 uint32_t verify_flags = Instruction::VerifyFlagsOf(enum_cast<Instruction::Code>(opcode));
345 if ((verify_flags & kVerifyFieldIndexFlags) != 0u) {
346 return opcode;
347 }
348 }
349 LOG(FATAL) << "Compile time error if we reach this.";
350 return 0u;
351 }();
352 static constexpr uint32_t kArraySize = kMaxFieldAccessOpcode + 1u - kMinFieldAccessOpcode;
353 using PermittedDescriptorArray = std::array<std::pair<char, char>, kArraySize>;
354 static constexpr PermittedDescriptorArray kPermittedDescriptors = []() constexpr {
355 PermittedDescriptorArray result;
356 for (uint32_t index = 0u; index != kArraySize; ++index) {
357 Instruction::Code opcode = enum_cast<Instruction::Code>(index + kMinFieldAccessOpcode);
358 DexMemAccessType access_type;
359 if (IsInstructionIGet(opcode) || IsInstructionIPut(opcode)) {
360 access_type = IGetOrIPutMemAccessType(opcode);
361 } else {
362 // `iget*`, `iput*`, `sget*` and `sput*` instructions form a contiguous range.
363 CHECK(IsInstructionSGet(opcode) || IsInstructionSPut(opcode));
364 access_type = SGetOrSPutMemAccessType(opcode);
365 }
366 switch (access_type) {
367 case DexMemAccessType::kDexMemAccessWord:
368 result[index] = { 'I', 'F' };
369 break;
370 case DexMemAccessType::kDexMemAccessWide:
371 result[index] = { 'J', 'D' };
372 break;
373 case DexMemAccessType::kDexMemAccessObject:
374 result[index] = { 'L', '[' };
375 break;
376 case DexMemAccessType::kDexMemAccessBoolean:
377 result[index] = { 'Z', 'Z' }; // Only one character is permitted.
378 break;
379 case DexMemAccessType::kDexMemAccessByte:
380 result[index] = { 'B', 'B' }; // Only one character is permitted.
381 break;
382 case DexMemAccessType::kDexMemAccessChar:
383 result[index] = { 'C', 'C' }; // Only one character is permitted.
384 break;
385 case DexMemAccessType::kDexMemAccessShort:
386 result[index] = { 'S', 'S' }; // Only one character is permitted.
387 break;
388 default:
389 LOG(FATAL) << "Compile time error if we reach this.";
390 break;
391 }
392 }
393 return result;
394 }();
395
396 // Check the first character of the field type descriptor.
397 Instruction::Code opcode = inst->Opcode(inst_data);
398 DCHECK_GE(opcode, kMinFieldAccessOpcode);
399 DCHECK_LE(opcode, kMaxFieldAccessOpcode);
400 std::pair<char, char> permitted = kPermittedDescriptors[opcode - kMinFieldAccessOpcode];
401 const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_idx);
402 if (UNLIKELY(descriptor[0] != permitted.first && descriptor[0] != permitted.second)) {
403 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
404 << "expected field " << dex_file_->PrettyField(field_idx)
405 << " to have type descritor starting with '" << permitted.first
406 << (permitted.second != permitted.first ? std::string("' or '") + permitted.second : "")
407 << "' but found '" << descriptor[0] << "' in " << opcode;
408 return false;
409 }
410 return true;
411 }
412
413 // Perform static checks on a method invocation instruction. All we do here is ensure that the
414 // method index is in the valid range.
CheckMethodIndex(uint32_t method_idx)415 ALWAYS_INLINE bool CheckMethodIndex(uint32_t method_idx) {
416 if (UNLIKELY(method_idx >= dex_file_->NumMethodIds())) {
417 FailBadMethodIndex(method_idx);
418 return false;
419 }
420 return true;
421 }
422
423 // Perform static checks on an instruction referencing a constant method handle. All we do here
424 // is ensure that the method index is in the valid range.
CheckMethodHandleIndex(uint32_t idx)425 bool CheckMethodHandleIndex(uint32_t idx) {
426 if (UNLIKELY(idx >= dex_file_->NumMethodHandles())) {
427 FailBadMethodHandleIndex(idx);
428 return false;
429 }
430 return true;
431 }
432
433 // Perform static checks on a prototype indexing instruction. All we do here is ensure that the
434 // prototype index is in the valid range.
CheckPrototypeIndex(uint32_t idx)435 bool CheckPrototypeIndex(uint32_t idx) {
436 if (UNLIKELY(idx >= dex_file_->NumProtoIds())) {
437 FailBadPrototypeIndex(idx);
438 return false;
439 }
440 return true;
441 }
442
443 /* Ensure that the string index is in the valid range. */
CheckStringIndex(uint32_t idx)444 bool CheckStringIndex(uint32_t idx) {
445 if (UNLIKELY(idx >= dex_file_->NumStringIds())) {
446 FailBadStringIndex(idx);
447 return false;
448 }
449 return true;
450 }
451
452 // Perform static checks on an instruction that takes a class constant. Ensure that the class
453 // index is in the valid range.
CheckTypeIndex(dex::TypeIndex idx)454 bool CheckTypeIndex(dex::TypeIndex idx) {
455 if (UNLIKELY(idx.index_ >= dex_file_->GetHeader().type_ids_size_)) {
456 FailBadTypeIndex(idx);
457 return false;
458 }
459 return true;
460 }
461
462 // Perform static checks on a `new-instance` instruction. Specifically, make sure the class
463 // reference isn't for an array class.
464 bool CheckNewInstance(dex::TypeIndex idx);
465
466 // Perform static checks on a `*new-array*` instruction. Specifically, make sure it
467 // references an array class with the number of dimensions not exceeding 255.
468 // For `filled-new-array*`, check for a valid component type; `I` is accepted, `J` and `D`
469 // are rejected in line with the specification and other primitive component types are marked
470 // for interpreting (throws `InternalError` in interpreter and the compiler cannot handle them).
471 template <bool kFilled>
472 bool CheckNewArray(dex::TypeIndex idx);
473
474 // Determine if the relative `offset` targets a valid dex pc.
475 // The `offset` should be inside the range `[-dex_pc, end_dex_pc - dex_pc)`.
476 ALWAYS_INLINE
IsOffsetInRange(uint32_t dex_pc,uint32_t end_dex_pc,int32_t offset)477 static bool IsOffsetInRange(uint32_t dex_pc, uint32_t end_dex_pc, int32_t offset) {
478 DCHECK_LT(dex_pc, end_dex_pc);
479 if (offset >= 0) {
480 return static_cast<uint32_t>(offset) < end_dex_pc - dex_pc;
481 } else {
482 // Use well-defined unsigned arithmetic for the lower bound check.
483 return dex_pc >= -static_cast<uint32_t>(offset);
484 }
485 }
486
487 // Verify an array data table.
488 bool CheckArrayData(uint32_t dex_pc, uint32_t end_dex_pc, const Instruction* inst);
489
490 // Verify that the target of a branch instruction is valid. We don't expect code to jump directly
491 // into an exception handler, but it's valid to do so as long as the target isn't a
492 // "move-exception" instruction. We verify that in a later stage.
493 // The dex format forbids instructions other than `goto/32` from branching to themselves.
494 // Updates "insn_flags_", setting the "branch target" flag.
495 template <Instruction::Format kFormat>
496 ALWAYS_INLINE
497 bool CheckAndMarkBranchTarget(uint32_t dex_pc,
498 uint32_t end_dex_pc,
499 const Instruction* inst,
500 uint16_t inst_data);
501
502 // Verify a switch table.
503 // Updates "insn_flags_", setting the "branch target" flag.
504 ALWAYS_INLINE
505 bool CheckAndMarkSwitchTargets(uint32_t dex_pc,
506 uint32_t end_dex_pc,
507 const Instruction* inst,
508 uint16_t inst_data);
509
510 // Check the register indices used in a "vararg" instruction, such as invoke-virtual or
511 // filled-new-array.
512 // - inst is the instruction from which we retrieve the arguments
513 // - vA holds the argument count (0-5)
514 // There are some tests we don't do here, e.g. we don't try to verify that invoking a method that
515 // takes a double is done with consecutive registers. This requires parsing the target method
516 // signature, which we will be doing later on during the code flow analysis.
CheckVarArgRegs(const Instruction * inst,uint32_t vA)517 bool CheckVarArgRegs(const Instruction* inst, uint32_t vA) {
518 uint16_t registers_size = code_item_accessor_.RegistersSize();
519 // All args are 4-bit and therefore under 16. We do not need to check args for
520 // `registers_size >= 16u` but let's check them anyway in debug builds.
521 if (registers_size < 16u || kIsDebugBuild) {
522 uint32_t args[Instruction::kMaxVarArgRegs];
523 inst->GetVarArgs(args);
524 for (uint32_t idx = 0; idx < vA; idx++) {
525 DCHECK_LT(args[idx], 16u);
526 if (UNLIKELY(args[idx] >= registers_size)) {
527 DCHECK_LT(registers_size, 16u);
528 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
529 << "invalid reg index (" << args[idx]
530 << ") in non-range invoke (>= " << registers_size << ")";
531 return false;
532 }
533 }
534 }
535 return true;
536 }
537
538 // Check the register indices used in a "vararg/range" instruction, such as invoke-virtual/range
539 // or filled-new-array/range.
540 // - vA holds word count, vC holds index of first reg.
CheckVarArgRangeRegs(uint32_t vA,uint32_t vC)541 bool CheckVarArgRangeRegs(uint32_t vA, uint32_t vC) {
542 uint16_t registers_size = code_item_accessor_.RegistersSize();
543 // vA/vC are unsigned 8-bit/16-bit quantities for /range instructions, so there's no risk of
544 // integer overflow when adding them here.
545 if (UNLIKELY(vA + vC > registers_size)) {
546 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid reg index " << vA << "+" << vC
547 << " in range invoke (> " << registers_size << ")";
548 return false;
549 }
550 return true;
551 }
552
553 // Checks the method matches the expectations required to be signature polymorphic.
554 bool CheckSignaturePolymorphicMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
555
556 // Checks the invoked receiver matches the expectations for signature polymorphic methods.
557 bool CheckSignaturePolymorphicReceiver(const Instruction* inst) REQUIRES_SHARED(Locks::mutator_lock_);
558
559 // Extract the relative offset from a branch instruction.
560 // Returns "false" on failure (e.g. this isn't a branch instruction).
561 bool GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional,
562 bool* selfOkay);
563
564 // Set the register types for the first instruction in the method based on the method signature.
565 // This has the side-effect of validating the signature.
566 bool SetTypesFromSignature() REQUIRES_SHARED(Locks::mutator_lock_);
567
568 // Perform verification of a `filled-new-array/-range` instruction.
569 bool VerifyFilledNewArray(const Instruction* inst, bool is_range)
570 REQUIRES_SHARED(Locks::mutator_lock_);
571
572 // Helper to perform verification on puts of primitive type.
573 void VerifyPrimitivePut(const RegType& target_type, uint32_t vregA)
574 REQUIRES_SHARED(Locks::mutator_lock_);
575
576 // Perform verification of an aget instruction. The destination register's type will be set to
577 // be that of component type of the array unless the array type is unknown, in which case a
578 // bottom type inferred from the type of instruction is used. is_primitive is false for an
579 // aget-object.
580 void VerifyAGet(const Instruction* inst, const RegType& insn_type,
581 bool is_primitive) REQUIRES_SHARED(Locks::mutator_lock_);
582
583 // Perform verification of an aput instruction.
584 void VerifyAPut(const Instruction* inst, const RegType& insn_type,
585 bool is_primitive) REQUIRES_SHARED(Locks::mutator_lock_);
586
587 // Lookup instance field and fail for resolution violations
588 ArtField* GetInstanceField(uint32_t vregB, uint32_t field_idx, bool is_put)
589 REQUIRES_SHARED(Locks::mutator_lock_);
590
591 // Lookup static field and fail for resolution violations
592 ArtField* GetStaticField(uint32_t field_idx, bool is_put) REQUIRES_SHARED(Locks::mutator_lock_);
593
594 // Common checks for `GetInstanceField()` and `GetStaticField()`.
595 ArtField* GetISFieldCommon(ArtField* field, bool is_put) REQUIRES_SHARED(Locks::mutator_lock_);
596
597 // Perform verification of an iget/sget/iput/sput instruction.
598 template <FieldAccessType kAccType>
599 void VerifyISFieldAccess(const Instruction* inst, bool is_primitive, bool is_static)
600 REQUIRES_SHARED(Locks::mutator_lock_);
601
602 // Resolves a class based on an index and, if C is kYes, performs access checks to ensure
603 // the referrer can access the resolved class.
604 template <CheckAccess C>
605 const RegType& ResolveClass(dex::TypeIndex class_idx)
606 REQUIRES_SHARED(Locks::mutator_lock_);
607
608 /*
609 * Resolves a method based on an index and performs access checks to ensure
610 * the referrer can access the resolved method.
611 * Does not throw exceptions.
612 */
613 ArtMethod* ResolveMethodAndCheckAccess(uint32_t method_idx, MethodType method_type)
614 REQUIRES_SHARED(Locks::mutator_lock_);
615
616 /*
617 * Verify the arguments to a method. We're executing in "method", making
618 * a call to the method reference in vB.
619 *
620 * If this is a "direct" invoke, we allow calls to <init>. For calls to
621 * <init>, the first argument may be an uninitialized reference. Otherwise,
622 * calls to anything starting with '<' will be rejected, as will any
623 * uninitialized reference arguments.
624 *
625 * For non-static method calls, this will verify that the method call is
626 * appropriate for the "this" argument.
627 *
628 * The method reference is in vBBBB. The "is_range" parameter determines
629 * whether we use 0-4 "args" values or a range of registers defined by
630 * vAA and vCCCC.
631 *
632 * Widening conversions on integers and references are allowed, but
633 * narrowing conversions are not.
634 *
635 * Returns the resolved method on success, null on failure (with *failure
636 * set appropriately).
637 */
638 ArtMethod* VerifyInvocationArgs(const Instruction* inst, MethodType method_type, bool is_range)
639 REQUIRES_SHARED(Locks::mutator_lock_);
640
641 // Similar checks to the above, but on the proto. Will be used when the method cannot be
642 // resolved.
643 void VerifyInvocationArgsUnresolvedMethod(const Instruction* inst, MethodType method_type,
644 bool is_range)
645 REQUIRES_SHARED(Locks::mutator_lock_);
646
647 template <class T>
648 ArtMethod* VerifyInvocationArgsFromIterator(T* it, const Instruction* inst,
649 MethodType method_type, bool is_range,
650 ArtMethod* res_method)
651 REQUIRES_SHARED(Locks::mutator_lock_);
652
653 /*
654 * Verify the arguments present for a call site. Returns "true" if all is well, "false" otherwise.
655 */
656 bool CheckCallSite(uint32_t call_site_idx);
657
658 // Return the register type for the method.
659 const RegType& GetMethodReturnType() REQUIRES_SHARED(Locks::mutator_lock_);
660
661 // Get a type representing the declaring class of the method.
GetDeclaringClass()662 const RegType& GetDeclaringClass() REQUIRES_SHARED(Locks::mutator_lock_) {
663 if (declaring_class_ == nullptr) {
664 const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
665 declaring_class_ = ®_types_.FromTypeIndex(method_id.class_idx_);
666 }
667 return *declaring_class_;
668 }
669
GetRegTypeClass(const RegType & reg_type)670 ObjPtr<mirror::Class> GetRegTypeClass(const RegType& reg_type)
671 REQUIRES_SHARED(Locks::mutator_lock_) {
672 DCHECK(reg_type.IsJavaLangObject() || reg_type.IsReference()) << reg_type;
673 return reg_type.IsJavaLangObject() ? GetClassRoot<mirror::Object>(GetClassLinker())
674 : reg_type.GetClass();
675 }
676
CanAccess(const RegType & other)677 bool CanAccess(const RegType& other) REQUIRES_SHARED(Locks::mutator_lock_) {
678 DCHECK(other.IsJavaLangObject() || other.IsReference() || other.IsUnresolvedReference());
679 const RegType& declaring_class = GetDeclaringClass();
680 if (declaring_class.Equals(other)) {
681 return true; // Trivial accessibility.
682 } else if (other.IsUnresolvedReference()) {
683 return false; // More complicated test not possible on unresolved types, be conservative.
684 } else if (declaring_class.IsUnresolvedReference()) {
685 // Be conservative, only allow if `other` is public.
686 return other.IsJavaLangObject() || (other.IsReference() && other.GetClass()->IsPublic());
687 } else {
688 return GetRegTypeClass(declaring_class)->CanAccess(GetRegTypeClass(other));
689 }
690 }
691
CanAccessMember(ObjPtr<mirror::Class> klass,uint32_t access_flags)692 bool CanAccessMember(ObjPtr<mirror::Class> klass, uint32_t access_flags)
693 REQUIRES_SHARED(Locks::mutator_lock_) {
694 const RegType& declaring_class = GetDeclaringClass();
695 if (declaring_class.IsUnresolvedReference()) {
696 return false; // More complicated test not possible on unresolved types, be conservative.
697 } else {
698 return GetRegTypeClass(declaring_class)->CanAccessMember(klass, access_flags);
699 }
700 }
701
IsMoveResult(Instruction::Code opcode)702 ALWAYS_INLINE static bool IsMoveResult(Instruction::Code opcode) {
703 static_assert(Instruction::MOVE_RESULT + 1 == Instruction::MOVE_RESULT_WIDE);
704 static_assert(Instruction::MOVE_RESULT_WIDE + 1 == Instruction::MOVE_RESULT_OBJECT);
705 return Instruction::MOVE_RESULT <= opcode && opcode <= Instruction::MOVE_RESULT_OBJECT;
706 }
707
IsMoveResultOrMoveException(Instruction::Code opcode)708 ALWAYS_INLINE static bool IsMoveResultOrMoveException(Instruction::Code opcode) {
709 static_assert(Instruction::MOVE_RESULT + 1 == Instruction::MOVE_RESULT_WIDE);
710 static_assert(Instruction::MOVE_RESULT_WIDE + 1 == Instruction::MOVE_RESULT_OBJECT);
711 static_assert(Instruction::MOVE_RESULT_OBJECT + 1 == Instruction::MOVE_EXCEPTION);
712 return Instruction::MOVE_RESULT <= opcode && opcode <= Instruction::MOVE_EXCEPTION;
713 }
714
FailInvalidArgCount(const Instruction * inst,uint32_t arg_count)715 NO_INLINE void FailInvalidArgCount(const Instruction* inst, uint32_t arg_count) {
716 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
717 << "invalid arg count (" << arg_count << ") in " << inst->Name();
718 }
719
FailUnexpectedOpcode(const Instruction * inst)720 NO_INLINE void FailUnexpectedOpcode(const Instruction* inst) {
721 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected opcode " << inst->Name();
722 }
723
FailBadFieldIndex(uint32_t field_idx)724 NO_INLINE void FailBadFieldIndex(uint32_t field_idx) {
725 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
726 << "bad field index " << field_idx << " (max " << dex_file_->NumFieldIds() << ")";
727 }
728
FailBadMethodIndex(uint32_t method_idx)729 NO_INLINE void FailBadMethodIndex(uint32_t method_idx) {
730 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
731 << "bad method index " << method_idx << " (max " << dex_file_->NumMethodIds() << ")";
732 }
733
FailBadMethodHandleIndex(uint32_t idx)734 NO_INLINE void FailBadMethodHandleIndex(uint32_t idx) {
735 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
736 << "bad method handle index " << idx << " (max " << dex_file_->NumMethodHandles() << ")";
737 }
738
FailBadPrototypeIndex(uint32_t idx)739 NO_INLINE void FailBadPrototypeIndex(uint32_t idx) {
740 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
741 << "bad prototype index " << idx << " (max " << dex_file_->NumProtoIds() << ")";
742 }
743
FailBadStringIndex(uint32_t idx)744 NO_INLINE void FailBadStringIndex(uint32_t idx) {
745 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
746 << "bad string index " << idx << " (max " << dex_file_->NumStringIds() << ")";
747 }
748
FailBadTypeIndex(dex::TypeIndex idx)749 NO_INLINE void FailBadTypeIndex(dex::TypeIndex idx) {
750 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
751 << "bad type index " << idx.index_ << " (max " << dex_file_->NumTypeIds() << ")";
752 }
753
FailBadNewArrayNotArray(const char * descriptor)754 NO_INLINE void FailBadNewArrayNotArray(const char* descriptor) {
755 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
756 << "can't new-array class '" << descriptor << "' (not an array)";
757 }
758
FailBadNewArrayTooManyDimensions(const char * descriptor)759 NO_INLINE void FailBadNewArrayTooManyDimensions(const char* descriptor) {
760 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
761 << "can't new-array class '" << descriptor << "' (exceeds limit)";
762 }
763
FailBadFilledNewArray(const char * descriptor)764 NO_INLINE void FailBadFilledNewArray(const char* descriptor) {
765 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
766 << "can't fill-new-array class '" << descriptor << "' (wide component type)";
767 }
768
FailBranchOffsetZero(uint32_t dex_pc)769 NO_INLINE void FailBranchOffsetZero(uint32_t dex_pc) {
770 work_insn_idx_ = dex_pc; // Let `Fail()` record the dex PC of the failing instruction.
771 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "branch offset of zero not allowed.";
772 }
773
FailTargetOffsetOutOfRange(uint32_t dex_pc,uint32_t end_dex_pc,int32_t offset)774 NO_INLINE void FailTargetOffsetOutOfRange(uint32_t dex_pc, uint32_t end_dex_pc, int32_t offset) {
775 work_insn_idx_ = dex_pc; // Let `Fail()` record the dex PC of the failing instruction.
776 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
777 << "invalid target offset " << offset
778 << " (end " << reinterpret_cast<void*>(end_dex_pc) << ")";
779 }
780
FailTargetMidInstruction(uint32_t dex_pc,uint32_t target_dex_pc)781 NO_INLINE void FailTargetMidInstruction(uint32_t dex_pc, uint32_t target_dex_pc) {
782 work_insn_idx_ = dex_pc; // Let `Fail()` record the dex PC of the failing instruction.
783 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
784 << "target dex pc " << reinterpret_cast<void*>(target_dex_pc)
785 << " is not at instruction start.";
786 }
787
FailBranchTargetIsMoveResultOrMoveException(uint32_t dex_pc,uint32_t target_dex_pc,Instruction::Code target_opcode)788 NO_INLINE void FailBranchTargetIsMoveResultOrMoveException(uint32_t dex_pc,
789 uint32_t target_dex_pc,
790 Instruction::Code target_opcode) {
791 DCHECK(IsMoveResultOrMoveException(target_opcode));
792 work_insn_idx_ = dex_pc; // Let `Fail()` record the dex PC of the failing instruction.
793 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
794 << "invalid use of " << target_opcode << " as branch target at "
795 << reinterpret_cast<void*>(target_dex_pc);
796 }
797
FailUnalignedTableDexPc(uint32_t dex_pc,uint32_t table_dex_pc)798 NO_INLINE void FailUnalignedTableDexPc(uint32_t dex_pc, uint32_t table_dex_pc) {
799 work_insn_idx_ = dex_pc; // Let `Fail()` record the dex PC of the failing instruction.
800 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unaligned table at " << table_dex_pc;
801 }
802
FailBadArrayDataSignature(uint32_t dex_pc,uint32_t array_data_dex_pc)803 NO_INLINE void FailBadArrayDataSignature(uint32_t dex_pc, uint32_t array_data_dex_pc) {
804 work_insn_idx_ = dex_pc; // Let `Fail()` record the dex PC of the failing instruction.
805 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
806 << "invalid magic for array-data at " << reinterpret_cast<void*>(array_data_dex_pc);
807 }
808
FailBadSwitchPayloadSignature(uint32_t dex_pc,uint32_t switch_payload_dex_pc,uint16_t signature,uint16_t expected_signature)809 NO_INLINE void FailBadSwitchPayloadSignature(uint32_t dex_pc,
810 uint32_t switch_payload_dex_pc,
811 uint16_t signature,
812 uint16_t expected_signature) {
813 work_insn_idx_ = dex_pc; // Let `Fail()` record the dex PC of the failing instruction.
814 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
815 << "wrong signature for switch payload at "
816 << reinterpret_cast<void*>(switch_payload_dex_pc)
817 << " (0x" << std::hex << signature << ", wanted 0x" << expected_signature << ")";
818 }
819
FailPackedSwitchKeyOverflow(uint32_t dex_pc,uint32_t switch_payload_dex_pc,int32_t first_key,uint32_t switch_count)820 NO_INLINE void FailPackedSwitchKeyOverflow(uint32_t dex_pc,
821 uint32_t switch_payload_dex_pc,
822 int32_t first_key,
823 uint32_t switch_count) {
824 work_insn_idx_ = dex_pc; // Let `Fail()` record the dex PC of the failing instruction.
825 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
826 << "invalid packed switch payload at "
827 << reinterpret_cast<void*>(switch_payload_dex_pc)
828 << ", key overflow: first_key=" << first_key << ", switch_count=" << switch_count;
829 }
830
FailSparseSwitchPayloadKeyOrder(uint32_t dex_pc,uint32_t switch_payload_dex_pc,int32_t previous_key,int32_t current_key)831 NO_INLINE void FailSparseSwitchPayloadKeyOrder(uint32_t dex_pc,
832 uint32_t switch_payload_dex_pc,
833 int32_t previous_key,
834 int32_t current_key) {
835 work_insn_idx_ = dex_pc; // Let `Fail()` record the dex PC of the failing instruction.
836 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
837 << "invalid sparse switch payload at "
838 << reinterpret_cast<void*>(switch_payload_dex_pc)
839 << ", unordered keys: previous=" << previous_key << ", current=" << current_key;
840 }
841
FailSwitchTargetOffsetOutOfRange(uint32_t dex_pc,uint32_t end_dex_pc,uint32_t switch_payload_dex_pc,int32_t offset,uint32_t target_index)842 NO_INLINE void FailSwitchTargetOffsetOutOfRange(uint32_t dex_pc,
843 uint32_t end_dex_pc,
844 uint32_t switch_payload_dex_pc,
845 int32_t offset,
846 uint32_t target_index) {
847 FailTargetOffsetOutOfRange(dex_pc, end_dex_pc, offset);
848 LastFailureMessageStream()
849 << " in switch payload at " << reinterpret_cast<void*>(switch_payload_dex_pc)
850 << ", target index " << target_index;
851 }
852
FailSwitchTargetMidInstruction(uint32_t dex_pc,uint32_t target_dex_pc,uint32_t switch_payload_dex_pc,uint32_t target_index)853 NO_INLINE void FailSwitchTargetMidInstruction(uint32_t dex_pc,
854 uint32_t target_dex_pc,
855 uint32_t switch_payload_dex_pc,
856 uint32_t target_index) {
857 FailTargetMidInstruction(dex_pc, target_dex_pc);
858 LastFailureMessageStream()
859 << " in switch payload at " << reinterpret_cast<void*>(switch_payload_dex_pc)
860 << ", target index " << target_index;
861 }
862
FailSwitchTargetIsMoveResultOrMoveException(uint32_t dex_pc,uint32_t target_dex_pc,Instruction::Code target_opcode,uint32_t switch_payload_dex_pc,uint32_t target_index)863 NO_INLINE void FailSwitchTargetIsMoveResultOrMoveException(uint32_t dex_pc,
864 uint32_t target_dex_pc,
865 Instruction::Code target_opcode,
866 uint32_t switch_payload_dex_pc,
867 uint32_t target_index) {
868 FailBranchTargetIsMoveResultOrMoveException(dex_pc, target_dex_pc, target_opcode);
869 LastFailureMessageStream()
870 << " in switch payload at " << reinterpret_cast<void*>(switch_payload_dex_pc)
871 << ", target index " << target_index;
872 }
873
FailForCopyReference(uint32_t vdst,uint32_t vsrc,const RegType & type)874 NO_INLINE void FailForCopyReference(uint32_t vdst, uint32_t vsrc, const RegType& type)
875 REQUIRES_SHARED(Locks::mutator_lock_) {
876 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
877 << "copy-reference v" << vdst << "<-v" << vsrc << " type=" << type;
878 }
879
FailForCopyCat1(uint32_t vdst,uint32_t vsrc,const RegType & type)880 NO_INLINE void FailForCopyCat1(uint32_t vdst, uint32_t vsrc, const RegType& type)
881 REQUIRES_SHARED(Locks::mutator_lock_) {
882 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
883 << "copy-cat1 v" << vdst << "<-v" << vsrc << " type=" << type;
884 }
885
FailForCopyCat2(uint32_t vdst,uint32_t vsrc,const RegType & type_l,const RegType & type_h)886 NO_INLINE void FailForCopyCat2(
887 uint32_t vdst, uint32_t vsrc, const RegType& type_l, const RegType& type_h)
888 REQUIRES_SHARED(Locks::mutator_lock_) {
889 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
890 << "copy-cat2 v" << vdst << "<-v" << vsrc << " type=" << type_l << "/" << type_h;
891 }
892
FailForRegisterType(uint32_t vsrc,const RegType & check_type,const RegType & src_type,VerifyError fail_type=VERIFY_ERROR_BAD_CLASS_HARD)893 NO_INLINE void FailForRegisterType(uint32_t vsrc,
894 const RegType& check_type,
895 const RegType& src_type,
896 VerifyError fail_type = VERIFY_ERROR_BAD_CLASS_HARD)
897 REQUIRES_SHARED(Locks::mutator_lock_) {
898 Fail(fail_type)
899 << "register v" << vsrc << " has type " << src_type << " but expected " << check_type;
900 }
901
FailForRegisterType(uint32_t vsrc,RegType::Kind check_kind,uint16_t src_type_id)902 NO_INLINE void FailForRegisterType(uint32_t vsrc,
903 RegType::Kind check_kind,
904 uint16_t src_type_id)
905 REQUIRES_SHARED(Locks::mutator_lock_) {
906 FailForRegisterType(
907 vsrc, reg_types_.GetFromRegKind(check_kind), reg_types_.GetFromId(src_type_id));
908 }
909
FailForRegisterTypeWide(uint32_t vsrc,const RegType & src_type,const RegType & src_type_h)910 NO_INLINE void FailForRegisterTypeWide(uint32_t vsrc,
911 const RegType& src_type,
912 const RegType& src_type_h)
913 REQUIRES_SHARED(Locks::mutator_lock_) {
914 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
915 << "wide register v" << vsrc << " has type " << src_type << "/" << src_type_h;
916 }
917
FailForRegisterTypeWide(uint32_t vsrc,uint16_t src_type_id,uint16_t src_type_id_h)918 NO_INLINE void FailForRegisterTypeWide(uint32_t vsrc,
919 uint16_t src_type_id,
920 uint16_t src_type_id_h)
921 REQUIRES_SHARED(Locks::mutator_lock_) {
922 FailForRegisterTypeWide(
923 vsrc, reg_types_.GetFromId(src_type_id), reg_types_.GetFromId(src_type_id_h));
924 }
925
VerifyCopyReference(uint32_t vdst,uint32_t vsrc)926 ALWAYS_INLINE inline bool VerifyCopyReference(uint32_t vdst, uint32_t vsrc)
927 REQUIRES_SHARED(Locks::mutator_lock_) {
928 const RegType& type = work_line_->GetRegisterType(this, vsrc);
929 // Allow conflicts to be copied around.
930 if (UNLIKELY(!type.IsConflict() && !type.IsReferenceTypes())) {
931 FailForCopyReference(vdst, vsrc, type);
932 return false;
933 }
934 work_line_->CopyReference(vdst, vsrc, type);
935 return true;
936 }
937
VerifyCopyCat1(uint32_t vdst,uint32_t vsrc)938 ALWAYS_INLINE inline bool VerifyCopyCat1(uint32_t vdst, uint32_t vsrc)
939 REQUIRES_SHARED(Locks::mutator_lock_) {
940 uint16_t src_type_id = work_line_->GetRegisterTypeId(vsrc);
941 if (UNLIKELY(src_type_id >= RegTypeCache::NumberOfRegKindCacheIds()) ||
942 UNLIKELY(RegTypeCache::RegKindForId(src_type_id) != RegType::kConflict &&
943 !RegType::IsCategory1Types(RegTypeCache::RegKindForId(src_type_id)))) {
944 const RegType& type = reg_types_.GetFromId(src_type_id);
945 DCHECK(!type.IsConflict() && !type.IsCategory1Types()) << type;
946 FailForCopyCat1(vdst, vsrc, type);
947 return false;
948 }
949 RegType::Kind kind = RegTypeCache::RegKindForId(src_type_id);
950 DCHECK(kind == RegType::kConflict || RegType::IsCategory1Types(kind)) << kind;
951 work_line_->SetRegisterType(vdst, kind);
952 return true;
953 }
954
VerifyCopyCat2(uint32_t vdst,uint32_t vsrc)955 ALWAYS_INLINE inline bool VerifyCopyCat2(uint32_t vdst, uint32_t vsrc)
956 REQUIRES_SHARED(Locks::mutator_lock_) {
957 uint16_t src_type_id_l = work_line_->GetRegisterTypeId(vsrc);
958 uint16_t src_type_id_h = work_line_->GetRegisterTypeId(vsrc + 1);
959 auto to_high_id = [](uint16_t low_id) ALWAYS_INLINE {
960 RegType::Kind low_kind = RegTypeCache::RegKindForId(low_id);
961 DCHECK(RegType::IsLowHalf(low_kind));
962 return RegTypeCache::IdForRegKind(RegType::ToHighHalf(low_kind));
963 };
964 if (UNLIKELY(src_type_id_l >= RegTypeCache::NumberOfRegKindCacheIds()) ||
965 UNLIKELY(!RegType::IsLowHalf(RegTypeCache::RegKindForId(src_type_id_l))) ||
966 UNLIKELY(src_type_id_h != to_high_id(src_type_id_l))) {
967 const RegType& type_l = reg_types_.GetFromId(src_type_id_l);
968 const RegType& type_h = reg_types_.GetFromId(src_type_id_h);
969 DCHECK(!type_l.CheckWidePair(type_h));
970 FailForCopyCat2(vdst, vsrc, type_l, type_h);
971 return false;
972 }
973 DCHECK(reg_types_.GetFromId(src_type_id_l).CheckWidePair(reg_types_.GetFromId(src_type_id_h)));
974 work_line_->SetRegisterTypeWide(vdst,
975 RegTypeCache::RegKindForId(src_type_id_l),
976 RegTypeCache::RegKindForId(src_type_id_h));
977 return true;
978 }
979
VerifyRegisterType(uint32_t vsrc,const RegType & check_type)980 ALWAYS_INLINE inline bool VerifyRegisterType(uint32_t vsrc, const RegType& check_type)
981 REQUIRES_SHARED(Locks::mutator_lock_) {
982 // Verify the src register type against the check type refining the type of the register
983 const RegType& src_type = work_line_->GetRegisterType(this, vsrc);
984 if (UNLIKELY(!IsAssignableFrom(check_type, src_type))) {
985 enum VerifyError fail_type;
986 if (!check_type.IsNonZeroReferenceTypes() || !src_type.IsNonZeroReferenceTypes()) {
987 // Hard fail if one of the types is primitive, since they are concretely known.
988 fail_type = VERIFY_ERROR_BAD_CLASS_HARD;
989 } else if (check_type.IsUninitializedTypes() || src_type.IsUninitializedTypes()) {
990 // Hard fail for uninitialized types, which don't match anything but themselves.
991 fail_type = VERIFY_ERROR_BAD_CLASS_HARD;
992 } else if (check_type.IsUnresolvedTypes() || src_type.IsUnresolvedTypes()) {
993 fail_type = VERIFY_ERROR_UNRESOLVED_TYPE_CHECK;
994 } else {
995 fail_type = VERIFY_ERROR_BAD_CLASS_HARD;
996 }
997 FailForRegisterType(vsrc, check_type, src_type, fail_type);
998 return fail_type != VERIFY_ERROR_BAD_CLASS_HARD;
999 }
1000 if (check_type.IsLowHalf()) {
1001 const RegType& src_type_h = work_line_->GetRegisterType(this, vsrc + 1);
1002 if (UNLIKELY(!src_type.CheckWidePair(src_type_h))) {
1003 FailForRegisterTypeWide(vsrc, src_type, src_type_h);
1004 return false;
1005 }
1006 }
1007 // The register at vsrc has a defined type, we know the lower-upper-bound, but this is less
1008 // precise than the subtype in vsrc so leave it for reference types. For primitive types if
1009 // they are a defined type then they are as precise as we can get, however, for constant types
1010 // we may wish to refine them. Unfortunately constant propagation has rendered this useless.
1011 return true;
1012 }
1013
VerifyRegisterType(uint32_t vsrc,RegType::Kind check_kind)1014 ALWAYS_INLINE inline bool VerifyRegisterType(uint32_t vsrc, RegType::Kind check_kind)
1015 REQUIRES_SHARED(Locks::mutator_lock_) {
1016 DCHECK(check_kind == RegType::Kind::kInteger || check_kind == RegType::Kind::kFloat);
1017 // Verify the src register type against the check type refining the type of the register
1018 uint16_t src_type_id = work_line_->GetRegisterTypeId(vsrc);
1019 if (UNLIKELY(src_type_id >= RegTypeCache::NumberOfRegKindCacheIds()) ||
1020 UNLIKELY(RegType::AssignabilityFrom(check_kind, RegTypeCache::RegKindForId(src_type_id)) !=
1021 RegType::Assignability::kAssignable)) {
1022 // Integer or float assignability is never a `kNarrowingConversion` or `kReference`.
1023 DCHECK_EQ(
1024 RegType::AssignabilityFrom(check_kind, reg_types_.GetFromId(src_type_id).GetKind()),
1025 RegType::Assignability::kNotAssignable);
1026 FailForRegisterType(vsrc, check_kind, src_type_id);
1027 return false;
1028 }
1029 return true;
1030 }
1031
VerifyRegisterTypeWide(uint32_t vsrc,RegType::Kind check_kind)1032 bool VerifyRegisterTypeWide(uint32_t vsrc, RegType::Kind check_kind)
1033 REQUIRES_SHARED(Locks::mutator_lock_) {
1034 DCHECK(check_kind == RegType::Kind::kLongLo || check_kind == RegType::Kind::kDoubleLo);
1035 // Verify the src register type against the check type refining the type of the register
1036 uint16_t src_type_id = work_line_->GetRegisterTypeId(vsrc);
1037 if (UNLIKELY(src_type_id >= RegTypeCache::NumberOfRegKindCacheIds()) ||
1038 UNLIKELY(RegType::AssignabilityFrom(check_kind, RegTypeCache::RegKindForId(src_type_id)) !=
1039 RegType::Assignability::kAssignable)) {
1040 // Wide assignability is never a `kNarrowingConversion` or `kReference`.
1041 DCHECK_EQ(
1042 RegType::AssignabilityFrom(check_kind, reg_types_.GetFromId(src_type_id).GetKind()),
1043 RegType::Assignability::kNotAssignable);
1044 FailForRegisterType(vsrc, check_kind, src_type_id);
1045 return false;
1046 }
1047 uint16_t src_type_id_h = work_line_->GetRegisterTypeId(vsrc + 1);
1048 uint16_t expected_src_type_id_h =
1049 RegTypeCache::IdForRegKind(RegType::ToHighHalf(RegTypeCache::RegKindForId(src_type_id)));
1050 DCHECK_EQ(src_type_id_h == expected_src_type_id_h,
1051 reg_types_.GetFromId(src_type_id).CheckWidePair(reg_types_.GetFromId(src_type_id_h)));
1052 if (UNLIKELY(src_type_id_h != expected_src_type_id_h)) {
1053 FailForRegisterTypeWide(vsrc, src_type_id, src_type_id_h);
1054 return false;
1055 }
1056 // The register at vsrc has a defined type, we know the lower-upper-bound, but this is less
1057 // precise than the subtype in vsrc so leave it for reference types. For primitive types if
1058 // they are a defined type then they are as precise as we can get, however, for constant types
1059 // we may wish to refine them. Unfortunately constant propagation has rendered this useless.
1060 return true;
1061 }
1062
1063 /*
1064 * Verify types for a simple two-register instruction (e.g. "neg-int").
1065 * "dst_type" is stored into vA, and "src_type" is verified against vB.
1066 */
1067 ALWAYS_INLINE
CheckUnaryOp(const Instruction * inst,uint16_t inst_data,RegType::Kind dst_kind,RegType::Kind src_kind)1068 bool CheckUnaryOp(const Instruction* inst,
1069 uint16_t inst_data,
1070 RegType::Kind dst_kind,
1071 RegType::Kind src_kind)
1072 REQUIRES_SHARED(Locks::mutator_lock_) {
1073 if (VerifyRegisterType(inst->VRegB_12x(inst_data), src_kind)) {
1074 work_line_->SetRegisterType(inst->VRegA_12x(inst_data), dst_kind);
1075 return true;
1076 } else {
1077 return false;
1078 }
1079 }
1080
1081 ALWAYS_INLINE
CheckUnaryOpWide(const Instruction * inst,uint16_t inst_data,RegType::Kind dst_kind,RegType::Kind src_kind)1082 bool CheckUnaryOpWide(const Instruction* inst,
1083 uint16_t inst_data,
1084 RegType::Kind dst_kind,
1085 RegType::Kind src_kind)
1086 REQUIRES_SHARED(Locks::mutator_lock_) {
1087 if (VerifyRegisterTypeWide(inst->VRegB_12x(inst_data), src_kind)) {
1088 work_line_->SetRegisterTypeWide(
1089 inst->VRegA_12x(inst_data), dst_kind, RegType::ToHighHalf(dst_kind));
1090 return true;
1091 } else {
1092 return false;
1093 }
1094 }
1095
1096 ALWAYS_INLINE
CheckUnaryOpToWide(const Instruction * inst,uint16_t inst_data,RegType::Kind dst_kind,RegType::Kind src_kind)1097 bool CheckUnaryOpToWide(const Instruction* inst,
1098 uint16_t inst_data,
1099 RegType::Kind dst_kind,
1100 RegType::Kind src_kind)
1101 REQUIRES_SHARED(Locks::mutator_lock_) {
1102 if (VerifyRegisterType(inst->VRegB_12x(inst_data), src_kind)) {
1103 work_line_->SetRegisterTypeWide(
1104 inst->VRegA_12x(inst_data), dst_kind, RegType::ToHighHalf(dst_kind));
1105 return true;
1106 } else {
1107 return false;
1108 }
1109 }
1110
1111 ALWAYS_INLINE
CheckUnaryOpFromWide(const Instruction * inst,uint16_t inst_data,RegType::Kind dst_kind,RegType::Kind src_kind)1112 bool CheckUnaryOpFromWide(const Instruction* inst,
1113 uint16_t inst_data,
1114 RegType::Kind dst_kind,
1115 RegType::Kind src_kind)
1116 REQUIRES_SHARED(Locks::mutator_lock_) {
1117 if (VerifyRegisterTypeWide(inst->VRegB_12x(inst_data), src_kind)) {
1118 work_line_->SetRegisterType(inst->VRegA_12x(inst_data), dst_kind);
1119 return true;
1120 } else {
1121 return false;
1122 }
1123 }
1124
1125 /*
1126 * Verify types for a simple three-register instruction (e.g. "add-int").
1127 * "dst_type" is stored into vA, and "src_type1"/"src_type2" are verified
1128 * against vB/vC.
1129 */
1130 ALWAYS_INLINE
CheckBinaryOp(const Instruction * inst,uint16_t inst_data,RegType::Kind dst_kind,RegType::Kind src_kind1,RegType::Kind src_kind2,bool check_boolean_op)1131 bool CheckBinaryOp(const Instruction* inst,
1132 uint16_t inst_data,
1133 RegType::Kind dst_kind,
1134 RegType::Kind src_kind1,
1135 RegType::Kind src_kind2,
1136 bool check_boolean_op)
1137 REQUIRES_SHARED(Locks::mutator_lock_) {
1138 const uint32_t vregA = inst->VRegA_23x(inst_data);
1139 const uint32_t vregB = inst->VRegB_23x();
1140 const uint32_t vregC = inst->VRegC_23x();
1141 if (VerifyRegisterType(vregB, src_kind1) &&
1142 VerifyRegisterType(vregC, src_kind2)) {
1143 if (check_boolean_op) {
1144 DCHECK_EQ(dst_kind, RegType::Kind::kInteger);
1145 if (RegType::IsBooleanTypes(
1146 RegTypeCache::RegKindForId(work_line_->GetRegisterTypeId(vregB))) &&
1147 RegType::IsBooleanTypes(
1148 RegTypeCache::RegKindForId(work_line_->GetRegisterTypeId(vregC)))) {
1149 dst_kind = RegType::Kind::kBoolean;
1150 }
1151 }
1152 work_line_->SetRegisterType(vregA, dst_kind);
1153 return true;
1154 } else {
1155 return false;
1156 }
1157 }
1158
1159 ALWAYS_INLINE
CheckBinaryOpWide(const Instruction * inst,uint16_t inst_data,RegType::Kind dst_kind,RegType::Kind src_kind1,RegType::Kind src_kind2)1160 bool CheckBinaryOpWide(const Instruction* inst,
1161 uint16_t inst_data,
1162 RegType::Kind dst_kind,
1163 RegType::Kind src_kind1,
1164 RegType::Kind src_kind2)
1165 REQUIRES_SHARED(Locks::mutator_lock_) {
1166 if (VerifyRegisterTypeWide(inst->VRegB_23x(), src_kind1) &&
1167 VerifyRegisterTypeWide(inst->VRegC_23x(), src_kind2)) {
1168 work_line_->SetRegisterTypeWide(
1169 inst->VRegA_23x(inst_data), dst_kind, RegType::ToHighHalf(dst_kind));
1170 return true;
1171 } else {
1172 return false;
1173 }
1174 }
1175
1176 ALWAYS_INLINE
CheckBinaryOpWideCmp(const Instruction * inst,uint16_t inst_data,RegType::Kind dst_kind,RegType::Kind src_kind1,RegType::Kind src_kind2)1177 bool CheckBinaryOpWideCmp(const Instruction* inst,
1178 uint16_t inst_data,
1179 RegType::Kind dst_kind,
1180 RegType::Kind src_kind1,
1181 RegType::Kind src_kind2)
1182 REQUIRES_SHARED(Locks::mutator_lock_) {
1183 if (VerifyRegisterTypeWide(inst->VRegB_23x(), src_kind1) &&
1184 VerifyRegisterTypeWide(inst->VRegC_23x(), src_kind2)) {
1185 work_line_->SetRegisterType(inst->VRegA_23x(inst_data), dst_kind);
1186 return true;
1187 } else {
1188 return false;
1189 }
1190 }
1191
1192 ALWAYS_INLINE
CheckBinaryOpWideShift(const Instruction * inst,uint16_t inst_data,RegType::Kind long_lo_kind,RegType::Kind int_kind)1193 bool CheckBinaryOpWideShift(const Instruction* inst,
1194 uint16_t inst_data,
1195 RegType::Kind long_lo_kind,
1196 RegType::Kind int_kind)
1197 REQUIRES_SHARED(Locks::mutator_lock_) {
1198 if (VerifyRegisterTypeWide(inst->VRegB_23x(), long_lo_kind) &&
1199 VerifyRegisterType(inst->VRegC_23x(), int_kind)) {
1200 RegType::Kind long_hi_kind = RegType::ToHighHalf(long_lo_kind);
1201 work_line_->SetRegisterTypeWide(inst->VRegA_23x(inst_data), long_lo_kind, long_hi_kind);
1202 return true;
1203 } else {
1204 return false;
1205 }
1206 }
1207
1208 /*
1209 * Verify types for a binary "2addr" operation. "src_type1"/"src_type2"
1210 * are verified against vA/vB, then "dst_type" is stored into vA.
1211 */
1212 ALWAYS_INLINE
CheckBinaryOp2addr(const Instruction * inst,uint16_t inst_data,RegType::Kind dst_kind,RegType::Kind src_kind1,RegType::Kind src_kind2,bool check_boolean_op)1213 bool CheckBinaryOp2addr(const Instruction* inst,
1214 uint16_t inst_data,
1215 RegType::Kind dst_kind,
1216 RegType::Kind src_kind1,
1217 RegType::Kind src_kind2,
1218 bool check_boolean_op)
1219 REQUIRES_SHARED(Locks::mutator_lock_) {
1220 const uint32_t vregA = inst->VRegA_12x(inst_data);
1221 const uint32_t vregB = inst->VRegB_12x(inst_data);
1222 if (VerifyRegisterType(vregA, src_kind1) &&
1223 VerifyRegisterType(vregB, src_kind2)) {
1224 if (check_boolean_op) {
1225 DCHECK_EQ(dst_kind, RegType::Kind::kInteger);
1226 if (RegType::IsBooleanTypes(
1227 RegTypeCache::RegKindForId(work_line_->GetRegisterTypeId(vregA))) &&
1228 RegType::IsBooleanTypes(
1229 RegTypeCache::RegKindForId(work_line_->GetRegisterTypeId(vregB)))) {
1230 dst_kind = RegType::Kind::kBoolean;
1231 }
1232 }
1233 work_line_->SetRegisterType(vregA, dst_kind);
1234 return true;
1235 } else {
1236 return false;
1237 }
1238 }
1239
1240 ALWAYS_INLINE
CheckBinaryOp2addrWide(const Instruction * inst,uint16_t inst_data,RegType::Kind dst_kind,RegType::Kind src_kind1,RegType::Kind src_kind2)1241 bool CheckBinaryOp2addrWide(const Instruction* inst,
1242 uint16_t inst_data,
1243 RegType::Kind dst_kind,
1244 RegType::Kind src_kind1,
1245 RegType::Kind src_kind2)
1246 REQUIRES_SHARED(Locks::mutator_lock_) {
1247 const uint32_t vregA = inst->VRegA_12x(inst_data);
1248 const uint32_t vregB = inst->VRegB_12x(inst_data);
1249 if (VerifyRegisterTypeWide(vregA, src_kind1) &&
1250 VerifyRegisterTypeWide(vregB, src_kind2)) {
1251 work_line_->SetRegisterTypeWide(vregA, dst_kind, RegType::ToHighHalf(dst_kind));
1252 return true;
1253 } else {
1254 return false;
1255 }
1256 }
1257
1258 ALWAYS_INLINE
CheckBinaryOp2addrWideShift(const Instruction * inst,uint16_t inst_data,RegType::Kind long_lo_kind,RegType::Kind int_kind)1259 bool CheckBinaryOp2addrWideShift(const Instruction* inst,
1260 uint16_t inst_data,
1261 RegType::Kind long_lo_kind,
1262 RegType::Kind int_kind)
1263 REQUIRES_SHARED(Locks::mutator_lock_) {
1264 const uint32_t vregA = inst->VRegA_12x(inst_data);
1265 const uint32_t vregB = inst->VRegB_12x(inst_data);
1266 if (VerifyRegisterTypeWide(vregA, long_lo_kind) &&
1267 VerifyRegisterType(vregB, int_kind)) {
1268 RegType::Kind long_hi_kind = RegType::ToHighHalf(long_lo_kind);
1269 work_line_->SetRegisterTypeWide(vregA, long_lo_kind, long_hi_kind);
1270 return true;
1271 } else {
1272 return false;
1273 }
1274 }
1275
1276 /*
1277 * Verify types for A two-register instruction with a literal constant (e.g. "add-int/lit8").
1278 * "dst_type" is stored into vA, and "src_type" is verified against vB.
1279 *
1280 * If "check_boolean_op" is set, we use the constant value in vC.
1281 */
1282 template <bool kIsLit16>
1283 ALWAYS_INLINE
CheckLiteralOp(const Instruction * inst,uint16_t inst_data,RegType::Kind dst_kind,RegType::Kind src_kind,bool check_boolean_op)1284 bool CheckLiteralOp(const Instruction* inst,
1285 uint16_t inst_data,
1286 RegType::Kind dst_kind,
1287 RegType::Kind src_kind,
1288 bool check_boolean_op)
1289 REQUIRES_SHARED(Locks::mutator_lock_) {
1290 const uint32_t vregA = kIsLit16 ? inst->VRegA_22s(inst_data) : inst->VRegA_22b(inst_data);
1291 const uint32_t vregB = kIsLit16 ? inst->VRegB_22s(inst_data) : inst->VRegB_22b();
1292 if (VerifyRegisterType(vregB, src_kind)) {
1293 if (check_boolean_op) {
1294 DCHECK_EQ(dst_kind, RegType::Kind::kInteger);
1295 /* check vB with the call, then check the constant manually */
1296 const uint32_t val = kIsLit16 ? inst->VRegC_22s() : inst->VRegC_22b();
1297 if (work_line_->GetRegisterType(this, vregB).IsBooleanTypes() && (val == 0 || val == 1)) {
1298 dst_kind = RegType::Kind::kBoolean;
1299 }
1300 }
1301 work_line_->SetRegisterType(vregA, dst_kind);
1302 return true;
1303 } else {
1304 return false;
1305 }
1306 }
1307
CurrentInsnFlags()1308 InstructionFlags* CurrentInsnFlags() {
1309 return &GetModifiableInstructionFlags(work_insn_idx_);
1310 }
1311
1312 RegType::Kind DetermineCat1Constant(int32_t value)
1313 REQUIRES_SHARED(Locks::mutator_lock_);
1314
GetModifiableInstructionFlags(size_t index)1315 ALWAYS_INLINE InstructionFlags& GetModifiableInstructionFlags(size_t index) {
1316 return insn_flags_[index];
1317 }
1318
1319 // Returns the method index of an invoke instruction.
GetMethodIdxOfInvoke(const Instruction * inst)1320 static uint16_t GetMethodIdxOfInvoke(const Instruction* inst) {
1321 // Note: This is compiled to a single load in release mode.
1322 Instruction::Code opcode = inst->Opcode();
1323 if (opcode == Instruction::INVOKE_VIRTUAL ||
1324 opcode == Instruction::INVOKE_SUPER ||
1325 opcode == Instruction::INVOKE_DIRECT ||
1326 opcode == Instruction::INVOKE_STATIC ||
1327 opcode == Instruction::INVOKE_INTERFACE ||
1328 opcode == Instruction::INVOKE_CUSTOM) {
1329 return inst->VRegB_35c();
1330 } else if (opcode == Instruction::INVOKE_VIRTUAL_RANGE ||
1331 opcode == Instruction::INVOKE_SUPER_RANGE ||
1332 opcode == Instruction::INVOKE_DIRECT_RANGE ||
1333 opcode == Instruction::INVOKE_STATIC_RANGE ||
1334 opcode == Instruction::INVOKE_INTERFACE_RANGE ||
1335 opcode == Instruction::INVOKE_CUSTOM_RANGE) {
1336 return inst->VRegB_3rc();
1337 } else if (opcode == Instruction::INVOKE_POLYMORPHIC) {
1338 return inst->VRegB_45cc();
1339 } else {
1340 DCHECK_EQ(opcode, Instruction::INVOKE_POLYMORPHIC_RANGE);
1341 return inst->VRegB_4rcc();
1342 }
1343 }
1344
1345 // Returns the field index of a field access instruction.
GetFieldIdxOfFieldAccess(const Instruction * inst)1346 ALWAYS_INLINE static uint16_t GetFieldIdxOfFieldAccess(const Instruction* inst) {
1347 // Note: This is compiled to a single load in release mode.
1348 Instruction::Code opcode = inst->Opcode();
1349 if (IsInstructionSGet(opcode) || IsInstructionSPut(opcode)) {
1350 return inst->VRegB_21c();
1351 } else {
1352 DCHECK(IsInstructionIGet(opcode) || IsInstructionIPut(opcode));
1353 return inst->VRegC_22c();
1354 }
1355 }
1356
1357 // For app-compatibility, code after a runtime throw is treated as dead code
1358 // for apps targeting <= S.
1359 void PotentiallyMarkRuntimeThrow() override;
1360
1361 // Dump the failures encountered by the verifier.
DumpFailures(std::ostream & os)1362 std::ostream& DumpFailures(std::ostream& os) {
1363 for (const VerifyErrorAndMessage& veam : failures_) {
1364 os << veam.message.view() << "\n";
1365 }
1366 return os;
1367 }
1368
1369 // Dump the state of the verifier, namely each instruction, what flags are set on it, register
1370 // information
Dump(std::ostream & os)1371 void Dump(std::ostream& os) REQUIRES_SHARED(Locks::mutator_lock_) {
1372 VariableIndentationOutputStream vios(&os);
1373 Dump(&vios);
1374 }
1375 void Dump(VariableIndentationOutputStream* vios) REQUIRES_SHARED(Locks::mutator_lock_);
1376
1377 struct HandleMoveExceptionResult {
1378 bool success;
1379 bool skip_verification_of_exception_handler;
1380 };
1381 HandleMoveExceptionResult HandleMoveException(const Instruction* inst)
1382 REQUIRES_SHARED(Locks::mutator_lock_);
1383
1384 const uint32_t method_access_flags_; // Method's access flags.
1385 const RegType* return_type_; // Lazily computed return type of the method.
1386 // The dex_cache for the declaring class of the method.
1387 Handle<mirror::DexCache> dex_cache_ GUARDED_BY(Locks::mutator_lock_);
1388 // The class loader for the declaring class of the method.
1389 Handle<mirror::ClassLoader> class_loader_ GUARDED_BY(Locks::mutator_lock_);
1390 const RegType* declaring_class_; // Lazily computed reg type of the method's declaring class.
1391
1392 // The dex PC of a FindLocksAtDexPc request, -1 otherwise.
1393 uint32_t interesting_dex_pc_;
1394 // The container into which FindLocksAtDexPc should write the registers containing held locks,
1395 // null if we're not doing FindLocksAtDexPc.
1396 std::vector<DexLockInfo>* monitor_enter_dex_pcs_;
1397
1398 // Indicates whether we verify to dump the info. In that case we accept quickened instructions
1399 // even though we might detect to be a compiler. Should only be set when running
1400 // VerifyMethodAndDump.
1401 const bool verify_to_dump_;
1402
1403 // Whether or not we call AllowThreadSuspension periodically, we want a way to disable this for
1404 // thread dumping checkpoints since we may get thread suspension at an inopportune time due to
1405 // FindLocksAtDexPC, resulting in deadlocks.
1406 const bool allow_thread_suspension_;
1407
1408 // Whether the method seems to be a constructor. Note that this field exists as we can't trust
1409 // the flags in the dex file. Some older code does not mark methods named "<init>" and "<clinit>"
1410 // correctly.
1411 //
1412 // Note: this flag is only valid once Verify() has started.
1413 bool is_constructor_;
1414
1415 // API level, for dependent checks. Note: we do not use '0' for unset here, to simplify checks.
1416 // Instead, unset level should correspond to max().
1417 const uint32_t api_level_;
1418
1419 DISALLOW_COPY_AND_ASSIGN(MethodVerifierImpl);
1420 };
1421
1422 template <bool kVerifierDebug>
1423 class MethodVerifier final : public MethodVerifierImpl {
1424 public:
1425 void FindLocksAtDexPc() REQUIRES_SHARED(Locks::mutator_lock_);
1426
1427 private:
1428 using MethodVerifierImpl::MethodVerifierImpl;
1429
1430 /* Perform detailed code-flow analysis on a single method. */
1431 bool VerifyCodeFlow() REQUIRES_SHARED(Locks::mutator_lock_);
1432
1433 /*
1434 * Perform code flow on a method.
1435 *
1436 * The basic strategy is as outlined in v3 4.11.1.2: set the "changed" bit on the first
1437 * instruction, process it (setting additional "changed" bits), and repeat until there are no
1438 * more.
1439 *
1440 * v3 4.11.1.1
1441 * - (N/A) operand stack is always the same size
1442 * - operand stack [registers] contain the correct types of values
1443 * - local variables [registers] contain the correct types of values
1444 * - methods are invoked with the appropriate arguments
1445 * - fields are assigned using values of appropriate types
1446 * - opcodes have the correct type values in operand registers
1447 * - there is never an uninitialized class instance in a local variable in code protected by an
1448 * exception handler (operand stack is okay, because the operand stack is discarded when an
1449 * exception is thrown) [can't know what's a local var w/o the debug info -- should fall out of
1450 * register typing]
1451 *
1452 * v3 4.11.1.2
1453 * - execution cannot fall off the end of the code
1454 *
1455 * (We also do many of the items described in the "static checks" sections, because it's easier to
1456 * do them here.)
1457 *
1458 * We need an array of RegType values, one per register, for every instruction. If the method uses
1459 * monitor-enter, we need extra data for every register, and a stack for every "interesting"
1460 * instruction. In theory this could become quite large -- up to several megabytes for a monster
1461 * function.
1462 *
1463 * NOTE:
1464 * The spec forbids backward branches when there's an uninitialized reference in a register. The
1465 * idea is to prevent something like this:
1466 * loop:
1467 * move r1, r0
1468 * new-instance r0, MyClass
1469 * ...
1470 * if-eq rN, loop // once
1471 * initialize r0
1472 *
1473 * This leaves us with two different instances, both allocated by the same instruction, but only
1474 * one is initialized. The scheme outlined in v3 4.11.1.4 wouldn't catch this, so they work around
1475 * it by preventing backward branches. We achieve identical results without restricting code
1476 * reordering by specifying that you can't execute the new-instance instruction if a register
1477 * contains an uninitialized instance created by that same instruction.
1478 */
1479 template <bool kMonitorDexPCs>
1480 bool CodeFlowVerifyMethod() REQUIRES_SHARED(Locks::mutator_lock_);
1481
1482 /*
1483 * Perform verification for a single instruction.
1484 *
1485 * This requires fully decoding the instruction to determine the effect it has on registers.
1486 *
1487 * Finds zero or more following instructions and sets the "changed" flag if execution at that
1488 * point needs to be (re-)evaluated. Register changes are merged into "reg_types_" at the target
1489 * addresses. Does not set or clear any other flags in "insn_flags_".
1490 */
1491 bool CodeFlowVerifyInstruction(uint32_t* start_guess)
1492 REQUIRES_SHARED(Locks::mutator_lock_);
1493
1494 /*
1495 * Control can transfer to "next_insn". Merge the registers from merge_line into the table at
1496 * next_insn, and set the changed flag on the target address if any of the registers were changed.
1497 * In the case of fall-through, update the merge line on a change as it's the working line for the
1498 * next instruction.
1499 */
1500 void UpdateRegisters(uint32_t next_insn, RegisterLine* merge_line, bool update_merge_line)
1501 REQUIRES_SHARED(Locks::mutator_lock_);
1502
1503 // Run verification on the method. Returns true if verification completes and false if the input
1504 // has an irrecoverable corruption.
1505 bool Verify() override REQUIRES_SHARED(Locks::mutator_lock_);
1506
1507 friend class ::art::verifier::MethodVerifier;
1508
1509 DISALLOW_COPY_AND_ASSIGN(MethodVerifier);
1510 };
1511
IsLargeMethod(const CodeItemDataAccessor & accessor)1512 static bool IsLargeMethod(const CodeItemDataAccessor& accessor) {
1513 if (!accessor.HasCodeItem()) {
1514 return false;
1515 }
1516
1517 uint16_t registers_size = accessor.RegistersSize();
1518 uint32_t insns_size = accessor.InsnsSizeInCodeUnits();
1519
1520 return registers_size * insns_size > 4*1024*1024;
1521 }
1522
1523 template <bool kVerifierDebug>
FindLocksAtDexPc()1524 void MethodVerifier<kVerifierDebug>::FindLocksAtDexPc() {
1525 CHECK(monitor_enter_dex_pcs_ != nullptr);
1526 CHECK(code_item_accessor_.HasCodeItem()); // This only makes sense for methods with code.
1527
1528 // Quick check whether there are any monitor_enter instructions before verifying.
1529 for (const DexInstructionPcPair& inst : code_item_accessor_) {
1530 if (inst->Opcode() == Instruction::MONITOR_ENTER) {
1531 // Strictly speaking, we ought to be able to get away with doing a subset of the full method
1532 // verification. In practice, the phase we want relies on data structures set up by all the
1533 // earlier passes, so we just run the full method verification and bail out early when we've
1534 // got what we wanted.
1535 Verify();
1536 return;
1537 }
1538 }
1539 }
1540
1541 template <bool kVerifierDebug>
Verify()1542 bool MethodVerifier<kVerifierDebug>::Verify() {
1543 // Some older code doesn't correctly mark constructors as such, so we need look
1544 // at the name if the constructor flag is not present.
1545 if ((method_access_flags_ & kAccConstructor) != 0) {
1546 // `DexFileVerifier` rejects methods with the constructor flag without a constructor name.
1547 DCHECK(dex_file_->GetMethodNameView(dex_method_idx_) == "<init>" ||
1548 dex_file_->GetMethodNameView(dex_method_idx_) == "<clinit>");
1549 is_constructor_ = true;
1550 } else if (dex_file_->GetMethodName(dex_method_idx_)[0] == '<') {
1551 // `DexFileVerifier` rejects method names starting with '<' other than constructors.
1552 DCHECK(dex_file_->GetMethodNameView(dex_method_idx_) == "<init>" ||
1553 dex_file_->GetMethodNameView(dex_method_idx_) == "<clinit>");
1554 LOG(WARNING) << "Method " << dex_file_->PrettyMethod(dex_method_idx_)
1555 << " not marked as constructor.";
1556 is_constructor_ = true;
1557 }
1558 // If it's a constructor, check whether IsStatic() matches the name for newer dex files.
1559 // This should be rejected by the `DexFileVerifier` but it's accepted for older dex files.
1560 if (kIsDebugBuild && IsConstructor() && dex_file_->SupportsDefaultMethods()) {
1561 CHECK_EQ(IsStatic(), dex_file_->GetMethodNameView(dex_method_idx_) == "<clinit>");
1562 }
1563
1564 // Methods may only have one of public/protected/private.
1565 // This should have been rejected by the dex file verifier. Only do in debug build.
1566 constexpr uint32_t kAccPublicProtectedPrivate = kAccPublic | kAccProtected | kAccPrivate;
1567 DCHECK_IMPLIES((method_access_flags_ & kAccPublicProtectedPrivate) != 0u,
1568 IsPowerOfTwo(method_access_flags_ & kAccPublicProtectedPrivate));
1569
1570 // If there aren't any instructions, make sure that's expected, then exit successfully.
1571 if (!code_item_accessor_.HasCodeItem()) {
1572 // Only native or abstract methods may not have code.
1573 if ((method_access_flags_ & (kAccNative | kAccAbstract)) == 0) {
1574 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "zero-length code in concrete non-native method";
1575 return false;
1576 }
1577
1578 // Test FastNative and CriticalNative annotations. We do this in the
1579 // verifier for convenience.
1580 if ((method_access_flags_ & kAccNative) != 0) {
1581 // Fetch the flags from the annotations: the class linker hasn't processed
1582 // them yet.
1583 uint32_t native_access_flags = annotations::GetNativeMethodAnnotationAccessFlags(
1584 *dex_file_, class_def_, dex_method_idx_);
1585 if ((native_access_flags & kAccFastNative) != 0) {
1586 if ((method_access_flags_ & kAccSynchronized) != 0) {
1587 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "fast native methods cannot be synchronized";
1588 return false;
1589 }
1590 }
1591 if ((native_access_flags & kAccCriticalNative) != 0) {
1592 if ((method_access_flags_ & kAccSynchronized) != 0) {
1593 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "critical native methods cannot be synchronized";
1594 return false;
1595 }
1596 if ((method_access_flags_ & kAccStatic) == 0) {
1597 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "critical native methods must be static";
1598 return false;
1599 }
1600 const char* shorty = dex_file_->GetMethodShorty(dex_method_idx_);
1601 for (size_t i = 0, len = strlen(shorty); i < len; ++i) {
1602 if (Primitive::GetType(shorty[i]) == Primitive::kPrimNot) {
1603 Fail(VERIFY_ERROR_BAD_CLASS_HARD) <<
1604 "critical native methods must not have references as arguments or return type";
1605 return false;
1606 }
1607 }
1608 }
1609 }
1610
1611 // This should have been rejected by the dex file verifier. Only do in debug build.
1612 // Note: the above will also be rejected in the dex file verifier, starting in dex version 37.
1613 if (kIsDebugBuild) {
1614 if ((method_access_flags_ & kAccAbstract) != 0) {
1615 // Abstract methods are not allowed to have the following flags.
1616 static constexpr uint32_t kForbidden =
1617 kAccPrivate |
1618 kAccStatic |
1619 kAccFinal |
1620 kAccNative |
1621 kAccStrict |
1622 kAccSynchronized;
1623 if ((method_access_flags_ & kForbidden) != 0) {
1624 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1625 << "method can't be abstract and private/static/final/native/strict/synchronized";
1626 return false;
1627 }
1628 }
1629 if ((class_def_.GetJavaAccessFlags() & kAccInterface) != 0) {
1630 // Interface methods must be public and abstract (if default methods are disabled).
1631 uint32_t kRequired = kAccPublic;
1632 if ((method_access_flags_ & kRequired) != kRequired) {
1633 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface methods must be public";
1634 return false;
1635 }
1636 // In addition to the above, interface methods must not be protected.
1637 static constexpr uint32_t kForbidden = kAccProtected;
1638 if ((method_access_flags_ & kForbidden) != 0) {
1639 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface methods can't be protected";
1640 return false;
1641 }
1642 }
1643 // We also don't allow constructors to be abstract or native.
1644 if (IsConstructor()) {
1645 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "constructors can't be abstract or native";
1646 return false;
1647 }
1648 }
1649 return true;
1650 }
1651
1652 // This should have been rejected by the dex file verifier. Only do in debug build.
1653 if (kIsDebugBuild) {
1654 // When there's code, the method must not be native or abstract.
1655 if ((method_access_flags_ & (kAccNative | kAccAbstract)) != 0) {
1656 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "non-zero-length code in abstract or native method";
1657 return false;
1658 }
1659
1660 if ((class_def_.GetJavaAccessFlags() & kAccInterface) != 0) {
1661 // Interfaces may always have static initializers for their fields. If we are running with
1662 // default methods enabled we also allow other public, static, non-final methods to have code.
1663 // Otherwise that is the only type of method allowed.
1664 if (!(IsConstructor() && IsStatic())) {
1665 if (IsInstanceConstructor()) {
1666 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interfaces may not have non-static constructor";
1667 return false;
1668 } else if (method_access_flags_ & kAccFinal) {
1669 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interfaces may not have final methods";
1670 return false;
1671 } else {
1672 uint32_t access_flag_options = kAccPublic;
1673 if (dex_file_->SupportsDefaultMethods()) {
1674 access_flag_options |= kAccPrivate;
1675 }
1676 if (!(method_access_flags_ & access_flag_options)) {
1677 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1678 << "interfaces may not have protected or package-private members";
1679 return false;
1680 }
1681 }
1682 }
1683 }
1684
1685 // Instance constructors must not be synchronized.
1686 if (IsInstanceConstructor()) {
1687 static constexpr uint32_t kForbidden = kAccSynchronized;
1688 if ((method_access_flags_ & kForbidden) != 0) {
1689 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "constructors can't be synchronized";
1690 return false;
1691 }
1692 }
1693 }
1694
1695 // Consistency-check of the register counts.
1696 // ins + locals = registers, so make sure that ins <= registers.
1697 if (code_item_accessor_.InsSize() > code_item_accessor_.RegistersSize()) {
1698 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad register counts (ins="
1699 << code_item_accessor_.InsSize()
1700 << " regs=" << code_item_accessor_.RegistersSize();
1701 return false;
1702 }
1703
1704 if (code_item_accessor_.InsnsSizeInCodeUnits() == 0u) {
1705 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "code item has no opcode";
1706 return false;
1707 }
1708 // Allocate and initialize an array to hold instruction data.
1709 insn_flags_.reset(allocator_.AllocArray<InstructionFlags>(
1710 code_item_accessor_.InsnsSizeInCodeUnits()));
1711 DCHECK(insn_flags_ != nullptr);
1712 // `ArenaAllocator` guarantees zero-initialization.
1713 static_assert(std::is_same_v<decltype(allocator_), ArenaAllocator>);
1714 DCHECK(std::all_of(
1715 insn_flags_.get(),
1716 insn_flags_.get() + code_item_accessor_.InsnsSizeInCodeUnits(),
1717 [](const InstructionFlags& flags) { return flags.Equals(InstructionFlags()); }));
1718 // Run through the instructions and see if the width checks out.
1719 bool result = ComputeWidthsAndCountOps();
1720 // Flag instructions guarded by a "try" block and check exception handlers.
1721 result = result && ScanTryCatchBlocks();
1722 // Perform static instruction verification.
1723 result = result && VerifyInstructions();
1724 // Perform code-flow analysis and return.
1725 result = result && VerifyCodeFlow();
1726
1727 return result;
1728 }
1729
ComputeWidthsAndCountOps()1730 bool MethodVerifierImpl::ComputeWidthsAndCountOps() {
1731 // We can't assume the instruction is well formed, handle the case where calculating the size
1732 // goes past the end of the code item.
1733 const uint32_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits();
1734 const Instruction* inst = &code_item_accessor_.InstructionAt(0u);
1735 uint32_t dex_pc = 0u;
1736 while (dex_pc != insns_size) {
1737 const uint32_t remaining_code_units = insns_size - dex_pc;
1738 const uint16_t inst_data = inst->Fetch16(0);
1739 const Instruction::Code opcode = inst->Opcode(inst_data);
1740 uint32_t instruction_size = 0u;
1741 bool ok;
1742 if (opcode == Instruction::NOP) {
1743 auto check_switch = [&](uint32_t base_size, uint32_t entry_size) ALWAYS_INLINE {
1744 if (UNLIKELY(base_size > remaining_code_units)) {
1745 return false;
1746 }
1747 // This 32-bit calculation cannot overflow because `num_entries` starts as 16-bit.
1748 uint32_t num_entries = inst->Fetch16(1);
1749 instruction_size = base_size + num_entries * entry_size;
1750 if (UNLIKELY(instruction_size > remaining_code_units)) {
1751 return false;
1752 }
1753 return true;
1754 };
1755 switch (inst_data) {
1756 case Instruction::kPackedSwitchSignature:
1757 ok = check_switch(4u, 2u);
1758 break;
1759 case Instruction::kSparseSwitchSignature:
1760 ok = check_switch(2u, 4u);
1761 break;
1762 case Instruction::kArrayDataSignature:
1763 if (UNLIKELY(remaining_code_units < 4u)) {
1764 ok = false;
1765 } else {
1766 uint16_t element_size = inst->Fetch16(1);
1767 uint32_t length = inst->Fetch16(2) | (((uint32_t)inst->Fetch16(3)) << 16);
1768 // Use 64-bit calculation to avoid arithmetic overflow.
1769 uint64_t bytes = static_cast<uint64_t>(element_size) * static_cast<uint64_t>(length);
1770 uint64_t code_units = UINT64_C(4) + (bytes + /* round up */ UINT64_C(1)) / UINT64_C(2);
1771 if (UNLIKELY(code_units > remaining_code_units)) {
1772 ok = false;
1773 } else {
1774 instruction_size = dchecked_integral_cast<uint32_t>(code_units);
1775 ok = true;
1776 }
1777 }
1778 break;
1779 default:
1780 instruction_size = 1u;
1781 ok = true;
1782 break;
1783 }
1784 } else {
1785 instruction_size = Instruction::SizeInCodeUnits(Instruction::FormatOf(opcode));
1786 DCHECK_EQ(instruction_size, inst->SizeInCodeUnits());
1787 ok = LIKELY(instruction_size <= remaining_code_units);
1788 }
1789 if (!ok) {
1790 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "code did not end where expected ("
1791 << dex_pc << " vs. " << insns_size << ")";
1792 return false;
1793 }
1794 GetModifiableInstructionFlags(dex_pc).SetIsOpcode();
1795 DCHECK_NE(instruction_size, 0u);
1796 DCHECK_EQ(instruction_size, inst->SizeInCodeUnits());
1797 DCHECK_LE(instruction_size, remaining_code_units);
1798 dex_pc += instruction_size;
1799 inst = inst->RelativeAt(instruction_size);
1800 }
1801 DCHECK(GetInstructionFlags(0).IsOpcode());
1802 return true;
1803 }
1804
ScanTryCatchBlocks()1805 bool MethodVerifierImpl::ScanTryCatchBlocks() {
1806 const uint32_t tries_size = code_item_accessor_.TriesSize();
1807 if (tries_size == 0) {
1808 return true;
1809 }
1810 const uint32_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits();
1811 for (const dex::TryItem& try_item : code_item_accessor_.TryItems()) {
1812 const uint32_t start = try_item.start_addr_;
1813 const uint32_t end = start + try_item.insn_count_;
1814 if ((start >= end) || (start >= insns_size) || (end > insns_size)) {
1815 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad exception entry: startAddr=" << start
1816 << " endAddr=" << end << " (size=" << insns_size << ")";
1817 return false;
1818 }
1819 if (!GetInstructionFlags(start).IsOpcode()) {
1820 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1821 << "'try' block starts inside an instruction (" << start << ")";
1822 return false;
1823 }
1824 DexInstructionIterator end_it(code_item_accessor_.Insns(), end);
1825 for (DexInstructionIterator it(code_item_accessor_.Insns(), start); it < end_it; ++it) {
1826 GetModifiableInstructionFlags(it.DexPc()).SetInTry();
1827 }
1828 }
1829 // Iterate over each of the handlers to verify target addresses.
1830 const uint8_t* handlers_ptr = code_item_accessor_.GetCatchHandlerData();
1831 const uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
1832 ClassLinker* linker = GetClassLinker();
1833 for (uint32_t idx = 0; idx < handlers_size; idx++) {
1834 CatchHandlerIterator iterator(handlers_ptr);
1835 for (; iterator.HasNext(); iterator.Next()) {
1836 uint32_t dex_pc = iterator.GetHandlerAddress();
1837 // `DexFileVerifier` checks that the `dex_pc` is in range.
1838 DCHECK_LT(dex_pc, code_item_accessor_.InsnsSizeInCodeUnits());
1839 if (!GetInstructionFlags(dex_pc).IsOpcode()) {
1840 work_insn_idx_ = dex_pc; // Let `Fail()` record the dex PC of the failing instruction.
1841 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "exception handler starts at bad address";
1842 return false;
1843 }
1844 if (UNLIKELY(IsMoveResult(code_item_accessor_.InstructionAt(dex_pc).Opcode()))) {
1845 work_insn_idx_ = dex_pc; // Let `Fail()` record the dex PC of the failing instruction.
1846 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "exception handler begins with move-result*";
1847 return false;
1848 }
1849 GetModifiableInstructionFlags(dex_pc).SetBranchTarget();
1850 // Ensure exception types are resolved so that they don't need resolution to be delivered,
1851 // unresolved exception types will be ignored by exception delivery
1852 if (iterator.GetHandlerTypeIndex().IsValid()) {
1853 ObjPtr<mirror::Class> exception_type =
1854 linker->ResolveType(iterator.GetHandlerTypeIndex(), dex_cache_, class_loader_);
1855 if (exception_type == nullptr) {
1856 DCHECK(self_->IsExceptionPending());
1857 self_->ClearException();
1858 }
1859 }
1860 }
1861 handlers_ptr = iterator.EndDataPointer();
1862 }
1863 return true;
1864 }
1865
VerifyInstructions()1866 bool MethodVerifierImpl::VerifyInstructions() {
1867 // Flag the start of the method as a branch target.
1868 GetModifiableInstructionFlags(0).SetBranchTarget();
1869 const Instruction* inst = Instruction::At(code_item_accessor_.Insns());
1870 uint32_t dex_pc = 0u;
1871 const uint32_t end_dex_pc = code_item_accessor_.InsnsSizeInCodeUnits();
1872 while (dex_pc != end_dex_pc) {
1873 auto find_dispatch_opcode = [](Instruction::Code opcode) constexpr {
1874 // NOP needs its own dipatch because it needs special code for instruction size.
1875 if (opcode == Instruction::NOP) {
1876 return opcode;
1877 }
1878 DCHECK_GT(Instruction::SizeInCodeUnits(Instruction::FormatOf(opcode)), 0u);
1879 for (uint32_t raw_other = 0; raw_other != opcode; ++raw_other) {
1880 Instruction::Code other = enum_cast<Instruction::Code>(raw_other);
1881 if (other == Instruction::NOP) {
1882 continue;
1883 }
1884 // We dispatch to `VerifyInstruction()` based on the format and verify flags but
1885 // we also treat return instructions separately to update instruction flags.
1886 if (Instruction::FormatOf(opcode) == Instruction::FormatOf(other) &&
1887 Instruction::VerifyFlagsOf(opcode) == Instruction::VerifyFlagsOf(other) &&
1888 Instruction::IsReturn(opcode) == Instruction::IsReturn(other)) {
1889 return other;
1890 }
1891 }
1892 return opcode;
1893 };
1894
1895 uint16_t inst_data = inst->Fetch16(0);
1896 Instruction::Code dispatch_opcode = Instruction::NOP;
1897 switch (inst->Opcode(inst_data)) {
1898 #define DEFINE_CASE(opcode, c, p, format, index, flags, eflags, vflags) \
1899 case opcode: { \
1900 /* Enforce compile-time evaluation. */ \
1901 constexpr Instruction::Code kDispatchOpcode = \
1902 find_dispatch_opcode(enum_cast<Instruction::Code>(opcode)); \
1903 dispatch_opcode = kDispatchOpcode; \
1904 break; \
1905 }
1906 DEX_INSTRUCTION_LIST(DEFINE_CASE)
1907 #undef DEFINE_CASE
1908 }
1909 bool is_return = false;
1910 uint32_t instruction_size = 0u;
1911 switch (dispatch_opcode) {
1912 #define DEFINE_CASE(opcode, c, p, format, index, flags, eflags, vflags) \
1913 case opcode: { \
1914 constexpr Instruction::Code kOpcode = enum_cast<Instruction::Code>(opcode); \
1915 if (!VerifyInstruction<kOpcode>(dex_pc, end_dex_pc, inst, inst_data)) { \
1916 DCHECK_NE(failures_.size(), 0U); \
1917 return false; \
1918 } \
1919 is_return = Instruction::IsReturn(kOpcode); \
1920 instruction_size = (opcode == Instruction::NOP) \
1921 ? inst->SizeInCodeUnitsComplexOpcode() \
1922 : Instruction::SizeInCodeUnits(Instruction::FormatOf(kOpcode)); \
1923 DCHECK_EQ(instruction_size, inst->SizeInCodeUnits()); \
1924 break; \
1925 }
1926 DEX_INSTRUCTION_LIST(DEFINE_CASE)
1927 #undef DEFINE_CASE
1928 }
1929 // Flag some interesting instructions.
1930 if (is_return) {
1931 GetModifiableInstructionFlags(dex_pc).SetReturn();
1932 }
1933 DCHECK_NE(instruction_size, 0u);
1934 DCHECK_LE(instruction_size, end_dex_pc - dex_pc);
1935 dex_pc += instruction_size;
1936 inst = inst->RelativeAt(instruction_size);
1937 }
1938 return true;
1939 }
1940
1941 template <Instruction::Code kDispatchOpcode>
VerifyInstruction(uint32_t dex_pc,uint32_t end_dex_pc,const Instruction * inst,uint16_t inst_data)1942 inline bool MethodVerifierImpl::VerifyInstruction(uint32_t dex_pc,
1943 uint32_t end_dex_pc,
1944 const Instruction* inst,
1945 uint16_t inst_data) {
1946 // The `kDispatchOpcode` may differ from the actual opcode but it shall have the
1947 // same verification flags and format. We explicitly `DCHECK` these below and
1948 // the format is also `DCHECK`ed in VReg getters that take it as an argument.
1949 constexpr Instruction::Format kFormat = Instruction::FormatOf(kDispatchOpcode);
1950 DCHECK_EQ(kFormat, Instruction::FormatOf(inst->Opcode()));
1951
1952 bool result = true;
1953 constexpr uint32_t kVerifyA = Instruction::GetVerifyTypeArgumentAOf(kDispatchOpcode);
1954 DCHECK_EQ(kVerifyA, inst->GetVerifyTypeArgumentA());
1955 switch (kVerifyA) {
1956 case Instruction::kVerifyRegA:
1957 result = result && CheckRegisterIndex(inst->VRegA(kFormat, inst_data));
1958 break;
1959 case Instruction::kVerifyRegAWide:
1960 result = result && CheckWideRegisterIndex(inst->VRegA(kFormat, inst_data));
1961 break;
1962 case Instruction::kVerifyNothing:
1963 break;
1964 }
1965 constexpr uint32_t kVerifyB = Instruction::GetVerifyTypeArgumentBOf(kDispatchOpcode);
1966 DCHECK_EQ(kVerifyB, inst->GetVerifyTypeArgumentB());
1967 switch (kVerifyB) {
1968 case Instruction::kVerifyRegB:
1969 result = result && CheckRegisterIndex(inst->VRegB(kFormat, inst_data));
1970 break;
1971 case Instruction::kVerifyRegBField:
1972 result = result && CheckFieldIndex(inst, inst_data, inst->VRegB(kFormat, inst_data));
1973 break;
1974 case Instruction::kVerifyRegBMethod:
1975 result = result && CheckMethodIndex(inst->VRegB(kFormat, inst_data));
1976 break;
1977 case Instruction::kVerifyRegBNewInstance:
1978 result = result && CheckNewInstance(dex::TypeIndex(inst->VRegB(kFormat, inst_data)));
1979 break;
1980 case Instruction::kVerifyRegBString:
1981 result = result && CheckStringIndex(inst->VRegB(kFormat, inst_data));
1982 break;
1983 case Instruction::kVerifyRegBType:
1984 result = result && CheckTypeIndex(dex::TypeIndex(inst->VRegB(kFormat, inst_data)));
1985 break;
1986 case Instruction::kVerifyRegBWide:
1987 result = result && CheckWideRegisterIndex(inst->VRegB(kFormat, inst_data));
1988 break;
1989 case Instruction::kVerifyRegBCallSite:
1990 result = result && CheckCallSiteIndex(inst->VRegB(kFormat, inst_data));
1991 break;
1992 case Instruction::kVerifyRegBMethodHandle:
1993 result = result && CheckMethodHandleIndex(inst->VRegB(kFormat, inst_data));
1994 break;
1995 case Instruction::kVerifyRegBPrototype:
1996 result = result && CheckPrototypeIndex(inst->VRegB(kFormat, inst_data));
1997 break;
1998 case Instruction::kVerifyRegBFilledNewArray:
1999 result = result &&
2000 CheckNewArray</*kFilled=*/ true>(dex::TypeIndex(inst->VRegB(kFormat, inst_data)));
2001 break;
2002 case Instruction::kVerifyNothing:
2003 break;
2004 }
2005 constexpr uint32_t kVerifyC = Instruction::GetVerifyTypeArgumentCOf(kDispatchOpcode);
2006 DCHECK_EQ(kVerifyC, inst->GetVerifyTypeArgumentC());
2007 switch (kVerifyC) {
2008 case Instruction::kVerifyRegC:
2009 result = result && CheckRegisterIndex(inst->VRegC(kFormat));
2010 break;
2011 case Instruction::kVerifyRegCField:
2012 result = result && CheckFieldIndex(inst, inst_data, inst->VRegC(kFormat));
2013 break;
2014 case Instruction::kVerifyRegCNewArray:
2015 result = result && CheckNewArray</*kFilled=*/ false>(dex::TypeIndex(inst->VRegC(kFormat)));
2016 break;
2017 case Instruction::kVerifyRegCType:
2018 result = result && CheckTypeIndex(dex::TypeIndex(inst->VRegC(kFormat)));
2019 break;
2020 case Instruction::kVerifyRegCWide:
2021 result = result && CheckWideRegisterIndex(inst->VRegC(kFormat));
2022 break;
2023 case Instruction::kVerifyNothing:
2024 break;
2025 }
2026 constexpr uint32_t kVerifyH = Instruction::GetVerifyTypeArgumentHOf(kDispatchOpcode);
2027 DCHECK_EQ(kVerifyH, inst->GetVerifyTypeArgumentH());
2028 switch (kVerifyH) {
2029 case Instruction::kVerifyRegHPrototype:
2030 result = result && CheckPrototypeIndex(inst->VRegH(kFormat));
2031 break;
2032 case Instruction::kVerifyNothing:
2033 break;
2034 }
2035 constexpr uint32_t kVerifyExtra = Instruction::GetVerifyExtraFlagsOf(kDispatchOpcode);
2036 DCHECK_EQ(kVerifyExtra, inst->GetVerifyExtraFlags());
2037 switch (kVerifyExtra) {
2038 case Instruction::kVerifyArrayData:
2039 result = result && CheckArrayData(dex_pc, end_dex_pc, inst);
2040 break;
2041 case Instruction::kVerifyBranchTarget:
2042 result = result && CheckAndMarkBranchTarget<kFormat>(dex_pc, end_dex_pc, inst, inst_data);
2043 break;
2044 case Instruction::kVerifySwitchTargets:
2045 result = result && CheckAndMarkSwitchTargets(dex_pc, end_dex_pc, inst, inst_data);
2046 break;
2047 case Instruction::kVerifyVarArgNonZero:
2048 // Fall-through.
2049 case Instruction::kVerifyVarArg: {
2050 // Instructions that can actually return a negative value shouldn't have this flag.
2051 uint32_t v_a = dchecked_integral_cast<uint32_t>(inst->VRegA(kFormat, inst_data));
2052 if ((kVerifyExtra == Instruction::kVerifyVarArgNonZero && v_a == 0) ||
2053 v_a > Instruction::kMaxVarArgRegs) {
2054 FailInvalidArgCount(inst, v_a);
2055 return false;
2056 }
2057
2058 result = result && CheckVarArgRegs(inst, v_a);
2059 break;
2060 }
2061 case Instruction::kVerifyVarArgRangeNonZero:
2062 // Fall-through.
2063 case Instruction::kVerifyVarArgRange: {
2064 uint32_t v_a = inst->VRegA(kFormat, inst_data);
2065 if (inst->GetVerifyExtraFlags() == Instruction::kVerifyVarArgRangeNonZero && v_a == 0) {
2066 FailInvalidArgCount(inst, v_a);
2067 return false;
2068 }
2069 result = result && CheckVarArgRangeRegs(v_a, inst->VRegC(kFormat));
2070 break;
2071 }
2072 case Instruction::kVerifyError:
2073 FailUnexpectedOpcode(inst);
2074 result = false;
2075 break;
2076 case Instruction::kVerifyNothing:
2077 break;
2078 }
2079 return result;
2080 }
2081
CheckNewInstance(dex::TypeIndex idx)2082 inline bool MethodVerifierImpl::CheckNewInstance(dex::TypeIndex idx) {
2083 if (!CheckTypeIndex(idx)) {
2084 return false;
2085 }
2086 // We don't need the actual class, just a pointer to the class name.
2087 const std::string_view descriptor = dex_file_->GetTypeDescriptorView(idx);
2088 if (UNLIKELY(descriptor[0] != 'L')) {
2089 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "can't call new-instance on type '" << descriptor << "'";
2090 return false;
2091 } else if (UNLIKELY(descriptor == "Ljava/lang/Class;")) {
2092 // An unlikely new instance on Class is not allowed.
2093 Fail(VERIFY_ERROR_INSTANTIATION);
2094 }
2095 return true;
2096 }
2097
2098 template <bool kFilled>
CheckNewArray(dex::TypeIndex idx)2099 inline bool MethodVerifierImpl::CheckNewArray(dex::TypeIndex idx) {
2100 if (!CheckTypeIndex(idx)) {
2101 return false;
2102 }
2103 const char* descriptor = dex_file_->GetTypeDescriptor(idx);
2104 const char* cp = descriptor;
2105 while (*cp == '[') {
2106 ++cp;
2107 }
2108 size_t bracket_count = static_cast<size_t>(cp - descriptor);
2109 if (UNLIKELY(bracket_count == 0u)) {
2110 /* The given class must be an array type. */
2111 FailBadNewArrayNotArray(descriptor);
2112 return false;
2113 } else if (UNLIKELY(bracket_count > 255u)) {
2114 /* It is illegal to create an array of more than 255 dimensions. */
2115 FailBadNewArrayTooManyDimensions(descriptor);
2116 return false;
2117 }
2118 if (kFilled && bracket_count == 1u && UNLIKELY(*cp != 'I' && *cp != 'L')) {
2119 if (UNLIKELY(*cp == 'J') || UNLIKELY(*cp == 'D')) {
2120 // Forbidden, see https://source.android.com/docs/core/runtime/dalvik-bytecode .
2121 FailBadFilledNewArray(descriptor);
2122 return false;
2123 } else {
2124 // Fall back to interpreter to throw `InternalError`. Compiler does not handle this case.
2125 Fail(VERIFY_ERROR_FILLED_NEW_ARRAY);
2126 }
2127 }
2128 return true;
2129 }
2130
CheckArrayData(uint32_t dex_pc,uint32_t end_dex_pc,const Instruction * inst)2131 bool MethodVerifierImpl::CheckArrayData(uint32_t dex_pc,
2132 uint32_t end_dex_pc,
2133 const Instruction* inst) {
2134 int32_t array_data_offset = inst->VRegB_31t();
2135 /* Make sure the start of the array data table is in range. */
2136 if (!IsOffsetInRange(dex_pc, end_dex_pc, array_data_offset)) {
2137 FailTargetOffsetOutOfRange(dex_pc, end_dex_pc, array_data_offset);
2138 return false;
2139 }
2140 // Make sure the array-data is marked as an opcode.
2141 // This ensures that it was reached when traversing the code in `ComputeWidthsAndCountOps()`.
2142 uint32_t array_data_dex_pc = dex_pc + array_data_offset;
2143 if (UNLIKELY(!GetInstructionFlags(array_data_dex_pc).IsOpcode())) {
2144 FailTargetMidInstruction(dex_pc, array_data_dex_pc);
2145 return false;
2146 }
2147 // Make sure the table is at an even dex pc, that is, 32-bit aligned.
2148 if (UNLIKELY(!IsAligned<2>(array_data_dex_pc))) {
2149 FailUnalignedTableDexPc(dex_pc, array_data_dex_pc);
2150 return false;
2151 }
2152 const Instruction* array_data = inst->RelativeAt(array_data_offset);
2153 DCHECK_EQ(array_data, &code_item_accessor_.InstructionAt(array_data_dex_pc));
2154 DCHECK_ALIGNED(array_data, 4u);
2155 // Make sure the array data has the correct signature.
2156 if (UNLIKELY(array_data->Fetch16(0) != Instruction::kArrayDataSignature)) {
2157 FailBadArrayDataSignature(dex_pc, array_data_dex_pc);
2158 return false;
2159 }
2160 // The length of the array data has been verified by `ComputeWidthsAndCountOps()`.
2161 DCHECK_LT(array_data_dex_pc, end_dex_pc);
2162 DCHECK_LE(array_data->SizeInCodeUnits(), end_dex_pc - array_data_dex_pc);
2163 return true;
2164 }
2165
2166 template <Instruction::Format kFormat>
CheckAndMarkBranchTarget(uint32_t dex_pc,uint32_t end_dex_pc,const Instruction * inst,uint16_t inst_data)2167 bool MethodVerifierImpl::CheckAndMarkBranchTarget(uint32_t dex_pc,
2168 uint32_t end_dex_pc,
2169 const Instruction* inst,
2170 uint16_t inst_data) {
2171 int32_t offset;
2172 if constexpr (kFormat == Instruction::k22t) { // if-<cond>?
2173 offset = inst->VRegC(kFormat);
2174 } else if constexpr (kFormat == Instruction::k21t) { // if-<cond>z?
2175 offset = inst->VRegB(kFormat, /*unused*/ inst_data);
2176 } else { // goto
2177 offset = inst->VRegA(kFormat, inst_data);
2178 }
2179 // Only `goto/32` instruction can target itself. For other instructions `offset` must not be 0.
2180 DCHECK_EQ(kFormat == Instruction::k30t,
2181 code_item_accessor_.InstructionAt(dex_pc).Opcode() == Instruction::GOTO_32);
2182 if (kFormat != Instruction::k30t && UNLIKELY(offset == 0)) {
2183 FailBranchOffsetZero(dex_pc);
2184 return false;
2185 }
2186 if (!IsOffsetInRange(dex_pc, end_dex_pc, offset)) {
2187 FailTargetOffsetOutOfRange(dex_pc, end_dex_pc, offset);
2188 return false;
2189 }
2190 uint32_t target_dex_pc = dex_pc + offset;
2191 if (UNLIKELY(!GetInstructionFlags(target_dex_pc).IsOpcode())) {
2192 FailTargetMidInstruction(dex_pc, target_dex_pc);
2193 return false;
2194 }
2195 Instruction::Code target_opcode = inst->RelativeAt(offset)->Opcode();
2196 if (UNLIKELY(IsMoveResultOrMoveException(target_opcode))) {
2197 FailBranchTargetIsMoveResultOrMoveException(dex_pc, target_dex_pc, target_opcode);
2198 return false;
2199 }
2200 GetModifiableInstructionFlags(target_dex_pc).SetBranchTarget();
2201 return true;
2202 }
2203
GetBranchOffset(uint32_t cur_offset,int32_t * pOffset,bool * pConditional,bool * selfOkay)2204 bool MethodVerifierImpl::GetBranchOffset(uint32_t cur_offset,
2205 int32_t* pOffset,
2206 bool* pConditional,
2207 bool* selfOkay) {
2208 const uint16_t* insns = code_item_accessor_.Insns() + cur_offset;
2209 *pConditional = false;
2210 *selfOkay = false;
2211 switch (*insns & 0xff) {
2212 case Instruction::GOTO:
2213 *pOffset = ((int16_t) *insns) >> 8;
2214 break;
2215 case Instruction::GOTO_32:
2216 *pOffset = insns[1] | (((uint32_t) insns[2]) << 16);
2217 *selfOkay = true;
2218 break;
2219 case Instruction::GOTO_16:
2220 *pOffset = (int16_t) insns[1];
2221 break;
2222 case Instruction::IF_EQ:
2223 case Instruction::IF_NE:
2224 case Instruction::IF_LT:
2225 case Instruction::IF_GE:
2226 case Instruction::IF_GT:
2227 case Instruction::IF_LE:
2228 case Instruction::IF_EQZ:
2229 case Instruction::IF_NEZ:
2230 case Instruction::IF_LTZ:
2231 case Instruction::IF_GEZ:
2232 case Instruction::IF_GTZ:
2233 case Instruction::IF_LEZ:
2234 *pOffset = (int16_t) insns[1];
2235 *pConditional = true;
2236 break;
2237 default:
2238 return false;
2239 }
2240 return true;
2241 }
2242
CheckAndMarkSwitchTargets(uint32_t dex_pc,uint32_t end_dex_pc,const Instruction * inst,uint16_t inst_data)2243 bool MethodVerifierImpl::CheckAndMarkSwitchTargets(uint32_t dex_pc,
2244 uint32_t end_dex_pc,
2245 const Instruction* inst,
2246 uint16_t inst_data) {
2247 int32_t switch_payload_offset = inst->VRegB_31t();
2248 /* Make sure the start of the switch data is in range. */
2249 if (!IsOffsetInRange(dex_pc, end_dex_pc, switch_payload_offset)) {
2250 FailTargetOffsetOutOfRange(dex_pc, end_dex_pc, switch_payload_offset);
2251 return false;
2252 }
2253 // Make sure the switch data is marked as an opcode.
2254 // This ensures that it was reached when traversing the code in `ComputeWidthsAndCountOps()`.
2255 uint32_t switch_payload_dex_pc = dex_pc + switch_payload_offset;
2256 if (UNLIKELY(!GetInstructionFlags(switch_payload_dex_pc).IsOpcode())) {
2257 FailTargetMidInstruction(dex_pc, switch_payload_dex_pc);
2258 return false;
2259 }
2260 // Make sure the switch data is at an even dex pc, that is, 32-bit aligned.
2261 if (UNLIKELY(!IsAligned<2>(switch_payload_dex_pc))) {
2262 FailUnalignedTableDexPc(dex_pc, switch_payload_dex_pc);
2263 return false;
2264 }
2265
2266 /* offset to switch table is a relative branch-style offset */
2267 const Instruction* payload = inst->RelativeAt(switch_payload_offset);
2268 DCHECK_EQ(payload, &code_item_accessor_.InstructionAt(switch_payload_dex_pc));
2269 DCHECK_ALIGNED(payload, 4u);
2270 const uint16_t* switch_insns = reinterpret_cast<const uint16_t*>(payload);
2271
2272 bool is_packed_switch = inst->Opcode(inst_data) == Instruction::PACKED_SWITCH;
2273 DCHECK_IMPLIES(!is_packed_switch, inst->Opcode(inst_data) == Instruction::SPARSE_SWITCH);
2274
2275 uint32_t switch_count = switch_insns[1];
2276 int32_t targets_offset;
2277 uint16_t expected_signature;
2278 if (is_packed_switch) {
2279 /* 0=sig, 1=count, 2/3=firstKey */
2280 targets_offset = 4;
2281 expected_signature = Instruction::kPackedSwitchSignature;
2282 } else {
2283 /* 0=sig, 1=count, 2..count*2 = keys */
2284 targets_offset = 2 + 2 * switch_count;
2285 expected_signature = Instruction::kSparseSwitchSignature;
2286 }
2287 uint16_t signature = switch_insns[0];
2288 if (UNLIKELY(signature != expected_signature)) {
2289 FailBadSwitchPayloadSignature(dex_pc, switch_payload_dex_pc, signature, expected_signature);
2290 return false;
2291 }
2292 // The table size has been verified in `ComputeWidthsAndCountOps()`.
2293 uint32_t table_size = targets_offset + switch_count * 2;
2294 DCHECK_LT(switch_payload_dex_pc, end_dex_pc);
2295 DCHECK_LE(table_size, end_dex_pc - switch_payload_dex_pc);
2296
2297 constexpr int32_t keys_offset = 2;
2298 if (switch_count > 1) {
2299 if (is_packed_switch) {
2300 /* for a packed switch, verify that keys do not overflow int32 */
2301 int32_t first_key = switch_insns[keys_offset] | (switch_insns[keys_offset + 1] << 16);
2302 int32_t max_first_key =
2303 std::numeric_limits<int32_t>::max() - (static_cast<int32_t>(switch_count) - 1);
2304 if (UNLIKELY(first_key > max_first_key)) {
2305 FailPackedSwitchKeyOverflow(dex_pc, switch_payload_dex_pc, first_key, switch_count);
2306 return false;
2307 }
2308 } else {
2309 /* for a sparse switch, verify the keys are in ascending order */
2310 int32_t last_key = switch_insns[keys_offset] | (switch_insns[keys_offset + 1] << 16);
2311 for (uint32_t targ = 1; targ < switch_count; targ++) {
2312 int32_t key =
2313 static_cast<int32_t>(switch_insns[keys_offset + targ * 2]) |
2314 static_cast<int32_t>(switch_insns[keys_offset + targ * 2 + 1] << 16);
2315 if (UNLIKELY(key <= last_key)) {
2316 FailSparseSwitchPayloadKeyOrder(dex_pc, switch_payload_dex_pc, last_key, key);
2317 return false;
2318 }
2319 last_key = key;
2320 }
2321 }
2322 }
2323 /* verify each switch target */
2324 for (uint32_t targ = 0; targ < switch_count; targ++) {
2325 int32_t offset = static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) |
2326 static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16);
2327 if (!IsOffsetInRange(dex_pc, end_dex_pc, offset)) {
2328 FailSwitchTargetOffsetOutOfRange(dex_pc, end_dex_pc, switch_payload_dex_pc, offset, targ);
2329 return false;
2330 }
2331 uint32_t target_dex_pc = dex_pc + offset;
2332 if (UNLIKELY(!GetInstructionFlags(target_dex_pc).IsOpcode())) {
2333 FailSwitchTargetMidInstruction(dex_pc, target_dex_pc, switch_payload_dex_pc, targ);
2334 return false;
2335 }
2336 Instruction::Code target_opcode = inst->RelativeAt(offset)->Opcode();
2337 if (UNLIKELY(IsMoveResultOrMoveException(target_opcode))) {
2338 FailSwitchTargetIsMoveResultOrMoveException(
2339 dex_pc, target_dex_pc, target_opcode, switch_payload_dex_pc, targ);
2340 return false;
2341 }
2342 GetModifiableInstructionFlags(target_dex_pc).SetBranchTarget();
2343 }
2344 return true;
2345 }
2346
2347 template <bool kVerifierDebug>
VerifyCodeFlow()2348 bool MethodVerifier<kVerifierDebug>::VerifyCodeFlow() {
2349 const uint16_t registers_size = code_item_accessor_.RegistersSize();
2350
2351 /* Create and initialize table holding register status */
2352 reg_table_.Init(insn_flags_.get(),
2353 code_item_accessor_.InsnsSizeInCodeUnits(),
2354 registers_size,
2355 allocator_,
2356 interesting_dex_pc_);
2357
2358 work_line_.reset(RegisterLine::Create(registers_size, allocator_));
2359 saved_line_.reset(RegisterLine::Create(registers_size, allocator_));
2360
2361 /* Initialize register types of method arguments. */
2362 if (!SetTypesFromSignature()) {
2363 DCHECK_NE(failures_.size(), 0U);
2364 std::string prepend("Bad signature in ");
2365 prepend += dex_file_->PrettyMethod(dex_method_idx_);
2366 PrependToLastFailMessage(prepend);
2367 return false;
2368 }
2369 // We may have a runtime failure here, clear.
2370 flags_.have_pending_runtime_throw_failure_ = false;
2371
2372 /* Perform code flow verification. */
2373 bool res = LIKELY(monitor_enter_dex_pcs_ == nullptr)
2374 ? CodeFlowVerifyMethod</*kMonitorDexPCs=*/ false>()
2375 : CodeFlowVerifyMethod</*kMonitorDexPCs=*/ true>();
2376 if (UNLIKELY(!res)) {
2377 DCHECK_NE(failures_.size(), 0U);
2378 return false;
2379 }
2380 return true;
2381 }
2382
Dump(VariableIndentationOutputStream * vios)2383 void MethodVerifierImpl::Dump(VariableIndentationOutputStream* vios) {
2384 if (!code_item_accessor_.HasCodeItem()) {
2385 vios->Stream() << "Native method\n";
2386 return;
2387 }
2388 {
2389 vios->Stream() << "Register Types:\n";
2390 ScopedIndentation indent1(vios);
2391 reg_types_.Dump(vios->Stream());
2392 }
2393 vios->Stream() << "Dumping instructions and register lines:\n";
2394 ScopedIndentation indent1(vios);
2395
2396 for (const DexInstructionPcPair& inst : code_item_accessor_) {
2397 const size_t dex_pc = inst.DexPc();
2398
2399 // Might be asked to dump before the table is initialized.
2400 if (reg_table_.IsInitialized()) {
2401 RegisterLine* reg_line = reg_table_.GetLine(dex_pc);
2402 if (reg_line != nullptr) {
2403 vios->Stream() << reg_line->Dump(this) << "\n";
2404 }
2405 }
2406
2407 vios->Stream()
2408 << StringPrintf("0x%04zx", dex_pc) << ": " << GetInstructionFlags(dex_pc).ToString() << " ";
2409 const bool kDumpHexOfInstruction = false;
2410 if (kDumpHexOfInstruction) {
2411 vios->Stream() << inst->DumpHex(5) << " ";
2412 }
2413 vios->Stream() << inst->DumpString(dex_file_) << "\n";
2414 }
2415 }
2416
SetTypesFromSignature()2417 bool MethodVerifierImpl::SetTypesFromSignature() {
2418 RegisterLine* reg_line = reg_table_.GetLine(0);
2419
2420 // Should have been verified earlier.
2421 DCHECK_GE(code_item_accessor_.RegistersSize(), code_item_accessor_.InsSize());
2422
2423 uint32_t arg_start = code_item_accessor_.RegistersSize() - code_item_accessor_.InsSize();
2424 size_t expected_args = code_item_accessor_.InsSize(); /* long/double count as two */
2425
2426 // Include the "this" pointer.
2427 size_t cur_arg = 0;
2428 if (!IsStatic()) {
2429 if (expected_args == 0) {
2430 // Expect at least a receiver.
2431 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected 0 args, but method is not static";
2432 return false;
2433 }
2434
2435 // If this is a constructor for a class other than java.lang.Object, mark the first ("this")
2436 // argument as uninitialized. This restricts field access until the superclass constructor is
2437 // called.
2438 const RegType& declaring_class = GetDeclaringClass();
2439 if (IsConstructor()) {
2440 if (declaring_class.IsJavaLangObject()) {
2441 // "this" is implicitly initialized.
2442 reg_line->SetThisInitialized();
2443 reg_line->SetRegisterType<LockOp::kClear>(arg_start + cur_arg, declaring_class);
2444 } else {
2445 reg_line->SetRegisterType<LockOp::kClear>(
2446 arg_start + cur_arg,
2447 reg_types_.UninitializedThisArgument(declaring_class));
2448 }
2449 } else {
2450 reg_line->SetRegisterType<LockOp::kClear>(arg_start + cur_arg, declaring_class);
2451 }
2452 cur_arg++;
2453 }
2454
2455 const dex::ProtoId& proto_id =
2456 dex_file_->GetMethodPrototype(dex_file_->GetMethodId(dex_method_idx_));
2457 DexFileParameterIterator iterator(*dex_file_, proto_id);
2458
2459 for (; iterator.HasNext(); iterator.Next()) {
2460 const char* descriptor = iterator.GetDescriptor();
2461 if (descriptor == nullptr) {
2462 LOG(FATAL) << "Null descriptor";
2463 }
2464 if (cur_arg >= expected_args) {
2465 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args
2466 << " args, found more (" << descriptor << ")";
2467 return false;
2468 }
2469 switch (descriptor[0]) {
2470 case 'L':
2471 case '[':
2472 // We assume that reference arguments are initialized. The only way it could be otherwise
2473 // (assuming the caller was verified) is if the current method is <init>, but in that case
2474 // it's effectively considered initialized the instant we reach here (in the sense that we
2475 // can return without doing anything or call virtual methods).
2476 {
2477 // Note: don't check access. No error would be thrown for declaring or passing an
2478 // inaccessible class. Only actual accesses to fields or methods will.
2479 const RegType& reg_type = ResolveClass<CheckAccess::kNo>(iterator.GetTypeIdx());
2480 if (!reg_type.IsNonZeroReferenceTypes()) {
2481 DCHECK(HasFailures());
2482 return false;
2483 }
2484 reg_line->SetRegisterType<LockOp::kClear>(arg_start + cur_arg, reg_type);
2485 }
2486 break;
2487 case 'Z':
2488 reg_line->SetRegisterType(arg_start + cur_arg, RegType::Kind::kBoolean);
2489 break;
2490 case 'C':
2491 reg_line->SetRegisterType(arg_start + cur_arg, RegType::Kind::kChar);
2492 break;
2493 case 'B':
2494 reg_line->SetRegisterType(arg_start + cur_arg, RegType::Kind::kByte);
2495 break;
2496 case 'I':
2497 reg_line->SetRegisterType(arg_start + cur_arg, RegType::Kind::kInteger);
2498 break;
2499 case 'S':
2500 reg_line->SetRegisterType(arg_start + cur_arg, RegType::Kind::kShort);
2501 break;
2502 case 'F':
2503 reg_line->SetRegisterType(arg_start + cur_arg, RegType::Kind::kFloat);
2504 break;
2505 case 'J':
2506 case 'D': {
2507 if (cur_arg + 1 >= expected_args) {
2508 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args
2509 << " args, found more (" << descriptor << ")";
2510 return false;
2511 }
2512
2513 RegType::Kind lo_half;
2514 RegType::Kind hi_half;
2515 if (descriptor[0] == 'J') {
2516 lo_half = RegType::kLongLo;
2517 hi_half = RegType::kLongHi;
2518 } else {
2519 lo_half = RegType::kDoubleLo;
2520 hi_half = RegType::kDoubleHi;
2521 }
2522 reg_line->SetRegisterTypeWide(arg_start + cur_arg, lo_half, hi_half);
2523 cur_arg++;
2524 break;
2525 }
2526 default:
2527 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected signature type char '"
2528 << descriptor << "'";
2529 return false;
2530 }
2531 cur_arg++;
2532 }
2533 if (cur_arg != expected_args) {
2534 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args
2535 << " arguments, found " << cur_arg;
2536 return false;
2537 }
2538 // Dex file verifier ensures that all valid type indexes reference valid descriptors.
2539 DCHECK(IsValidDescriptor(dex_file_->GetReturnTypeDescriptor(proto_id)));
2540 return true;
2541 }
2542
2543 COLD_ATTR
HandleMonitorDexPcsWorkLine(std::vector<::art::verifier::MethodVerifier::DexLockInfo> * monitor_enter_dex_pcs,RegisterLine * work_line)2544 void HandleMonitorDexPcsWorkLine(
2545 std::vector<::art::verifier::MethodVerifier::DexLockInfo>* monitor_enter_dex_pcs,
2546 RegisterLine* work_line) {
2547 monitor_enter_dex_pcs->clear(); // The new work line is more accurate than the previous one.
2548
2549 std::map<uint32_t, ::art::verifier::MethodVerifier::DexLockInfo> depth_to_lock_info;
2550 auto collector = [&](uint32_t dex_reg, uint32_t depth) {
2551 auto insert_pair = depth_to_lock_info.emplace(
2552 depth, ::art::verifier::MethodVerifier::DexLockInfo(depth));
2553 auto it = insert_pair.first;
2554 auto set_insert_pair = it->second.dex_registers.insert(dex_reg);
2555 DCHECK(set_insert_pair.second);
2556 };
2557 work_line->IterateRegToLockDepths(collector);
2558 for (auto& pair : depth_to_lock_info) {
2559 monitor_enter_dex_pcs->push_back(pair.second);
2560 // Map depth to dex PC.
2561 monitor_enter_dex_pcs->back().dex_pc = work_line->GetMonitorEnterDexPc(pair.second.dex_pc);
2562 }
2563 }
2564
2565 template <bool kVerifierDebug>
2566 template <bool kMonitorDexPCs>
CodeFlowVerifyMethod()2567 bool MethodVerifier<kVerifierDebug>::CodeFlowVerifyMethod() {
2568 const uint16_t* insns = code_item_accessor_.Insns();
2569 const uint32_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits();
2570
2571 /* Begin by marking the first instruction as "changed". */
2572 GetModifiableInstructionFlags(0).SetChanged();
2573 uint32_t start_guess = 0;
2574
2575 /* Continue until no instructions are marked "changed". */
2576 while (true) {
2577 if (allow_thread_suspension_) {
2578 self_->AllowThreadSuspension();
2579 }
2580 // Find the first marked one. Use "start_guess" as a way to find one quickly.
2581 uint32_t insn_idx = start_guess;
2582 for (; insn_idx < insns_size; insn_idx++) {
2583 if (GetInstructionFlags(insn_idx).IsChanged())
2584 break;
2585 }
2586 if (insn_idx == insns_size) {
2587 if (start_guess != 0) {
2588 /* try again, starting from the top */
2589 start_guess = 0;
2590 continue;
2591 } else {
2592 /* all flags are clear */
2593 break;
2594 }
2595 }
2596 // We carry the working set of registers from instruction to instruction. If this address can
2597 // be the target of a branch (or throw) instruction, or if we're skipping around chasing
2598 // "changed" flags, we need to load the set of registers from the table.
2599 // Because we always prefer to continue on to the next instruction, we should never have a
2600 // situation where we have a stray "changed" flag set on an instruction that isn't a branch
2601 // target.
2602 work_insn_idx_ = insn_idx;
2603 if (GetInstructionFlags(insn_idx).IsBranchTarget()) {
2604 work_line_->CopyFromLine(reg_table_.GetLine(insn_idx));
2605 } else if (kIsDebugBuild) {
2606 /*
2607 * Consistency check: retrieve the stored register line (assuming
2608 * a full table) and make sure it actually matches.
2609 */
2610 RegisterLine* register_line = reg_table_.GetLine(insn_idx);
2611 if (register_line != nullptr) {
2612 if (work_line_->CompareLine(register_line) != 0) {
2613 Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
2614 LOG(FATAL_WITHOUT_ABORT) << InfoMessages().view();
2615 LOG(FATAL) << "work_line diverged in " << dex_file_->PrettyMethod(dex_method_idx_)
2616 << "@" << reinterpret_cast<void*>(work_insn_idx_) << "\n"
2617 << " work_line=" << work_line_->Dump(this) << "\n"
2618 << " expected=" << register_line->Dump(this);
2619 }
2620 }
2621 }
2622
2623 // If we're doing FindLocksAtDexPc, check whether we're at the dex pc we care about.
2624 // We want the state _before_ the instruction, for the case where the dex pc we're
2625 // interested in is itself a monitor-enter instruction (which is a likely place
2626 // for a thread to be suspended).
2627 if (kMonitorDexPCs && UNLIKELY(work_insn_idx_ == interesting_dex_pc_)) {
2628 HandleMonitorDexPcsWorkLine(monitor_enter_dex_pcs_, work_line_.get());
2629 }
2630
2631 if (UNLIKELY(!CodeFlowVerifyInstruction(&start_guess))) {
2632 DCHECK(flags_.have_pending_hard_failure_);
2633 if (IsAotMode()) {
2634 /* When AOT compiling, check that the last failure is a hard failure */
2635 DCHECK(!failures_.empty());
2636 if (failures_.back().error != VERIFY_ERROR_BAD_CLASS_HARD) {
2637 LOG(ERROR) << "Pending failures:";
2638 for (const VerifyErrorAndMessage& veam : failures_) {
2639 LOG(ERROR) << veam.error << " " << veam.message.view();
2640 }
2641 LOG(FATAL) << "Pending hard failure, but last failure not hard.";
2642 }
2643 }
2644 if (kVerifierDebug) {
2645 InfoMessages() << "Rejecting opcode "
2646 << code_item_accessor_.InstructionAt(work_insn_idx_).DumpString(dex_file_);
2647 }
2648
2649 std::string prepend(dex_file_->PrettyMethod(dex_method_idx_));
2650 prepend += " failed to verify: ";
2651 PrependToLastFailMessage(prepend);
2652 return false;
2653 }
2654 /* Clear "changed" and mark as visited. */
2655 DCHECK(!flags_.have_pending_hard_failure_);
2656 GetModifiableInstructionFlags(insn_idx).SetVisited();
2657 GetModifiableInstructionFlags(insn_idx).ClearChanged();
2658 }
2659
2660 if (kVerifierDebug) {
2661 /*
2662 * Scan for dead code. There's nothing "evil" about dead code
2663 * (besides the wasted space), but it indicates a flaw somewhere
2664 * down the line, possibly in the verifier.
2665 *
2666 * If we've substituted "always throw" instructions into the stream,
2667 * we are almost certainly going to have some dead code.
2668 */
2669 int dead_start = -1;
2670
2671 for (const DexInstructionPcPair& inst : code_item_accessor_) {
2672 const uint32_t insn_idx = inst.DexPc();
2673 /*
2674 * Switch-statement data doesn't get "visited" by scanner. It
2675 * may or may not be preceded by a padding NOP (for alignment).
2676 */
2677 if (insns[insn_idx] == Instruction::kPackedSwitchSignature ||
2678 insns[insn_idx] == Instruction::kSparseSwitchSignature ||
2679 insns[insn_idx] == Instruction::kArrayDataSignature ||
2680 (insns[insn_idx] == Instruction::NOP && (insn_idx + 1 < insns_size) &&
2681 (insns[insn_idx + 1] == Instruction::kPackedSwitchSignature ||
2682 insns[insn_idx + 1] == Instruction::kSparseSwitchSignature ||
2683 insns[insn_idx + 1] == Instruction::kArrayDataSignature))) {
2684 GetModifiableInstructionFlags(insn_idx).SetVisited();
2685 }
2686
2687 if (!GetInstructionFlags(insn_idx).IsVisited()) {
2688 if (dead_start < 0) {
2689 dead_start = insn_idx;
2690 }
2691 } else if (dead_start >= 0) {
2692 LogVerifyInfo() << "dead code " << reinterpret_cast<void*>(dead_start)
2693 << "-" << reinterpret_cast<void*>(insn_idx - 1);
2694 dead_start = -1;
2695 }
2696 }
2697 if (dead_start >= 0) {
2698 LogVerifyInfo()
2699 << "dead code " << reinterpret_cast<void*>(dead_start)
2700 << "-" << reinterpret_cast<void*>(code_item_accessor_.InsnsSizeInCodeUnits() - 1);
2701 }
2702 // To dump the state of the verify after a method, do something like:
2703 // if (dex_file_->PrettyMethod(dex_method_idx_) ==
2704 // "boolean java.lang.String.equals(java.lang.Object)") {
2705 // LOG(INFO) << InfoMessages().view();
2706 // }
2707 }
2708 return true;
2709 }
2710
2711 template <bool kVerifierDebug>
CodeFlowVerifyInstruction(uint32_t * start_guess)2712 bool MethodVerifier<kVerifierDebug>::CodeFlowVerifyInstruction(uint32_t* start_guess) {
2713 /*
2714 * Once we finish decoding the instruction, we need to figure out where
2715 * we can go from here. There are three possible ways to transfer
2716 * control to another statement:
2717 *
2718 * (1) Continue to the next instruction. Applies to all but
2719 * unconditional branches, method returns, and exception throws.
2720 * (2) Branch to one or more possible locations. Applies to branches
2721 * and switch statements.
2722 * (3) Exception handlers. Applies to any instruction that can
2723 * throw an exception that is handled by an encompassing "try"
2724 * block.
2725 *
2726 * We can also return, in which case there is no successor instruction
2727 * from this point.
2728 *
2729 * The behavior can be determined from the opcode flags.
2730 */
2731 const uint16_t* insns = code_item_accessor_.Insns() + work_insn_idx_;
2732 const Instruction* inst = Instruction::At(insns);
2733 int opcode_flags = Instruction::FlagsOf(inst->Opcode());
2734
2735 int32_t branch_target = 0;
2736 bool just_set_result = false;
2737 if (kVerifierDebug) {
2738 // Generate processing back trace to debug verifier
2739 LogVerifyInfo() << "Processing " << inst->DumpString(dex_file_) << std::endl
2740 << work_line_->Dump(this);
2741 }
2742
2743 /*
2744 * Make a copy of the previous register state. If the instruction
2745 * can throw an exception, we will copy/merge this into the "catch"
2746 * address rather than work_line, because we don't want the result
2747 * from the "successful" code path (e.g. a check-cast that "improves"
2748 * a type) to be visible to the exception handler.
2749 */
2750 if (((opcode_flags & Instruction::kThrow) != 0 || IsCompatThrow(inst->Opcode())) &&
2751 CurrentInsnFlags()->IsInTry()) {
2752 saved_line_->CopyFromLine(work_line_.get());
2753 } else if (kIsDebugBuild) {
2754 saved_line_->FillWithGarbage();
2755 }
2756 // Per-instruction flag, should not be set here.
2757 DCHECK(!flags_.have_pending_runtime_throw_failure_);
2758
2759
2760 // We need to ensure the work line is consistent while performing validation. When we spot a
2761 // peephole pattern we compute a new line for either the fallthrough instruction or the
2762 // branch target.
2763 RegisterLineArenaUniquePtr branch_line;
2764 RegisterLineArenaUniquePtr fallthrough_line;
2765
2766 using enum RegType::Kind;
2767 uint16_t inst_data = inst->Fetch16(0);
2768 Instruction::Code opcode = inst->Opcode(inst_data);
2769 switch (opcode) {
2770 case Instruction::NOP:
2771 /*
2772 * A "pure" NOP has no effect on anything. Data tables start with
2773 * a signature that looks like a NOP; if we see one of these in
2774 * the course of executing code then we have a problem.
2775 */
2776 if (inst->VRegA_10x(inst_data) != 0) {
2777 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "encountered data table in instruction stream";
2778 return false;
2779 }
2780 break;
2781
2782 case Instruction::MOVE:
2783 if (!VerifyCopyCat1(inst->VRegA_12x(inst_data), inst->VRegB_12x(inst_data))) {
2784 return false;
2785 }
2786 break;
2787 case Instruction::MOVE_FROM16:
2788 if (!VerifyCopyCat1(inst->VRegA_22x(inst_data), inst->VRegB_22x())) {
2789 return false;
2790 }
2791 break;
2792 case Instruction::MOVE_16:
2793 if (!VerifyCopyCat1(inst->VRegA_32x(), inst->VRegB_32x())) {
2794 return false;
2795 }
2796 break;
2797 case Instruction::MOVE_WIDE:
2798 if (!VerifyCopyCat2(inst->VRegA_12x(inst_data), inst->VRegB_12x(inst_data))) {
2799 return false;
2800 }
2801 break;
2802 case Instruction::MOVE_WIDE_FROM16:
2803 if (!VerifyCopyCat2(inst->VRegA_22x(inst_data), inst->VRegB_22x())) {
2804 return false;
2805 }
2806 break;
2807 case Instruction::MOVE_WIDE_16:
2808 if (!VerifyCopyCat2(inst->VRegA_32x(), inst->VRegB_32x())) {
2809 return false;
2810 }
2811 break;
2812 case Instruction::MOVE_OBJECT:
2813 if (!VerifyCopyReference(inst->VRegA_12x(inst_data), inst->VRegB_12x(inst_data))) {
2814 return false;
2815 }
2816 break;
2817 case Instruction::MOVE_OBJECT_FROM16:
2818 if (!VerifyCopyReference(inst->VRegA_22x(inst_data), inst->VRegB_22x())) {
2819 return false;
2820 }
2821 break;
2822 case Instruction::MOVE_OBJECT_16:
2823 if (!VerifyCopyReference(inst->VRegA_32x(), inst->VRegB_32x())) {
2824 return false;
2825 }
2826 break;
2827
2828 /*
2829 * The move-result instructions copy data out of a "pseudo-register"
2830 * with the results from the last method invocation. In practice we
2831 * might want to hold the result in an actual CPU register, so the
2832 * Dalvik spec requires that these only appear immediately after an
2833 * invoke or filled-new-array.
2834 *
2835 * These calls invalidate the "result" register. (This is now
2836 * redundant with the reset done below, but it can make the debug info
2837 * easier to read in some cases.)
2838 */
2839 case Instruction::MOVE_RESULT:
2840 work_line_->CopyResultRegister1(this, inst->VRegA_11x(inst_data), false);
2841 break;
2842 case Instruction::MOVE_RESULT_WIDE:
2843 work_line_->CopyResultRegister2(this, inst->VRegA_11x(inst_data));
2844 break;
2845 case Instruction::MOVE_RESULT_OBJECT:
2846 work_line_->CopyResultRegister1(this, inst->VRegA_11x(inst_data), true);
2847 break;
2848
2849 case Instruction::MOVE_EXCEPTION: {
2850 auto result = HandleMoveException(inst);
2851 if (!result.success) {
2852 return false;
2853 }
2854 DCHECK_NE(opcode_flags & Instruction::kContinue, 0);
2855 if (UNLIKELY(result.skip_verification_of_exception_handler)) {
2856 // Avoid verification of the following exception handler instructions.
2857 opcode_flags &= ~Instruction::kContinue;
2858 }
2859 break;
2860 }
2861
2862 case Instruction::RETURN_VOID:
2863 if (IsInstanceConstructor() && UNLIKELY(!work_line_->CheckConstructorReturn(this))) {
2864 return false;
2865 }
2866 if (!GetMethodReturnType().IsConflict()) {
2867 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void not expected";
2868 return false;
2869 }
2870 break;
2871 case Instruction::RETURN: {
2872 if (IsInstanceConstructor() && UNLIKELY(!work_line_->CheckConstructorReturn(this))) {
2873 return false;
2874 }
2875 /* check the method signature */
2876 const RegType& return_type = GetMethodReturnType();
2877 if (!return_type.IsCategory1Types()) {
2878 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected non-category 1 return type "
2879 << return_type;
2880 return false;
2881 } else {
2882 // Compilers may generate synthetic functions that write byte values into boolean fields.
2883 // Also, it may use integer values for boolean, byte, short, and character return types.
2884 const uint32_t vregA = inst->VRegA_11x(inst_data);
2885 const RegType& src_type = work_line_->GetRegisterType(this, vregA);
2886 bool use_src = ((return_type.IsBoolean() && src_type.IsByte()) ||
2887 ((return_type.IsBoolean() || return_type.IsByte() ||
2888 return_type.IsShort() || return_type.IsChar()) &&
2889 src_type.IsInteger()));
2890 /* check the register contents */
2891 bool success = VerifyRegisterType(vregA, use_src ? src_type : return_type);
2892 if (!success) {
2893 LastFailureMessageStream() << " return-1nr on invalid register v" << vregA;
2894 }
2895 }
2896 break;
2897 }
2898 case Instruction::RETURN_WIDE: {
2899 if (IsInstanceConstructor() && UNLIKELY(!work_line_->CheckConstructorReturn(this))) {
2900 return false;
2901 }
2902 /* check the method signature */
2903 const RegType& return_type = GetMethodReturnType();
2904 if (!return_type.IsCategory2Types()) {
2905 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-wide not expected";
2906 return false;
2907 } else {
2908 /* check the register contents */
2909 const uint32_t vregA = inst->VRegA_11x(inst_data);
2910 bool success = VerifyRegisterTypeWide(vregA, return_type.GetKind());
2911 if (!success) {
2912 LastFailureMessageStream() << " return-wide on invalid register v" << vregA;
2913 }
2914 }
2915 break;
2916 }
2917 case Instruction::RETURN_OBJECT: {
2918 if (IsInstanceConstructor() && UNLIKELY(!work_line_->CheckConstructorReturn(this))) {
2919 return false;
2920 }
2921 const RegType& return_type = GetMethodReturnType();
2922 if (!return_type.IsReferenceTypes()) {
2923 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-object not expected";
2924 return false;
2925 } else {
2926 /* return_type is the *expected* return type, not register value */
2927 DCHECK(!return_type.IsZeroOrNull());
2928 DCHECK(!return_type.IsUninitializedReference());
2929 const uint32_t vregA = inst->VRegA_11x(inst_data);
2930 const RegType& reg_type = work_line_->GetRegisterType(this, vregA);
2931 // Disallow returning undefined, conflict & uninitialized values and verify that the
2932 // reference in vAA is an instance of the "return_type."
2933 if (reg_type.IsUndefined()) {
2934 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning undefined register";
2935 return false;
2936 } else if (reg_type.IsConflict()) {
2937 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning register with conflict";
2938 return false;
2939 } else if (reg_type.IsUninitializedTypes()) {
2940 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning uninitialized object '"
2941 << reg_type << "'";
2942 return false;
2943 } else if (!reg_type.IsReferenceTypes()) {
2944 // We really do expect a reference here.
2945 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-object returns a non-reference type "
2946 << reg_type;
2947 return false;
2948 } else if (!IsAssignableFrom(return_type, reg_type)) {
2949 if (reg_type.IsUnresolvedTypes() || return_type.IsUnresolvedTypes()) {
2950 Fail(VERIFY_ERROR_UNRESOLVED_TYPE_CHECK)
2951 << " can't resolve returned type '" << return_type << "' or '" << reg_type << "'";
2952 } else {
2953 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning '" << reg_type
2954 << "', but expected from declaration '" << return_type << "'";
2955 return false;
2956 }
2957 }
2958 }
2959 break;
2960 }
2961 /* could be boolean, int, float, or a null reference */
2962 case Instruction::CONST_4: {
2963 int32_t val = static_cast<int32_t>(inst->VRegB_11n(inst_data) << 28) >> 28;
2964 work_line_->SetRegisterType(inst->VRegA_11n(inst_data), DetermineCat1Constant(val));
2965 break;
2966 }
2967 case Instruction::CONST_16: {
2968 int16_t val = static_cast<int16_t>(inst->VRegB_21s());
2969 work_line_->SetRegisterType(inst->VRegA_21s(inst_data), DetermineCat1Constant(val));
2970 break;
2971 }
2972 case Instruction::CONST: {
2973 int32_t val = inst->VRegB_31i();
2974 work_line_->SetRegisterType(inst->VRegA_31i(inst_data), DetermineCat1Constant(val));
2975 break;
2976 }
2977 case Instruction::CONST_HIGH16: {
2978 int32_t val = static_cast<int32_t>(inst->VRegB_21h() << 16);
2979 work_line_->SetRegisterType(inst->VRegA_21h(inst_data), DetermineCat1Constant(val));
2980 break;
2981 }
2982 /* could be long or double; resolved upon use */
2983 case Instruction::CONST_WIDE_16:
2984 work_line_->SetRegisterTypeWide(inst->VRegA_21s(inst_data), kConstantLo, kConstantHi);
2985 break;
2986 case Instruction::CONST_WIDE_32:
2987 work_line_->SetRegisterTypeWide(inst->VRegA_31i(inst_data), kConstantLo, kConstantHi);
2988 break;
2989 case Instruction::CONST_WIDE:
2990 work_line_->SetRegisterTypeWide(inst->VRegA_51l(inst_data), kConstantLo, kConstantHi);
2991 break;
2992 case Instruction::CONST_WIDE_HIGH16:
2993 work_line_->SetRegisterTypeWide(inst->VRegA_21h(inst_data), kConstantLo, kConstantHi);
2994 break;
2995 case Instruction::CONST_STRING:
2996 work_line_->SetRegisterType<LockOp::kClear>(
2997 inst->VRegA_21c(inst_data), reg_types_.JavaLangString());
2998 break;
2999 case Instruction::CONST_STRING_JUMBO:
3000 work_line_->SetRegisterType<LockOp::kClear>(
3001 inst->VRegA_31c(inst_data), reg_types_.JavaLangString());
3002 break;
3003 case Instruction::CONST_CLASS: {
3004 // Get type from instruction if unresolved then we need an access check
3005 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
3006 const RegType& res_type = ResolveClass<CheckAccess::kYes>(dex::TypeIndex(inst->VRegB_21c()));
3007 // Register holds class, ie its type is class, on error it will hold Conflict.
3008 work_line_->SetRegisterType<LockOp::kClear>(
3009 inst->VRegA_21c(inst_data),
3010 res_type.IsConflict() ? res_type : reg_types_.JavaLangClass());
3011 break;
3012 }
3013 case Instruction::CONST_METHOD_HANDLE:
3014 work_line_->SetRegisterType<LockOp::kClear>(
3015 inst->VRegA_21c(inst_data), reg_types_.JavaLangInvokeMethodHandle());
3016 break;
3017 case Instruction::CONST_METHOD_TYPE:
3018 work_line_->SetRegisterType<LockOp::kClear>(
3019 inst->VRegA_21c(inst_data), reg_types_.JavaLangInvokeMethodType());
3020 break;
3021 case Instruction::MONITOR_ENTER: {
3022 uint32_t vreg = inst->VRegA_11x(inst_data);
3023 const RegType& reg_type = work_line_->GetRegisterType(this, vreg);
3024 if (!reg_type.IsReferenceTypes()) {
3025 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "monitor-enter on non-object (" << reg_type << ")";
3026 return false;
3027 }
3028 work_line_->PushMonitor(this, vreg, reg_type, work_insn_idx_);
3029 // Check whether the previous instruction is a move-object with vAA as a source, creating
3030 // untracked lock aliasing.
3031 if (0 != work_insn_idx_ && !GetInstructionFlags(work_insn_idx_).IsBranchTarget()) {
3032 uint32_t prev_idx = work_insn_idx_ - 1;
3033 while (0 != prev_idx && !GetInstructionFlags(prev_idx).IsOpcode()) {
3034 prev_idx--;
3035 }
3036 const Instruction& prev_inst = code_item_accessor_.InstructionAt(prev_idx);
3037 switch (prev_inst.Opcode()) {
3038 case Instruction::MOVE_OBJECT:
3039 case Instruction::MOVE_OBJECT_16:
3040 case Instruction::MOVE_OBJECT_FROM16:
3041 if (static_cast<uint32_t>(prev_inst.VRegB()) == vreg) {
3042 // Redo the copy. This won't change the register types, but update the lock status
3043 // for the aliased register.
3044 work_line_->CopyReference(prev_inst.VRegA(), vreg, reg_type);
3045 }
3046 break;
3047
3048 // Catch a case of register aliasing when two registers are linked to the same
3049 // java.lang.Class object via two consequent const-class instructions immediately
3050 // preceding monitor-enter called on one of those registers.
3051 case Instruction::CONST_CLASS: {
3052 // Get the second previous instruction.
3053 if (prev_idx == 0 || GetInstructionFlags(prev_idx).IsBranchTarget()) {
3054 break;
3055 }
3056 prev_idx--;
3057 while (0 != prev_idx && !GetInstructionFlags(prev_idx).IsOpcode()) {
3058 prev_idx--;
3059 }
3060 const Instruction& prev2_inst = code_item_accessor_.InstructionAt(prev_idx);
3061
3062 // Match the pattern "const-class; const-class; monitor-enter;"
3063 if (prev2_inst.Opcode() != Instruction::CONST_CLASS) {
3064 break;
3065 }
3066
3067 // Ensure both const-classes are called for the same type_idx.
3068 if (prev_inst.VRegB_21c() != prev2_inst.VRegB_21c()) {
3069 break;
3070 }
3071
3072 // Update the lock status for the aliased register.
3073 uint32_t prev_inst_vregA = prev_inst.VRegA_21c(prev_inst.Fetch16(0));
3074 uint32_t prev2_inst_vregA = prev2_inst.VRegA_21c(prev2_inst.Fetch16(0));
3075 if (prev_inst_vregA == vreg) {
3076 work_line_->CopyReference(prev2_inst_vregA, vreg, reg_type);
3077 } else if (prev2_inst_vregA == vreg) {
3078 work_line_->CopyReference(prev_inst_vregA, vreg, reg_type);
3079 }
3080 break;
3081 }
3082
3083 default: // Other instruction types ignored.
3084 break;
3085 }
3086 }
3087 break;
3088 }
3089 case Instruction::MONITOR_EXIT: {
3090 /*
3091 * monitor-exit instructions are odd. They can throw exceptions,
3092 * but when they do they act as if they succeeded and the PC is
3093 * pointing to the following instruction. (This behavior goes back
3094 * to the need to handle asynchronous exceptions, a now-deprecated
3095 * feature that Dalvik doesn't support.)
3096 *
3097 * In practice we don't need to worry about this. The only
3098 * exceptions that can be thrown from monitor-exit are for a
3099 * null reference and -exit without a matching -enter. If the
3100 * structured locking checks are working, the former would have
3101 * failed on the -enter instruction, and the latter is impossible.
3102 *
3103 * This is fortunate, because issue 3221411 prevents us from
3104 * chasing the "can throw" path when monitor verification is
3105 * enabled. If we can fully verify the locking we can ignore
3106 * some catch blocks (which will show up as "dead" code when
3107 * we skip them here); if we can't, then the code path could be
3108 * "live" so we still need to check it.
3109 */
3110 opcode_flags &= ~Instruction::kThrow;
3111 uint32_t vreg = inst->VRegA_11x(inst_data);
3112 const RegType& reg_type = work_line_->GetRegisterType(this, vreg);
3113 if (!reg_type.IsReferenceTypes()) {
3114 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "monitor-exit on non-object (" << reg_type << ")";
3115 return false;
3116 }
3117 work_line_->PopMonitor(this, vreg, reg_type);
3118 break;
3119 }
3120 case Instruction::CHECK_CAST:
3121 case Instruction::INSTANCE_OF: {
3122 /*
3123 * If this instruction succeeds, we will "downcast" register vA to the type in vB. (This
3124 * could be a "upcast" -- not expected, so we don't try to address it.)
3125 *
3126 * If it fails, an exception is thrown, which we deal with later by ignoring the update to
3127 * dec_insn.vA when branching to a handler.
3128 */
3129 const bool is_checkcast = (inst->Opcode() == Instruction::CHECK_CAST);
3130 const dex::TypeIndex type_idx((is_checkcast) ? inst->VRegB_21c() : inst->VRegC_22c());
3131 const RegType& res_type = ResolveClass<CheckAccess::kYes>(type_idx);
3132 if (res_type.IsConflict()) {
3133 // If this is a primitive type, fail HARD.
3134 ObjPtr<mirror::Class> klass = GetClassLinker()->LookupResolvedType(
3135 type_idx, dex_cache_.Get(), class_loader_.Get());
3136 if (klass != nullptr && klass->IsPrimitive()) {
3137 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "using primitive type "
3138 << dex_file_->GetTypeDescriptorView(type_idx) << " in instanceof in "
3139 << GetDeclaringClass();
3140 return false;
3141 }
3142
3143 DCHECK_NE(failures_.size(), 0U);
3144 if (!is_checkcast) {
3145 work_line_->SetRegisterType(inst->VRegA_22c(inst_data), kBoolean);
3146 }
3147 break; // bad class
3148 }
3149 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
3150 uint32_t orig_type_reg =
3151 (is_checkcast) ? inst->VRegA_21c(inst_data) : inst->VRegB_22c(inst_data);
3152 const RegType& orig_type = work_line_->GetRegisterType(this, orig_type_reg);
3153 if (!res_type.IsNonZeroReferenceTypes()) {
3154 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << opcode << " on unexpected class " << res_type;
3155 return false;
3156 } else if (!orig_type.IsReferenceTypes()) {
3157 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << opcode << " on non-reference in v" << orig_type_reg;
3158 return false;
3159 } else if (orig_type.IsUninitializedTypes()) {
3160 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << opcode << " on uninitialized reference in v"
3161 << orig_type_reg;
3162 return false;
3163 } else {
3164 if (is_checkcast) {
3165 work_line_->SetRegisterType<LockOp::kKeep>(inst->VRegA_21c(inst_data), res_type);
3166 } else {
3167 work_line_->SetRegisterType(inst->VRegA_22c(inst_data), kBoolean);
3168 }
3169 }
3170 break;
3171 }
3172 case Instruction::ARRAY_LENGTH: {
3173 const RegType& res_type = work_line_->GetRegisterType(this, inst->VRegB_12x(inst_data));
3174 if (!res_type.IsReferenceTypes() || (!res_type.IsArrayTypes() && !res_type.IsZeroOrNull())) {
3175 // ie not an array or null
3176 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type;
3177 return false;
3178 }
3179 work_line_->SetRegisterType(inst->VRegA_12x(inst_data), kInteger);
3180 break;
3181 }
3182 case Instruction::NEW_INSTANCE: {
3183 const RegType& res_type = ResolveClass<CheckAccess::kYes>(dex::TypeIndex(inst->VRegB_21c()));
3184 // Dex file verifier ensures that all valid type indexes reference valid descriptors and the
3185 // `CheckNewInstance()` ensures that the descriptor starts with an `L` before we get to the
3186 // code flow verification. So, we should not see a conflict (void) or a primitive type here.
3187 DCHECK(res_type.IsJavaLangObject() ||
3188 res_type.IsReference() ||
3189 res_type.IsUnresolvedReference()) << res_type;
3190 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
3191 // can't create an instance of an interface or abstract class */
3192 if (!res_type.IsInstantiableTypes()) {
3193 Fail(VERIFY_ERROR_INSTANTIATION)
3194 << "new-instance on primitive, interface or abstract class" << res_type;
3195 // Soft failure so carry on to set register type.
3196 }
3197 const RegType& uninit_type = reg_types_.Uninitialized(res_type);
3198 // Add the new uninitialized reference to the register state and record the allocation dex pc.
3199 uint32_t vA = inst->VRegA_21c(inst_data);
3200 work_line_->DCheckUniqueNewInstanceDexPc(this, work_insn_idx_);
3201 work_line_->SetRegisterTypeForNewInstance(vA, uninit_type, work_insn_idx_);
3202 break;
3203 }
3204 case Instruction::NEW_ARRAY: {
3205 // Make sure the "size" register has a valid type.
3206 if (!VerifyRegisterType(inst->VRegB_22c(), RegType::Kind::kInteger)) {
3207 return false;
3208 }
3209 // Dex file verifier ensures that all valid type indexes reference valid descriptors and the
3210 // `CheckNewArray()` ensures that the descriptor starts with an `[` before we get to the
3211 // code flow verification. So, we should see only array types here.
3212 const RegType& res_type = ResolveClass<CheckAccess::kYes>(dex::TypeIndex(inst->VRegC_22c()));
3213 DCHECK(res_type.IsArrayTypes());
3214 // Set the register type to the array class.
3215 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_22c(), res_type);
3216 break;
3217 }
3218 case Instruction::FILLED_NEW_ARRAY:
3219 if (!VerifyFilledNewArray(inst, /*is_range=*/ false)) {
3220 return false;
3221 }
3222 just_set_result = true; // Filled new array sets result register
3223 break;
3224 case Instruction::FILLED_NEW_ARRAY_RANGE:
3225 if (!VerifyFilledNewArray(inst, /*is_range=*/ true)) {
3226 return false;
3227 }
3228 just_set_result = true; // Filled new array range sets result register
3229 break;
3230 case Instruction::CMPL_FLOAT:
3231 case Instruction::CMPG_FLOAT:
3232 if (!CheckBinaryOp(inst, inst_data, kInteger, kFloat, kFloat, /*check_boolean_op=*/ false)) {
3233 return false;
3234 }
3235 break;
3236 case Instruction::CMPL_DOUBLE:
3237 case Instruction::CMPG_DOUBLE:
3238 if (!CheckBinaryOpWideCmp(inst, inst_data, kInteger, kDoubleLo, kDoubleLo)) {
3239 return false;
3240 }
3241 break;
3242 case Instruction::CMP_LONG:
3243 if (!CheckBinaryOpWideCmp(inst, inst_data, kInteger, kLongLo, kLongLo)) {
3244 return false;
3245 }
3246 break;
3247 case Instruction::THROW: {
3248 const RegType& res_type = work_line_->GetRegisterType(this, inst->VRegA_11x(inst_data));
3249 if (!IsAssignableFrom(reg_types_.JavaLangThrowable(), res_type)) {
3250 if (res_type.IsUninitializedTypes()) {
3251 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "thrown exception not initialized";
3252 return false;
3253 } else if (!res_type.IsReferenceTypes()) {
3254 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "thrown value of non-reference type " << res_type;
3255 return false;
3256 } else {
3257 bool unresolved = res_type.IsUnresolvedTypes();
3258 Fail(unresolved ? VERIFY_ERROR_UNRESOLVED_TYPE_CHECK : VERIFY_ERROR_BAD_CLASS_HARD)
3259 << "thrown class " << res_type << " not instanceof Throwable";
3260 if (!unresolved) {
3261 return false;
3262 }
3263 }
3264 }
3265 break;
3266 }
3267 case Instruction::GOTO:
3268 case Instruction::GOTO_16:
3269 case Instruction::GOTO_32:
3270 /* no effect on or use of registers */
3271 break;
3272
3273 case Instruction::PACKED_SWITCH:
3274 case Instruction::SPARSE_SWITCH:
3275 /* verify that vAA is an integer, or can be converted to one */
3276 VerifyRegisterType(inst->VRegA_31t(inst_data), kInteger);
3277 break;
3278
3279 case Instruction::FILL_ARRAY_DATA: {
3280 /* Similar to the verification done for APUT */
3281 const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegA_31t(inst_data));
3282 /* array_type can be null if the reg type is Zero */
3283 if (!array_type.IsZeroOrNull()) {
3284 if (!array_type.IsArrayTypes()) {
3285 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with array type "
3286 << array_type;
3287 return false;
3288 } else if (array_type.IsUnresolvedTypes()) {
3289 // If it's an unresolved array type, it must be non-primitive.
3290 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data for array of type "
3291 << array_type;
3292 return false;
3293 } else {
3294 const RegType& component_type = reg_types_.GetComponentType(array_type);
3295 DCHECK(!component_type.IsConflict());
3296 if (component_type.IsNonZeroReferenceTypes()) {
3297 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with component type "
3298 << component_type;
3299 return false;
3300 } else {
3301 // Now verify if the element width in the table matches the element width declared in
3302 // the array. The signature has been verified by `CheckArrayData()`.
3303 const uint16_t* array_data =
3304 insns + (insns[1] | (static_cast<int32_t>(insns[2]) << 16));
3305 DCHECK_EQ(array_data[0], Instruction::kArrayDataSignature);
3306 size_t elem_width = Primitive::ComponentSize(component_type.GetPrimitiveType());
3307 // Since we don't compress the data in Dex, expect to see equal width of data stored
3308 // in the table and expected from the array class.
3309 if (array_data[1] != elem_width) {
3310 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-data size mismatch (" << array_data[1]
3311 << " vs " << elem_width << ")";
3312 return false;
3313 }
3314 }
3315 }
3316 }
3317 break;
3318 }
3319 case Instruction::IF_EQ:
3320 case Instruction::IF_NE: {
3321 const RegType& reg_type1 = work_line_->GetRegisterType(this, inst->VRegA_22t(inst_data));
3322 const RegType& reg_type2 = work_line_->GetRegisterType(this, inst->VRegB_22t(inst_data));
3323 bool mismatch = false;
3324 if (reg_type1.IsZeroOrNull()) { // zero then integral or reference expected
3325 mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes();
3326 } else if (reg_type1.IsReferenceTypes()) { // both references?
3327 mismatch = !reg_type2.IsReferenceTypes();
3328 } else { // both integral?
3329 mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes();
3330 }
3331 if (mismatch) {
3332 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to if-eq/if-ne (" << reg_type1 << ","
3333 << reg_type2 << ") must both be references or integral";
3334 return false;
3335 }
3336 break;
3337 }
3338 case Instruction::IF_LT:
3339 case Instruction::IF_GE:
3340 case Instruction::IF_GT:
3341 case Instruction::IF_LE: {
3342 const RegType& reg_type1 = work_line_->GetRegisterType(this, inst->VRegA_22t(inst_data));
3343 const RegType& reg_type2 = work_line_->GetRegisterType(this, inst->VRegB_22t(inst_data));
3344 if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) {
3345 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to 'if' (" << reg_type1 << ","
3346 << reg_type2 << ") must be integral";
3347 return false;
3348 }
3349 break;
3350 }
3351 case Instruction::IF_EQZ:
3352 case Instruction::IF_NEZ: {
3353 const RegType& reg_type = work_line_->GetRegisterType(this, inst->VRegA_21t(inst_data));
3354 if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) {
3355 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type
3356 << " unexpected as arg to if-eqz/if-nez";
3357 return false;
3358 }
3359
3360 // Find previous instruction - its existence is a precondition to peephole optimization.
3361 if (UNLIKELY(0 == work_insn_idx_)) {
3362 break;
3363 }
3364 uint32_t instance_of_idx = work_insn_idx_ - 1;
3365 while (0 != instance_of_idx && !GetInstructionFlags(instance_of_idx).IsOpcode()) {
3366 instance_of_idx--;
3367 }
3368 // Dex index 0 must be an opcode.
3369 DCHECK(GetInstructionFlags(instance_of_idx).IsOpcode());
3370
3371 const Instruction& instance_of_inst = code_item_accessor_.InstructionAt(instance_of_idx);
3372
3373 /* Check for peep-hole pattern of:
3374 * ...;
3375 * instance-of vX, vY, T;
3376 * ifXXX vX, label ;
3377 * ...;
3378 * label:
3379 * ...;
3380 * and sharpen the type of vY to be type T.
3381 * Note, this pattern can't be if:
3382 * - if there are other branches to this branch,
3383 * - when vX == vY.
3384 */
3385 if (!CurrentInsnFlags()->IsBranchTarget() &&
3386 (Instruction::INSTANCE_OF == instance_of_inst.Opcode()) &&
3387 (inst->VRegA_21t(inst_data) == instance_of_inst.VRegA_22c()) &&
3388 (instance_of_inst.VRegA_22c() != instance_of_inst.VRegB_22c())) {
3389 // Check the type of the instance-of is different than that of registers type, as if they
3390 // are the same there is no work to be done here. Check that the conversion is not to or
3391 // from an unresolved type as type information is imprecise. If the instance-of is to an
3392 // interface then ignore the type information as interfaces can only be treated as Objects
3393 // and we don't want to disallow field and other operations on the object. If the value
3394 // being instance-of checked against is known null (zero) then allow the optimization as
3395 // we didn't have type information. If the merge of the instance-of type with the original
3396 // type is assignable to the original then allow optimization. This check is performed to
3397 // ensure that subsequent merges don't lose type information - such as becoming an
3398 // interface from a class that would lose information relevant to field checks.
3399 //
3400 // Note: do not do an access check. This may mark this with a runtime throw that actually
3401 // happens at the instanceof, not the branch (and branches aren't flagged to throw).
3402 const RegType& orig_type = work_line_->GetRegisterType(this, instance_of_inst.VRegB_22c());
3403 const RegType& cast_type = ResolveClass<CheckAccess::kNo>(
3404 dex::TypeIndex(instance_of_inst.VRegC_22c()));
3405
3406 if (!orig_type.Equals(cast_type) &&
3407 !cast_type.IsUnresolvedTypes() && !orig_type.IsUnresolvedTypes() &&
3408 cast_type.HasClass() && // Could be conflict type, make sure it has a class.
3409 !cast_type.GetClass()->IsInterface() &&
3410 !orig_type.IsZeroOrNull() &&
3411 IsStrictlyAssignableFrom(orig_type, cast_type.Merge(orig_type, ®_types_, this))) {
3412 RegisterLine* update_line = RegisterLine::Create(code_item_accessor_.RegistersSize(),
3413 allocator_);
3414 if (inst->Opcode() == Instruction::IF_EQZ) {
3415 fallthrough_line.reset(update_line);
3416 } else {
3417 branch_line.reset(update_line);
3418 }
3419 update_line->CopyFromLine(work_line_.get());
3420 update_line->SetRegisterType<LockOp::kKeep>(instance_of_inst.VRegB_22c(), cast_type);
3421 if (!GetInstructionFlags(instance_of_idx).IsBranchTarget() && 0 != instance_of_idx) {
3422 // See if instance-of was preceded by a move-object operation, common due to the small
3423 // register encoding space of instance-of, and propagate type information to the source
3424 // of the move-object.
3425 // Note: this is only valid if the move source was not clobbered.
3426 uint32_t move_idx = instance_of_idx - 1;
3427 while (0 != move_idx && !GetInstructionFlags(move_idx).IsOpcode()) {
3428 move_idx--;
3429 }
3430 DCHECK(GetInstructionFlags(move_idx).IsOpcode());
3431 auto maybe_update_fn = [&instance_of_inst, update_line, &cast_type](
3432 uint16_t move_src,
3433 uint16_t move_trg)
3434 REQUIRES_SHARED(Locks::mutator_lock_) {
3435 if (move_trg == instance_of_inst.VRegB_22c() &&
3436 move_src != instance_of_inst.VRegA_22c()) {
3437 update_line->SetRegisterType<LockOp::kKeep>(move_src, cast_type);
3438 }
3439 };
3440 const Instruction& move_inst = code_item_accessor_.InstructionAt(move_idx);
3441 switch (move_inst.Opcode()) {
3442 case Instruction::MOVE_OBJECT:
3443 maybe_update_fn(move_inst.VRegB_12x(), move_inst.VRegA_12x());
3444 break;
3445 case Instruction::MOVE_OBJECT_FROM16:
3446 maybe_update_fn(move_inst.VRegB_22x(), move_inst.VRegA_22x());
3447 break;
3448 case Instruction::MOVE_OBJECT_16:
3449 maybe_update_fn(move_inst.VRegB_32x(), move_inst.VRegA_32x());
3450 break;
3451 default:
3452 break;
3453 }
3454 }
3455 }
3456 }
3457
3458 break;
3459 }
3460 case Instruction::IF_LTZ:
3461 case Instruction::IF_GEZ:
3462 case Instruction::IF_GTZ:
3463 case Instruction::IF_LEZ: {
3464 const RegType& reg_type = work_line_->GetRegisterType(this, inst->VRegA_21t(inst_data));
3465 if (!reg_type.IsIntegralTypes()) {
3466 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type
3467 << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez";
3468 return false;
3469 }
3470 break;
3471 }
3472 case Instruction::AGET_BOOLEAN:
3473 VerifyAGet(inst, reg_types_.Boolean(), true);
3474 break;
3475 case Instruction::AGET_BYTE:
3476 VerifyAGet(inst, reg_types_.Byte(), true);
3477 break;
3478 case Instruction::AGET_CHAR:
3479 VerifyAGet(inst, reg_types_.Char(), true);
3480 break;
3481 case Instruction::AGET_SHORT:
3482 VerifyAGet(inst, reg_types_.Short(), true);
3483 break;
3484 case Instruction::AGET:
3485 VerifyAGet(inst, reg_types_.Integer(), true);
3486 break;
3487 case Instruction::AGET_WIDE:
3488 VerifyAGet(inst, reg_types_.LongLo(), true);
3489 break;
3490 case Instruction::AGET_OBJECT:
3491 VerifyAGet(inst, reg_types_.JavaLangObject(), false);
3492 break;
3493
3494 case Instruction::APUT_BOOLEAN:
3495 VerifyAPut(inst, reg_types_.Boolean(), true);
3496 break;
3497 case Instruction::APUT_BYTE:
3498 VerifyAPut(inst, reg_types_.Byte(), true);
3499 break;
3500 case Instruction::APUT_CHAR:
3501 VerifyAPut(inst, reg_types_.Char(), true);
3502 break;
3503 case Instruction::APUT_SHORT:
3504 VerifyAPut(inst, reg_types_.Short(), true);
3505 break;
3506 case Instruction::APUT:
3507 VerifyAPut(inst, reg_types_.Integer(), true);
3508 break;
3509 case Instruction::APUT_WIDE:
3510 VerifyAPut(inst, reg_types_.LongLo(), true);
3511 break;
3512 case Instruction::APUT_OBJECT:
3513 VerifyAPut(inst, reg_types_.JavaLangObject(), false);
3514 break;
3515
3516 case Instruction::IGET_BOOLEAN:
3517 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, false);
3518 break;
3519 case Instruction::IGET_BYTE:
3520 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, false);
3521 break;
3522 case Instruction::IGET_CHAR:
3523 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, false);
3524 break;
3525 case Instruction::IGET_SHORT:
3526 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, false);
3527 break;
3528 case Instruction::IGET:
3529 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, false);
3530 break;
3531 case Instruction::IGET_WIDE:
3532 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, false);
3533 break;
3534 case Instruction::IGET_OBJECT:
3535 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, false, false);
3536 break;
3537
3538 case Instruction::IPUT_BOOLEAN:
3539 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, false);
3540 break;
3541 case Instruction::IPUT_BYTE:
3542 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, false);
3543 break;
3544 case Instruction::IPUT_CHAR:
3545 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, false);
3546 break;
3547 case Instruction::IPUT_SHORT:
3548 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, false);
3549 break;
3550 case Instruction::IPUT:
3551 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, false);
3552 break;
3553 case Instruction::IPUT_WIDE:
3554 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, false);
3555 break;
3556 case Instruction::IPUT_OBJECT:
3557 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, false, false);
3558 break;
3559
3560 case Instruction::SGET_BOOLEAN:
3561 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, true);
3562 break;
3563 case Instruction::SGET_BYTE:
3564 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, true);
3565 break;
3566 case Instruction::SGET_CHAR:
3567 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, true);
3568 break;
3569 case Instruction::SGET_SHORT:
3570 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, true);
3571 break;
3572 case Instruction::SGET:
3573 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, true);
3574 break;
3575 case Instruction::SGET_WIDE:
3576 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, true, true);
3577 break;
3578 case Instruction::SGET_OBJECT:
3579 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, false, true);
3580 break;
3581
3582 case Instruction::SPUT_BOOLEAN:
3583 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, true);
3584 break;
3585 case Instruction::SPUT_BYTE:
3586 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, true);
3587 break;
3588 case Instruction::SPUT_CHAR:
3589 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, true);
3590 break;
3591 case Instruction::SPUT_SHORT:
3592 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, true);
3593 break;
3594 case Instruction::SPUT:
3595 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, true);
3596 break;
3597 case Instruction::SPUT_WIDE:
3598 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, true, true);
3599 break;
3600 case Instruction::SPUT_OBJECT:
3601 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, false, true);
3602 break;
3603
3604 case Instruction::INVOKE_VIRTUAL:
3605 case Instruction::INVOKE_VIRTUAL_RANGE:
3606 case Instruction::INVOKE_SUPER:
3607 case Instruction::INVOKE_SUPER_RANGE: {
3608 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE ||
3609 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE);
3610 bool is_super = (inst->Opcode() == Instruction::INVOKE_SUPER ||
3611 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE);
3612 MethodType type = is_super ? METHOD_SUPER : METHOD_VIRTUAL;
3613 ArtMethod* called_method = VerifyInvocationArgs(inst, type, is_range);
3614 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
3615 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
3616 dex::TypeIndex return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
3617 DCHECK_IMPLIES(called_method != nullptr,
3618 called_method->GetReturnTypeDescriptorView() ==
3619 dex_file_->GetTypeDescriptorView(return_type_idx));
3620 const RegType& return_type = reg_types_.FromTypeIndex(return_type_idx);
3621 if (!return_type.IsLowHalf()) {
3622 work_line_->SetResultRegisterType(return_type);
3623 } else {
3624 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_));
3625 }
3626 just_set_result = true;
3627 break;
3628 }
3629 case Instruction::INVOKE_DIRECT:
3630 case Instruction::INVOKE_DIRECT_RANGE: {
3631 bool is_range = (inst->Opcode() == Instruction::INVOKE_DIRECT_RANGE);
3632 ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_DIRECT, is_range);
3633 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
3634 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
3635 dex::TypeIndex return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
3636 DCHECK_IMPLIES(called_method != nullptr,
3637 called_method->GetReturnTypeDescriptorView() ==
3638 dex_file_->GetTypeDescriptorView(return_type_idx));
3639 bool is_constructor = (called_method != nullptr)
3640 ? called_method->IsConstructor()
3641 : dex_file_->GetStringView(method_id.name_idx_) == "<init>";
3642 if (is_constructor) {
3643 /*
3644 * Some additional checks when calling a constructor. We know from the invocation arg check
3645 * that the "this" argument is an instance of called_method->klass. Now we further restrict
3646 * that to require that called_method->klass is the same as this->klass or this->super,
3647 * allowing the latter only if the "this" argument is the same as the "this" argument to
3648 * this method (which implies that we're in a constructor ourselves).
3649 */
3650 const RegType& this_type = GetInvocationThis(inst);
3651 if (this_type.IsConflict()) { // failure.
3652 return false;
3653 }
3654
3655 /* no null refs allowed (?) */
3656 if (this_type.IsZeroOrNull()) {
3657 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to initialize null ref";
3658 return false;
3659 }
3660
3661 /* arg must be an uninitialized reference */
3662 if (!this_type.IsUninitializedTypes()) {
3663 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Expected initialization on uninitialized reference "
3664 << this_type;
3665 return false;
3666 }
3667
3668 // Note: According to JLS, constructors are never inherited. Therefore the target
3669 // constructor should be defined exactly by the `this_type`, or by the direct
3670 // superclass in the case of a constructor calling the superclass constructor.
3671 // However, ART had this check commented out for a very long time and this has
3672 // allowed bytecode optimizers such as R8 to inline constructors, often calling
3673 // `j.l.Object.<init>` directly without any intermediate constructor. Since this
3674 // optimization allows eliminating constructor methods, this often results in a
3675 // significant dex size reduction. Therefore it is undesirable to reinstate this
3676 // check and ART deliberately remains permissive here and diverges from the RI.
3677
3678 /*
3679 * Replace the uninitialized reference with an initialized one. We need to do this for all
3680 * registers that have the same object instance in them, not just the "this" register.
3681 */
3682 work_line_->MarkRefsAsInitialized(this, inst->VRegC());
3683 }
3684 const RegType& return_type = reg_types_.FromTypeIndex(return_type_idx);
3685 if (!return_type.IsLowHalf()) {
3686 work_line_->SetResultRegisterType(return_type);
3687 } else {
3688 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_));
3689 }
3690 just_set_result = true;
3691 break;
3692 }
3693 case Instruction::INVOKE_STATIC:
3694 case Instruction::INVOKE_STATIC_RANGE: {
3695 bool is_range = (inst->Opcode() == Instruction::INVOKE_STATIC_RANGE);
3696 ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_STATIC, is_range);
3697 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
3698 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
3699 dex::TypeIndex return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
3700 DCHECK_IMPLIES(called_method != nullptr,
3701 called_method->GetReturnTypeDescriptorView() ==
3702 dex_file_->GetTypeDescriptorView(return_type_idx));
3703 const RegType& return_type = reg_types_.FromTypeIndex(return_type_idx);
3704 if (!return_type.IsLowHalf()) {
3705 work_line_->SetResultRegisterType(return_type);
3706 } else {
3707 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_));
3708 }
3709 just_set_result = true;
3710 break;
3711 }
3712 case Instruction::INVOKE_INTERFACE:
3713 case Instruction::INVOKE_INTERFACE_RANGE: {
3714 bool is_range = (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE);
3715 ArtMethod* abs_method = VerifyInvocationArgs(inst, METHOD_INTERFACE, is_range);
3716 if (abs_method != nullptr) {
3717 ObjPtr<mirror::Class> called_interface = abs_method->GetDeclaringClass();
3718 if (!called_interface->IsInterface() && !called_interface->IsObjectClass()) {
3719 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '"
3720 << abs_method->PrettyMethod() << "'";
3721 break;
3722 }
3723 }
3724 /* Get the type of the "this" arg, which should either be a sub-interface of called
3725 * interface or Object (see comments in RegType::JoinClass).
3726 */
3727 const RegType& this_type = GetInvocationThis(inst);
3728 if (this_type.IsZeroOrNull()) {
3729 /* null pointer always passes (and always fails at runtime) */
3730 } else {
3731 if (this_type.IsUninitializedTypes()) {
3732 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface call on uninitialized object "
3733 << this_type;
3734 return false;
3735 }
3736 // In the past we have tried to assert that "called_interface" is assignable
3737 // from "this_type.GetClass()", however, as we do an imprecise Join
3738 // (RegType::JoinClass) we don't have full information on what interfaces are
3739 // implemented by "this_type". For example, two classes may implement the same
3740 // interfaces and have a common parent that doesn't implement the interface. The
3741 // join will set "this_type" to the parent class and a test that this implements
3742 // the interface will incorrectly fail.
3743 }
3744 /*
3745 * We don't have an object instance, so we can't find the concrete method. However, all of
3746 * the type information is in the abstract method, so we're good.
3747 */
3748 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
3749 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
3750 dex::TypeIndex return_type_idx = dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
3751 DCHECK_IMPLIES(abs_method != nullptr,
3752 abs_method->GetReturnTypeDescriptorView() ==
3753 dex_file_->GetTypeDescriptorView(return_type_idx));
3754 const RegType& return_type = reg_types_.FromTypeIndex(return_type_idx);
3755 if (!return_type.IsLowHalf()) {
3756 work_line_->SetResultRegisterType(return_type);
3757 } else {
3758 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_));
3759 }
3760 just_set_result = true;
3761 break;
3762 }
3763 case Instruction::INVOKE_POLYMORPHIC:
3764 case Instruction::INVOKE_POLYMORPHIC_RANGE: {
3765 bool is_range = (inst->Opcode() == Instruction::INVOKE_POLYMORPHIC_RANGE);
3766 ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_POLYMORPHIC, is_range);
3767 if (called_method == nullptr) {
3768 // Convert potential soft failures in VerifyInvocationArgs() to hard errors.
3769 std::string_view message = failures_.empty() ? "invoke-polymorphic verification failure."
3770 : failures_.back().message.view();
3771 // Note: Adding another failure to `failures_` does not invalidate the view of
3772 // the previous message (if any) - the list node holding it is not even moved.
3773 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << message;
3774 return false;
3775 }
3776 if (!CheckSignaturePolymorphicMethod(called_method) ||
3777 !CheckSignaturePolymorphicReceiver(inst)) {
3778 DCHECK(HasFailures());
3779 break;
3780 }
3781 const dex::ProtoIndex proto_idx((is_range) ? inst->VRegH_4rcc() : inst->VRegH_45cc());
3782 const RegType& return_type =
3783 reg_types_.FromTypeIndex(dex_file_->GetProtoId(proto_idx).return_type_idx_);
3784 if (!return_type.IsLowHalf()) {
3785 work_line_->SetResultRegisterType(return_type);
3786 } else {
3787 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_));
3788 }
3789 just_set_result = true;
3790 break;
3791 }
3792 case Instruction::INVOKE_CUSTOM:
3793 case Instruction::INVOKE_CUSTOM_RANGE: {
3794 // Verify registers based on method_type in the call site.
3795 bool is_range = (inst->Opcode() == Instruction::INVOKE_CUSTOM_RANGE);
3796
3797 // Step 1. Check the call site that produces the method handle for invocation
3798 const uint32_t call_site_idx = is_range ? inst->VRegB_3rc() : inst->VRegB_35c();
3799 if (!CheckCallSite(call_site_idx)) {
3800 DCHECK(HasFailures());
3801 break;
3802 }
3803
3804 // Step 2. Check the register arguments correspond to the expected arguments for the
3805 // method handle produced by step 1. The dex file verifier has checked ranges for
3806 // the first three arguments and CheckCallSite has checked the method handle type.
3807 const dex::ProtoIndex proto_idx = dex_file_->GetProtoIndexForCallSite(call_site_idx);
3808 const dex::ProtoId& proto_id = dex_file_->GetProtoId(proto_idx);
3809 DexFileParameterIterator param_it(*dex_file_, proto_id);
3810 // Treat method as static as it has yet to be determined.
3811 VerifyInvocationArgsFromIterator(¶m_it, inst, METHOD_STATIC, is_range, nullptr);
3812
3813 // Step 3. Propagate return type information
3814 const RegType& return_type = reg_types_.FromTypeIndex(proto_id.return_type_idx_);
3815 if (!return_type.IsLowHalf()) {
3816 work_line_->SetResultRegisterType(return_type);
3817 } else {
3818 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_));
3819 }
3820 just_set_result = true;
3821 break;
3822 }
3823 case Instruction::NEG_INT:
3824 case Instruction::NOT_INT:
3825 if (!CheckUnaryOp(inst, inst_data, kInteger, kInteger)) {
3826 return false;
3827 }
3828 break;
3829 case Instruction::NEG_LONG:
3830 case Instruction::NOT_LONG:
3831 if (!CheckUnaryOpWide(inst, inst_data, kLongLo, kLongLo)) {
3832 return false;
3833 }
3834 break;
3835 case Instruction::NEG_FLOAT:
3836 if (!CheckUnaryOp(inst, inst_data, kFloat, kFloat)) {
3837 return false;
3838 }
3839 break;
3840 case Instruction::NEG_DOUBLE:
3841 if (!CheckUnaryOpWide(inst, inst_data, kDoubleLo, kDoubleLo)) {
3842 return false;
3843 }
3844 break;
3845 case Instruction::INT_TO_LONG:
3846 if (!CheckUnaryOpToWide(inst, inst_data, kLongLo, kInteger)) {
3847 return false;
3848 }
3849 break;
3850 case Instruction::INT_TO_FLOAT:
3851 if (!CheckUnaryOp(inst, inst_data, kFloat, kInteger)) {
3852 return false;
3853 }
3854 break;
3855 case Instruction::INT_TO_DOUBLE:
3856 if (!CheckUnaryOpToWide(inst, inst_data, kDoubleLo, kInteger)) {
3857 return false;
3858 }
3859 break;
3860 case Instruction::LONG_TO_INT:
3861 if (!CheckUnaryOpFromWide(inst, inst_data, kInteger, kLongLo)) {
3862 return false;
3863 }
3864 break;
3865 case Instruction::LONG_TO_FLOAT:
3866 if (!CheckUnaryOpFromWide(inst, inst_data, kFloat, kLongLo)) {
3867 return false;
3868 }
3869 break;
3870 case Instruction::LONG_TO_DOUBLE:
3871 if (!CheckUnaryOpWide(inst, inst_data, kDoubleLo, kLongLo)) {
3872 return false;
3873 }
3874 break;
3875 case Instruction::FLOAT_TO_INT:
3876 if (!CheckUnaryOp(inst, inst_data, kInteger, kFloat)) {
3877 return false;
3878 }
3879 break;
3880 case Instruction::FLOAT_TO_LONG:
3881 if (!CheckUnaryOpToWide(inst, inst_data, kLongLo, kFloat)) {
3882 return false;
3883 }
3884 break;
3885 case Instruction::FLOAT_TO_DOUBLE:
3886 if (!CheckUnaryOpToWide(inst, inst_data, kDoubleLo, kFloat)) {
3887 return false;
3888 }
3889 break;
3890 case Instruction::DOUBLE_TO_INT:
3891 if (!CheckUnaryOpFromWide(inst, inst_data, kInteger, kDoubleLo)) {
3892 return false;
3893 }
3894 break;
3895 case Instruction::DOUBLE_TO_LONG:
3896 if (!CheckUnaryOpWide(inst, inst_data, kLongLo, kDoubleLo)) {
3897 return false;
3898 }
3899 break;
3900 case Instruction::DOUBLE_TO_FLOAT:
3901 if (!CheckUnaryOpFromWide(inst, inst_data, kFloat, kDoubleLo)) {
3902 return false;
3903 }
3904 break;
3905 case Instruction::INT_TO_BYTE:
3906 if (!CheckUnaryOp(inst, inst_data, kByte, kInteger)) {
3907 return false;
3908 }
3909 break;
3910 case Instruction::INT_TO_CHAR:
3911 if (!CheckUnaryOp(inst, inst_data, kChar, kInteger)) {
3912 return false;
3913 }
3914 break;
3915 case Instruction::INT_TO_SHORT:
3916 if (!CheckUnaryOp(inst, inst_data, kShort, kInteger)) {
3917 return false;
3918 }
3919 break;
3920
3921 case Instruction::ADD_INT:
3922 case Instruction::SUB_INT:
3923 case Instruction::MUL_INT:
3924 case Instruction::REM_INT:
3925 case Instruction::DIV_INT:
3926 case Instruction::SHL_INT:
3927 case Instruction::SHR_INT:
3928 case Instruction::USHR_INT:
3929 if (!CheckBinaryOp(
3930 inst, inst_data, kInteger, kInteger, kInteger, /*check_boolean_op=*/ false)) {
3931 return false;
3932 }
3933 break;
3934 case Instruction::AND_INT:
3935 case Instruction::OR_INT:
3936 case Instruction::XOR_INT:
3937 if (!CheckBinaryOp(
3938 inst, inst_data, kInteger, kInteger, kInteger, /*check_boolean_op=*/ true)) {
3939 return false;
3940 }
3941 break;
3942 case Instruction::ADD_LONG:
3943 case Instruction::SUB_LONG:
3944 case Instruction::MUL_LONG:
3945 case Instruction::DIV_LONG:
3946 case Instruction::REM_LONG:
3947 case Instruction::AND_LONG:
3948 case Instruction::OR_LONG:
3949 case Instruction::XOR_LONG:
3950 if (!CheckBinaryOpWide(inst, inst_data, kLongLo, kLongLo, kLongLo)) {
3951 return false;
3952 }
3953 break;
3954 case Instruction::SHL_LONG:
3955 case Instruction::SHR_LONG:
3956 case Instruction::USHR_LONG:
3957 /* shift distance is Int, making these different from other binary operations */
3958 if (!CheckBinaryOpWideShift(inst, inst_data, kLongLo, kInteger)) {
3959 return false;
3960 }
3961 break;
3962 case Instruction::ADD_FLOAT:
3963 case Instruction::SUB_FLOAT:
3964 case Instruction::MUL_FLOAT:
3965 case Instruction::DIV_FLOAT:
3966 case Instruction::REM_FLOAT:
3967 if (!CheckBinaryOp(inst, inst_data, kFloat, kFloat, kFloat, /*check_boolean_op=*/ false)) {
3968 return false;
3969 }
3970 break;
3971 case Instruction::ADD_DOUBLE:
3972 case Instruction::SUB_DOUBLE:
3973 case Instruction::MUL_DOUBLE:
3974 case Instruction::DIV_DOUBLE:
3975 case Instruction::REM_DOUBLE:
3976 if (!CheckBinaryOpWide(inst, inst_data, kDoubleLo, kDoubleLo, kDoubleLo)) {
3977 return false;
3978 }
3979 break;
3980 case Instruction::ADD_INT_2ADDR:
3981 case Instruction::SUB_INT_2ADDR:
3982 case Instruction::MUL_INT_2ADDR:
3983 case Instruction::REM_INT_2ADDR:
3984 case Instruction::SHL_INT_2ADDR:
3985 case Instruction::SHR_INT_2ADDR:
3986 case Instruction::USHR_INT_2ADDR:
3987 if (!CheckBinaryOp2addr(
3988 inst, inst_data, kInteger, kInteger, kInteger, /*check_boolean_op=*/ false)) {
3989 return false;
3990 }
3991 break;
3992 case Instruction::AND_INT_2ADDR:
3993 case Instruction::OR_INT_2ADDR:
3994 case Instruction::XOR_INT_2ADDR:
3995 if (!CheckBinaryOp2addr(
3996 inst, inst_data, kInteger, kInteger, kInteger, /*check_boolean_op=*/ true)) {
3997 return false;
3998 }
3999 break;
4000 case Instruction::DIV_INT_2ADDR:
4001 if (!CheckBinaryOp2addr(
4002 inst, inst_data, kInteger, kInteger, kInteger, /*check_boolean_op=*/ false)) {
4003 return false;
4004 }
4005 break;
4006 case Instruction::ADD_LONG_2ADDR:
4007 case Instruction::SUB_LONG_2ADDR:
4008 case Instruction::MUL_LONG_2ADDR:
4009 case Instruction::DIV_LONG_2ADDR:
4010 case Instruction::REM_LONG_2ADDR:
4011 case Instruction::AND_LONG_2ADDR:
4012 case Instruction::OR_LONG_2ADDR:
4013 case Instruction::XOR_LONG_2ADDR:
4014 if (!CheckBinaryOp2addrWide(inst, inst_data, kLongLo, kLongLo, kLongLo)) {
4015 return false;
4016 }
4017 break;
4018 case Instruction::SHL_LONG_2ADDR:
4019 case Instruction::SHR_LONG_2ADDR:
4020 case Instruction::USHR_LONG_2ADDR:
4021 if (!CheckBinaryOp2addrWideShift(inst, inst_data, kLongLo, kInteger)) {
4022 return false;
4023 }
4024 break;
4025 case Instruction::ADD_FLOAT_2ADDR:
4026 case Instruction::SUB_FLOAT_2ADDR:
4027 case Instruction::MUL_FLOAT_2ADDR:
4028 case Instruction::DIV_FLOAT_2ADDR:
4029 case Instruction::REM_FLOAT_2ADDR:
4030 if (!CheckBinaryOp2addr(
4031 inst, inst_data, kFloat, kFloat, kFloat, /*check_boolean_op=*/ false)) {
4032 return false;
4033 }
4034 break;
4035 case Instruction::ADD_DOUBLE_2ADDR:
4036 case Instruction::SUB_DOUBLE_2ADDR:
4037 case Instruction::MUL_DOUBLE_2ADDR:
4038 case Instruction::DIV_DOUBLE_2ADDR:
4039 case Instruction::REM_DOUBLE_2ADDR:
4040 if (!CheckBinaryOp2addrWide(inst, inst_data, kDoubleLo, kDoubleLo, kDoubleLo)) {
4041 return false;
4042 }
4043 break;
4044 case Instruction::ADD_INT_LIT16:
4045 case Instruction::RSUB_INT_LIT16:
4046 case Instruction::MUL_INT_LIT16:
4047 case Instruction::DIV_INT_LIT16:
4048 case Instruction::REM_INT_LIT16:
4049 if (!CheckLiteralOp</*kIsLit16=*/ true>(
4050 inst, inst_data, kInteger, kInteger, /*check_boolean_op=*/ false)) {
4051 return false;
4052 }
4053 break;
4054 case Instruction::AND_INT_LIT16:
4055 case Instruction::OR_INT_LIT16:
4056 case Instruction::XOR_INT_LIT16:
4057 if (!CheckLiteralOp</*kIsLit16=*/ true>(
4058 inst, inst_data, kInteger, kInteger, /*check_boolean_op=*/ true)) {
4059 return false;
4060 }
4061 break;
4062 case Instruction::ADD_INT_LIT8:
4063 case Instruction::RSUB_INT_LIT8:
4064 case Instruction::MUL_INT_LIT8:
4065 case Instruction::DIV_INT_LIT8:
4066 case Instruction::REM_INT_LIT8:
4067 case Instruction::SHL_INT_LIT8:
4068 case Instruction::SHR_INT_LIT8:
4069 case Instruction::USHR_INT_LIT8:
4070 if (!CheckLiteralOp</*kIsLit16=*/ false>(
4071 inst, inst_data, kInteger, kInteger, /*check_boolean_op=*/ false)) {
4072 return false;
4073 }
4074 break;
4075 case Instruction::AND_INT_LIT8:
4076 case Instruction::OR_INT_LIT8:
4077 case Instruction::XOR_INT_LIT8:
4078 if (!CheckLiteralOp</*kIsLit16=*/ false>(
4079 inst, inst_data, kInteger, kInteger, /*check_boolean_op=*/ true)) {
4080 return false;
4081 }
4082 break;
4083
4084 /* These should never appear during verification. */
4085 case Instruction::UNUSED_3E ... Instruction::UNUSED_43:
4086 case Instruction::UNUSED_E3 ... Instruction::UNUSED_F9:
4087 case Instruction::UNUSED_73:
4088 case Instruction::UNUSED_79:
4089 case Instruction::UNUSED_7A:
4090 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Unexpected opcode " << inst->DumpString(dex_file_);
4091 return false;
4092
4093 /*
4094 * DO NOT add a "default" clause here. Without it the compiler will
4095 * complain if an instruction is missing (which is desirable).
4096 */
4097 } // end - switch (dec_insn.opcode)
4098
4099 if (flags_.have_pending_hard_failure_) {
4100 /* immediate failure, reject class */
4101 return false;
4102 } else if (flags_.have_pending_runtime_throw_failure_) {
4103 LogVerifyInfo() << "Elevating opcode flags from " << opcode_flags << " to Throw";
4104 /* checking interpreter will throw, mark following code as unreachable */
4105 opcode_flags = Instruction::kThrow;
4106 // Note: the flag must be reset as it is only global to decouple Fail and is semantically per
4107 // instruction. However, RETURN checking may throw LOCKING errors, so we clear at the
4108 // very end.
4109 }
4110 /*
4111 * If we didn't just set the result register, clear it out. This ensures that you can only use
4112 * "move-result" immediately after the result is set. (We could check this statically, but it's
4113 * not expensive and it makes our debugging output cleaner.)
4114 */
4115 if (!just_set_result) {
4116 work_line_->SetResultTypeToUnknown();
4117 }
4118
4119 /*
4120 * Handle "branch". Tag the branch target.
4121 *
4122 * NOTE: instructions like Instruction::EQZ provide information about the
4123 * state of the register when the branch is taken or not taken. For example,
4124 * somebody could get a reference field, check it for zero, and if the
4125 * branch is taken immediately store that register in a boolean field
4126 * since the value is known to be zero. We do not currently account for
4127 * that, and will reject the code.
4128 *
4129 * TODO: avoid re-fetching the branch target
4130 */
4131 if ((opcode_flags & Instruction::kBranch) != 0) {
4132 bool isConditional, selfOkay;
4133 if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) {
4134 /* should never happen after static verification */
4135 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad branch";
4136 return false;
4137 }
4138 DCHECK_EQ(isConditional, (opcode_flags & Instruction::kContinue) != 0);
4139 DCHECK(!IsMoveResultOrMoveException(inst->RelativeAt(branch_target)->Opcode()));
4140 /* update branch target, set "changed" if appropriate */
4141 if (nullptr != branch_line) {
4142 UpdateRegisters(work_insn_idx_ + branch_target, branch_line.get(), false);
4143 } else {
4144 UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get(), false);
4145 }
4146 }
4147
4148 /*
4149 * Handle "switch". Tag all possible branch targets.
4150 *
4151 * We've already verified that the table is structurally sound, so we
4152 * just need to walk through and tag the targets.
4153 */
4154 if ((opcode_flags & Instruction::kSwitch) != 0) {
4155 int offset_to_switch = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
4156 const uint16_t* switch_insns = insns + offset_to_switch;
4157 int switch_count = switch_insns[1];
4158 int offset_to_targets, targ;
4159
4160 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
4161 /* 0 = sig, 1 = count, 2/3 = first key */
4162 offset_to_targets = 4;
4163 } else {
4164 /* 0 = sig, 1 = count, 2..count * 2 = keys */
4165 DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH);
4166 offset_to_targets = 2 + 2 * switch_count;
4167 }
4168
4169 /* verify each switch target */
4170 for (targ = 0; targ < switch_count; targ++) {
4171 int offset;
4172 uint32_t abs_offset;
4173
4174 /* offsets are 32-bit, and only partly endian-swapped */
4175 offset = switch_insns[offset_to_targets + targ * 2] |
4176 (static_cast<int32_t>(switch_insns[offset_to_targets + targ * 2 + 1]) << 16);
4177 abs_offset = work_insn_idx_ + offset;
4178 DCHECK_LT(abs_offset, code_item_accessor_.InsnsSizeInCodeUnits());
4179 DCHECK(!IsMoveResultOrMoveException(inst->RelativeAt(offset)->Opcode()));
4180 UpdateRegisters(abs_offset, work_line_.get(), false);
4181 }
4182 }
4183
4184 /*
4185 * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a
4186 * "try" block when they throw, control transfers out of the method.)
4187 */
4188 if ((opcode_flags & Instruction::kThrow) != 0 && GetInstructionFlags(work_insn_idx_).IsInTry()) {
4189 bool has_catch_all_handler = false;
4190 const dex::TryItem* try_item = code_item_accessor_.FindTryItem(work_insn_idx_);
4191 CHECK(try_item != nullptr);
4192 CatchHandlerIterator iterator(code_item_accessor_, *try_item);
4193
4194 // Need the linker to try and resolve the handled class to check if it's Throwable.
4195 ClassLinker* linker = GetClassLinker();
4196
4197 for (; iterator.HasNext(); iterator.Next()) {
4198 dex::TypeIndex handler_type_idx = iterator.GetHandlerTypeIndex();
4199 if (!handler_type_idx.IsValid()) {
4200 has_catch_all_handler = true;
4201 } else {
4202 // It is also a catch-all if it is java.lang.Throwable.
4203 ObjPtr<mirror::Class> klass =
4204 linker->ResolveType(handler_type_idx, dex_cache_, class_loader_);
4205 if (klass != nullptr) {
4206 if (klass == GetClassRoot<mirror::Throwable>()) {
4207 has_catch_all_handler = true;
4208 }
4209 } else {
4210 // Clear exception.
4211 DCHECK(self_->IsExceptionPending());
4212 self_->ClearException();
4213 }
4214 }
4215 /*
4216 * Merge registers into the "catch" block. We want to use the "savedRegs" rather than
4217 * "work_regs", because at runtime the exception will be thrown before the instruction
4218 * modifies any registers.
4219 */
4220 if (kVerifierDebug) {
4221 LogVerifyInfo() << "Updating exception handler 0x"
4222 << std::hex << iterator.GetHandlerAddress();
4223 }
4224 UpdateRegisters(iterator.GetHandlerAddress(), saved_line_.get(), false);
4225 }
4226
4227 /*
4228 * If the monitor stack depth is nonzero, there must be a "catch all" handler for this
4229 * instruction. This does apply to monitor-exit because of async exception handling.
4230 */
4231 if (work_line_->MonitorStackDepth() > 0 && !has_catch_all_handler) {
4232 /*
4233 * The state in work_line reflects the post-execution state. If the current instruction is a
4234 * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws,
4235 * it will do so before grabbing the lock).
4236 */
4237 if (inst->Opcode() != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) {
4238 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4239 << "expected to be within a catch-all for an instruction where a monitor is held";
4240 return false;
4241 }
4242 }
4243 }
4244
4245 /* Handle "continue". Tag the next consecutive instruction.
4246 * Note: Keep the code handling "continue" case below the "branch" and "switch" cases,
4247 * because it changes work_line_ when performing peephole optimization
4248 * and this change should not be used in those cases.
4249 */
4250 if ((opcode_flags & Instruction::kContinue) != 0) {
4251 DCHECK_EQ(&code_item_accessor_.InstructionAt(work_insn_idx_), inst);
4252 uint32_t next_insn_idx = work_insn_idx_ + inst->SizeInCodeUnits();
4253 if (next_insn_idx >= code_item_accessor_.InsnsSizeInCodeUnits()) {
4254 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Can flow through to end of code area";
4255 return false;
4256 }
4257 // The only way to get to a move-exception instruction is to get thrown there. Make sure the
4258 // next instruction isn't one.
4259 Instruction::Code next_opcode = code_item_accessor_.InstructionAt(next_insn_idx).Opcode();
4260 if (UNLIKELY(next_opcode == Instruction::MOVE_EXCEPTION)) {
4261 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Can flow through to move-exception";
4262 return false;
4263 }
4264 if (nullptr != fallthrough_line) {
4265 // Make workline consistent with fallthrough computed from peephole optimization.
4266 work_line_->CopyFromLine(fallthrough_line.get());
4267 }
4268 RegisterLine* next_line = reg_table_.GetLine(next_insn_idx);
4269 if (next_line != nullptr) {
4270 // Merge registers into what we have for the next instruction, and set the "changed" flag if
4271 // needed. If the merge changes the state of the registers then the work line will be
4272 // updated.
4273 UpdateRegisters(next_insn_idx, work_line_.get(), true);
4274 } else {
4275 /*
4276 * We're not recording register data for the next instruction, so we don't know what the
4277 * prior state was. We have to assume that something has changed and re-evaluate it.
4278 */
4279 GetModifiableInstructionFlags(next_insn_idx).SetChanged();
4280 }
4281 }
4282
4283 /* If we're returning from the method, make sure monitor stack is empty. */
4284 if ((opcode_flags & Instruction::kReturn) != 0) {
4285 work_line_->VerifyMonitorStackEmpty(this);
4286 }
4287
4288 /*
4289 * Update start_guess. Advance to the next instruction of that's
4290 * possible, otherwise use the branch target if one was found. If
4291 * neither of those exists we're in a return or throw; leave start_guess
4292 * alone and let the caller sort it out.
4293 */
4294 if ((opcode_flags & Instruction::kContinue) != 0) {
4295 DCHECK_EQ(&code_item_accessor_.InstructionAt(work_insn_idx_), inst);
4296 *start_guess = work_insn_idx_ + inst->SizeInCodeUnits();
4297 } else if ((opcode_flags & Instruction::kBranch) != 0) {
4298 /* we're still okay if branch_target is zero */
4299 *start_guess = work_insn_idx_ + branch_target;
4300 }
4301
4302 DCHECK_LT(*start_guess, code_item_accessor_.InsnsSizeInCodeUnits());
4303 DCHECK(GetInstructionFlags(*start_guess).IsOpcode());
4304
4305 if (flags_.have_pending_runtime_throw_failure_) {
4306 Fail(VERIFY_ERROR_RUNTIME_THROW, /* pending_exc= */ false);
4307 // Reset the pending_runtime_throw flag now.
4308 flags_.have_pending_runtime_throw_failure_ = false;
4309 }
4310
4311 return true;
4312 } // NOLINT(readability/fn_size)
4313
4314 template <CheckAccess C>
ResolveClass(dex::TypeIndex class_idx)4315 const RegType& MethodVerifierImpl::ResolveClass(dex::TypeIndex class_idx) {
4316 // FIXME: `RegTypeCache` can currently return a few fundamental classes such as j.l.Object
4317 // or j.l.Class without resolving them using the current class loader and recording them
4318 // in the corresponding `ClassTable`. The subsequent method and field lookup by callers of
4319 // `ResolveClass<>()` can then put their methods and fields to the `DexCache` which should
4320 // not be done for classes that are not in the `ClassTable`, potentially leading to crashes.
4321 // For now, we force the class resolution here to avoid the inconsistency.
4322 // Note that there's nothing we can do if we cannot load classes. (The only code path that
4323 // does not allow loading classes is `FindLocksAtDexPc()` which should really need only to
4324 // distinguish between reference and non-reference types and track locking. All the other
4325 // work, including class lookup, is unnecessary as the class has already been verified.)
4326 if (CanLoadClasses()) {
4327 ClassLinker* linker = GetClassLinker();
4328 ObjPtr<mirror::Class> klass = linker->ResolveType(class_idx, dex_cache_, class_loader_);
4329 if (klass == nullptr) {
4330 DCHECK(self_->IsExceptionPending());
4331 self_->ClearException();
4332 }
4333 }
4334
4335 const RegType& result = reg_types_.FromTypeIndex(class_idx);
4336 if (result.IsConflict()) {
4337 const char* descriptor = dex_file_->GetTypeDescriptor(class_idx);
4338 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "accessing broken descriptor '" << descriptor
4339 << "' in " << GetDeclaringClass();
4340 return result;
4341 }
4342
4343 // If requested, check if access is allowed. Unresolved types are included in this check, as the
4344 // interpreter only tests whether access is allowed when a class is not pre-verified and runs in
4345 // the access-checks interpreter. If result is primitive, skip the access check.
4346 //
4347 // Note: we do this for unresolved classes to trigger re-verification at runtime.
4348 if (C != CheckAccess::kNo &&
4349 result.IsNonZeroReferenceTypes() &&
4350 ((C == CheckAccess::kYes && IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP))
4351 || !result.IsUnresolvedTypes())) {
4352 const RegType& referrer = GetDeclaringClass();
4353 if ((IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP) || !referrer.IsUnresolvedTypes()) &&
4354 !CanAccess(result)) {
4355 if (IsAotMode()) {
4356 Fail(VERIFY_ERROR_ACCESS_CLASS);
4357 VLOG(verifier)
4358 << "(possibly) illegal class access: '" << referrer << "' -> '" << result << "'";
4359 } else {
4360 Fail(VERIFY_ERROR_ACCESS_CLASS)
4361 << "(possibly) illegal class access: '" << referrer << "' -> '" << result << "'";
4362 }
4363 }
4364 }
4365 return result;
4366 }
4367
4368 MethodVerifierImpl::HandleMoveExceptionResult
HandleMoveException(const Instruction * inst)4369 MethodVerifierImpl::HandleMoveException(const Instruction* inst) {
4370 // We do not allow MOVE_EXCEPTION as the first instruction in a method. This is a simple case
4371 // where one entrypoint to the catch block is not actually an exception path.
4372 if (work_insn_idx_ == 0) {
4373 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "move-exception at pc 0x0";
4374 return {false, false};
4375 }
4376 /*
4377 * This statement can only appear as the first instruction in an exception handler. We verify
4378 * that as part of extracting the exception type from the catch block list.
4379 */
4380 const RegType* common_super = nullptr;
4381 const RegType* unresolved = nullptr;
4382 if (code_item_accessor_.TriesSize() != 0) {
4383 const uint8_t* handlers_ptr = code_item_accessor_.GetCatchHandlerData();
4384 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
4385 for (uint32_t i = 0; i < handlers_size; i++) {
4386 CatchHandlerIterator iterator(handlers_ptr);
4387 for (; iterator.HasNext(); iterator.Next()) {
4388 if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) {
4389 if (!iterator.GetHandlerTypeIndex().IsValid()) {
4390 common_super = ®_types_.JavaLangThrowable();
4391 } else {
4392 // Do access checks only on resolved exception classes.
4393 const RegType& exception =
4394 ResolveClass<CheckAccess::kOnResolvedClass>(iterator.GetHandlerTypeIndex());
4395 if (!IsAssignableFrom(reg_types_.JavaLangThrowable(), exception)) {
4396 DCHECK(!exception.IsUninitializedTypes()); // Comes from dex, shouldn't be uninit.
4397 if (exception.IsUnresolvedTypes()) {
4398 if (unresolved == nullptr) {
4399 unresolved = &exception;
4400 } else {
4401 unresolved = &unresolved->SafeMerge(exception, ®_types_, this);
4402 }
4403 } else {
4404 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected non-throwable class "
4405 << exception;
4406 return {false, false};
4407 }
4408 } else if (common_super == nullptr) {
4409 common_super = &exception;
4410 } else if (common_super->Equals(exception)) {
4411 // odd case, but nothing to do
4412 } else {
4413 common_super = &common_super->Merge(exception, ®_types_, this);
4414 if (UNLIKELY(!IsAssignableFrom(reg_types_.JavaLangThrowable(), *common_super))) {
4415 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4416 << "java.lang.Throwable is not assignable-from common_super";
4417 return {false, false};
4418 }
4419 }
4420 }
4421 }
4422 }
4423 handlers_ptr = iterator.EndDataPointer();
4424 }
4425 }
4426 const RegType* reg_type = nullptr;
4427 bool skip_verification_of_exception_handler = false;
4428 if (unresolved != nullptr) {
4429 // Soft-fail, but do not handle this with a synthetic throw.
4430 Fail(VERIFY_ERROR_UNRESOLVED_TYPE_CHECK, /*pending_exc=*/ false)
4431 << "Unresolved catch handler";
4432 bool should_continue = true;
4433 if (common_super != nullptr) {
4434 reg_type = &unresolved->Merge(*common_super, ®_types_, this);
4435 } else {
4436 reg_type = unresolved;
4437 if (!IsAotMode() && !IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kS_V2)) {
4438 // This is an unreachable handler at runtime. For older API levels, we avoid the
4439 // verification of the entire handler for compatibility reasons. The instruction
4440 // doesn't throw, but we mark the method as having a pending runtime throw failure
4441 // so that the JIT compiler does not try to compile it - the compiler expects all
4442 // instructions to be properly verified and may crash otherwise.
4443 Fail(VERIFY_ERROR_RUNTIME_THROW, /* pending_exc= */ false);
4444 skip_verification_of_exception_handler = true;
4445 }
4446 }
4447 } else if (common_super == nullptr) {
4448 /* No catch block */
4449 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to find exception handler";
4450 return {false, false};
4451 } else {
4452 DCHECK(common_super->HasClass());
4453 CheckForFinalAbstractClass(common_super->GetClass());
4454 reg_type = common_super;
4455 }
4456 DCHECK(reg_type != nullptr);
4457 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_11x(), *reg_type);
4458 return {true, skip_verification_of_exception_handler};
4459 }
4460
ResolveMethodAndCheckAccess(uint32_t dex_method_idx,MethodType method_type)4461 ArtMethod* MethodVerifierImpl::ResolveMethodAndCheckAccess(
4462 uint32_t dex_method_idx, MethodType method_type) {
4463 const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx);
4464 const RegType& klass_type = ResolveClass<CheckAccess::kYes>(method_id.class_idx_);
4465 if (klass_type.IsConflict()) {
4466 LastFailureMessageStream()
4467 << " in attempt to access method " << dex_file_->GetMethodName(method_id);
4468 return nullptr;
4469 }
4470 if (klass_type.IsUnresolvedTypes()) {
4471 return nullptr; // Can't resolve Class so no more to do here
4472 }
4473 ClassLinker* class_linker = GetClassLinker();
4474 ObjPtr<mirror::Class> klass = GetRegTypeClass(klass_type);
4475
4476 ArtMethod* res_method = dex_cache_->GetResolvedMethod(dex_method_idx);
4477 if (res_method == nullptr) {
4478 res_method = class_linker->FindResolvedMethod(
4479 klass, dex_cache_.Get(), class_loader_.Get(), dex_method_idx);
4480 }
4481
4482 bool must_fail = false;
4483 // This is traditional and helps with screwy bytecode. It will tell you that, yes, a method
4484 // exists, but that it's called incorrectly. This significantly helps debugging, as locally it's
4485 // hard to see the differences.
4486 // If we don't have res_method here we must fail. Just use this bool to make sure of that with a
4487 // DCHECK.
4488 if (res_method == nullptr) {
4489 must_fail = true;
4490 // Try to find the method also with the other type for better error reporting below
4491 // but do not store such bogus lookup result in the DexCache or VerifierDeps.
4492 res_method = class_linker->FindIncompatibleMethod(
4493 klass, dex_cache_.Get(), class_loader_.Get(), dex_method_idx);
4494 }
4495
4496 if (res_method == nullptr) {
4497 Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method "
4498 << klass->PrettyDescriptor() << "."
4499 << dex_file_->GetMethodName(method_id) << " "
4500 << dex_file_->GetMethodSignature(method_id);
4501 return nullptr;
4502 }
4503
4504 // Make sure calls to constructors are "direct". There are additional restrictions but we don't
4505 // enforce them here.
4506 if (res_method->IsConstructor() && method_type != METHOD_DIRECT) {
4507 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting non-direct call to constructor "
4508 << res_method->PrettyMethod();
4509 return nullptr;
4510 }
4511 // Disallow any calls to class initializers.
4512 if (res_method->IsClassInitializer()) {
4513 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting call to class initializer "
4514 << res_method->PrettyMethod();
4515 return nullptr;
4516 }
4517
4518 // Check that interface methods are static or match interface classes.
4519 // We only allow statics if we don't have default methods enabled.
4520 //
4521 // Note: this check must be after the initializer check, as those are required to fail a class,
4522 // while this check implies an IncompatibleClassChangeError.
4523 if (klass->IsInterface()) {
4524 // methods called on interfaces should be invoke-interface, invoke-super, invoke-direct (if
4525 // default methods are supported for the dex file), or invoke-static.
4526 if (method_type != METHOD_INTERFACE &&
4527 method_type != METHOD_STATIC &&
4528 (!dex_file_->SupportsDefaultMethods() ||
4529 method_type != METHOD_DIRECT) &&
4530 method_type != METHOD_SUPER) {
4531 Fail(VERIFY_ERROR_CLASS_CHANGE)
4532 << "non-interface method " << dex_file_->PrettyMethod(dex_method_idx)
4533 << " is in an interface class " << klass->PrettyClass();
4534 return nullptr;
4535 }
4536 if (method_type == METHOD_SUPER &&
4537 res_method->GetDeclaringClass()->IsObjectClass()) {
4538 Fail(VERIFY_ERROR_NO_METHOD) << "invoke-super " << klass->PrettyDescriptor() << "."
4539 << dex_file_->GetMethodName(method_id) << " "
4540 << dex_file_->GetMethodSignature(method_id) << " resolved to "
4541 << "object method " << res_method->PrettyMethod() << " "
4542 << "but Object methods are excluded from super "
4543 << "method resolution on interfaces.";
4544 return nullptr;
4545 }
4546 } else {
4547 if (method_type == METHOD_INTERFACE) {
4548 Fail(VERIFY_ERROR_CLASS_CHANGE)
4549 << "interface method " << dex_file_->PrettyMethod(dex_method_idx)
4550 << " is in a non-interface class " << klass->PrettyClass();
4551 return nullptr;
4552 }
4553 }
4554
4555 // Check specifically for non-public object methods being provided for interface dispatch. This
4556 // can occur if we failed to find a method with FindInterfaceMethod but later find one with
4557 // FindClassMethod for error message use.
4558 if (method_type == METHOD_INTERFACE &&
4559 res_method->GetDeclaringClass()->IsObjectClass() &&
4560 !res_method->IsPublic()) {
4561 Fail(VERIFY_ERROR_NO_METHOD) << "invoke-interface " << klass->PrettyDescriptor() << "."
4562 << dex_file_->GetMethodName(method_id) << " "
4563 << dex_file_->GetMethodSignature(method_id) << " resolved to "
4564 << "non-public object method " << res_method->PrettyMethod() << " "
4565 << "but non-public Object methods are excluded from interface "
4566 << "method resolution.";
4567 return nullptr;
4568 }
4569 // Check if access is allowed.
4570 if (!CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) {
4571 Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call "
4572 << res_method->PrettyMethod()
4573 << " from " << GetDeclaringClass() << ")";
4574 return res_method;
4575 }
4576 // Check that invoke-virtual and invoke-super are not used on private methods of the same class.
4577 if (res_method->IsPrivate() && (method_type == METHOD_VIRTUAL || method_type == METHOD_SUPER)) {
4578 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-super/virtual can't be used on private method "
4579 << res_method->PrettyMethod();
4580 return nullptr;
4581 }
4582 // See if the method type implied by the invoke instruction matches the access flags for the
4583 // target method. The flags for METHOD_POLYMORPHIC are based on there being precisely two
4584 // signature polymorphic methods supported by the run-time which are native methods with variable
4585 // arguments.
4586 if ((method_type == METHOD_DIRECT && (!res_method->IsDirect() || res_method->IsStatic())) ||
4587 (method_type == METHOD_STATIC && !res_method->IsStatic()) ||
4588 ((method_type == METHOD_SUPER ||
4589 method_type == METHOD_VIRTUAL ||
4590 method_type == METHOD_INTERFACE) && res_method->IsDirect()) ||
4591 ((method_type == METHOD_POLYMORPHIC) &&
4592 (!res_method->IsNative() || !res_method->IsVarargs()))) {
4593 Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type (" << method_type << ") does not match method "
4594 "type of " << res_method->PrettyMethod();
4595 return nullptr;
4596 }
4597 // Make sure we weren't expecting to fail.
4598 DCHECK(!must_fail) << "invoke type (" << method_type << ")"
4599 << klass->PrettyDescriptor() << "."
4600 << dex_file_->GetMethodName(method_id) << " "
4601 << dex_file_->GetMethodSignature(method_id) << " unexpectedly resolved to "
4602 << res_method->PrettyMethod() << " without error. Initially this method was "
4603 << "not found so we were expecting to fail for some reason.";
4604 return res_method;
4605 }
4606
4607 template <class T>
VerifyInvocationArgsFromIterator(T * it,const Instruction * inst,MethodType method_type,bool is_range,ArtMethod * res_method)4608 ArtMethod* MethodVerifierImpl::VerifyInvocationArgsFromIterator(
4609 T* it, const Instruction* inst, MethodType method_type, bool is_range, ArtMethod* res_method) {
4610 DCHECK_EQ(!is_range, inst->HasVarArgs());
4611
4612 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to
4613 // match the call to the signature. Also, we might be calling through an abstract method
4614 // definition (which doesn't have register count values).
4615 const size_t expected_args = inst->VRegA();
4616 /* caught by static verifier */
4617 DCHECK(is_range || expected_args <= 5);
4618
4619 if (expected_args > code_item_accessor_.OutsSize()) {
4620 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args
4621 << ") exceeds outsSize ("
4622 << code_item_accessor_.OutsSize() << ")";
4623 return nullptr;
4624 }
4625
4626 /*
4627 * Check the "this" argument, which must be an instance of the class that declared the method.
4628 * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a
4629 * rigorous check here (which is okay since we have to do it at runtime).
4630 */
4631 if (method_type != METHOD_STATIC) {
4632 const RegType& actual_arg_type = GetInvocationThis(inst);
4633 if (actual_arg_type.IsConflict()) { // GetInvocationThis failed.
4634 CHECK(flags_.have_pending_hard_failure_);
4635 return nullptr;
4636 }
4637 bool is_init = false;
4638 if (actual_arg_type.IsUninitializedTypes()) {
4639 if (res_method != nullptr) {
4640 if (!res_method->IsConstructor()) {
4641 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
4642 return nullptr;
4643 }
4644 } else {
4645 // Check whether the name of the called method is "<init>"
4646 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
4647 if (strcmp(dex_file_->GetMethodName(dex_file_->GetMethodId(method_idx)), "<init>") != 0) {
4648 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
4649 return nullptr;
4650 }
4651 }
4652 is_init = true;
4653 }
4654 const RegType& adjusted_type = is_init
4655 ? GetRegTypeCache()->FromUninitialized(actual_arg_type)
4656 : actual_arg_type;
4657 if (method_type != METHOD_INTERFACE && !adjusted_type.IsZeroOrNull()) {
4658 // Get the referenced class first. This is fast because it's already cached by the type
4659 // index due to method resolution. It is usually the resolved method's declaring class.
4660 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
4661 const dex::TypeIndex class_idx = dex_file_->GetMethodId(method_idx).class_idx_;
4662 const RegType* res_method_class = ®_types_.FromTypeIndex(class_idx);
4663 DCHECK_IMPLIES(res_method != nullptr,
4664 res_method_class->IsJavaLangObject() || res_method_class->IsReference());
4665 DCHECK_IMPLIES(res_method != nullptr && res_method_class->IsJavaLangObject(),
4666 res_method->GetDeclaringClass()->IsObjectClass());
4667 // Miranda methods have the declaring interface as their declaring class, not the abstract
4668 // class. It would be wrong to use this for the type check (interface type checks are
4669 // postponed to runtime).
4670 if (res_method != nullptr && res_method_class->IsReference() && !res_method->IsMiranda()) {
4671 ObjPtr<mirror::Class> klass = res_method->GetDeclaringClass();
4672 if (res_method_class->GetClass() != klass) {
4673 // The resolved method is in a superclass, not directly in the referenced class.
4674 res_method_class = ®_types_.FromClass(klass);
4675 }
4676 }
4677 if (!IsAssignableFrom(*res_method_class, adjusted_type)) {
4678 Fail(adjusted_type.IsUnresolvedTypes()
4679 ? VERIFY_ERROR_UNRESOLVED_TYPE_CHECK
4680 : VERIFY_ERROR_BAD_CLASS_HARD)
4681 << "'this' argument '" << actual_arg_type << "' not instance of '"
4682 << *res_method_class << "'";
4683 // Continue on soft failures. We need to find possible hard failures to avoid problems in
4684 // the compiler.
4685 if (flags_.have_pending_hard_failure_) {
4686 return nullptr;
4687 }
4688 }
4689 }
4690 }
4691
4692 uint32_t arg[5];
4693 if (!is_range) {
4694 inst->GetVarArgs(arg);
4695 }
4696 uint32_t sig_registers = (method_type == METHOD_STATIC) ? 0 : 1;
4697 for ( ; it->HasNext(); it->Next()) {
4698 if (sig_registers >= expected_args) {
4699 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << inst->VRegA() <<
4700 " argument registers, method signature has " << sig_registers + 1 << " or more";
4701 return nullptr;
4702 }
4703
4704 const RegType& reg_type = reg_types_.FromTypeIndex(it->GetTypeIdx());
4705 uint32_t get_reg = is_range ? inst->VRegC() + static_cast<uint32_t>(sig_registers) :
4706 arg[sig_registers];
4707 if (reg_type.IsIntegralTypes()) {
4708 const RegType& src_type = work_line_->GetRegisterType(this, get_reg);
4709 if (!src_type.IsIntegralTypes()) {
4710 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register v" << get_reg << " has type " << src_type
4711 << " but expected " << reg_type;
4712 return nullptr;
4713 }
4714 } else {
4715 if (!VerifyRegisterType(get_reg, reg_type)) {
4716 // Continue on soft failures. We need to find possible hard failures to avoid problems in
4717 // the compiler.
4718 if (flags_.have_pending_hard_failure_) {
4719 return nullptr;
4720 }
4721 } else if (reg_type.IsLongOrDoubleTypes()) {
4722 // Check that registers are consecutive (for non-range invokes). Invokes are the only
4723 // instructions not specifying register pairs by the first component, but require them
4724 // nonetheless. Only check when there's an actual register in the parameters. If there's
4725 // none, this will fail below.
4726 if (!is_range && sig_registers + 1 < expected_args) {
4727 uint32_t second_reg = arg[sig_registers + 1];
4728 if (second_reg != get_reg + 1) {
4729 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, long or double parameter "
4730 "at index " << sig_registers << " is not a pair: " << get_reg << " + "
4731 << second_reg << ".";
4732 return nullptr;
4733 }
4734 }
4735 }
4736 }
4737 sig_registers += reg_type.IsLongOrDoubleTypes() ? 2 : 1;
4738 }
4739 if (expected_args != sig_registers) {
4740 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << expected_args <<
4741 " argument registers, method signature has " << sig_registers;
4742 return nullptr;
4743 }
4744 return res_method;
4745 }
4746
VerifyInvocationArgsUnresolvedMethod(const Instruction * inst,MethodType method_type,bool is_range)4747 void MethodVerifierImpl::VerifyInvocationArgsUnresolvedMethod(const Instruction* inst,
4748 MethodType method_type,
4749 bool is_range) {
4750 // As the method may not have been resolved, make this static check against what we expect.
4751 // The main reason for this code block is to fail hard when we find an illegal use, e.g.,
4752 // wrong number of arguments or wrong primitive types, even if the method could not be resolved.
4753 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
4754 DexFileParameterIterator it(*dex_file_,
4755 dex_file_->GetProtoId(dex_file_->GetMethodId(method_idx).proto_idx_));
4756 VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, nullptr);
4757 }
4758
CheckCallSite(uint32_t call_site_idx)4759 bool MethodVerifierImpl::CheckCallSite(uint32_t call_site_idx) {
4760 if (call_site_idx >= dex_file_->NumCallSiteIds()) {
4761 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Bad call site id #" << call_site_idx
4762 << " >= " << dex_file_->NumCallSiteIds();
4763 return false;
4764 }
4765
4766 CallSiteArrayValueIterator it(*dex_file_, dex_file_->GetCallSiteId(call_site_idx));
4767 // Check essential arguments are provided. The dex file verifier has verified indices of the
4768 // main values (method handle, name, method_type).
4769 static const size_t kRequiredArguments = 3;
4770 if (it.Size() < kRequiredArguments) {
4771 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site #" << call_site_idx
4772 << " has too few arguments: "
4773 << it.Size() << " < " << kRequiredArguments;
4774 return false;
4775 }
4776
4777 std::pair<const EncodedArrayValueIterator::ValueType, size_t> type_and_max[kRequiredArguments] =
4778 { { EncodedArrayValueIterator::ValueType::kMethodHandle, dex_file_->NumMethodHandles() },
4779 { EncodedArrayValueIterator::ValueType::kString, dex_file_->NumStringIds() },
4780 { EncodedArrayValueIterator::ValueType::kMethodType, dex_file_->NumProtoIds() }
4781 };
4782 uint32_t index[kRequiredArguments];
4783
4784 // Check arguments have expected types and are within permitted ranges.
4785 for (size_t i = 0; i < kRequiredArguments; ++i) {
4786 if (it.GetValueType() != type_and_max[i].first) {
4787 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site id #" << call_site_idx
4788 << " argument " << i << " has wrong type "
4789 << it.GetValueType() << "!=" << type_and_max[i].first;
4790 return false;
4791 }
4792 index[i] = static_cast<uint32_t>(it.GetJavaValue().i);
4793 if (index[i] >= type_and_max[i].second) {
4794 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site id #" << call_site_idx
4795 << " argument " << i << " bad index "
4796 << index[i] << " >= " << type_and_max[i].second;
4797 return false;
4798 }
4799
4800 // Don't increase if we are going to read past the item.
4801 if (i != kRequiredArguments - 1) {
4802 it.Next();
4803 }
4804 }
4805
4806 // Check method handle kind is valid.
4807 const dex::MethodHandleItem& mh = dex_file_->GetMethodHandle(index[0]);
4808 if (mh.method_handle_type_ != static_cast<uint16_t>(DexFile::MethodHandleType::kInvokeStatic)) {
4809 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site #" << call_site_idx
4810 << " argument 0 method handle type is not InvokeStatic: "
4811 << mh.method_handle_type_;
4812 return false;
4813 }
4814 return true;
4815 }
4816
VerifyInvocationArgs(const Instruction * inst,MethodType method_type,bool is_range)4817 ArtMethod* MethodVerifierImpl::VerifyInvocationArgs(
4818 const Instruction* inst, MethodType method_type, bool is_range) {
4819 // Resolve the method. This could be an abstract or concrete method depending on what sort of call
4820 // we're making.
4821 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
4822 ArtMethod* res_method = ResolveMethodAndCheckAccess(method_idx, method_type);
4823 if (res_method == nullptr) { // error or class is unresolved
4824 // Check what we can statically.
4825 if (!flags_.have_pending_hard_failure_) {
4826 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4827 }
4828 return nullptr;
4829 }
4830
4831 // If we're using invoke-super(method), make sure that the executing method's class' superclass
4832 // has a vtable entry for the target method. Or the target is on a interface.
4833 if (method_type == METHOD_SUPER) {
4834 dex::TypeIndex class_idx = dex_file_->GetMethodId(method_idx).class_idx_;
4835 const RegType& reference_type = reg_types_.FromTypeIndex(class_idx);
4836 if (reference_type.IsUnresolvedTypes()) {
4837 // We cannot differentiate on whether this is a class change error or just
4838 // a missing method. This will be handled at runtime.
4839 Fail(VERIFY_ERROR_NO_METHOD) << "Unable to find referenced class from invoke-super";
4840 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4841 return nullptr;
4842 }
4843 DCHECK(reference_type.IsJavaLangObject() || reference_type.IsReference());
4844 if (reference_type.IsReference() && reference_type.GetClass()->IsInterface()) {
4845 if (!GetDeclaringClass().HasClass()) {
4846 Fail(VERIFY_ERROR_NO_CLASS) << "Unable to resolve the full class of 'this' used in an"
4847 << "interface invoke-super";
4848 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4849 return nullptr;
4850 } else if (!IsStrictlyAssignableFrom(reference_type, GetDeclaringClass())) {
4851 Fail(VERIFY_ERROR_CLASS_CHANGE)
4852 << "invoke-super in " << mirror::Class::PrettyClass(GetDeclaringClass().GetClass())
4853 << " in method "
4854 << dex_file_->PrettyMethod(dex_method_idx_) << " to method "
4855 << dex_file_->PrettyMethod(method_idx) << " references "
4856 << "non-super-interface type " << mirror::Class::PrettyClass(reference_type.GetClass());
4857 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4858 return nullptr;
4859 }
4860 } else {
4861 if (UNLIKELY(!class_def_.superclass_idx_.IsValid())) {
4862 // Verification error in `j.l.Object` leads to a hang while trying to verify
4863 // the exception class. It is better to crash directly.
4864 LOG(FATAL) << "No superclass for invoke-super from "
4865 << dex_file_->PrettyMethod(dex_method_idx_)
4866 << " to super " << res_method->PrettyMethod() << ".";
4867 UNREACHABLE();
4868 }
4869 const RegType& super = reg_types_.FromTypeIndex(class_def_.superclass_idx_);
4870 if (super.IsUnresolvedTypes()) {
4871 Fail(VERIFY_ERROR_NO_METHOD) << "unknown super class in invoke-super from "
4872 << dex_file_->PrettyMethod(dex_method_idx_)
4873 << " to super " << res_method->PrettyMethod();
4874 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4875 return nullptr;
4876 }
4877 if (!IsStrictlyAssignableFrom(reference_type, GetDeclaringClass()) ||
4878 (res_method->GetMethodIndex() >= GetRegTypeClass(super)->GetVTableLength())) {
4879 Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from "
4880 << dex_file_->PrettyMethod(dex_method_idx_)
4881 << " to super " << super
4882 << "." << res_method->GetName()
4883 << res_method->GetSignature();
4884 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4885 return nullptr;
4886 }
4887 }
4888 }
4889
4890 dex::ProtoIndex proto_idx;
4891 if (UNLIKELY(method_type == METHOD_POLYMORPHIC)) {
4892 // Process the signature of the calling site that is invoking the method handle.
4893 proto_idx = dex::ProtoIndex(inst->VRegH());
4894 } else {
4895 // Process the target method's signature.
4896 proto_idx = dex_file_->GetMethodId(method_idx).proto_idx_;
4897 }
4898 DexFileParameterIterator it(*dex_file_, dex_file_->GetProtoId(proto_idx));
4899 ArtMethod* verified_method =
4900 VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, res_method);
4901
4902 if (verified_method != nullptr && !verified_method->GetDeclaringClass()->IsInterface()) {
4903 CheckForFinalAbstractClass(res_method->GetDeclaringClass());
4904 }
4905
4906 return verified_method;
4907 }
4908
CheckSignaturePolymorphicMethod(ArtMethod * method)4909 bool MethodVerifierImpl::CheckSignaturePolymorphicMethod(ArtMethod* method) {
4910 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
4911 const char* method_name = method->GetName();
4912
4913 const char* expected_return_descriptor;
4914 ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots = GetClassLinker()->GetClassRoots();
4915 if (klass == GetClassRoot<mirror::MethodHandle>(class_roots)) {
4916 expected_return_descriptor = mirror::MethodHandle::GetReturnTypeDescriptor(method_name);
4917 } else if (klass == GetClassRoot<mirror::VarHandle>(class_roots)) {
4918 expected_return_descriptor = mirror::VarHandle::GetReturnTypeDescriptor(method_name);
4919 } else {
4920 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4921 << "Signature polymorphic method in unsuppported class: " << klass->PrettyDescriptor();
4922 return false;
4923 }
4924
4925 if (expected_return_descriptor == nullptr) {
4926 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4927 << "Signature polymorphic method name invalid: " << method_name;
4928 return false;
4929 }
4930
4931 const dex::TypeList* types = method->GetParameterTypeList();
4932 if (types->Size() != 1) {
4933 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4934 << "Signature polymorphic method has too many arguments " << types->Size() << " != 1";
4935 return false;
4936 }
4937
4938 const dex::TypeIndex argument_type_index = types->GetTypeItem(0).type_idx_;
4939 const char* argument_descriptor = method->GetTypeDescriptorFromTypeIdx(argument_type_index);
4940 if (strcmp(argument_descriptor, "[Ljava/lang/Object;") != 0) {
4941 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4942 << "Signature polymorphic method has unexpected argument type: " << argument_descriptor;
4943 return false;
4944 }
4945
4946 const char* return_descriptor = method->GetReturnTypeDescriptor();
4947 if (strcmp(return_descriptor, expected_return_descriptor) != 0) {
4948 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4949 << "Signature polymorphic method has unexpected return type: " << return_descriptor
4950 << " != " << expected_return_descriptor;
4951 return false;
4952 }
4953
4954 return true;
4955 }
4956
CheckSignaturePolymorphicReceiver(const Instruction * inst)4957 bool MethodVerifierImpl::CheckSignaturePolymorphicReceiver(const Instruction* inst) {
4958 const RegType& this_type = GetInvocationThis(inst);
4959 if (this_type.IsZeroOrNull()) {
4960 /* null pointer always passes (and always fails at run time) */
4961 return true;
4962 } else if (!this_type.IsNonZeroReferenceTypes()) {
4963 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4964 << "invoke-polymorphic receiver is not a reference: "
4965 << this_type;
4966 return false;
4967 } else if (this_type.IsUninitializedReference()) {
4968 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4969 << "invoke-polymorphic receiver is uninitialized: "
4970 << this_type;
4971 return false;
4972 } else if (!this_type.HasClass()) {
4973 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4974 << "invoke-polymorphic receiver has no class: "
4975 << this_type;
4976 return false;
4977 } else {
4978 ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots = GetClassLinker()->GetClassRoots();
4979 if (!this_type.GetClass()->IsSubClass(GetClassRoot<mirror::MethodHandle>(class_roots)) &&
4980 !this_type.GetClass()->IsSubClass(GetClassRoot<mirror::VarHandle>(class_roots))) {
4981 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4982 << "invoke-polymorphic receiver is not a subclass of MethodHandle or VarHandle: "
4983 << this_type;
4984 return false;
4985 }
4986 }
4987 return true;
4988 }
4989
VerifyFilledNewArray(const Instruction * inst,bool is_range)4990 bool MethodVerifierImpl::VerifyFilledNewArray(const Instruction* inst, bool is_range) {
4991 dex::TypeIndex type_idx;
4992 if (!is_range) {
4993 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY);
4994 type_idx = dex::TypeIndex(inst->VRegB_35c());
4995 } else {
4996 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY_RANGE);
4997 type_idx = dex::TypeIndex(inst->VRegB_3rc());
4998 }
4999 // Dex file verifier ensures that all valid type indexes reference valid descriptors and the
5000 // `CheckNewArray()` ensures that the descriptor starts with an `[` before we get to the
5001 // code flow verification. So, we should see only array types here.
5002 const RegType& res_type = ResolveClass<CheckAccess::kYes>(type_idx);
5003 DCHECK(res_type.IsArrayTypes());
5004 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
5005 DCHECK(!res_type.IsUnresolvedMergedReference());
5006 // Verify each input register. It's legal, if silly, for arg_count to be zero.
5007 const RegType& expected_type = reg_types_.GetComponentType(res_type);
5008 uint32_t arg_count = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c();
5009 uint32_t arg[5];
5010 if (!is_range) {
5011 inst->GetVarArgs(arg);
5012 }
5013 for (size_t ui = 0; ui < arg_count; ui++) {
5014 uint32_t get_reg = is_range ? inst->VRegC_3rc() + ui : arg[ui];
5015 if (!VerifyRegisterType(get_reg, expected_type)) {
5016 // Don't continue on hard failures.
5017 DCHECK(flags_.have_pending_hard_failure_);
5018 return false;
5019 }
5020 DCHECK(!flags_.have_pending_hard_failure_);
5021 }
5022 // filled-array result goes into "result" register
5023 work_line_->SetResultRegisterType(res_type);
5024 return true;
5025 }
5026
VerifyAGet(const Instruction * inst,const RegType & insn_type,bool is_primitive)5027 void MethodVerifierImpl::VerifyAGet(const Instruction* inst,
5028 const RegType& insn_type,
5029 bool is_primitive) {
5030 const RegType& index_type = work_line_->GetRegisterType(this, inst->VRegC_23x());
5031 if (!index_type.IsArrayIndexTypes()) {
5032 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
5033 } else {
5034 const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegB_23x());
5035 if (array_type.IsZeroOrNull()) {
5036 // Null array class; this code path will fail at runtime. Infer a merge-able type from the
5037 // instruction type.
5038 if (!is_primitive) {
5039 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_23x(), reg_types_.Null());
5040 } else if (insn_type.IsInteger()) {
5041 // Pick a non-zero constant (to distinguish with null) that can fit in any primitive.
5042 // We cannot use 'insn_type' as it could be a float array or an int array.
5043 work_line_->SetRegisterType(inst->VRegA_23x(), DetermineCat1Constant(1));
5044 } else if (insn_type.IsCategory1Types()) {
5045 // Category 1
5046 // The 'insn_type' is exactly the type we need.
5047 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_23x(), insn_type);
5048 } else {
5049 // Category 2
5050 work_line_->SetRegisterTypeWide(inst->VRegA_23x(),
5051 RegType::kConstantLo,
5052 RegType::kConstantHi);
5053 }
5054 } else if (!array_type.IsArrayTypes()) {
5055 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aget";
5056 } else if (array_type.IsUnresolvedMergedReference()) {
5057 // Unresolved array types must be reference array types.
5058 if (is_primitive) {
5059 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type
5060 << " source for category 1 aget";
5061 } else {
5062 Fail(VERIFY_ERROR_NO_CLASS) << "cannot verify aget for " << array_type
5063 << " because of missing class";
5064 // Approximate with java.lang.Object[].
5065 work_line_->SetRegisterType(inst->VRegA_23x(), RegType::Kind::kJavaLangObject);
5066 }
5067 } else {
5068 /* verify the class */
5069 const RegType& component_type = reg_types_.GetComponentType(array_type);
5070 if (!component_type.IsReferenceTypes() && !is_primitive) {
5071 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
5072 << " source for aget-object";
5073 } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) {
5074 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type
5075 << " source for category 1 aget";
5076 } else if (is_primitive && !insn_type.Equals(component_type) &&
5077 !((insn_type.IsInteger() && component_type.IsFloat()) ||
5078 (insn_type.IsLongLo() && component_type.IsDoubleLo()))) {
5079 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type
5080 << " incompatible with aget of type " << insn_type;
5081 } else {
5082 // Use knowledge of the field type which is stronger than the type inferred from the
5083 // instruction, which can't differentiate object types and ints from floats, longs from
5084 // doubles.
5085 if (!component_type.IsLowHalf()) {
5086 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_23x(), component_type);
5087 } else {
5088 work_line_->SetRegisterTypeWide(inst->VRegA_23x(), component_type,
5089 component_type.HighHalf(®_types_));
5090 }
5091 }
5092 }
5093 }
5094 }
5095
VerifyPrimitivePut(const RegType & target_type,uint32_t vregA)5096 void MethodVerifierImpl::VerifyPrimitivePut(const RegType& target_type, uint32_t vregA) {
5097 // Primitive assignability rules are weaker than regular assignability rules.
5098 bool value_compatible;
5099 const RegType& value_type = work_line_->GetRegisterType(this, vregA);
5100 if (target_type.IsIntegralTypes()) {
5101 value_compatible = value_type.IsIntegralTypes();
5102 } else if (target_type.IsFloat()) {
5103 value_compatible = value_type.IsFloatTypes();
5104 } else if (target_type.IsLongLo()) {
5105 DCHECK_LT(vregA + 1, work_line_->NumRegs());
5106 const RegType& value_type_hi = work_line_->GetRegisterType(this, vregA + 1);
5107 value_compatible = value_type.IsLongTypes() && value_type.CheckWidePair(value_type_hi);
5108 } else if (target_type.IsDoubleLo()) {
5109 DCHECK_LT(vregA + 1, work_line_->NumRegs());
5110 const RegType& value_type_hi = work_line_->GetRegisterType(this, vregA + 1);
5111 value_compatible = value_type.IsDoubleTypes() && value_type.CheckWidePair(value_type_hi);
5112 } else {
5113 value_compatible = false; // unused
5114 }
5115 if (!value_compatible) {
5116 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA
5117 << " of type " << value_type << " but expected " << target_type << " for put";
5118 return;
5119 }
5120 }
5121
VerifyAPut(const Instruction * inst,const RegType & insn_type,bool is_primitive)5122 void MethodVerifierImpl::VerifyAPut(const Instruction* inst,
5123 const RegType& insn_type,
5124 bool is_primitive) {
5125 const RegType& index_type = work_line_->GetRegisterType(this, inst->VRegC_23x());
5126 if (!index_type.IsArrayIndexTypes()) {
5127 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
5128 } else {
5129 const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegB_23x());
5130 if (array_type.IsZeroOrNull()) {
5131 // Null array type; this code path will fail at runtime.
5132 // Still check that the given value matches the instruction's type.
5133 // Note: this is, as usual, complicated by the fact the the instruction isn't fully typed
5134 // and fits multiple register types.
5135 const RegType* modified_reg_type = &insn_type;
5136 if ((modified_reg_type == ®_types_.Integer()) ||
5137 (modified_reg_type == ®_types_.LongLo())) {
5138 // May be integer or float | long or double. Overwrite insn_type accordingly.
5139 const RegType& value_type = work_line_->GetRegisterType(this, inst->VRegA_23x());
5140 if (modified_reg_type == ®_types_.Integer()) {
5141 if (&value_type == ®_types_.Float()) {
5142 modified_reg_type = &value_type;
5143 }
5144 } else {
5145 if (&value_type == ®_types_.DoubleLo()) {
5146 modified_reg_type = &value_type;
5147 }
5148 }
5149 }
5150 VerifyRegisterType(inst->VRegA_23x(), *modified_reg_type);
5151 } else if (!array_type.IsArrayTypes()) {
5152 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aput";
5153 } else if (array_type.IsUnresolvedMergedReference()) {
5154 // Unresolved array types must be reference array types.
5155 if (is_primitive) {
5156 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "aput insn has type '" << insn_type
5157 << "' but unresolved type '" << array_type << "'";
5158 } else {
5159 Fail(VERIFY_ERROR_NO_CLASS) << "cannot verify aput for " << array_type
5160 << " because of missing class";
5161 }
5162 } else {
5163 const RegType& component_type = reg_types_.GetComponentType(array_type);
5164 const uint32_t vregA = inst->VRegA_23x();
5165 if (is_primitive) {
5166 bool instruction_compatible;
5167 if (component_type.IsIntegralTypes()) {
5168 instruction_compatible = component_type.Equals(insn_type);
5169 } else if (component_type.IsFloat()) {
5170 instruction_compatible = insn_type.IsInteger(); // no put-float, so expect put-int
5171 } else if (component_type.IsLongLo()) {
5172 instruction_compatible = insn_type.IsLongLo();
5173 } else if (component_type.IsDoubleLo()) {
5174 instruction_compatible = insn_type.IsLongLo(); // no put-double, so expect put-long
5175 } else {
5176 instruction_compatible = false; // reference with primitive store
5177 }
5178 if (!instruction_compatible) {
5179 // This is a global failure rather than a class change failure as the instructions and
5180 // the descriptors for the type should have been consistent within the same file at
5181 // compile time.
5182 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "aput insn has type '" << insn_type
5183 << "' but expected type '" << component_type << "'";
5184 return;
5185 }
5186 VerifyPrimitivePut(component_type, vregA);
5187 } else {
5188 if (!component_type.IsReferenceTypes()) {
5189 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
5190 << " source for aput-object";
5191 } else {
5192 // The instruction agrees with the type of array, confirm the value to be stored does too
5193 // Note: we use the instruction type (rather than the component type) for aput-object as
5194 // incompatible classes will be caught at runtime as an array store exception
5195 VerifyRegisterType(vregA, insn_type);
5196 }
5197 }
5198 }
5199 }
5200 }
5201
GetStaticField(uint32_t field_idx,bool is_put)5202 ArtField* MethodVerifierImpl::GetStaticField(uint32_t field_idx, bool is_put) {
5203 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
5204 // Check access to class
5205 const RegType& klass_type = ResolveClass<CheckAccess::kYes>(field_id.class_idx_);
5206 // Dex file verifier ensures that field ids reference valid descriptors starting with `L`.
5207 DCHECK(klass_type.IsJavaLangObject() ||
5208 klass_type.IsReference() ||
5209 klass_type.IsUnresolvedReference());
5210 if (klass_type.IsUnresolvedReference()) {
5211 // Accessibility checks depend on resolved fields.
5212 DCHECK(klass_type.Equals(GetDeclaringClass()) ||
5213 !failures_.empty() ||
5214 IsSdkVersionSetAndLessThan(api_level_, SdkVersion::kP));
5215 return nullptr; // Can't resolve Class so no more to do here, will do checking at runtime.
5216 }
5217 ClassLinker* class_linker = GetClassLinker();
5218 ArtField* field = class_linker->ResolveFieldJLS(field_idx, dex_cache_, class_loader_);
5219 if (field == nullptr) {
5220 VLOG(verifier) << "Unable to resolve static field " << field_idx << " ("
5221 << dex_file_->GetFieldName(field_id) << ") in "
5222 << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
5223 DCHECK(self_->IsExceptionPending());
5224 self_->ClearException();
5225 Fail(VERIFY_ERROR_NO_FIELD)
5226 << "field " << dex_file_->PrettyField(field_idx)
5227 << " not found in the resolved type " << klass_type;
5228 return nullptr;
5229 } else if (!field->IsStatic()) {
5230 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << field->PrettyField() << " to be static";
5231 return nullptr;
5232 }
5233
5234 return GetISFieldCommon(field, is_put);
5235 }
5236
GetInstanceField(uint32_t vregB,uint32_t field_idx,bool is_put)5237 ArtField* MethodVerifierImpl::GetInstanceField(uint32_t vregB, uint32_t field_idx, bool is_put) {
5238 const RegType& obj_type = work_line_->GetRegisterType(this, vregB);
5239 if (!obj_type.IsReferenceTypes()) {
5240 // Trying to read a field from something that isn't a reference.
5241 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
5242 << "instance field access on object that has non-reference type " << obj_type;
5243 return nullptr;
5244 }
5245 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
5246 // Check access to class.
5247 const RegType& klass_type = ResolveClass<CheckAccess::kYes>(field_id.class_idx_);
5248 // Dex file verifier ensures that field ids reference valid descriptors starting with `L`.
5249 DCHECK(klass_type.IsJavaLangObject() ||
5250 klass_type.IsReference() ||
5251 klass_type.IsUnresolvedReference());
5252 ArtField* field = nullptr;
5253 if (!klass_type.IsUnresolvedReference()) {
5254 ClassLinker* class_linker = GetClassLinker();
5255 field = class_linker->ResolveFieldJLS(field_idx, dex_cache_, class_loader_);
5256 if (field == nullptr) {
5257 VLOG(verifier) << "Unable to resolve instance field " << field_idx << " ("
5258 << dex_file_->GetFieldName(field_id) << ") in "
5259 << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
5260 DCHECK(self_->IsExceptionPending());
5261 self_->ClearException();
5262 }
5263 }
5264
5265 if (obj_type.IsUninitializedTypes()) {
5266 // One is not allowed to access fields on uninitialized references, except to write to
5267 // fields in the constructor (before calling another constructor). We strictly check
5268 // that the field id references the class directly instead of some subclass.
5269 if (is_put && field_id.class_idx_ == GetClassDef().class_idx_) {
5270 if (obj_type.IsUnresolvedUninitializedThisReference()) {
5271 DCHECK(GetDeclaringClass().IsUnresolvedReference());
5272 DCHECK(GetDeclaringClass().Equals(reg_types_.FromUninitialized(obj_type)));
5273 ClassAccessor accessor(*dex_file_, GetClassDef());
5274 auto it = std::find_if(
5275 accessor.GetInstanceFields().begin(),
5276 accessor.GetInstanceFields().end(),
5277 [field_idx] (const ClassAccessor::Field& f) { return f.GetIndex() == field_idx; });
5278 if (it != accessor.GetInstanceFields().end()) {
5279 // There are no soft failures to report anymore, other than the class being unresolved.
5280 return nullptr;
5281 }
5282 } else if (obj_type.IsUninitializedThisReference()) {
5283 DCHECK(GetDeclaringClass().IsJavaLangObject() || GetDeclaringClass().IsReference());
5284 DCHECK(GetDeclaringClass().Equals(reg_types_.FromUninitialized(obj_type)));
5285 if (field != nullptr &&
5286 field->GetDeclaringClass() == GetDeclaringClass().GetClass() &&
5287 !field->IsStatic()) {
5288 // The field is now fully verified against the `obj_type`.
5289 return field;
5290 }
5291 }
5292 }
5293 // Allow `iget` on resolved uninitialized `this` for app compatibility.
5294 // This is rejected by the RI but there are Android apps that actually have such `iget`s.
5295 // TODO: Should we start rejecting such bytecode based on the SDK level?
5296 if (!is_put &&
5297 obj_type.IsUninitializedThisReference() &&
5298 field != nullptr &&
5299 field->GetDeclaringClass() == GetDeclaringClass().GetClass()) {
5300 return field;
5301 }
5302 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
5303 << "cannot access instance field " << dex_file_->PrettyField(field_idx)
5304 << " of a not fully initialized object within the context of "
5305 << dex_file_->PrettyMethod(dex_method_idx_);
5306 return nullptr;
5307 }
5308
5309 if (klass_type.IsUnresolvedReference()) {
5310 // Accessibility checks depend on resolved fields.
5311 DCHECK(klass_type.Equals(GetDeclaringClass()) ||
5312 !failures_.empty() ||
5313 IsSdkVersionSetAndLessThan(api_level_, SdkVersion::kP));
5314 return nullptr; // Can't resolve Class so no more to do here, will do checking at runtime.
5315 } else if (field == nullptr) {
5316 Fail(VERIFY_ERROR_NO_FIELD)
5317 << "field " << dex_file_->PrettyField(field_idx)
5318 << " not found in the resolved type " << klass_type;
5319 return nullptr;
5320 } else if (obj_type.IsZeroOrNull()) {
5321 // Cannot infer and check type, however, access will cause null pointer exception.
5322 // Fall through into a few last soft failure checks below.
5323 } else {
5324 ObjPtr<mirror::Class> klass = field->GetDeclaringClass();
5325 DCHECK_IMPLIES(klass_type.IsJavaLangObject(), klass->IsObjectClass());
5326 const RegType& field_klass =
5327 LIKELY(klass_type.IsJavaLangObject() || klass_type.GetClass() == klass)
5328 ? klass_type
5329 : reg_types_.FromClass(klass);
5330 DCHECK(!obj_type.IsUninitializedTypes());
5331 if (!IsAssignableFrom(field_klass, obj_type)) {
5332 // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class
5333 // of C1. For resolution to occur the declared class of the field must be compatible with
5334 // obj_type, we've discovered this wasn't so, so report the field didn't exist.
5335 DCHECK(!field_klass.IsUnresolvedTypes());
5336 Fail(obj_type.IsUnresolvedTypes()
5337 ? VERIFY_ERROR_UNRESOLVED_TYPE_CHECK
5338 : VERIFY_ERROR_BAD_CLASS_HARD)
5339 << "cannot access instance field " << field->PrettyField()
5340 << " from object of type " << obj_type;
5341 return nullptr;
5342 }
5343 }
5344
5345 // Few last soft failure checks.
5346 if (field->IsStatic()) {
5347 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << field->PrettyField()
5348 << " to not be static";
5349 return nullptr;
5350 }
5351
5352 return GetISFieldCommon(field, is_put);
5353 }
5354
GetISFieldCommon(ArtField * field,bool is_put)5355 ArtField* MethodVerifierImpl::GetISFieldCommon(ArtField* field, bool is_put) {
5356 DCHECK(field != nullptr);
5357 if (!CanAccessMember(field->GetDeclaringClass(), field->GetAccessFlags())) {
5358 Fail(VERIFY_ERROR_ACCESS_FIELD)
5359 << "cannot access " << (field->IsStatic() ? "static" : "instance") << " field "
5360 << field->PrettyField() << " from " << GetDeclaringClass();
5361 return nullptr;
5362 }
5363 if (is_put && field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) {
5364 Fail(VERIFY_ERROR_ACCESS_FIELD)
5365 << "cannot modify final field " << field->PrettyField()
5366 << " from other class " << GetDeclaringClass();
5367 return nullptr;
5368 }
5369 CheckForFinalAbstractClass(field->GetDeclaringClass());
5370 return field;
5371 }
5372
5373 template <FieldAccessType kAccType>
VerifyISFieldAccess(const Instruction * inst,bool is_primitive,bool is_static)5374 void MethodVerifierImpl::VerifyISFieldAccess(const Instruction* inst,
5375 bool is_primitive,
5376 bool is_static) {
5377 uint32_t field_idx = GetFieldIdxOfFieldAccess(inst);
5378 DCHECK(!flags_.have_pending_hard_failure_);
5379 ArtField* field;
5380 if (is_static) {
5381 field = GetStaticField(field_idx, kAccType == FieldAccessType::kAccPut);
5382 } else {
5383 field = GetInstanceField(inst->VRegB_22c(), field_idx, kAccType == FieldAccessType::kAccPut);
5384 if (UNLIKELY(flags_.have_pending_hard_failure_)) {
5385 return;
5386 }
5387 }
5388 DCHECK(!flags_.have_pending_hard_failure_);
5389 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
5390 DCHECK_IMPLIES(field == nullptr && IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP),
5391 field_id.class_idx_ == class_def_.class_idx_ || !failures_.empty());
5392 const RegType& field_type = reg_types_.FromTypeIndex(field_id.type_idx_);
5393 const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c();
5394 static_assert(kAccType == FieldAccessType::kAccPut || kAccType == FieldAccessType::kAccGet,
5395 "Unexpected third access type");
5396 if (kAccType == FieldAccessType::kAccPut) {
5397 // sput or iput.
5398 if (is_primitive) {
5399 VerifyPrimitivePut(field_type, vregA);
5400 } else {
5401 VerifyRegisterType(vregA, field_type);
5402 }
5403 } else if (kAccType == FieldAccessType::kAccGet) {
5404 // sget or iget.
5405 if (!field_type.IsLowHalf()) {
5406 work_line_->SetRegisterType<LockOp::kClear>(vregA, field_type);
5407 } else {
5408 work_line_->SetRegisterTypeWide(vregA, field_type, field_type.HighHalf(®_types_));
5409 }
5410 } else {
5411 LOG(FATAL) << "Unexpected case.";
5412 }
5413 }
5414
5415 template <bool kVerifierDebug>
UpdateRegisters(uint32_t next_insn,RegisterLine * merge_line,bool update_merge_line)5416 void MethodVerifier<kVerifierDebug>::UpdateRegisters(uint32_t next_insn,
5417 RegisterLine* merge_line,
5418 bool update_merge_line) {
5419 DCHECK(!flags_.have_pending_hard_failure_);
5420 bool changed = true;
5421 RegisterLine* target_line = reg_table_.GetLine(next_insn);
5422 if (!GetInstructionFlags(next_insn).IsVisitedOrChanged()) {
5423 /*
5424 * We haven't processed this instruction before, and we haven't touched the registers here, so
5425 * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the
5426 * only way a register can transition out of "unknown", so this is not just an optimization.)
5427 */
5428 target_line->CopyFromLine(merge_line);
5429 } else {
5430 RegisterLineArenaUniquePtr copy;
5431 if (kVerifierDebug) {
5432 copy.reset(RegisterLine::Create(target_line->NumRegs(), allocator_));
5433 copy->CopyFromLine(target_line);
5434 }
5435 changed = target_line->MergeRegisters(this, merge_line);
5436 if (kVerifierDebug && changed) {
5437 LogVerifyInfo() << "Merging at [" << reinterpret_cast<void*>(work_insn_idx_) << "]"
5438 << " to [" << reinterpret_cast<void*>(next_insn) << "]: " << "\n"
5439 << copy->Dump(this) << " MERGE\n"
5440 << merge_line->Dump(this) << " ==\n"
5441 << target_line->Dump(this);
5442 }
5443 if (update_merge_line && changed) {
5444 merge_line->CopyFromLine(target_line);
5445 }
5446 }
5447 if (changed) {
5448 GetModifiableInstructionFlags(next_insn).SetChanged();
5449 }
5450 DCHECK(!flags_.have_pending_hard_failure_);
5451 }
5452
GetMethodReturnType()5453 const RegType& MethodVerifierImpl::GetMethodReturnType() {
5454 if (return_type_ == nullptr) {
5455 const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
5456 const dex::ProtoId& proto_id = dex_file_->GetMethodPrototype(method_id);
5457 return_type_ = ®_types_.FromTypeIndex(proto_id.return_type_idx_);
5458 }
5459 return *return_type_;
5460 }
5461
DetermineCat1Constant(int32_t value)5462 RegType::Kind MethodVerifierImpl::DetermineCat1Constant(int32_t value) {
5463 // Imprecise constant type.
5464 if (value < -32768) {
5465 return RegType::Kind::kIntegerConstant;
5466 } else if (value < -128) {
5467 return RegType::Kind::kShortConstant;
5468 } else if (value < 0) {
5469 return RegType::Kind::kByteConstant;
5470 } else if (value == 0) {
5471 return RegType::Kind::kZero;
5472 } else if (value == 1) {
5473 return RegType::Kind::kBooleanConstant;
5474 } else if (value < 128) {
5475 return RegType::Kind::kPositiveByteConstant;
5476 } else if (value < 32768) {
5477 return RegType::Kind::kPositiveShortConstant;
5478 } else if (value < 65536) {
5479 return RegType::Kind::kCharConstant;
5480 } else {
5481 return RegType::Kind::kIntegerConstant;
5482 }
5483 }
5484
PotentiallyMarkRuntimeThrow()5485 void MethodVerifierImpl::PotentiallyMarkRuntimeThrow() {
5486 if (IsAotMode() || IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kS_V2)) {
5487 return;
5488 }
5489 // Compatibility mode: we treat the following code unreachable and the verifier
5490 // will not analyze it.
5491 // The verifier may fail before we touch any instruction, for the signature of a method. So
5492 // add a check.
5493 if (work_insn_idx_ < dex::kDexNoIndex) {
5494 const Instruction& inst = code_item_accessor_.InstructionAt(work_insn_idx_);
5495 Instruction::Code opcode = inst.Opcode();
5496 DCHECK_NE(opcode, Instruction::MOVE_EXCEPTION);
5497 // How to handle runtime failures for instructions that are not flagged kThrow.
5498 if ((Instruction::FlagsOf(opcode) & Instruction::kThrow) == 0 &&
5499 !impl::IsCompatThrow(opcode) &&
5500 GetInstructionFlags(work_insn_idx_).IsInTry()) {
5501 if (Runtime::Current()->IsVerifierMissingKThrowFatal()) {
5502 LOG(FATAL) << "Unexpected throw: " << std::hex << work_insn_idx_ << " " << opcode;
5503 UNREACHABLE();
5504 }
5505 // We need to save the work_line if the instruction wasn't throwing before. Otherwise
5506 // we'll try to merge garbage.
5507 // Note: this assumes that Fail is called before we do any work_line modifications.
5508 saved_line_->CopyFromLine(work_line_.get());
5509 }
5510 }
5511 flags_.have_pending_runtime_throw_failure_ = true;
5512 }
5513
5514 } // namespace
5515 } // namespace impl
5516
GetClassLinker() const5517 inline ClassLinker* MethodVerifier::GetClassLinker() const {
5518 return reg_types_.GetClassLinker();
5519 }
5520
MethodVerifier(Thread * self,ArenaPool * arena_pool,RegTypeCache * reg_types,VerifierDeps * verifier_deps,const dex::ClassDef & class_def,const dex::CodeItem * code_item,uint32_t dex_method_idx,bool aot_mode)5521 MethodVerifier::MethodVerifier(Thread* self,
5522 ArenaPool* arena_pool,
5523 RegTypeCache* reg_types,
5524 VerifierDeps* verifier_deps,
5525 const dex::ClassDef& class_def,
5526 const dex::CodeItem* code_item,
5527 uint32_t dex_method_idx,
5528 bool aot_mode)
5529 : self_(self),
5530 allocator_(arena_pool),
5531 reg_types_(*reg_types),
5532 reg_table_(allocator_),
5533 work_insn_idx_(dex::kDexNoIndex),
5534 dex_method_idx_(dex_method_idx),
5535 dex_file_(reg_types->GetDexFile()),
5536 class_def_(class_def),
5537 code_item_accessor_(*dex_file_, code_item),
5538 failures_(allocator_.Adapter(kArenaAllocVerifier)),
5539 flags_{ .have_pending_hard_failure_ = false, .have_pending_runtime_throw_failure_ = false },
5540 const_flags_{ .aot_mode_ = aot_mode, .can_load_classes_ = reg_types->CanLoadClasses() },
5541 encountered_failure_types_(0),
5542 info_messages_(std::nullopt),
5543 verifier_deps_(verifier_deps),
5544 link_(nullptr) {
5545 }
5546
VerifyMethod(Thread * self,ArenaPool * arena_pool,RegTypeCache * reg_types,VerifierDeps * verifier_deps,uint32_t method_idx,Handle<mirror::DexCache> dex_cache,const dex::ClassDef & class_def,const dex::CodeItem * code_item,uint32_t method_access_flags,HardFailLogMode log_level,uint32_t api_level,bool aot_mode,std::string * hard_failure_msg)5547 MethodVerifier::FailureData MethodVerifier::VerifyMethod(Thread* self,
5548 ArenaPool* arena_pool,
5549 RegTypeCache* reg_types,
5550 VerifierDeps* verifier_deps,
5551 uint32_t method_idx,
5552 Handle<mirror::DexCache> dex_cache,
5553 const dex::ClassDef& class_def,
5554 const dex::CodeItem* code_item,
5555 uint32_t method_access_flags,
5556 HardFailLogMode log_level,
5557 uint32_t api_level,
5558 bool aot_mode,
5559 std::string* hard_failure_msg) {
5560 if (VLOG_IS_ON(verifier_debug)) {
5561 return VerifyMethod<true>(self,
5562 arena_pool,
5563 reg_types,
5564 verifier_deps,
5565 method_idx,
5566 dex_cache,
5567 class_def,
5568 code_item,
5569 method_access_flags,
5570 log_level,
5571 api_level,
5572 aot_mode,
5573 hard_failure_msg);
5574 } else {
5575 return VerifyMethod<false>(self,
5576 arena_pool,
5577 reg_types,
5578 verifier_deps,
5579 method_idx,
5580 dex_cache,
5581 class_def,
5582 code_item,
5583 method_access_flags,
5584 log_level,
5585 api_level,
5586 aot_mode,
5587 hard_failure_msg);
5588 }
5589 }
5590
5591 template <bool kVerifierDebug>
VerifyMethod(Thread * self,ArenaPool * arena_pool,RegTypeCache * reg_types,VerifierDeps * verifier_deps,uint32_t method_idx,Handle<mirror::DexCache> dex_cache,const dex::ClassDef & class_def,const dex::CodeItem * code_item,uint32_t method_access_flags,HardFailLogMode log_level,uint32_t api_level,bool aot_mode,std::string * hard_failure_msg)5592 MethodVerifier::FailureData MethodVerifier::VerifyMethod(Thread* self,
5593 ArenaPool* arena_pool,
5594 RegTypeCache* reg_types,
5595 VerifierDeps* verifier_deps,
5596 uint32_t method_idx,
5597 Handle<mirror::DexCache> dex_cache,
5598 const dex::ClassDef& class_def,
5599 const dex::CodeItem* code_item,
5600 uint32_t method_access_flags,
5601 HardFailLogMode log_level,
5602 uint32_t api_level,
5603 bool aot_mode,
5604 std::string* hard_failure_msg) {
5605 MethodVerifier::FailureData result;
5606 uint64_t start_ns = kTimeVerifyMethod ? NanoTime() : 0;
5607
5608 impl::MethodVerifier<kVerifierDebug> verifier(self,
5609 arena_pool,
5610 reg_types,
5611 verifier_deps,
5612 code_item,
5613 method_idx,
5614 aot_mode,
5615 dex_cache,
5616 class_def,
5617 method_access_flags,
5618 /* verify_to_dump= */ false,
5619 api_level);
5620 if (verifier.Verify()) {
5621 // Verification completed, however failures may be pending that didn't cause the verification
5622 // to hard fail.
5623 CHECK(!verifier.flags_.have_pending_hard_failure_);
5624
5625 if (verifier.failures_.size() != 0) {
5626 if (VLOG_IS_ON(verifier)) {
5627 verifier.DumpFailures(VLOG_STREAM(verifier)
5628 << "Soft verification failures in "
5629 << reg_types->GetDexFile()->PrettyMethod(method_idx) << "\n");
5630 }
5631 if (kVerifierDebug) {
5632 LOG(INFO) << verifier.InfoMessages().view();
5633 verifier.Dump(LOG_STREAM(INFO));
5634 }
5635 if (CanCompilerHandleVerificationFailure(verifier.encountered_failure_types_)) {
5636 if (verifier.encountered_failure_types_ & VERIFY_ERROR_UNRESOLVED_TYPE_CHECK) {
5637 result.kind = FailureKind::kTypeChecksFailure;
5638 } else {
5639 result.kind = FailureKind::kAccessChecksFailure;
5640 }
5641 } else {
5642 // If the compiler cannot handle the failure, force a soft failure to
5643 // ensure the class will be re-verified at runtime and the method marked
5644 // as not compilable.
5645 result.kind = FailureKind::kSoftFailure;
5646 }
5647 }
5648 } else {
5649 // Bad method data.
5650 CHECK_NE(verifier.failures_.size(), 0U);
5651 CHECK(verifier.flags_.have_pending_hard_failure_);
5652 if (VLOG_IS_ON(verifier)) {
5653 log_level = std::max(HardFailLogMode::kLogVerbose, log_level);
5654 }
5655 if (log_level >= HardFailLogMode::kLogVerbose) {
5656 LogSeverity severity;
5657 switch (log_level) {
5658 case HardFailLogMode::kLogVerbose:
5659 severity = LogSeverity::VERBOSE;
5660 break;
5661 case HardFailLogMode::kLogWarning:
5662 severity = LogSeverity::WARNING;
5663 break;
5664 case HardFailLogMode::kLogInternalFatal:
5665 severity = LogSeverity::FATAL_WITHOUT_ABORT;
5666 break;
5667 default:
5668 LOG(FATAL) << "Unsupported log-level " << static_cast<uint32_t>(log_level);
5669 UNREACHABLE();
5670 }
5671 verifier.DumpFailures(LOG_STREAM(severity)
5672 << "Verification error in "
5673 << reg_types->GetDexFile()->PrettyMethod(method_idx) << "\n");
5674 }
5675 if (hard_failure_msg != nullptr) {
5676 CHECK(!verifier.failures_.empty());
5677 *hard_failure_msg = verifier.failures_.back().message.view();
5678 }
5679 result.kind = FailureKind::kHardFailure;
5680
5681 if (kVerifierDebug || VLOG_IS_ON(verifier)) {
5682 LOG(ERROR) << verifier.InfoMessages().view();
5683 verifier.Dump(LOG_STREAM(ERROR));
5684 }
5685 // Under verifier-debug, dump the complete log into the error message.
5686 if (kVerifierDebug && hard_failure_msg != nullptr) {
5687 hard_failure_msg->append("\n");
5688 hard_failure_msg->append(verifier.InfoMessages().view());
5689 hard_failure_msg->append("\n");
5690 std::ostringstream oss;
5691 verifier.Dump(oss);
5692 hard_failure_msg->append(oss.view());
5693 }
5694 }
5695 if (kTimeVerifyMethod) {
5696 uint64_t duration_ns = NanoTime() - start_ns;
5697 if (duration_ns > MsToNs(Runtime::Current()->GetVerifierLoggingThresholdMs())) {
5698 double bytecodes_per_second =
5699 verifier.code_item_accessor_.InsnsSizeInCodeUnits() / (duration_ns * 1e-9);
5700 LOG(WARNING) << "Verification of " << reg_types->GetDexFile()->PrettyMethod(method_idx)
5701 << " took " << PrettyDuration(duration_ns)
5702 << (impl::IsLargeMethod(verifier.CodeItem()) ? " (large method)" : "")
5703 << " (" << StringPrintf("%.2f", bytecodes_per_second) << " bytecodes/s)"
5704 << " (" << verifier.allocator_.BytesAllocated() << "B arena alloc)";
5705 }
5706 }
5707 result.types = verifier.encountered_failure_types_;
5708 return result;
5709 }
5710
CalculateVerificationInfo(Thread * self,RegTypeCache * reg_types,ArtMethod * method,Handle<mirror::DexCache> dex_cache,uint32_t dex_pc)5711 MethodVerifier* MethodVerifier::CalculateVerificationInfo(
5712 Thread* self,
5713 RegTypeCache* reg_types,
5714 ArtMethod* method,
5715 Handle<mirror::DexCache> dex_cache,
5716 uint32_t dex_pc) {
5717 Runtime* runtime = Runtime::Current();
5718 std::unique_ptr<impl::MethodVerifier<false>> verifier(
5719 new impl::MethodVerifier<false>(self,
5720 runtime->GetArenaPool(),
5721 reg_types,
5722 /* verifier_deps= */ nullptr,
5723 method->GetCodeItem(),
5724 method->GetDexMethodIndex(),
5725 runtime->IsAotCompiler(),
5726 dex_cache,
5727 *method->GetDeclaringClass()->GetClassDef(),
5728 method->GetAccessFlags(),
5729 /* verify_to_dump= */ false,
5730 // Just use the verifier at the current skd-version.
5731 // This might affect what soft-verifier errors are reported.
5732 // Callers can then filter out relevant errors if needed.
5733 runtime->GetTargetSdkVersion()));
5734 verifier->interesting_dex_pc_ = dex_pc;
5735 verifier->Verify();
5736 if (VLOG_IS_ON(verifier)) {
5737 verifier->DumpFailures(VLOG_STREAM(verifier));
5738 VLOG(verifier) << verifier->InfoMessages().view();
5739 verifier->Dump(VLOG_STREAM(verifier));
5740 }
5741 if (verifier->flags_.have_pending_hard_failure_) {
5742 return nullptr;
5743 } else {
5744 return verifier.release();
5745 }
5746 }
5747
VerifyMethodAndDump(Thread * self,VariableIndentationOutputStream * vios,uint32_t dex_method_idx,const DexFile * dex_file,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,const dex::ClassDef & class_def,const dex::CodeItem * code_item,uint32_t method_access_flags,uint32_t api_level)5748 void MethodVerifier::VerifyMethodAndDump(Thread* self,
5749 VariableIndentationOutputStream* vios,
5750 uint32_t dex_method_idx,
5751 const DexFile* dex_file,
5752 Handle<mirror::DexCache> dex_cache,
5753 Handle<mirror::ClassLoader> class_loader,
5754 const dex::ClassDef& class_def,
5755 const dex::CodeItem* code_item,
5756 uint32_t method_access_flags,
5757 uint32_t api_level) {
5758 Runtime* runtime = Runtime::Current();
5759 ClassLinker* class_linker = runtime->GetClassLinker();
5760 ArenaPool* arena_pool = runtime->GetArenaPool();
5761 RegTypeCache reg_types(self, class_linker, arena_pool, class_loader, dex_file);
5762 impl::MethodVerifier<false> verifier(
5763 self,
5764 arena_pool,
5765 ®_types,
5766 /* verifier_deps= */ nullptr,
5767 code_item,
5768 dex_method_idx,
5769 runtime->IsAotCompiler(),
5770 dex_cache,
5771 class_def,
5772 method_access_flags,
5773 /* verify_to_dump= */ true,
5774 api_level);
5775 verifier.Verify();
5776 verifier.DumpFailures(vios->Stream());
5777 vios->Stream() << verifier.InfoMessages().view();
5778 // Only dump if no hard failures. Otherwise the verifier may be not fully initialized
5779 // and querying any info is dangerous/can abort.
5780 if (!verifier.flags_.have_pending_hard_failure_) {
5781 verifier.Dump(vios);
5782 }
5783 }
5784
FindLocksAtDexPc(ArtMethod * m,uint32_t dex_pc,std::vector<MethodVerifier::DexLockInfo> * monitor_enter_dex_pcs,uint32_t api_level)5785 void MethodVerifier::FindLocksAtDexPc(
5786 ArtMethod* m,
5787 uint32_t dex_pc,
5788 std::vector<MethodVerifier::DexLockInfo>* monitor_enter_dex_pcs,
5789 uint32_t api_level) {
5790 Thread* self = Thread::Current();
5791 StackHandleScope<2> hs(self);
5792 Handle<mirror::DexCache> dex_cache(hs.NewHandle(m->GetDexCache()));
5793 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(m->GetClassLoader()));
5794 Runtime* runtime = Runtime::Current();
5795 ClassLinker* class_linker = runtime->GetClassLinker();
5796 ArenaPool* arena_pool = runtime->GetArenaPool();
5797 RegTypeCache reg_types(self,
5798 class_linker,
5799 arena_pool,
5800 class_loader,
5801 dex_cache->GetDexFile(),
5802 /* can_load_classes= */ false,
5803 /* can_suspend= */ false);
5804 impl::MethodVerifier<false> verifier(self,
5805 arena_pool,
5806 ®_types,
5807 /* verifier_deps= */ nullptr,
5808 m->GetCodeItem(),
5809 m->GetDexMethodIndex(),
5810 runtime->IsAotCompiler(),
5811 dex_cache,
5812 m->GetClassDef(),
5813 m->GetAccessFlags(),
5814 /* verify_to_dump= */ false,
5815 api_level);
5816 verifier.interesting_dex_pc_ = dex_pc;
5817 verifier.monitor_enter_dex_pcs_ = monitor_enter_dex_pcs;
5818 verifier.FindLocksAtDexPc();
5819 }
5820
CreateVerifier(Thread * self,RegTypeCache * reg_types,VerifierDeps * verifier_deps,Handle<mirror::DexCache> dex_cache,const dex::ClassDef & class_def,const dex::CodeItem * code_item,uint32_t method_idx,uint32_t access_flags,bool verify_to_dump,uint32_t api_level)5821 MethodVerifier* MethodVerifier::CreateVerifier(Thread* self,
5822 RegTypeCache* reg_types,
5823 VerifierDeps* verifier_deps,
5824 Handle<mirror::DexCache> dex_cache,
5825 const dex::ClassDef& class_def,
5826 const dex::CodeItem* code_item,
5827 uint32_t method_idx,
5828 uint32_t access_flags,
5829 bool verify_to_dump,
5830 uint32_t api_level) {
5831 return new impl::MethodVerifier<false>(self,
5832 Runtime::Current()->GetArenaPool(),
5833 reg_types,
5834 verifier_deps,
5835 code_item,
5836 method_idx,
5837 Runtime::Current()->IsAotCompiler(),
5838 dex_cache,
5839 class_def,
5840 access_flags,
5841 verify_to_dump,
5842 api_level);
5843 }
5844
Fail(VerifyError error,bool pending_exc)5845 std::ostream& MethodVerifier::Fail(VerifyError error, bool pending_exc) {
5846 // Mark the error type as encountered.
5847 encountered_failure_types_ |= static_cast<uint32_t>(error);
5848
5849 if (pending_exc) {
5850 switch (error) {
5851 case VERIFY_ERROR_NO_CLASS:
5852 case VERIFY_ERROR_UNRESOLVED_TYPE_CHECK:
5853 case VERIFY_ERROR_NO_METHOD:
5854 case VERIFY_ERROR_NO_FIELD:
5855 case VERIFY_ERROR_ACCESS_CLASS:
5856 case VERIFY_ERROR_ACCESS_FIELD:
5857 case VERIFY_ERROR_ACCESS_METHOD:
5858 case VERIFY_ERROR_INSTANTIATION:
5859 case VERIFY_ERROR_FILLED_NEW_ARRAY:
5860 case VERIFY_ERROR_CLASS_CHANGE: {
5861 PotentiallyMarkRuntimeThrow();
5862 break;
5863 }
5864
5865 case VERIFY_ERROR_LOCKING:
5866 PotentiallyMarkRuntimeThrow();
5867 // This will be reported to the runtime as a soft failure.
5868 break;
5869
5870 // Hard verification failures at compile time will still fail at runtime, so the class is
5871 // marked as rejected to prevent it from being compiled.
5872 case VERIFY_ERROR_BAD_CLASS_HARD: {
5873 flags_.have_pending_hard_failure_ = true;
5874 break;
5875 }
5876
5877 case VERIFY_ERROR_RUNTIME_THROW: {
5878 LOG(FATAL) << "UNREACHABLE";
5879 }
5880 }
5881 } else if (kIsDebugBuild) {
5882 CHECK_NE(error, VERIFY_ERROR_BAD_CLASS_HARD);
5883 }
5884
5885 std::string location =
5886 StringPrintf("%s: [0x%X] ", dex_file_->PrettyMethod(dex_method_idx_).c_str(), work_insn_idx_);
5887 failures_.emplace_back(error, location, failures_.get_allocator());
5888 return failures_.back().message;
5889 }
5890
LogVerifyInfo()5891 ScopedNewLine MethodVerifier::LogVerifyInfo() {
5892 ScopedNewLine ret{InfoMessages()};
5893 ret << "VFY: " << dex_file_->PrettyMethod(dex_method_idx_)
5894 << '[' << reinterpret_cast<void*>(work_insn_idx_) << "] : ";
5895 return ret;
5896 }
5897
FailureKindMax(FailureKind fk1,FailureKind fk2)5898 static FailureKind FailureKindMax(FailureKind fk1, FailureKind fk2) {
5899 static_assert(FailureKind::kNoFailure < FailureKind::kSoftFailure
5900 && FailureKind::kSoftFailure < FailureKind::kHardFailure,
5901 "Unexpected FailureKind order");
5902 return std::max(fk1, fk2);
5903 }
5904
Merge(const MethodVerifier::FailureData & fd)5905 void MethodVerifier::FailureData::Merge(const MethodVerifier::FailureData& fd) {
5906 kind = FailureKindMax(kind, fd.kind);
5907 types |= fd.types;
5908 }
5909
GetInvocationThis(const Instruction * inst)5910 const RegType& MethodVerifier::GetInvocationThis(const Instruction* inst) {
5911 DCHECK(inst->IsInvoke());
5912 const size_t args_count = inst->VRegA();
5913 if (args_count < 1) {
5914 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke lacks 'this'";
5915 return reg_types_.Conflict();
5916 }
5917 const uint32_t this_reg = inst->VRegC();
5918 const RegType& this_type = work_line_->GetRegisterType(this, this_reg);
5919 if (!this_type.IsReferenceTypes()) {
5920 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
5921 << "tried to get class from non-reference register v" << this_reg
5922 << " (type=" << this_type << ")";
5923 return reg_types_.Conflict();
5924 }
5925 return this_type;
5926 }
5927
AssignableFrom(const RegType & lhs,const RegType & rhs,bool strict) const5928 bool MethodVerifier::AssignableFrom(const RegType& lhs, const RegType& rhs, bool strict) const {
5929 if (lhs.Equals(rhs)) {
5930 return true;
5931 }
5932
5933 RegType::Assignability assignable = RegType::AssignabilityFrom(lhs.GetKind(), rhs.GetKind());
5934 DCHECK(assignable != RegType::Assignability::kInvalid)
5935 << "Unexpected register type in IsAssignableFrom: '" << lhs << "' := '" << rhs << "'";
5936 if (assignable == RegType::Assignability::kAssignable) {
5937 return true;
5938 } else if (assignable == RegType::Assignability::kNotAssignable) {
5939 return false;
5940 } else if (assignable == RegType::Assignability::kNarrowingConversion) {
5941 // FIXME: The `MethodVerifier` is mostly doing a category check and avoiding
5942 // assignability checks that would expose narrowing conversions. However, for
5943 // the `return` instruction, it explicitly allows certain narrowing conversions
5944 // and prohibits others by doing a modified assignability check. Without strict
5945 // enforcement in all cases, this can compromise compiler optimizations that
5946 // rely on knowing the range of the values. Bug: 270660613
5947 return false;
5948 } else {
5949 DCHECK(assignable == RegType::Assignability::kReference);
5950 DCHECK(lhs.IsNonZeroReferenceTypes());
5951 DCHECK(rhs.IsNonZeroReferenceTypes());
5952 DCHECK(!lhs.IsUninitializedTypes());
5953 DCHECK(!rhs.IsUninitializedTypes());
5954 DCHECK(!lhs.IsJavaLangObject());
5955 if (!strict && !lhs.IsUnresolvedTypes() && lhs.GetClass()->IsInterface()) {
5956 // If we're not strict allow assignment to any interface, see comment in ClassJoin.
5957 return true;
5958 } else if (lhs.IsJavaLangObjectArray()) {
5959 return rhs.IsObjectArrayTypes(); // All reference arrays may be assigned to Object[]
5960 } else if (lhs.HasClass() && rhs.IsJavaLangObject()) {
5961 return false; // Note: Non-strict check for interface `lhs` is handled above.
5962 } else if (lhs.HasClass() && rhs.HasClass()) {
5963 // Test assignability from the Class point-of-view.
5964 bool result = lhs.GetClass()->IsAssignableFrom(rhs.GetClass());
5965 // Record assignability dependency. The `verifier` is null during unit tests and
5966 // VerifiedMethod::GenerateSafeCastSet.
5967 if (result) {
5968 VerifierDeps::MaybeRecordAssignability(GetVerifierDeps(),
5969 GetDexFile(),
5970 GetClassDef(),
5971 lhs.GetClass(),
5972 rhs.GetClass());
5973 }
5974 return result;
5975 } else {
5976 // For unresolved types, we don't know if they are assignable, and the
5977 // verifier will continue assuming they are. We need to record that.
5978 //
5979 // Note that if `rhs` is an interface type, `lhs` may be j.l.Object
5980 // and if the assignability check is not strict, then this should be
5981 // OK. However we don't encode strictness in the verifier deps, and
5982 // such a situation will force a full verification.
5983 VerifierDeps::MaybeRecordAssignability(GetVerifierDeps(),
5984 GetDexFile(),
5985 GetClassDef(),
5986 lhs,
5987 rhs);
5988 // Unresolved types are only assignable for null and equality.
5989 // Null cannot be the left-hand side.
5990 return false;
5991 }
5992 }
5993 }
5994
IsAssignableFrom(const RegType & lhs,const RegType & rhs) const5995 inline bool MethodVerifier::IsAssignableFrom(const RegType& lhs, const RegType& rhs) const {
5996 return AssignableFrom(lhs, rhs, false);
5997 }
5998
IsStrictlyAssignableFrom(const RegType & lhs,const RegType & rhs) const5999 inline bool MethodVerifier::IsStrictlyAssignableFrom(const RegType& lhs, const RegType& rhs) const {
6000 return AssignableFrom(lhs, rhs, true);
6001 }
6002
6003 } // namespace verifier
6004 } // namespace art
6005