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