1 /*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "method_verifier-inl.h"
18
19 #include <ostream>
20
21 #include "android-base/stringprintf.h"
22
23 #include "art_field-inl.h"
24 #include "art_method-inl.h"
25 #include "base/aborting.h"
26 #include "base/leb128.h"
27 #include "base/indenter.h"
28 #include "base/logging.h" // For VLOG.
29 #include "base/mutex-inl.h"
30 #include "base/pointer_size.h"
31 #include "base/sdk_version.h"
32 #include "base/stl_util.h"
33 #include "base/systrace.h"
34 #include "base/time_utils.h"
35 #include "base/utils.h"
36 #include "class_linker.h"
37 #include "class_root-inl.h"
38 #include "dex/class_accessor-inl.h"
39 #include "dex/descriptors_names.h"
40 #include "dex/dex_file-inl.h"
41 #include "dex/dex_file_exception_helpers.h"
42 #include "dex/dex_instruction-inl.h"
43 #include "dex/dex_instruction_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 HIDDEN {
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_, descriptor);
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 std::string_view method_name = dex_file_->GetStringView(method_id.name_idx_);
855 bool instance_constructor_by_name = method_name == "<init>";
856 bool static_constructor_by_name = method_name == "<clinit>";
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 std::string_view descriptor = dex_file_->GetTypeDescriptorView(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(descriptor == "Ljava/lang/Class;")) {
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_->GetTypeDescriptor(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_->GetTypeDescriptorView(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().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, class_loader_);
2538 DCHECK(!component_type.IsConflict());
2539 if (component_type.IsNonZeroReferenceTypes()) {
2540 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with component type "
2541 << component_type;
2542 } else {
2543 // Now verify if the element width in the table matches the element width declared in
2544 // the array
2545 const uint16_t* array_data =
2546 insns + (insns[1] | (static_cast<int32_t>(insns[2]) << 16));
2547 if (array_data[0] != Instruction::kArrayDataSignature) {
2548 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid magic for array-data";
2549 } else {
2550 size_t elem_width = Primitive::ComponentSize(component_type.GetPrimitiveType());
2551 // Since we don't compress the data in Dex, expect to see equal width of data stored
2552 // in the table and expected from the array class.
2553 if (array_data[1] != elem_width) {
2554 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-data size mismatch (" << array_data[1]
2555 << " vs " << elem_width << ")";
2556 }
2557 }
2558 }
2559 }
2560 }
2561 break;
2562 }
2563 case Instruction::IF_EQ:
2564 case Instruction::IF_NE: {
2565 const RegType& reg_type1 = work_line_->GetRegisterType(this, inst->VRegA_22t());
2566 const RegType& reg_type2 = work_line_->GetRegisterType(this, inst->VRegB_22t());
2567 bool mismatch = false;
2568 if (reg_type1.IsZeroOrNull()) { // zero then integral or reference expected
2569 mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes();
2570 } else if (reg_type1.IsReferenceTypes()) { // both references?
2571 mismatch = !reg_type2.IsReferenceTypes();
2572 } else { // both integral?
2573 mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes();
2574 }
2575 if (mismatch) {
2576 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to if-eq/if-ne (" << reg_type1 << ","
2577 << reg_type2 << ") must both be references or integral";
2578 }
2579 break;
2580 }
2581 case Instruction::IF_LT:
2582 case Instruction::IF_GE:
2583 case Instruction::IF_GT:
2584 case Instruction::IF_LE: {
2585 const RegType& reg_type1 = work_line_->GetRegisterType(this, inst->VRegA_22t());
2586 const RegType& reg_type2 = work_line_->GetRegisterType(this, inst->VRegB_22t());
2587 if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) {
2588 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to 'if' (" << reg_type1 << ","
2589 << reg_type2 << ") must be integral";
2590 }
2591 break;
2592 }
2593 case Instruction::IF_EQZ:
2594 case Instruction::IF_NEZ: {
2595 const RegType& reg_type = work_line_->GetRegisterType(this, inst->VRegA_21t());
2596 if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) {
2597 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type
2598 << " unexpected as arg to if-eqz/if-nez";
2599 }
2600
2601 // Find previous instruction - its existence is a precondition to peephole optimization.
2602 if (UNLIKELY(0 == work_insn_idx_)) {
2603 break;
2604 }
2605 uint32_t instance_of_idx = work_insn_idx_ - 1;
2606 while (0 != instance_of_idx && !GetInstructionFlags(instance_of_idx).IsOpcode()) {
2607 instance_of_idx--;
2608 }
2609 // Dex index 0 must be an opcode.
2610 DCHECK(GetInstructionFlags(instance_of_idx).IsOpcode());
2611
2612 const Instruction& instance_of_inst = code_item_accessor_.InstructionAt(instance_of_idx);
2613
2614 /* Check for peep-hole pattern of:
2615 * ...;
2616 * instance-of vX, vY, T;
2617 * ifXXX vX, label ;
2618 * ...;
2619 * label:
2620 * ...;
2621 * and sharpen the type of vY to be type T.
2622 * Note, this pattern can't be if:
2623 * - if there are other branches to this branch,
2624 * - when vX == vY.
2625 */
2626 if (!CurrentInsnFlags()->IsBranchTarget() &&
2627 (Instruction::INSTANCE_OF == instance_of_inst.Opcode()) &&
2628 (inst->VRegA_21t() == instance_of_inst.VRegA_22c()) &&
2629 (instance_of_inst.VRegA_22c() != instance_of_inst.VRegB_22c())) {
2630 // Check the type of the instance-of is different than that of registers type, as if they
2631 // are the same there is no work to be done here. Check that the conversion is not to or
2632 // from an unresolved type as type information is imprecise. If the instance-of is to an
2633 // interface then ignore the type information as interfaces can only be treated as Objects
2634 // and we don't want to disallow field and other operations on the object. If the value
2635 // being instance-of checked against is known null (zero) then allow the optimization as
2636 // we didn't have type information. If the merge of the instance-of type with the original
2637 // type is assignable to the original then allow optimization. This check is performed to
2638 // ensure that subsequent merges don't lose type information - such as becoming an
2639 // interface from a class that would lose information relevant to field checks.
2640 //
2641 // Note: do not do an access check. This may mark this with a runtime throw that actually
2642 // happens at the instanceof, not the branch (and branches aren't flagged to throw).
2643 const RegType& orig_type = work_line_->GetRegisterType(this, instance_of_inst.VRegB_22c());
2644 const RegType& cast_type = ResolveClass<CheckAccess::kNo>(
2645 dex::TypeIndex(instance_of_inst.VRegC_22c()));
2646
2647 if (!orig_type.Equals(cast_type) &&
2648 !cast_type.IsUnresolvedTypes() && !orig_type.IsUnresolvedTypes() &&
2649 cast_type.HasClass() && // Could be conflict type, make sure it has a class.
2650 !cast_type.GetClass()->IsInterface() &&
2651 !orig_type.IsZeroOrNull() &&
2652 orig_type.IsStrictlyAssignableFrom(
2653 cast_type.Merge(orig_type, ®_types_, this), this)) {
2654 RegisterLine* update_line = RegisterLine::Create(code_item_accessor_.RegistersSize(),
2655 allocator_,
2656 GetRegTypeCache());
2657 if (inst->Opcode() == Instruction::IF_EQZ) {
2658 fallthrough_line.reset(update_line);
2659 } else {
2660 branch_line.reset(update_line);
2661 }
2662 update_line->CopyFromLine(work_line_.get());
2663 update_line->SetRegisterType<LockOp::kKeep>(instance_of_inst.VRegB_22c(), cast_type);
2664 if (!GetInstructionFlags(instance_of_idx).IsBranchTarget() && 0 != instance_of_idx) {
2665 // See if instance-of was preceded by a move-object operation, common due to the small
2666 // register encoding space of instance-of, and propagate type information to the source
2667 // of the move-object.
2668 // Note: this is only valid if the move source was not clobbered.
2669 uint32_t move_idx = instance_of_idx - 1;
2670 while (0 != move_idx && !GetInstructionFlags(move_idx).IsOpcode()) {
2671 move_idx--;
2672 }
2673 DCHECK(GetInstructionFlags(move_idx).IsOpcode());
2674 auto maybe_update_fn = [&instance_of_inst, update_line, &cast_type](
2675 uint16_t move_src,
2676 uint16_t move_trg)
2677 REQUIRES_SHARED(Locks::mutator_lock_) {
2678 if (move_trg == instance_of_inst.VRegB_22c() &&
2679 move_src != instance_of_inst.VRegA_22c()) {
2680 update_line->SetRegisterType<LockOp::kKeep>(move_src, cast_type);
2681 }
2682 };
2683 const Instruction& move_inst = code_item_accessor_.InstructionAt(move_idx);
2684 switch (move_inst.Opcode()) {
2685 case Instruction::MOVE_OBJECT:
2686 maybe_update_fn(move_inst.VRegB_12x(), move_inst.VRegA_12x());
2687 break;
2688 case Instruction::MOVE_OBJECT_FROM16:
2689 maybe_update_fn(move_inst.VRegB_22x(), move_inst.VRegA_22x());
2690 break;
2691 case Instruction::MOVE_OBJECT_16:
2692 maybe_update_fn(move_inst.VRegB_32x(), move_inst.VRegA_32x());
2693 break;
2694 default:
2695 break;
2696 }
2697 }
2698 }
2699 }
2700
2701 break;
2702 }
2703 case Instruction::IF_LTZ:
2704 case Instruction::IF_GEZ:
2705 case Instruction::IF_GTZ:
2706 case Instruction::IF_LEZ: {
2707 const RegType& reg_type = work_line_->GetRegisterType(this, inst->VRegA_21t());
2708 if (!reg_type.IsIntegralTypes()) {
2709 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type
2710 << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez";
2711 }
2712 break;
2713 }
2714 case Instruction::AGET_BOOLEAN:
2715 VerifyAGet(inst, reg_types_.Boolean(), true);
2716 break;
2717 case Instruction::AGET_BYTE:
2718 VerifyAGet(inst, reg_types_.Byte(), true);
2719 break;
2720 case Instruction::AGET_CHAR:
2721 VerifyAGet(inst, reg_types_.Char(), true);
2722 break;
2723 case Instruction::AGET_SHORT:
2724 VerifyAGet(inst, reg_types_.Short(), true);
2725 break;
2726 case Instruction::AGET:
2727 VerifyAGet(inst, reg_types_.Integer(), true);
2728 break;
2729 case Instruction::AGET_WIDE:
2730 VerifyAGet(inst, reg_types_.LongLo(), true);
2731 break;
2732 case Instruction::AGET_OBJECT:
2733 VerifyAGet(inst, reg_types_.JavaLangObject(false), false);
2734 break;
2735
2736 case Instruction::APUT_BOOLEAN:
2737 VerifyAPut(inst, reg_types_.Boolean(), true);
2738 break;
2739 case Instruction::APUT_BYTE:
2740 VerifyAPut(inst, reg_types_.Byte(), true);
2741 break;
2742 case Instruction::APUT_CHAR:
2743 VerifyAPut(inst, reg_types_.Char(), true);
2744 break;
2745 case Instruction::APUT_SHORT:
2746 VerifyAPut(inst, reg_types_.Short(), true);
2747 break;
2748 case Instruction::APUT:
2749 VerifyAPut(inst, reg_types_.Integer(), true);
2750 break;
2751 case Instruction::APUT_WIDE:
2752 VerifyAPut(inst, reg_types_.LongLo(), true);
2753 break;
2754 case Instruction::APUT_OBJECT:
2755 VerifyAPut(inst, reg_types_.JavaLangObject(false), false);
2756 break;
2757
2758 case Instruction::IGET_BOOLEAN:
2759 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Boolean(), true, false);
2760 break;
2761 case Instruction::IGET_BYTE:
2762 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Byte(), true, false);
2763 break;
2764 case Instruction::IGET_CHAR:
2765 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Char(), true, false);
2766 break;
2767 case Instruction::IGET_SHORT:
2768 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Short(), true, false);
2769 break;
2770 case Instruction::IGET:
2771 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Integer(), true, false);
2772 break;
2773 case Instruction::IGET_WIDE:
2774 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.LongLo(), true, false);
2775 break;
2776 case Instruction::IGET_OBJECT:
2777 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.JavaLangObject(false), false,
2778 false);
2779 break;
2780
2781 case Instruction::IPUT_BOOLEAN:
2782 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Boolean(), true, false);
2783 break;
2784 case Instruction::IPUT_BYTE:
2785 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Byte(), true, false);
2786 break;
2787 case Instruction::IPUT_CHAR:
2788 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Char(), true, false);
2789 break;
2790 case Instruction::IPUT_SHORT:
2791 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Short(), true, false);
2792 break;
2793 case Instruction::IPUT:
2794 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Integer(), true, false);
2795 break;
2796 case Instruction::IPUT_WIDE:
2797 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.LongLo(), true, false);
2798 break;
2799 case Instruction::IPUT_OBJECT:
2800 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.JavaLangObject(false), false,
2801 false);
2802 break;
2803
2804 case Instruction::SGET_BOOLEAN:
2805 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Boolean(), true, true);
2806 break;
2807 case Instruction::SGET_BYTE:
2808 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Byte(), true, true);
2809 break;
2810 case Instruction::SGET_CHAR:
2811 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Char(), true, true);
2812 break;
2813 case Instruction::SGET_SHORT:
2814 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Short(), true, true);
2815 break;
2816 case Instruction::SGET:
2817 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Integer(), true, true);
2818 break;
2819 case Instruction::SGET_WIDE:
2820 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.LongLo(), true, true);
2821 break;
2822 case Instruction::SGET_OBJECT:
2823 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.JavaLangObject(false), false,
2824 true);
2825 break;
2826
2827 case Instruction::SPUT_BOOLEAN:
2828 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Boolean(), true, true);
2829 break;
2830 case Instruction::SPUT_BYTE:
2831 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Byte(), true, true);
2832 break;
2833 case Instruction::SPUT_CHAR:
2834 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Char(), true, true);
2835 break;
2836 case Instruction::SPUT_SHORT:
2837 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Short(), true, true);
2838 break;
2839 case Instruction::SPUT:
2840 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Integer(), true, true);
2841 break;
2842 case Instruction::SPUT_WIDE:
2843 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.LongLo(), true, true);
2844 break;
2845 case Instruction::SPUT_OBJECT:
2846 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.JavaLangObject(false), false,
2847 true);
2848 break;
2849
2850 case Instruction::INVOKE_VIRTUAL:
2851 case Instruction::INVOKE_VIRTUAL_RANGE:
2852 case Instruction::INVOKE_SUPER:
2853 case Instruction::INVOKE_SUPER_RANGE: {
2854 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE ||
2855 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE);
2856 bool is_super = (inst->Opcode() == Instruction::INVOKE_SUPER ||
2857 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE);
2858 MethodType type = is_super ? METHOD_SUPER : METHOD_VIRTUAL;
2859 ArtMethod* called_method = VerifyInvocationArgs(inst, type, is_range);
2860 const RegType* return_type = nullptr;
2861 if (called_method != nullptr) {
2862 ObjPtr<mirror::Class> return_type_class = CanLoadClasses()
2863 ? called_method->ResolveReturnType()
2864 : called_method->LookupResolvedReturnType();
2865 if (return_type_class != nullptr) {
2866 return_type = &FromClass(called_method->GetReturnTypeDescriptor(),
2867 return_type_class,
2868 return_type_class->CannotBeAssignedFromOtherTypes());
2869 } else {
2870 DCHECK_IMPLIES(CanLoadClasses(), self_->IsExceptionPending());
2871 self_->ClearException();
2872 }
2873 }
2874 if (return_type == nullptr) {
2875 uint32_t method_idx = GetMethodIdxOfInvoke(inst);
2876 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2877 dex::TypeIndex return_type_idx =
2878 dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2879 const char* descriptor = dex_file_->GetTypeDescriptor(return_type_idx);
2880 return_type = ®_types_.FromDescriptor(class_loader_, descriptor);
2881 }
2882 if (!return_type->IsLowHalf()) {
2883 work_line_->SetResultRegisterType(this, *return_type);
2884 } else {
2885 work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(®_types_));
2886 }
2887 just_set_result = true;
2888 break;
2889 }
2890 case Instruction::INVOKE_DIRECT:
2891 case Instruction::INVOKE_DIRECT_RANGE: {
2892 bool is_range = (inst->Opcode() == Instruction::INVOKE_DIRECT_RANGE);
2893 ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_DIRECT, is_range);
2894 const char* return_type_descriptor;
2895 bool is_constructor;
2896 const RegType* return_type = nullptr;
2897 if (called_method == nullptr) {
2898 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
2899 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2900 is_constructor = dex_file_->GetStringView(method_id.name_idx_) == "<init>";
2901 dex::TypeIndex return_type_idx =
2902 dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2903 return_type_descriptor = dex_file_->GetTypeDescriptor(return_type_idx);
2904 } else {
2905 is_constructor = called_method->IsConstructor();
2906 return_type_descriptor = called_method->GetReturnTypeDescriptor();
2907 ObjPtr<mirror::Class> return_type_class = CanLoadClasses()
2908 ? called_method->ResolveReturnType()
2909 : called_method->LookupResolvedReturnType();
2910 if (return_type_class != nullptr) {
2911 return_type = &FromClass(return_type_descriptor,
2912 return_type_class,
2913 return_type_class->CannotBeAssignedFromOtherTypes());
2914 } else {
2915 DCHECK_IMPLIES(CanLoadClasses(), self_->IsExceptionPending());
2916 self_->ClearException();
2917 }
2918 }
2919 if (is_constructor) {
2920 /*
2921 * Some additional checks when calling a constructor. We know from the invocation arg check
2922 * that the "this" argument is an instance of called_method->klass. Now we further restrict
2923 * that to require that called_method->klass is the same as this->klass or this->super,
2924 * allowing the latter only if the "this" argument is the same as the "this" argument to
2925 * this method (which implies that we're in a constructor ourselves).
2926 */
2927 const RegType& this_type = work_line_->GetInvocationThis(this, inst);
2928 if (this_type.IsConflict()) // failure.
2929 break;
2930
2931 /* no null refs allowed (?) */
2932 if (this_type.IsZeroOrNull()) {
2933 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to initialize null ref";
2934 break;
2935 }
2936
2937 /* must be in same class or in superclass */
2938 // const RegType& this_super_klass = this_type.GetSuperClass(®_types_);
2939 // TODO: re-enable constructor type verification
2940 // if (this_super_klass.IsConflict()) {
2941 // Unknown super class, fail so we re-check at runtime.
2942 // Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "super class unknown for '" << this_type << "'";
2943 // break;
2944 // }
2945
2946 /* arg must be an uninitialized reference */
2947 if (!this_type.IsUninitializedTypes()) {
2948 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Expected initialization on uninitialized reference "
2949 << this_type;
2950 break;
2951 }
2952
2953 /*
2954 * Replace the uninitialized reference with an initialized one. We need to do this for all
2955 * registers that have the same object instance in them, not just the "this" register.
2956 */
2957 work_line_->MarkRefsAsInitialized(this, this_type);
2958 }
2959 if (return_type == nullptr) {
2960 return_type = ®_types_.FromDescriptor(class_loader_, return_type_descriptor);
2961 }
2962 if (!return_type->IsLowHalf()) {
2963 work_line_->SetResultRegisterType(this, *return_type);
2964 } else {
2965 work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(®_types_));
2966 }
2967 just_set_result = true;
2968 break;
2969 }
2970 case Instruction::INVOKE_STATIC:
2971 case Instruction::INVOKE_STATIC_RANGE: {
2972 bool is_range = (inst->Opcode() == Instruction::INVOKE_STATIC_RANGE);
2973 ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_STATIC, is_range);
2974 const char* descriptor;
2975 if (called_method == nullptr) {
2976 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
2977 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
2978 dex::TypeIndex return_type_idx =
2979 dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
2980 descriptor = dex_file_->GetTypeDescriptor(return_type_idx);
2981 } else {
2982 descriptor = called_method->GetReturnTypeDescriptor();
2983 }
2984 const RegType& return_type = reg_types_.FromDescriptor(class_loader_, descriptor);
2985 if (!return_type.IsLowHalf()) {
2986 work_line_->SetResultRegisterType(this, return_type);
2987 } else {
2988 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_));
2989 }
2990 just_set_result = true;
2991 }
2992 break;
2993 case Instruction::INVOKE_INTERFACE:
2994 case Instruction::INVOKE_INTERFACE_RANGE: {
2995 bool is_range = (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE);
2996 ArtMethod* abs_method = VerifyInvocationArgs(inst, METHOD_INTERFACE, is_range);
2997 if (abs_method != nullptr) {
2998 ObjPtr<mirror::Class> called_interface = abs_method->GetDeclaringClass();
2999 if (!called_interface->IsInterface() && !called_interface->IsObjectClass()) {
3000 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '"
3001 << abs_method->PrettyMethod() << "'";
3002 break;
3003 }
3004 }
3005 /* Get the type of the "this" arg, which should either be a sub-interface of called
3006 * interface or Object (see comments in RegType::JoinClass).
3007 */
3008 const RegType& this_type = work_line_->GetInvocationThis(this, inst);
3009 if (this_type.IsZeroOrNull()) {
3010 /* null pointer always passes (and always fails at runtime) */
3011 } else {
3012 if (this_type.IsUninitializedTypes()) {
3013 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface call on uninitialized object "
3014 << this_type;
3015 break;
3016 }
3017 // In the past we have tried to assert that "called_interface" is assignable
3018 // from "this_type.GetClass()", however, as we do an imprecise Join
3019 // (RegType::JoinClass) we don't have full information on what interfaces are
3020 // implemented by "this_type". For example, two classes may implement the same
3021 // interfaces and have a common parent that doesn't implement the interface. The
3022 // join will set "this_type" to the parent class and a test that this implements
3023 // the interface will incorrectly fail.
3024 }
3025 /*
3026 * We don't have an object instance, so we can't find the concrete method. However, all of
3027 * the type information is in the abstract method, so we're good.
3028 */
3029 const char* descriptor;
3030 if (abs_method == nullptr) {
3031 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
3032 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
3033 dex::TypeIndex return_type_idx =
3034 dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
3035 descriptor = dex_file_->GetTypeDescriptor(return_type_idx);
3036 } else {
3037 descriptor = abs_method->GetReturnTypeDescriptor();
3038 }
3039 const RegType& return_type = reg_types_.FromDescriptor(class_loader_, descriptor);
3040 if (!return_type.IsLowHalf()) {
3041 work_line_->SetResultRegisterType(this, return_type);
3042 } else {
3043 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_));
3044 }
3045 just_set_result = true;
3046 break;
3047 }
3048 case Instruction::INVOKE_POLYMORPHIC:
3049 case Instruction::INVOKE_POLYMORPHIC_RANGE: {
3050 bool is_range = (inst->Opcode() == Instruction::INVOKE_POLYMORPHIC_RANGE);
3051 ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_POLYMORPHIC, is_range);
3052 if (called_method == nullptr) {
3053 // Convert potential soft failures in VerifyInvocationArgs() to hard errors.
3054 if (failure_messages_.size() > 0) {
3055 std::string message = failure_messages_.back()->str();
3056 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << message;
3057 } else {
3058 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-polymorphic verification failure.";
3059 }
3060 break;
3061 }
3062 if (!CheckSignaturePolymorphicMethod(called_method) ||
3063 !CheckSignaturePolymorphicReceiver(inst)) {
3064 DCHECK(HasFailures());
3065 break;
3066 }
3067 const uint16_t vRegH = (is_range) ? inst->VRegH_4rcc() : inst->VRegH_45cc();
3068 const dex::ProtoIndex proto_idx(vRegH);
3069 const char* return_descriptor =
3070 dex_file_->GetReturnTypeDescriptor(dex_file_->GetProtoId(proto_idx));
3071 const RegType& return_type =
3072 reg_types_.FromDescriptor(class_loader_, return_descriptor);
3073 if (!return_type.IsLowHalf()) {
3074 work_line_->SetResultRegisterType(this, return_type);
3075 } else {
3076 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_));
3077 }
3078 just_set_result = true;
3079 break;
3080 }
3081 case Instruction::INVOKE_CUSTOM:
3082 case Instruction::INVOKE_CUSTOM_RANGE: {
3083 // Verify registers based on method_type in the call site.
3084 bool is_range = (inst->Opcode() == Instruction::INVOKE_CUSTOM_RANGE);
3085
3086 // Step 1. Check the call site that produces the method handle for invocation
3087 const uint32_t call_site_idx = is_range ? inst->VRegB_3rc() : inst->VRegB_35c();
3088 if (!CheckCallSite(call_site_idx)) {
3089 DCHECK(HasFailures());
3090 break;
3091 }
3092
3093 // Step 2. Check the register arguments correspond to the expected arguments for the
3094 // method handle produced by step 1. The dex file verifier has checked ranges for
3095 // the first three arguments and CheckCallSite has checked the method handle type.
3096 const dex::ProtoIndex proto_idx = dex_file_->GetProtoIndexForCallSite(call_site_idx);
3097 const dex::ProtoId& proto_id = dex_file_->GetProtoId(proto_idx);
3098 DexFileParameterIterator param_it(*dex_file_, proto_id);
3099 // Treat method as static as it has yet to be determined.
3100 VerifyInvocationArgsFromIterator(¶m_it, inst, METHOD_STATIC, is_range, nullptr);
3101 const char* return_descriptor = dex_file_->GetReturnTypeDescriptor(proto_id);
3102
3103 // Step 3. Propagate return type information
3104 const RegType& return_type =
3105 reg_types_.FromDescriptor(class_loader_, return_descriptor);
3106 if (!return_type.IsLowHalf()) {
3107 work_line_->SetResultRegisterType(this, return_type);
3108 } else {
3109 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(®_types_));
3110 }
3111 just_set_result = true;
3112 break;
3113 }
3114 case Instruction::NEG_INT:
3115 case Instruction::NOT_INT:
3116 work_line_->CheckUnaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer());
3117 break;
3118 case Instruction::NEG_LONG:
3119 case Instruction::NOT_LONG:
3120 work_line_->CheckUnaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3121 reg_types_.LongLo(), reg_types_.LongHi());
3122 break;
3123 case Instruction::NEG_FLOAT:
3124 work_line_->CheckUnaryOp(this, inst, reg_types_.Float(), reg_types_.Float());
3125 break;
3126 case Instruction::NEG_DOUBLE:
3127 work_line_->CheckUnaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3128 reg_types_.DoubleLo(), reg_types_.DoubleHi());
3129 break;
3130 case Instruction::INT_TO_LONG:
3131 work_line_->CheckUnaryOpToWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3132 reg_types_.Integer());
3133 break;
3134 case Instruction::INT_TO_FLOAT:
3135 work_line_->CheckUnaryOp(this, inst, reg_types_.Float(), reg_types_.Integer());
3136 break;
3137 case Instruction::INT_TO_DOUBLE:
3138 work_line_->CheckUnaryOpToWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3139 reg_types_.Integer());
3140 break;
3141 case Instruction::LONG_TO_INT:
3142 work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Integer(),
3143 reg_types_.LongLo(), reg_types_.LongHi());
3144 break;
3145 case Instruction::LONG_TO_FLOAT:
3146 work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Float(),
3147 reg_types_.LongLo(), reg_types_.LongHi());
3148 break;
3149 case Instruction::LONG_TO_DOUBLE:
3150 work_line_->CheckUnaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3151 reg_types_.LongLo(), reg_types_.LongHi());
3152 break;
3153 case Instruction::FLOAT_TO_INT:
3154 work_line_->CheckUnaryOp(this, inst, reg_types_.Integer(), reg_types_.Float());
3155 break;
3156 case Instruction::FLOAT_TO_LONG:
3157 work_line_->CheckUnaryOpToWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3158 reg_types_.Float());
3159 break;
3160 case Instruction::FLOAT_TO_DOUBLE:
3161 work_line_->CheckUnaryOpToWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3162 reg_types_.Float());
3163 break;
3164 case Instruction::DOUBLE_TO_INT:
3165 work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Integer(),
3166 reg_types_.DoubleLo(), reg_types_.DoubleHi());
3167 break;
3168 case Instruction::DOUBLE_TO_LONG:
3169 work_line_->CheckUnaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3170 reg_types_.DoubleLo(), reg_types_.DoubleHi());
3171 break;
3172 case Instruction::DOUBLE_TO_FLOAT:
3173 work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Float(),
3174 reg_types_.DoubleLo(), reg_types_.DoubleHi());
3175 break;
3176 case Instruction::INT_TO_BYTE:
3177 work_line_->CheckUnaryOp(this, inst, reg_types_.Byte(), reg_types_.Integer());
3178 break;
3179 case Instruction::INT_TO_CHAR:
3180 work_line_->CheckUnaryOp(this, inst, reg_types_.Char(), reg_types_.Integer());
3181 break;
3182 case Instruction::INT_TO_SHORT:
3183 work_line_->CheckUnaryOp(this, inst, reg_types_.Short(), reg_types_.Integer());
3184 break;
3185
3186 case Instruction::ADD_INT:
3187 case Instruction::SUB_INT:
3188 case Instruction::MUL_INT:
3189 case Instruction::REM_INT:
3190 case Instruction::DIV_INT:
3191 case Instruction::SHL_INT:
3192 case Instruction::SHR_INT:
3193 case Instruction::USHR_INT:
3194 work_line_->CheckBinaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3195 reg_types_.Integer(), false);
3196 break;
3197 case Instruction::AND_INT:
3198 case Instruction::OR_INT:
3199 case Instruction::XOR_INT:
3200 work_line_->CheckBinaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3201 reg_types_.Integer(), true);
3202 break;
3203 case Instruction::ADD_LONG:
3204 case Instruction::SUB_LONG:
3205 case Instruction::MUL_LONG:
3206 case Instruction::DIV_LONG:
3207 case Instruction::REM_LONG:
3208 case Instruction::AND_LONG:
3209 case Instruction::OR_LONG:
3210 case Instruction::XOR_LONG:
3211 work_line_->CheckBinaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3212 reg_types_.LongLo(), reg_types_.LongHi(),
3213 reg_types_.LongLo(), reg_types_.LongHi());
3214 break;
3215 case Instruction::SHL_LONG:
3216 case Instruction::SHR_LONG:
3217 case Instruction::USHR_LONG:
3218 /* shift distance is Int, making these different from other binary operations */
3219 work_line_->CheckBinaryOpWideShift(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3220 reg_types_.Integer());
3221 break;
3222 case Instruction::ADD_FLOAT:
3223 case Instruction::SUB_FLOAT:
3224 case Instruction::MUL_FLOAT:
3225 case Instruction::DIV_FLOAT:
3226 case Instruction::REM_FLOAT:
3227 work_line_->CheckBinaryOp(this, inst, reg_types_.Float(), reg_types_.Float(),
3228 reg_types_.Float(), false);
3229 break;
3230 case Instruction::ADD_DOUBLE:
3231 case Instruction::SUB_DOUBLE:
3232 case Instruction::MUL_DOUBLE:
3233 case Instruction::DIV_DOUBLE:
3234 case Instruction::REM_DOUBLE:
3235 work_line_->CheckBinaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3236 reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3237 reg_types_.DoubleLo(), reg_types_.DoubleHi());
3238 break;
3239 case Instruction::ADD_INT_2ADDR:
3240 case Instruction::SUB_INT_2ADDR:
3241 case Instruction::MUL_INT_2ADDR:
3242 case Instruction::REM_INT_2ADDR:
3243 case Instruction::SHL_INT_2ADDR:
3244 case Instruction::SHR_INT_2ADDR:
3245 case Instruction::USHR_INT_2ADDR:
3246 work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3247 reg_types_.Integer(), false);
3248 break;
3249 case Instruction::AND_INT_2ADDR:
3250 case Instruction::OR_INT_2ADDR:
3251 case Instruction::XOR_INT_2ADDR:
3252 work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3253 reg_types_.Integer(), true);
3254 break;
3255 case Instruction::DIV_INT_2ADDR:
3256 work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3257 reg_types_.Integer(), false);
3258 break;
3259 case Instruction::ADD_LONG_2ADDR:
3260 case Instruction::SUB_LONG_2ADDR:
3261 case Instruction::MUL_LONG_2ADDR:
3262 case Instruction::DIV_LONG_2ADDR:
3263 case Instruction::REM_LONG_2ADDR:
3264 case Instruction::AND_LONG_2ADDR:
3265 case Instruction::OR_LONG_2ADDR:
3266 case Instruction::XOR_LONG_2ADDR:
3267 work_line_->CheckBinaryOp2addrWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3268 reg_types_.LongLo(), reg_types_.LongHi(),
3269 reg_types_.LongLo(), reg_types_.LongHi());
3270 break;
3271 case Instruction::SHL_LONG_2ADDR:
3272 case Instruction::SHR_LONG_2ADDR:
3273 case Instruction::USHR_LONG_2ADDR:
3274 work_line_->CheckBinaryOp2addrWideShift(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
3275 reg_types_.Integer());
3276 break;
3277 case Instruction::ADD_FLOAT_2ADDR:
3278 case Instruction::SUB_FLOAT_2ADDR:
3279 case Instruction::MUL_FLOAT_2ADDR:
3280 case Instruction::DIV_FLOAT_2ADDR:
3281 case Instruction::REM_FLOAT_2ADDR:
3282 work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Float(), reg_types_.Float(),
3283 reg_types_.Float(), false);
3284 break;
3285 case Instruction::ADD_DOUBLE_2ADDR:
3286 case Instruction::SUB_DOUBLE_2ADDR:
3287 case Instruction::MUL_DOUBLE_2ADDR:
3288 case Instruction::DIV_DOUBLE_2ADDR:
3289 case Instruction::REM_DOUBLE_2ADDR:
3290 work_line_->CheckBinaryOp2addrWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3291 reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3292 reg_types_.DoubleLo(), reg_types_.DoubleHi());
3293 break;
3294 case Instruction::ADD_INT_LIT16:
3295 case Instruction::RSUB_INT_LIT16:
3296 case Instruction::MUL_INT_LIT16:
3297 case Instruction::DIV_INT_LIT16:
3298 case Instruction::REM_INT_LIT16:
3299 work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), false,
3300 true);
3301 break;
3302 case Instruction::AND_INT_LIT16:
3303 case Instruction::OR_INT_LIT16:
3304 case Instruction::XOR_INT_LIT16:
3305 work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), true,
3306 true);
3307 break;
3308 case Instruction::ADD_INT_LIT8:
3309 case Instruction::RSUB_INT_LIT8:
3310 case Instruction::MUL_INT_LIT8:
3311 case Instruction::DIV_INT_LIT8:
3312 case Instruction::REM_INT_LIT8:
3313 case Instruction::SHL_INT_LIT8:
3314 case Instruction::SHR_INT_LIT8:
3315 case Instruction::USHR_INT_LIT8:
3316 work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), false,
3317 false);
3318 break;
3319 case Instruction::AND_INT_LIT8:
3320 case Instruction::OR_INT_LIT8:
3321 case Instruction::XOR_INT_LIT8:
3322 work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), true,
3323 false);
3324 break;
3325
3326 /* These should never appear during verification. */
3327 case Instruction::UNUSED_3E ... Instruction::UNUSED_43:
3328 case Instruction::UNUSED_E3 ... Instruction::UNUSED_F9:
3329 case Instruction::UNUSED_73:
3330 case Instruction::UNUSED_79:
3331 case Instruction::UNUSED_7A:
3332 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Unexpected opcode " << inst->DumpString(dex_file_);
3333 break;
3334
3335 /*
3336 * DO NOT add a "default" clause here. Without it the compiler will
3337 * complain if an instruction is missing (which is desirable).
3338 */
3339 } // end - switch (dec_insn.opcode)
3340
3341 if (flags_.have_pending_hard_failure_) {
3342 if (IsAotMode()) {
3343 /* When AOT compiling, check that the last failure is a hard failure */
3344 if (failures_[failures_.size() - 1] != VERIFY_ERROR_BAD_CLASS_HARD) {
3345 LOG(ERROR) << "Pending failures:";
3346 for (auto& error : failures_) {
3347 LOG(ERROR) << error;
3348 }
3349 for (auto& error_msg : failure_messages_) {
3350 LOG(ERROR) << error_msg->str();
3351 }
3352 LOG(FATAL) << "Pending hard failure, but last failure not hard.";
3353 }
3354 }
3355 /* immediate failure, reject class */
3356 info_messages_ << "Rejecting opcode " << inst->DumpString(dex_file_);
3357 return false;
3358 } else if (flags_.have_pending_runtime_throw_failure_) {
3359 LogVerifyInfo() << "Elevating opcode flags from " << opcode_flags << " to Throw";
3360 /* checking interpreter will throw, mark following code as unreachable */
3361 opcode_flags = Instruction::kThrow;
3362 // Note: the flag must be reset as it is only global to decouple Fail and is semantically per
3363 // instruction. However, RETURN checking may throw LOCKING errors, so we clear at the
3364 // very end.
3365 }
3366 /*
3367 * If we didn't just set the result register, clear it out. This ensures that you can only use
3368 * "move-result" immediately after the result is set. (We could check this statically, but it's
3369 * not expensive and it makes our debugging output cleaner.)
3370 */
3371 if (!just_set_result) {
3372 work_line_->SetResultTypeToUnknown(GetRegTypeCache());
3373 }
3374
3375 /*
3376 * Handle "branch". Tag the branch target.
3377 *
3378 * NOTE: instructions like Instruction::EQZ provide information about the
3379 * state of the register when the branch is taken or not taken. For example,
3380 * somebody could get a reference field, check it for zero, and if the
3381 * branch is taken immediately store that register in a boolean field
3382 * since the value is known to be zero. We do not currently account for
3383 * that, and will reject the code.
3384 *
3385 * TODO: avoid re-fetching the branch target
3386 */
3387 if ((opcode_flags & Instruction::kBranch) != 0) {
3388 bool isConditional, selfOkay;
3389 if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) {
3390 /* should never happen after static verification */
3391 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad branch";
3392 return false;
3393 }
3394 DCHECK_EQ(isConditional, (opcode_flags & Instruction::kContinue) != 0);
3395 if (!CheckNotMoveExceptionOrMoveResult(code_item_accessor_.Insns(),
3396 work_insn_idx_ + branch_target)) {
3397 return false;
3398 }
3399 /* update branch target, set "changed" if appropriate */
3400 if (nullptr != branch_line) {
3401 if (!UpdateRegisters(work_insn_idx_ + branch_target, branch_line.get(), false)) {
3402 return false;
3403 }
3404 } else {
3405 if (!UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get(), false)) {
3406 return false;
3407 }
3408 }
3409 }
3410
3411 /*
3412 * Handle "switch". Tag all possible branch targets.
3413 *
3414 * We've already verified that the table is structurally sound, so we
3415 * just need to walk through and tag the targets.
3416 */
3417 if ((opcode_flags & Instruction::kSwitch) != 0) {
3418 int offset_to_switch = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
3419 const uint16_t* switch_insns = insns + offset_to_switch;
3420 int switch_count = switch_insns[1];
3421 int offset_to_targets, targ;
3422
3423 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
3424 /* 0 = sig, 1 = count, 2/3 = first key */
3425 offset_to_targets = 4;
3426 } else {
3427 /* 0 = sig, 1 = count, 2..count * 2 = keys */
3428 DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH);
3429 offset_to_targets = 2 + 2 * switch_count;
3430 }
3431
3432 /* verify each switch target */
3433 for (targ = 0; targ < switch_count; targ++) {
3434 int offset;
3435 uint32_t abs_offset;
3436
3437 /* offsets are 32-bit, and only partly endian-swapped */
3438 offset = switch_insns[offset_to_targets + targ * 2] |
3439 (static_cast<int32_t>(switch_insns[offset_to_targets + targ * 2 + 1]) << 16);
3440 abs_offset = work_insn_idx_ + offset;
3441 DCHECK_LT(abs_offset, code_item_accessor_.InsnsSizeInCodeUnits());
3442 if (!CheckNotMoveExceptionOrMoveResult(code_item_accessor_.Insns(), abs_offset)) {
3443 return false;
3444 }
3445 if (!UpdateRegisters(abs_offset, work_line_.get(), false)) {
3446 return false;
3447 }
3448 }
3449 }
3450
3451 /*
3452 * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a
3453 * "try" block when they throw, control transfers out of the method.)
3454 */
3455 if ((opcode_flags & Instruction::kThrow) != 0 && GetInstructionFlags(work_insn_idx_).IsInTry()) {
3456 bool has_catch_all_handler = false;
3457 const dex::TryItem* try_item = code_item_accessor_.FindTryItem(work_insn_idx_);
3458 CHECK(try_item != nullptr);
3459 CatchHandlerIterator iterator(code_item_accessor_, *try_item);
3460
3461 // Need the linker to try and resolve the handled class to check if it's Throwable.
3462 ClassLinker* linker = GetClassLinker();
3463
3464 for (; iterator.HasNext(); iterator.Next()) {
3465 dex::TypeIndex handler_type_idx = iterator.GetHandlerTypeIndex();
3466 if (!handler_type_idx.IsValid()) {
3467 has_catch_all_handler = true;
3468 } else {
3469 // It is also a catch-all if it is java.lang.Throwable.
3470 ObjPtr<mirror::Class> klass =
3471 linker->ResolveType(handler_type_idx, dex_cache_, class_loader_);
3472 if (klass != nullptr) {
3473 if (klass == GetClassRoot<mirror::Throwable>()) {
3474 has_catch_all_handler = true;
3475 }
3476 } else {
3477 // Clear exception.
3478 DCHECK(self_->IsExceptionPending());
3479 self_->ClearException();
3480 }
3481 }
3482 /*
3483 * Merge registers into the "catch" block. We want to use the "savedRegs" rather than
3484 * "work_regs", because at runtime the exception will be thrown before the instruction
3485 * modifies any registers.
3486 */
3487 if (kVerifierDebug) {
3488 LogVerifyInfo() << "Updating exception handler 0x"
3489 << std::hex << iterator.GetHandlerAddress();
3490 }
3491 if (!UpdateRegisters(iterator.GetHandlerAddress(), saved_line_.get(), false)) {
3492 return false;
3493 }
3494 }
3495
3496 /*
3497 * If the monitor stack depth is nonzero, there must be a "catch all" handler for this
3498 * instruction. This does apply to monitor-exit because of async exception handling.
3499 */
3500 if (work_line_->MonitorStackDepth() > 0 && !has_catch_all_handler) {
3501 /*
3502 * The state in work_line reflects the post-execution state. If the current instruction is a
3503 * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws,
3504 * it will do so before grabbing the lock).
3505 */
3506 if (inst->Opcode() != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) {
3507 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
3508 << "expected to be within a catch-all for an instruction where a monitor is held";
3509 return false;
3510 }
3511 }
3512 }
3513
3514 /* Handle "continue". Tag the next consecutive instruction.
3515 * Note: Keep the code handling "continue" case below the "branch" and "switch" cases,
3516 * because it changes work_line_ when performing peephole optimization
3517 * and this change should not be used in those cases.
3518 */
3519 if ((opcode_flags & Instruction::kContinue) != 0 && !exc_handler_unreachable) {
3520 DCHECK_EQ(&code_item_accessor_.InstructionAt(work_insn_idx_), inst);
3521 uint32_t next_insn_idx = work_insn_idx_ + inst->SizeInCodeUnits();
3522 if (next_insn_idx >= code_item_accessor_.InsnsSizeInCodeUnits()) {
3523 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Execution can walk off end of code area";
3524 return false;
3525 }
3526 // The only way to get to a move-exception instruction is to get thrown there. Make sure the
3527 // next instruction isn't one.
3528 if (!CheckNotMoveException(code_item_accessor_.Insns(), next_insn_idx)) {
3529 return false;
3530 }
3531 if (nullptr != fallthrough_line) {
3532 // Make workline consistent with fallthrough computed from peephole optimization.
3533 work_line_->CopyFromLine(fallthrough_line.get());
3534 }
3535 if (GetInstructionFlags(next_insn_idx).IsReturn()) {
3536 // For returns we only care about the operand to the return, all other registers are dead.
3537 const Instruction* ret_inst = &code_item_accessor_.InstructionAt(next_insn_idx);
3538 AdjustReturnLine(this, ret_inst, work_line_.get());
3539 }
3540 RegisterLine* next_line = reg_table_.GetLine(next_insn_idx);
3541 if (next_line != nullptr) {
3542 // Merge registers into what we have for the next instruction, and set the "changed" flag if
3543 // needed. If the merge changes the state of the registers then the work line will be
3544 // updated.
3545 if (!UpdateRegisters(next_insn_idx, work_line_.get(), true)) {
3546 return false;
3547 }
3548 } else {
3549 /*
3550 * We're not recording register data for the next instruction, so we don't know what the
3551 * prior state was. We have to assume that something has changed and re-evaluate it.
3552 */
3553 GetModifiableInstructionFlags(next_insn_idx).SetChanged();
3554 }
3555 }
3556
3557 /* If we're returning from the method, make sure monitor stack is empty. */
3558 if ((opcode_flags & Instruction::kReturn) != 0) {
3559 work_line_->VerifyMonitorStackEmpty(this);
3560 }
3561
3562 /*
3563 * Update start_guess. Advance to the next instruction of that's
3564 * possible, otherwise use the branch target if one was found. If
3565 * neither of those exists we're in a return or throw; leave start_guess
3566 * alone and let the caller sort it out.
3567 */
3568 if ((opcode_flags & Instruction::kContinue) != 0) {
3569 DCHECK_EQ(&code_item_accessor_.InstructionAt(work_insn_idx_), inst);
3570 *start_guess = work_insn_idx_ + inst->SizeInCodeUnits();
3571 } else if ((opcode_flags & Instruction::kBranch) != 0) {
3572 /* we're still okay if branch_target is zero */
3573 *start_guess = work_insn_idx_ + branch_target;
3574 }
3575
3576 DCHECK_LT(*start_guess, code_item_accessor_.InsnsSizeInCodeUnits());
3577 DCHECK(GetInstructionFlags(*start_guess).IsOpcode());
3578
3579 if (flags_.have_pending_runtime_throw_failure_) {
3580 Fail(VERIFY_ERROR_RUNTIME_THROW, /* pending_exc= */ false);
3581 // Reset the pending_runtime_throw flag now.
3582 flags_.have_pending_runtime_throw_failure_ = false;
3583 }
3584
3585 return true;
3586 } // NOLINT(readability/fn_size)
3587
3588 template <bool kVerifierDebug>
3589 template <CheckAccess C>
ResolveClass(dex::TypeIndex class_idx)3590 const RegType& MethodVerifier<kVerifierDebug>::ResolveClass(dex::TypeIndex class_idx) {
3591 ClassLinker* linker = GetClassLinker();
3592 ObjPtr<mirror::Class> klass = CanLoadClasses()
3593 ? linker->ResolveType(class_idx, dex_cache_, class_loader_)
3594 : linker->LookupResolvedType(class_idx, dex_cache_.Get(), class_loader_.Get());
3595 if (CanLoadClasses() && klass == nullptr) {
3596 DCHECK(self_->IsExceptionPending());
3597 self_->ClearException();
3598 }
3599 const RegType* result = nullptr;
3600 if (klass != nullptr) {
3601 bool precise = klass->CannotBeAssignedFromOtherTypes();
3602 if (precise && !IsInstantiableOrPrimitive(klass)) {
3603 const char* descriptor = dex_file_->GetTypeDescriptor(class_idx);
3604 UninstantiableError(descriptor);
3605 precise = false;
3606 }
3607 result = reg_types_.FindClass(klass, precise);
3608 if (result == nullptr) {
3609 const char* descriptor = dex_file_->GetTypeDescriptor(class_idx);
3610 result = reg_types_.InsertClass(descriptor, klass, precise);
3611 }
3612 } else {
3613 const char* descriptor = dex_file_->GetTypeDescriptor(class_idx);
3614 result = ®_types_.FromDescriptor(class_loader_, descriptor);
3615 }
3616 DCHECK(result != nullptr);
3617 if (result->IsConflict()) {
3618 const char* descriptor = dex_file_->GetTypeDescriptor(class_idx);
3619 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "accessing broken descriptor '" << descriptor
3620 << "' in " << GetDeclaringClass();
3621 return *result;
3622 }
3623
3624 // If requested, check if access is allowed. Unresolved types are included in this check, as the
3625 // interpreter only tests whether access is allowed when a class is not pre-verified and runs in
3626 // the access-checks interpreter. If result is primitive, skip the access check.
3627 //
3628 // Note: we do this for unresolved classes to trigger re-verification at runtime.
3629 if (C != CheckAccess::kNo &&
3630 result->IsNonZeroReferenceTypes() &&
3631 ((C == CheckAccess::kYes && IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP))
3632 || !result->IsUnresolvedTypes())) {
3633 const RegType& referrer = GetDeclaringClass();
3634 if ((IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP) || !referrer.IsUnresolvedTypes()) &&
3635 !referrer.CanAccess(*result)) {
3636 if (IsAotMode()) {
3637 Fail(VERIFY_ERROR_ACCESS_CLASS);
3638 VLOG(verifier)
3639 << "(possibly) illegal class access: '" << referrer << "' -> '" << *result << "'";
3640 } else {
3641 Fail(VERIFY_ERROR_ACCESS_CLASS)
3642 << "(possibly) illegal class access: '" << referrer << "' -> '" << *result << "'";
3643 }
3644 }
3645 }
3646 return *result;
3647 }
3648
3649 template <bool kVerifierDebug>
HandleMoveException(const Instruction * inst)3650 bool MethodVerifier<kVerifierDebug>::HandleMoveException(const Instruction* inst) {
3651 // We do not allow MOVE_EXCEPTION as the first instruction in a method. This is a simple case
3652 // where one entrypoint to the catch block is not actually an exception path.
3653 if (work_insn_idx_ == 0) {
3654 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "move-exception at pc 0x0";
3655 return true;
3656 }
3657 /*
3658 * This statement can only appear as the first instruction in an exception handler. We verify
3659 * that as part of extracting the exception type from the catch block list.
3660 */
3661 auto caught_exc_type_fn = [&]() REQUIRES_SHARED(Locks::mutator_lock_) ->
3662 std::pair<bool, const RegType*> {
3663 const RegType* common_super = nullptr;
3664 if (code_item_accessor_.TriesSize() != 0) {
3665 const uint8_t* handlers_ptr = code_item_accessor_.GetCatchHandlerData();
3666 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3667 const RegType* unresolved = nullptr;
3668 for (uint32_t i = 0; i < handlers_size; i++) {
3669 CatchHandlerIterator iterator(handlers_ptr);
3670 for (; iterator.HasNext(); iterator.Next()) {
3671 if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) {
3672 if (!iterator.GetHandlerTypeIndex().IsValid()) {
3673 common_super = ®_types_.JavaLangThrowable();
3674 } else {
3675 // Do access checks only on resolved exception classes.
3676 const RegType& exception =
3677 ResolveClass<CheckAccess::kOnResolvedClass>(iterator.GetHandlerTypeIndex());
3678 if (!reg_types_.JavaLangThrowable().IsAssignableFrom(exception, this)) {
3679 DCHECK(!exception.IsUninitializedTypes()); // Comes from dex, shouldn't be uninit.
3680 if (exception.IsUnresolvedTypes()) {
3681 if (unresolved == nullptr) {
3682 unresolved = &exception;
3683 } else {
3684 unresolved = &unresolved->SafeMerge(exception, ®_types_, this);
3685 }
3686 } else {
3687 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected non-throwable class "
3688 << exception;
3689 return std::make_pair(true, ®_types_.Conflict());
3690 }
3691 } else if (common_super == nullptr) {
3692 common_super = &exception;
3693 } else if (common_super->Equals(exception)) {
3694 // odd case, but nothing to do
3695 } else {
3696 common_super = &common_super->Merge(exception, ®_types_, this);
3697 if (FailOrAbort(reg_types_.JavaLangThrowable().IsAssignableFrom(
3698 *common_super, this),
3699 "java.lang.Throwable is not assignable-from common_super at ",
3700 work_insn_idx_)) {
3701 break;
3702 }
3703 }
3704 }
3705 }
3706 }
3707 handlers_ptr = iterator.EndDataPointer();
3708 }
3709 if (unresolved != nullptr) {
3710 // Soft-fail, but do not handle this with a synthetic throw.
3711 Fail(VERIFY_ERROR_UNRESOLVED_TYPE_CHECK, /*pending_exc=*/ false)
3712 << "Unresolved catch handler";
3713 bool should_continue = true;
3714 if (common_super != nullptr) {
3715 unresolved = &unresolved->Merge(*common_super, ®_types_, this);
3716 } else {
3717 should_continue = !PotentiallyMarkRuntimeThrow();
3718 }
3719 return std::make_pair(should_continue, unresolved);
3720 }
3721 }
3722 if (common_super == nullptr) {
3723 /* No catch block */
3724 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to find exception handler";
3725 return std::make_pair(true, ®_types_.Conflict());
3726 }
3727 return std::make_pair(true, common_super);
3728 };
3729 auto result = caught_exc_type_fn();
3730 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_11x(), *result.second);
3731 return result.first;
3732 }
3733
3734 template <bool kVerifierDebug>
ResolveMethodAndCheckAccess(uint32_t dex_method_idx,MethodType method_type)3735 ArtMethod* MethodVerifier<kVerifierDebug>::ResolveMethodAndCheckAccess(
3736 uint32_t dex_method_idx, MethodType method_type) {
3737 const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx);
3738 const RegType& klass_type = ResolveClass<CheckAccess::kYes>(method_id.class_idx_);
3739 if (klass_type.IsConflict()) {
3740 std::string append(" in attempt to access method ");
3741 append += dex_file_->GetMethodName(method_id);
3742 AppendToLastFailMessage(append);
3743 return nullptr;
3744 }
3745 if (klass_type.IsUnresolvedTypes()) {
3746 return nullptr; // Can't resolve Class so no more to do here
3747 }
3748 ObjPtr<mirror::Class> klass = klass_type.GetClass();
3749 const RegType& referrer = GetDeclaringClass();
3750 ClassLinker* class_linker = GetClassLinker();
3751
3752 ArtMethod* res_method = dex_cache_->GetResolvedMethod(dex_method_idx);
3753 if (res_method == nullptr) {
3754 res_method = class_linker->FindResolvedMethod(
3755 klass, dex_cache_.Get(), class_loader_.Get(), dex_method_idx);
3756 }
3757
3758 bool must_fail = false;
3759 // This is traditional and helps with screwy bytecode. It will tell you that, yes, a method
3760 // exists, but that it's called incorrectly. This significantly helps debugging, as locally it's
3761 // hard to see the differences.
3762 // If we don't have res_method here we must fail. Just use this bool to make sure of that with a
3763 // DCHECK.
3764 if (res_method == nullptr) {
3765 must_fail = true;
3766 // Try to find the method also with the other type for better error reporting below
3767 // but do not store such bogus lookup result in the DexCache or VerifierDeps.
3768 res_method = class_linker->FindIncompatibleMethod(
3769 klass, dex_cache_.Get(), class_loader_.Get(), dex_method_idx);
3770 }
3771
3772 if (res_method == nullptr) {
3773 Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method "
3774 << klass->PrettyDescriptor() << "."
3775 << dex_file_->GetMethodName(method_id) << " "
3776 << dex_file_->GetMethodSignature(method_id);
3777 return nullptr;
3778 }
3779
3780 // Make sure calls to constructors are "direct". There are additional restrictions but we don't
3781 // enforce them here.
3782 if (res_method->IsConstructor() && method_type != METHOD_DIRECT) {
3783 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting non-direct call to constructor "
3784 << res_method->PrettyMethod();
3785 return nullptr;
3786 }
3787 // Disallow any calls to class initializers.
3788 if (res_method->IsClassInitializer()) {
3789 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting call to class initializer "
3790 << res_method->PrettyMethod();
3791 return nullptr;
3792 }
3793
3794 // Check that interface methods are static or match interface classes.
3795 // We only allow statics if we don't have default methods enabled.
3796 //
3797 // Note: this check must be after the initializer check, as those are required to fail a class,
3798 // while this check implies an IncompatibleClassChangeError.
3799 if (klass->IsInterface()) {
3800 // methods called on interfaces should be invoke-interface, invoke-super, invoke-direct (if
3801 // default methods are supported for the dex file), or invoke-static.
3802 if (method_type != METHOD_INTERFACE &&
3803 method_type != METHOD_STATIC &&
3804 (!dex_file_->SupportsDefaultMethods() ||
3805 method_type != METHOD_DIRECT) &&
3806 method_type != METHOD_SUPER) {
3807 Fail(VERIFY_ERROR_CLASS_CHANGE)
3808 << "non-interface method " << dex_file_->PrettyMethod(dex_method_idx)
3809 << " is in an interface class " << klass->PrettyClass();
3810 return nullptr;
3811 }
3812 } else {
3813 if (method_type == METHOD_INTERFACE) {
3814 Fail(VERIFY_ERROR_CLASS_CHANGE)
3815 << "interface method " << dex_file_->PrettyMethod(dex_method_idx)
3816 << " is in a non-interface class " << klass->PrettyClass();
3817 return nullptr;
3818 }
3819 }
3820
3821 // Check specifically for non-public object methods being provided for interface dispatch. This
3822 // can occur if we failed to find a method with FindInterfaceMethod but later find one with
3823 // FindClassMethod for error message use.
3824 if (method_type == METHOD_INTERFACE &&
3825 res_method->GetDeclaringClass()->IsObjectClass() &&
3826 !res_method->IsPublic()) {
3827 Fail(VERIFY_ERROR_NO_METHOD) << "invoke-interface " << klass->PrettyDescriptor() << "."
3828 << dex_file_->GetMethodName(method_id) << " "
3829 << dex_file_->GetMethodSignature(method_id) << " resolved to "
3830 << "non-public object method " << res_method->PrettyMethod() << " "
3831 << "but non-public Object methods are excluded from interface "
3832 << "method resolution.";
3833 return nullptr;
3834 }
3835 // Check if access is allowed.
3836 if (!referrer.CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) {
3837 Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call "
3838 << res_method->PrettyMethod()
3839 << " from " << referrer << ")";
3840 return res_method;
3841 }
3842 // Check that invoke-virtual and invoke-super are not used on private methods of the same class.
3843 if (res_method->IsPrivate() && (method_type == METHOD_VIRTUAL || method_type == METHOD_SUPER)) {
3844 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-super/virtual can't be used on private method "
3845 << res_method->PrettyMethod();
3846 return nullptr;
3847 }
3848 // See if the method type implied by the invoke instruction matches the access flags for the
3849 // target method. The flags for METHOD_POLYMORPHIC are based on there being precisely two
3850 // signature polymorphic methods supported by the run-time which are native methods with variable
3851 // arguments.
3852 if ((method_type == METHOD_DIRECT && (!res_method->IsDirect() || res_method->IsStatic())) ||
3853 (method_type == METHOD_STATIC && !res_method->IsStatic()) ||
3854 ((method_type == METHOD_SUPER ||
3855 method_type == METHOD_VIRTUAL ||
3856 method_type == METHOD_INTERFACE) && res_method->IsDirect()) ||
3857 ((method_type == METHOD_POLYMORPHIC) &&
3858 (!res_method->IsNative() || !res_method->IsVarargs()))) {
3859 Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type (" << method_type << ") does not match method "
3860 "type of " << res_method->PrettyMethod();
3861 return nullptr;
3862 }
3863 // Make sure we weren't expecting to fail.
3864 DCHECK(!must_fail) << "invoke type (" << method_type << ")"
3865 << klass->PrettyDescriptor() << "."
3866 << dex_file_->GetMethodName(method_id) << " "
3867 << dex_file_->GetMethodSignature(method_id) << " unexpectedly resolved to "
3868 << res_method->PrettyMethod() << " without error. Initially this method was "
3869 << "not found so we were expecting to fail for some reason.";
3870 return res_method;
3871 }
3872
3873 template <bool kVerifierDebug>
3874 template <class T>
VerifyInvocationArgsFromIterator(T * it,const Instruction * inst,MethodType method_type,bool is_range,ArtMethod * res_method)3875 ArtMethod* MethodVerifier<kVerifierDebug>::VerifyInvocationArgsFromIterator(
3876 T* it, const Instruction* inst, MethodType method_type, bool is_range, ArtMethod* res_method) {
3877 DCHECK_EQ(!is_range, inst->HasVarArgs());
3878
3879 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to
3880 // match the call to the signature. Also, we might be calling through an abstract method
3881 // definition (which doesn't have register count values).
3882 const size_t expected_args = inst->VRegA();
3883 /* caught by static verifier */
3884 DCHECK(is_range || expected_args <= 5);
3885
3886 if (expected_args > code_item_accessor_.OutsSize()) {
3887 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args
3888 << ") exceeds outsSize ("
3889 << code_item_accessor_.OutsSize() << ")";
3890 return nullptr;
3891 }
3892
3893 /*
3894 * Check the "this" argument, which must be an instance of the class that declared the method.
3895 * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a
3896 * rigorous check here (which is okay since we have to do it at runtime).
3897 */
3898 if (method_type != METHOD_STATIC) {
3899 const RegType& actual_arg_type = work_line_->GetInvocationThis(this, inst);
3900 if (actual_arg_type.IsConflict()) { // GetInvocationThis failed.
3901 CHECK(flags_.have_pending_hard_failure_);
3902 return nullptr;
3903 }
3904 bool is_init = false;
3905 if (actual_arg_type.IsUninitializedTypes()) {
3906 if (res_method != nullptr) {
3907 if (!res_method->IsConstructor()) {
3908 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
3909 return nullptr;
3910 }
3911 } else {
3912 // Check whether the name of the called method is "<init>"
3913 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
3914 if (strcmp(dex_file_->GetMethodName(dex_file_->GetMethodId(method_idx)), "<init>") != 0) {
3915 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
3916 return nullptr;
3917 }
3918 }
3919 is_init = true;
3920 }
3921 const RegType& adjusted_type = is_init
3922 ? GetRegTypeCache()->FromUninitialized(actual_arg_type)
3923 : actual_arg_type;
3924 if (method_type != METHOD_INTERFACE && !adjusted_type.IsZeroOrNull()) {
3925 const RegType* res_method_class;
3926 // Miranda methods have the declaring interface as their declaring class, not the abstract
3927 // class. It would be wrong to use this for the type check (interface type checks are
3928 // postponed to runtime).
3929 if (res_method != nullptr && !res_method->IsMiranda()) {
3930 ObjPtr<mirror::Class> klass = res_method->GetDeclaringClass();
3931 std::string temp;
3932 res_method_class = &FromClass(klass->GetDescriptor(&temp), klass,
3933 klass->CannotBeAssignedFromOtherTypes());
3934 } else {
3935 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
3936 const dex::TypeIndex class_idx = dex_file_->GetMethodId(method_idx).class_idx_;
3937 res_method_class =
3938 ®_types_.FromDescriptor(class_loader_, dex_file_->GetTypeDescriptor(class_idx));
3939 }
3940 if (!res_method_class->IsAssignableFrom(adjusted_type, this)) {
3941 Fail(adjusted_type.IsUnresolvedTypes()
3942 ? VERIFY_ERROR_UNRESOLVED_TYPE_CHECK
3943 : VERIFY_ERROR_BAD_CLASS_HARD)
3944 << "'this' argument '" << actual_arg_type << "' not instance of '"
3945 << *res_method_class << "'";
3946 // Continue on soft failures. We need to find possible hard failures to avoid problems in
3947 // the compiler.
3948 if (flags_.have_pending_hard_failure_) {
3949 return nullptr;
3950 }
3951 }
3952 }
3953 }
3954
3955 uint32_t arg[5];
3956 if (!is_range) {
3957 inst->GetVarArgs(arg);
3958 }
3959 uint32_t sig_registers = (method_type == METHOD_STATIC) ? 0 : 1;
3960 for ( ; it->HasNext(); it->Next()) {
3961 if (sig_registers >= expected_args) {
3962 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << inst->VRegA() <<
3963 " argument registers, method signature has " << sig_registers + 1 << " or more";
3964 return nullptr;
3965 }
3966
3967 const char* param_descriptor = it->GetDescriptor();
3968
3969 if (param_descriptor == nullptr) {
3970 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation because of missing signature "
3971 "component";
3972 return nullptr;
3973 }
3974
3975 const RegType& reg_type = reg_types_.FromDescriptor(class_loader_, param_descriptor);
3976 uint32_t get_reg = is_range ? inst->VRegC() + static_cast<uint32_t>(sig_registers) :
3977 arg[sig_registers];
3978 if (reg_type.IsIntegralTypes()) {
3979 const RegType& src_type = work_line_->GetRegisterType(this, get_reg);
3980 if (!src_type.IsIntegralTypes()) {
3981 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register v" << get_reg << " has type " << src_type
3982 << " but expected " << reg_type;
3983 return nullptr;
3984 }
3985 } else {
3986 if (!work_line_->VerifyRegisterType(this, get_reg, reg_type)) {
3987 // Continue on soft failures. We need to find possible hard failures to avoid problems in
3988 // the compiler.
3989 if (flags_.have_pending_hard_failure_) {
3990 return nullptr;
3991 }
3992 } else if (reg_type.IsLongOrDoubleTypes()) {
3993 // Check that registers are consecutive (for non-range invokes). Invokes are the only
3994 // instructions not specifying register pairs by the first component, but require them
3995 // nonetheless. Only check when there's an actual register in the parameters. If there's
3996 // none, this will fail below.
3997 if (!is_range && sig_registers + 1 < expected_args) {
3998 uint32_t second_reg = arg[sig_registers + 1];
3999 if (second_reg != get_reg + 1) {
4000 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, long or double parameter "
4001 "at index " << sig_registers << " is not a pair: " << get_reg << " + "
4002 << second_reg << ".";
4003 return nullptr;
4004 }
4005 }
4006 }
4007 }
4008 sig_registers += reg_type.IsLongOrDoubleTypes() ? 2 : 1;
4009 }
4010 if (expected_args != sig_registers) {
4011 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << expected_args <<
4012 " argument registers, method signature has " << sig_registers;
4013 return nullptr;
4014 }
4015 return res_method;
4016 }
4017
4018 template <bool kVerifierDebug>
VerifyInvocationArgsUnresolvedMethod(const Instruction * inst,MethodType method_type,bool is_range)4019 void MethodVerifier<kVerifierDebug>::VerifyInvocationArgsUnresolvedMethod(const Instruction* inst,
4020 MethodType method_type,
4021 bool is_range) {
4022 // As the method may not have been resolved, make this static check against what we expect.
4023 // The main reason for this code block is to fail hard when we find an illegal use, e.g.,
4024 // wrong number of arguments or wrong primitive types, even if the method could not be resolved.
4025 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
4026 DexFileParameterIterator it(*dex_file_,
4027 dex_file_->GetProtoId(dex_file_->GetMethodId(method_idx).proto_idx_));
4028 VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, nullptr);
4029 }
4030
4031 template <bool kVerifierDebug>
CheckCallSite(uint32_t call_site_idx)4032 bool MethodVerifier<kVerifierDebug>::CheckCallSite(uint32_t call_site_idx) {
4033 if (call_site_idx >= dex_file_->NumCallSiteIds()) {
4034 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Bad call site id #" << call_site_idx
4035 << " >= " << dex_file_->NumCallSiteIds();
4036 return false;
4037 }
4038
4039 CallSiteArrayValueIterator it(*dex_file_, dex_file_->GetCallSiteId(call_site_idx));
4040 // Check essential arguments are provided. The dex file verifier has verified indices of the
4041 // main values (method handle, name, method_type).
4042 static const size_t kRequiredArguments = 3;
4043 if (it.Size() < kRequiredArguments) {
4044 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site #" << call_site_idx
4045 << " has too few arguments: "
4046 << it.Size() << " < " << kRequiredArguments;
4047 return false;
4048 }
4049
4050 std::pair<const EncodedArrayValueIterator::ValueType, size_t> type_and_max[kRequiredArguments] =
4051 { { EncodedArrayValueIterator::ValueType::kMethodHandle, dex_file_->NumMethodHandles() },
4052 { EncodedArrayValueIterator::ValueType::kString, dex_file_->NumStringIds() },
4053 { EncodedArrayValueIterator::ValueType::kMethodType, dex_file_->NumProtoIds() }
4054 };
4055 uint32_t index[kRequiredArguments];
4056
4057 // Check arguments have expected types and are within permitted ranges.
4058 for (size_t i = 0; i < kRequiredArguments; ++i) {
4059 if (it.GetValueType() != type_and_max[i].first) {
4060 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site id #" << call_site_idx
4061 << " argument " << i << " has wrong type "
4062 << it.GetValueType() << "!=" << type_and_max[i].first;
4063 return false;
4064 }
4065 index[i] = static_cast<uint32_t>(it.GetJavaValue().i);
4066 if (index[i] >= type_and_max[i].second) {
4067 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site id #" << call_site_idx
4068 << " argument " << i << " bad index "
4069 << index[i] << " >= " << type_and_max[i].second;
4070 return false;
4071 }
4072 it.Next();
4073 }
4074
4075 // Check method handle kind is valid.
4076 const dex::MethodHandleItem& mh = dex_file_->GetMethodHandle(index[0]);
4077 if (mh.method_handle_type_ != static_cast<uint16_t>(DexFile::MethodHandleType::kInvokeStatic)) {
4078 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site #" << call_site_idx
4079 << " argument 0 method handle type is not InvokeStatic: "
4080 << mh.method_handle_type_;
4081 return false;
4082 }
4083 return true;
4084 }
4085
4086 class MethodParamListDescriptorIterator {
4087 public:
MethodParamListDescriptorIterator(ArtMethod * res_method)4088 explicit MethodParamListDescriptorIterator(ArtMethod* res_method) :
4089 res_method_(res_method), pos_(0), params_(res_method->GetParameterTypeList()),
4090 params_size_(params_ == nullptr ? 0 : params_->Size()) {
4091 }
4092
HasNext()4093 bool HasNext() {
4094 return pos_ < params_size_;
4095 }
4096
Next()4097 void Next() {
4098 ++pos_;
4099 }
4100
GetDescriptor()4101 const char* GetDescriptor() REQUIRES_SHARED(Locks::mutator_lock_) {
4102 return res_method_->GetTypeDescriptorFromTypeIdx(params_->GetTypeItem(pos_).type_idx_);
4103 }
4104
4105 private:
4106 ArtMethod* res_method_;
4107 size_t pos_;
4108 const dex::TypeList* params_;
4109 const size_t params_size_;
4110 };
4111
4112 template <bool kVerifierDebug>
VerifyInvocationArgs(const Instruction * inst,MethodType method_type,bool is_range)4113 ArtMethod* MethodVerifier<kVerifierDebug>::VerifyInvocationArgs(
4114 const Instruction* inst, MethodType method_type, bool is_range) {
4115 // Resolve the method. This could be an abstract or concrete method depending on what sort of call
4116 // we're making.
4117 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
4118 ArtMethod* res_method = ResolveMethodAndCheckAccess(method_idx, method_type);
4119 if (res_method == nullptr) { // error or class is unresolved
4120 // Check what we can statically.
4121 if (!flags_.have_pending_hard_failure_) {
4122 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4123 }
4124 return nullptr;
4125 }
4126
4127 // If we're using invoke-super(method), make sure that the executing method's class' superclass
4128 // has a vtable entry for the target method. Or the target is on a interface.
4129 if (method_type == METHOD_SUPER) {
4130 dex::TypeIndex class_idx = dex_file_->GetMethodId(method_idx).class_idx_;
4131 const RegType& reference_type =
4132 reg_types_.FromDescriptor(class_loader_, dex_file_->GetTypeDescriptor(class_idx));
4133 if (reference_type.IsUnresolvedTypes()) {
4134 // We cannot differentiate on whether this is a class change error or just
4135 // a missing method. This will be handled at runtime.
4136 Fail(VERIFY_ERROR_NO_METHOD) << "Unable to find referenced class from invoke-super";
4137 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4138 return nullptr;
4139 }
4140 if (reference_type.GetClass()->IsInterface()) {
4141 if (!GetDeclaringClass().HasClass()) {
4142 Fail(VERIFY_ERROR_NO_CLASS) << "Unable to resolve the full class of 'this' used in an"
4143 << "interface invoke-super";
4144 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4145 return nullptr;
4146 } else if (!reference_type.IsStrictlyAssignableFrom(GetDeclaringClass(), this)) {
4147 Fail(VERIFY_ERROR_CLASS_CHANGE)
4148 << "invoke-super in " << mirror::Class::PrettyClass(GetDeclaringClass().GetClass())
4149 << " in method "
4150 << dex_file_->PrettyMethod(dex_method_idx_) << " to method "
4151 << dex_file_->PrettyMethod(method_idx) << " references "
4152 << "non-super-interface type " << mirror::Class::PrettyClass(reference_type.GetClass());
4153 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4154 return nullptr;
4155 }
4156 } else {
4157 const RegType& super = GetDeclaringClass().GetSuperClass(®_types_);
4158 if (super.IsUnresolvedTypes()) {
4159 Fail(VERIFY_ERROR_NO_METHOD) << "unknown super class in invoke-super from "
4160 << dex_file_->PrettyMethod(dex_method_idx_)
4161 << " to super " << res_method->PrettyMethod();
4162 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4163 return nullptr;
4164 }
4165 if (!reference_type.IsStrictlyAssignableFrom(GetDeclaringClass(), this) ||
4166 (res_method->GetMethodIndex() >= super.GetClass()->GetVTableLength())) {
4167 Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from "
4168 << dex_file_->PrettyMethod(dex_method_idx_)
4169 << " to super " << super
4170 << "." << res_method->GetName()
4171 << res_method->GetSignature();
4172 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4173 return nullptr;
4174 }
4175 }
4176 }
4177
4178 if (UNLIKELY(method_type == METHOD_POLYMORPHIC)) {
4179 // Process the signature of the calling site that is invoking the method handle.
4180 dex::ProtoIndex proto_idx(inst->VRegH());
4181 DexFileParameterIterator it(*dex_file_, dex_file_->GetProtoId(proto_idx));
4182 return VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, res_method);
4183 } else {
4184 // Process the target method's signature.
4185 MethodParamListDescriptorIterator it(res_method);
4186 return VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, res_method);
4187 }
4188 }
4189
4190 template <bool kVerifierDebug>
CheckSignaturePolymorphicMethod(ArtMethod * method)4191 bool MethodVerifier<kVerifierDebug>::CheckSignaturePolymorphicMethod(ArtMethod* method) {
4192 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
4193 const char* method_name = method->GetName();
4194
4195 const char* expected_return_descriptor;
4196 ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots = GetClassLinker()->GetClassRoots();
4197 if (klass == GetClassRoot<mirror::MethodHandle>(class_roots)) {
4198 expected_return_descriptor = mirror::MethodHandle::GetReturnTypeDescriptor(method_name);
4199 } else if (klass == GetClassRoot<mirror::VarHandle>(class_roots)) {
4200 expected_return_descriptor = mirror::VarHandle::GetReturnTypeDescriptor(method_name);
4201 } else {
4202 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4203 << "Signature polymorphic method in unsuppported class: " << klass->PrettyDescriptor();
4204 return false;
4205 }
4206
4207 if (expected_return_descriptor == nullptr) {
4208 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4209 << "Signature polymorphic method name invalid: " << method_name;
4210 return false;
4211 }
4212
4213 const dex::TypeList* types = method->GetParameterTypeList();
4214 if (types->Size() != 1) {
4215 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4216 << "Signature polymorphic method has too many arguments " << types->Size() << " != 1";
4217 return false;
4218 }
4219
4220 const dex::TypeIndex argument_type_index = types->GetTypeItem(0).type_idx_;
4221 const char* argument_descriptor = method->GetTypeDescriptorFromTypeIdx(argument_type_index);
4222 if (strcmp(argument_descriptor, "[Ljava/lang/Object;") != 0) {
4223 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4224 << "Signature polymorphic method has unexpected argument type: " << argument_descriptor;
4225 return false;
4226 }
4227
4228 const char* return_descriptor = method->GetReturnTypeDescriptor();
4229 if (strcmp(return_descriptor, expected_return_descriptor) != 0) {
4230 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4231 << "Signature polymorphic method has unexpected return type: " << return_descriptor
4232 << " != " << expected_return_descriptor;
4233 return false;
4234 }
4235
4236 return true;
4237 }
4238
4239 template <bool kVerifierDebug>
CheckSignaturePolymorphicReceiver(const Instruction * inst)4240 bool MethodVerifier<kVerifierDebug>::CheckSignaturePolymorphicReceiver(const Instruction* inst) {
4241 const RegType& this_type = work_line_->GetInvocationThis(this, inst);
4242 if (this_type.IsZeroOrNull()) {
4243 /* null pointer always passes (and always fails at run time) */
4244 return true;
4245 } else if (!this_type.IsNonZeroReferenceTypes()) {
4246 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4247 << "invoke-polymorphic receiver is not a reference: "
4248 << this_type;
4249 return false;
4250 } else if (this_type.IsUninitializedReference()) {
4251 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4252 << "invoke-polymorphic receiver is uninitialized: "
4253 << this_type;
4254 return false;
4255 } else if (!this_type.HasClass()) {
4256 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4257 << "invoke-polymorphic receiver has no class: "
4258 << this_type;
4259 return false;
4260 } else {
4261 ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots = GetClassLinker()->GetClassRoots();
4262 if (!this_type.GetClass()->IsSubClass(GetClassRoot<mirror::MethodHandle>(class_roots)) &&
4263 !this_type.GetClass()->IsSubClass(GetClassRoot<mirror::VarHandle>(class_roots))) {
4264 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4265 << "invoke-polymorphic receiver is not a subclass of MethodHandle or VarHandle: "
4266 << this_type;
4267 return false;
4268 }
4269 }
4270 return true;
4271 }
4272
4273 template <bool kVerifierDebug>
VerifyNewArray(const Instruction * inst,bool is_filled,bool is_range)4274 void MethodVerifier<kVerifierDebug>::VerifyNewArray(const Instruction* inst,
4275 bool is_filled,
4276 bool is_range) {
4277 dex::TypeIndex type_idx;
4278 if (!is_filled) {
4279 DCHECK_EQ(inst->Opcode(), Instruction::NEW_ARRAY);
4280 type_idx = dex::TypeIndex(inst->VRegC_22c());
4281 } else if (!is_range) {
4282 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY);
4283 type_idx = dex::TypeIndex(inst->VRegB_35c());
4284 } else {
4285 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY_RANGE);
4286 type_idx = dex::TypeIndex(inst->VRegB_3rc());
4287 }
4288 const RegType& res_type = ResolveClass<CheckAccess::kYes>(type_idx);
4289 if (res_type.IsConflict()) { // bad class
4290 DCHECK_NE(failures_.size(), 0U);
4291 } else {
4292 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
4293 if (!res_type.IsArrayTypes()) {
4294 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "new-array on non-array class " << res_type;
4295 } else if (!is_filled) {
4296 /* make sure "size" register is valid type */
4297 work_line_->VerifyRegisterType(this, inst->VRegB_22c(), reg_types_.Integer());
4298 /* set register type to array class */
4299 const RegType& precise_type = reg_types_.FromUninitialized(res_type);
4300 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_22c(), precise_type);
4301 } else {
4302 DCHECK(!res_type.IsUnresolvedMergedReference());
4303 // Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of
4304 // the list and fail. It's legal, if silly, for arg_count to be zero.
4305 const RegType& expected_type = reg_types_.GetComponentType(res_type, class_loader_);
4306 uint32_t arg_count = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c();
4307 uint32_t arg[5];
4308 if (!is_range) {
4309 inst->GetVarArgs(arg);
4310 }
4311 for (size_t ui = 0; ui < arg_count; ui++) {
4312 uint32_t get_reg = is_range ? inst->VRegC_3rc() + ui : arg[ui];
4313 work_line_->VerifyRegisterType(this, get_reg, expected_type);
4314 }
4315 // filled-array result goes into "result" register
4316 const RegType& precise_type = reg_types_.FromUninitialized(res_type);
4317 work_line_->SetResultRegisterType(this, precise_type);
4318 }
4319 }
4320 }
4321
4322 template <bool kVerifierDebug>
VerifyAGet(const Instruction * inst,const RegType & insn_type,bool is_primitive)4323 void MethodVerifier<kVerifierDebug>::VerifyAGet(const Instruction* inst,
4324 const RegType& insn_type,
4325 bool is_primitive) {
4326 const RegType& index_type = work_line_->GetRegisterType(this, inst->VRegC_23x());
4327 if (!index_type.IsArrayIndexTypes()) {
4328 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
4329 } else {
4330 const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegB_23x());
4331 if (array_type.IsZeroOrNull()) {
4332 // Null array class; this code path will fail at runtime. Infer a merge-able type from the
4333 // instruction type.
4334 if (!is_primitive) {
4335 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_23x(), reg_types_.Null());
4336 } else if (insn_type.IsInteger()) {
4337 // Pick a non-zero constant (to distinguish with null) that can fit in any primitive.
4338 // We cannot use 'insn_type' as it could be a float array or an int array.
4339 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_23x(), DetermineCat1Constant(1));
4340 } else if (insn_type.IsCategory1Types()) {
4341 // Category 1
4342 // The 'insn_type' is exactly the type we need.
4343 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_23x(), insn_type);
4344 } else {
4345 // Category 2
4346 work_line_->SetRegisterTypeWide(inst->VRegA_23x(),
4347 reg_types_.FromCat2ConstLo(0, false),
4348 reg_types_.FromCat2ConstHi(0, false));
4349 }
4350 } else if (!array_type.IsArrayTypes()) {
4351 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aget";
4352 } else if (array_type.IsUnresolvedMergedReference()) {
4353 // Unresolved array types must be reference array types.
4354 if (is_primitive) {
4355 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type
4356 << " source for category 1 aget";
4357 } else {
4358 Fail(VERIFY_ERROR_NO_CLASS) << "cannot verify aget for " << array_type
4359 << " because of missing class";
4360 // Approximate with java.lang.Object[].
4361 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_23x(),
4362 reg_types_.JavaLangObject(false));
4363 }
4364 } else {
4365 /* verify the class */
4366 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_);
4367 if (!component_type.IsReferenceTypes() && !is_primitive) {
4368 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
4369 << " source for aget-object";
4370 } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) {
4371 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type
4372 << " source for category 1 aget";
4373 } else if (is_primitive && !insn_type.Equals(component_type) &&
4374 !((insn_type.IsInteger() && component_type.IsFloat()) ||
4375 (insn_type.IsLong() && component_type.IsDouble()))) {
4376 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type
4377 << " incompatible with aget of type " << insn_type;
4378 } else {
4379 // Use knowledge of the field type which is stronger than the type inferred from the
4380 // instruction, which can't differentiate object types and ints from floats, longs from
4381 // doubles.
4382 if (!component_type.IsLowHalf()) {
4383 work_line_->SetRegisterType<LockOp::kClear>(inst->VRegA_23x(), component_type);
4384 } else {
4385 work_line_->SetRegisterTypeWide(inst->VRegA_23x(), component_type,
4386 component_type.HighHalf(®_types_));
4387 }
4388 }
4389 }
4390 }
4391 }
4392
4393 template <bool kVerifierDebug>
VerifyPrimitivePut(const RegType & target_type,const RegType & insn_type,const uint32_t vregA)4394 void MethodVerifier<kVerifierDebug>::VerifyPrimitivePut(const RegType& target_type,
4395 const RegType& insn_type,
4396 const uint32_t vregA) {
4397 // Primitive assignability rules are weaker than regular assignability rules.
4398 bool instruction_compatible;
4399 bool value_compatible;
4400 const RegType& value_type = work_line_->GetRegisterType(this, vregA);
4401 if (target_type.IsIntegralTypes()) {
4402 instruction_compatible = target_type.Equals(insn_type);
4403 value_compatible = value_type.IsIntegralTypes();
4404 } else if (target_type.IsFloat()) {
4405 instruction_compatible = insn_type.IsInteger(); // no put-float, so expect put-int
4406 value_compatible = value_type.IsFloatTypes();
4407 } else if (target_type.IsLong()) {
4408 instruction_compatible = insn_type.IsLong();
4409 // Additional register check: this is not checked statically (as part of VerifyInstructions),
4410 // as target_type depends on the resolved type of the field.
4411 if (instruction_compatible && work_line_->NumRegs() > vregA + 1) {
4412 const RegType& value_type_hi = work_line_->GetRegisterType(this, vregA + 1);
4413 value_compatible = value_type.IsLongTypes() && value_type.CheckWidePair(value_type_hi);
4414 } else {
4415 value_compatible = false;
4416 }
4417 } else if (target_type.IsDouble()) {
4418 instruction_compatible = insn_type.IsLong(); // no put-double, so expect put-long
4419 // Additional register check: this is not checked statically (as part of VerifyInstructions),
4420 // as target_type depends on the resolved type of the field.
4421 if (instruction_compatible && work_line_->NumRegs() > vregA + 1) {
4422 const RegType& value_type_hi = work_line_->GetRegisterType(this, vregA + 1);
4423 value_compatible = value_type.IsDoubleTypes() && value_type.CheckWidePair(value_type_hi);
4424 } else {
4425 value_compatible = false;
4426 }
4427 } else {
4428 instruction_compatible = false; // reference with primitive store
4429 value_compatible = false; // unused
4430 }
4431 if (!instruction_compatible) {
4432 // This is a global failure rather than a class change failure as the instructions and
4433 // the descriptors for the type should have been consistent within the same file at
4434 // compile time.
4435 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type
4436 << "' but expected type '" << target_type << "'";
4437 return;
4438 }
4439 if (!value_compatible) {
4440 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA
4441 << " of type " << value_type << " but expected " << target_type << " for put";
4442 return;
4443 }
4444 }
4445
4446 template <bool kVerifierDebug>
VerifyAPut(const Instruction * inst,const RegType & insn_type,bool is_primitive)4447 void MethodVerifier<kVerifierDebug>::VerifyAPut(const Instruction* inst,
4448 const RegType& insn_type,
4449 bool is_primitive) {
4450 const RegType& index_type = work_line_->GetRegisterType(this, inst->VRegC_23x());
4451 if (!index_type.IsArrayIndexTypes()) {
4452 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
4453 } else {
4454 const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegB_23x());
4455 if (array_type.IsZeroOrNull()) {
4456 // Null array type; this code path will fail at runtime.
4457 // Still check that the given value matches the instruction's type.
4458 // Note: this is, as usual, complicated by the fact the the instruction isn't fully typed
4459 // and fits multiple register types.
4460 const RegType* modified_reg_type = &insn_type;
4461 if ((modified_reg_type == ®_types_.Integer()) ||
4462 (modified_reg_type == ®_types_.LongLo())) {
4463 // May be integer or float | long or double. Overwrite insn_type accordingly.
4464 const RegType& value_type = work_line_->GetRegisterType(this, inst->VRegA_23x());
4465 if (modified_reg_type == ®_types_.Integer()) {
4466 if (&value_type == ®_types_.Float()) {
4467 modified_reg_type = &value_type;
4468 }
4469 } else {
4470 if (&value_type == ®_types_.DoubleLo()) {
4471 modified_reg_type = &value_type;
4472 }
4473 }
4474 }
4475 work_line_->VerifyRegisterType(this, inst->VRegA_23x(), *modified_reg_type);
4476 } else if (!array_type.IsArrayTypes()) {
4477 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aput";
4478 } else if (array_type.IsUnresolvedMergedReference()) {
4479 // Unresolved array types must be reference array types.
4480 if (is_primitive) {
4481 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type
4482 << "' but unresolved type '" << array_type << "'";
4483 } else {
4484 Fail(VERIFY_ERROR_NO_CLASS) << "cannot verify aput for " << array_type
4485 << " because of missing class";
4486 }
4487 } else {
4488 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_);
4489 const uint32_t vregA = inst->VRegA_23x();
4490 if (is_primitive) {
4491 VerifyPrimitivePut(component_type, insn_type, vregA);
4492 } else {
4493 if (!component_type.IsReferenceTypes()) {
4494 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
4495 << " source for aput-object";
4496 } else {
4497 // The instruction agrees with the type of array, confirm the value to be stored does too
4498 // Note: we use the instruction type (rather than the component type) for aput-object as
4499 // incompatible classes will be caught at runtime as an array store exception
4500 work_line_->VerifyRegisterType(this, vregA, insn_type);
4501 }
4502 }
4503 }
4504 }
4505 }
4506
4507 template <bool kVerifierDebug>
GetStaticField(int field_idx)4508 ArtField* MethodVerifier<kVerifierDebug>::GetStaticField(int field_idx) {
4509 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
4510 // Check access to class
4511 const RegType& klass_type = ResolveClass<CheckAccess::kYes>(field_id.class_idx_);
4512 if (klass_type.IsConflict()) { // bad class
4513 AppendToLastFailMessage(StringPrintf(" in attempt to access static field %d (%s) in %s",
4514 field_idx, dex_file_->GetFieldName(field_id),
4515 dex_file_->GetFieldDeclaringClassDescriptor(field_id)));
4516 return nullptr;
4517 }
4518 if (klass_type.IsUnresolvedTypes()) {
4519 // Accessibility checks depend on resolved fields.
4520 DCHECK(klass_type.Equals(GetDeclaringClass()) ||
4521 !failures_.empty() ||
4522 IsSdkVersionSetAndLessThan(api_level_, SdkVersion::kP));
4523
4524 return nullptr; // Can't resolve Class so no more to do here, will do checking at runtime.
4525 }
4526 ClassLinker* class_linker = GetClassLinker();
4527 ArtField* field = class_linker->ResolveFieldJLS(field_idx, dex_cache_, class_loader_);
4528
4529 if (field == nullptr) {
4530 VLOG(verifier) << "Unable to resolve static field " << field_idx << " ("
4531 << dex_file_->GetFieldName(field_id) << ") in "
4532 << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
4533 DCHECK(self_->IsExceptionPending());
4534 self_->ClearException();
4535 return nullptr;
4536 } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(),
4537 field->GetAccessFlags())) {
4538 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << field->PrettyField()
4539 << " from " << GetDeclaringClass();
4540 return nullptr;
4541 } else if (!field->IsStatic()) {
4542 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << field->PrettyField() << " to be static";
4543 return nullptr;
4544 }
4545 return field;
4546 }
4547
4548 template <bool kVerifierDebug>
GetInstanceField(const RegType & obj_type,int field_idx)4549 ArtField* MethodVerifier<kVerifierDebug>::GetInstanceField(const RegType& obj_type, int field_idx) {
4550 if (!obj_type.IsZeroOrNull() && !obj_type.IsReferenceTypes()) {
4551 // Trying to read a field from something that isn't a reference.
4552 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance field access on object that has "
4553 << "non-reference type " << obj_type;
4554 return nullptr;
4555 }
4556 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
4557 // Check access to class.
4558 const RegType& klass_type = ResolveClass<CheckAccess::kYes>(field_id.class_idx_);
4559 if (klass_type.IsConflict()) {
4560 AppendToLastFailMessage(StringPrintf(" in attempt to access instance field %d (%s) in %s",
4561 field_idx, dex_file_->GetFieldName(field_id),
4562 dex_file_->GetFieldDeclaringClassDescriptor(field_id)));
4563 return nullptr;
4564 }
4565 if (klass_type.IsUnresolvedTypes()) {
4566 // Accessibility checks depend on resolved fields.
4567 DCHECK(klass_type.Equals(GetDeclaringClass()) ||
4568 !failures_.empty() ||
4569 IsSdkVersionSetAndLessThan(api_level_, SdkVersion::kP));
4570
4571 return nullptr; // Can't resolve Class so no more to do here
4572 }
4573 ClassLinker* class_linker = GetClassLinker();
4574 ArtField* field = class_linker->ResolveFieldJLS(field_idx, dex_cache_, class_loader_);
4575
4576 if (field == nullptr) {
4577 VLOG(verifier) << "Unable to resolve instance field " << field_idx << " ("
4578 << dex_file_->GetFieldName(field_id) << ") in "
4579 << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
4580 DCHECK(self_->IsExceptionPending());
4581 self_->ClearException();
4582 return nullptr;
4583 } else if (obj_type.IsZeroOrNull()) {
4584 // Cannot infer and check type, however, access will cause null pointer exception.
4585 // Fall through into a few last soft failure checks below.
4586 } else {
4587 std::string temp;
4588 ObjPtr<mirror::Class> klass = field->GetDeclaringClass();
4589 const RegType& field_klass =
4590 FromClass(klass->GetDescriptor(&temp), klass, klass->CannotBeAssignedFromOtherTypes());
4591 if (obj_type.IsUninitializedTypes()) {
4592 // Field accesses through uninitialized references are only allowable for constructors where
4593 // the field is declared in this class.
4594 // Note: this IsConstructor check is technically redundant, as UninitializedThis should only
4595 // appear in constructors.
4596 if (!obj_type.IsUninitializedThisReference() ||
4597 !IsConstructor() ||
4598 !field_klass.Equals(GetDeclaringClass())) {
4599 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access instance field " << field->PrettyField()
4600 << " of a not fully initialized object within the context"
4601 << " of " << dex_file_->PrettyMethod(dex_method_idx_);
4602 return nullptr;
4603 }
4604 } else if (!field_klass.IsAssignableFrom(obj_type, this)) {
4605 // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class
4606 // of C1. For resolution to occur the declared class of the field must be compatible with
4607 // obj_type, we've discovered this wasn't so, so report the field didn't exist.
4608 VerifyError type;
4609 bool is_aot = IsAotMode();
4610 if (is_aot && (field_klass.IsUnresolvedTypes() || obj_type.IsUnresolvedTypes())) {
4611 // Compiler & unresolved types involved, retry at runtime.
4612 type = VerifyError::VERIFY_ERROR_UNRESOLVED_TYPE_CHECK;
4613 } else {
4614 // Classes known (resolved; and thus assignability check is precise), or we are at runtime
4615 // and still missing classes. This is a hard failure.
4616 type = VerifyError::VERIFY_ERROR_BAD_CLASS_HARD;
4617 }
4618 Fail(type) << "cannot access instance field " << field->PrettyField()
4619 << " from object of type " << obj_type;
4620 return nullptr;
4621 }
4622 }
4623
4624 // Few last soft failure checks.
4625 if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(),
4626 field->GetAccessFlags())) {
4627 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << field->PrettyField()
4628 << " from " << GetDeclaringClass();
4629 return nullptr;
4630 } else if (field->IsStatic()) {
4631 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << field->PrettyField()
4632 << " to not be static";
4633 return nullptr;
4634 }
4635
4636 return field;
4637 }
4638
4639 template <bool kVerifierDebug>
4640 template <FieldAccessType kAccType>
VerifyISFieldAccess(const Instruction * inst,const RegType & insn_type,bool is_primitive,bool is_static)4641 void MethodVerifier<kVerifierDebug>::VerifyISFieldAccess(const Instruction* inst,
4642 const RegType& insn_type,
4643 bool is_primitive,
4644 bool is_static) {
4645 uint32_t field_idx = GetFieldIdxOfFieldAccess(inst, is_static);
4646 ArtField* field;
4647 if (is_static) {
4648 field = GetStaticField(field_idx);
4649 } else {
4650 const RegType& object_type = work_line_->GetRegisterType(this, inst->VRegB_22c());
4651
4652 // One is not allowed to access fields on uninitialized references, except to write to
4653 // fields in the constructor (before calling another constructor).
4654 // GetInstanceField does an assignability check which will fail for uninitialized types.
4655 // We thus modify the type if the uninitialized reference is a "this" reference (this also
4656 // checks at the same time that we're verifying a constructor).
4657 bool should_adjust = (kAccType == FieldAccessType::kAccPut) &&
4658 (object_type.IsUninitializedThisReference() ||
4659 object_type.IsUnresolvedAndUninitializedThisReference());
4660 const RegType& adjusted_type = should_adjust
4661 ? GetRegTypeCache()->FromUninitialized(object_type)
4662 : object_type;
4663 field = GetInstanceField(adjusted_type, field_idx);
4664 if (UNLIKELY(flags_.have_pending_hard_failure_)) {
4665 return;
4666 }
4667 if (should_adjust) {
4668 bool illegal_field_access = false;
4669 if (field == nullptr) {
4670 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
4671 if (field_id.class_idx_ != GetClassDef().class_idx_) {
4672 illegal_field_access = true;
4673 } else {
4674 ClassAccessor accessor(*dex_file_, GetClassDef());
4675 illegal_field_access = (accessor.GetInstanceFields().end() ==
4676 std::find_if(accessor.GetInstanceFields().begin(),
4677 accessor.GetInstanceFields().end(),
4678 [field_idx] (const ClassAccessor::Field& f) {
4679 return f.GetIndex() == field_idx;
4680 }));
4681 }
4682 } else if (field->GetDeclaringClass() != GetDeclaringClass().GetClass()) {
4683 illegal_field_access = true;
4684 }
4685 if (illegal_field_access) {
4686 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access instance field "
4687 << dex_file_->PrettyField(field_idx)
4688 << " of a not fully initialized "
4689 << "object within the context of "
4690 << dex_file_->PrettyMethod(dex_method_idx_);
4691 return;
4692 }
4693 }
4694 }
4695 const RegType* field_type = nullptr;
4696 if (field != nullptr) {
4697 if (kAccType == FieldAccessType::kAccPut) {
4698 if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) {
4699 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << field->PrettyField()
4700 << " from other class " << GetDeclaringClass();
4701 // Keep hunting for possible hard fails.
4702 }
4703 }
4704
4705 ObjPtr<mirror::Class> field_type_class =
4706 CanLoadClasses() ? field->ResolveType() : field->LookupResolvedType();
4707 if (field_type_class != nullptr) {
4708 field_type = &FromClass(field->GetTypeDescriptor(),
4709 field_type_class,
4710 field_type_class->CannotBeAssignedFromOtherTypes());
4711 } else {
4712 DCHECK_IMPLIES(CanLoadClasses(), self_->IsExceptionPending());
4713 self_->ClearException();
4714 }
4715 } else if (IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP)) {
4716 // If we don't have the field (it seems we failed resolution) and this is a PUT, we need to
4717 // redo verification at runtime as the field may be final, unless the field id shows it's in
4718 // the same class.
4719 //
4720 // For simplicity, it is OK to not distinguish compile-time vs runtime, and post this an
4721 // ACCESS_FIELD failure at runtime. This has the same effect as NO_FIELD - punting the class
4722 // to the access-checks interpreter.
4723 //
4724 // Note: see b/34966607. This and above may be changed in the future.
4725 if (kAccType == FieldAccessType::kAccPut) {
4726 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
4727 const char* field_class_descriptor = dex_file_->GetFieldDeclaringClassDescriptor(field_id);
4728 const RegType* field_class_type =
4729 ®_types_.FromDescriptor(class_loader_, field_class_descriptor);
4730 if (!field_class_type->Equals(GetDeclaringClass())) {
4731 Fail(VERIFY_ERROR_ACCESS_FIELD) << "could not check field put for final field modify of "
4732 << field_class_descriptor
4733 << "."
4734 << dex_file_->GetFieldName(field_id)
4735 << " from other class "
4736 << GetDeclaringClass();
4737 }
4738 }
4739 }
4740 if (field_type == nullptr) {
4741 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
4742 const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id);
4743 field_type = ®_types_.FromDescriptor(class_loader_, descriptor);
4744 }
4745 DCHECK(field_type != nullptr);
4746 const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c();
4747 static_assert(kAccType == FieldAccessType::kAccPut || kAccType == FieldAccessType::kAccGet,
4748 "Unexpected third access type");
4749 if (kAccType == FieldAccessType::kAccPut) {
4750 // sput or iput.
4751 if (is_primitive) {
4752 VerifyPrimitivePut(*field_type, insn_type, vregA);
4753 } else {
4754 DCHECK(insn_type.IsJavaLangObject());
4755 if (!insn_type.IsAssignableFrom(*field_type, this)) {
4756 DCHECK(!field_type->IsReferenceTypes());
4757 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << ArtField::PrettyField(field)
4758 << " to be compatible with type '" << insn_type
4759 << "' but found type '" << *field_type
4760 << "' in put-object";
4761 return;
4762 }
4763 work_line_->VerifyRegisterType(this, vregA, *field_type);
4764 }
4765 } else if (kAccType == FieldAccessType::kAccGet) {
4766 // sget or iget.
4767 if (is_primitive) {
4768 if (field_type->Equals(insn_type) ||
4769 (field_type->IsFloat() && insn_type.IsInteger()) ||
4770 (field_type->IsDouble() && insn_type.IsLong())) {
4771 // expected that read is of the correct primitive type or that int reads are reading
4772 // floats or long reads are reading doubles
4773 } else {
4774 // This is a global failure rather than a class change failure as the instructions and
4775 // the descriptors for the type should have been consistent within the same file at
4776 // compile time
4777 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << ArtField::PrettyField(field)
4778 << " to be of type '" << insn_type
4779 << "' but found type '" << *field_type << "' in get";
4780 return;
4781 }
4782 } else {
4783 DCHECK(insn_type.IsJavaLangObject());
4784 if (!insn_type.IsAssignableFrom(*field_type, this)) {
4785 DCHECK(!field_type->IsReferenceTypes());
4786 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << ArtField::PrettyField(field)
4787 << " to be compatible with type '" << insn_type
4788 << "' but found type '" << *field_type
4789 << "' in get-object";
4790 return;
4791 }
4792 }
4793 if (!field_type->IsLowHalf()) {
4794 work_line_->SetRegisterType<LockOp::kClear>(vregA, *field_type);
4795 } else {
4796 work_line_->SetRegisterTypeWide(vregA, *field_type, field_type->HighHalf(®_types_));
4797 }
4798 } else {
4799 LOG(FATAL) << "Unexpected case.";
4800 }
4801 }
4802
4803 template <bool kVerifierDebug>
UpdateRegisters(uint32_t next_insn,RegisterLine * merge_line,bool update_merge_line)4804 bool MethodVerifier<kVerifierDebug>::UpdateRegisters(uint32_t next_insn,
4805 RegisterLine* merge_line,
4806 bool update_merge_line) {
4807 bool changed = true;
4808 RegisterLine* target_line = reg_table_.GetLine(next_insn);
4809 if (!GetInstructionFlags(next_insn).IsVisitedOrChanged()) {
4810 /*
4811 * We haven't processed this instruction before, and we haven't touched the registers here, so
4812 * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the
4813 * only way a register can transition out of "unknown", so this is not just an optimization.)
4814 */
4815 target_line->CopyFromLine(merge_line);
4816 if (GetInstructionFlags(next_insn).IsReturn()) {
4817 // Verify that the monitor stack is empty on return.
4818 merge_line->VerifyMonitorStackEmpty(this);
4819
4820 // For returns we only care about the operand to the return, all other registers are dead.
4821 // Initialize them as conflicts so they don't add to GC and deoptimization information.
4822 const Instruction* ret_inst = &code_item_accessor_.InstructionAt(next_insn);
4823 AdjustReturnLine(this, ret_inst, target_line);
4824 // Directly bail if a hard failure was found.
4825 if (flags_.have_pending_hard_failure_) {
4826 return false;
4827 }
4828 }
4829 } else {
4830 RegisterLineArenaUniquePtr copy;
4831 if (kVerifierDebug) {
4832 copy.reset(RegisterLine::Create(target_line->NumRegs(), allocator_, GetRegTypeCache()));
4833 copy->CopyFromLine(target_line);
4834 }
4835 changed = target_line->MergeRegisters(this, merge_line);
4836 if (flags_.have_pending_hard_failure_) {
4837 return false;
4838 }
4839 if (kVerifierDebug && changed) {
4840 LogVerifyInfo() << "Merging at [" << reinterpret_cast<void*>(work_insn_idx_) << "]"
4841 << " to [" << reinterpret_cast<void*>(next_insn) << "]: " << "\n"
4842 << copy->Dump(this) << " MERGE\n"
4843 << merge_line->Dump(this) << " ==\n"
4844 << target_line->Dump(this);
4845 }
4846 if (update_merge_line && changed) {
4847 merge_line->CopyFromLine(target_line);
4848 }
4849 }
4850 if (changed) {
4851 GetModifiableInstructionFlags(next_insn).SetChanged();
4852 }
4853 return true;
4854 }
4855
4856 template <bool kVerifierDebug>
GetMethodReturnType()4857 const RegType& MethodVerifier<kVerifierDebug>::GetMethodReturnType() {
4858 if (return_type_ == nullptr) {
4859 const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
4860 const dex::ProtoId& proto_id = dex_file_->GetMethodPrototype(method_id);
4861 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
4862 const char* descriptor = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(return_type_idx));
4863 return_type_ = ®_types_.FromDescriptor(class_loader_, descriptor);
4864 }
4865 return *return_type_;
4866 }
4867
4868 template <bool kVerifierDebug>
DetermineCat1Constant(int32_t value)4869 const RegType& MethodVerifier<kVerifierDebug>::DetermineCat1Constant(int32_t value) {
4870 // Imprecise constant type.
4871 if (value < -32768) {
4872 return reg_types_.IntConstant();
4873 } else if (value < -128) {
4874 return reg_types_.ShortConstant();
4875 } else if (value < 0) {
4876 return reg_types_.ByteConstant();
4877 } else if (value == 0) {
4878 return reg_types_.Zero();
4879 } else if (value == 1) {
4880 return reg_types_.One();
4881 } else if (value < 128) {
4882 return reg_types_.PosByteConstant();
4883 } else if (value < 32768) {
4884 return reg_types_.PosShortConstant();
4885 } else if (value < 65536) {
4886 return reg_types_.CharConstant();
4887 } else {
4888 return reg_types_.IntConstant();
4889 }
4890 }
4891
4892 template <bool kVerifierDebug>
PotentiallyMarkRuntimeThrow()4893 bool MethodVerifier<kVerifierDebug>::PotentiallyMarkRuntimeThrow() {
4894 if (IsAotMode() || IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kS_V2)) {
4895 return false;
4896 }
4897 // Compatibility mode: we treat the following code unreachable and the verifier
4898 // will not analyze it.
4899 // The verifier may fail before we touch any instruction, for the signature of a method. So
4900 // add a check.
4901 if (work_insn_idx_ < dex::kDexNoIndex) {
4902 const Instruction& inst = code_item_accessor_.InstructionAt(work_insn_idx_);
4903 Instruction::Code opcode = inst.Opcode();
4904 if (opcode == Instruction::MOVE_EXCEPTION) {
4905 // This is an unreachable handler. The instruction doesn't throw, but we
4906 // mark the method as having a pending runtime throw failure so that
4907 // the compiler does not try to compile it.
4908 Fail(VERIFY_ERROR_RUNTIME_THROW, /* pending_exc= */ false);
4909 return true;
4910 }
4911 // How to handle runtime failures for instructions that are not flagged kThrow.
4912 if ((Instruction::FlagsOf(opcode) & Instruction::kThrow) == 0 &&
4913 !impl::IsCompatThrow(opcode) &&
4914 GetInstructionFlags(work_insn_idx_).IsInTry()) {
4915 if (Runtime::Current()->IsVerifierMissingKThrowFatal()) {
4916 LOG(FATAL) << "Unexpected throw: " << std::hex << work_insn_idx_ << " " << opcode;
4917 UNREACHABLE();
4918 }
4919 // We need to save the work_line if the instruction wasn't throwing before. Otherwise
4920 // we'll try to merge garbage.
4921 // Note: this assumes that Fail is called before we do any work_line modifications.
4922 saved_line_->CopyFromLine(work_line_.get());
4923 }
4924 }
4925 flags_.have_pending_runtime_throw_failure_ = true;
4926 return true;
4927 }
4928
4929 } // namespace
4930 } // namespace impl
4931
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)4932 MethodVerifier::MethodVerifier(Thread* self,
4933 ClassLinker* class_linker,
4934 ArenaPool* arena_pool,
4935 VerifierDeps* verifier_deps,
4936 const DexFile* dex_file,
4937 const dex::ClassDef& class_def,
4938 const dex::CodeItem* code_item,
4939 uint32_t dex_method_idx,
4940 bool can_load_classes,
4941 bool allow_thread_suspension,
4942 bool aot_mode)
4943 : self_(self),
4944 arena_stack_(arena_pool),
4945 allocator_(&arena_stack_),
4946 reg_types_(self, class_linker, can_load_classes, allocator_, allow_thread_suspension),
4947 reg_table_(allocator_),
4948 work_insn_idx_(dex::kDexNoIndex),
4949 dex_method_idx_(dex_method_idx),
4950 dex_file_(dex_file),
4951 class_def_(class_def),
4952 code_item_accessor_(*dex_file, code_item),
4953 // TODO: make it designated initialization when we compile as C++20.
4954 flags_({false, false}),
4955 const_flags_({aot_mode, can_load_classes}),
4956 encountered_failure_types_(0),
4957 verifier_deps_(verifier_deps),
4958 link_(nullptr) {
4959 }
4960
~MethodVerifier()4961 MethodVerifier::~MethodVerifier() {
4962 STLDeleteElements(&failure_messages_);
4963 }
4964
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)4965 MethodVerifier::FailureData MethodVerifier::VerifyMethod(Thread* self,
4966 ClassLinker* class_linker,
4967 ArenaPool* arena_pool,
4968 VerifierDeps* verifier_deps,
4969 uint32_t method_idx,
4970 const DexFile* dex_file,
4971 Handle<mirror::DexCache> dex_cache,
4972 Handle<mirror::ClassLoader> class_loader,
4973 const dex::ClassDef& class_def,
4974 const dex::CodeItem* code_item,
4975 uint32_t method_access_flags,
4976 HardFailLogMode log_level,
4977 uint32_t api_level,
4978 bool aot_mode,
4979 std::string* hard_failure_msg) {
4980 if (VLOG_IS_ON(verifier_debug)) {
4981 return VerifyMethod<true>(self,
4982 class_linker,
4983 arena_pool,
4984 verifier_deps,
4985 method_idx,
4986 dex_file,
4987 dex_cache,
4988 class_loader,
4989 class_def,
4990 code_item,
4991 method_access_flags,
4992 log_level,
4993 api_level,
4994 aot_mode,
4995 hard_failure_msg);
4996 } else {
4997 return VerifyMethod<false>(self,
4998 class_linker,
4999 arena_pool,
5000 verifier_deps,
5001 method_idx,
5002 dex_file,
5003 dex_cache,
5004 class_loader,
5005 class_def,
5006 code_item,
5007 method_access_flags,
5008 log_level,
5009 api_level,
5010 aot_mode,
5011 hard_failure_msg);
5012 }
5013 }
5014
5015 // Return whether the runtime knows how to execute a method without needing to
5016 // re-verify it at runtime (and therefore save on first use of the class).
5017 // The AOT/JIT compiled code is not affected.
CanRuntimeHandleVerificationFailure(uint32_t encountered_failure_types)5018 static inline bool CanRuntimeHandleVerificationFailure(uint32_t encountered_failure_types) {
5019 constexpr uint32_t unresolved_mask =
5020 verifier::VerifyError::VERIFY_ERROR_UNRESOLVED_TYPE_CHECK |
5021 verifier::VerifyError::VERIFY_ERROR_NO_CLASS |
5022 verifier::VerifyError::VERIFY_ERROR_CLASS_CHANGE |
5023 verifier::VerifyError::VERIFY_ERROR_INSTANTIATION |
5024 verifier::VerifyError::VERIFY_ERROR_ACCESS_CLASS |
5025 verifier::VerifyError::VERIFY_ERROR_ACCESS_FIELD |
5026 verifier::VerifyError::VERIFY_ERROR_NO_METHOD |
5027 verifier::VerifyError::VERIFY_ERROR_ACCESS_METHOD |
5028 verifier::VerifyError::VERIFY_ERROR_RUNTIME_THROW;
5029 return (encountered_failure_types & (~unresolved_mask)) == 0;
5030 }
5031
5032 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)5033 MethodVerifier::FailureData MethodVerifier::VerifyMethod(Thread* self,
5034 ClassLinker* class_linker,
5035 ArenaPool* arena_pool,
5036 VerifierDeps* verifier_deps,
5037 uint32_t method_idx,
5038 const DexFile* dex_file,
5039 Handle<mirror::DexCache> dex_cache,
5040 Handle<mirror::ClassLoader> class_loader,
5041 const dex::ClassDef& class_def,
5042 const dex::CodeItem* code_item,
5043 uint32_t method_access_flags,
5044 HardFailLogMode log_level,
5045 uint32_t api_level,
5046 bool aot_mode,
5047 std::string* hard_failure_msg) {
5048 MethodVerifier::FailureData result;
5049 uint64_t start_ns = kTimeVerifyMethod ? NanoTime() : 0;
5050
5051 impl::MethodVerifier<kVerifierDebug> verifier(self,
5052 class_linker,
5053 arena_pool,
5054 verifier_deps,
5055 dex_file,
5056 code_item,
5057 method_idx,
5058 /* can_load_classes= */ true,
5059 /* allow_thread_suspension= */ true,
5060 aot_mode,
5061 dex_cache,
5062 class_loader,
5063 class_def,
5064 method_access_flags,
5065 /* verify to dump */ false,
5066 api_level);
5067 if (verifier.Verify()) {
5068 // Verification completed, however failures may be pending that didn't cause the verification
5069 // to hard fail.
5070 CHECK(!verifier.flags_.have_pending_hard_failure_);
5071
5072 if (verifier.failures_.size() != 0) {
5073 if (VLOG_IS_ON(verifier)) {
5074 verifier.DumpFailures(VLOG_STREAM(verifier) << "Soft verification failures in "
5075 << dex_file->PrettyMethod(method_idx) << "\n");
5076 }
5077 if (kVerifierDebug) {
5078 LOG(INFO) << verifier.info_messages_.str();
5079 verifier.Dump(LOG_STREAM(INFO));
5080 }
5081 if (CanRuntimeHandleVerificationFailure(verifier.encountered_failure_types_)) {
5082 if (verifier.encountered_failure_types_ & VERIFY_ERROR_UNRESOLVED_TYPE_CHECK) {
5083 result.kind = FailureKind::kTypeChecksFailure;
5084 } else {
5085 result.kind = FailureKind::kAccessChecksFailure;
5086 }
5087 } else {
5088 result.kind = FailureKind::kSoftFailure;
5089 }
5090 }
5091 } else {
5092 // Bad method data.
5093 CHECK_NE(verifier.failures_.size(), 0U);
5094 CHECK(verifier.flags_.have_pending_hard_failure_);
5095 if (VLOG_IS_ON(verifier)) {
5096 log_level = std::max(HardFailLogMode::kLogVerbose, log_level);
5097 }
5098 if (log_level >= HardFailLogMode::kLogVerbose) {
5099 LogSeverity severity;
5100 switch (log_level) {
5101 case HardFailLogMode::kLogVerbose:
5102 severity = LogSeverity::VERBOSE;
5103 break;
5104 case HardFailLogMode::kLogWarning:
5105 severity = LogSeverity::WARNING;
5106 break;
5107 case HardFailLogMode::kLogInternalFatal:
5108 severity = LogSeverity::FATAL_WITHOUT_ABORT;
5109 break;
5110 default:
5111 LOG(FATAL) << "Unsupported log-level " << static_cast<uint32_t>(log_level);
5112 UNREACHABLE();
5113 }
5114 verifier.DumpFailures(LOG_STREAM(severity) << "Verification error in "
5115 << dex_file->PrettyMethod(method_idx)
5116 << "\n");
5117 }
5118 if (hard_failure_msg != nullptr) {
5119 CHECK(!verifier.failure_messages_.empty());
5120 *hard_failure_msg =
5121 verifier.failure_messages_[verifier.failure_messages_.size() - 1]->str();
5122 }
5123 result.kind = FailureKind::kHardFailure;
5124
5125 if (kVerifierDebug || VLOG_IS_ON(verifier)) {
5126 LOG(ERROR) << verifier.info_messages_.str();
5127 verifier.Dump(LOG_STREAM(ERROR));
5128 }
5129 // Under verifier-debug, dump the complete log into the error message.
5130 if (kVerifierDebug && hard_failure_msg != nullptr) {
5131 hard_failure_msg->append("\n");
5132 hard_failure_msg->append(verifier.info_messages_.str());
5133 hard_failure_msg->append("\n");
5134 std::ostringstream oss;
5135 verifier.Dump(oss);
5136 hard_failure_msg->append(oss.str());
5137 }
5138 }
5139 if (kTimeVerifyMethod) {
5140 uint64_t duration_ns = NanoTime() - start_ns;
5141 if (duration_ns > MsToNs(Runtime::Current()->GetVerifierLoggingThresholdMs())) {
5142 double bytecodes_per_second =
5143 verifier.code_item_accessor_.InsnsSizeInCodeUnits() / (duration_ns * 1e-9);
5144 LOG(WARNING) << "Verification of " << dex_file->PrettyMethod(method_idx)
5145 << " took " << PrettyDuration(duration_ns)
5146 << (impl::IsLargeMethod(verifier.CodeItem()) ? " (large method)" : "")
5147 << " (" << StringPrintf("%.2f", bytecodes_per_second) << " bytecodes/s)"
5148 << " (" << verifier.allocator_.ApproximatePeakBytes()
5149 << "B approximate peak alloc)";
5150 }
5151 }
5152 result.types = verifier.encountered_failure_types_;
5153 return result;
5154 }
5155
CalculateVerificationInfo(Thread * self,ArtMethod * method,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,uint32_t dex_pc)5156 MethodVerifier* MethodVerifier::CalculateVerificationInfo(
5157 Thread* self,
5158 ArtMethod* method,
5159 Handle<mirror::DexCache> dex_cache,
5160 Handle<mirror::ClassLoader> class_loader,
5161 uint32_t dex_pc) {
5162 std::unique_ptr<impl::MethodVerifier<false>> verifier(
5163 new impl::MethodVerifier<false>(self,
5164 Runtime::Current()->GetClassLinker(),
5165 Runtime::Current()->GetArenaPool(),
5166 /* verifier_deps= */ nullptr,
5167 method->GetDexFile(),
5168 method->GetCodeItem(),
5169 method->GetDexMethodIndex(),
5170 /* can_load_classes= */ false,
5171 /* allow_thread_suspension= */ false,
5172 Runtime::Current()->IsAotCompiler(),
5173 dex_cache,
5174 class_loader,
5175 *method->GetDeclaringClass()->GetClassDef(),
5176 method->GetAccessFlags(),
5177 /* verify_to_dump= */ false,
5178 // Just use the verifier at the current skd-version.
5179 // This might affect what soft-verifier errors are reported.
5180 // Callers can then filter out relevant errors if needed.
5181 Runtime::Current()->GetTargetSdkVersion()));
5182 verifier->interesting_dex_pc_ = dex_pc;
5183 verifier->Verify();
5184 if (VLOG_IS_ON(verifier)) {
5185 verifier->DumpFailures(VLOG_STREAM(verifier));
5186 VLOG(verifier) << verifier->info_messages_.str();
5187 verifier->Dump(VLOG_STREAM(verifier));
5188 }
5189 if (verifier->flags_.have_pending_hard_failure_) {
5190 return nullptr;
5191 } else {
5192 return verifier.release();
5193 }
5194 }
5195
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)5196 MethodVerifier* MethodVerifier::VerifyMethodAndDump(Thread* self,
5197 VariableIndentationOutputStream* vios,
5198 uint32_t dex_method_idx,
5199 const DexFile* dex_file,
5200 Handle<mirror::DexCache> dex_cache,
5201 Handle<mirror::ClassLoader> class_loader,
5202 const dex::ClassDef& class_def,
5203 const dex::CodeItem* code_item,
5204 uint32_t method_access_flags,
5205 uint32_t api_level) {
5206 impl::MethodVerifier<false>* verifier = new impl::MethodVerifier<false>(
5207 self,
5208 Runtime::Current()->GetClassLinker(),
5209 Runtime::Current()->GetArenaPool(),
5210 /* verifier_deps= */ nullptr,
5211 dex_file,
5212 code_item,
5213 dex_method_idx,
5214 /* can_load_classes= */ true,
5215 /* allow_thread_suspension= */ true,
5216 Runtime::Current()->IsAotCompiler(),
5217 dex_cache,
5218 class_loader,
5219 class_def,
5220 method_access_flags,
5221 /* verify_to_dump= */ true,
5222 api_level);
5223 verifier->Verify();
5224 verifier->DumpFailures(vios->Stream());
5225 vios->Stream() << verifier->info_messages_.str();
5226 // Only dump and return if no hard failures. Otherwise the verifier may be not fully initialized
5227 // and querying any info is dangerous/can abort.
5228 if (verifier->flags_.have_pending_hard_failure_) {
5229 delete verifier;
5230 return nullptr;
5231 } else {
5232 verifier->Dump(vios);
5233 return verifier;
5234 }
5235 }
5236
FindLocksAtDexPc(ArtMethod * m,uint32_t dex_pc,std::vector<MethodVerifier::DexLockInfo> * monitor_enter_dex_pcs,uint32_t api_level)5237 void MethodVerifier::FindLocksAtDexPc(
5238 ArtMethod* m,
5239 uint32_t dex_pc,
5240 std::vector<MethodVerifier::DexLockInfo>* monitor_enter_dex_pcs,
5241 uint32_t api_level) {
5242 StackHandleScope<2> hs(Thread::Current());
5243 Handle<mirror::DexCache> dex_cache(hs.NewHandle(m->GetDexCache()));
5244 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(m->GetClassLoader()));
5245 impl::MethodVerifier<false> verifier(hs.Self(),
5246 Runtime::Current()->GetClassLinker(),
5247 Runtime::Current()->GetArenaPool(),
5248 /* verifier_deps= */ nullptr,
5249 m->GetDexFile(),
5250 m->GetCodeItem(),
5251 m->GetDexMethodIndex(),
5252 /* can_load_classes= */ false,
5253 /* allow_thread_suspension= */ false,
5254 Runtime::Current()->IsAotCompiler(),
5255 dex_cache,
5256 class_loader,
5257 m->GetClassDef(),
5258 m->GetAccessFlags(),
5259 /* verify_to_dump= */ false,
5260 api_level);
5261 verifier.interesting_dex_pc_ = dex_pc;
5262 verifier.monitor_enter_dex_pcs_ = monitor_enter_dex_pcs;
5263 verifier.FindLocksAtDexPc();
5264 }
5265
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)5266 MethodVerifier* MethodVerifier::CreateVerifier(Thread* self,
5267 VerifierDeps* verifier_deps,
5268 const DexFile* dex_file,
5269 Handle<mirror::DexCache> dex_cache,
5270 Handle<mirror::ClassLoader> class_loader,
5271 const dex::ClassDef& class_def,
5272 const dex::CodeItem* code_item,
5273 uint32_t method_idx,
5274 uint32_t access_flags,
5275 bool can_load_classes,
5276 bool verify_to_dump,
5277 bool allow_thread_suspension,
5278 uint32_t api_level) {
5279 return new impl::MethodVerifier<false>(self,
5280 Runtime::Current()->GetClassLinker(),
5281 Runtime::Current()->GetArenaPool(),
5282 verifier_deps,
5283 dex_file,
5284 code_item,
5285 method_idx,
5286 can_load_classes,
5287 allow_thread_suspension,
5288 Runtime::Current()->IsAotCompiler(),
5289 dex_cache,
5290 class_loader,
5291 class_def,
5292 access_flags,
5293 verify_to_dump,
5294 api_level);
5295 }
5296
Fail(VerifyError error,bool pending_exc)5297 std::ostream& MethodVerifier::Fail(VerifyError error, bool pending_exc) {
5298 // Mark the error type as encountered.
5299 encountered_failure_types_ |= static_cast<uint32_t>(error);
5300
5301 if (pending_exc) {
5302 switch (error) {
5303 case VERIFY_ERROR_NO_CLASS:
5304 case VERIFY_ERROR_UNRESOLVED_TYPE_CHECK:
5305 case VERIFY_ERROR_NO_METHOD:
5306 case VERIFY_ERROR_ACCESS_CLASS:
5307 case VERIFY_ERROR_ACCESS_FIELD:
5308 case VERIFY_ERROR_ACCESS_METHOD:
5309 case VERIFY_ERROR_INSTANTIATION:
5310 case VERIFY_ERROR_CLASS_CHANGE: {
5311 PotentiallyMarkRuntimeThrow();
5312 break;
5313 }
5314
5315 case VERIFY_ERROR_LOCKING:
5316 PotentiallyMarkRuntimeThrow();
5317 // This will be reported to the runtime as a soft failure.
5318 break;
5319
5320 // Hard verification failures at compile time will still fail at runtime, so the class is
5321 // marked as rejected to prevent it from being compiled.
5322 case VERIFY_ERROR_BAD_CLASS_HARD: {
5323 flags_.have_pending_hard_failure_ = true;
5324 break;
5325 }
5326
5327 case VERIFY_ERROR_RUNTIME_THROW: {
5328 LOG(FATAL) << "UNREACHABLE";
5329 }
5330 }
5331 } else if (kIsDebugBuild) {
5332 CHECK_NE(error, VERIFY_ERROR_BAD_CLASS_HARD);
5333 }
5334
5335 failures_.push_back(error);
5336 std::string location(StringPrintf("%s: [0x%X] ", dex_file_->PrettyMethod(dex_method_idx_).c_str(),
5337 work_insn_idx_));
5338 std::ostringstream* failure_message = new std::ostringstream(location, std::ostringstream::ate);
5339 failure_messages_.push_back(failure_message);
5340 return *failure_message;
5341 }
5342
LogVerifyInfo()5343 ScopedNewLine MethodVerifier::LogVerifyInfo() {
5344 ScopedNewLine ret{info_messages_};
5345 ret << "VFY: " << dex_file_->PrettyMethod(dex_method_idx_)
5346 << '[' << reinterpret_cast<void*>(work_insn_idx_) << "] : ";
5347 return ret;
5348 }
5349
FailureKindMax(FailureKind fk1,FailureKind fk2)5350 static FailureKind FailureKindMax(FailureKind fk1, FailureKind fk2) {
5351 static_assert(FailureKind::kNoFailure < FailureKind::kSoftFailure
5352 && FailureKind::kSoftFailure < FailureKind::kHardFailure,
5353 "Unexpected FailureKind order");
5354 return std::max(fk1, fk2);
5355 }
5356
Merge(const MethodVerifier::FailureData & fd)5357 void MethodVerifier::FailureData::Merge(const MethodVerifier::FailureData& fd) {
5358 kind = FailureKindMax(kind, fd.kind);
5359 types |= fd.types;
5360 }
5361
5362 } // namespace verifier
5363 } // namespace art
5364