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