blob: ff448283e28e7bea57f55816b4be34c96b78f900 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Mathieu Chartierc645f1d2014-03-06 18:11:53 -080017#include "method_verifier-inl.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Andreas Gampe4a57d5f2019-04-03 12:31:18 -070019#include <ostream>
Elliott Hughes1f359b02011-07-17 14:27:17 -070020
Andreas Gampe46ee31b2016-12-14 10:11:49 -080021#include "android-base/stringprintf.h"
22
Mathieu Chartierc7853442015-03-27 14:35:38 -070023#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070024#include "art_method-inl.h"
Andreas Gampe39b378c2017-12-07 15:44:13 -080025#include "base/aborting.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.h"
David Sehr67bf42e2018-02-26 16:43:04 -080027#include "base/leb128.h"
David Sehr9c4a0152018-04-05 12:23:54 -070028#include "base/indenter.h"
Andreas Gampe57943812017-12-06 21:39:13 -080029#include "base/logging.h" // For VLOG.
Ian Rogers637c65b2013-05-31 11:46:00 -070030#include "base/mutex-inl.h"
David Brazdil2bb2fbd2018-11-13 18:24:26 +000031#include "base/sdk_version.h"
Vladimir Marko637ee0b2015-09-04 12:47:41 +010032#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080033#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010034#include "base/time_utils.h"
David Sehrc431b9d2018-03-02 12:01:51 -080035#include "base/utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070036#include "class_linker.h"
Vladimir Markoc7aa87e2018-05-24 15:19:52 +010037#include "class_root.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000038#include "compiler_callbacks.h"
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -070039#include "dex/class_accessor-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080040#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080041#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"
Alex Lighteb7c1442015-08-31 13:17:42 -070045#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070046#include "gc/accounting/card_table-inl.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070047#include "handle_scope-inl.h"
Ian Rogers84fa0742011-10-25 18:13:30 -070048#include "intern_table.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080049#include "mirror/class-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070050#include "mirror/class.h"
Andreas Gampe51de69e2019-04-19 15:14:14 -070051#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070052#include "mirror/dex_cache-inl.h"
Orion Hodsoncfa325e2016-10-13 10:25:54 +010053#include "mirror/method_handle_impl.h"
Orion Hodson2e599942017-09-22 16:17:41 +010054#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/object-inl.h"
56#include "mirror/object_array-inl.h"
Orion Hodsonfe92d122018-01-02 10:45:17 +000057#include "mirror/var_handle.h"
Andreas Gampe51de69e2019-04-19 15:14:14 -070058#include "obj_ptr-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070059#include "reg_type-inl.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070060#include "register_line-inl.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070061#include "runtime.h"
Andreas Gampe2ad6cce2019-04-11 16:17:39 -070062#include "scoped_newline.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070063#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070064#include "stack.h"
Nicolas Geoffrayb041a402017-11-13 15:16:22 +000065#include "vdex_file.h"
Alex Lighte48fd0b2019-05-20 10:04:44 -070066#include "verifier/method_verifier.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070067#include "verifier_compiler_binding.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070068#include "verifier_deps.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070069
70namespace art {
Ian Rogersd81871c2011-10-03 13:57:23 -070071namespace verifier {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070072
Andreas Gampe46ee31b2016-12-14 10:11:49 -080073using android::base::StringPrintf;
74
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070075static constexpr bool kTimeVerifyMethod = !kIsDebugBuild;
Ian Rogers2c8a8572011-10-24 17:11:36 -070076
Vladimir Marko69d310e2017-10-09 14:12:23 +010077PcToRegisterLineTable::PcToRegisterLineTable(ScopedArenaAllocator& allocator)
78 : register_lines_(allocator.Adapter(kArenaAllocVerifier)) {}
Mathieu Chartierde40d472015-10-15 17:47:48 -070079
Andreas Gamped09c0592019-04-19 15:44:05 -070080void PcToRegisterLineTable::Init(RegisterTrackingMode mode,
81 InstructionFlags* flags,
82 uint32_t insns_size,
83 uint16_t registers_size,
84 ScopedArenaAllocator& allocator,
85 RegTypeCache* reg_types) {
Ian Rogersd81871c2011-10-03 13:57:23 -070086 DCHECK_GT(insns_size, 0U);
Mathieu Chartierde40d472015-10-15 17:47:48 -070087 register_lines_.resize(insns_size);
Ian Rogersd81871c2011-10-03 13:57:23 -070088 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;
Sameer Abu Asal02c42232013-04-30 12:09:45 -070094 case kTrackCompilerInterestPoints:
Brian Carlstrom02c8cc62013-07-18 15:54:44 -070095 interesting = flags[i].IsCompileTimeInfoPoint() || flags[i].IsBranchTarget();
Ian Rogersd81871c2011-10-03 13:57:23 -070096 break;
97 case kTrackRegsBranches:
98 interesting = flags[i].IsBranchTarget();
99 break;
100 default:
101 break;
102 }
103 if (interesting) {
Andreas Gamped09c0592019-04-19 15:44:05 -0700104 register_lines_[i].reset(RegisterLine::Create(registers_size, allocator, reg_types));
Ian Rogersd0fbd852013-09-24 18:17:04 -0700105 }
106 }
107}
108
Mathieu Chartierde40d472015-10-15 17:47:48 -0700109PcToRegisterLineTable::~PcToRegisterLineTable() {}
Ian Rogersd81871c2011-10-03 13:57:23 -0700110
Andreas Gampefc25ae92019-04-19 22:22:57 -0700111namespace impl {
112namespace {
113
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700114enum class CheckAccess {
115 kYes,
116 kNo,
117};
118
119enum class FieldAccessType {
120 kAccGet,
121 kAccPut
122};
123
124template <bool kVerifierDebug>
Andreas Gampefc25ae92019-04-19 22:22:57 -0700125class MethodVerifier final : public ::art::verifier::MethodVerifier {
126 public:
127 bool IsInstanceConstructor() const {
128 return IsConstructor() && !IsStatic();
129 }
130
131 const RegType& ResolveCheckedClass(dex::TypeIndex class_idx) override
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700132 REQUIRES_SHARED(Locks::mutator_lock_) {
133 DCHECK(!HasFailures());
134 const RegType& result = ResolveClass<CheckAccess::kYes>(class_idx);
135 DCHECK(!HasFailures());
136 return result;
137 }
Andreas Gampefc25ae92019-04-19 22:22:57 -0700138
139 void FindLocksAtDexPc() REQUIRES_SHARED(Locks::mutator_lock_);
140
141 private:
142 MethodVerifier(Thread* self,
143 const DexFile* dex_file,
144 Handle<mirror::DexCache> dex_cache,
145 Handle<mirror::ClassLoader> class_loader,
146 const dex::ClassDef& class_def,
147 const dex::CodeItem* code_item,
148 uint32_t method_idx,
149 ArtMethod* method,
150 uint32_t access_flags,
151 bool can_load_classes,
152 bool allow_soft_failures,
153 bool need_precise_constants,
154 bool verify_to_dump,
155 bool allow_thread_suspension,
Alex Lighte48fd0b2019-05-20 10:04:44 -0700156 bool fill_register_lines_,
Andreas Gampefc25ae92019-04-19 22:22:57 -0700157 uint32_t api_level)
158 REQUIRES_SHARED(Locks::mutator_lock_);
159
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700160 void UninstantiableError(const char* descriptor) {
161 Fail(VerifyError::VERIFY_ERROR_NO_CLASS) << "Could not create precise reference for "
162 << "non-instantiable klass " << descriptor;
163 }
Andreas Gampefc25ae92019-04-19 22:22:57 -0700164 static bool IsInstantiableOrPrimitive(ObjPtr<mirror::Class> klass)
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700165 REQUIRES_SHARED(Locks::mutator_lock_) {
166 return klass->IsInstantiable() || klass->IsPrimitive();
167 }
Andreas Gampefc25ae92019-04-19 22:22:57 -0700168
169 // Is the method being verified a constructor? See the comment on the field.
170 bool IsConstructor() const {
171 return is_constructor_;
172 }
173
174 // Is the method verified static?
175 bool IsStatic() const {
176 return (method_access_flags_ & kAccStatic) != 0;
177 }
178
179 // Adds the given string to the beginning of the last failure message.
180 void PrependToLastFailMessage(std::string);
181
182 // Adds the given string to the end of the last failure message.
183 void AppendToLastFailMessage(const std::string& append);
184
Andreas Gampefc25ae92019-04-19 22:22:57 -0700185 /*
186 * Compute the width of the instruction at each address in the instruction stream, and store it in
187 * insn_flags_. Addresses that are in the middle of an instruction, or that are part of switch
188 * table data, are not touched (so the caller should probably initialize "insn_flags" to zero).
189 *
190 * The "new_instance_count_" and "monitor_enter_count_" fields in vdata are also set.
191 *
192 * Performs some static checks, notably:
193 * - opcode of first instruction begins at index 0
194 * - only documented instructions may appear
195 * - each instruction follows the last
196 * - last byte of last instruction is at (code_length-1)
197 *
198 * Logs an error and returns "false" on failure.
199 */
200 bool ComputeWidthsAndCountOps();
201
202 /*
203 * Set the "in try" flags for all instructions protected by "try" statements. Also sets the
204 * "branch target" flags for exception handlers.
205 *
206 * Call this after widths have been set in "insn_flags".
207 *
208 * Returns "false" if something in the exception table looks fishy, but we're expecting the
209 * exception table to be somewhat sane.
210 */
211 bool ScanTryCatchBlocks() REQUIRES_SHARED(Locks::mutator_lock_);
212
213 /*
214 * Perform static verification on all instructions in a method.
215 *
216 * Walks through instructions in a method calling VerifyInstruction on each.
217 */
218 template <bool kAllowRuntimeOnlyInstructions>
219 bool VerifyInstructions();
220
221 /*
222 * Perform static verification on an instruction.
223 *
224 * As a side effect, this sets the "branch target" flags in InsnFlags.
225 *
226 * "(CF)" items are handled during code-flow analysis.
227 *
228 * v3 4.10.1
229 * - target of each jump and branch instruction must be valid
230 * - targets of switch statements must be valid
231 * - operands referencing constant pool entries must be valid
232 * - (CF) operands of getfield, putfield, getstatic, putstatic must be valid
233 * - (CF) operands of method invocation instructions must be valid
234 * - (CF) only invoke-direct can call a method starting with '<'
235 * - (CF) <clinit> must never be called explicitly
236 * - operands of instanceof, checkcast, new (and variants) must be valid
237 * - new-array[-type] limited to 255 dimensions
238 * - can't use "new" on an array class
239 * - (?) limit dimensions in multi-array creation
240 * - local variable load/store register values must be in valid range
241 *
242 * v3 4.11.1.2
243 * - branches must be within the bounds of the code array
244 * - targets of all control-flow instructions are the start of an instruction
245 * - register accesses fall within range of allocated registers
246 * - (N/A) access to constant pool must be of appropriate type
247 * - code does not end in the middle of an instruction
248 * - execution cannot fall off the end of the code
249 * - (earlier) for each exception handler, the "try" area must begin and
250 * end at the start of an instruction (end can be at the end of the code)
251 * - (earlier) for each exception handler, the handler must start at a valid
252 * instruction
253 */
254 template <bool kAllowRuntimeOnlyInstructions>
255 bool VerifyInstruction(const Instruction* inst, uint32_t code_offset);
256
257 /* Ensure that the register index is valid for this code item. */
258 bool CheckRegisterIndex(uint32_t idx);
259
260 /* Ensure that the wide register index is valid for this code item. */
261 bool CheckWideRegisterIndex(uint32_t idx);
262
263 // Perform static checks on an instruction referencing a CallSite. All we do here is ensure that
264 // the call site index is in the valid range.
265 bool CheckCallSiteIndex(uint32_t idx);
266
267 // Perform static checks on a field Get or set instruction. All we do here is ensure that the
268 // field index is in the valid range.
269 bool CheckFieldIndex(uint32_t idx);
270
271 // Perform static checks on a method invocation instruction. All we do here is ensure that the
272 // method index is in the valid range.
273 bool CheckMethodIndex(uint32_t idx);
274
275 // Perform static checks on an instruction referencing a constant method handle. All we do here
276 // is ensure that the method index is in the valid range.
277 bool CheckMethodHandleIndex(uint32_t idx);
278
279 // Perform static checks on a "new-instance" instruction. Specifically, make sure the class
280 // reference isn't for an array class.
281 bool CheckNewInstance(dex::TypeIndex idx);
282
283 // Perform static checks on a prototype indexing instruction. All we do here is ensure that the
284 // prototype index is in the valid range.
285 bool CheckPrototypeIndex(uint32_t idx);
286
287 /* Ensure that the string index is in the valid range. */
288 bool CheckStringIndex(uint32_t idx);
289
290 // Perform static checks on an instruction that takes a class constant. Ensure that the class
291 // index is in the valid range.
292 bool CheckTypeIndex(dex::TypeIndex idx);
293
294 // Perform static checks on a "new-array" instruction. Specifically, make sure they aren't
295 // creating an array of arrays that causes the number of dimensions to exceed 255.
296 bool CheckNewArray(dex::TypeIndex idx);
297
298 // Verify an array data table. "cur_offset" is the offset of the fill-array-data instruction.
299 bool CheckArrayData(uint32_t cur_offset);
300
301 // Verify that the target of a branch instruction is valid. We don't expect code to jump directly
302 // into an exception handler, but it's valid to do so as long as the target isn't a
303 // "move-exception" instruction. We verify that in a later stage.
304 // The dex format forbids certain instructions from branching to themselves.
305 // Updates "insn_flags_", setting the "branch target" flag.
306 bool CheckBranchTarget(uint32_t cur_offset);
307
308 // Verify a switch table. "cur_offset" is the offset of the switch instruction.
309 // Updates "insn_flags_", setting the "branch target" flag.
310 bool CheckSwitchTargets(uint32_t cur_offset);
311
312 // Check the register indices used in a "vararg" instruction, such as invoke-virtual or
313 // filled-new-array.
314 // - vA holds word count (0-5), args[] have values.
315 // There are some tests we don't do here, e.g. we don't try to verify that invoking a method that
316 // takes a double is done with consecutive registers. This requires parsing the target method
317 // signature, which we will be doing later on during the code flow analysis.
318 bool CheckVarArgRegs(uint32_t vA, uint32_t arg[]);
319
320 // Check the register indices used in a "vararg/range" instruction, such as invoke-virtual/range
321 // or filled-new-array/range.
322 // - vA holds word count, vC holds index of first reg.
323 bool CheckVarArgRangeRegs(uint32_t vA, uint32_t vC);
324
325 // Checks the method matches the expectations required to be signature polymorphic.
326 bool CheckSignaturePolymorphicMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_);
327
328 // Checks the invoked receiver matches the expectations for signature polymorphic methods.
329 bool CheckSignaturePolymorphicReceiver(const Instruction* inst) REQUIRES_SHARED(Locks::mutator_lock_);
330
331 // Extract the relative offset from a branch instruction.
332 // Returns "false" on failure (e.g. this isn't a branch instruction).
333 bool GetBranchOffset(uint32_t cur_offset, int32_t* pOffset, bool* pConditional,
334 bool* selfOkay);
335
336 /* Perform detailed code-flow analysis on a single method. */
337 bool VerifyCodeFlow() REQUIRES_SHARED(Locks::mutator_lock_);
338
339 // Set the register types for the first instruction in the method based on the method signature.
340 // This has the side-effect of validating the signature.
341 bool SetTypesFromSignature() REQUIRES_SHARED(Locks::mutator_lock_);
342
343 /*
344 * Perform code flow on a method.
345 *
346 * The basic strategy is as outlined in v3 4.11.1.2: set the "changed" bit on the first
347 * instruction, process it (setting additional "changed" bits), and repeat until there are no
348 * more.
349 *
350 * v3 4.11.1.1
351 * - (N/A) operand stack is always the same size
352 * - operand stack [registers] contain the correct types of values
353 * - local variables [registers] contain the correct types of values
354 * - methods are invoked with the appropriate arguments
355 * - fields are assigned using values of appropriate types
356 * - opcodes have the correct type values in operand registers
357 * - there is never an uninitialized class instance in a local variable in code protected by an
358 * exception handler (operand stack is okay, because the operand stack is discarded when an
359 * exception is thrown) [can't know what's a local var w/o the debug info -- should fall out of
360 * register typing]
361 *
362 * v3 4.11.1.2
363 * - execution cannot fall off the end of the code
364 *
365 * (We also do many of the items described in the "static checks" sections, because it's easier to
366 * do them here.)
367 *
368 * We need an array of RegType values, one per register, for every instruction. If the method uses
369 * monitor-enter, we need extra data for every register, and a stack for every "interesting"
370 * instruction. In theory this could become quite large -- up to several megabytes for a monster
371 * function.
372 *
373 * NOTE:
374 * The spec forbids backward branches when there's an uninitialized reference in a register. The
375 * idea is to prevent something like this:
376 * loop:
377 * move r1, r0
378 * new-instance r0, MyClass
379 * ...
380 * if-eq rN, loop // once
381 * initialize r0
382 *
383 * This leaves us with two different instances, both allocated by the same instruction, but only
384 * one is initialized. The scheme outlined in v3 4.11.1.4 wouldn't catch this, so they work around
385 * it by preventing backward branches. We achieve identical results without restricting code
386 * reordering by specifying that you can't execute the new-instance instruction if a register
387 * contains an uninitialized instance created by that same instruction.
388 */
389 bool CodeFlowVerifyMethod() REQUIRES_SHARED(Locks::mutator_lock_);
390
391 /*
392 * Perform verification for a single instruction.
393 *
394 * This requires fully decoding the instruction to determine the effect it has on registers.
395 *
396 * Finds zero or more following instructions and sets the "changed" flag if execution at that
397 * point needs to be (re-)evaluated. Register changes are merged into "reg_types_" at the target
398 * addresses. Does not set or clear any other flags in "insn_flags_".
399 */
400 bool CodeFlowVerifyInstruction(uint32_t* start_guess)
401 REQUIRES_SHARED(Locks::mutator_lock_);
402
403 // Perform verification of a new array instruction
404 void VerifyNewArray(const Instruction* inst, bool is_filled, bool is_range)
405 REQUIRES_SHARED(Locks::mutator_lock_);
406
407 // Helper to perform verification on puts of primitive type.
408 void VerifyPrimitivePut(const RegType& target_type, const RegType& insn_type,
409 const uint32_t vregA) REQUIRES_SHARED(Locks::mutator_lock_);
410
411 // Perform verification of an aget instruction. The destination register's type will be set to
412 // be that of component type of the array unless the array type is unknown, in which case a
413 // bottom type inferred from the type of instruction is used. is_primitive is false for an
414 // aget-object.
415 void VerifyAGet(const Instruction* inst, const RegType& insn_type,
416 bool is_primitive) REQUIRES_SHARED(Locks::mutator_lock_);
417
418 // Perform verification of an aput instruction.
419 void VerifyAPut(const Instruction* inst, const RegType& insn_type,
420 bool is_primitive) REQUIRES_SHARED(Locks::mutator_lock_);
421
422 // Lookup instance field and fail for resolution violations
423 ArtField* GetInstanceField(const RegType& obj_type, int field_idx)
424 REQUIRES_SHARED(Locks::mutator_lock_);
425
426 // Lookup static field and fail for resolution violations
427 ArtField* GetStaticField(int field_idx) REQUIRES_SHARED(Locks::mutator_lock_);
428
429 // Perform verification of an iget/sget/iput/sput instruction.
Andreas Gampefc25ae92019-04-19 22:22:57 -0700430 template <FieldAccessType kAccType>
431 void VerifyISFieldAccess(const Instruction* inst, const RegType& insn_type,
432 bool is_primitive, bool is_static)
433 REQUIRES_SHARED(Locks::mutator_lock_);
434
Andreas Gampefc25ae92019-04-19 22:22:57 -0700435 // Resolves a class based on an index and, if C is kYes, performs access checks to ensure
436 // the referrer can access the resolved class.
437 template <CheckAccess C>
438 const RegType& ResolveClass(dex::TypeIndex class_idx)
439 REQUIRES_SHARED(Locks::mutator_lock_);
440
441 /*
442 * For the "move-exception" instruction at "work_insn_idx_", which must be at an exception handler
443 * address, determine the Join of all exceptions that can land here. Fails if no matching
444 * exception handler can be found or if the Join of exception types fails.
445 */
446 const RegType& GetCaughtExceptionType()
447 REQUIRES_SHARED(Locks::mutator_lock_);
448
449 /*
450 * Resolves a method based on an index and performs access checks to ensure
451 * the referrer can access the resolved method.
452 * Does not throw exceptions.
453 */
454 ArtMethod* ResolveMethodAndCheckAccess(uint32_t method_idx, MethodType method_type)
455 REQUIRES_SHARED(Locks::mutator_lock_);
456
457 /*
458 * Verify the arguments to a method. We're executing in "method", making
459 * a call to the method reference in vB.
460 *
461 * If this is a "direct" invoke, we allow calls to <init>. For calls to
462 * <init>, the first argument may be an uninitialized reference. Otherwise,
463 * calls to anything starting with '<' will be rejected, as will any
464 * uninitialized reference arguments.
465 *
466 * For non-static method calls, this will verify that the method call is
467 * appropriate for the "this" argument.
468 *
469 * The method reference is in vBBBB. The "is_range" parameter determines
470 * whether we use 0-4 "args" values or a range of registers defined by
471 * vAA and vCCCC.
472 *
473 * Widening conversions on integers and references are allowed, but
474 * narrowing conversions are not.
475 *
476 * Returns the resolved method on success, null on failure (with *failure
477 * set appropriately).
478 */
479 ArtMethod* VerifyInvocationArgs(const Instruction* inst, MethodType method_type, bool is_range)
480 REQUIRES_SHARED(Locks::mutator_lock_);
481
482 // Similar checks to the above, but on the proto. Will be used when the method cannot be
483 // resolved.
484 void VerifyInvocationArgsUnresolvedMethod(const Instruction* inst, MethodType method_type,
485 bool is_range)
486 REQUIRES_SHARED(Locks::mutator_lock_);
487
488 template <class T>
489 ArtMethod* VerifyInvocationArgsFromIterator(T* it, const Instruction* inst,
490 MethodType method_type, bool is_range,
491 ArtMethod* res_method)
492 REQUIRES_SHARED(Locks::mutator_lock_);
493
494 /*
495 * Verify the arguments present for a call site. Returns "true" if all is well, "false" otherwise.
496 */
497 bool CheckCallSite(uint32_t call_site_idx);
498
499 /*
500 * Verify that the target instruction is not "move-exception". It's important that the only way
501 * to execute a move-exception is as the first instruction of an exception handler.
502 * Returns "true" if all is well, "false" if the target instruction is move-exception.
503 */
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700504 bool CheckNotMoveException(const uint16_t* insns, int insn_idx) {
505 if ((insns[insn_idx] & 0xff) == Instruction::MOVE_EXCEPTION) {
506 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-exception";
507 return false;
508 }
509 return true;
510 }
Andreas Gampefc25ae92019-04-19 22:22:57 -0700511
512 /*
513 * Verify that the target instruction is not "move-result". It is important that we cannot
514 * branch to move-result instructions, but we have to make this a distinct check instead of
515 * adding it to CheckNotMoveException, because it is legal to continue into "move-result"
516 * instructions - as long as the previous instruction was an invoke, which is checked elsewhere.
517 */
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700518 bool CheckNotMoveResult(const uint16_t* insns, int insn_idx) {
519 if (((insns[insn_idx] & 0xff) >= Instruction::MOVE_RESULT) &&
520 ((insns[insn_idx] & 0xff) <= Instruction::MOVE_RESULT_OBJECT)) {
521 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid use of move-result*";
522 return false;
523 }
524 return true;
525 }
Andreas Gampefc25ae92019-04-19 22:22:57 -0700526
527 /*
528 * Verify that the target instruction is not "move-result" or "move-exception". This is to
529 * be used when checking branch and switch instructions, but not instructions that can
530 * continue.
531 */
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700532 bool CheckNotMoveExceptionOrMoveResult(const uint16_t* insns, int insn_idx) {
533 return (CheckNotMoveException(insns, insn_idx) && CheckNotMoveResult(insns, insn_idx));
534 }
Andreas Gampefc25ae92019-04-19 22:22:57 -0700535
536 /*
537 * Control can transfer to "next_insn". Merge the registers from merge_line into the table at
538 * next_insn, and set the changed flag on the target address if any of the registers were changed.
539 * In the case of fall-through, update the merge line on a change as its the working line for the
540 * next instruction.
541 * Returns "false" if an error is encountered.
542 */
543 bool UpdateRegisters(uint32_t next_insn, RegisterLine* merge_line, bool update_merge_line)
544 REQUIRES_SHARED(Locks::mutator_lock_);
545
546 // Return the register type for the method.
547 const RegType& GetMethodReturnType() REQUIRES_SHARED(Locks::mutator_lock_);
548
549 // Get a type representing the declaring class of the method.
550 const RegType& GetDeclaringClass() REQUIRES_SHARED(Locks::mutator_lock_);
551
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700552 InstructionFlags* CurrentInsnFlags() {
553 return &GetModifiableInstructionFlags(work_insn_idx_);
554 }
Andreas Gampefc25ae92019-04-19 22:22:57 -0700555
556 const RegType& DetermineCat1Constant(int32_t value, bool precise)
557 REQUIRES_SHARED(Locks::mutator_lock_);
558
559 // Try to create a register type from the given class. In case a precise type is requested, but
560 // the class is not instantiable, a soft error (of type NO_CLASS) will be enqueued and a
561 // non-precise reference will be returned.
562 // Note: we reuse NO_CLASS as this will throw an exception at runtime, when the failing class is
563 // actually touched.
564 const RegType& FromClass(const char* descriptor, ObjPtr<mirror::Class> klass, bool precise)
565 REQUIRES_SHARED(Locks::mutator_lock_);
566
567 ALWAYS_INLINE bool FailOrAbort(bool condition, const char* error_msg, uint32_t work_insn_idx);
568
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700569 ALWAYS_INLINE InstructionFlags& GetModifiableInstructionFlags(size_t index) {
570 return insn_flags_[index];
571 }
Andreas Gampefc25ae92019-04-19 22:22:57 -0700572
573 // Returns the method index of an invoke instruction.
574 uint16_t GetMethodIdxOfInvoke(const Instruction* inst)
575 REQUIRES_SHARED(Locks::mutator_lock_);
576 // Returns the field index of a field access instruction.
577 uint16_t GetFieldIdxOfFieldAccess(const Instruction* inst, bool is_static)
578 REQUIRES_SHARED(Locks::mutator_lock_);
579
580 // Run verification on the method. Returns true if verification completes and false if the input
581 // has an irrecoverable corruption.
582 bool Verify() override REQUIRES_SHARED(Locks::mutator_lock_);
583
584 // Dump the failures encountered by the verifier.
585 std::ostream& DumpFailures(std::ostream& os);
586
587 // Dump the state of the verifier, namely each instruction, what flags are set on it, register
588 // information
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700589 void Dump(std::ostream& os) REQUIRES_SHARED(Locks::mutator_lock_) {
590 VariableIndentationOutputStream vios(&os);
591 Dump(&vios);
592 }
Andreas Gampefc25ae92019-04-19 22:22:57 -0700593 void Dump(VariableIndentationOutputStream* vios) REQUIRES_SHARED(Locks::mutator_lock_);
594
595 ArtMethod* method_being_verified_; // Its ArtMethod representation if known.
596 const uint32_t method_access_flags_; // Method's access flags.
597 const RegType* return_type_; // Lazily computed return type of the method.
598 // The dex_cache for the declaring class of the method.
599 Handle<mirror::DexCache> dex_cache_ GUARDED_BY(Locks::mutator_lock_);
600 // The class loader for the declaring class of the method.
601 Handle<mirror::ClassLoader> class_loader_ GUARDED_BY(Locks::mutator_lock_);
602 const dex::ClassDef& class_def_; // The class def of the declaring class of the method.
603 const RegType* declaring_class_; // Lazily computed reg type of the method's declaring class.
604
605 // The dex PC of a FindLocksAtDexPc request, -1 otherwise.
606 uint32_t interesting_dex_pc_;
607 // The container into which FindLocksAtDexPc should write the registers containing held locks,
608 // null if we're not doing FindLocksAtDexPc.
609 std::vector<DexLockInfo>* monitor_enter_dex_pcs_;
610
611
612 // An optimization where instead of generating unique RegTypes for constants we use imprecise
613 // constants that cover a range of constants. This isn't good enough for deoptimization that
614 // avoids loading from registers in the case of a constant as the dex instruction set lost the
615 // notion of whether a value should be in a floating point or general purpose register file.
616 const bool need_precise_constants_;
617
618 // Indicates whether we verify to dump the info. In that case we accept quickened instructions
619 // even though we might detect to be a compiler. Should only be set when running
620 // VerifyMethodAndDump.
621 const bool verify_to_dump_;
622
623 // Whether or not we call AllowThreadSuspension periodically, we want a way to disable this for
624 // thread dumping checkpoints since we may get thread suspension at an inopportune time due to
625 // FindLocksAtDexPC, resulting in deadlocks.
626 const bool allow_thread_suspension_;
627
628 // Whether the method seems to be a constructor. Note that this field exists as we can't trust
629 // the flags in the dex file. Some older code does not mark methods named "<init>" and "<clinit>"
630 // correctly.
631 //
632 // Note: this flag is only valid once Verify() has started.
633 bool is_constructor_;
634
Alex Lighte48fd0b2019-05-20 10:04:44 -0700635 // Whether to attempt to fill all register lines for (ex) debugger use.
636 bool fill_register_lines_;
637
Andreas Gampefc25ae92019-04-19 22:22:57 -0700638 // API level, for dependent checks. Note: we do not use '0' for unset here, to simplify checks.
639 // Instead, unset level should correspond to max().
640 const uint32_t api_level_;
641
642 friend class ::art::verifier::MethodVerifier;
643
644 DISALLOW_COPY_AND_ASSIGN(MethodVerifier);
645};
646
Andreas Gampe7c038102014-10-27 20:08:46 -0700647// Note: returns true on failure.
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700648template <bool kVerifierDebug>
649inline bool MethodVerifier<kVerifierDebug>::FailOrAbort(bool condition,
650 const char* error_msg,
651 uint32_t work_insn_idx) {
Andreas Gampe7c038102014-10-27 20:08:46 -0700652 if (kIsDebugBuild) {
Andreas Gampef8f36c22016-11-19 14:51:52 -0800653 // In a debug build, abort if the error condition is wrong. Only warn if
654 // we are already aborting (as this verification is likely run to print
655 // lock information).
656 if (LIKELY(gAborting == 0)) {
Mathieu Chartierc2a2bda2018-03-12 11:21:52 -0700657 DCHECK(condition) << error_msg << work_insn_idx << " "
658 << dex_file_->PrettyMethod(dex_method_idx_);
Andreas Gampef8f36c22016-11-19 14:51:52 -0800659 } else {
660 if (!condition) {
661 LOG(ERROR) << error_msg << work_insn_idx;
Mathieu Chartierc2a2bda2018-03-12 11:21:52 -0700662 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << error_msg << work_insn_idx;
Andreas Gampef8f36c22016-11-19 14:51:52 -0800663 return true;
664 }
665 }
Andreas Gampe7c038102014-10-27 20:08:46 -0700666 } else {
667 // In a non-debug build, just fail the class.
668 if (!condition) {
Mathieu Chartierc2a2bda2018-03-12 11:21:52 -0700669 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << error_msg << work_insn_idx;
Andreas Gampe7c038102014-10-27 20:08:46 -0700670 return true;
671 }
672 }
673
674 return false;
675}
676
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800677static bool IsLargeMethod(const CodeItemDataAccessor& accessor) {
678 if (!accessor.HasCodeItem()) {
Andreas Gampe3c651fc2015-05-21 14:06:46 -0700679 return false;
680 }
681
Mathieu Chartier808c7a52017-12-15 11:19:33 -0800682 uint16_t registers_size = accessor.RegistersSize();
683 uint32_t insns_size = accessor.InsnsSizeInCodeUnits();
Andreas Gampea4f5bf62015-05-18 20:50:12 -0700684
685 return registers_size * insns_size > 4*1024*1024;
686}
687
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700688template <bool kVerifierDebug>
689MethodVerifier<kVerifierDebug>::MethodVerifier(Thread* self,
690 const DexFile* dex_file,
691 Handle<mirror::DexCache> dex_cache,
692 Handle<mirror::ClassLoader> class_loader,
693 const dex::ClassDef& class_def,
694 const dex::CodeItem* code_item,
695 uint32_t dex_method_idx,
696 ArtMethod* method,
697 uint32_t method_access_flags,
698 bool can_load_classes,
699 bool allow_soft_failures,
700 bool need_precise_constants,
701 bool verify_to_dump,
702 bool allow_thread_suspension,
Alex Lighte48fd0b2019-05-20 10:04:44 -0700703 bool fill_register_lines,
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700704 uint32_t api_level)
Andreas Gampefc25ae92019-04-19 22:22:57 -0700705 : art::verifier::MethodVerifier(self,
706 dex_file,
707 code_item,
708 dex_method_idx,
709 can_load_classes,
710 allow_thread_suspension,
711 allow_soft_failures),
Nicolas Geoffrayb041a402017-11-13 15:16:22 +0000712 method_being_verified_(method),
Ian Rogersad0b3a32012-04-16 14:50:24 -0700713 method_access_flags_(method_access_flags),
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700714 return_type_(nullptr),
jeffhaof56197c2012-03-05 18:01:54 -0800715 dex_cache_(dex_cache),
716 class_loader_(class_loader),
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700717 class_def_(class_def),
Ian Rogers7b078e82014-09-10 14:44:24 -0700718 declaring_class_(nullptr),
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700719 interesting_dex_pc_(-1),
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700720 monitor_enter_dex_pcs_(nullptr),
Ian Rogers46960fe2014-05-23 10:43:43 -0700721 need_precise_constants_(need_precise_constants),
Mathieu Chartier4306ef82014-12-19 18:41:47 -0800722 verify_to_dump_(verify_to_dump),
Andreas Gamped5ad72f2015-06-26 17:33:47 -0700723 allow_thread_suspension_(allow_thread_suspension),
Andreas Gampee6215c02015-08-31 18:54:38 -0700724 is_constructor_(false),
Alex Lighte48fd0b2019-05-20 10:04:44 -0700725 fill_register_lines_(fill_register_lines),
Andreas Gampe6cc23ac2018-08-24 15:22:43 -0700726 api_level_(api_level == 0 ? std::numeric_limits<uint32_t>::max() : api_level) {
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700727}
728
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700729template <bool kVerifierDebug>
730void MethodVerifier<kVerifierDebug>::FindLocksAtDexPc() {
Ian Rogers7b078e82014-09-10 14:44:24 -0700731 CHECK(monitor_enter_dex_pcs_ != nullptr);
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800732 CHECK(code_item_accessor_.HasCodeItem()); // This only makes sense for methods with code.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700733
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800734 // Quick check whether there are any monitor_enter instructions before verifying.
735 for (const DexInstructionPcPair& inst : code_item_accessor_) {
736 if (inst->Opcode() == Instruction::MONITOR_ENTER) {
737 // Strictly speaking, we ought to be able to get away with doing a subset of the full method
738 // verification. In practice, the phase we want relies on data structures set up by all the
739 // earlier passes, so we just run the full method verification and bail out early when we've
740 // got what we wanted.
741 Verify();
742 return;
743 }
Andreas Gampecb3c08f2014-09-18 13:16:38 -0700744 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700745}
746
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700747template <bool kVerifierDebug>
748bool MethodVerifier<kVerifierDebug>::Verify() {
Andreas Gampee6215c02015-08-31 18:54:38 -0700749 // Some older code doesn't correctly mark constructors as such. Test for this case by looking at
750 // the name.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800751 const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
Andreas Gampee6215c02015-08-31 18:54:38 -0700752 const char* method_name = dex_file_->StringDataByIdx(method_id.name_idx_);
753 bool instance_constructor_by_name = strcmp("<init>", method_name) == 0;
754 bool static_constructor_by_name = strcmp("<clinit>", method_name) == 0;
755 bool constructor_by_name = instance_constructor_by_name || static_constructor_by_name;
756 // Check that only constructors are tagged, and check for bad code that doesn't tag constructors.
757 if ((method_access_flags_ & kAccConstructor) != 0) {
758 if (!constructor_by_name) {
759 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
760 << "method is marked as constructor, but not named accordingly";
jeffhaobdb76512011-09-07 11:43:16 -0700761 return false;
Andreas Gampee6215c02015-08-31 18:54:38 -0700762 }
763 is_constructor_ = true;
764 } else if (constructor_by_name) {
David Sehr709b0702016-10-13 09:12:37 -0700765 LOG(WARNING) << "Method " << dex_file_->PrettyMethod(dex_method_idx_)
Andreas Gampee6215c02015-08-31 18:54:38 -0700766 << " not marked as constructor.";
767 is_constructor_ = true;
768 }
769 // If it's a constructor, check whether IsStatic() matches the name.
770 // This should have been rejected by the dex file verifier. Only do in debug build.
771 if (kIsDebugBuild) {
772 if (IsConstructor()) {
773 if (IsStatic() ^ static_constructor_by_name) {
774 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
775 << "constructor name doesn't match static flag";
776 return false;
777 }
jeffhaobdb76512011-09-07 11:43:16 -0700778 }
jeffhaobdb76512011-09-07 11:43:16 -0700779 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700780
781 // Methods may only have one of public/protected/private.
782 // This should have been rejected by the dex file verifier. Only do in debug build.
783 if (kIsDebugBuild) {
784 size_t access_mod_count =
785 (((method_access_flags_ & kAccPublic) == 0) ? 0 : 1) +
786 (((method_access_flags_ & kAccProtected) == 0) ? 0 : 1) +
787 (((method_access_flags_ & kAccPrivate) == 0) ? 0 : 1);
788 if (access_mod_count > 1) {
789 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "method has more than one of public/protected/private";
790 return false;
791 }
792 }
793
794 // If there aren't any instructions, make sure that's expected, then exit successfully.
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800795 if (!code_item_accessor_.HasCodeItem()) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700796 // Only native or abstract methods may not have code.
797 if ((method_access_flags_ & (kAccNative | kAccAbstract)) == 0) {
798 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "zero-length code in concrete non-native method";
799 return false;
800 }
801
Andreas Gampee6215c02015-08-31 18:54:38 -0700802 // This should have been rejected by the dex file verifier. Only do in debug build.
Andreas Gampe76ed99d2016-03-28 18:31:29 -0700803 // Note: the above will also be rejected in the dex file verifier, starting in dex version 37.
Andreas Gampee6215c02015-08-31 18:54:38 -0700804 if (kIsDebugBuild) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700805 if ((method_access_flags_ & kAccAbstract) != 0) {
806 // Abstract methods are not allowed to have the following flags.
807 static constexpr uint32_t kForbidden =
808 kAccPrivate |
809 kAccStatic |
810 kAccFinal |
811 kAccNative |
812 kAccStrict |
813 kAccSynchronized;
814 if ((method_access_flags_ & kForbidden) != 0) {
815 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
816 << "method can't be abstract and private/static/final/native/strict/synchronized";
817 return false;
818 }
819 }
David Brazdil15fc7292016-09-02 14:13:18 +0100820 if ((class_def_.GetJavaAccessFlags() & kAccInterface) != 0) {
Alex Lighteb7c1442015-08-31 13:17:42 -0700821 // Interface methods must be public and abstract (if default methods are disabled).
Neil Fuller9724c632016-01-07 15:42:47 +0000822 uint32_t kRequired = kAccPublic;
Alex Lighteb7c1442015-08-31 13:17:42 -0700823 if ((method_access_flags_ & kRequired) != kRequired) {
Neil Fuller9724c632016-01-07 15:42:47 +0000824 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface methods must be public";
Andreas Gampee6215c02015-08-31 18:54:38 -0700825 return false;
826 }
827 // In addition to the above, interface methods must not be protected.
828 static constexpr uint32_t kForbidden = kAccProtected;
829 if ((method_access_flags_ & kForbidden) != 0) {
830 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interface methods can't be protected";
831 return false;
832 }
833 }
834 // We also don't allow constructors to be abstract or native.
835 if (IsConstructor()) {
836 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "constructors can't be abstract or native";
837 return false;
838 }
839 }
840 return true;
841 }
842
843 // This should have been rejected by the dex file verifier. Only do in debug build.
844 if (kIsDebugBuild) {
845 // When there's code, the method must not be native or abstract.
846 if ((method_access_flags_ & (kAccNative | kAccAbstract)) != 0) {
847 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "non-zero-length code in abstract or native method";
848 return false;
849 }
850
David Brazdil15fc7292016-09-02 14:13:18 +0100851 if ((class_def_.GetJavaAccessFlags() & kAccInterface) != 0) {
Alex Lighteb7c1442015-08-31 13:17:42 -0700852 // Interfaces may always have static initializers for their fields. If we are running with
853 // default methods enabled we also allow other public, static, non-final methods to have code.
854 // Otherwise that is the only type of method allowed.
Alex Light0db36b32015-10-27 14:06:34 -0700855 if (!(IsConstructor() && IsStatic())) {
Neil Fuller9724c632016-01-07 15:42:47 +0000856 if (IsInstanceConstructor()) {
857 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interfaces may not have non-static constructor";
858 return false;
859 } else if (method_access_flags_ & kAccFinal) {
860 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "interfaces may not have final methods";
861 return false;
Alex Lightb55f1ac2016-04-12 15:50:55 -0700862 } else {
863 uint32_t access_flag_options = kAccPublic;
Mathieu Chartierf6e31472017-12-28 13:32:08 -0800864 if (dex_file_->SupportsDefaultMethods()) {
Alex Lightb55f1ac2016-04-12 15:50:55 -0700865 access_flag_options |= kAccPrivate;
866 }
867 if (!(method_access_flags_ & access_flag_options)) {
868 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
869 << "interfaces may not have protected or package-private members";
870 return false;
871 }
Alex Lighteb7c1442015-08-31 13:17:42 -0700872 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700873 }
874 }
875
876 // Instance constructors must not be synchronized.
877 if (IsInstanceConstructor()) {
878 static constexpr uint32_t kForbidden = kAccSynchronized;
879 if ((method_access_flags_ & kForbidden) != 0) {
880 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "constructors can't be synchronized";
881 return false;
882 }
883 }
884 }
885
Ian Rogersd81871c2011-10-03 13:57:23 -0700886 // Sanity-check the register counts. ins + locals = registers, so make sure that ins <= registers.
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800887 if (code_item_accessor_.InsSize() > code_item_accessor_.RegistersSize()) {
888 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad register counts (ins="
889 << code_item_accessor_.InsSize()
890 << " regs=" << code_item_accessor_.RegistersSize();
Ian Rogersd81871c2011-10-03 13:57:23 -0700891 return false;
jeffhaobdb76512011-09-07 11:43:16 -0700892 }
Alex Lighteb7c1442015-08-31 13:17:42 -0700893
Ian Rogersd81871c2011-10-03 13:57:23 -0700894 // Allocate and initialize an array to hold instruction data.
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800895 insn_flags_.reset(allocator_.AllocArray<InstructionFlags>(
896 code_item_accessor_.InsnsSizeInCodeUnits()));
Mathieu Chartierde40d472015-10-15 17:47:48 -0700897 DCHECK(insn_flags_ != nullptr);
898 std::uninitialized_fill_n(insn_flags_.get(),
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800899 code_item_accessor_.InsnsSizeInCodeUnits(),
Mathieu Chartierde40d472015-10-15 17:47:48 -0700900 InstructionFlags());
Ian Rogersd81871c2011-10-03 13:57:23 -0700901 // Run through the instructions and see if the width checks out.
902 bool result = ComputeWidthsAndCountOps();
Andreas Gampebf1cb772017-05-15 15:39:00 -0700903 bool allow_runtime_only_instructions = !Runtime::Current()->IsAotCompiler() || verify_to_dump_;
Ian Rogersd81871c2011-10-03 13:57:23 -0700904 // Flag instructions guarded by a "try" block and check exception handlers.
905 result = result && ScanTryCatchBlocks();
906 // Perform static instruction verification.
Andreas Gampebf1cb772017-05-15 15:39:00 -0700907 result = result && (allow_runtime_only_instructions
908 ? VerifyInstructions<true>()
909 : VerifyInstructions<false>());
Ian Rogersad0b3a32012-04-16 14:50:24 -0700910 // Perform code-flow analysis and return.
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000911 result = result && VerifyCodeFlow();
Andreas Gampe53e32d12015-12-09 21:03:23 -0800912
Vladimir Marko2b5eaa22013-12-13 13:59:30 +0000913 return result;
jeffhaoba5ebb92011-08-25 17:24:37 -0700914}
915
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700916template <bool kVerifierDebug>
917void MethodVerifier<kVerifierDebug>::PrependToLastFailMessage(std::string prepend) {
Ian Rogersad0b3a32012-04-16 14:50:24 -0700918 size_t failure_num = failure_messages_.size();
919 DCHECK_NE(failure_num, 0U);
920 std::ostringstream* last_fail_message = failure_messages_[failure_num - 1];
921 prepend += last_fail_message->str();
Elena Sayapina78480ec2014-08-15 15:52:42 +0700922 failure_messages_[failure_num - 1] = new std::ostringstream(prepend, std::ostringstream::ate);
Ian Rogersad0b3a32012-04-16 14:50:24 -0700923 delete last_fail_message;
924}
925
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700926template <bool kVerifierDebug>
927void MethodVerifier<kVerifierDebug>::AppendToLastFailMessage(const std::string& append) {
Ian Rogersad0b3a32012-04-16 14:50:24 -0700928 size_t failure_num = failure_messages_.size();
929 DCHECK_NE(failure_num, 0U);
930 std::ostringstream* last_fail_message = failure_messages_[failure_num - 1];
931 (*last_fail_message) << append;
Ian Rogers47a05882012-02-03 12:23:33 -0800932}
933
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700934template <bool kVerifierDebug>
935bool MethodVerifier<kVerifierDebug>::ComputeWidthsAndCountOps() {
Mathieu Chartieraf7c9022017-10-27 09:42:46 -0700936 // We can't assume the instruction is well formed, handle the case where calculating the size
937 // goes past the end of the code item.
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800938 SafeDexInstructionIterator it(code_item_accessor_.begin(), code_item_accessor_.end());
939 for ( ; !it.IsErrorState() && it < code_item_accessor_.end(); ++it) {
Mathieu Chartieraf7c9022017-10-27 09:42:46 -0700940 // In case the instruction goes past the end of the code item, make sure to not process it.
941 SafeDexInstructionIterator next = it;
942 ++next;
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800943 if (next.IsErrorState()) {
Mathieu Chartieraf7c9022017-10-27 09:42:46 -0700944 break;
945 }
946 Instruction::Code opcode = it->Opcode();
Ian Rogersa9a82542013-10-04 11:17:26 -0700947 switch (opcode) {
948 case Instruction::APUT_OBJECT:
949 case Instruction::CHECK_CAST:
950 has_check_casts_ = true;
951 break;
Ian Rogersa9a82542013-10-04 11:17:26 -0700952 default:
953 break;
jeffhaobdb76512011-09-07 11:43:16 -0700954 }
Andreas Gampe51de69e2019-04-19 15:14:14 -0700955 GetModifiableInstructionFlags(it.DexPc()).SetIsOpcode();
jeffhaobdb76512011-09-07 11:43:16 -0700956 }
957
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800958 if (it != code_item_accessor_.end()) {
959 const size_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits();
jeffhaod5347e02012-03-22 17:25:05 -0700960 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "code did not end where expected ("
Mathieu Chartier2b2bef22017-10-26 17:10:19 -0700961 << it.DexPc() << " vs. " << insns_size << ")";
jeffhaobdb76512011-09-07 11:43:16 -0700962 return false;
963 }
964
jeffhaobdb76512011-09-07 11:43:16 -0700965 return true;
966}
967
Andreas Gampe99db7bb2019-04-19 23:05:47 -0700968template <bool kVerifierDebug>
969bool MethodVerifier<kVerifierDebug>::ScanTryCatchBlocks() {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800970 const uint32_t tries_size = code_item_accessor_.TriesSize();
jeffhaobdb76512011-09-07 11:43:16 -0700971 if (tries_size == 0) {
972 return true;
973 }
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800974 const uint32_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800975 for (const dex::TryItem& try_item : code_item_accessor_.TryItems()) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800976 const uint32_t start = try_item.start_addr_;
977 const uint32_t end = start + try_item.insn_count_;
jeffhaobdb76512011-09-07 11:43:16 -0700978 if ((start >= end) || (start >= insns_size) || (end > insns_size)) {
jeffhaod5347e02012-03-22 17:25:05 -0700979 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad exception entry: startAddr=" << start
980 << " endAddr=" << end << " (size=" << insns_size << ")";
jeffhaobdb76512011-09-07 11:43:16 -0700981 return false;
982 }
Mathieu Chartierde40d472015-10-15 17:47:48 -0700983 if (!GetInstructionFlags(start).IsOpcode()) {
Brian Carlstrom93c33962013-07-26 10:37:43 -0700984 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
985 << "'try' block starts inside an instruction (" << start << ")";
jeffhaobdb76512011-09-07 11:43:16 -0700986 return false;
987 }
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800988 DexInstructionIterator end_it(code_item_accessor_.Insns(), end);
989 for (DexInstructionIterator it(code_item_accessor_.Insns(), start); it < end_it; ++it) {
Andreas Gampe51de69e2019-04-19 15:14:14 -0700990 GetModifiableInstructionFlags(it.DexPc()).SetInTry();
jeffhaobdb76512011-09-07 11:43:16 -0700991 }
992 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800993 // Iterate over each of the handlers to verify target addresses.
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -0800994 const uint8_t* handlers_ptr = code_item_accessor_.GetCatchHandlerData();
995 const uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Ian Rogers28ad40d2011-10-27 15:19:26 -0700996 ClassLinker* linker = Runtime::Current()->GetClassLinker();
jeffhaobdb76512011-09-07 11:43:16 -0700997 for (uint32_t idx = 0; idx < handlers_size; idx++) {
Ian Rogers0571d352011-11-03 19:51:38 -0700998 CatchHandlerIterator iterator(handlers_ptr);
999 for (; iterator.HasNext(); iterator.Next()) {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08001000 uint32_t dex_pc = iterator.GetHandlerAddress();
Mathieu Chartierde40d472015-10-15 17:47:48 -07001001 if (!GetInstructionFlags(dex_pc).IsOpcode()) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07001002 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1003 << "exception handler starts at bad address (" << dex_pc << ")";
jeffhaobdb76512011-09-07 11:43:16 -07001004 return false;
1005 }
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001006 if (!CheckNotMoveResult(code_item_accessor_.Insns(), dex_pc)) {
Stephen Kyle9bc61992014-09-22 13:53:15 +01001007 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1008 << "exception handler begins with move-result* (" << dex_pc << ")";
1009 return false;
1010 }
Andreas Gampe51de69e2019-04-19 15:14:14 -07001011 GetModifiableInstructionFlags(dex_pc).SetBranchTarget();
Ian Rogers28ad40d2011-10-27 15:19:26 -07001012 // Ensure exception types are resolved so that they don't need resolution to be delivered,
1013 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08001014 if (iterator.GetHandlerTypeIndex().IsValid()) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001015 ObjPtr<mirror::Class> exception_type =
1016 linker->ResolveType(iterator.GetHandlerTypeIndex(), dex_cache_, class_loader_);
Ian Rogers7b078e82014-09-10 14:44:24 -07001017 if (exception_type == nullptr) {
1018 DCHECK(self_->IsExceptionPending());
1019 self_->ClearException();
Ian Rogers28ad40d2011-10-27 15:19:26 -07001020 }
1021 }
jeffhaobdb76512011-09-07 11:43:16 -07001022 }
Ian Rogers0571d352011-11-03 19:51:38 -07001023 handlers_ptr = iterator.EndDataPointer();
jeffhaobdb76512011-09-07 11:43:16 -07001024 }
jeffhaobdb76512011-09-07 11:43:16 -07001025 return true;
1026}
1027
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001028template <bool kVerifierDebug>
Andreas Gampebf1cb772017-05-15 15:39:00 -07001029template <bool kAllowRuntimeOnlyInstructions>
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001030bool MethodVerifier<kVerifierDebug>::VerifyInstructions() {
Ian Rogers0c7abda2012-09-19 13:33:42 -07001031 /* Flag the start of the method as a branch target, and a GC point due to stack overflow errors */
Andreas Gampe51de69e2019-04-19 15:14:14 -07001032 GetModifiableInstructionFlags(0).SetBranchTarget();
1033 GetModifiableInstructionFlags(0).SetCompileTimeInfoPoint();
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001034 for (const DexInstructionPcPair& inst : code_item_accessor_) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001035 const uint32_t dex_pc = inst.DexPc();
1036 if (!VerifyInstruction<kAllowRuntimeOnlyInstructions>(&inst.Inst(), dex_pc)) {
Ian Rogersad0b3a32012-04-16 14:50:24 -07001037 DCHECK_NE(failures_.size(), 0U);
Ian Rogersd81871c2011-10-03 13:57:23 -07001038 return false;
1039 }
1040 /* Flag instructions that are garbage collection points */
Sameer Abu Asal02c42232013-04-30 12:09:45 -07001041 // All invoke points are marked as "Throw" points already.
1042 // We are relying on this to also count all the invokes as interesting.
Vladimir Marko8b858e12014-11-27 14:52:37 +00001043 if (inst->IsBranch()) {
Andreas Gampe51de69e2019-04-19 15:14:14 -07001044 GetModifiableInstructionFlags(dex_pc).SetCompileTimeInfoPoint();
Vladimir Marko8b858e12014-11-27 14:52:37 +00001045 // The compiler also needs safepoints for fall-through to loop heads.
1046 // Such a loop head must be a target of a branch.
1047 int32_t offset = 0;
1048 bool cond, self_ok;
1049 bool target_ok = GetBranchOffset(dex_pc, &offset, &cond, &self_ok);
1050 DCHECK(target_ok);
Andreas Gampe51de69e2019-04-19 15:14:14 -07001051 GetModifiableInstructionFlags(dex_pc + offset).SetCompileTimeInfoPoint();
Vladimir Marko8b858e12014-11-27 14:52:37 +00001052 } else if (inst->IsSwitch() || inst->IsThrow()) {
Andreas Gampe51de69e2019-04-19 15:14:14 -07001053 GetModifiableInstructionFlags(dex_pc).SetCompileTimeInfoPoint();
Ian Rogersb8c78592013-07-25 23:52:52 +00001054 } else if (inst->IsReturn()) {
Andreas Gampe51de69e2019-04-19 15:14:14 -07001055 GetModifiableInstructionFlags(dex_pc).SetCompileTimeInfoPointAndReturn();
Ian Rogersd81871c2011-10-03 13:57:23 -07001056 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001057 }
1058 return true;
1059}
1060
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001061template <bool kVerifierDebug>
Andreas Gampebf1cb772017-05-15 15:39:00 -07001062template <bool kAllowRuntimeOnlyInstructions>
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001063bool MethodVerifier<kVerifierDebug>::VerifyInstruction(const Instruction* inst,
1064 uint32_t code_offset) {
Andreas Gampee05cc662017-05-15 10:17:30 -07001065 if (Instruction::kHaveExperimentalInstructions && UNLIKELY(inst->IsExperimental())) {
Igor Murashkin4d7b75f2015-07-21 17:03:36 -07001066 // Experimental instructions don't yet have verifier support implementation.
1067 // While it is possible to use them by themselves, when we try to use stable instructions
1068 // with a virtual register that was created by an experimental instruction,
1069 // the data flow analysis will fail.
1070 Fail(VERIFY_ERROR_FORCE_INTERPRETER)
1071 << "experimental instruction is not supported by verifier; skipping verification";
1072 have_pending_experimental_failure_ = true;
1073 return false;
1074 }
1075
Ian Rogersd81871c2011-10-03 13:57:23 -07001076 bool result = true;
1077 switch (inst->GetVerifyTypeArgumentA()) {
1078 case Instruction::kVerifyRegA:
Ian Rogers29a26482014-05-02 15:27:29 -07001079 result = result && CheckRegisterIndex(inst->VRegA());
Ian Rogersd81871c2011-10-03 13:57:23 -07001080 break;
1081 case Instruction::kVerifyRegAWide:
Ian Rogers29a26482014-05-02 15:27:29 -07001082 result = result && CheckWideRegisterIndex(inst->VRegA());
Ian Rogersd81871c2011-10-03 13:57:23 -07001083 break;
1084 }
1085 switch (inst->GetVerifyTypeArgumentB()) {
1086 case Instruction::kVerifyRegB:
Ian Rogers29a26482014-05-02 15:27:29 -07001087 result = result && CheckRegisterIndex(inst->VRegB());
Ian Rogersd81871c2011-10-03 13:57:23 -07001088 break;
1089 case Instruction::kVerifyRegBField:
Ian Rogers29a26482014-05-02 15:27:29 -07001090 result = result && CheckFieldIndex(inst->VRegB());
Ian Rogersd81871c2011-10-03 13:57:23 -07001091 break;
1092 case Instruction::kVerifyRegBMethod:
Ian Rogers29a26482014-05-02 15:27:29 -07001093 result = result && CheckMethodIndex(inst->VRegB());
Ian Rogersd81871c2011-10-03 13:57:23 -07001094 break;
1095 case Instruction::kVerifyRegBNewInstance:
Andreas Gampea5b09a62016-11-17 15:21:22 -08001096 result = result && CheckNewInstance(dex::TypeIndex(inst->VRegB()));
Ian Rogersd81871c2011-10-03 13:57:23 -07001097 break;
1098 case Instruction::kVerifyRegBString:
Ian Rogers29a26482014-05-02 15:27:29 -07001099 result = result && CheckStringIndex(inst->VRegB());
Ian Rogersd81871c2011-10-03 13:57:23 -07001100 break;
1101 case Instruction::kVerifyRegBType:
Andreas Gampea5b09a62016-11-17 15:21:22 -08001102 result = result && CheckTypeIndex(dex::TypeIndex(inst->VRegB()));
Ian Rogersd81871c2011-10-03 13:57:23 -07001103 break;
1104 case Instruction::kVerifyRegBWide:
Ian Rogers29a26482014-05-02 15:27:29 -07001105 result = result && CheckWideRegisterIndex(inst->VRegB());
Ian Rogersd81871c2011-10-03 13:57:23 -07001106 break;
Orion Hodson2e599942017-09-22 16:17:41 +01001107 case Instruction::kVerifyRegBCallSite:
1108 result = result && CheckCallSiteIndex(inst->VRegB());
1109 break;
1110 case Instruction::kVerifyRegBMethodHandle:
1111 result = result && CheckMethodHandleIndex(inst->VRegB());
1112 break;
1113 case Instruction::kVerifyRegBPrototype:
1114 result = result && CheckPrototypeIndex(inst->VRegB());
1115 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07001116 }
1117 switch (inst->GetVerifyTypeArgumentC()) {
1118 case Instruction::kVerifyRegC:
Ian Rogers29a26482014-05-02 15:27:29 -07001119 result = result && CheckRegisterIndex(inst->VRegC());
Ian Rogersd81871c2011-10-03 13:57:23 -07001120 break;
1121 case Instruction::kVerifyRegCField:
Ian Rogers29a26482014-05-02 15:27:29 -07001122 result = result && CheckFieldIndex(inst->VRegC());
Ian Rogersd81871c2011-10-03 13:57:23 -07001123 break;
1124 case Instruction::kVerifyRegCNewArray:
Andreas Gampea5b09a62016-11-17 15:21:22 -08001125 result = result && CheckNewArray(dex::TypeIndex(inst->VRegC()));
Ian Rogersd81871c2011-10-03 13:57:23 -07001126 break;
1127 case Instruction::kVerifyRegCType:
Andreas Gampea5b09a62016-11-17 15:21:22 -08001128 result = result && CheckTypeIndex(dex::TypeIndex(inst->VRegC()));
Ian Rogersd81871c2011-10-03 13:57:23 -07001129 break;
1130 case Instruction::kVerifyRegCWide:
Ian Rogers29a26482014-05-02 15:27:29 -07001131 result = result && CheckWideRegisterIndex(inst->VRegC());
Ian Rogersd81871c2011-10-03 13:57:23 -07001132 break;
1133 }
Orion Hodsoncfa325e2016-10-13 10:25:54 +01001134 switch (inst->GetVerifyTypeArgumentH()) {
1135 case Instruction::kVerifyRegHPrototype:
1136 result = result && CheckPrototypeIndex(inst->VRegH());
1137 break;
1138 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001139 switch (inst->GetVerifyExtraFlags()) {
1140 case Instruction::kVerifyArrayData:
1141 result = result && CheckArrayData(code_offset);
1142 break;
1143 case Instruction::kVerifyBranchTarget:
1144 result = result && CheckBranchTarget(code_offset);
1145 break;
1146 case Instruction::kVerifySwitchTargets:
1147 result = result && CheckSwitchTargets(code_offset);
1148 break;
Andreas Gampec3314312014-06-19 18:13:29 -07001149 case Instruction::kVerifyVarArgNonZero:
1150 // Fall-through.
Ian Rogers29a26482014-05-02 15:27:29 -07001151 case Instruction::kVerifyVarArg: {
Taiju Tsuiki29498a22015-04-13 14:21:00 +09001152 // Instructions that can actually return a negative value shouldn't have this flag.
1153 uint32_t v_a = dchecked_integral_cast<uint32_t>(inst->VRegA());
1154 if ((inst->GetVerifyExtraFlags() == Instruction::kVerifyVarArgNonZero && v_a == 0) ||
1155 v_a > Instruction::kMaxVarArgRegs) {
1156 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid arg count (" << v_a << ") in "
Andreas Gampec3314312014-06-19 18:13:29 -07001157 "non-range invoke";
1158 return false;
1159 }
Taiju Tsuiki29498a22015-04-13 14:21:00 +09001160
Ian Rogers29a26482014-05-02 15:27:29 -07001161 uint32_t args[Instruction::kMaxVarArgRegs];
1162 inst->GetVarArgs(args);
Taiju Tsuiki29498a22015-04-13 14:21:00 +09001163 result = result && CheckVarArgRegs(v_a, args);
Ian Rogersd81871c2011-10-03 13:57:23 -07001164 break;
Ian Rogers29a26482014-05-02 15:27:29 -07001165 }
Andreas Gampec3314312014-06-19 18:13:29 -07001166 case Instruction::kVerifyVarArgRangeNonZero:
1167 // Fall-through.
Ian Rogersd81871c2011-10-03 13:57:23 -07001168 case Instruction::kVerifyVarArgRange:
Andreas Gampec3314312014-06-19 18:13:29 -07001169 if (inst->GetVerifyExtraFlags() == Instruction::kVerifyVarArgRangeNonZero &&
1170 inst->VRegA() <= 0) {
1171 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid arg count (" << inst->VRegA() << ") in "
1172 "range invoke";
1173 return false;
1174 }
Ian Rogers29a26482014-05-02 15:27:29 -07001175 result = result && CheckVarArgRangeRegs(inst->VRegA(), inst->VRegC());
Ian Rogersd81871c2011-10-03 13:57:23 -07001176 break;
1177 case Instruction::kVerifyError:
jeffhaod5347e02012-03-22 17:25:05 -07001178 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected opcode " << inst->Name();
Ian Rogersd81871c2011-10-03 13:57:23 -07001179 result = false;
1180 break;
1181 }
Andreas Gampebf1cb772017-05-15 15:39:00 -07001182 if (!kAllowRuntimeOnlyInstructions && inst->GetVerifyIsRuntimeOnly()) {
Ian Rogers5fb22a92014-06-13 10:31:28 -07001183 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "opcode only expected at runtime " << inst->Name();
1184 result = false;
1185 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001186 return result;
1187}
1188
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001189template <bool kVerifierDebug>
1190inline bool MethodVerifier<kVerifierDebug>::CheckRegisterIndex(uint32_t idx) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001191 if (UNLIKELY(idx >= code_item_accessor_.RegistersSize())) {
jeffhaod5347e02012-03-22 17:25:05 -07001192 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register index out of range (" << idx << " >= "
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001193 << code_item_accessor_.RegistersSize() << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07001194 return false;
1195 }
1196 return true;
1197}
1198
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001199template <bool kVerifierDebug>
1200inline bool MethodVerifier<kVerifierDebug>::CheckWideRegisterIndex(uint32_t idx) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001201 if (UNLIKELY(idx + 1 >= code_item_accessor_.RegistersSize())) {
jeffhaod5347e02012-03-22 17:25:05 -07001202 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "wide register index out of range (" << idx
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001203 << "+1 >= " << code_item_accessor_.RegistersSize() << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07001204 return false;
1205 }
1206 return true;
1207}
1208
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001209template <bool kVerifierDebug>
1210inline bool MethodVerifier<kVerifierDebug>::CheckCallSiteIndex(uint32_t idx) {
Orion Hodson2e599942017-09-22 16:17:41 +01001211 uint32_t limit = dex_file_->NumCallSiteIds();
1212 if (UNLIKELY(idx >= limit)) {
1213 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad call site index " << idx << " (max "
1214 << limit << ")";
1215 return false;
1216 }
1217 return true;
1218}
1219
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001220template <bool kVerifierDebug>
1221inline bool MethodVerifier<kVerifierDebug>::CheckFieldIndex(uint32_t idx) {
Andreas Gampe29e81422017-05-15 16:29:32 -07001222 if (UNLIKELY(idx >= dex_file_->GetHeader().field_ids_size_)) {
jeffhaod5347e02012-03-22 17:25:05 -07001223 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad field index " << idx << " (max "
1224 << dex_file_->GetHeader().field_ids_size_ << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07001225 return false;
1226 }
1227 return true;
1228}
1229
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001230template <bool kVerifierDebug>
1231inline bool MethodVerifier<kVerifierDebug>::CheckMethodIndex(uint32_t idx) {
Andreas Gampe29e81422017-05-15 16:29:32 -07001232 if (UNLIKELY(idx >= dex_file_->GetHeader().method_ids_size_)) {
jeffhaod5347e02012-03-22 17:25:05 -07001233 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad method index " << idx << " (max "
1234 << dex_file_->GetHeader().method_ids_size_ << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07001235 return false;
1236 }
1237 return true;
1238}
1239
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001240template <bool kVerifierDebug>
1241inline bool MethodVerifier<kVerifierDebug>::CheckMethodHandleIndex(uint32_t idx) {
Orion Hodson2e599942017-09-22 16:17:41 +01001242 uint32_t limit = dex_file_->NumMethodHandles();
1243 if (UNLIKELY(idx >= limit)) {
1244 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad method handle index " << idx << " (max "
1245 << limit << ")";
1246 return false;
1247 }
1248 return true;
1249}
1250
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001251template <bool kVerifierDebug>
1252inline bool MethodVerifier<kVerifierDebug>::CheckNewInstance(dex::TypeIndex idx) {
Andreas Gampe29e81422017-05-15 16:29:32 -07001253 if (UNLIKELY(idx.index_ >= dex_file_->GetHeader().type_ids_size_)) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001254 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx.index_ << " (max "
jeffhaod5347e02012-03-22 17:25:05 -07001255 << dex_file_->GetHeader().type_ids_size_ << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07001256 return false;
1257 }
1258 // We don't need the actual class, just a pointer to the class name.
Ian Rogers0571d352011-11-03 19:51:38 -07001259 const char* descriptor = dex_file_->StringByTypeIdx(idx);
Andreas Gampe29e81422017-05-15 16:29:32 -07001260 if (UNLIKELY(descriptor[0] != 'L')) {
jeffhaod5347e02012-03-22 17:25:05 -07001261 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "can't call new-instance on type '" << descriptor << "'";
Ian Rogersd81871c2011-10-03 13:57:23 -07001262 return false;
Andreas Gampe29e81422017-05-15 16:29:32 -07001263 } else if (UNLIKELY(strcmp(descriptor, "Ljava/lang/Class;") == 0)) {
Aart Bikdb698f12016-07-25 17:52:22 -07001264 // An unlikely new instance on Class is not allowed. Fall back to interpreter to ensure an
1265 // exception is thrown when this statement is executed (compiled code would not do that).
1266 Fail(VERIFY_ERROR_INSTANTIATION);
Ian Rogersd81871c2011-10-03 13:57:23 -07001267 }
1268 return true;
1269}
1270
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001271template <bool kVerifierDebug>
1272inline bool MethodVerifier<kVerifierDebug>::CheckPrototypeIndex(uint32_t idx) {
Andreas Gampe29e81422017-05-15 16:29:32 -07001273 if (UNLIKELY(idx >= dex_file_->GetHeader().proto_ids_size_)) {
Orion Hodsoncfa325e2016-10-13 10:25:54 +01001274 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad prototype index " << idx << " (max "
1275 << dex_file_->GetHeader().proto_ids_size_ << ")";
1276 return false;
1277 }
1278 return true;
1279}
1280
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001281template <bool kVerifierDebug>
1282inline bool MethodVerifier<kVerifierDebug>::CheckStringIndex(uint32_t idx) {
Andreas Gampe29e81422017-05-15 16:29:32 -07001283 if (UNLIKELY(idx >= dex_file_->GetHeader().string_ids_size_)) {
jeffhaod5347e02012-03-22 17:25:05 -07001284 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad string index " << idx << " (max "
1285 << dex_file_->GetHeader().string_ids_size_ << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07001286 return false;
1287 }
1288 return true;
1289}
1290
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001291template <bool kVerifierDebug>
1292inline bool MethodVerifier<kVerifierDebug>::CheckTypeIndex(dex::TypeIndex idx) {
Andreas Gampe29e81422017-05-15 16:29:32 -07001293 if (UNLIKELY(idx.index_ >= dex_file_->GetHeader().type_ids_size_)) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001294 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx.index_ << " (max "
jeffhaod5347e02012-03-22 17:25:05 -07001295 << dex_file_->GetHeader().type_ids_size_ << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07001296 return false;
1297 }
1298 return true;
1299}
1300
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001301template <bool kVerifierDebug>
1302bool MethodVerifier<kVerifierDebug>::CheckNewArray(dex::TypeIndex idx) {
Andreas Gampe29e81422017-05-15 16:29:32 -07001303 if (UNLIKELY(idx.index_ >= dex_file_->GetHeader().type_ids_size_)) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001304 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad type index " << idx.index_ << " (max "
jeffhaod5347e02012-03-22 17:25:05 -07001305 << dex_file_->GetHeader().type_ids_size_ << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07001306 return false;
1307 }
1308 int bracket_count = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001309 const char* descriptor = dex_file_->StringByTypeIdx(idx);
Ian Rogersd81871c2011-10-03 13:57:23 -07001310 const char* cp = descriptor;
1311 while (*cp++ == '[') {
1312 bracket_count++;
1313 }
Andreas Gampe29e81422017-05-15 16:29:32 -07001314 if (UNLIKELY(bracket_count == 0)) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001315 /* The given class must be an array type. */
Brian Carlstrom93c33962013-07-26 10:37:43 -07001316 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1317 << "can't new-array class '" << descriptor << "' (not an array)";
Ian Rogersd81871c2011-10-03 13:57:23 -07001318 return false;
Andreas Gampe29e81422017-05-15 16:29:32 -07001319 } else if (UNLIKELY(bracket_count > 255)) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001320 /* It is illegal to create an array of more than 255 dimensions. */
Brian Carlstrom93c33962013-07-26 10:37:43 -07001321 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1322 << "can't new-array class '" << descriptor << "' (exceeds limit)";
Ian Rogersd81871c2011-10-03 13:57:23 -07001323 return false;
1324 }
1325 return true;
1326}
1327
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001328template <bool kVerifierDebug>
1329bool MethodVerifier<kVerifierDebug>::CheckArrayData(uint32_t cur_offset) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001330 const uint32_t insn_count = code_item_accessor_.InsnsSizeInCodeUnits();
1331 const uint16_t* insns = code_item_accessor_.Insns() + cur_offset;
Ian Rogersd81871c2011-10-03 13:57:23 -07001332 const uint16_t* array_data;
1333 int32_t array_data_offset;
1334
1335 DCHECK_LT(cur_offset, insn_count);
1336 /* make sure the start of the array data table is in range */
Andreas Gampe53de99c2015-08-17 13:43:55 -07001337 array_data_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
Andreas Gampe29e81422017-05-15 16:29:32 -07001338 if (UNLIKELY(static_cast<int32_t>(cur_offset) + array_data_offset < 0 ||
1339 cur_offset + array_data_offset + 2 >= insn_count)) {
jeffhaod5347e02012-03-22 17:25:05 -07001340 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid array data start: at " << cur_offset
Brian Carlstrom93c33962013-07-26 10:37:43 -07001341 << ", data offset " << array_data_offset
1342 << ", count " << insn_count;
Ian Rogersd81871c2011-10-03 13:57:23 -07001343 return false;
1344 }
1345 /* offset to array data table is a relative branch-style offset */
1346 array_data = insns + array_data_offset;
Andreas Gampe57c47582015-07-01 22:05:59 -07001347 // Make sure the table is at an even dex pc, that is, 32-bit aligned.
Andreas Gampe29e81422017-05-15 16:29:32 -07001348 if (UNLIKELY(!IsAligned<4>(array_data))) {
jeffhaod5347e02012-03-22 17:25:05 -07001349 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unaligned array data table: at " << cur_offset
1350 << ", data offset " << array_data_offset;
Ian Rogersd81871c2011-10-03 13:57:23 -07001351 return false;
1352 }
Andreas Gampe57c47582015-07-01 22:05:59 -07001353 // Make sure the array-data is marked as an opcode. This ensures that it was reached when
1354 // traversing the code item linearly. It is an approximation for a by-spec padding value.
Andreas Gampe29e81422017-05-15 16:29:32 -07001355 if (UNLIKELY(!GetInstructionFlags(cur_offset + array_data_offset).IsOpcode())) {
Andreas Gampe57c47582015-07-01 22:05:59 -07001356 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array data table at " << cur_offset
1357 << ", data offset " << array_data_offset
1358 << " not correctly visited, probably bad padding.";
1359 return false;
1360 }
1361
Ian Rogersd81871c2011-10-03 13:57:23 -07001362 uint32_t value_width = array_data[1];
Elliott Hughes398f64b2012-03-26 18:05:48 -07001363 uint32_t value_count = *reinterpret_cast<const uint32_t*>(&array_data[2]);
Ian Rogersd81871c2011-10-03 13:57:23 -07001364 uint32_t table_size = 4 + (value_width * value_count + 1) / 2;
1365 /* make sure the end of the switch is in range */
Andreas Gampe29e81422017-05-15 16:29:32 -07001366 if (UNLIKELY(cur_offset + array_data_offset + table_size > insn_count)) {
jeffhaod5347e02012-03-22 17:25:05 -07001367 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid array data end: at " << cur_offset
1368 << ", data offset " << array_data_offset << ", end "
1369 << cur_offset + array_data_offset + table_size
1370 << ", count " << insn_count;
Ian Rogersd81871c2011-10-03 13:57:23 -07001371 return false;
1372 }
1373 return true;
1374}
1375
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001376template <bool kVerifierDebug>
1377bool MethodVerifier<kVerifierDebug>::CheckBranchTarget(uint32_t cur_offset) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001378 int32_t offset;
1379 bool isConditional, selfOkay;
1380 if (!GetBranchOffset(cur_offset, &offset, &isConditional, &selfOkay)) {
1381 return false;
1382 }
Andreas Gampe29e81422017-05-15 16:29:32 -07001383 if (UNLIKELY(!selfOkay && offset == 0)) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07001384 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "branch offset of zero not allowed at"
1385 << reinterpret_cast<void*>(cur_offset);
Ian Rogersd81871c2011-10-03 13:57:23 -07001386 return false;
1387 }
Elliott Hughes81ff3182012-03-23 20:35:56 -07001388 // Check for 32-bit overflow. This isn't strictly necessary if we can depend on the runtime
1389 // to have identical "wrap-around" behavior, but it's unwise to depend on that.
Andreas Gampe29e81422017-05-15 16:29:32 -07001390 if (UNLIKELY(((int64_t) cur_offset + (int64_t) offset) != (int64_t) (cur_offset + offset))) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07001391 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "branch target overflow "
1392 << reinterpret_cast<void*>(cur_offset) << " +" << offset;
Ian Rogersd81871c2011-10-03 13:57:23 -07001393 return false;
1394 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001395 int32_t abs_offset = cur_offset + offset;
Andreas Gampe29e81422017-05-15 16:29:32 -07001396 if (UNLIKELY(abs_offset < 0 ||
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001397 (uint32_t) abs_offset >= code_item_accessor_.InsnsSizeInCodeUnits() ||
Andreas Gampe29e81422017-05-15 16:29:32 -07001398 !GetInstructionFlags(abs_offset).IsOpcode())) {
jeffhaod5347e02012-03-22 17:25:05 -07001399 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid branch target " << offset << " (-> "
Elliott Hughes398f64b2012-03-26 18:05:48 -07001400 << reinterpret_cast<void*>(abs_offset) << ") at "
1401 << reinterpret_cast<void*>(cur_offset);
Ian Rogersd81871c2011-10-03 13:57:23 -07001402 return false;
1403 }
Andreas Gampe51de69e2019-04-19 15:14:14 -07001404 GetModifiableInstructionFlags(abs_offset).SetBranchTarget();
Ian Rogersd81871c2011-10-03 13:57:23 -07001405 return true;
1406}
1407
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001408template <bool kVerifierDebug>
1409bool MethodVerifier<kVerifierDebug>::GetBranchOffset(uint32_t cur_offset,
1410 int32_t* pOffset,
1411 bool* pConditional,
1412 bool* selfOkay) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001413 const uint16_t* insns = code_item_accessor_.Insns() + cur_offset;
Ian Rogersd81871c2011-10-03 13:57:23 -07001414 *pConditional = false;
1415 *selfOkay = false;
jeffhaoba5ebb92011-08-25 17:24:37 -07001416 switch (*insns & 0xff) {
1417 case Instruction::GOTO:
1418 *pOffset = ((int16_t) *insns) >> 8;
jeffhaoba5ebb92011-08-25 17:24:37 -07001419 break;
1420 case Instruction::GOTO_32:
1421 *pOffset = insns[1] | (((uint32_t) insns[2]) << 16);
jeffhaoba5ebb92011-08-25 17:24:37 -07001422 *selfOkay = true;
1423 break;
1424 case Instruction::GOTO_16:
1425 *pOffset = (int16_t) insns[1];
jeffhaoba5ebb92011-08-25 17:24:37 -07001426 break;
1427 case Instruction::IF_EQ:
1428 case Instruction::IF_NE:
1429 case Instruction::IF_LT:
1430 case Instruction::IF_GE:
1431 case Instruction::IF_GT:
1432 case Instruction::IF_LE:
1433 case Instruction::IF_EQZ:
1434 case Instruction::IF_NEZ:
1435 case Instruction::IF_LTZ:
1436 case Instruction::IF_GEZ:
1437 case Instruction::IF_GTZ:
1438 case Instruction::IF_LEZ:
1439 *pOffset = (int16_t) insns[1];
1440 *pConditional = true;
jeffhaoba5ebb92011-08-25 17:24:37 -07001441 break;
1442 default:
1443 return false;
jeffhaoba5ebb92011-08-25 17:24:37 -07001444 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001445 return true;
1446}
1447
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001448template <bool kVerifierDebug>
1449bool MethodVerifier<kVerifierDebug>::CheckSwitchTargets(uint32_t cur_offset) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001450 const uint32_t insn_count = code_item_accessor_.InsnsSizeInCodeUnits();
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001451 DCHECK_LT(cur_offset, insn_count);
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001452 const uint16_t* insns = code_item_accessor_.Insns() + cur_offset;
jeffhaoba5ebb92011-08-25 17:24:37 -07001453 /* make sure the start of the switch is in range */
Andreas Gampe53de99c2015-08-17 13:43:55 -07001454 int32_t switch_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
Andreas Gampe29e81422017-05-15 16:29:32 -07001455 if (UNLIKELY(static_cast<int32_t>(cur_offset) + switch_offset < 0 ||
1456 cur_offset + switch_offset + 2 > insn_count)) {
jeffhaod5347e02012-03-22 17:25:05 -07001457 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch start: at " << cur_offset
Brian Carlstrom93c33962013-07-26 10:37:43 -07001458 << ", switch offset " << switch_offset
1459 << ", count " << insn_count;
jeffhaoba5ebb92011-08-25 17:24:37 -07001460 return false;
1461 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001462 /* offset to switch table is a relative branch-style offset */
Ian Rogersd81871c2011-10-03 13:57:23 -07001463 const uint16_t* switch_insns = insns + switch_offset;
Andreas Gampe57c47582015-07-01 22:05:59 -07001464 // Make sure the table is at an even dex pc, that is, 32-bit aligned.
Andreas Gampe29e81422017-05-15 16:29:32 -07001465 if (UNLIKELY(!IsAligned<4>(switch_insns))) {
jeffhaod5347e02012-03-22 17:25:05 -07001466 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unaligned switch table: at " << cur_offset
1467 << ", switch offset " << switch_offset;
jeffhaoba5ebb92011-08-25 17:24:37 -07001468 return false;
1469 }
Andreas Gampe57c47582015-07-01 22:05:59 -07001470 // Make sure the switch data is marked as an opcode. This ensures that it was reached when
1471 // traversing the code item linearly. It is an approximation for a by-spec padding value.
Andreas Gampe29e81422017-05-15 16:29:32 -07001472 if (UNLIKELY(!GetInstructionFlags(cur_offset + switch_offset).IsOpcode())) {
Andreas Gampe57c47582015-07-01 22:05:59 -07001473 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "switch table at " << cur_offset
1474 << ", switch offset " << switch_offset
1475 << " not correctly visited, probably bad padding.";
1476 return false;
1477 }
1478
David Brazdil5469d342015-09-25 16:57:53 +01001479 bool is_packed_switch = (*insns & 0xff) == Instruction::PACKED_SWITCH;
1480
Ian Rogersd81871c2011-10-03 13:57:23 -07001481 uint32_t switch_count = switch_insns[1];
David Brazdil5469d342015-09-25 16:57:53 +01001482 int32_t targets_offset;
Ian Rogersd81871c2011-10-03 13:57:23 -07001483 uint16_t expected_signature;
David Brazdil5469d342015-09-25 16:57:53 +01001484 if (is_packed_switch) {
jeffhaoba5ebb92011-08-25 17:24:37 -07001485 /* 0=sig, 1=count, 2/3=firstKey */
1486 targets_offset = 4;
jeffhaoba5ebb92011-08-25 17:24:37 -07001487 expected_signature = Instruction::kPackedSwitchSignature;
1488 } else {
1489 /* 0=sig, 1=count, 2..count*2 = keys */
jeffhaoba5ebb92011-08-25 17:24:37 -07001490 targets_offset = 2 + 2 * switch_count;
1491 expected_signature = Instruction::kSparseSwitchSignature;
1492 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001493 uint32_t table_size = targets_offset + switch_count * 2;
Andreas Gampe29e81422017-05-15 16:29:32 -07001494 if (UNLIKELY(switch_insns[0] != expected_signature)) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07001495 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
1496 << StringPrintf("wrong signature for switch table (%x, wanted %x)",
1497 switch_insns[0], expected_signature);
jeffhaoba5ebb92011-08-25 17:24:37 -07001498 return false;
1499 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001500 /* make sure the end of the switch is in range */
Andreas Gampe29e81422017-05-15 16:29:32 -07001501 if (UNLIKELY(cur_offset + switch_offset + table_size > (uint32_t) insn_count)) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07001502 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch end: at " << cur_offset
1503 << ", switch offset " << switch_offset
1504 << ", end " << (cur_offset + switch_offset + table_size)
jeffhaod5347e02012-03-22 17:25:05 -07001505 << ", count " << insn_count;
jeffhaoba5ebb92011-08-25 17:24:37 -07001506 return false;
1507 }
David Brazdil5469d342015-09-25 16:57:53 +01001508
1509 constexpr int32_t keys_offset = 2;
1510 if (switch_count > 1) {
1511 if (is_packed_switch) {
1512 /* for a packed switch, verify that keys do not overflow int32 */
1513 int32_t first_key = switch_insns[keys_offset] | (switch_insns[keys_offset + 1] << 16);
1514 int32_t max_first_key =
1515 std::numeric_limits<int32_t>::max() - (static_cast<int32_t>(switch_count) - 1);
Andreas Gampe29e81422017-05-15 16:29:32 -07001516 if (UNLIKELY(first_key > max_first_key)) {
David Brazdil5469d342015-09-25 16:57:53 +01001517 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid packed switch: first_key=" << first_key
1518 << ", switch_count=" << switch_count;
jeffhaoba5ebb92011-08-25 17:24:37 -07001519 return false;
1520 }
David Brazdil5469d342015-09-25 16:57:53 +01001521 } else {
1522 /* for a sparse switch, verify the keys are in ascending order */
1523 int32_t last_key = switch_insns[keys_offset] | (switch_insns[keys_offset + 1] << 16);
1524 for (uint32_t targ = 1; targ < switch_count; targ++) {
1525 int32_t key =
1526 static_cast<int32_t>(switch_insns[keys_offset + targ * 2]) |
1527 static_cast<int32_t>(switch_insns[keys_offset + targ * 2 + 1] << 16);
Andreas Gampe29e81422017-05-15 16:29:32 -07001528 if (UNLIKELY(key <= last_key)) {
David Brazdil5469d342015-09-25 16:57:53 +01001529 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid sparse switch: last key=" << last_key
1530 << ", this=" << key;
1531 return false;
1532 }
1533 last_key = key;
1534 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001535 }
1536 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001537 /* verify each switch target */
Ian Rogersd81871c2011-10-03 13:57:23 -07001538 for (uint32_t targ = 0; targ < switch_count; targ++) {
Andreas Gampe53de99c2015-08-17 13:43:55 -07001539 int32_t offset = static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) |
1540 static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16);
Ian Rogersd81871c2011-10-03 13:57:23 -07001541 int32_t abs_offset = cur_offset + offset;
Andreas Gampe29e81422017-05-15 16:29:32 -07001542 if (UNLIKELY(abs_offset < 0 ||
1543 abs_offset >= static_cast<int32_t>(insn_count) ||
1544 !GetInstructionFlags(abs_offset).IsOpcode())) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07001545 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid switch target " << offset
1546 << " (-> " << reinterpret_cast<void*>(abs_offset) << ") at "
1547 << reinterpret_cast<void*>(cur_offset)
1548 << "[" << targ << "]";
jeffhaoba5ebb92011-08-25 17:24:37 -07001549 return false;
1550 }
Andreas Gampe51de69e2019-04-19 15:14:14 -07001551 GetModifiableInstructionFlags(abs_offset).SetBranchTarget();
Ian Rogersd81871c2011-10-03 13:57:23 -07001552 }
1553 return true;
1554}
1555
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001556template <bool kVerifierDebug>
1557bool MethodVerifier<kVerifierDebug>::CheckVarArgRegs(uint32_t vA, uint32_t arg[]) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001558 uint16_t registers_size = code_item_accessor_.RegistersSize();
Ian Rogersd81871c2011-10-03 13:57:23 -07001559 for (uint32_t idx = 0; idx < vA; idx++) {
Andreas Gampe29e81422017-05-15 16:29:32 -07001560 if (UNLIKELY(arg[idx] >= registers_size)) {
jeffhaod5347e02012-03-22 17:25:05 -07001561 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid reg index (" << arg[idx]
1562 << ") in non-range invoke (>= " << registers_size << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07001563 return false;
1564 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001565 }
1566
1567 return true;
1568}
1569
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001570template <bool kVerifierDebug>
1571bool MethodVerifier<kVerifierDebug>::CheckVarArgRangeRegs(uint32_t vA, uint32_t vC) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001572 uint16_t registers_size = code_item_accessor_.RegistersSize();
Ian Rogersd81871c2011-10-03 13:57:23 -07001573 // vA/vC are unsigned 8-bit/16-bit quantities for /range instructions, so there's no risk of
1574 // integer overflow when adding them here.
Andreas Gampe29e81422017-05-15 16:29:32 -07001575 if (UNLIKELY(vA + vC > registers_size)) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07001576 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid reg index " << vA << "+" << vC
1577 << " in range invoke (> " << registers_size << ")";
jeffhaoba5ebb92011-08-25 17:24:37 -07001578 return false;
1579 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001580 return true;
1581}
1582
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001583template <bool kVerifierDebug>
1584bool MethodVerifier<kVerifierDebug>::VerifyCodeFlow() {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001585 const uint16_t registers_size = code_item_accessor_.RegistersSize();
jeffhaobdb76512011-09-07 11:43:16 -07001586
Ian Rogersd81871c2011-10-03 13:57:23 -07001587 /* Create and initialize table holding register status */
Alex Lighte48fd0b2019-05-20 10:04:44 -07001588 reg_table_.Init(fill_register_lines_ ? kTrackRegsAll : kTrackCompilerInterestPoints,
Brian Carlstrom93c33962013-07-26 10:37:43 -07001589 insn_flags_.get(),
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001590 code_item_accessor_.InsnsSizeInCodeUnits(),
Brian Carlstrom93c33962013-07-26 10:37:43 -07001591 registers_size,
Andreas Gamped09c0592019-04-19 15:44:05 -07001592 allocator_,
1593 GetRegTypeCache());
Sameer Abu Asal02c42232013-04-30 12:09:45 -07001594
Andreas Gamped09c0592019-04-19 15:44:05 -07001595 work_line_.reset(RegisterLine::Create(registers_size, allocator_, GetRegTypeCache()));
1596 saved_line_.reset(RegisterLine::Create(registers_size, allocator_, GetRegTypeCache()));
jeffhaobdb76512011-09-07 11:43:16 -07001597
Ian Rogersd81871c2011-10-03 13:57:23 -07001598 /* Initialize register types of method arguments. */
1599 if (!SetTypesFromSignature()) {
Ian Rogersad0b3a32012-04-16 14:50:24 -07001600 DCHECK_NE(failures_.size(), 0U);
1601 std::string prepend("Bad signature in ");
David Sehr709b0702016-10-13 09:12:37 -07001602 prepend += dex_file_->PrettyMethod(dex_method_idx_);
Ian Rogersad0b3a32012-04-16 14:50:24 -07001603 PrependToLastFailMessage(prepend);
Ian Rogersd81871c2011-10-03 13:57:23 -07001604 return false;
1605 }
Andreas Gamped5ad72f2015-06-26 17:33:47 -07001606 // We may have a runtime failure here, clear.
1607 have_pending_runtime_throw_failure_ = false;
1608
Ian Rogersd81871c2011-10-03 13:57:23 -07001609 /* Perform code flow verification. */
1610 if (!CodeFlowVerifyMethod()) {
Ian Rogersad0b3a32012-04-16 14:50:24 -07001611 DCHECK_NE(failures_.size(), 0U);
Ian Rogersd81871c2011-10-03 13:57:23 -07001612 return false;
jeffhaobdb76512011-09-07 11:43:16 -07001613 }
jeffhaobdb76512011-09-07 11:43:16 -07001614 return true;
1615}
1616
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001617template <bool kVerifierDebug>
1618std::ostream& MethodVerifier<kVerifierDebug>::DumpFailures(std::ostream& os) {
Ian Rogersad0b3a32012-04-16 14:50:24 -07001619 DCHECK_EQ(failures_.size(), failure_messages_.size());
Jeff Hao4137f482013-11-22 11:44:57 -08001620 for (size_t i = 0; i < failures_.size(); ++i) {
1621 os << failure_messages_[i]->str() << "\n";
Ian Rogersad0b3a32012-04-16 14:50:24 -07001622 }
1623 return os;
1624}
1625
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001626template <bool kVerifierDebug>
1627void MethodVerifier<kVerifierDebug>::Dump(VariableIndentationOutputStream* vios) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001628 if (!code_item_accessor_.HasCodeItem()) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001629 vios->Stream() << "Native method\n";
Ian Rogersd81871c2011-10-03 13:57:23 -07001630 return;
jeffhaobdb76512011-09-07 11:43:16 -07001631 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001632 {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001633 vios->Stream() << "Register Types:\n";
1634 ScopedIndentation indent1(vios);
1635 reg_types_.Dump(vios->Stream());
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001636 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001637 vios->Stream() << "Dumping instructions and register lines:\n";
1638 ScopedIndentation indent1(vios);
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07001639
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001640 for (const DexInstructionPcPair& inst : code_item_accessor_) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001641 const size_t dex_pc = inst.DexPc();
Andreas Gampe077d9db2018-01-19 18:54:14 -08001642
1643 // Might be asked to dump before the table is initialized.
1644 if (reg_table_.IsInitialized()) {
1645 RegisterLine* reg_line = reg_table_.GetLine(dex_pc);
1646 if (reg_line != nullptr) {
1647 vios->Stream() << reg_line->Dump(this) << "\n";
1648 }
jeffhaobdb76512011-09-07 11:43:16 -07001649 }
Andreas Gampe077d9db2018-01-19 18:54:14 -08001650
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001651 vios->Stream()
Mathieu Chartierde40d472015-10-15 17:47:48 -07001652 << StringPrintf("0x%04zx", dex_pc) << ": " << GetInstructionFlags(dex_pc).ToString() << " ";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001653 const bool kDumpHexOfInstruction = false;
1654 if (kDumpHexOfInstruction) {
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001655 vios->Stream() << inst->DumpHex(5) << " ";
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001656 }
Vladimir Marko8f1e08a2015-06-26 12:06:30 +01001657 vios->Stream() << inst->DumpString(dex_file_) << "\n";
jeffhaoba5ebb92011-08-25 17:24:37 -07001658 }
jeffhaobdb76512011-09-07 11:43:16 -07001659}
1660
Ian Rogersd81871c2011-10-03 13:57:23 -07001661static bool IsPrimitiveDescriptor(char descriptor) {
1662 switch (descriptor) {
jeffhaobdb76512011-09-07 11:43:16 -07001663 case 'I':
1664 case 'C':
1665 case 'S':
1666 case 'B':
1667 case 'Z':
jeffhaobdb76512011-09-07 11:43:16 -07001668 case 'F':
1669 case 'D':
1670 case 'J':
Ian Rogersd81871c2011-10-03 13:57:23 -07001671 return true;
jeffhaobdb76512011-09-07 11:43:16 -07001672 default:
1673 return false;
1674 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001675}
1676
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001677template <bool kVerifierDebug>
1678bool MethodVerifier<kVerifierDebug>::SetTypesFromSignature() {
Ian Rogersd81871c2011-10-03 13:57:23 -07001679 RegisterLine* reg_line = reg_table_.GetLine(0);
Andreas Gampeef0b1a12015-06-19 20:37:46 -07001680
1681 // Should have been verified earlier.
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001682 DCHECK_GE(code_item_accessor_.RegistersSize(), code_item_accessor_.InsSize());
Andreas Gampeef0b1a12015-06-19 20:37:46 -07001683
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001684 uint32_t arg_start = code_item_accessor_.RegistersSize() - code_item_accessor_.InsSize();
1685 size_t expected_args = code_item_accessor_.InsSize(); /* long/double count as two */
jeffhaobdb76512011-09-07 11:43:16 -07001686
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001687 // Include the "this" pointer.
Ian Rogersd81871c2011-10-03 13:57:23 -07001688 size_t cur_arg = 0;
Ian Rogersad0b3a32012-04-16 14:50:24 -07001689 if (!IsStatic()) {
Andreas Gampeef0b1a12015-06-19 20:37:46 -07001690 if (expected_args == 0) {
1691 // Expect at least a receiver.
1692 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected 0 args, but method is not static";
1693 return false;
1694 }
1695
Ian Rogersd81871c2011-10-03 13:57:23 -07001696 // If this is a constructor for a class other than java.lang.Object, mark the first ("this")
1697 // argument as uninitialized. This restricts field access until the superclass constructor is
1698 // called.
Ian Rogersd8f69b02014-09-10 21:43:52 +00001699 const RegType& declaring_class = GetDeclaringClass();
Andreas Gampef10b6e12015-08-12 10:48:12 -07001700 if (IsConstructor()) {
1701 if (declaring_class.IsJavaLangObject()) {
1702 // "this" is implicitly initialized.
1703 reg_line->SetThisInitialized();
Andreas Gampead238ce2015-08-24 21:13:08 -07001704 reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, declaring_class);
Andreas Gampef10b6e12015-08-12 10:48:12 -07001705 } else {
Andreas Gampead238ce2015-08-24 21:13:08 -07001706 reg_line->SetRegisterType<LockOp::kClear>(
1707 this,
1708 arg_start + cur_arg,
1709 reg_types_.UninitializedThisArgument(declaring_class));
Andreas Gampef10b6e12015-08-12 10:48:12 -07001710 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001711 } else {
Andreas Gampead238ce2015-08-24 21:13:08 -07001712 reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, declaring_class);
jeffhaobdb76512011-09-07 11:43:16 -07001713 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001714 cur_arg++;
jeffhaobdb76512011-09-07 11:43:16 -07001715 }
1716
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001717 const dex::ProtoId& proto_id =
Ian Rogers2bcb4a42012-11-08 10:39:18 -08001718 dex_file_->GetMethodPrototype(dex_file_->GetMethodId(dex_method_idx_));
Ian Rogers0571d352011-11-03 19:51:38 -07001719 DexFileParameterIterator iterator(*dex_file_, proto_id);
Ian Rogersd81871c2011-10-03 13:57:23 -07001720
1721 for (; iterator.HasNext(); iterator.Next()) {
1722 const char* descriptor = iterator.GetDescriptor();
Ian Rogers7b078e82014-09-10 14:44:24 -07001723 if (descriptor == nullptr) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001724 LOG(FATAL) << "Null descriptor";
1725 }
1726 if (cur_arg >= expected_args) {
jeffhaod5347e02012-03-22 17:25:05 -07001727 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args
1728 << " args, found more (" << descriptor << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07001729 return false;
1730 }
1731 switch (descriptor[0]) {
1732 case 'L':
1733 case '[':
1734 // We assume that reference arguments are initialized. The only way it could be otherwise
1735 // (assuming the caller was verified) is if the current method is <init>, but in that case
1736 // it's effectively considered initialized the instant we reach here (in the sense that we
1737 // can return without doing anything or call virtual methods).
1738 {
Andreas Gampe98be1a92017-08-28 08:25:45 -07001739 // Note: don't check access. No error would be thrown for declaring or passing an
1740 // inaccessible class. Only actual accesses to fields or methods will.
1741 const RegType& reg_type = ResolveClass<CheckAccess::kNo>(iterator.GetTypeIdx());
Sebastien Hertz2ed76f92014-04-22 17:11:08 +02001742 if (!reg_type.IsNonZeroReferenceTypes()) {
1743 DCHECK(HasFailures());
1744 return false;
1745 }
Andreas Gampead238ce2015-08-24 21:13:08 -07001746 reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07001747 }
1748 break;
1749 case 'Z':
Andreas Gampead238ce2015-08-24 21:13:08 -07001750 reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Boolean());
Ian Rogersd81871c2011-10-03 13:57:23 -07001751 break;
1752 case 'C':
Andreas Gampead238ce2015-08-24 21:13:08 -07001753 reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Char());
Ian Rogersd81871c2011-10-03 13:57:23 -07001754 break;
1755 case 'B':
Andreas Gampead238ce2015-08-24 21:13:08 -07001756 reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Byte());
Ian Rogersd81871c2011-10-03 13:57:23 -07001757 break;
1758 case 'I':
Andreas Gampead238ce2015-08-24 21:13:08 -07001759 reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Integer());
Ian Rogersd81871c2011-10-03 13:57:23 -07001760 break;
1761 case 'S':
Andreas Gampead238ce2015-08-24 21:13:08 -07001762 reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Short());
Ian Rogersd81871c2011-10-03 13:57:23 -07001763 break;
1764 case 'F':
Andreas Gampead238ce2015-08-24 21:13:08 -07001765 reg_line->SetRegisterType<LockOp::kClear>(this, arg_start + cur_arg, reg_types_.Float());
Ian Rogersd81871c2011-10-03 13:57:23 -07001766 break;
1767 case 'J':
1768 case 'D': {
Andreas Gampe77cd4d62014-06-19 17:29:48 -07001769 if (cur_arg + 1 >= expected_args) {
1770 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args
1771 << " args, found more (" << descriptor << ")";
1772 return false;
1773 }
1774
Ian Rogers7b078e82014-09-10 14:44:24 -07001775 const RegType* lo_half;
1776 const RegType* hi_half;
1777 if (descriptor[0] == 'J') {
1778 lo_half = &reg_types_.LongLo();
1779 hi_half = &reg_types_.LongHi();
1780 } else {
1781 lo_half = &reg_types_.DoubleLo();
1782 hi_half = &reg_types_.DoubleHi();
1783 }
1784 reg_line->SetRegisterTypeWide(this, arg_start + cur_arg, *lo_half, *hi_half);
Ian Rogersd81871c2011-10-03 13:57:23 -07001785 cur_arg++;
1786 break;
1787 }
1788 default:
Brian Carlstrom93c33962013-07-26 10:37:43 -07001789 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected signature type char '"
1790 << descriptor << "'";
Ian Rogersd81871c2011-10-03 13:57:23 -07001791 return false;
1792 }
1793 cur_arg++;
1794 }
1795 if (cur_arg != expected_args) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07001796 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected " << expected_args
1797 << " arguments, found " << cur_arg;
Ian Rogersd81871c2011-10-03 13:57:23 -07001798 return false;
1799 }
1800 const char* descriptor = dex_file_->GetReturnTypeDescriptor(proto_id);
1801 // Validate return type. We don't do the type lookup; just want to make sure that it has the right
1802 // format. Only major difference from the method argument format is that 'V' is supported.
1803 bool result;
1804 if (IsPrimitiveDescriptor(descriptor[0]) || descriptor[0] == 'V') {
1805 result = descriptor[1] == '\0';
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001806 } else if (descriptor[0] == '[') { // single/multi-dimensional array of object/primitive
Ian Rogersd81871c2011-10-03 13:57:23 -07001807 size_t i = 0;
1808 do {
1809 i++;
1810 } while (descriptor[i] == '['); // process leading [
1811 if (descriptor[i] == 'L') { // object array
1812 do {
1813 i++; // find closing ;
1814 } while (descriptor[i] != ';' && descriptor[i] != '\0');
1815 result = descriptor[i] == ';';
1816 } else { // primitive array
1817 result = IsPrimitiveDescriptor(descriptor[i]) && descriptor[i + 1] == '\0';
1818 }
1819 } else if (descriptor[0] == 'L') {
1820 // could be more thorough here, but shouldn't be required
1821 size_t i = 0;
1822 do {
1823 i++;
1824 } while (descriptor[i] != ';' && descriptor[i] != '\0');
1825 result = descriptor[i] == ';';
1826 } else {
1827 result = false;
1828 }
1829 if (!result) {
jeffhaod5347e02012-03-22 17:25:05 -07001830 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected char in return type descriptor '"
1831 << descriptor << "'";
Ian Rogersd81871c2011-10-03 13:57:23 -07001832 }
1833 return result;
jeffhaobdb76512011-09-07 11:43:16 -07001834}
1835
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001836template <bool kVerifierDebug>
1837bool MethodVerifier<kVerifierDebug>::CodeFlowVerifyMethod() {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001838 const uint16_t* insns = code_item_accessor_.Insns();
1839 const uint32_t insns_size = code_item_accessor_.InsnsSizeInCodeUnits();
jeffhaoba5ebb92011-08-25 17:24:37 -07001840
jeffhaobdb76512011-09-07 11:43:16 -07001841 /* Begin by marking the first instruction as "changed". */
Andreas Gampe51de69e2019-04-19 15:14:14 -07001842 GetModifiableInstructionFlags(0).SetChanged();
Ian Rogersd81871c2011-10-03 13:57:23 -07001843 uint32_t start_guess = 0;
jeffhaoba5ebb92011-08-25 17:24:37 -07001844
jeffhaobdb76512011-09-07 11:43:16 -07001845 /* Continue until no instructions are marked "changed". */
1846 while (true) {
Mathieu Chartier4306ef82014-12-19 18:41:47 -08001847 if (allow_thread_suspension_) {
1848 self_->AllowThreadSuspension();
1849 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001850 // Find the first marked one. Use "start_guess" as a way to find one quickly.
1851 uint32_t insn_idx = start_guess;
1852 for (; insn_idx < insns_size; insn_idx++) {
Mathieu Chartierde40d472015-10-15 17:47:48 -07001853 if (GetInstructionFlags(insn_idx).IsChanged())
jeffhaobdb76512011-09-07 11:43:16 -07001854 break;
1855 }
jeffhaobdb76512011-09-07 11:43:16 -07001856 if (insn_idx == insns_size) {
1857 if (start_guess != 0) {
1858 /* try again, starting from the top */
1859 start_guess = 0;
1860 continue;
1861 } else {
1862 /* all flags are clear */
1863 break;
1864 }
1865 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001866 // We carry the working set of registers from instruction to instruction. If this address can
1867 // be the target of a branch (or throw) instruction, or if we're skipping around chasing
1868 // "changed" flags, we need to load the set of registers from the table.
1869 // Because we always prefer to continue on to the next instruction, we should never have a
1870 // situation where we have a stray "changed" flag set on an instruction that isn't a branch
1871 // target.
1872 work_insn_idx_ = insn_idx;
Mathieu Chartierde40d472015-10-15 17:47:48 -07001873 if (GetInstructionFlags(insn_idx).IsBranchTarget()) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001874 work_line_->CopyFromLine(reg_table_.GetLine(insn_idx));
Ian Rogersebbdd872014-07-07 23:53:08 -07001875 } else if (kIsDebugBuild) {
jeffhaobdb76512011-09-07 11:43:16 -07001876 /*
1877 * Sanity check: retrieve the stored register line (assuming
1878 * a full table) and make sure it actually matches.
1879 */
Ian Rogersd81871c2011-10-03 13:57:23 -07001880 RegisterLine* register_line = reg_table_.GetLine(insn_idx);
Ian Rogers7b078e82014-09-10 14:44:24 -07001881 if (register_line != nullptr) {
Ian Rogersd81871c2011-10-03 13:57:23 -07001882 if (work_line_->CompareLine(register_line) != 0) {
Andreas Gampe4a57d5f2019-04-03 12:31:18 -07001883 Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
1884 LOG(FATAL_WITHOUT_ABORT) << info_messages_.str();
David Sehr709b0702016-10-13 09:12:37 -07001885 LOG(FATAL) << "work_line diverged in " << dex_file_->PrettyMethod(dex_method_idx_)
Elliott Hughesc073b072012-05-24 19:29:17 -07001886 << "@" << reinterpret_cast<void*>(work_insn_idx_) << "\n"
Ian Rogers7b078e82014-09-10 14:44:24 -07001887 << " work_line=" << work_line_->Dump(this) << "\n"
1888 << " expected=" << register_line->Dump(this);
Ian Rogersd81871c2011-10-03 13:57:23 -07001889 }
jeffhaobdb76512011-09-07 11:43:16 -07001890 }
jeffhaobdb76512011-09-07 11:43:16 -07001891 }
Ian Rogersd81871c2011-10-03 13:57:23 -07001892 if (!CodeFlowVerifyInstruction(&start_guess)) {
David Sehr709b0702016-10-13 09:12:37 -07001893 std::string prepend(dex_file_->PrettyMethod(dex_method_idx_));
Ian Rogersad0b3a32012-04-16 14:50:24 -07001894 prepend += " failed to verify: ";
1895 PrependToLastFailMessage(prepend);
jeffhaoba5ebb92011-08-25 17:24:37 -07001896 return false;
1897 }
jeffhaobdb76512011-09-07 11:43:16 -07001898 /* Clear "changed" and mark as visited. */
Andreas Gampe51de69e2019-04-19 15:14:14 -07001899 GetModifiableInstructionFlags(insn_idx).SetVisited();
1900 GetModifiableInstructionFlags(insn_idx).ClearChanged();
jeffhaobdb76512011-09-07 11:43:16 -07001901 }
jeffhaoba5ebb92011-08-25 17:24:37 -07001902
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001903 if (kVerifierDebug) {
jeffhaobdb76512011-09-07 11:43:16 -07001904 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001905 * Scan for dead code. There's nothing "evil" about dead code
jeffhaobdb76512011-09-07 11:43:16 -07001906 * (besides the wasted space), but it indicates a flaw somewhere
1907 * down the line, possibly in the verifier.
1908 *
1909 * If we've substituted "always throw" instructions into the stream,
1910 * we are almost certainly going to have some dead code.
1911 */
1912 int dead_start = -1;
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07001913
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001914 for (const DexInstructionPcPair& inst : code_item_accessor_) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001915 const uint32_t insn_idx = inst.DexPc();
jeffhaobdb76512011-09-07 11:43:16 -07001916 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07001917 * Switch-statement data doesn't get "visited" by scanner. It
jeffhaobdb76512011-09-07 11:43:16 -07001918 * may or may not be preceded by a padding NOP (for alignment).
1919 */
1920 if (insns[insn_idx] == Instruction::kPackedSwitchSignature ||
1921 insns[insn_idx] == Instruction::kSparseSwitchSignature ||
1922 insns[insn_idx] == Instruction::kArrayDataSignature ||
Elliott Hughes380aaa72012-07-09 14:33:15 -07001923 (insns[insn_idx] == Instruction::NOP && (insn_idx + 1 < insns_size) &&
jeffhaobdb76512011-09-07 11:43:16 -07001924 (insns[insn_idx + 1] == Instruction::kPackedSwitchSignature ||
1925 insns[insn_idx + 1] == Instruction::kSparseSwitchSignature ||
1926 insns[insn_idx + 1] == Instruction::kArrayDataSignature))) {
Andreas Gampe51de69e2019-04-19 15:14:14 -07001927 GetModifiableInstructionFlags(insn_idx).SetVisited();
jeffhaobdb76512011-09-07 11:43:16 -07001928 }
1929
Mathieu Chartierde40d472015-10-15 17:47:48 -07001930 if (!GetInstructionFlags(insn_idx).IsVisited()) {
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07001931 if (dead_start < 0) {
jeffhaobdb76512011-09-07 11:43:16 -07001932 dead_start = insn_idx;
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07001933 }
jeffhaobdb76512011-09-07 11:43:16 -07001934 } else if (dead_start >= 0) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07001935 LogVerifyInfo() << "dead code " << reinterpret_cast<void*>(dead_start)
1936 << "-" << reinterpret_cast<void*>(insn_idx - 1);
jeffhaobdb76512011-09-07 11:43:16 -07001937 dead_start = -1;
1938 }
1939 }
1940 if (dead_start >= 0) {
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07001941 LogVerifyInfo()
1942 << "dead code " << reinterpret_cast<void*>(dead_start)
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08001943 << "-" << reinterpret_cast<void*>(code_item_accessor_.InsnsSizeInCodeUnits() - 1);
jeffhaoba5ebb92011-08-25 17:24:37 -07001944 }
Ian Rogersc9e463c2013-06-05 16:52:26 -07001945 // To dump the state of the verify after a method, do something like:
David Sehr709b0702016-10-13 09:12:37 -07001946 // if (dex_file_->PrettyMethod(dex_method_idx_) ==
Ian Rogersc9e463c2013-06-05 16:52:26 -07001947 // "boolean java.lang.String.equals(java.lang.Object)") {
1948 // LOG(INFO) << info_messages_.str();
1949 // }
jeffhaoba5ebb92011-08-25 17:24:37 -07001950 }
jeffhaobdb76512011-09-07 11:43:16 -07001951 return true;
1952}
1953
Andreas Gampe68df3202015-06-22 11:35:46 -07001954// Returns the index of the first final instance field of the given class, or kDexNoIndex if there
1955// is no such field.
Andreas Gampea5b09a62016-11-17 15:21:22 -08001956static uint32_t GetFirstFinalInstanceFieldIndex(const DexFile& dex_file, dex::TypeIndex type_idx) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001957 const dex::ClassDef* class_def = dex_file.FindClassDef(type_idx);
Andreas Gampe68df3202015-06-22 11:35:46 -07001958 DCHECK(class_def != nullptr);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07001959 ClassAccessor accessor(dex_file, *class_def);
1960 for (const ClassAccessor::Field& field : accessor.GetInstanceFields()) {
1961 if (field.IsFinal()) {
1962 return field.GetIndex();
Andreas Gampe68df3202015-06-22 11:35:46 -07001963 }
Andreas Gampe68df3202015-06-22 11:35:46 -07001964 }
Andreas Gampee2abbc62017-09-15 11:59:26 -07001965 return dex::kDexNoIndex;
Andreas Gampe68df3202015-06-22 11:35:46 -07001966}
1967
Andreas Gampea727e372015-08-25 09:22:37 -07001968// Setup a register line for the given return instruction.
Andreas Gampe99db7bb2019-04-19 23:05:47 -07001969template <bool kVerifierDebug>
1970static void AdjustReturnLine(MethodVerifier<kVerifierDebug>* verifier,
Andreas Gampea727e372015-08-25 09:22:37 -07001971 const Instruction* ret_inst,
1972 RegisterLine* line) {
1973 Instruction::Code opcode = ret_inst->Opcode();
1974
1975 switch (opcode) {
1976 case Instruction::RETURN_VOID:
1977 case Instruction::RETURN_VOID_NO_BARRIER:
Andreas Gampe51de69e2019-04-19 15:14:14 -07001978 if (verifier->IsInstanceConstructor()) {
1979 // Before we mark all regs as conflicts, check that we don't have an uninitialized this.
1980 line->CheckConstructorReturn(verifier);
1981 }
1982 line->MarkAllRegistersAsConflicts(verifier);
Andreas Gampea727e372015-08-25 09:22:37 -07001983 break;
1984
1985 case Instruction::RETURN:
1986 case Instruction::RETURN_OBJECT:
1987 line->MarkAllRegistersAsConflictsExcept(verifier, ret_inst->VRegA_11x());
1988 break;
1989
1990 case Instruction::RETURN_WIDE:
1991 line->MarkAllRegistersAsConflictsExceptWide(verifier, ret_inst->VRegA_11x());
1992 break;
1993
1994 default:
1995 LOG(FATAL) << "Unknown return opcode " << opcode;
1996 UNREACHABLE();
1997 }
1998}
1999
Andreas Gampe99db7bb2019-04-19 23:05:47 -07002000template <bool kVerifierDebug>
2001bool MethodVerifier<kVerifierDebug>::CodeFlowVerifyInstruction(uint32_t* start_guess) {
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002002 // If we're doing FindLocksAtDexPc, check whether we're at the dex pc we care about.
2003 // We want the state _before_ the instruction, for the case where the dex pc we're
2004 // interested in is itself a monitor-enter instruction (which is a likely place
2005 // for a thread to be suspended).
Ian Rogers7b078e82014-09-10 14:44:24 -07002006 if (monitor_enter_dex_pcs_ != nullptr && work_insn_idx_ == interesting_dex_pc_) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002007 monitor_enter_dex_pcs_->clear(); // The new work line is more accurate than the previous one.
Andreas Gampeaaf0d382017-11-27 14:10:21 -08002008
2009 std::map<uint32_t, DexLockInfo> depth_to_lock_info;
2010 auto collector = [&](uint32_t dex_reg, uint32_t depth) {
2011 auto insert_pair = depth_to_lock_info.emplace(depth, DexLockInfo(depth));
2012 auto it = insert_pair.first;
2013 auto set_insert_pair = it->second.dex_registers.insert(dex_reg);
2014 DCHECK(set_insert_pair.second);
2015 };
2016 work_line_->IterateRegToLockDepths(collector);
2017 for (auto& pair : depth_to_lock_info) {
2018 monitor_enter_dex_pcs_->push_back(pair.second);
2019 // Map depth to dex PC.
2020 (*monitor_enter_dex_pcs_)[monitor_enter_dex_pcs_->size() - 1].dex_pc =
2021 work_line_->GetMonitorEnterDexPc(pair.second.dex_pc);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002022 }
2023 }
2024
jeffhaobdb76512011-09-07 11:43:16 -07002025 /*
2026 * Once we finish decoding the instruction, we need to figure out where
jeffhaod1f0fde2011-09-08 17:25:33 -07002027 * we can go from here. There are three possible ways to transfer
jeffhaobdb76512011-09-07 11:43:16 -07002028 * control to another statement:
2029 *
jeffhaod1f0fde2011-09-08 17:25:33 -07002030 * (1) Continue to the next instruction. Applies to all but
jeffhaobdb76512011-09-07 11:43:16 -07002031 * unconditional branches, method returns, and exception throws.
jeffhaod1f0fde2011-09-08 17:25:33 -07002032 * (2) Branch to one or more possible locations. Applies to branches
jeffhaobdb76512011-09-07 11:43:16 -07002033 * and switch statements.
jeffhaod1f0fde2011-09-08 17:25:33 -07002034 * (3) Exception handlers. Applies to any instruction that can
jeffhaobdb76512011-09-07 11:43:16 -07002035 * throw an exception that is handled by an encompassing "try"
2036 * block.
2037 *
2038 * We can also return, in which case there is no successor instruction
2039 * from this point.
2040 *
Elliott Hughesadb8c672012-03-06 16:49:32 -08002041 * The behavior can be determined from the opcode flags.
jeffhaobdb76512011-09-07 11:43:16 -07002042 */
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08002043 const uint16_t* insns = code_item_accessor_.Insns() + work_insn_idx_;
Ian Rogersd81871c2011-10-03 13:57:23 -07002044 const Instruction* inst = Instruction::At(insns);
Ian Rogersa75a0132012-09-28 11:41:42 -07002045 int opcode_flags = Instruction::FlagsOf(inst->Opcode());
jeffhaobdb76512011-09-07 11:43:16 -07002046
jeffhaobdb76512011-09-07 11:43:16 -07002047 int32_t branch_target = 0;
jeffhaobdb76512011-09-07 11:43:16 -07002048 bool just_set_result = false;
Andreas Gampe99db7bb2019-04-19 23:05:47 -07002049 if (kVerifierDebug) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002050 // Generate processing back trace to debug verifier
Andreas Gampe2ad6cce2019-04-11 16:17:39 -07002051 LogVerifyInfo() << "Processing " << inst->DumpString(dex_file_) << std::endl
2052 << work_line_->Dump(this);
Ian Rogersd81871c2011-10-03 13:57:23 -07002053 }
jeffhaobdb76512011-09-07 11:43:16 -07002054
2055 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002056 * Make a copy of the previous register state. If the instruction
jeffhaobdb76512011-09-07 11:43:16 -07002057 * can throw an exception, we will copy/merge this into the "catch"
2058 * address rather than work_line, because we don't want the result
2059 * from the "successful" code path (e.g. a check-cast that "improves"
2060 * a type) to be visible to the exception handler.
2061 */
Ian Rogers776ac1f2012-04-13 23:36:36 -07002062 if ((opcode_flags & Instruction::kThrow) != 0 && CurrentInsnFlags()->IsInTry()) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002063 saved_line_->CopyFromLine(work_line_.get());
Ian Rogers1ff3c982014-08-12 02:30:58 -07002064 } else if (kIsDebugBuild) {
Ian Rogersd81871c2011-10-03 13:57:23 -07002065 saved_line_->FillWithGarbage();
jeffhaobdb76512011-09-07 11:43:16 -07002066 }
Andreas Gamped12e7822015-06-25 10:26:40 -07002067 DCHECK(!have_pending_runtime_throw_failure_); // Per-instruction flag, should not be set here.
jeffhaobdb76512011-09-07 11:43:16 -07002068
Dragos Sbirlea980d16b2013-06-04 15:01:40 -07002069
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002070 // We need to ensure the work line is consistent while performing validation. When we spot a
2071 // peephole pattern we compute a new line for either the fallthrough instruction or the
2072 // branch target.
Mathieu Chartier361e04a2016-02-16 14:06:35 -08002073 RegisterLineArenaUniquePtr branch_line;
2074 RegisterLineArenaUniquePtr fallthrough_line;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002075
Sebastien Hertz5243e912013-05-21 10:55:07 +02002076 switch (inst->Opcode()) {
jeffhaobdb76512011-09-07 11:43:16 -07002077 case Instruction::NOP:
2078 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002079 * A "pure" NOP has no effect on anything. Data tables start with
jeffhaobdb76512011-09-07 11:43:16 -07002080 * a signature that looks like a NOP; if we see one of these in
2081 * the course of executing code then we have a problem.
2082 */
Sebastien Hertz5243e912013-05-21 10:55:07 +02002083 if (inst->VRegA_10x() != 0) {
jeffhaod5347e02012-03-22 17:25:05 -07002084 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "encountered data table in instruction stream";
jeffhaobdb76512011-09-07 11:43:16 -07002085 }
2086 break;
2087
2088 case Instruction::MOVE:
Ian Rogers7b078e82014-09-10 14:44:24 -07002089 work_line_->CopyRegister1(this, inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategory1nr);
Sebastien Hertz5243e912013-05-21 10:55:07 +02002090 break;
jeffhaobdb76512011-09-07 11:43:16 -07002091 case Instruction::MOVE_FROM16:
Ian Rogers7b078e82014-09-10 14:44:24 -07002092 work_line_->CopyRegister1(this, inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategory1nr);
Sebastien Hertz5243e912013-05-21 10:55:07 +02002093 break;
jeffhaobdb76512011-09-07 11:43:16 -07002094 case Instruction::MOVE_16:
Ian Rogers7b078e82014-09-10 14:44:24 -07002095 work_line_->CopyRegister1(this, inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategory1nr);
jeffhaobdb76512011-09-07 11:43:16 -07002096 break;
2097 case Instruction::MOVE_WIDE:
Ian Rogers7b078e82014-09-10 14:44:24 -07002098 work_line_->CopyRegister2(this, inst->VRegA_12x(), inst->VRegB_12x());
Sebastien Hertz5243e912013-05-21 10:55:07 +02002099 break;
jeffhaobdb76512011-09-07 11:43:16 -07002100 case Instruction::MOVE_WIDE_FROM16:
Ian Rogers7b078e82014-09-10 14:44:24 -07002101 work_line_->CopyRegister2(this, inst->VRegA_22x(), inst->VRegB_22x());
Sebastien Hertz5243e912013-05-21 10:55:07 +02002102 break;
jeffhaobdb76512011-09-07 11:43:16 -07002103 case Instruction::MOVE_WIDE_16:
Ian Rogers7b078e82014-09-10 14:44:24 -07002104 work_line_->CopyRegister2(this, inst->VRegA_32x(), inst->VRegB_32x());
jeffhaobdb76512011-09-07 11:43:16 -07002105 break;
2106 case Instruction::MOVE_OBJECT:
Ian Rogers7b078e82014-09-10 14:44:24 -07002107 work_line_->CopyRegister1(this, inst->VRegA_12x(), inst->VRegB_12x(), kTypeCategoryRef);
Sebastien Hertz5243e912013-05-21 10:55:07 +02002108 break;
jeffhaobdb76512011-09-07 11:43:16 -07002109 case Instruction::MOVE_OBJECT_FROM16:
Ian Rogers7b078e82014-09-10 14:44:24 -07002110 work_line_->CopyRegister1(this, inst->VRegA_22x(), inst->VRegB_22x(), kTypeCategoryRef);
Sebastien Hertz5243e912013-05-21 10:55:07 +02002111 break;
jeffhaobdb76512011-09-07 11:43:16 -07002112 case Instruction::MOVE_OBJECT_16:
Ian Rogers7b078e82014-09-10 14:44:24 -07002113 work_line_->CopyRegister1(this, inst->VRegA_32x(), inst->VRegB_32x(), kTypeCategoryRef);
jeffhaobdb76512011-09-07 11:43:16 -07002114 break;
2115
2116 /*
2117 * The move-result instructions copy data out of a "pseudo-register"
jeffhaod1f0fde2011-09-08 17:25:33 -07002118 * with the results from the last method invocation. In practice we
jeffhaobdb76512011-09-07 11:43:16 -07002119 * might want to hold the result in an actual CPU register, so the
2120 * Dalvik spec requires that these only appear immediately after an
2121 * invoke or filled-new-array.
2122 *
jeffhaod1f0fde2011-09-08 17:25:33 -07002123 * These calls invalidate the "result" register. (This is now
jeffhaobdb76512011-09-07 11:43:16 -07002124 * redundant with the reset done below, but it can make the debug info
2125 * easier to read in some cases.)
2126 */
2127 case Instruction::MOVE_RESULT:
Ian Rogers7b078e82014-09-10 14:44:24 -07002128 work_line_->CopyResultRegister1(this, inst->VRegA_11x(), false);
jeffhaobdb76512011-09-07 11:43:16 -07002129 break;
2130 case Instruction::MOVE_RESULT_WIDE:
Ian Rogers7b078e82014-09-10 14:44:24 -07002131 work_line_->CopyResultRegister2(this, inst->VRegA_11x());
jeffhaobdb76512011-09-07 11:43:16 -07002132 break;
2133 case Instruction::MOVE_RESULT_OBJECT:
Ian Rogers7b078e82014-09-10 14:44:24 -07002134 work_line_->CopyResultRegister1(this, inst->VRegA_11x(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002135 break;
2136
Ian Rogersd81871c2011-10-03 13:57:23 -07002137 case Instruction::MOVE_EXCEPTION: {
Sebastien Hertz270a0e12015-01-16 19:49:09 +01002138 // We do not allow MOVE_EXCEPTION as the first instruction in a method. This is a simple case
2139 // where one entrypoint to the catch block is not actually an exception path.
2140 if (work_insn_idx_ == 0) {
2141 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "move-exception at pc 0x0";
2142 break;
2143 }
jeffhaobdb76512011-09-07 11:43:16 -07002144 /*
jeffhao60f83e32012-02-13 17:16:30 -08002145 * This statement can only appear as the first instruction in an exception handler. We verify
2146 * that as part of extracting the exception type from the catch block list.
jeffhaobdb76512011-09-07 11:43:16 -07002147 */
Ian Rogersd8f69b02014-09-10 21:43:52 +00002148 const RegType& res_type = GetCaughtExceptionType();
Andreas Gampead238ce2015-08-24 21:13:08 -07002149 work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_11x(), res_type);
jeffhaobdb76512011-09-07 11:43:16 -07002150 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002151 }
jeffhaobdb76512011-09-07 11:43:16 -07002152 case Instruction::RETURN_VOID:
Andreas Gampef10b6e12015-08-12 10:48:12 -07002153 if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) {
Ian Rogersad0b3a32012-04-16 14:50:24 -07002154 if (!GetMethodReturnType().IsConflict()) {
jeffhaod5347e02012-03-22 17:25:05 -07002155 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void not expected";
Ian Rogersd81871c2011-10-03 13:57:23 -07002156 }
jeffhaobdb76512011-09-07 11:43:16 -07002157 }
2158 break;
2159 case Instruction::RETURN:
Andreas Gampef10b6e12015-08-12 10:48:12 -07002160 if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) {
jeffhaobdb76512011-09-07 11:43:16 -07002161 /* check the method signature */
Ian Rogersd8f69b02014-09-10 21:43:52 +00002162 const RegType& return_type = GetMethodReturnType();
Ian Rogersd81871c2011-10-03 13:57:23 -07002163 if (!return_type.IsCategory1Types()) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07002164 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected non-category 1 return type "
2165 << return_type;
Ian Rogersd81871c2011-10-03 13:57:23 -07002166 } else {
2167 // Compilers may generate synthetic functions that write byte values into boolean fields.
2168 // Also, it may use integer values for boolean, byte, short, and character return types.
Sebastien Hertz5243e912013-05-21 10:55:07 +02002169 const uint32_t vregA = inst->VRegA_11x();
Ian Rogers7b078e82014-09-10 14:44:24 -07002170 const RegType& src_type = work_line_->GetRegisterType(this, vregA);
Ian Rogersd81871c2011-10-03 13:57:23 -07002171 bool use_src = ((return_type.IsBoolean() && src_type.IsByte()) ||
2172 ((return_type.IsBoolean() || return_type.IsByte() ||
2173 return_type.IsShort() || return_type.IsChar()) &&
2174 src_type.IsInteger()));
2175 /* check the register contents */
Ian Rogersad0b3a32012-04-16 14:50:24 -07002176 bool success =
Ian Rogers7b078e82014-09-10 14:44:24 -07002177 work_line_->VerifyRegisterType(this, vregA, use_src ? src_type : return_type);
Ian Rogersad0b3a32012-04-16 14:50:24 -07002178 if (!success) {
Sebastien Hertz5243e912013-05-21 10:55:07 +02002179 AppendToLastFailMessage(StringPrintf(" return-1nr on invalid register v%d", vregA));
Ian Rogersd81871c2011-10-03 13:57:23 -07002180 }
jeffhaobdb76512011-09-07 11:43:16 -07002181 }
2182 }
2183 break;
2184 case Instruction::RETURN_WIDE:
Andreas Gampef10b6e12015-08-12 10:48:12 -07002185 if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) {
jeffhaobdb76512011-09-07 11:43:16 -07002186 /* check the method signature */
Ian Rogersd8f69b02014-09-10 21:43:52 +00002187 const RegType& return_type = GetMethodReturnType();
Ian Rogersd81871c2011-10-03 13:57:23 -07002188 if (!return_type.IsCategory2Types()) {
jeffhaod5347e02012-03-22 17:25:05 -07002189 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-wide not expected";
Ian Rogersd81871c2011-10-03 13:57:23 -07002190 } else {
2191 /* check the register contents */
Sebastien Hertz5243e912013-05-21 10:55:07 +02002192 const uint32_t vregA = inst->VRegA_11x();
Ian Rogers7b078e82014-09-10 14:44:24 -07002193 bool success = work_line_->VerifyRegisterType(this, vregA, return_type);
Ian Rogersad0b3a32012-04-16 14:50:24 -07002194 if (!success) {
Sebastien Hertz5243e912013-05-21 10:55:07 +02002195 AppendToLastFailMessage(StringPrintf(" return-wide on invalid register v%d", vregA));
Ian Rogersd81871c2011-10-03 13:57:23 -07002196 }
jeffhaobdb76512011-09-07 11:43:16 -07002197 }
2198 }
2199 break;
2200 case Instruction::RETURN_OBJECT:
Andreas Gampef10b6e12015-08-12 10:48:12 -07002201 if (!IsInstanceConstructor() || work_line_->CheckConstructorReturn(this)) {
Ian Rogersd8f69b02014-09-10 21:43:52 +00002202 const RegType& return_type = GetMethodReturnType();
Ian Rogersd81871c2011-10-03 13:57:23 -07002203 if (!return_type.IsReferenceTypes()) {
jeffhaod5347e02012-03-22 17:25:05 -07002204 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-object not expected";
Ian Rogersd81871c2011-10-03 13:57:23 -07002205 } else {
2206 /* return_type is the *expected* return type, not register value */
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08002207 DCHECK(!return_type.IsZeroOrNull());
Ian Rogersd81871c2011-10-03 13:57:23 -07002208 DCHECK(!return_type.IsUninitializedReference());
Sebastien Hertz5243e912013-05-21 10:55:07 +02002209 const uint32_t vregA = inst->VRegA_11x();
Ian Rogers7b078e82014-09-10 14:44:24 -07002210 const RegType& reg_type = work_line_->GetRegisterType(this, vregA);
Andreas Gampea32210c2015-06-24 10:26:13 -07002211 // Disallow returning undefined, conflict & uninitialized values and verify that the
2212 // reference in vAA is an instance of the "return_type."
2213 if (reg_type.IsUndefined()) {
2214 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning undefined register";
2215 } else if (reg_type.IsConflict()) {
2216 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning register with conflict";
2217 } else if (reg_type.IsUninitializedTypes()) {
David Brazdil68b5c0b2016-01-19 14:25:29 +00002218 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning uninitialized object '"
Brian Carlstrom93c33962013-07-26 10:37:43 -07002219 << reg_type << "'";
Andreas Gampea4c98f22015-11-06 16:24:49 -08002220 } else if (!reg_type.IsReferenceTypes()) {
2221 // We really do expect a reference here.
2222 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-object returns a non-reference type "
2223 << reg_type;
David Brazdilca3c8c32016-09-06 14:04:48 +01002224 } else if (!return_type.IsAssignableFrom(reg_type, this)) {
Jeff Haoa3faaf42013-09-03 19:07:00 -07002225 if (reg_type.IsUnresolvedTypes() || return_type.IsUnresolvedTypes()) {
2226 Fail(VERIFY_ERROR_NO_CLASS) << " can't resolve returned type '" << return_type
2227 << "' or '" << reg_type << "'";
2228 } else {
Andreas Gampe16f149c2015-03-23 10:10:20 -07002229 bool soft_error = false;
2230 // Check whether arrays are involved. They will show a valid class status, even
2231 // if their components are erroneous.
2232 if (reg_type.IsArrayTypes() && return_type.IsArrayTypes()) {
David Brazdilca3c8c32016-09-06 14:04:48 +01002233 return_type.CanAssignArray(reg_type, reg_types_, class_loader_, this, &soft_error);
Andreas Gampe16f149c2015-03-23 10:10:20 -07002234 if (soft_error) {
2235 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "array with erroneous component type: "
2236 << reg_type << " vs " << return_type;
2237 }
2238 }
2239
2240 if (!soft_error) {
2241 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "returning '" << reg_type
2242 << "', but expected from declaration '" << return_type << "'";
2243 }
Jeff Haoa3faaf42013-09-03 19:07:00 -07002244 }
jeffhaobdb76512011-09-07 11:43:16 -07002245 }
2246 }
2247 }
2248 break;
2249
Ian Rogers2fa6b2e2012-10-17 00:10:17 -07002250 /* could be boolean, int, float, or a null reference */
Sebastien Hertz5243e912013-05-21 10:55:07 +02002251 case Instruction::CONST_4: {
2252 int32_t val = static_cast<int32_t>(inst->VRegB_11n() << 28) >> 28;
Andreas Gampead238ce2015-08-24 21:13:08 -07002253 work_line_->SetRegisterType<LockOp::kClear>(
2254 this, inst->VRegA_11n(), DetermineCat1Constant(val, need_precise_constants_));
Ian Rogers2fa6b2e2012-10-17 00:10:17 -07002255 break;
Sebastien Hertz5243e912013-05-21 10:55:07 +02002256 }
2257 case Instruction::CONST_16: {
2258 int16_t val = static_cast<int16_t>(inst->VRegB_21s());
Andreas Gampead238ce2015-08-24 21:13:08 -07002259 work_line_->SetRegisterType<LockOp::kClear>(
2260 this, inst->VRegA_21s(), DetermineCat1Constant(val, need_precise_constants_));
Ian Rogers2fa6b2e2012-10-17 00:10:17 -07002261 break;
Sebastien Hertz5243e912013-05-21 10:55:07 +02002262 }
Sebastien Hertz849600b2013-12-20 10:28:08 +01002263 case Instruction::CONST: {
2264 int32_t val = inst->VRegB_31i();
Andreas Gampead238ce2015-08-24 21:13:08 -07002265 work_line_->SetRegisterType<LockOp::kClear>(
2266 this, inst->VRegA_31i(), DetermineCat1Constant(val, need_precise_constants_));
jeffhaobdb76512011-09-07 11:43:16 -07002267 break;
Sebastien Hertz849600b2013-12-20 10:28:08 +01002268 }
2269 case Instruction::CONST_HIGH16: {
2270 int32_t val = static_cast<int32_t>(inst->VRegB_21h() << 16);
Andreas Gampead238ce2015-08-24 21:13:08 -07002271 work_line_->SetRegisterType<LockOp::kClear>(
2272 this, inst->VRegA_21h(), DetermineCat1Constant(val, need_precise_constants_));
jeffhaobdb76512011-09-07 11:43:16 -07002273 break;
Sebastien Hertz849600b2013-12-20 10:28:08 +01002274 }
jeffhaobdb76512011-09-07 11:43:16 -07002275 /* could be long or double; resolved upon use */
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002276 case Instruction::CONST_WIDE_16: {
Sebastien Hertz5243e912013-05-21 10:55:07 +02002277 int64_t val = static_cast<int16_t>(inst->VRegB_21s());
Ian Rogersd8f69b02014-09-10 21:43:52 +00002278 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true);
2279 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true);
Ian Rogers7b078e82014-09-10 14:44:24 -07002280 work_line_->SetRegisterTypeWide(this, inst->VRegA_21s(), lo, hi);
jeffhaobdb76512011-09-07 11:43:16 -07002281 break;
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002282 }
2283 case Instruction::CONST_WIDE_32: {
Sebastien Hertz5243e912013-05-21 10:55:07 +02002284 int64_t val = static_cast<int32_t>(inst->VRegB_31i());
Ian Rogersd8f69b02014-09-10 21:43:52 +00002285 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true);
2286 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true);
Ian Rogers7b078e82014-09-10 14:44:24 -07002287 work_line_->SetRegisterTypeWide(this, inst->VRegA_31i(), lo, hi);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002288 break;
2289 }
2290 case Instruction::CONST_WIDE: {
Sebastien Hertz5243e912013-05-21 10:55:07 +02002291 int64_t val = inst->VRegB_51l();
Ian Rogersd8f69b02014-09-10 21:43:52 +00002292 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true);
2293 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true);
Ian Rogers7b078e82014-09-10 14:44:24 -07002294 work_line_->SetRegisterTypeWide(this, inst->VRegA_51l(), lo, hi);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002295 break;
2296 }
2297 case Instruction::CONST_WIDE_HIGH16: {
Sebastien Hertz5243e912013-05-21 10:55:07 +02002298 int64_t val = static_cast<uint64_t>(inst->VRegB_21h()) << 48;
Ian Rogersd8f69b02014-09-10 21:43:52 +00002299 const RegType& lo = reg_types_.FromCat2ConstLo(static_cast<int32_t>(val), true);
2300 const RegType& hi = reg_types_.FromCat2ConstHi(static_cast<int32_t>(val >> 32), true);
Ian Rogers7b078e82014-09-10 14:44:24 -07002301 work_line_->SetRegisterTypeWide(this, inst->VRegA_21h(), lo, hi);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002302 break;
2303 }
jeffhaobdb76512011-09-07 11:43:16 -07002304 case Instruction::CONST_STRING:
Andreas Gampead238ce2015-08-24 21:13:08 -07002305 work_line_->SetRegisterType<LockOp::kClear>(
2306 this, inst->VRegA_21c(), reg_types_.JavaLangString());
Sebastien Hertz5243e912013-05-21 10:55:07 +02002307 break;
jeffhaobdb76512011-09-07 11:43:16 -07002308 case Instruction::CONST_STRING_JUMBO:
Andreas Gampead238ce2015-08-24 21:13:08 -07002309 work_line_->SetRegisterType<LockOp::kClear>(
2310 this, inst->VRegA_31c(), reg_types_.JavaLangString());
jeffhaobdb76512011-09-07 11:43:16 -07002311 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002312 case Instruction::CONST_CLASS: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002313 // Get type from instruction if unresolved then we need an access check
2314 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
Andreas Gampe98be1a92017-08-28 08:25:45 -07002315 const RegType& res_type = ResolveClass<CheckAccess::kYes>(dex::TypeIndex(inst->VRegB_21c()));
Ian Rogersad0b3a32012-04-16 14:50:24 -07002316 // Register holds class, ie its type is class, on error it will hold Conflict.
Andreas Gampead238ce2015-08-24 21:13:08 -07002317 work_line_->SetRegisterType<LockOp::kClear>(
2318 this, inst->VRegA_21c(), res_type.IsConflict() ? res_type
2319 : reg_types_.JavaLangClass());
jeffhaobdb76512011-09-07 11:43:16 -07002320 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002321 }
Orion Hodson2e599942017-09-22 16:17:41 +01002322 case Instruction::CONST_METHOD_HANDLE:
2323 work_line_->SetRegisterType<LockOp::kClear>(
2324 this, inst->VRegA_21c(), reg_types_.JavaLangInvokeMethodHandle());
Orion Hodson2e599942017-09-22 16:17:41 +01002325 break;
2326 case Instruction::CONST_METHOD_TYPE:
2327 work_line_->SetRegisterType<LockOp::kClear>(
2328 this, inst->VRegA_21c(), reg_types_.JavaLangInvokeMethodType());
Orion Hodson2e599942017-09-22 16:17:41 +01002329 break;
jeffhaobdb76512011-09-07 11:43:16 -07002330 case Instruction::MONITOR_ENTER:
Ian Rogers7b078e82014-09-10 14:44:24 -07002331 work_line_->PushMonitor(this, inst->VRegA_11x(), work_insn_idx_);
Andreas Gampec1474102015-08-18 08:57:44 -07002332 // Check whether the previous instruction is a move-object with vAA as a source, creating
2333 // untracked lock aliasing.
Mathieu Chartierde40d472015-10-15 17:47:48 -07002334 if (0 != work_insn_idx_ && !GetInstructionFlags(work_insn_idx_).IsBranchTarget()) {
Andreas Gampec1474102015-08-18 08:57:44 -07002335 uint32_t prev_idx = work_insn_idx_ - 1;
Mathieu Chartierde40d472015-10-15 17:47:48 -07002336 while (0 != prev_idx && !GetInstructionFlags(prev_idx).IsOpcode()) {
Andreas Gampec1474102015-08-18 08:57:44 -07002337 prev_idx--;
2338 }
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08002339 const Instruction& prev_inst = code_item_accessor_.InstructionAt(prev_idx);
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07002340 switch (prev_inst.Opcode()) {
Andreas Gampec1474102015-08-18 08:57:44 -07002341 case Instruction::MOVE_OBJECT:
2342 case Instruction::MOVE_OBJECT_16:
2343 case Instruction::MOVE_OBJECT_FROM16:
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07002344 if (prev_inst.VRegB() == inst->VRegA_11x()) {
Andreas Gampec1474102015-08-18 08:57:44 -07002345 // Redo the copy. This won't change the register types, but update the lock status
2346 // for the aliased register.
2347 work_line_->CopyRegister1(this,
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07002348 prev_inst.VRegA(),
2349 prev_inst.VRegB(),
Andreas Gampec1474102015-08-18 08:57:44 -07002350 kTypeCategoryRef);
2351 }
2352 break;
2353
Alexey Grebenkince750492018-05-31 23:42:20 +03002354 // Catch a case of register aliasing when two registers are linked to the same
2355 // java.lang.Class object via two consequent const-class instructions immediately
2356 // preceding monitor-enter called on one of those registers.
2357 case Instruction::CONST_CLASS: {
2358 // Get the second previous instruction.
2359 if (prev_idx == 0 || GetInstructionFlags(prev_idx).IsBranchTarget()) {
2360 break;
2361 }
2362 prev_idx--;
2363 while (0 != prev_idx && !GetInstructionFlags(prev_idx).IsOpcode()) {
2364 prev_idx--;
2365 }
2366 const Instruction& prev2_inst = code_item_accessor_.InstructionAt(prev_idx);
2367
2368 // Match the pattern "const-class; const-class; monitor-enter;"
2369 if (prev2_inst.Opcode() != Instruction::CONST_CLASS) {
2370 break;
2371 }
2372
2373 // Ensure both const-classes are called for the same type_idx.
2374 if (prev_inst.VRegB_21c() != prev2_inst.VRegB_21c()) {
2375 break;
2376 }
2377
2378 // Update the lock status for the aliased register.
2379 if (prev_inst.VRegA() == inst->VRegA_11x()) {
2380 work_line_->CopyRegister1(this,
2381 prev2_inst.VRegA(),
2382 inst->VRegA_11x(),
2383 kTypeCategoryRef);
2384 } else if (prev2_inst.VRegA() == inst->VRegA_11x()) {
2385 work_line_->CopyRegister1(this,
2386 prev_inst.VRegA(),
2387 inst->VRegA_11x(),
2388 kTypeCategoryRef);
2389 }
2390 break;
2391 }
2392
Andreas Gampec1474102015-08-18 08:57:44 -07002393 default: // Other instruction types ignored.
2394 break;
2395 }
2396 }
jeffhaobdb76512011-09-07 11:43:16 -07002397 break;
2398 case Instruction::MONITOR_EXIT:
2399 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07002400 * monitor-exit instructions are odd. They can throw exceptions,
jeffhaobdb76512011-09-07 11:43:16 -07002401 * but when they do they act as if they succeeded and the PC is
jeffhaod1f0fde2011-09-08 17:25:33 -07002402 * pointing to the following instruction. (This behavior goes back
jeffhaobdb76512011-09-07 11:43:16 -07002403 * to the need to handle asynchronous exceptions, a now-deprecated
2404 * feature that Dalvik doesn't support.)
2405 *
jeffhaod1f0fde2011-09-08 17:25:33 -07002406 * In practice we don't need to worry about this. The only
jeffhaobdb76512011-09-07 11:43:16 -07002407 * exceptions that can be thrown from monitor-exit are for a
jeffhaod1f0fde2011-09-08 17:25:33 -07002408 * null reference and -exit without a matching -enter. If the
jeffhaobdb76512011-09-07 11:43:16 -07002409 * structured locking checks are working, the former would have
2410 * failed on the -enter instruction, and the latter is impossible.
2411 *
2412 * This is fortunate, because issue 3221411 prevents us from
2413 * chasing the "can throw" path when monitor verification is
jeffhaod1f0fde2011-09-08 17:25:33 -07002414 * enabled. If we can fully verify the locking we can ignore
jeffhaobdb76512011-09-07 11:43:16 -07002415 * some catch blocks (which will show up as "dead" code when
2416 * we skip them here); if we can't, then the code path could be
2417 * "live" so we still need to check it.
2418 */
Elliott Hughesadb8c672012-03-06 16:49:32 -08002419 opcode_flags &= ~Instruction::kThrow;
Ian Rogers7b078e82014-09-10 14:44:24 -07002420 work_line_->PopMonitor(this, inst->VRegA_11x());
jeffhaobdb76512011-09-07 11:43:16 -07002421 break;
Ian Rogers28ad40d2011-10-27 15:19:26 -07002422 case Instruction::CHECK_CAST:
Ian Rogersd81871c2011-10-03 13:57:23 -07002423 case Instruction::INSTANCE_OF: {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002424 /*
2425 * If this instruction succeeds, we will "downcast" register vA to the type in vB. (This
2426 * could be a "upcast" -- not expected, so we don't try to address it.)
2427 *
2428 * If it fails, an exception is thrown, which we deal with later by ignoring the update to
Elliott Hughesadb8c672012-03-06 16:49:32 -08002429 * dec_insn.vA when branching to a handler.
Ian Rogers28ad40d2011-10-27 15:19:26 -07002430 */
Sebastien Hertz5243e912013-05-21 10:55:07 +02002431 const bool is_checkcast = (inst->Opcode() == Instruction::CHECK_CAST);
Andreas Gampea5b09a62016-11-17 15:21:22 -08002432 const dex::TypeIndex type_idx((is_checkcast) ? inst->VRegB_21c() : inst->VRegC_22c());
Andreas Gampe98be1a92017-08-28 08:25:45 -07002433 const RegType& res_type = ResolveClass<CheckAccess::kYes>(type_idx);
Ian Rogersad0b3a32012-04-16 14:50:24 -07002434 if (res_type.IsConflict()) {
Andreas Gampe00633eb2014-07-17 16:13:35 -07002435 // If this is a primitive type, fail HARD.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00002436 ObjPtr<mirror::Class> klass = Runtime::Current()->GetClassLinker()->LookupResolvedType(
2437 type_idx, dex_cache_.Get(), class_loader_.Get());
Andreas Gampe00633eb2014-07-17 16:13:35 -07002438 if (klass != nullptr && klass->IsPrimitive()) {
2439 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "using primitive type "
2440 << dex_file_->StringByTypeIdx(type_idx) << " in instanceof in "
2441 << GetDeclaringClass();
2442 break;
2443 }
2444
Ian Rogersad0b3a32012-04-16 14:50:24 -07002445 DCHECK_NE(failures_.size(), 0U);
2446 if (!is_checkcast) {
Andreas Gampead238ce2015-08-24 21:13:08 -07002447 work_line_->SetRegisterType<LockOp::kClear>(this,
2448 inst->VRegA_22c(),
2449 reg_types_.Boolean());
Ian Rogersad0b3a32012-04-16 14:50:24 -07002450 }
2451 break; // bad class
Ian Rogers9f1ab122011-12-12 08:52:43 -08002452 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002453 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
Sebastien Hertz5243e912013-05-21 10:55:07 +02002454 uint32_t orig_type_reg = (is_checkcast) ? inst->VRegA_21c() : inst->VRegB_22c();
Ian Rogers7b078e82014-09-10 14:44:24 -07002455 const RegType& orig_type = work_line_->GetRegisterType(this, orig_type_reg);
Ian Rogers28ad40d2011-10-27 15:19:26 -07002456 if (!res_type.IsNonZeroReferenceTypes()) {
Sebastien Hertz5243e912013-05-21 10:55:07 +02002457 if (is_checkcast) {
2458 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on unexpected class " << res_type;
2459 } else {
2460 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on unexpected class " << res_type;
2461 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002462 } else if (!orig_type.IsReferenceTypes()) {
Sebastien Hertz5243e912013-05-21 10:55:07 +02002463 if (is_checkcast) {
2464 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on non-reference in v" << orig_type_reg;
2465 } else {
2466 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on non-reference in v" << orig_type_reg;
2467 }
David Brazdil68b5c0b2016-01-19 14:25:29 +00002468 } else if (orig_type.IsUninitializedTypes()) {
2469 if (is_checkcast) {
2470 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "check-cast on uninitialized reference in v"
2471 << orig_type_reg;
2472 } else {
2473 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance-of on uninitialized reference in v"
2474 << orig_type_reg;
2475 }
jeffhao2a8a90e2011-09-26 14:25:31 -07002476 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002477 if (is_checkcast) {
Andreas Gampead238ce2015-08-24 21:13:08 -07002478 work_line_->SetRegisterType<LockOp::kKeep>(this, inst->VRegA_21c(), res_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07002479 } else {
Andreas Gampead238ce2015-08-24 21:13:08 -07002480 work_line_->SetRegisterType<LockOp::kClear>(this,
2481 inst->VRegA_22c(),
2482 reg_types_.Boolean());
jeffhaobdb76512011-09-07 11:43:16 -07002483 }
jeffhaobdb76512011-09-07 11:43:16 -07002484 }
jeffhao2a8a90e2011-09-26 14:25:31 -07002485 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002486 }
2487 case Instruction::ARRAY_LENGTH: {
Ian Rogers7b078e82014-09-10 14:44:24 -07002488 const RegType& res_type = work_line_->GetRegisterType(this, inst->VRegB_12x());
Ian Rogers28ad40d2011-10-27 15:19:26 -07002489 if (res_type.IsReferenceTypes()) {
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08002490 if (!res_type.IsArrayTypes() && !res_type.IsZeroOrNull()) {
2491 // ie not an array or null
jeffhaod5347e02012-03-22 17:25:05 -07002492 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type;
Ian Rogersd81871c2011-10-03 13:57:23 -07002493 } else {
Andreas Gampead238ce2015-08-24 21:13:08 -07002494 work_line_->SetRegisterType<LockOp::kClear>(this,
2495 inst->VRegA_12x(),
2496 reg_types_.Integer());
Ian Rogersd81871c2011-10-03 13:57:23 -07002497 }
Andreas Gampe65c9db82014-07-28 13:14:34 -07002498 } else {
2499 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-length on non-array " << res_type;
Ian Rogersd81871c2011-10-03 13:57:23 -07002500 }
2501 break;
2502 }
2503 case Instruction::NEW_INSTANCE: {
Andreas Gampe98be1a92017-08-28 08:25:45 -07002504 const RegType& res_type = ResolveClass<CheckAccess::kYes>(dex::TypeIndex(inst->VRegB_21c()));
Ian Rogersad0b3a32012-04-16 14:50:24 -07002505 if (res_type.IsConflict()) {
2506 DCHECK_NE(failures_.size(), 0U);
2507 break; // bad class
jeffhao8cd6dda2012-02-22 10:15:34 -08002508 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002509 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
2510 // can't create an instance of an interface or abstract class */
2511 if (!res_type.IsInstantiableTypes()) {
2512 Fail(VERIFY_ERROR_INSTANTIATION)
2513 << "new-instance on primitive, interface or abstract class" << res_type;
Ian Rogers08f753d2012-08-24 14:35:25 -07002514 // Soft failure so carry on to set register type.
Ian Rogersd81871c2011-10-03 13:57:23 -07002515 }
Ian Rogersd8f69b02014-09-10 21:43:52 +00002516 const RegType& uninit_type = reg_types_.Uninitialized(res_type, work_insn_idx_);
Ian Rogers08f753d2012-08-24 14:35:25 -07002517 // Any registers holding previous allocations from this address that have not yet been
2518 // initialized must be marked invalid.
Ian Rogers7b078e82014-09-10 14:44:24 -07002519 work_line_->MarkUninitRefsAsInvalid(this, uninit_type);
Ian Rogers08f753d2012-08-24 14:35:25 -07002520 // add the new uninitialized reference to the register state
Andreas Gampead238ce2015-08-24 21:13:08 -07002521 work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_21c(), uninit_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07002522 break;
2523 }
Ian Rogers0c4a5062012-02-03 15:18:59 -08002524 case Instruction::NEW_ARRAY:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002525 VerifyNewArray(inst, false, false);
jeffhaobdb76512011-09-07 11:43:16 -07002526 break;
2527 case Instruction::FILLED_NEW_ARRAY:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002528 VerifyNewArray(inst, true, false);
Ian Rogers0c4a5062012-02-03 15:18:59 -08002529 just_set_result = true; // Filled new array sets result register
jeffhaobdb76512011-09-07 11:43:16 -07002530 break;
Ian Rogers0c4a5062012-02-03 15:18:59 -08002531 case Instruction::FILLED_NEW_ARRAY_RANGE:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002532 VerifyNewArray(inst, true, true);
Ian Rogers0c4a5062012-02-03 15:18:59 -08002533 just_set_result = true; // Filled new array range sets result register
2534 break;
jeffhaobdb76512011-09-07 11:43:16 -07002535 case Instruction::CMPL_FLOAT:
2536 case Instruction::CMPG_FLOAT:
Ian Rogers7b078e82014-09-10 14:44:24 -07002537 if (!work_line_->VerifyRegisterType(this, inst->VRegB_23x(), reg_types_.Float())) {
jeffhao457cc512012-02-02 16:55:13 -08002538 break;
2539 }
Ian Rogers7b078e82014-09-10 14:44:24 -07002540 if (!work_line_->VerifyRegisterType(this, inst->VRegC_23x(), reg_types_.Float())) {
jeffhao457cc512012-02-02 16:55:13 -08002541 break;
2542 }
Andreas Gampead238ce2015-08-24 21:13:08 -07002543 work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002544 break;
2545 case Instruction::CMPL_DOUBLE:
2546 case Instruction::CMPG_DOUBLE:
Ian Rogers7b078e82014-09-10 14:44:24 -07002547 if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegB_23x(), reg_types_.DoubleLo(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002548 reg_types_.DoubleHi())) {
jeffhao457cc512012-02-02 16:55:13 -08002549 break;
2550 }
Ian Rogers7b078e82014-09-10 14:44:24 -07002551 if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegC_23x(), reg_types_.DoubleLo(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002552 reg_types_.DoubleHi())) {
jeffhao457cc512012-02-02 16:55:13 -08002553 break;
2554 }
Andreas Gampead238ce2015-08-24 21:13:08 -07002555 work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002556 break;
2557 case Instruction::CMP_LONG:
Ian Rogers7b078e82014-09-10 14:44:24 -07002558 if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegB_23x(), reg_types_.LongLo(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002559 reg_types_.LongHi())) {
jeffhao457cc512012-02-02 16:55:13 -08002560 break;
2561 }
Ian Rogers7b078e82014-09-10 14:44:24 -07002562 if (!work_line_->VerifyRegisterTypeWide(this, inst->VRegC_23x(), reg_types_.LongLo(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002563 reg_types_.LongHi())) {
jeffhao457cc512012-02-02 16:55:13 -08002564 break;
2565 }
Andreas Gampead238ce2015-08-24 21:13:08 -07002566 work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002567 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002568 case Instruction::THROW: {
Ian Rogers7b078e82014-09-10 14:44:24 -07002569 const RegType& res_type = work_line_->GetRegisterType(this, inst->VRegA_11x());
David Brazdilca3c8c32016-09-06 14:04:48 +01002570 if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(res_type, this)) {
David Brazdil68b5c0b2016-01-19 14:25:29 +00002571 if (res_type.IsUninitializedTypes()) {
2572 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "thrown exception not initialized";
Pavel Vyssotski980027c2016-02-11 20:28:11 +06002573 } else if (!res_type.IsReferenceTypes()) {
2574 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "thrown value of non-reference type " << res_type;
David Brazdil68b5c0b2016-01-19 14:25:29 +00002575 } else {
2576 Fail(res_type.IsUnresolvedTypes() ? VERIFY_ERROR_NO_CLASS : VERIFY_ERROR_BAD_CLASS_SOFT)
2577 << "thrown class " << res_type << " not instanceof Throwable";
2578 }
jeffhaobdb76512011-09-07 11:43:16 -07002579 }
2580 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002581 }
jeffhaobdb76512011-09-07 11:43:16 -07002582 case Instruction::GOTO:
2583 case Instruction::GOTO_16:
2584 case Instruction::GOTO_32:
2585 /* no effect on or use of registers */
2586 break;
2587
2588 case Instruction::PACKED_SWITCH:
2589 case Instruction::SPARSE_SWITCH:
2590 /* verify that vAA is an integer, or can be converted to one */
Ian Rogers7b078e82014-09-10 14:44:24 -07002591 work_line_->VerifyRegisterType(this, inst->VRegA_31t(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07002592 break;
2593
Ian Rogersd81871c2011-10-03 13:57:23 -07002594 case Instruction::FILL_ARRAY_DATA: {
2595 /* Similar to the verification done for APUT */
Ian Rogers7b078e82014-09-10 14:44:24 -07002596 const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegA_31t());
Ian Rogers89310de2012-02-01 13:47:30 -08002597 /* array_type can be null if the reg type is Zero */
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08002598 if (!array_type.IsZeroOrNull()) {
jeffhao457cc512012-02-02 16:55:13 -08002599 if (!array_type.IsArrayTypes()) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07002600 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with array type "
2601 << array_type;
Andreas Gampebb18a032016-03-22 20:34:25 -07002602 } else if (array_type.IsUnresolvedTypes()) {
2603 // If it's an unresolved array type, it must be non-primitive.
2604 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data for array of type "
2605 << array_type;
Ian Rogers89310de2012-02-01 13:47:30 -08002606 } else {
Andreas Gampe51de69e2019-04-19 15:14:14 -07002607 const RegType& component_type = reg_types_.GetComponentType(array_type,
2608 class_loader_.Get());
Ian Rogersad0b3a32012-04-16 14:50:24 -07002609 DCHECK(!component_type.IsConflict());
jeffhao457cc512012-02-02 16:55:13 -08002610 if (component_type.IsNonZeroReferenceTypes()) {
jeffhaod5347e02012-03-22 17:25:05 -07002611 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid fill-array-data with component type "
2612 << component_type;
Ian Rogersd81871c2011-10-03 13:57:23 -07002613 } else {
jeffhao457cc512012-02-02 16:55:13 -08002614 // Now verify if the element width in the table matches the element width declared in
2615 // the array
Andreas Gampe53de99c2015-08-17 13:43:55 -07002616 const uint16_t* array_data =
2617 insns + (insns[1] | (static_cast<int32_t>(insns[2]) << 16));
jeffhao457cc512012-02-02 16:55:13 -08002618 if (array_data[0] != Instruction::kArrayDataSignature) {
jeffhaod5347e02012-03-22 17:25:05 -07002619 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid magic for array-data";
jeffhao457cc512012-02-02 16:55:13 -08002620 } else {
2621 size_t elem_width = Primitive::ComponentSize(component_type.GetPrimitiveType());
2622 // Since we don't compress the data in Dex, expect to see equal width of data stored
2623 // in the table and expected from the array class.
2624 if (array_data[1] != elem_width) {
jeffhaod5347e02012-03-22 17:25:05 -07002625 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array-data size mismatch (" << array_data[1]
2626 << " vs " << elem_width << ")";
jeffhao457cc512012-02-02 16:55:13 -08002627 }
Ian Rogersd81871c2011-10-03 13:57:23 -07002628 }
2629 }
jeffhaobdb76512011-09-07 11:43:16 -07002630 }
2631 }
2632 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002633 }
jeffhaobdb76512011-09-07 11:43:16 -07002634 case Instruction::IF_EQ:
Ian Rogersd81871c2011-10-03 13:57:23 -07002635 case Instruction::IF_NE: {
Ian Rogers7b078e82014-09-10 14:44:24 -07002636 const RegType& reg_type1 = work_line_->GetRegisterType(this, inst->VRegA_22t());
2637 const RegType& reg_type2 = work_line_->GetRegisterType(this, inst->VRegB_22t());
Ian Rogersd81871c2011-10-03 13:57:23 -07002638 bool mismatch = false;
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08002639 if (reg_type1.IsZeroOrNull()) { // zero then integral or reference expected
Ian Rogersd81871c2011-10-03 13:57:23 -07002640 mismatch = !reg_type2.IsReferenceTypes() && !reg_type2.IsIntegralTypes();
2641 } else if (reg_type1.IsReferenceTypes()) { // both references?
2642 mismatch = !reg_type2.IsReferenceTypes();
2643 } else { // both integral?
2644 mismatch = !reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes();
2645 }
2646 if (mismatch) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07002647 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to if-eq/if-ne (" << reg_type1 << ","
2648 << reg_type2 << ") must both be references or integral";
jeffhaobdb76512011-09-07 11:43:16 -07002649 }
2650 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002651 }
jeffhaobdb76512011-09-07 11:43:16 -07002652 case Instruction::IF_LT:
2653 case Instruction::IF_GE:
2654 case Instruction::IF_GT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002655 case Instruction::IF_LE: {
Ian Rogers7b078e82014-09-10 14:44:24 -07002656 const RegType& reg_type1 = work_line_->GetRegisterType(this, inst->VRegA_22t());
2657 const RegType& reg_type2 = work_line_->GetRegisterType(this, inst->VRegB_22t());
Ian Rogersd81871c2011-10-03 13:57:23 -07002658 if (!reg_type1.IsIntegralTypes() || !reg_type2.IsIntegralTypes()) {
jeffhaod5347e02012-03-22 17:25:05 -07002659 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "args to 'if' (" << reg_type1 << ","
2660 << reg_type2 << ") must be integral";
jeffhaobdb76512011-09-07 11:43:16 -07002661 }
2662 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002663 }
jeffhaobdb76512011-09-07 11:43:16 -07002664 case Instruction::IF_EQZ:
Ian Rogersd81871c2011-10-03 13:57:23 -07002665 case Instruction::IF_NEZ: {
Ian Rogers7b078e82014-09-10 14:44:24 -07002666 const RegType& reg_type = work_line_->GetRegisterType(this, inst->VRegA_21t());
Ian Rogersd81871c2011-10-03 13:57:23 -07002667 if (!reg_type.IsReferenceTypes() && !reg_type.IsIntegralTypes()) {
Brian Carlstrom93c33962013-07-26 10:37:43 -07002668 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type
2669 << " unexpected as arg to if-eqz/if-nez";
Ian Rogersd81871c2011-10-03 13:57:23 -07002670 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002671
2672 // Find previous instruction - its existence is a precondition to peephole optimization.
Ian Rogers9b360392013-06-06 14:45:07 -07002673 uint32_t instance_of_idx = 0;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002674 if (0 != work_insn_idx_) {
Ian Rogers9b360392013-06-06 14:45:07 -07002675 instance_of_idx = work_insn_idx_ - 1;
Mathieu Chartierde40d472015-10-15 17:47:48 -07002676 while (0 != instance_of_idx && !GetInstructionFlags(instance_of_idx).IsOpcode()) {
Ian Rogers9b360392013-06-06 14:45:07 -07002677 instance_of_idx--;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002678 }
Mathieu Chartierc2a2bda2018-03-12 11:21:52 -07002679 if (FailOrAbort(GetInstructionFlags(instance_of_idx).IsOpcode(),
Andreas Gampe7c038102014-10-27 20:08:46 -07002680 "Unable to get previous instruction of if-eqz/if-nez for work index ",
2681 work_insn_idx_)) {
2682 break;
2683 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002684 } else {
2685 break;
2686 }
2687
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08002688 const Instruction& instance_of_inst = code_item_accessor_.InstructionAt(instance_of_idx);
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002689
2690 /* Check for peep-hole pattern of:
2691 * ...;
Ian Rogersfae370a2013-06-05 08:33:27 -07002692 * instance-of vX, vY, T;
2693 * ifXXX vX, label ;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002694 * ...;
Ian Rogersfae370a2013-06-05 08:33:27 -07002695 * label:
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002696 * ...;
Ian Rogersfae370a2013-06-05 08:33:27 -07002697 * and sharpen the type of vY to be type T.
2698 * Note, this pattern can't be if:
2699 * - if there are other branches to this branch,
2700 * - when vX == vY.
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002701 */
Ian Rogersfae370a2013-06-05 08:33:27 -07002702 if (!CurrentInsnFlags()->IsBranchTarget() &&
Vladimir Markod7559b72017-09-28 13:50:37 +01002703 (Instruction::INSTANCE_OF == instance_of_inst.Opcode()) &&
2704 (inst->VRegA_21t() == instance_of_inst.VRegA_22c()) &&
2705 (instance_of_inst.VRegA_22c() != instance_of_inst.VRegB_22c())) {
Ian Rogersebbdd872014-07-07 23:53:08 -07002706 // Check the type of the instance-of is different than that of registers type, as if they
2707 // are the same there is no work to be done here. Check that the conversion is not to or
2708 // from an unresolved type as type information is imprecise. If the instance-of is to an
2709 // interface then ignore the type information as interfaces can only be treated as Objects
2710 // and we don't want to disallow field and other operations on the object. If the value
2711 // being instance-of checked against is known null (zero) then allow the optimization as
2712 // we didn't have type information. If the merge of the instance-of type with the original
2713 // type is assignable to the original then allow optimization. This check is performed to
2714 // ensure that subsequent merges don't lose type information - such as becoming an
2715 // interface from a class that would lose information relevant to field checks.
Vladimir Markod7559b72017-09-28 13:50:37 +01002716 const RegType& orig_type = work_line_->GetRegisterType(this, instance_of_inst.VRegB_22c());
Andreas Gampe98be1a92017-08-28 08:25:45 -07002717 const RegType& cast_type = ResolveClass<CheckAccess::kYes>(
Vladimir Markod7559b72017-09-28 13:50:37 +01002718 dex::TypeIndex(instance_of_inst.VRegC_22c()));
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002719
Ian Rogersebbdd872014-07-07 23:53:08 -07002720 if (!orig_type.Equals(cast_type) &&
2721 !cast_type.IsUnresolvedTypes() && !orig_type.IsUnresolvedTypes() &&
Andreas Gampe00633eb2014-07-17 16:13:35 -07002722 cast_type.HasClass() && // Could be conflict type, make sure it has a class.
Ian Rogersebbdd872014-07-07 23:53:08 -07002723 !cast_type.GetClass()->IsInterface() &&
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08002724 (orig_type.IsZeroOrNull() ||
David Brazdilca3c8c32016-09-06 14:04:48 +01002725 orig_type.IsStrictlyAssignableFrom(
2726 cast_type.Merge(orig_type, &reg_types_, this), this))) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08002727 RegisterLine* update_line = RegisterLine::Create(code_item_accessor_.RegistersSize(),
Andreas Gamped09c0592019-04-19 15:44:05 -07002728 allocator_,
2729 GetRegTypeCache());
Ian Rogersfae370a2013-06-05 08:33:27 -07002730 if (inst->Opcode() == Instruction::IF_EQZ) {
Ian Rogers9b360392013-06-06 14:45:07 -07002731 fallthrough_line.reset(update_line);
Ian Rogersfae370a2013-06-05 08:33:27 -07002732 } else {
Ian Rogers9b360392013-06-06 14:45:07 -07002733 branch_line.reset(update_line);
2734 }
2735 update_line->CopyFromLine(work_line_.get());
Andreas Gampead238ce2015-08-24 21:13:08 -07002736 update_line->SetRegisterType<LockOp::kKeep>(this,
Vladimir Markod7559b72017-09-28 13:50:37 +01002737 instance_of_inst.VRegB_22c(),
Andreas Gampead238ce2015-08-24 21:13:08 -07002738 cast_type);
Mathieu Chartierde40d472015-10-15 17:47:48 -07002739 if (!GetInstructionFlags(instance_of_idx).IsBranchTarget() && 0 != instance_of_idx) {
Ian Rogers9b360392013-06-06 14:45:07 -07002740 // See if instance-of was preceded by a move-object operation, common due to the small
2741 // register encoding space of instance-of, and propagate type information to the source
2742 // of the move-object.
Andreas Gampe43e43252019-01-08 12:06:57 -08002743 // Note: this is only valid if the move source was not clobbered.
Ian Rogers9b360392013-06-06 14:45:07 -07002744 uint32_t move_idx = instance_of_idx - 1;
Mathieu Chartierde40d472015-10-15 17:47:48 -07002745 while (0 != move_idx && !GetInstructionFlags(move_idx).IsOpcode()) {
Ian Rogers9b360392013-06-06 14:45:07 -07002746 move_idx--;
2747 }
Mathieu Chartierc2a2bda2018-03-12 11:21:52 -07002748 if (FailOrAbort(GetInstructionFlags(move_idx).IsOpcode(),
Andreas Gampe7c038102014-10-27 20:08:46 -07002749 "Unable to get previous instruction of if-eqz/if-nez for work index ",
2750 work_insn_idx_)) {
2751 break;
2752 }
Andreas Gampe43e43252019-01-08 12:06:57 -08002753 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 };
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08002762 const Instruction& move_inst = code_item_accessor_.InstructionAt(move_idx);
Vladimir Markod7559b72017-09-28 13:50:37 +01002763 switch (move_inst.Opcode()) {
Ian Rogers9b360392013-06-06 14:45:07 -07002764 case Instruction::MOVE_OBJECT:
Andreas Gampe43e43252019-01-08 12:06:57 -08002765 maybe_update_fn(move_inst.VRegB_12x(), move_inst.VRegA_12x());
Ian Rogers9b360392013-06-06 14:45:07 -07002766 break;
2767 case Instruction::MOVE_OBJECT_FROM16:
Andreas Gampe43e43252019-01-08 12:06:57 -08002768 maybe_update_fn(move_inst.VRegB_22x(), move_inst.VRegA_22x());
Ian Rogers9b360392013-06-06 14:45:07 -07002769 break;
2770 case Instruction::MOVE_OBJECT_16:
Andreas Gampe43e43252019-01-08 12:06:57 -08002771 maybe_update_fn(move_inst.VRegB_32x(), move_inst.VRegA_32x());
Ian Rogers9b360392013-06-06 14:45:07 -07002772 break;
2773 default:
2774 break;
2775 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002776 }
2777 }
2778 }
2779
jeffhaobdb76512011-09-07 11:43:16 -07002780 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002781 }
jeffhaobdb76512011-09-07 11:43:16 -07002782 case Instruction::IF_LTZ:
2783 case Instruction::IF_GEZ:
2784 case Instruction::IF_GTZ:
Ian Rogersd81871c2011-10-03 13:57:23 -07002785 case Instruction::IF_LEZ: {
Ian Rogers7b078e82014-09-10 14:44:24 -07002786 const RegType& reg_type = work_line_->GetRegisterType(this, inst->VRegA_21t());
Ian Rogersd81871c2011-10-03 13:57:23 -07002787 if (!reg_type.IsIntegralTypes()) {
jeffhaod5347e02012-03-22 17:25:05 -07002788 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "type " << reg_type
2789 << " unexpected as arg to if-ltz/if-gez/if-gtz/if-lez";
Ian Rogersd81871c2011-10-03 13:57:23 -07002790 }
jeffhaobdb76512011-09-07 11:43:16 -07002791 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002792 }
jeffhaobdb76512011-09-07 11:43:16 -07002793 case Instruction::AGET_BOOLEAN:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002794 VerifyAGet(inst, reg_types_.Boolean(), true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002795 break;
jeffhaobdb76512011-09-07 11:43:16 -07002796 case Instruction::AGET_BYTE:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002797 VerifyAGet(inst, reg_types_.Byte(), true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002798 break;
jeffhaobdb76512011-09-07 11:43:16 -07002799 case Instruction::AGET_CHAR:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002800 VerifyAGet(inst, reg_types_.Char(), true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002801 break;
jeffhaobdb76512011-09-07 11:43:16 -07002802 case Instruction::AGET_SHORT:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002803 VerifyAGet(inst, reg_types_.Short(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002804 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002805 case Instruction::AGET:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002806 VerifyAGet(inst, reg_types_.Integer(), true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002807 break;
jeffhaobdb76512011-09-07 11:43:16 -07002808 case Instruction::AGET_WIDE:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002809 VerifyAGet(inst, reg_types_.LongLo(), true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002810 break;
2811 case Instruction::AGET_OBJECT:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002812 VerifyAGet(inst, reg_types_.JavaLangObject(false), false);
jeffhaobdb76512011-09-07 11:43:16 -07002813 break;
2814
Ian Rogersd81871c2011-10-03 13:57:23 -07002815 case Instruction::APUT_BOOLEAN:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002816 VerifyAPut(inst, reg_types_.Boolean(), true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002817 break;
2818 case Instruction::APUT_BYTE:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002819 VerifyAPut(inst, reg_types_.Byte(), true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002820 break;
2821 case Instruction::APUT_CHAR:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002822 VerifyAPut(inst, reg_types_.Char(), true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002823 break;
2824 case Instruction::APUT_SHORT:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002825 VerifyAPut(inst, reg_types_.Short(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002826 break;
2827 case Instruction::APUT:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002828 VerifyAPut(inst, reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002829 break;
2830 case Instruction::APUT_WIDE:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002831 VerifyAPut(inst, reg_types_.LongLo(), true);
jeffhaobdb76512011-09-07 11:43:16 -07002832 break;
2833 case Instruction::APUT_OBJECT:
Sebastien Hertz5243e912013-05-21 10:55:07 +02002834 VerifyAPut(inst, reg_types_.JavaLangObject(false), false);
jeffhaobdb76512011-09-07 11:43:16 -07002835 break;
2836
jeffhaobdb76512011-09-07 11:43:16 -07002837 case Instruction::IGET_BOOLEAN:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002838 case Instruction::IGET_BOOLEAN_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002839 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Boolean(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002840 break;
jeffhaobdb76512011-09-07 11:43:16 -07002841 case Instruction::IGET_BYTE:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002842 case Instruction::IGET_BYTE_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002843 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Byte(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002844 break;
jeffhaobdb76512011-09-07 11:43:16 -07002845 case Instruction::IGET_CHAR:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002846 case Instruction::IGET_CHAR_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002847 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Char(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002848 break;
jeffhaobdb76512011-09-07 11:43:16 -07002849 case Instruction::IGET_SHORT:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002850 case Instruction::IGET_SHORT_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002851 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Short(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002852 break;
2853 case Instruction::IGET:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002854 case Instruction::IGET_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002855 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Integer(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002856 break;
2857 case Instruction::IGET_WIDE:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002858 case Instruction::IGET_WIDE_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002859 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.LongLo(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002860 break;
2861 case Instruction::IGET_OBJECT:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002862 case Instruction::IGET_OBJECT_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002863 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.JavaLangObject(false), false,
2864 false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002865 break;
jeffhaobdb76512011-09-07 11:43:16 -07002866
Ian Rogersd81871c2011-10-03 13:57:23 -07002867 case Instruction::IPUT_BOOLEAN:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002868 case Instruction::IPUT_BOOLEAN_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002869 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Boolean(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002870 break;
2871 case Instruction::IPUT_BYTE:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002872 case Instruction::IPUT_BYTE_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002873 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Byte(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002874 break;
2875 case Instruction::IPUT_CHAR:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002876 case Instruction::IPUT_CHAR_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002877 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Char(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002878 break;
2879 case Instruction::IPUT_SHORT:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002880 case Instruction::IPUT_SHORT_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002881 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Short(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002882 break;
2883 case Instruction::IPUT:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002884 case Instruction::IPUT_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002885 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Integer(), true, false);
jeffhaobdb76512011-09-07 11:43:16 -07002886 break;
2887 case Instruction::IPUT_WIDE:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002888 case Instruction::IPUT_WIDE_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002889 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.LongLo(), true, false);
Ian Rogersd81871c2011-10-03 13:57:23 -07002890 break;
jeffhaobdb76512011-09-07 11:43:16 -07002891 case Instruction::IPUT_OBJECT:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002892 case Instruction::IPUT_OBJECT_QUICK:
Andreas Gampe896df402014-10-20 22:25:29 -07002893 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.JavaLangObject(false), false,
2894 false);
jeffhaobdb76512011-09-07 11:43:16 -07002895 break;
2896
jeffhaobdb76512011-09-07 11:43:16 -07002897 case Instruction::SGET_BOOLEAN:
Andreas Gampe896df402014-10-20 22:25:29 -07002898 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Boolean(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002899 break;
jeffhaobdb76512011-09-07 11:43:16 -07002900 case Instruction::SGET_BYTE:
Andreas Gampe896df402014-10-20 22:25:29 -07002901 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Byte(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002902 break;
jeffhaobdb76512011-09-07 11:43:16 -07002903 case Instruction::SGET_CHAR:
Andreas Gampe896df402014-10-20 22:25:29 -07002904 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Char(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002905 break;
jeffhaobdb76512011-09-07 11:43:16 -07002906 case Instruction::SGET_SHORT:
Andreas Gampe896df402014-10-20 22:25:29 -07002907 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Short(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002908 break;
2909 case Instruction::SGET:
Andreas Gampe896df402014-10-20 22:25:29 -07002910 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.Integer(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002911 break;
2912 case Instruction::SGET_WIDE:
Andreas Gampe896df402014-10-20 22:25:29 -07002913 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.LongLo(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002914 break;
2915 case Instruction::SGET_OBJECT:
Andreas Gampe896df402014-10-20 22:25:29 -07002916 VerifyISFieldAccess<FieldAccessType::kAccGet>(inst, reg_types_.JavaLangObject(false), false,
2917 true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002918 break;
2919
2920 case Instruction::SPUT_BOOLEAN:
Andreas Gampe896df402014-10-20 22:25:29 -07002921 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Boolean(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002922 break;
2923 case Instruction::SPUT_BYTE:
Andreas Gampe896df402014-10-20 22:25:29 -07002924 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Byte(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002925 break;
2926 case Instruction::SPUT_CHAR:
Andreas Gampe896df402014-10-20 22:25:29 -07002927 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Char(), true, true);
Ian Rogersd81871c2011-10-03 13:57:23 -07002928 break;
2929 case Instruction::SPUT_SHORT:
Andreas Gampe896df402014-10-20 22:25:29 -07002930 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Short(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002931 break;
2932 case Instruction::SPUT:
Andreas Gampe896df402014-10-20 22:25:29 -07002933 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.Integer(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002934 break;
2935 case Instruction::SPUT_WIDE:
Andreas Gampe896df402014-10-20 22:25:29 -07002936 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.LongLo(), true, true);
jeffhaobdb76512011-09-07 11:43:16 -07002937 break;
2938 case Instruction::SPUT_OBJECT:
Andreas Gampe896df402014-10-20 22:25:29 -07002939 VerifyISFieldAccess<FieldAccessType::kAccPut>(inst, reg_types_.JavaLangObject(false), false,
2940 true);
jeffhaobdb76512011-09-07 11:43:16 -07002941 break;
2942
2943 case Instruction::INVOKE_VIRTUAL:
2944 case Instruction::INVOKE_VIRTUAL_RANGE:
2945 case Instruction::INVOKE_SUPER:
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002946 case Instruction::INVOKE_SUPER_RANGE:
2947 case Instruction::INVOKE_VIRTUAL_QUICK:
2948 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: {
Sebastien Hertz5243e912013-05-21 10:55:07 +02002949 bool is_range = (inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE ||
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002950 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE ||
2951 inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07002952 bool is_super = (inst->Opcode() == Instruction::INVOKE_SUPER ||
2953 inst->Opcode() == Instruction::INVOKE_SUPER_RANGE);
Alex Light7268d472016-01-20 15:50:01 -08002954 MethodType type = is_super ? METHOD_SUPER : METHOD_VIRTUAL;
2955 ArtMethod* called_method = VerifyInvocationArgs(inst, type, is_range);
Ian Rogersd8f69b02014-09-10 21:43:52 +00002956 const RegType* return_type = nullptr;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002957 if (called_method != nullptr) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002958 ObjPtr<mirror::Class> return_type_class = can_load_classes_
2959 ? called_method->ResolveReturnType()
2960 : called_method->LookupResolvedReturnType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002961 if (return_type_class != nullptr) {
Andreas Gampef23f33d2015-06-23 14:18:17 -07002962 return_type = &FromClass(called_method->GetReturnTypeDescriptor(),
Vladimir Marko179b7c62019-03-22 13:38:57 +00002963 return_type_class,
Andreas Gampef23f33d2015-06-23 14:18:17 -07002964 return_type_class->CannotBeAssignedFromOtherTypes());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002965 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -07002966 DCHECK(!can_load_classes_ || self_->IsExceptionPending());
2967 self_->ClearException();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002968 }
2969 }
2970 if (return_type == nullptr) {
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00002971 uint32_t method_idx = GetMethodIdxOfInvoke(inst);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002972 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
Andreas Gampea5b09a62016-11-17 15:21:22 -08002973 dex::TypeIndex return_type_idx =
2974 dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002975 const char* descriptor = dex_file_->StringByTypeIdx(return_type_idx);
Andreas Gampe51de69e2019-04-19 15:14:14 -07002976 return_type = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false);
jeffhaobdb76512011-09-07 11:43:16 -07002977 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002978 if (!return_type->IsLowHalf()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002979 work_line_->SetResultRegisterType(this, *return_type);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002980 } else {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002981 work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(&reg_types_));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002982 }
Ian Rogersad0b3a32012-04-16 14:50:24 -07002983 just_set_result = true;
jeffhaobdb76512011-09-07 11:43:16 -07002984 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07002985 }
jeffhaobdb76512011-09-07 11:43:16 -07002986 case Instruction::INVOKE_DIRECT:
Ian Rogersd81871c2011-10-03 13:57:23 -07002987 case Instruction::INVOKE_DIRECT_RANGE: {
Sebastien Hertz5243e912013-05-21 10:55:07 +02002988 bool is_range = (inst->Opcode() == Instruction::INVOKE_DIRECT_RANGE);
Alex Light7268d472016-01-20 15:50:01 -08002989 ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_DIRECT, is_range);
Ian Rogers46685432012-06-03 22:26:43 -07002990 const char* return_type_descriptor;
2991 bool is_constructor;
Ian Rogersd8f69b02014-09-10 21:43:52 +00002992 const RegType* return_type = nullptr;
Ian Rogers7b078e82014-09-10 14:44:24 -07002993 if (called_method == nullptr) {
Sebastien Hertz5243e912013-05-21 10:55:07 +02002994 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002995 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002996 is_constructor = strcmp("<init>", dex_file_->StringDataByIdx(method_id.name_idx_)) == 0;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002997 dex::TypeIndex return_type_idx =
2998 dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
Ian Rogers46685432012-06-03 22:26:43 -07002999 return_type_descriptor = dex_file_->StringByTypeIdx(return_type_idx);
3000 } else {
3001 is_constructor = called_method->IsConstructor();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003002 return_type_descriptor = called_method->GetReturnTypeDescriptor();
Vladimir Markob45528c2017-07-27 14:14:28 +01003003 ObjPtr<mirror::Class> return_type_class = can_load_classes_
3004 ? called_method->ResolveReturnType()
3005 : called_method->LookupResolvedReturnType();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003006 if (return_type_class != nullptr) {
Andreas Gampef23f33d2015-06-23 14:18:17 -07003007 return_type = &FromClass(return_type_descriptor,
Vladimir Markobcf17522018-06-01 13:14:32 +01003008 return_type_class,
Andreas Gampef23f33d2015-06-23 14:18:17 -07003009 return_type_class->CannotBeAssignedFromOtherTypes());
Ian Rogers1ff3c982014-08-12 02:30:58 -07003010 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -07003011 DCHECK(!can_load_classes_ || self_->IsExceptionPending());
3012 self_->ClearException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003013 }
Ian Rogers46685432012-06-03 22:26:43 -07003014 }
3015 if (is_constructor) {
jeffhaobdb76512011-09-07 11:43:16 -07003016 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07003017 * 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).
jeffhaobdb76512011-09-07 11:43:16 -07003022 */
Orion Hodsoncfa325e2016-10-13 10:25:54 +01003023 const RegType& this_type = work_line_->GetInvocationThis(this, inst);
jeffhaob57e9522012-04-26 18:08:21 -07003024 if (this_type.IsConflict()) // failure.
3025 break;
jeffhaobdb76512011-09-07 11:43:16 -07003026
jeffhaob57e9522012-04-26 18:08:21 -07003027 /* no null refs allowed (?) */
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08003028 if (this_type.IsZeroOrNull()) {
jeffhaob57e9522012-04-26 18:08:21 -07003029 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unable to initialize null ref";
3030 break;
jeffhao2a8a90e2011-09-26 14:25:31 -07003031 }
jeffhaob57e9522012-04-26 18:08:21 -07003032
3033 /* must be in same class or in superclass */
Ian Rogersd8f69b02014-09-10 21:43:52 +00003034 // const RegType& this_super_klass = this_type.GetSuperClass(&reg_types_);
Ian Rogers46685432012-06-03 22:26:43 -07003035 // TODO: re-enable constructor type verification
3036 // if (this_super_klass.IsConflict()) {
jeffhaob57e9522012-04-26 18:08:21 -07003037 // Unknown super class, fail so we re-check at runtime.
Ian Rogers46685432012-06-03 22:26:43 -07003038 // Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "super class unknown for '" << this_type << "'";
3039 // break;
3040 // }
jeffhaob57e9522012-04-26 18:08:21 -07003041
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 */
Nicolas Geoffray98e6ce42016-02-16 18:42:15 +00003053 work_line_->MarkRefsAsInitialized(this, this_type);
Ian Rogersad0b3a32012-04-16 14:50:24 -07003054 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003055 if (return_type == nullptr) {
Andreas Gampe51de69e2019-04-19 15:14:14 -07003056 return_type = &reg_types_.FromDescriptor(class_loader_.Get(),
3057 return_type_descriptor,
3058 false);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003059 }
3060 if (!return_type->IsLowHalf()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003061 work_line_->SetResultRegisterType(this, *return_type);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003062 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003063 work_line_->SetResultRegisterTypeWide(*return_type, return_type->HighHalf(&reg_types_));
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003064 }
Ian Rogersad0b3a32012-04-16 14:50:24 -07003065 just_set_result = true;
3066 break;
3067 }
3068 case Instruction::INVOKE_STATIC:
3069 case Instruction::INVOKE_STATIC_RANGE: {
Sebastien Hertz5243e912013-05-21 10:55:07 +02003070 bool is_range = (inst->Opcode() == Instruction::INVOKE_STATIC_RANGE);
Alex Light7268d472016-01-20 15:50:01 -08003071 ArtMethod* called_method = VerifyInvocationArgs(inst, METHOD_STATIC, is_range);
Ian Rogers28ad40d2011-10-27 15:19:26 -07003072 const char* descriptor;
Ian Rogers7b078e82014-09-10 14:44:24 -07003073 if (called_method == nullptr) {
Sebastien Hertz5243e912013-05-21 10:55:07 +02003074 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003075 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
Andreas Gampea5b09a62016-11-17 15:21:22 -08003076 dex::TypeIndex return_type_idx =
3077 dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003078 descriptor = dex_file_->StringByTypeIdx(return_type_idx);
Ian Rogers28ad40d2011-10-27 15:19:26 -07003079 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003080 descriptor = called_method->GetReturnTypeDescriptor();
Ian Rogers28ad40d2011-10-27 15:19:26 -07003081 }
Andreas Gampe51de69e2019-04-19 15:14:14 -07003082 const RegType& return_type = reg_types_.FromDescriptor(class_loader_.Get(),
3083 descriptor,
3084 false);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003085 if (!return_type.IsLowHalf()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003086 work_line_->SetResultRegisterType(this, return_type);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003087 } else {
3088 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
3089 }
jeffhaobdb76512011-09-07 11:43:16 -07003090 just_set_result = true;
3091 }
3092 break;
jeffhaobdb76512011-09-07 11:43:16 -07003093 case Instruction::INVOKE_INTERFACE:
Ian Rogersd81871c2011-10-03 13:57:23 -07003094 case Instruction::INVOKE_INTERFACE_RANGE: {
Sebastien Hertz5243e912013-05-21 10:55:07 +02003095 bool is_range = (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE);
Alex Light7268d472016-01-20 15:50:01 -08003096 ArtMethod* abs_method = VerifyInvocationArgs(inst, METHOD_INTERFACE, is_range);
Ian Rogers7b078e82014-09-10 14:44:24 -07003097 if (abs_method != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01003098 ObjPtr<mirror::Class> called_interface = abs_method->GetDeclaringClass();
Ian Rogersad0b3a32012-04-16 14:50:24 -07003099 if (!called_interface->IsInterface() && !called_interface->IsObjectClass()) {
3100 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected interface class in invoke-interface '"
David Sehr709b0702016-10-13 09:12:37 -07003101 << abs_method->PrettyMethod() << "'";
Ian Rogersad0b3a32012-04-16 14:50:24 -07003102 break;
Ian Rogers28ad40d2011-10-27 15:19:26 -07003103 }
Ian Rogers0d604842012-04-16 14:50:24 -07003104 }
Ian Rogersad0b3a32012-04-16 14:50:24 -07003105 /* 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 */
Orion Hodsoncfa325e2016-10-13 10:25:54 +01003108 const RegType& this_type = work_line_->GetInvocationThis(this, inst);
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08003109 if (this_type.IsZeroOrNull()) {
Ian Rogersad0b3a32012-04-16 14:50:24 -07003110 /* 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;
Ian Rogers7b078e82014-09-10 14:44:24 -07003130 if (abs_method == nullptr) {
Sebastien Hertz5243e912013-05-21 10:55:07 +02003131 uint32_t method_idx = (is_range) ? inst->VRegB_3rc() : inst->VRegB_35c();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003132 const dex::MethodId& method_id = dex_file_->GetMethodId(method_idx);
Andreas Gampea5b09a62016-11-17 15:21:22 -08003133 dex::TypeIndex return_type_idx =
3134 dex_file_->GetProtoId(method_id.proto_idx_).return_type_idx_;
Mathieu Chartierde40d472015-10-15 17:47:48 -07003135 descriptor = dex_file_->StringByTypeIdx(return_type_idx);
Ian Rogersad0b3a32012-04-16 14:50:24 -07003136 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003137 descriptor = abs_method->GetReturnTypeDescriptor();
Ian Rogersad0b3a32012-04-16 14:50:24 -07003138 }
Andreas Gampe51de69e2019-04-19 15:14:14 -07003139 const RegType& return_type = reg_types_.FromDescriptor(class_loader_.Get(),
3140 descriptor,
3141 false);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003142 if (!return_type.IsLowHalf()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003143 work_line_->SetResultRegisterType(this, return_type);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003144 } else {
3145 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
3146 }
Ian Rogersad0b3a32012-04-16 14:50:24 -07003147 just_set_result = true;
jeffhaobdb76512011-09-07 11:43:16 -07003148 break;
Ian Rogersd81871c2011-10-03 13:57:23 -07003149 }
Narayan Kamath9823e782016-08-03 12:46:58 +01003150 case Instruction::INVOKE_POLYMORPHIC:
3151 case Instruction::INVOKE_POLYMORPHIC_RANGE: {
Orion Hodsoncfa325e2016-10-13 10:25:54 +01003152 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)) {
Orion Hodsonfe92d122018-01-02 10:45:17 +00003166 DCHECK(HasFailures());
Orion Hodsoncfa325e2016-10-13 10:25:54 +01003167 break;
3168 }
Orion Hodson06d10a72018-05-14 08:53:38 +01003169 const uint16_t vRegH = (is_range) ? inst->VRegH_4rcc() : inst->VRegH_45cc();
3170 const dex::ProtoIndex proto_idx(vRegH);
Orion Hodsonac141392017-01-13 11:53:47 +00003171 const char* return_descriptor =
Orion Hodsoncfa325e2016-10-13 10:25:54 +01003172 dex_file_->GetReturnTypeDescriptor(dex_file_->GetProtoId(proto_idx));
3173 const RegType& return_type =
Andreas Gampe51de69e2019-04-19 15:14:14 -07003174 reg_types_.FromDescriptor(class_loader_.Get(), return_descriptor, false);
Orion Hodsoncfa325e2016-10-13 10:25:54 +01003175 if (!return_type.IsLowHalf()) {
3176 work_line_->SetResultRegisterType(this, return_type);
3177 } else {
3178 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
3179 }
Orion Hodsonac141392017-01-13 11:53:47 +00003180 just_set_result = true;
Orion Hodsoncfa325e2016-10-13 10:25:54 +01003181 break;
Narayan Kamath9823e782016-08-03 12:46:58 +01003182 }
Orion Hodsonc069a302017-01-18 09:23:12 +00003183 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.
Orion Hodson4c8e12e2018-05-18 08:33:20 +01003198 const dex::ProtoIndex proto_idx = dex_file_->GetProtoIndexForCallSite(call_site_idx);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003199 const dex::ProtoId& proto_id = dex_file_->GetProtoId(proto_idx);
Orion Hodsonc069a302017-01-18 09:23:12 +00003200 DexFileParameterIterator param_it(*dex_file_, proto_id);
3201 // Treat method as static as it has yet to be determined.
3202 VerifyInvocationArgsFromIterator(&param_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 =
Andreas Gampe51de69e2019-04-19 15:14:14 -07003207 reg_types_.FromDescriptor(class_loader_.Get(), return_descriptor, false);
Orion Hodsonc069a302017-01-18 09:23:12 +00003208 if (!return_type.IsLowHalf()) {
3209 work_line_->SetResultRegisterType(this, return_type);
3210 } else {
3211 work_line_->SetResultRegisterTypeWide(return_type, return_type.HighHalf(&reg_types_));
3212 }
3213 just_set_result = true;
Orion Hodsonc069a302017-01-18 09:23:12 +00003214 break;
3215 }
jeffhaobdb76512011-09-07 11:43:16 -07003216 case Instruction::NEG_INT:
3217 case Instruction::NOT_INT:
Ian Rogers7b078e82014-09-10 14:44:24 -07003218 work_line_->CheckUnaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07003219 break;
3220 case Instruction::NEG_LONG:
3221 case Instruction::NOT_LONG:
Ian Rogers7b078e82014-09-10 14:44:24 -07003222 work_line_->CheckUnaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003223 reg_types_.LongLo(), reg_types_.LongHi());
jeffhaobdb76512011-09-07 11:43:16 -07003224 break;
3225 case Instruction::NEG_FLOAT:
Ian Rogers7b078e82014-09-10 14:44:24 -07003226 work_line_->CheckUnaryOp(this, inst, reg_types_.Float(), reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07003227 break;
3228 case Instruction::NEG_DOUBLE:
Ian Rogers7b078e82014-09-10 14:44:24 -07003229 work_line_->CheckUnaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003230 reg_types_.DoubleLo(), reg_types_.DoubleHi());
jeffhaobdb76512011-09-07 11:43:16 -07003231 break;
3232 case Instruction::INT_TO_LONG:
Ian Rogers7b078e82014-09-10 14:44:24 -07003233 work_line_->CheckUnaryOpToWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003234 reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07003235 break;
3236 case Instruction::INT_TO_FLOAT:
Ian Rogers7b078e82014-09-10 14:44:24 -07003237 work_line_->CheckUnaryOp(this, inst, reg_types_.Float(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07003238 break;
3239 case Instruction::INT_TO_DOUBLE:
Ian Rogers7b078e82014-09-10 14:44:24 -07003240 work_line_->CheckUnaryOpToWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003241 reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07003242 break;
3243 case Instruction::LONG_TO_INT:
Ian Rogers7b078e82014-09-10 14:44:24 -07003244 work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Integer(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003245 reg_types_.LongLo(), reg_types_.LongHi());
jeffhaobdb76512011-09-07 11:43:16 -07003246 break;
3247 case Instruction::LONG_TO_FLOAT:
Ian Rogers7b078e82014-09-10 14:44:24 -07003248 work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Float(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003249 reg_types_.LongLo(), reg_types_.LongHi());
jeffhaobdb76512011-09-07 11:43:16 -07003250 break;
3251 case Instruction::LONG_TO_DOUBLE:
Ian Rogers7b078e82014-09-10 14:44:24 -07003252 work_line_->CheckUnaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003253 reg_types_.LongLo(), reg_types_.LongHi());
jeffhaobdb76512011-09-07 11:43:16 -07003254 break;
3255 case Instruction::FLOAT_TO_INT:
Ian Rogers7b078e82014-09-10 14:44:24 -07003256 work_line_->CheckUnaryOp(this, inst, reg_types_.Integer(), reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07003257 break;
3258 case Instruction::FLOAT_TO_LONG:
Ian Rogers7b078e82014-09-10 14:44:24 -07003259 work_line_->CheckUnaryOpToWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003260 reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07003261 break;
3262 case Instruction::FLOAT_TO_DOUBLE:
Ian Rogers7b078e82014-09-10 14:44:24 -07003263 work_line_->CheckUnaryOpToWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003264 reg_types_.Float());
jeffhaobdb76512011-09-07 11:43:16 -07003265 break;
3266 case Instruction::DOUBLE_TO_INT:
Ian Rogers7b078e82014-09-10 14:44:24 -07003267 work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Integer(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003268 reg_types_.DoubleLo(), reg_types_.DoubleHi());
jeffhaobdb76512011-09-07 11:43:16 -07003269 break;
3270 case Instruction::DOUBLE_TO_LONG:
Ian Rogers7b078e82014-09-10 14:44:24 -07003271 work_line_->CheckUnaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003272 reg_types_.DoubleLo(), reg_types_.DoubleHi());
jeffhaobdb76512011-09-07 11:43:16 -07003273 break;
3274 case Instruction::DOUBLE_TO_FLOAT:
Ian Rogers7b078e82014-09-10 14:44:24 -07003275 work_line_->CheckUnaryOpFromWide(this, inst, reg_types_.Float(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003276 reg_types_.DoubleLo(), reg_types_.DoubleHi());
jeffhaobdb76512011-09-07 11:43:16 -07003277 break;
3278 case Instruction::INT_TO_BYTE:
Ian Rogers7b078e82014-09-10 14:44:24 -07003279 work_line_->CheckUnaryOp(this, inst, reg_types_.Byte(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07003280 break;
3281 case Instruction::INT_TO_CHAR:
Ian Rogers7b078e82014-09-10 14:44:24 -07003282 work_line_->CheckUnaryOp(this, inst, reg_types_.Char(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07003283 break;
3284 case Instruction::INT_TO_SHORT:
Ian Rogers7b078e82014-09-10 14:44:24 -07003285 work_line_->CheckUnaryOp(this, inst, reg_types_.Short(), reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07003286 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:
Ian Rogers7b078e82014-09-10 14:44:24 -07003296 work_line_->CheckBinaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003297 reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07003298 break;
3299 case Instruction::AND_INT:
3300 case Instruction::OR_INT:
3301 case Instruction::XOR_INT:
Ian Rogers7b078e82014-09-10 14:44:24 -07003302 work_line_->CheckBinaryOp(this, inst, reg_types_.Integer(), reg_types_.Integer(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003303 reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07003304 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:
Ian Rogers7b078e82014-09-10 14:44:24 -07003313 work_line_->CheckBinaryOpWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003314 reg_types_.LongLo(), reg_types_.LongHi(),
3315 reg_types_.LongLo(), reg_types_.LongHi());
jeffhaobdb76512011-09-07 11:43:16 -07003316 break;
3317 case Instruction::SHL_LONG:
3318 case Instruction::SHR_LONG:
3319 case Instruction::USHR_LONG:
Ian Rogersd81871c2011-10-03 13:57:23 -07003320 /* shift distance is Int, making these different from other binary operations */
Ian Rogers7b078e82014-09-10 14:44:24 -07003321 work_line_->CheckBinaryOpWideShift(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003322 reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07003323 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:
Ian Rogers7b078e82014-09-10 14:44:24 -07003329 work_line_->CheckBinaryOp(this, inst, reg_types_.Float(), reg_types_.Float(),
3330 reg_types_.Float(), false);
jeffhaobdb76512011-09-07 11:43:16 -07003331 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:
Ian Rogers7b078e82014-09-10 14:44:24 -07003337 work_line_->CheckBinaryOpWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003338 reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3339 reg_types_.DoubleLo(), reg_types_.DoubleHi());
jeffhaobdb76512011-09-07 11:43:16 -07003340 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:
Ian Rogers7b078e82014-09-10 14:44:24 -07003348 work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3349 reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07003350 break;
3351 case Instruction::AND_INT_2ADDR:
3352 case Instruction::OR_INT_2ADDR:
3353 case Instruction::XOR_INT_2ADDR:
Ian Rogers7b078e82014-09-10 14:44:24 -07003354 work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3355 reg_types_.Integer(), true);
jeffhaobdb76512011-09-07 11:43:16 -07003356 break;
3357 case Instruction::DIV_INT_2ADDR:
Ian Rogers7b078e82014-09-10 14:44:24 -07003358 work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Integer(), reg_types_.Integer(),
3359 reg_types_.Integer(), false);
jeffhaobdb76512011-09-07 11:43:16 -07003360 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:
Ian Rogers7b078e82014-09-10 14:44:24 -07003369 work_line_->CheckBinaryOp2addrWide(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003370 reg_types_.LongLo(), reg_types_.LongHi(),
3371 reg_types_.LongLo(), reg_types_.LongHi());
jeffhaobdb76512011-09-07 11:43:16 -07003372 break;
3373 case Instruction::SHL_LONG_2ADDR:
3374 case Instruction::SHR_LONG_2ADDR:
3375 case Instruction::USHR_LONG_2ADDR:
Ian Rogers7b078e82014-09-10 14:44:24 -07003376 work_line_->CheckBinaryOp2addrWideShift(this, inst, reg_types_.LongLo(), reg_types_.LongHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003377 reg_types_.Integer());
jeffhaobdb76512011-09-07 11:43:16 -07003378 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:
Ian Rogers7b078e82014-09-10 14:44:24 -07003384 work_line_->CheckBinaryOp2addr(this, inst, reg_types_.Float(), reg_types_.Float(),
3385 reg_types_.Float(), false);
jeffhaobdb76512011-09-07 11:43:16 -07003386 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:
Ian Rogers7b078e82014-09-10 14:44:24 -07003392 work_line_->CheckBinaryOp2addrWide(this, inst, reg_types_.DoubleLo(), reg_types_.DoubleHi(),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003393 reg_types_.DoubleLo(), reg_types_.DoubleHi(),
3394 reg_types_.DoubleLo(), reg_types_.DoubleHi());
jeffhaobdb76512011-09-07 11:43:16 -07003395 break;
3396 case Instruction::ADD_INT_LIT16:
Ian Rogersf72a11d2014-10-30 15:41:08 -07003397 case Instruction::RSUB_INT_LIT16:
jeffhaobdb76512011-09-07 11:43:16 -07003398 case Instruction::MUL_INT_LIT16:
3399 case Instruction::DIV_INT_LIT16:
3400 case Instruction::REM_INT_LIT16:
Ian Rogers7b078e82014-09-10 14:44:24 -07003401 work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), false,
3402 true);
jeffhaobdb76512011-09-07 11:43:16 -07003403 break;
3404 case Instruction::AND_INT_LIT16:
3405 case Instruction::OR_INT_LIT16:
3406 case Instruction::XOR_INT_LIT16:
Ian Rogers7b078e82014-09-10 14:44:24 -07003407 work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), true,
3408 true);
jeffhaobdb76512011-09-07 11:43:16 -07003409 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:
jeffhaobdb76512011-09-07 11:43:16 -07003416 case Instruction::SHR_INT_LIT8:
jeffhaobdb76512011-09-07 11:43:16 -07003417 case Instruction::USHR_INT_LIT8:
Ian Rogers7b078e82014-09-10 14:44:24 -07003418 work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), false,
3419 false);
jeffhaobdb76512011-09-07 11:43:16 -07003420 break;
3421 case Instruction::AND_INT_LIT8:
3422 case Instruction::OR_INT_LIT8:
3423 case Instruction::XOR_INT_LIT8:
Ian Rogers7b078e82014-09-10 14:44:24 -07003424 work_line_->CheckLiteralOp(this, inst, reg_types_.Integer(), reg_types_.Integer(), true,
3425 false);
jeffhaobdb76512011-09-07 11:43:16 -07003426 break;
3427
Sebastien Hertz2d6ba512013-05-17 11:31:37 +02003428 // Special instructions.
Mathieu Chartierd7cbf8a2015-03-19 12:43:20 -07003429 case Instruction::RETURN_VOID_NO_BARRIER:
3430 if (IsConstructor() && !IsStatic()) {
Vladimir Markod93e3742018-07-18 10:58:13 +01003431 const RegType& declaring_class = GetDeclaringClass();
Andreas Gampe68df3202015-06-22 11:35:46 -07003432 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_);
Andreas Gampee2abbc62017-09-15 11:59:26 -07003437 if (first_index != dex::kDexNoIndex) {
Andreas Gampe68df3202015-06-22 11:35:46 -07003438 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void-no-barrier not expected for field "
3439 << first_index;
3440 }
3441 break;
3442 }
Vladimir Marko2cffc5d2018-05-29 15:40:56 +01003443 ObjPtr<mirror::Class> klass = declaring_class.GetClass();
Mathieu Chartierd7cbf8a2015-03-19 12:43:20 -07003444 for (uint32_t i = 0, num_fields = klass->NumInstanceFields(); i < num_fields; ++i) {
3445 if (klass->GetInstanceField(i)->IsFinal()) {
Mathieu Chartiere86deef2015-03-19 13:43:37 -07003446 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "return-void-no-barrier not expected for "
David Sehr709b0702016-10-13 09:12:37 -07003447 << klass->GetInstanceField(i)->PrettyField();
Mathieu Chartierd7cbf8a2015-03-19 12:43:20 -07003448 break;
3449 }
3450 }
Sebastien Hertzcc10e0e2013-06-28 14:24:48 +02003451 }
Andreas Gampeb2917962015-07-31 13:36:10 -07003452 // 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 }
Sebastien Hertzcc10e0e2013-06-28 14:24:48 +02003459 break;
Sebastien Hertz2d6ba512013-05-17 11:31:37 +02003460
Ian Rogersd81871c2011-10-03 13:57:23 -07003461 /* These should never appear during verification. */
Mathieu Chartierffc605c2014-12-10 10:35:44 -08003462 case Instruction::UNUSED_3E ... Instruction::UNUSED_43:
Narayan Kamath8ec3bd22016-08-03 12:46:23 +01003463 case Instruction::UNUSED_F3 ... Instruction::UNUSED_F9:
Sebastien Hertz2d6ba512013-05-17 11:31:37 +02003464 case Instruction::UNUSED_79:
3465 case Instruction::UNUSED_7A:
jeffhaod5347e02012-03-22 17:25:05 -07003466 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Unexpected opcode " << inst->DumpString(dex_file_);
jeffhaobdb76512011-09-07 11:43:16 -07003467 break;
3468
3469 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07003470 * DO NOT add a "default" clause here. Without it the compiler will
jeffhaobdb76512011-09-07 11:43:16 -07003471 * complain if an instruction is missing (which is desirable).
3472 */
Elliott Hughesadb8c672012-03-06 16:49:32 -08003473 } // end - switch (dec_insn.opcode)
jeffhaobdb76512011-09-07 11:43:16 -07003474
Ian Rogersad0b3a32012-04-16 14:50:24 -07003475 if (have_pending_hard_failure_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003476 if (Runtime::Current()->IsAotCompiler()) {
3477 /* When AOT compiling, check that the last failure is a hard failure */
Andreas Gampeb588f4c2015-05-26 13:35:39 -07003478 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 }
Ian Rogerse1758fe2012-04-19 11:31:15 -07003488 }
Ian Rogersad0b3a32012-04-16 14:50:24 -07003489 /* immediate failure, reject class */
3490 info_messages_ << "Rejecting opcode " << inst->DumpString(dex_file_);
3491 return false;
jeffhaofaf459e2012-08-31 15:32:47 -07003492 } else if (have_pending_runtime_throw_failure_) {
Jeff Haoa3faaf42013-09-03 19:07:00 -07003493 /* checking interpreter will throw, mark following code as unreachable */
jeffhaofaf459e2012-08-31 15:32:47 -07003494 opcode_flags = Instruction::kThrow;
Andreas Gampea727e372015-08-25 09:22:37 -07003495 // Note: the flag must be reset as it is only global to decouple Fail and is semantically per
3496 // instruction. However, RETURN checking may throw LOCKING errors, so we clear at the
3497 // very end.
jeffhaobdb76512011-09-07 11:43:16 -07003498 }
jeffhaobdb76512011-09-07 11:43:16 -07003499 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07003500 * If we didn't just set the result register, clear it out. This ensures that you can only use
3501 * "move-result" immediately after the result is set. (We could check this statically, but it's
3502 * not expensive and it makes our debugging output cleaner.)
jeffhaobdb76512011-09-07 11:43:16 -07003503 */
3504 if (!just_set_result) {
Andreas Gamped09c0592019-04-19 15:44:05 -07003505 work_line_->SetResultTypeToUnknown(GetRegTypeCache());
jeffhaobdb76512011-09-07 11:43:16 -07003506 }
3507
jeffhaobdb76512011-09-07 11:43:16 -07003508 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07003509 * Handle "branch". Tag the branch target.
jeffhaobdb76512011-09-07 11:43:16 -07003510 *
3511 * NOTE: instructions like Instruction::EQZ provide information about the
jeffhaod1f0fde2011-09-08 17:25:33 -07003512 * state of the register when the branch is taken or not taken. For example,
jeffhaobdb76512011-09-07 11:43:16 -07003513 * somebody could get a reference field, check it for zero, and if the
3514 * branch is taken immediately store that register in a boolean field
jeffhaod1f0fde2011-09-08 17:25:33 -07003515 * since the value is known to be zero. We do not currently account for
jeffhaobdb76512011-09-07 11:43:16 -07003516 * that, and will reject the code.
3517 *
3518 * TODO: avoid re-fetching the branch target
3519 */
Elliott Hughesadb8c672012-03-06 16:49:32 -08003520 if ((opcode_flags & Instruction::kBranch) != 0) {
jeffhaobdb76512011-09-07 11:43:16 -07003521 bool isConditional, selfOkay;
Ian Rogersd81871c2011-10-03 13:57:23 -07003522 if (!GetBranchOffset(work_insn_idx_, &branch_target, &isConditional, &selfOkay)) {
jeffhaobdb76512011-09-07 11:43:16 -07003523 /* should never happen after static verification */
jeffhaod5347e02012-03-22 17:25:05 -07003524 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "bad branch";
jeffhaobdb76512011-09-07 11:43:16 -07003525 return false;
3526 }
Elliott Hughesadb8c672012-03-06 16:49:32 -08003527 DCHECK_EQ(isConditional, (opcode_flags & Instruction::kContinue) != 0);
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003528 if (!CheckNotMoveExceptionOrMoveResult(code_item_accessor_.Insns(),
3529 work_insn_idx_ + branch_target)) {
jeffhaobdb76512011-09-07 11:43:16 -07003530 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07003531 }
jeffhaobdb76512011-09-07 11:43:16 -07003532 /* update branch target, set "changed" if appropriate */
Mathieu Chartierde40d472015-10-15 17:47:48 -07003533 if (nullptr != branch_line) {
Ian Rogersebbdd872014-07-07 23:53:08 -07003534 if (!UpdateRegisters(work_insn_idx_ + branch_target, branch_line.get(), false)) {
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07003535 return false;
3536 }
3537 } else {
Ian Rogersebbdd872014-07-07 23:53:08 -07003538 if (!UpdateRegisters(work_insn_idx_ + branch_target, work_line_.get(), false)) {
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07003539 return false;
3540 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003541 }
jeffhaobdb76512011-09-07 11:43:16 -07003542 }
3543
3544 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07003545 * Handle "switch". Tag all possible branch targets.
jeffhaobdb76512011-09-07 11:43:16 -07003546 *
3547 * We've already verified that the table is structurally sound, so we
3548 * just need to walk through and tag the targets.
3549 */
Elliott Hughesadb8c672012-03-06 16:49:32 -08003550 if ((opcode_flags & Instruction::kSwitch) != 0) {
Andreas Gampe53de99c2015-08-17 13:43:55 -07003551 int offset_to_switch = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
jeffhaobdb76512011-09-07 11:43:16 -07003552 const uint16_t* switch_insns = insns + offset_to_switch;
3553 int switch_count = switch_insns[1];
3554 int offset_to_targets, targ;
3555
3556 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
3557 /* 0 = sig, 1 = count, 2/3 = first key */
3558 offset_to_targets = 4;
3559 } else {
3560 /* 0 = sig, 1 = count, 2..count * 2 = keys */
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003561 DCHECK((*insns & 0xff) == Instruction::SPARSE_SWITCH);
jeffhaobdb76512011-09-07 11:43:16 -07003562 offset_to_targets = 2 + 2 * switch_count;
3563 }
3564
3565 /* verify each switch target */
3566 for (targ = 0; targ < switch_count; targ++) {
3567 int offset;
3568 uint32_t abs_offset;
3569
3570 /* offsets are 32-bit, and only partly endian-swapped */
3571 offset = switch_insns[offset_to_targets + targ * 2] |
Andreas Gampe53de99c2015-08-17 13:43:55 -07003572 (static_cast<int32_t>(switch_insns[offset_to_targets + targ * 2 + 1]) << 16);
Ian Rogersd81871c2011-10-03 13:57:23 -07003573 abs_offset = work_insn_idx_ + offset;
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003574 DCHECK_LT(abs_offset, code_item_accessor_.InsnsSizeInCodeUnits());
3575 if (!CheckNotMoveExceptionOrMoveResult(code_item_accessor_.Insns(), abs_offset)) {
jeffhaobdb76512011-09-07 11:43:16 -07003576 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07003577 }
Ian Rogersebbdd872014-07-07 23:53:08 -07003578 if (!UpdateRegisters(abs_offset, work_line_.get(), false)) {
jeffhaobdb76512011-09-07 11:43:16 -07003579 return false;
Ian Rogersebbdd872014-07-07 23:53:08 -07003580 }
jeffhaobdb76512011-09-07 11:43:16 -07003581 }
3582 }
3583
3584 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07003585 * Handle instructions that can throw and that are sitting in a "try" block. (If they're not in a
3586 * "try" block when they throw, control transfers out of the method.)
jeffhaobdb76512011-09-07 11:43:16 -07003587 */
Mathieu Chartierde40d472015-10-15 17:47:48 -07003588 if ((opcode_flags & Instruction::kThrow) != 0 && GetInstructionFlags(work_insn_idx_).IsInTry()) {
Andreas Gampef91baf12014-07-18 15:41:00 -07003589 bool has_catch_all_handler = false;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003590 const dex::TryItem* try_item = code_item_accessor_.FindTryItem(work_insn_idx_);
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003591 CHECK(try_item != nullptr);
Mathieu Chartierdc578c72017-12-27 11:51:45 -08003592 CatchHandlerIterator iterator(code_item_accessor_, *try_item);
jeffhaobdb76512011-09-07 11:43:16 -07003593
Andreas Gampef91baf12014-07-18 15:41:00 -07003594 // Need the linker to try and resolve the handled class to check if it's Throwable.
3595 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3596
Ian Rogers0571d352011-11-03 19:51:38 -07003597 for (; iterator.HasNext(); iterator.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08003598 dex::TypeIndex handler_type_idx = iterator.GetHandlerTypeIndex();
3599 if (!handler_type_idx.IsValid()) {
Andreas Gampef91baf12014-07-18 15:41:00 -07003600 has_catch_all_handler = true;
3601 } else {
3602 // It is also a catch-all if it is java.lang.Throwable.
Vladimir Marko28e012a2017-12-07 11:22:59 +00003603 ObjPtr<mirror::Class> klass =
Vladimir Marko666ee3d2017-12-11 18:37:36 +00003604 linker->ResolveType(handler_type_idx, dex_cache_, class_loader_);
Andreas Gampef91baf12014-07-18 15:41:00 -07003605 if (klass != nullptr) {
Vladimir Markoadbceb72018-05-29 14:34:14 +01003606 if (klass == GetClassRoot<mirror::Throwable>()) {
Andreas Gampef91baf12014-07-18 15:41:00 -07003607 has_catch_all_handler = true;
3608 }
3609 } else {
3610 // Clear exception.
Ian Rogers7b078e82014-09-10 14:44:24 -07003611 DCHECK(self_->IsExceptionPending());
3612 self_->ClearException();
Andreas Gampef91baf12014-07-18 15:41:00 -07003613 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003614 }
jeffhaobdb76512011-09-07 11:43:16 -07003615 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07003616 * Merge registers into the "catch" block. We want to use the "savedRegs" rather than
3617 * "work_regs", because at runtime the exception will be thrown before the instruction
3618 * modifies any registers.
jeffhaobdb76512011-09-07 11:43:16 -07003619 */
Andreas Gampebfcca582019-04-19 12:01:55 -07003620 if (kVerifierDebug) {
3621 LogVerifyInfo() << "Updating exception handler 0x"
3622 << std::hex << iterator.GetHandlerAddress();
3623 }
Ian Rogersebbdd872014-07-07 23:53:08 -07003624 if (!UpdateRegisters(iterator.GetHandlerAddress(), saved_line_.get(), false)) {
jeffhaobdb76512011-09-07 11:43:16 -07003625 return false;
Ian Rogersd81871c2011-10-03 13:57:23 -07003626 }
jeffhaobdb76512011-09-07 11:43:16 -07003627 }
3628
3629 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07003630 * If the monitor stack depth is nonzero, there must be a "catch all" handler for this
3631 * instruction. This does apply to monitor-exit because of async exception handling.
jeffhaobdb76512011-09-07 11:43:16 -07003632 */
Andreas Gampef91baf12014-07-18 15:41:00 -07003633 if (work_line_->MonitorStackDepth() > 0 && !has_catch_all_handler) {
jeffhaobdb76512011-09-07 11:43:16 -07003634 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07003635 * The state in work_line reflects the post-execution state. If the current instruction is a
3636 * monitor-enter and the monitor stack was empty, we don't need a catch-all (if it throws,
jeffhaobdb76512011-09-07 11:43:16 -07003637 * it will do so before grabbing the lock).
3638 */
Sebastien Hertz5243e912013-05-21 10:55:07 +02003639 if (inst->Opcode() != Instruction::MONITOR_ENTER || work_line_->MonitorStackDepth() != 1) {
jeffhaod5347e02012-03-22 17:25:05 -07003640 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
Ian Rogersd81871c2011-10-03 13:57:23 -07003641 << "expected to be within a catch-all for an instruction where a monitor is held";
jeffhaobdb76512011-09-07 11:43:16 -07003642 return false;
3643 }
3644 }
3645 }
3646
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07003647 /* Handle "continue". Tag the next consecutive instruction.
3648 * Note: Keep the code handling "continue" case below the "branch" and "switch" cases,
3649 * because it changes work_line_ when performing peephole optimization
3650 * and this change should not be used in those cases.
3651 */
Ian Rogers6d376ae2013-07-23 15:12:40 -07003652 if ((opcode_flags & Instruction::kContinue) != 0) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003653 DCHECK_EQ(&code_item_accessor_.InstructionAt(work_insn_idx_), inst);
Ian Rogers7b078e82014-09-10 14:44:24 -07003654 uint32_t next_insn_idx = work_insn_idx_ + inst->SizeInCodeUnits();
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003655 if (next_insn_idx >= code_item_accessor_.InsnsSizeInCodeUnits()) {
Ian Rogers6d376ae2013-07-23 15:12:40 -07003656 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Execution can walk off end of code area";
3657 return false;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07003658 }
Ian Rogers6d376ae2013-07-23 15:12:40 -07003659 // The only way to get to a move-exception instruction is to get thrown there. Make sure the
3660 // next instruction isn't one.
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003661 if (!CheckNotMoveException(code_item_accessor_.Insns(), next_insn_idx)) {
Ian Rogers6d376ae2013-07-23 15:12:40 -07003662 return false;
3663 }
Mathieu Chartierde40d472015-10-15 17:47:48 -07003664 if (nullptr != fallthrough_line) {
Ian Rogers6d376ae2013-07-23 15:12:40 -07003665 // Make workline consistent with fallthrough computed from peephole optimization.
3666 work_line_->CopyFromLine(fallthrough_line.get());
3667 }
Mathieu Chartierde40d472015-10-15 17:47:48 -07003668 if (GetInstructionFlags(next_insn_idx).IsReturn()) {
Ian Rogersb8c78592013-07-25 23:52:52 +00003669 // For returns we only care about the operand to the return, all other registers are dead.
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003670 const Instruction* ret_inst = &code_item_accessor_.InstructionAt(next_insn_idx);
Andreas Gampea727e372015-08-25 09:22:37 -07003671 AdjustReturnLine(this, ret_inst, work_line_.get());
Ian Rogersb8c78592013-07-25 23:52:52 +00003672 }
Ian Rogers6d376ae2013-07-23 15:12:40 -07003673 RegisterLine* next_line = reg_table_.GetLine(next_insn_idx);
Ian Rogers7b078e82014-09-10 14:44:24 -07003674 if (next_line != nullptr) {
Ian Rogersebbdd872014-07-07 23:53:08 -07003675 // Merge registers into what we have for the next instruction, and set the "changed" flag if
3676 // needed. If the merge changes the state of the registers then the work line will be
3677 // updated.
3678 if (!UpdateRegisters(next_insn_idx, work_line_.get(), true)) {
Ian Rogers6d376ae2013-07-23 15:12:40 -07003679 return false;
3680 }
3681 } else {
3682 /*
3683 * We're not recording register data for the next instruction, so we don't know what the
3684 * prior state was. We have to assume that something has changed and re-evaluate it.
3685 */
Andreas Gampe51de69e2019-04-19 15:14:14 -07003686 GetModifiableInstructionFlags(next_insn_idx).SetChanged();
Ian Rogers6d376ae2013-07-23 15:12:40 -07003687 }
3688 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07003689
jeffhaod1f0fde2011-09-08 17:25:33 -07003690 /* If we're returning from the method, make sure monitor stack is empty. */
Elliott Hughesadb8c672012-03-06 16:49:32 -08003691 if ((opcode_flags & Instruction::kReturn) != 0) {
Andreas Gampea727e372015-08-25 09:22:37 -07003692 work_line_->VerifyMonitorStackEmpty(this);
jeffhaobdb76512011-09-07 11:43:16 -07003693 }
3694
3695 /*
jeffhaod1f0fde2011-09-08 17:25:33 -07003696 * Update start_guess. Advance to the next instruction of that's
3697 * possible, otherwise use the branch target if one was found. If
jeffhaobdb76512011-09-07 11:43:16 -07003698 * neither of those exists we're in a return or throw; leave start_guess
3699 * alone and let the caller sort it out.
3700 */
Elliott Hughesadb8c672012-03-06 16:49:32 -08003701 if ((opcode_flags & Instruction::kContinue) != 0) {
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003702 DCHECK_EQ(&code_item_accessor_.InstructionAt(work_insn_idx_), inst);
Ian Rogers7b078e82014-09-10 14:44:24 -07003703 *start_guess = work_insn_idx_ + inst->SizeInCodeUnits();
Elliott Hughesadb8c672012-03-06 16:49:32 -08003704 } else if ((opcode_flags & Instruction::kBranch) != 0) {
jeffhaobdb76512011-09-07 11:43:16 -07003705 /* we're still okay if branch_target is zero */
Ian Rogersd81871c2011-10-03 13:57:23 -07003706 *start_guess = work_insn_idx_ + branch_target;
jeffhaobdb76512011-09-07 11:43:16 -07003707 }
3708
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003709 DCHECK_LT(*start_guess, code_item_accessor_.InsnsSizeInCodeUnits());
Mathieu Chartierde40d472015-10-15 17:47:48 -07003710 DCHECK(GetInstructionFlags(*start_guess).IsOpcode());
jeffhaobdb76512011-09-07 11:43:16 -07003711
Andreas Gampea727e372015-08-25 09:22:37 -07003712 if (have_pending_runtime_throw_failure_) {
3713 have_any_pending_runtime_throw_failure_ = true;
3714 // Reset the pending_runtime_throw flag now.
3715 have_pending_runtime_throw_failure_ = false;
3716 }
3717
jeffhaobdb76512011-09-07 11:43:16 -07003718 return true;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07003719} // NOLINT(readability/fn_size)
jeffhaobdb76512011-09-07 11:43:16 -07003720
Andreas Gampe99db7bb2019-04-19 23:05:47 -07003721template <bool kVerifierDebug>
3722template <CheckAccess C>
3723const RegType& MethodVerifier<kVerifierDebug>::ResolveClass(dex::TypeIndex class_idx) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00003724 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Vladimir Marko28e012a2017-12-07 11:22:59 +00003725 ObjPtr<mirror::Class> klass = can_load_classes_
Vladimir Marko666ee3d2017-12-11 18:37:36 +00003726 ? linker->ResolveType(class_idx, dex_cache_, class_loader_)
3727 : linker->LookupResolvedType(class_idx, dex_cache_.Get(), class_loader_.Get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00003728 if (can_load_classes_ && klass == nullptr) {
3729 DCHECK(self_->IsExceptionPending());
3730 self_->ClearException();
3731 }
Mathieu Chartierde40d472015-10-15 17:47:48 -07003732 const RegType* result = nullptr;
Vladimir Marko9cb0c462017-04-21 13:31:41 +01003733 if (klass != nullptr) {
Mathieu Chartierde40d472015-10-15 17:47:48 -07003734 bool precise = klass->CannotBeAssignedFromOtherTypes();
3735 if (precise && !IsInstantiableOrPrimitive(klass)) {
3736 const char* descriptor = dex_file_->StringByTypeIdx(class_idx);
3737 UninstantiableError(descriptor);
3738 precise = false;
3739 }
Vladimir Marko2cffc5d2018-05-29 15:40:56 +01003740 result = reg_types_.FindClass(klass, precise);
Mathieu Chartierde40d472015-10-15 17:47:48 -07003741 if (result == nullptr) {
3742 const char* descriptor = dex_file_->StringByTypeIdx(class_idx);
Vladimir Marko2cffc5d2018-05-29 15:40:56 +01003743 result = reg_types_.InsertClass(descriptor, klass, precise);
Mathieu Chartierde40d472015-10-15 17:47:48 -07003744 }
3745 } else {
3746 const char* descriptor = dex_file_->StringByTypeIdx(class_idx);
Andreas Gampe51de69e2019-04-19 15:14:14 -07003747 result = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false);
Ian Rogersad0b3a32012-04-16 14:50:24 -07003748 }
Mathieu Chartierde40d472015-10-15 17:47:48 -07003749 DCHECK(result != nullptr);
3750 if (result->IsConflict()) {
3751 const char* descriptor = dex_file_->StringByTypeIdx(class_idx);
3752 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "accessing broken descriptor '" << descriptor
3753 << "' in " << GetDeclaringClass();
3754 return *result;
3755 }
David Brazdilca3c8c32016-09-06 14:04:48 +01003756
3757 // Record result of class resolution attempt.
Vladimir Markobcf17522018-06-01 13:14:32 +01003758 VerifierDeps::MaybeRecordClassResolution(*dex_file_, class_idx, klass);
David Brazdilca3c8c32016-09-06 14:04:48 +01003759
Andreas Gampe629be512017-08-25 17:09:32 -07003760 // If requested, check if access is allowed. Unresolved types are included in this check, as the
3761 // interpreter only tests whether access is allowed when a class is not pre-verified and runs in
3762 // the access-checks interpreter. If result is primitive, skip the access check.
3763 //
3764 // Note: we do this for unresolved classes to trigger re-verification at runtime.
Andreas Gampedc39d322018-09-04 09:26:03 -07003765 if (C == CheckAccess::kYes &&
3766 result->IsNonZeroReferenceTypes() &&
David Brazdil2bb2fbd2018-11-13 18:24:26 +00003767 (IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP) || !result->IsUnresolvedTypes())) {
Mathieu Chartierde40d472015-10-15 17:47:48 -07003768 const RegType& referrer = GetDeclaringClass();
David Brazdil2bb2fbd2018-11-13 18:24:26 +00003769 if ((IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP) || !referrer.IsUnresolvedTypes()) &&
3770 !referrer.CanAccess(*result)) {
Andreas Gampe629be512017-08-25 17:09:32 -07003771 Fail(VERIFY_ERROR_ACCESS_CLASS) << "(possibly) illegal class access: '"
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01003772 << referrer << "' -> '" << *result << "'";
Mathieu Chartierde40d472015-10-15 17:47:48 -07003773 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07003774 }
Mathieu Chartierde40d472015-10-15 17:47:48 -07003775 return *result;
Ian Rogersd81871c2011-10-03 13:57:23 -07003776}
3777
Andreas Gampe99db7bb2019-04-19 23:05:47 -07003778template <bool kVerifierDebug>
3779const RegType& MethodVerifier<kVerifierDebug>::GetCaughtExceptionType() {
Ian Rogers7b078e82014-09-10 14:44:24 -07003780 const RegType* common_super = nullptr;
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003781 if (code_item_accessor_.TriesSize() != 0) {
3782 const uint8_t* handlers_ptr = code_item_accessor_.GetCatchHandlerData();
Ian Rogersd81871c2011-10-03 13:57:23 -07003783 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3784 for (uint32_t i = 0; i < handlers_size; i++) {
Ian Rogers0571d352011-11-03 19:51:38 -07003785 CatchHandlerIterator iterator(handlers_ptr);
3786 for (; iterator.HasNext(); iterator.Next()) {
3787 if (iterator.GetHandlerAddress() == (uint32_t) work_insn_idx_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08003788 if (!iterator.GetHandlerTypeIndex().IsValid()) {
Ian Rogersb4903572012-10-11 11:52:56 -07003789 common_super = &reg_types_.JavaLangThrowable(false);
Ian Rogersd81871c2011-10-03 13:57:23 -07003790 } else {
Andreas Gampe98be1a92017-08-28 08:25:45 -07003791 const RegType& exception =
3792 ResolveClass<CheckAccess::kYes>(iterator.GetHandlerTypeIndex());
David Brazdilca3c8c32016-09-06 14:04:48 +01003793 if (!reg_types_.JavaLangThrowable(false).IsAssignableFrom(exception, this)) {
David Brazdil68b5c0b2016-01-19 14:25:29 +00003794 DCHECK(!exception.IsUninitializedTypes()); // Comes from dex, shouldn't be uninit.
Jeff Haoc26a56c2013-11-04 12:00:47 -08003795 if (exception.IsUnresolvedTypes()) {
3796 // We don't know enough about the type. Fail here and let runtime handle it.
3797 Fail(VERIFY_ERROR_NO_CLASS) << "unresolved exception class " << exception;
3798 return exception;
3799 } else {
3800 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unexpected non-exception class " << exception;
3801 return reg_types_.Conflict();
3802 }
Jeff Haob878f212014-04-24 16:25:36 -07003803 } else if (common_super == nullptr) {
3804 common_super = &exception;
Ian Rogers28ad40d2011-10-27 15:19:26 -07003805 } else if (common_super->Equals(exception)) {
Ian Rogersc4762272012-02-01 15:55:55 -08003806 // odd case, but nothing to do
Ian Rogersd81871c2011-10-03 13:57:23 -07003807 } else {
David Brazdilca3c8c32016-09-06 14:04:48 +01003808 common_super = &common_super->Merge(exception, &reg_types_, this);
Mathieu Chartierc2a2bda2018-03-12 11:21:52 -07003809 if (FailOrAbort(reg_types_.JavaLangThrowable(false).IsAssignableFrom(
David Brazdilca3c8c32016-09-06 14:04:48 +01003810 *common_super, this),
Andreas Gampe7c038102014-10-27 20:08:46 -07003811 "java.lang.Throwable is not assignable-from common_super at ",
3812 work_insn_idx_)) {
3813 break;
3814 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003815 }
3816 }
3817 }
3818 }
Ian Rogers0571d352011-11-03 19:51:38 -07003819 handlers_ptr = iterator.EndDataPointer();
Ian Rogersd81871c2011-10-03 13:57:23 -07003820 }
3821 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003822 if (common_super == nullptr) {
Ian Rogersd81871c2011-10-03 13:57:23 -07003823 /* no catch blocks, or no catches with classes we can find */
jeffhaod5347e02012-03-22 17:25:05 -07003824 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "unable to find exception handler";
Ian Rogersad0b3a32012-04-16 14:50:24 -07003825 return reg_types_.Conflict();
Ian Rogersd81871c2011-10-03 13:57:23 -07003826 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07003827 return *common_super;
Ian Rogersd81871c2011-10-03 13:57:23 -07003828}
3829
Andreas Gampe99db7bb2019-04-19 23:05:47 -07003830template <bool kVerifierDebug>
3831ArtMethod* MethodVerifier<kVerifierDebug>::ResolveMethodAndCheckAccess(
Alex Light7268d472016-01-20 15:50:01 -08003832 uint32_t dex_method_idx, MethodType method_type) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003833 const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx);
Andreas Gampe98be1a92017-08-28 08:25:45 -07003834 const RegType& klass_type = ResolveClass<CheckAccess::kYes>(method_id.class_idx_);
Ian Rogersad0b3a32012-04-16 14:50:24 -07003835 if (klass_type.IsConflict()) {
3836 std::string append(" in attempt to access method ");
3837 append += dex_file_->GetMethodName(method_id);
3838 AppendToLastFailMessage(append);
Ian Rogers7b078e82014-09-10 14:44:24 -07003839 return nullptr;
Ian Rogers90040192011-12-16 08:54:29 -08003840 }
jeffhao8cd6dda2012-02-22 10:15:34 -08003841 if (klass_type.IsUnresolvedTypes()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003842 return nullptr; // Can't resolve Class so no more to do here
Ian Rogers90040192011-12-16 08:54:29 -08003843 }
Vladimir Markoba118822017-06-12 15:41:56 +01003844 ObjPtr<mirror::Class> klass = klass_type.GetClass();
Ian Rogersd8f69b02014-09-10 21:43:52 +00003845 const RegType& referrer = GetDeclaringClass();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00003846 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
3847 PointerSize pointer_size = class_linker->GetImagePointerSize();
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08003848
Mathieu Chartiere401d142015-04-22 13:56:20 -07003849 ArtMethod* res_method = dex_cache_->GetResolvedMethod(dex_method_idx, pointer_size);
Ian Rogers7b078e82014-09-10 14:44:24 -07003850 if (res_method == nullptr) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00003851 res_method = class_linker->FindResolvedMethod(
3852 klass, dex_cache_.Get(), class_loader_.Get(), dex_method_idx);
Ian Rogersd81871c2011-10-03 13:57:23 -07003853 }
David Brazdilca3c8c32016-09-06 14:04:48 +01003854
Vladimir Markoba118822017-06-12 15:41:56 +01003855 // Record result of method resolution attempt. The klass resolution has recorded whether
3856 // the class is an interface or not and therefore the type of the lookup performed above.
3857 // TODO: Maybe we should not record dependency if the invoke type does not match the lookup type.
3858 VerifierDeps::MaybeRecordMethodResolution(*dex_file_, dex_method_idx, res_method);
3859
Alex Lightafb66472017-08-01 09:54:49 -07003860 bool must_fail = false;
3861 // This is traditional and helps with screwy bytecode. It will tell you that, yes, a method
3862 // exists, but that it's called incorrectly. This significantly helps debugging, as locally it's
3863 // hard to see the differences.
3864 // If we don't have res_method here we must fail. Just use this bool to make sure of that with a
3865 // DCHECK.
Vladimir Markoba118822017-06-12 15:41:56 +01003866 if (res_method == nullptr) {
Alex Lightafb66472017-08-01 09:54:49 -07003867 must_fail = true;
Vladimir Markoba118822017-06-12 15:41:56 +01003868 // Try to find the method also with the other type for better error reporting below
3869 // but do not store such bogus lookup result in the DexCache or VerifierDeps.
David Brazdil4525e0b2018-04-05 16:57:32 +01003870 res_method = class_linker->FindIncompatibleMethod(
3871 klass, dex_cache_.Get(), class_loader_.Get(), dex_method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01003872 }
David Brazdilca3c8c32016-09-06 14:04:48 +01003873
3874 if (res_method == nullptr) {
3875 Fail(VERIFY_ERROR_NO_METHOD) << "couldn't find method "
David Sehr709b0702016-10-13 09:12:37 -07003876 << klass->PrettyDescriptor() << "."
David Brazdilca3c8c32016-09-06 14:04:48 +01003877 << dex_file_->GetMethodName(method_id) << " "
3878 << dex_file_->GetMethodSignature(method_id);
3879 return nullptr;
3880 }
3881
Ian Rogersd81871c2011-10-03 13:57:23 -07003882 // Make sure calls to constructors are "direct". There are additional restrictions but we don't
3883 // enforce them here.
3884 if (res_method->IsConstructor() && method_type != METHOD_DIRECT) {
jeffhaod5347e02012-03-22 17:25:05 -07003885 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting non-direct call to constructor "
David Sehr709b0702016-10-13 09:12:37 -07003886 << res_method->PrettyMethod();
Ian Rogers7b078e82014-09-10 14:44:24 -07003887 return nullptr;
Ian Rogersd81871c2011-10-03 13:57:23 -07003888 }
jeffhao8cd6dda2012-02-22 10:15:34 -08003889 // Disallow any calls to class initializers.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003890 if (res_method->IsClassInitializer()) {
jeffhaod5347e02012-03-22 17:25:05 -07003891 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "rejecting call to class initializer "
David Sehr709b0702016-10-13 09:12:37 -07003892 << res_method->PrettyMethod();
Ian Rogers7b078e82014-09-10 14:44:24 -07003893 return nullptr;
jeffhao8cd6dda2012-02-22 10:15:34 -08003894 }
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08003895
3896 // Check that interface methods are static or match interface classes.
3897 // We only allow statics if we don't have default methods enabled.
3898 //
3899 // Note: this check must be after the initializer check, as those are required to fail a class,
3900 // while this check implies an IncompatibleClassChangeError.
3901 if (klass->IsInterface()) {
Alex Lightb55f1ac2016-04-12 15:50:55 -07003902 // methods called on interfaces should be invoke-interface, invoke-super, invoke-direct (if
Mathieu Chartierf6e31472017-12-28 13:32:08 -08003903 // default methods are supported for the dex file), or invoke-static.
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08003904 if (method_type != METHOD_INTERFACE &&
Neil Fuller9724c632016-01-07 15:42:47 +00003905 method_type != METHOD_STATIC &&
Mathieu Chartierf6e31472017-12-28 13:32:08 -08003906 (!dex_file_->SupportsDefaultMethods() ||
Alex Lightb55f1ac2016-04-12 15:50:55 -07003907 method_type != METHOD_DIRECT) &&
Neil Fuller9724c632016-01-07 15:42:47 +00003908 method_type != METHOD_SUPER) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08003909 Fail(VERIFY_ERROR_CLASS_CHANGE)
David Sehr709b0702016-10-13 09:12:37 -07003910 << "non-interface method " << dex_file_->PrettyMethod(dex_method_idx)
3911 << " is in an interface class " << klass->PrettyClass();
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08003912 return nullptr;
3913 }
3914 } else {
3915 if (method_type == METHOD_INTERFACE) {
3916 Fail(VERIFY_ERROR_CLASS_CHANGE)
David Sehr709b0702016-10-13 09:12:37 -07003917 << "interface method " << dex_file_->PrettyMethod(dex_method_idx)
3918 << " is in a non-interface class " << klass->PrettyClass();
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08003919 return nullptr;
3920 }
3921 }
3922
Alex Lightafb66472017-08-01 09:54:49 -07003923 // Check specifically for non-public object methods being provided for interface dispatch. This
3924 // can occur if we failed to find a method with FindInterfaceMethod but later find one with
3925 // FindClassMethod for error message use.
3926 if (method_type == METHOD_INTERFACE &&
3927 res_method->GetDeclaringClass()->IsObjectClass() &&
3928 !res_method->IsPublic()) {
3929 Fail(VERIFY_ERROR_NO_METHOD) << "invoke-interface " << klass->PrettyDescriptor() << "."
3930 << dex_file_->GetMethodName(method_id) << " "
3931 << dex_file_->GetMethodSignature(method_id) << " resolved to "
3932 << "non-public object method " << res_method->PrettyMethod() << " "
3933 << "but non-public Object methods are excluded from interface "
3934 << "method resolution.";
3935 return nullptr;
3936 }
jeffhao8cd6dda2012-02-22 10:15:34 -08003937 // Check if access is allowed.
Ian Rogersad0b3a32012-04-16 14:50:24 -07003938 if (!referrer.CanAccessMember(res_method->GetDeclaringClass(), res_method->GetAccessFlags())) {
David Sehr709b0702016-10-13 09:12:37 -07003939 Fail(VERIFY_ERROR_ACCESS_METHOD) << "illegal method access (call "
3940 << res_method->PrettyMethod()
Ian Rogersad0b3a32012-04-16 14:50:24 -07003941 << " from " << referrer << ")";
jeffhaob57e9522012-04-26 18:08:21 -07003942 return res_method;
jeffhao8cd6dda2012-02-22 10:15:34 -08003943 }
jeffhaode0d9c92012-02-27 13:58:13 -08003944 // Check that invoke-virtual and invoke-super are not used on private methods of the same class.
Alex Light7268d472016-01-20 15:50:01 -08003945 if (res_method->IsPrivate() && (method_type == METHOD_VIRTUAL || method_type == METHOD_SUPER)) {
jeffhaod5347e02012-03-22 17:25:05 -07003946 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invoke-super/virtual can't be used on private method "
David Sehr709b0702016-10-13 09:12:37 -07003947 << res_method->PrettyMethod();
Ian Rogers7b078e82014-09-10 14:44:24 -07003948 return nullptr;
jeffhaode0d9c92012-02-27 13:58:13 -08003949 }
Ian Rogersd81871c2011-10-03 13:57:23 -07003950 // See if the method type implied by the invoke instruction matches the access flags for the
Orion Hodsoncfa325e2016-10-13 10:25:54 +01003951 // target method. The flags for METHOD_POLYMORPHIC are based on there being precisely two
3952 // signature polymorphic methods supported by the run-time which are native methods with variable
3953 // arguments.
Brian Carlstrombe6fa5e2014-12-09 20:15:42 -08003954 if ((method_type == METHOD_DIRECT && (!res_method->IsDirect() || res_method->IsStatic())) ||
Ian Rogersd81871c2011-10-03 13:57:23 -07003955 (method_type == METHOD_STATIC && !res_method->IsStatic()) ||
Alex Light7268d472016-01-20 15:50:01 -08003956 ((method_type == METHOD_SUPER ||
3957 method_type == METHOD_VIRTUAL ||
Orion Hodsoncfa325e2016-10-13 10:25:54 +01003958 method_type == METHOD_INTERFACE) && res_method->IsDirect()) ||
3959 ((method_type == METHOD_POLYMORPHIC) &&
3960 (!res_method->IsNative() || !res_method->IsVarargs()))) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003961 Fail(VERIFY_ERROR_CLASS_CHANGE) << "invoke type (" << method_type << ") does not match method "
Orion Hodsoncfa325e2016-10-13 10:25:54 +01003962 "type of " << res_method->PrettyMethod();
Ian Rogers7b078e82014-09-10 14:44:24 -07003963 return nullptr;
Ian Rogersd81871c2011-10-03 13:57:23 -07003964 }
Alex Lightafb66472017-08-01 09:54:49 -07003965 // Make sure we weren't expecting to fail.
3966 DCHECK(!must_fail) << "invoke type (" << method_type << ")"
3967 << klass->PrettyDescriptor() << "."
3968 << dex_file_->GetMethodName(method_id) << " "
3969 << dex_file_->GetMethodSignature(method_id) << " unexpectedly resolved to "
3970 << res_method->PrettyMethod() << " without error. Initially this method was "
3971 << "not found so we were expecting to fail for some reason.";
jeffhao8cd6dda2012-02-22 10:15:34 -08003972 return res_method;
3973}
3974
Andreas Gampe99db7bb2019-04-19 23:05:47 -07003975template <bool kVerifierDebug>
Andreas Gampe95c0bf82014-06-16 14:06:52 -07003976template <class T>
Andreas Gampe99db7bb2019-04-19 23:05:47 -07003977ArtMethod* MethodVerifier<kVerifierDebug>::VerifyInvocationArgsFromIterator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07003978 T* it, const Instruction* inst, MethodType method_type, bool is_range, ArtMethod* res_method) {
Andreas Gampee383d232018-06-19 12:29:51 -07003979 DCHECK_EQ(!is_range, inst->HasVarArgs());
3980
Andreas Gampe95c0bf82014-06-16 14:06:52 -07003981 // We use vAA as our expected arg count, rather than res_method->insSize, because we need to
3982 // match the call to the signature. Also, we might be calling through an abstract method
3983 // definition (which doesn't have register count values).
Orion Hodsoncfa325e2016-10-13 10:25:54 +01003984 const size_t expected_args = inst->VRegA();
Andreas Gampe95c0bf82014-06-16 14:06:52 -07003985 /* caught by static verifier */
3986 DCHECK(is_range || expected_args <= 5);
Andreas Gampe95c0bf82014-06-16 14:06:52 -07003987
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003988 if (expected_args > code_item_accessor_.OutsSize()) {
Orion Hodson1cda7c22017-08-10 13:06:45 +01003989 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "invalid argument count (" << expected_args
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08003990 << ") exceeds outsSize ("
3991 << code_item_accessor_.OutsSize() << ")";
Orion Hodson1cda7c22017-08-10 13:06:45 +01003992 return nullptr;
Andreas Gampe95c0bf82014-06-16 14:06:52 -07003993 }
Andreas Gampe95c0bf82014-06-16 14:06:52 -07003994
3995 /*
3996 * Check the "this" argument, which must be an instance of the class that declared the method.
3997 * For an interface class, we don't do the full interface merge (see JoinClass), so we can't do a
3998 * rigorous check here (which is okay since we have to do it at runtime).
3999 */
4000 if (method_type != METHOD_STATIC) {
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004001 const RegType& actual_arg_type = work_line_->GetInvocationThis(this, inst);
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004002 if (actual_arg_type.IsConflict()) { // GetInvocationThis failed.
4003 CHECK(have_pending_hard_failure_);
4004 return nullptr;
4005 }
David Brazdil68b5c0b2016-01-19 14:25:29 +00004006 bool is_init = false;
4007 if (actual_arg_type.IsUninitializedTypes()) {
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004008 if (res_method) {
4009 if (!res_method->IsConstructor()) {
4010 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
4011 return nullptr;
4012 }
4013 } else {
4014 // Check whether the name of the called method is "<init>"
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00004015 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
Jeff Hao0d087272014-08-04 14:47:17 -07004016 if (strcmp(dex_file_->GetMethodName(dex_file_->GetMethodId(method_idx)), "<init>") != 0) {
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004017 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "'this' arg must be initialized";
4018 return nullptr;
4019 }
4020 }
David Brazdil68b5c0b2016-01-19 14:25:29 +00004021 is_init = true;
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004022 }
David Brazdil68b5c0b2016-01-19 14:25:29 +00004023 const RegType& adjusted_type = is_init
4024 ? GetRegTypeCache()->FromUninitialized(actual_arg_type)
4025 : actual_arg_type;
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08004026 if (method_type != METHOD_INTERFACE && !adjusted_type.IsZeroOrNull()) {
Ian Rogersd8f69b02014-09-10 21:43:52 +00004027 const RegType* res_method_class;
Andreas Gamped9e23012015-06-04 22:19:58 -07004028 // Miranda methods have the declaring interface as their declaring class, not the abstract
4029 // class. It would be wrong to use this for the type check (interface type checks are
4030 // postponed to runtime).
4031 if (res_method != nullptr && !res_method->IsMiranda()) {
Vladimir Markod93e3742018-07-18 10:58:13 +01004032 ObjPtr<mirror::Class> klass = res_method->GetDeclaringClass();
Ian Rogers1ff3c982014-08-12 02:30:58 -07004033 std::string temp;
Andreas Gampef23f33d2015-06-23 14:18:17 -07004034 res_method_class = &FromClass(klass->GetDescriptor(&temp), klass,
4035 klass->CannotBeAssignedFromOtherTypes());
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004036 } else {
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00004037 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
Andreas Gampea5b09a62016-11-17 15:21:22 -08004038 const dex::TypeIndex class_idx = dex_file_->GetMethodId(method_idx).class_idx_;
Mathieu Chartierde40d472015-10-15 17:47:48 -07004039 res_method_class = &reg_types_.FromDescriptor(
Andreas Gampe51de69e2019-04-19 15:14:14 -07004040 class_loader_.Get(),
Mathieu Chartierde40d472015-10-15 17:47:48 -07004041 dex_file_->StringByTypeIdx(class_idx),
4042 false);
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004043 }
David Brazdilca3c8c32016-09-06 14:04:48 +01004044 if (!res_method_class->IsAssignableFrom(adjusted_type, this)) {
David Brazdil68b5c0b2016-01-19 14:25:29 +00004045 Fail(adjusted_type.IsUnresolvedTypes()
4046 ? VERIFY_ERROR_NO_CLASS
4047 : VERIFY_ERROR_BAD_CLASS_SOFT)
4048 << "'this' argument '" << actual_arg_type << "' not instance of '"
4049 << *res_method_class << "'";
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004050 // Continue on soft failures. We need to find possible hard failures to avoid problems in
4051 // the compiler.
4052 if (have_pending_hard_failure_) {
4053 return nullptr;
4054 }
4055 }
4056 }
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004057 }
4058
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004059 uint32_t arg[5];
4060 if (!is_range) {
4061 inst->GetVarArgs(arg);
4062 }
4063 uint32_t sig_registers = (method_type == METHOD_STATIC) ? 0 : 1;
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004064 for ( ; it->HasNext(); it->Next()) {
4065 if (sig_registers >= expected_args) {
4066 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << inst->VRegA() <<
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004067 " argument registers, method signature has " << sig_registers + 1 << " or more";
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004068 return nullptr;
4069 }
4070
4071 const char* param_descriptor = it->GetDescriptor();
4072
4073 if (param_descriptor == nullptr) {
4074 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation because of missing signature "
4075 "component";
4076 return nullptr;
4077 }
4078
Andreas Gampe51de69e2019-04-19 15:14:14 -07004079 const RegType& reg_type = reg_types_.FromDescriptor(class_loader_.Get(),
4080 param_descriptor,
4081 false);
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004082 uint32_t get_reg = is_range ? inst->VRegC() + static_cast<uint32_t>(sig_registers) :
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004083 arg[sig_registers];
4084 if (reg_type.IsIntegralTypes()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004085 const RegType& src_type = work_line_->GetRegisterType(this, get_reg);
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004086 if (!src_type.IsIntegralTypes()) {
4087 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "register v" << get_reg << " has type " << src_type
4088 << " but expected " << reg_type;
Andreas Gampeb588f4c2015-05-26 13:35:39 -07004089 return nullptr;
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004090 }
Andreas Gampeda9badb2015-06-05 20:22:12 -07004091 } else {
4092 if (!work_line_->VerifyRegisterType(this, get_reg, reg_type)) {
4093 // Continue on soft failures. We need to find possible hard failures to avoid problems in
4094 // the compiler.
4095 if (have_pending_hard_failure_) {
4096 return nullptr;
4097 }
4098 } else if (reg_type.IsLongOrDoubleTypes()) {
4099 // Check that registers are consecutive (for non-range invokes). Invokes are the only
4100 // instructions not specifying register pairs by the first component, but require them
4101 // nonetheless. Only check when there's an actual register in the parameters. If there's
4102 // none, this will fail below.
4103 if (!is_range && sig_registers + 1 < expected_args) {
4104 uint32_t second_reg = arg[sig_registers + 1];
4105 if (second_reg != get_reg + 1) {
4106 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, long or double parameter "
4107 "at index " << sig_registers << " is not a pair: " << get_reg << " + "
4108 << second_reg << ".";
4109 return nullptr;
4110 }
4111 }
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004112 }
4113 }
4114 sig_registers += reg_type.IsLongOrDoubleTypes() ? 2 : 1;
4115 }
4116 if (expected_args != sig_registers) {
4117 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Rejecting invocation, expected " << expected_args <<
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004118 " argument registers, method signature has " << sig_registers;
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004119 return nullptr;
4120 }
4121 return res_method;
4122}
4123
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004124template <bool kVerifierDebug>
4125void MethodVerifier<kVerifierDebug>::VerifyInvocationArgsUnresolvedMethod(const Instruction* inst,
4126 MethodType method_type,
4127 bool is_range) {
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004128 // As the method may not have been resolved, make this static check against what we expect.
4129 // The main reason for this code block is to fail hard when we find an illegal use, e.g.,
4130 // wrong number of arguments or wrong primitive types, even if the method could not be resolved.
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00004131 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004132 DexFileParameterIterator it(*dex_file_,
4133 dex_file_->GetProtoId(dex_file_->GetMethodId(method_idx).proto_idx_));
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004134 VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, nullptr);
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004135}
4136
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004137template <bool kVerifierDebug>
4138bool MethodVerifier<kVerifierDebug>::CheckCallSite(uint32_t call_site_idx) {
Orion Hodson3a842f52017-04-21 15:24:10 +01004139 if (call_site_idx >= dex_file_->NumCallSiteIds()) {
4140 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Bad call site id #" << call_site_idx
4141 << " >= " << dex_file_->NumCallSiteIds();
4142 return false;
4143 }
4144
Orion Hodsonc069a302017-01-18 09:23:12 +00004145 CallSiteArrayValueIterator it(*dex_file_, dex_file_->GetCallSiteId(call_site_idx));
4146 // Check essential arguments are provided. The dex file verifier has verified indicies of the
4147 // main values (method handle, name, method_type).
Orion Hodson4c8e12e2018-05-18 08:33:20 +01004148 static const size_t kRequiredArguments = 3;
4149 if (it.Size() < kRequiredArguments) {
Orion Hodsonc069a302017-01-18 09:23:12 +00004150 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site #" << call_site_idx
4151 << " has too few arguments: "
Orion Hodson4c8e12e2018-05-18 08:33:20 +01004152 << it.Size() << " < " << kRequiredArguments;
Orion Hodsonc069a302017-01-18 09:23:12 +00004153 return false;
4154 }
4155
Orion Hodson4c8e12e2018-05-18 08:33:20 +01004156 std::pair<const EncodedArrayValueIterator::ValueType, size_t> type_and_max[kRequiredArguments] =
4157 { { EncodedArrayValueIterator::ValueType::kMethodHandle, dex_file_->NumMethodHandles() },
4158 { EncodedArrayValueIterator::ValueType::kString, dex_file_->NumStringIds() },
4159 { EncodedArrayValueIterator::ValueType::kMethodType, dex_file_->NumProtoIds() }
4160 };
4161 uint32_t index[kRequiredArguments];
4162
4163 // Check arguments have expected types and are within permitted ranges.
4164 for (size_t i = 0; i < kRequiredArguments; ++i) {
4165 if (it.GetValueType() != type_and_max[i].first) {
4166 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site id #" << call_site_idx
4167 << " argument " << i << " has wrong type "
4168 << it.GetValueType() << "!=" << type_and_max[i].first;
4169 return false;
4170 }
4171 index[i] = static_cast<uint32_t>(it.GetJavaValue().i);
4172 if (index[i] >= type_and_max[i].second) {
4173 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site id #" << call_site_idx
4174 << " argument " << i << " bad index "
4175 << index[i] << " >= " << type_and_max[i].second;
4176 return false;
4177 }
4178 it.Next();
Orion Hodsona5dca522018-02-27 12:42:11 +00004179 }
Orion Hodson3a842f52017-04-21 15:24:10 +01004180
Orion Hodson4c8e12e2018-05-18 08:33:20 +01004181 // Check method handle kind is valid.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004182 const dex::MethodHandleItem& mh = dex_file_->GetMethodHandle(index[0]);
Orion Hodsonc069a302017-01-18 09:23:12 +00004183 if (mh.method_handle_type_ != static_cast<uint16_t>(DexFile::MethodHandleType::kInvokeStatic)) {
4184 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Call site #" << call_site_idx
Orion Hodson631827d2017-04-10 14:53:47 +01004185 << " argument 0 method handle type is not InvokeStatic: "
4186 << mh.method_handle_type_;
Orion Hodsonc069a302017-01-18 09:23:12 +00004187 return false;
4188 }
Orion Hodsonc069a302017-01-18 09:23:12 +00004189 return true;
4190}
4191
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004192class MethodParamListDescriptorIterator {
4193 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07004194 explicit MethodParamListDescriptorIterator(ArtMethod* res_method) :
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004195 res_method_(res_method), pos_(0), params_(res_method->GetParameterTypeList()),
4196 params_size_(params_ == nullptr ? 0 : params_->Size()) {
4197 }
4198
4199 bool HasNext() {
4200 return pos_ < params_size_;
4201 }
4202
4203 void Next() {
4204 ++pos_;
4205 }
4206
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004207 const char* GetDescriptor() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004208 return res_method_->GetTypeDescriptorFromTypeIdx(params_->GetTypeItem(pos_).type_idx_);
4209 }
4210
4211 private:
Mathieu Chartiere401d142015-04-22 13:56:20 -07004212 ArtMethod* res_method_;
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004213 size_t pos_;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004214 const dex::TypeList* params_;
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004215 const size_t params_size_;
4216};
4217
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004218template <bool kVerifierDebug>
4219ArtMethod* MethodVerifier<kVerifierDebug>::VerifyInvocationArgs(
Alex Light7268d472016-01-20 15:50:01 -08004220 const Instruction* inst, MethodType method_type, bool is_range) {
jeffhao8cd6dda2012-02-22 10:15:34 -08004221 // Resolve the method. This could be an abstract or concrete method depending on what sort of call
4222 // we're making.
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00004223 const uint32_t method_idx = GetMethodIdxOfInvoke(inst);
Alex Light7268d472016-01-20 15:50:01 -08004224 ArtMethod* res_method = ResolveMethodAndCheckAccess(method_idx, method_type);
Ian Rogers7b078e82014-09-10 14:44:24 -07004225 if (res_method == nullptr) { // error or class is unresolved
Andreas Gampe95c0bf82014-06-16 14:06:52 -07004226 // Check what we can statically.
4227 if (!have_pending_hard_failure_) {
4228 VerifyInvocationArgsUnresolvedMethod(inst, method_type, is_range);
4229 }
4230 return nullptr;
jeffhao8cd6dda2012-02-22 10:15:34 -08004231 }
4232
Ian Rogersd81871c2011-10-03 13:57:23 -07004233 // If we're using invoke-super(method), make sure that the executing method's class' superclass
Alex Light705ad492015-09-21 11:36:30 -07004234 // has a vtable entry for the target method. Or the target is on a interface.
Alex Light7268d472016-01-20 15:50:01 -08004235 if (method_type == METHOD_SUPER) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08004236 dex::TypeIndex class_idx = dex_file_->GetMethodId(method_idx).class_idx_;
David Brazdilca3c8c32016-09-06 14:04:48 +01004237 const RegType& reference_type = reg_types_.FromDescriptor(
Andreas Gampe51de69e2019-04-19 15:14:14 -07004238 class_loader_.Get(),
David Brazdilca3c8c32016-09-06 14:04:48 +01004239 dex_file_->StringByTypeIdx(class_idx),
4240 false);
4241 if (reference_type.IsUnresolvedTypes()) {
Alex Lightfedd91d2016-01-07 14:49:16 -08004242 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "Unable to find referenced class from invoke-super";
4243 return nullptr;
4244 }
David Brazdilca3c8c32016-09-06 14:04:48 +01004245 if (reference_type.GetClass()->IsInterface()) {
Alex Lightfedd91d2016-01-07 14:49:16 -08004246 // TODO Can we verify anything else.
David Brazdil15fc7292016-09-02 14:13:18 +01004247 if (class_idx == class_def_.class_idx_) {
Alex Lightfedd91d2016-01-07 14:49:16 -08004248 Fail(VERIFY_ERROR_CLASS_CHANGE) << "Cannot invoke-super on self as interface";
Alex Light55ea94d2016-03-15 09:50:26 -07004249 return nullptr;
Alex Lightfedd91d2016-01-07 14:49:16 -08004250 }
4251 // TODO Revisit whether we want to allow invoke-super on direct interfaces only like the JLS
4252 // does.
Alex Light55ea94d2016-03-15 09:50:26 -07004253 if (!GetDeclaringClass().HasClass()) {
4254 Fail(VERIFY_ERROR_NO_CLASS) << "Unable to resolve the full class of 'this' used in an"
4255 << "interface invoke-super";
4256 return nullptr;
David Brazdilca3c8c32016-09-06 14:04:48 +01004257 } else if (!reference_type.IsStrictlyAssignableFrom(GetDeclaringClass(), this)) {
Alex Lightfedd91d2016-01-07 14:49:16 -08004258 Fail(VERIFY_ERROR_CLASS_CHANGE)
David Sehr709b0702016-10-13 09:12:37 -07004259 << "invoke-super in " << mirror::Class::PrettyClass(GetDeclaringClass().GetClass())
4260 << " in method "
4261 << dex_file_->PrettyMethod(dex_method_idx_) << " to method "
4262 << dex_file_->PrettyMethod(method_idx) << " references "
4263 << "non-super-interface type " << mirror::Class::PrettyClass(reference_type.GetClass());
Alex Lightfedd91d2016-01-07 14:49:16 -08004264 return nullptr;
Alex Light705ad492015-09-21 11:36:30 -07004265 }
4266 } else {
4267 const RegType& super = GetDeclaringClass().GetSuperClass(&reg_types_);
4268 if (super.IsUnresolvedTypes()) {
4269 Fail(VERIFY_ERROR_NO_METHOD) << "unknown super class in invoke-super from "
David Sehr709b0702016-10-13 09:12:37 -07004270 << dex_file_->PrettyMethod(dex_method_idx_)
4271 << " to super " << res_method->PrettyMethod();
Alex Light705ad492015-09-21 11:36:30 -07004272 return nullptr;
4273 }
David Brazdilca3c8c32016-09-06 14:04:48 +01004274 if (!reference_type.IsStrictlyAssignableFrom(GetDeclaringClass(), this) ||
Aart Bikf663e342016-04-04 17:28:59 -07004275 (res_method->GetMethodIndex() >= super.GetClass()->GetVTableLength())) {
Alex Light705ad492015-09-21 11:36:30 -07004276 Fail(VERIFY_ERROR_NO_METHOD) << "invalid invoke-super from "
David Sehr709b0702016-10-13 09:12:37 -07004277 << dex_file_->PrettyMethod(dex_method_idx_)
Alex Light705ad492015-09-21 11:36:30 -07004278 << " to super " << super
4279 << "." << res_method->GetName()
4280 << res_method->GetSignature();
4281 return nullptr;
4282 }
Ian Rogersd81871c2011-10-03 13:57:23 -07004283 }
4284 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004285
Andreas Gampe74979b12017-05-16 09:28:06 -07004286 if (UNLIKELY(method_type == METHOD_POLYMORPHIC)) {
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004287 // Process the signature of the calling site that is invoking the method handle.
Orion Hodson06d10a72018-05-14 08:53:38 +01004288 dex::ProtoIndex proto_idx(inst->VRegH());
4289 DexFileParameterIterator it(*dex_file_, dex_file_->GetProtoId(proto_idx));
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004290 return VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, res_method);
4291 } else {
4292 // Process the target method's signature.
4293 MethodParamListDescriptorIterator it(res_method);
4294 return VerifyInvocationArgsFromIterator(&it, inst, method_type, is_range, res_method);
4295 }
4296}
4297
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004298template <bool kVerifierDebug>
4299bool MethodVerifier<kVerifierDebug>::CheckSignaturePolymorphicMethod(ArtMethod* method) {
Vladimir Markod93e3742018-07-18 10:58:13 +01004300 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
Orion Hodsonfe92d122018-01-02 10:45:17 +00004301 const char* method_name = method->GetName();
4302
4303 const char* expected_return_descriptor;
Vladimir Markoc7aa87e2018-05-24 15:19:52 +01004304 ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
4305 Runtime::Current()->GetClassLinker()->GetClassRoots();
4306 if (klass == GetClassRoot<mirror::MethodHandle>(class_roots)) {
Orion Hodsonfe92d122018-01-02 10:45:17 +00004307 expected_return_descriptor = mirror::MethodHandle::GetReturnTypeDescriptor(method_name);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +01004308 } else if (klass == GetClassRoot<mirror::VarHandle>(class_roots)) {
Orion Hodsonfe92d122018-01-02 10:45:17 +00004309 expected_return_descriptor = mirror::VarHandle::GetReturnTypeDescriptor(method_name);
4310 } else {
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004311 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
Orion Hodsonfe92d122018-01-02 10:45:17 +00004312 << "Signature polymorphic method in unsuppported class: " << klass->PrettyDescriptor();
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004313 return false;
4314 }
4315
Orion Hodsonfe92d122018-01-02 10:45:17 +00004316 if (expected_return_descriptor == nullptr) {
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004317 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4318 << "Signature polymorphic method name invalid: " << method_name;
4319 return false;
4320 }
4321
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004322 const dex::TypeList* types = method->GetParameterTypeList();
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004323 if (types->Size() != 1) {
4324 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4325 << "Signature polymorphic method has too many arguments " << types->Size() << " != 1";
4326 return false;
4327 }
4328
4329 const dex::TypeIndex argument_type_index = types->GetTypeItem(0).type_idx_;
4330 const char* argument_descriptor = method->GetTypeDescriptorFromTypeIdx(argument_type_index);
4331 if (strcmp(argument_descriptor, "[Ljava/lang/Object;") != 0) {
4332 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4333 << "Signature polymorphic method has unexpected argument type: " << argument_descriptor;
4334 return false;
4335 }
4336
4337 const char* return_descriptor = method->GetReturnTypeDescriptor();
Orion Hodsonfe92d122018-01-02 10:45:17 +00004338 if (strcmp(return_descriptor, expected_return_descriptor) != 0) {
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004339 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
Orion Hodsonfe92d122018-01-02 10:45:17 +00004340 << "Signature polymorphic method has unexpected return type: " << return_descriptor
4341 << " != " << expected_return_descriptor;
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004342 return false;
4343 }
4344
4345 return true;
4346}
4347
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004348template <bool kVerifierDebug>
4349bool MethodVerifier<kVerifierDebug>::CheckSignaturePolymorphicReceiver(const Instruction* inst) {
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004350 const RegType& this_type = work_line_->GetInvocationThis(this, inst);
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08004351 if (this_type.IsZeroOrNull()) {
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004352 /* null pointer always passes (and always fails at run time) */
4353 return true;
4354 } else if (!this_type.IsNonZeroReferenceTypes()) {
4355 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4356 << "invoke-polymorphic receiver is not a reference: "
4357 << this_type;
4358 return false;
4359 } else if (this_type.IsUninitializedReference()) {
4360 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4361 << "invoke-polymorphic receiver is uninitialized: "
4362 << this_type;
4363 return false;
4364 } else if (!this_type.HasClass()) {
4365 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4366 << "invoke-polymorphic receiver has no class: "
4367 << this_type;
4368 return false;
Vladimir Markoc7aa87e2018-05-24 15:19:52 +01004369 } else {
4370 ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
4371 Runtime::Current()->GetClassLinker()->GetClassRoots();
4372 if (!this_type.GetClass()->IsSubClass(GetClassRoot<mirror::MethodHandle>(class_roots)) &&
4373 !this_type.GetClass()->IsSubClass(GetClassRoot<mirror::VarHandle>(class_roots))) {
4374 Fail(VERIFY_ERROR_BAD_CLASS_HARD)
4375 << "invoke-polymorphic receiver is not a subclass of MethodHandle or VarHandle: "
4376 << this_type;
4377 return false;
4378 }
Orion Hodsoncfa325e2016-10-13 10:25:54 +01004379 }
4380 return true;
Ian Rogersd81871c2011-10-03 13:57:23 -07004381}
4382
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004383template <bool kVerifierDebug>
4384uint16_t MethodVerifier<kVerifierDebug>::GetMethodIdxOfInvoke(const Instruction* inst) {
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00004385 switch (inst->Opcode()) {
4386 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK:
4387 case Instruction::INVOKE_VIRTUAL_QUICK: {
4388 DCHECK(Runtime::Current()->IsStarted() || verify_to_dump_)
4389 << dex_file_->PrettyMethod(dex_method_idx_, true) << "@" << work_insn_idx_;
4390 DCHECK(method_being_verified_ != nullptr);
4391 uint16_t method_idx = method_being_verified_->GetIndexFromQuickening(work_insn_idx_);
4392 CHECK_NE(method_idx, DexFile::kDexNoIndex16);
4393 return method_idx;
4394 }
4395 default: {
4396 return inst->VRegB();
4397 }
Mathieu Chartier091d2382015-03-06 10:59:06 -08004398 }
Sebastien Hertzc15853b2013-06-25 17:36:27 +02004399}
4400
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004401template <bool kVerifierDebug>
4402uint16_t MethodVerifier<kVerifierDebug>::GetFieldIdxOfFieldAccess(const Instruction* inst,
4403 bool is_static) {
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00004404 if (is_static) {
4405 return inst->VRegB_21c();
4406 } else if (inst->IsQuickened()) {
4407 DCHECK(Runtime::Current()->IsStarted() || verify_to_dump_);
4408 DCHECK(method_being_verified_ != nullptr);
4409 uint16_t field_idx = method_being_verified_->GetIndexFromQuickening(work_insn_idx_);
4410 CHECK_NE(field_idx, DexFile::kDexNoIndex16);
4411 return field_idx;
Sebastien Hertz2d6ba512013-05-17 11:31:37 +02004412 } else {
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00004413 return inst->VRegC_22c();
Sebastien Hertz2d6ba512013-05-17 11:31:37 +02004414 }
4415}
4416
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004417template <bool kVerifierDebug>
4418void MethodVerifier<kVerifierDebug>::VerifyNewArray(const Instruction* inst,
4419 bool is_filled,
4420 bool is_range) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08004421 dex::TypeIndex type_idx;
Sebastien Hertz5243e912013-05-21 10:55:07 +02004422 if (!is_filled) {
4423 DCHECK_EQ(inst->Opcode(), Instruction::NEW_ARRAY);
Andreas Gampea5b09a62016-11-17 15:21:22 -08004424 type_idx = dex::TypeIndex(inst->VRegC_22c());
Sebastien Hertz5243e912013-05-21 10:55:07 +02004425 } else if (!is_range) {
4426 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY);
Andreas Gampea5b09a62016-11-17 15:21:22 -08004427 type_idx = dex::TypeIndex(inst->VRegB_35c());
Sebastien Hertz5243e912013-05-21 10:55:07 +02004428 } else {
4429 DCHECK_EQ(inst->Opcode(), Instruction::FILLED_NEW_ARRAY_RANGE);
Andreas Gampea5b09a62016-11-17 15:21:22 -08004430 type_idx = dex::TypeIndex(inst->VRegB_3rc());
Sebastien Hertz5243e912013-05-21 10:55:07 +02004431 }
Andreas Gampe98be1a92017-08-28 08:25:45 -07004432 const RegType& res_type = ResolveClass<CheckAccess::kYes>(type_idx);
Ian Rogersad0b3a32012-04-16 14:50:24 -07004433 if (res_type.IsConflict()) { // bad class
4434 DCHECK_NE(failures_.size(), 0U);
Ian Rogers0c4a5062012-02-03 15:18:59 -08004435 } else {
4436 // TODO: check Compiler::CanAccessTypeWithoutChecks returns false when res_type is unresolved
4437 if (!res_type.IsArrayTypes()) {
jeffhaod5347e02012-03-22 17:25:05 -07004438 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "new-array on non-array class " << res_type;
Ian Rogers0c4a5062012-02-03 15:18:59 -08004439 } else if (!is_filled) {
4440 /* make sure "size" register is valid type */
Ian Rogers7b078e82014-09-10 14:44:24 -07004441 work_line_->VerifyRegisterType(this, inst->VRegB_22c(), reg_types_.Integer());
Ian Rogers0c4a5062012-02-03 15:18:59 -08004442 /* set register type to array class */
Ian Rogersd8f69b02014-09-10 21:43:52 +00004443 const RegType& precise_type = reg_types_.FromUninitialized(res_type);
Andreas Gampead238ce2015-08-24 21:13:08 -07004444 work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_22c(), precise_type);
Ian Rogers0c4a5062012-02-03 15:18:59 -08004445 } else {
Andreas Gampebb18a032016-03-22 20:34:25 -07004446 DCHECK(!res_type.IsUnresolvedMergedReference());
Ian Rogers0c4a5062012-02-03 15:18:59 -08004447 // Verify each register. If "arg_count" is bad, VerifyRegisterType() will run off the end of
4448 // the list and fail. It's legal, if silly, for arg_count to be zero.
Andreas Gampe51de69e2019-04-19 15:14:14 -07004449 const RegType& expected_type = reg_types_.GetComponentType(res_type, class_loader_.Get());
Sebastien Hertz5243e912013-05-21 10:55:07 +02004450 uint32_t arg_count = (is_range) ? inst->VRegA_3rc() : inst->VRegA_35c();
4451 uint32_t arg[5];
4452 if (!is_range) {
Ian Rogers29a26482014-05-02 15:27:29 -07004453 inst->GetVarArgs(arg);
Sebastien Hertz5243e912013-05-21 10:55:07 +02004454 }
Ian Rogers0c4a5062012-02-03 15:18:59 -08004455 for (size_t ui = 0; ui < arg_count; ui++) {
Sebastien Hertz5243e912013-05-21 10:55:07 +02004456 uint32_t get_reg = is_range ? inst->VRegC_3rc() + ui : arg[ui];
Ian Rogers7b078e82014-09-10 14:44:24 -07004457 if (!work_line_->VerifyRegisterType(this, get_reg, expected_type)) {
4458 work_line_->SetResultRegisterType(this, reg_types_.Conflict());
Ian Rogers0c4a5062012-02-03 15:18:59 -08004459 return;
4460 }
4461 }
4462 // filled-array result goes into "result" register
Ian Rogersd8f69b02014-09-10 21:43:52 +00004463 const RegType& precise_type = reg_types_.FromUninitialized(res_type);
Ian Rogers7b078e82014-09-10 14:44:24 -07004464 work_line_->SetResultRegisterType(this, precise_type);
Ian Rogers0c4a5062012-02-03 15:18:59 -08004465 }
4466 }
4467}
4468
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004469template <bool kVerifierDebug>
4470void MethodVerifier<kVerifierDebug>::VerifyAGet(const Instruction* inst,
4471 const RegType& insn_type,
4472 bool is_primitive) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004473 const RegType& index_type = work_line_->GetRegisterType(this, inst->VRegC_23x());
Ian Rogersd81871c2011-10-03 13:57:23 -07004474 if (!index_type.IsArrayIndexTypes()) {
jeffhaod5347e02012-03-22 17:25:05 -07004475 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07004476 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -07004477 const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegB_23x());
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08004478 if (array_type.IsZeroOrNull()) {
Ian Rogers89310de2012-02-01 13:47:30 -08004479 // Null array class; this code path will fail at runtime. Infer a merge-able type from the
Andreas Gampe52f205a2017-12-01 12:16:07 -08004480 // instruction type.
4481 if (!is_primitive) {
4482 work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), reg_types_.Null());
4483 } else if (insn_type.IsInteger()) {
4484 // Pick a non-zero constant (to distinguish with null) that can fit in any primitive.
4485 // We cannot use 'insn_type' as it could be a float array or an int array.
4486 work_line_->SetRegisterType<LockOp::kClear>(
4487 this, inst->VRegA_23x(), DetermineCat1Constant(1, need_precise_constants_));
4488 } else if (insn_type.IsCategory1Types()) {
4489 // Category 1
4490 // The 'insn_type' is exactly the type we need.
4491 work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), insn_type);
Ian Rogersd81871c2011-10-03 13:57:23 -07004492 } else {
Ian Rogers89310de2012-02-01 13:47:30 -08004493 // Category 2
Ian Rogers7b078e82014-09-10 14:44:24 -07004494 work_line_->SetRegisterTypeWide(this, inst->VRegA_23x(),
4495 reg_types_.FromCat2ConstLo(0, false),
Ian Rogers2bcb4a42012-11-08 10:39:18 -08004496 reg_types_.FromCat2ConstHi(0, false));
Ian Rogers89310de2012-02-01 13:47:30 -08004497 }
jeffhaofc3144e2012-02-01 17:21:15 -08004498 } else if (!array_type.IsArrayTypes()) {
jeffhaod5347e02012-03-22 17:25:05 -07004499 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aget";
Andreas Gampe8d8fc482016-03-25 16:24:20 -07004500 } else if (array_type.IsUnresolvedMergedReference()) {
Andreas Gampebb18a032016-03-22 20:34:25 -07004501 // Unresolved array types must be reference array types.
4502 if (is_primitive) {
4503 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type
4504 << " source for category 1 aget";
4505 } else {
4506 Fail(VERIFY_ERROR_NO_CLASS) << "cannot verify aget for " << array_type
4507 << " because of missing class";
Andreas Gampe8d8fc482016-03-25 16:24:20 -07004508 // Approximate with java.lang.Object[].
4509 work_line_->SetRegisterType<LockOp::kClear>(this,
4510 inst->VRegA_23x(),
4511 reg_types_.JavaLangObject(false));
Andreas Gampebb18a032016-03-22 20:34:25 -07004512 }
Ian Rogers89310de2012-02-01 13:47:30 -08004513 } else {
4514 /* verify the class */
Andreas Gampe51de69e2019-04-19 15:14:14 -07004515 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_.Get());
jeffhaofc3144e2012-02-01 17:21:15 -08004516 if (!component_type.IsReferenceTypes() && !is_primitive) {
jeffhaod5347e02012-03-22 17:25:05 -07004517 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
Ian Rogers89310de2012-02-01 13:47:30 -08004518 << " source for aget-object";
4519 } else if (component_type.IsNonZeroReferenceTypes() && is_primitive) {
jeffhaod5347e02012-03-22 17:25:05 -07004520 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "reference array type " << array_type
Ian Rogers89310de2012-02-01 13:47:30 -08004521 << " source for category 1 aget";
4522 } else if (is_primitive && !insn_type.Equals(component_type) &&
4523 !((insn_type.IsInteger() && component_type.IsFloat()) ||
Ian Rogers2bcb4a42012-11-08 10:39:18 -08004524 (insn_type.IsLong() && component_type.IsDouble()))) {
4525 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "array type " << array_type
4526 << " incompatible with aget of type " << insn_type;
Ian Rogers89310de2012-02-01 13:47:30 -08004527 } else {
Ian Rogers2bcb4a42012-11-08 10:39:18 -08004528 // Use knowledge of the field type which is stronger than the type inferred from the
4529 // instruction, which can't differentiate object types and ints from floats, longs from
4530 // doubles.
4531 if (!component_type.IsLowHalf()) {
Andreas Gampead238ce2015-08-24 21:13:08 -07004532 work_line_->SetRegisterType<LockOp::kClear>(this, inst->VRegA_23x(), component_type);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08004533 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -07004534 work_line_->SetRegisterTypeWide(this, inst->VRegA_23x(), component_type,
Ian Rogers2bcb4a42012-11-08 10:39:18 -08004535 component_type.HighHalf(&reg_types_));
4536 }
Ian Rogersd81871c2011-10-03 13:57:23 -07004537 }
4538 }
4539 }
4540}
4541
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004542template <bool kVerifierDebug>
4543void MethodVerifier<kVerifierDebug>::VerifyPrimitivePut(const RegType& target_type,
4544 const RegType& insn_type,
4545 const uint32_t vregA) {
Jeff Haofe1f7c82013-08-01 14:50:24 -07004546 // Primitive assignability rules are weaker than regular assignability rules.
4547 bool instruction_compatible;
4548 bool value_compatible;
Ian Rogers7b078e82014-09-10 14:44:24 -07004549 const RegType& value_type = work_line_->GetRegisterType(this, vregA);
Jeff Haofe1f7c82013-08-01 14:50:24 -07004550 if (target_type.IsIntegralTypes()) {
Jeff Haoa4647482013-08-06 15:35:47 -07004551 instruction_compatible = target_type.Equals(insn_type);
Jeff Haofe1f7c82013-08-01 14:50:24 -07004552 value_compatible = value_type.IsIntegralTypes();
4553 } else if (target_type.IsFloat()) {
4554 instruction_compatible = insn_type.IsInteger(); // no put-float, so expect put-int
4555 value_compatible = value_type.IsFloatTypes();
4556 } else if (target_type.IsLong()) {
4557 instruction_compatible = insn_type.IsLong();
Andreas Gampe376fa682014-09-07 13:06:12 -07004558 // Additional register check: this is not checked statically (as part of VerifyInstructions),
4559 // as target_type depends on the resolved type of the field.
4560 if (instruction_compatible && work_line_->NumRegs() > vregA + 1) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004561 const RegType& value_type_hi = work_line_->GetRegisterType(this, vregA + 1);
Andreas Gampe376fa682014-09-07 13:06:12 -07004562 value_compatible = value_type.IsLongTypes() && value_type.CheckWidePair(value_type_hi);
4563 } else {
4564 value_compatible = false;
4565 }
Jeff Haofe1f7c82013-08-01 14:50:24 -07004566 } else if (target_type.IsDouble()) {
4567 instruction_compatible = insn_type.IsLong(); // no put-double, so expect put-long
Andreas Gampe376fa682014-09-07 13:06:12 -07004568 // Additional register check: this is not checked statically (as part of VerifyInstructions),
4569 // as target_type depends on the resolved type of the field.
4570 if (instruction_compatible && work_line_->NumRegs() > vregA + 1) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004571 const RegType& value_type_hi = work_line_->GetRegisterType(this, vregA + 1);
Andreas Gampe376fa682014-09-07 13:06:12 -07004572 value_compatible = value_type.IsDoubleTypes() && value_type.CheckWidePair(value_type_hi);
4573 } else {
4574 value_compatible = false;
4575 }
Jeff Haofe1f7c82013-08-01 14:50:24 -07004576 } else {
4577 instruction_compatible = false; // reference with primitive store
4578 value_compatible = false; // unused
4579 }
4580 if (!instruction_compatible) {
4581 // This is a global failure rather than a class change failure as the instructions and
4582 // the descriptors for the type should have been consistent within the same file at
4583 // compile time.
4584 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type
4585 << "' but expected type '" << target_type << "'";
4586 return;
4587 }
4588 if (!value_compatible) {
4589 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "unexpected value in v" << vregA
4590 << " of type " << value_type << " but expected " << target_type << " for put";
4591 return;
4592 }
4593}
4594
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004595template <bool kVerifierDebug>
4596void MethodVerifier<kVerifierDebug>::VerifyAPut(const Instruction* inst,
4597 const RegType& insn_type,
4598 bool is_primitive) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004599 const RegType& index_type = work_line_->GetRegisterType(this, inst->VRegC_23x());
Ian Rogersd81871c2011-10-03 13:57:23 -07004600 if (!index_type.IsArrayIndexTypes()) {
jeffhaod5347e02012-03-22 17:25:05 -07004601 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "Invalid reg type for array index (" << index_type << ")";
Ian Rogersd81871c2011-10-03 13:57:23 -07004602 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -07004603 const RegType& array_type = work_line_->GetRegisterType(this, inst->VRegB_23x());
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08004604 if (array_type.IsZeroOrNull()) {
Nicolas Geoffray66389fb2015-06-19 10:35:42 +01004605 // Null array type; this code path will fail at runtime.
4606 // Still check that the given value matches the instruction's type.
Andreas Gampe4bf4c782015-08-14 14:07:43 -07004607 // Note: this is, as usual, complicated by the fact the the instruction isn't fully typed
4608 // and fits multiple register types.
4609 const RegType* modified_reg_type = &insn_type;
4610 if ((modified_reg_type == &reg_types_.Integer()) ||
4611 (modified_reg_type == &reg_types_.LongLo())) {
4612 // May be integer or float | long or double. Overwrite insn_type accordingly.
4613 const RegType& value_type = work_line_->GetRegisterType(this, inst->VRegA_23x());
4614 if (modified_reg_type == &reg_types_.Integer()) {
4615 if (&value_type == &reg_types_.Float()) {
4616 modified_reg_type = &value_type;
4617 }
4618 } else {
4619 if (&value_type == &reg_types_.DoubleLo()) {
4620 modified_reg_type = &value_type;
4621 }
4622 }
4623 }
4624 work_line_->VerifyRegisterType(this, inst->VRegA_23x(), *modified_reg_type);
jeffhaofc3144e2012-02-01 17:21:15 -08004625 } else if (!array_type.IsArrayTypes()) {
jeffhaod5347e02012-03-22 17:25:05 -07004626 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "not array type " << array_type << " with aput";
Andreas Gampe8d8fc482016-03-25 16:24:20 -07004627 } else if (array_type.IsUnresolvedMergedReference()) {
Andreas Gampebb18a032016-03-22 20:34:25 -07004628 // Unresolved array types must be reference array types.
4629 if (is_primitive) {
4630 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "put insn has type '" << insn_type
4631 << "' but unresolved type '" << array_type << "'";
4632 } else {
4633 Fail(VERIFY_ERROR_NO_CLASS) << "cannot verify aput for " << array_type
4634 << " because of missing class";
4635 }
Ian Rogers89310de2012-02-01 13:47:30 -08004636 } else {
Andreas Gampe51de69e2019-04-19 15:14:14 -07004637 const RegType& component_type = reg_types_.GetComponentType(array_type, class_loader_.Get());
Jeff Haofe1f7c82013-08-01 14:50:24 -07004638 const uint32_t vregA = inst->VRegA_23x();
Jeff Haob24b4a72013-07-31 13:47:31 -07004639 if (is_primitive) {
Jeff Haofe1f7c82013-08-01 14:50:24 -07004640 VerifyPrimitivePut(component_type, insn_type, vregA);
Ian Rogersd81871c2011-10-03 13:57:23 -07004641 } else {
Jeff Haob24b4a72013-07-31 13:47:31 -07004642 if (!component_type.IsReferenceTypes()) {
4643 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "primitive array type " << array_type
4644 << " source for aput-object";
4645 } else {
4646 // The instruction agrees with the type of array, confirm the value to be stored does too
4647 // Note: we use the instruction type (rather than the component type) for aput-object as
4648 // incompatible classes will be caught at runtime as an array store exception
Ian Rogers7b078e82014-09-10 14:44:24 -07004649 work_line_->VerifyRegisterType(this, vregA, insn_type);
Jeff Haob24b4a72013-07-31 13:47:31 -07004650 }
Ian Rogersd81871c2011-10-03 13:57:23 -07004651 }
4652 }
4653 }
4654}
4655
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004656template <bool kVerifierDebug>
4657ArtField* MethodVerifier<kVerifierDebug>::GetStaticField(int field_idx) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004658 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
Ian Rogers90040192011-12-16 08:54:29 -08004659 // Check access to class
Andreas Gampe98be1a92017-08-28 08:25:45 -07004660 const RegType& klass_type = ResolveClass<CheckAccess::kYes>(field_id.class_idx_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004661 if (klass_type.IsConflict()) { // bad class
Ian Rogersad0b3a32012-04-16 14:50:24 -07004662 AppendToLastFailMessage(StringPrintf(" in attempt to access static field %d (%s) in %s",
4663 field_idx, dex_file_->GetFieldName(field_id),
4664 dex_file_->GetFieldDeclaringClassDescriptor(field_id)));
Ian Rogers7b078e82014-09-10 14:44:24 -07004665 return nullptr;
Ian Rogers90040192011-12-16 08:54:29 -08004666 }
Elliott Hughesb25c3f62012-03-26 16:35:06 -07004667 if (klass_type.IsUnresolvedTypes()) {
Andreas Gampe629be512017-08-25 17:09:32 -07004668 // Accessibility checks depend on resolved fields.
David Brazdil2bb2fbd2018-11-13 18:24:26 +00004669 DCHECK(klass_type.Equals(GetDeclaringClass()) ||
4670 !failures_.empty() ||
4671 IsSdkVersionSetAndLessThan(api_level_, SdkVersion::kP));
Andreas Gampe629be512017-08-25 17:09:32 -07004672
Ian Rogers7b078e82014-09-10 14:44:24 -07004673 return nullptr; // Can't resolve Class so no more to do here, will do checking at runtime.
Ian Rogers90040192011-12-16 08:54:29 -08004674 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004675 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Vladimir Markoe11dd502017-12-08 14:09:45 +00004676 ArtField* field = class_linker->ResolveFieldJLS(field_idx, dex_cache_, class_loader_);
David Brazdilca3c8c32016-09-06 14:04:48 +01004677
4678 // Record result of the field resolution attempt.
4679 VerifierDeps::MaybeRecordFieldResolution(*dex_file_, field_idx, field);
4680
Ian Rogers7b078e82014-09-10 14:44:24 -07004681 if (field == nullptr) {
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07004682 VLOG(verifier) << "Unable to resolve static field " << field_idx << " ("
Ian Rogersf4028cc2011-11-02 14:56:39 -07004683 << dex_file_->GetFieldName(field_id) << ") in "
4684 << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
Ian Rogers7b078e82014-09-10 14:44:24 -07004685 DCHECK(self_->IsExceptionPending());
4686 self_->ClearException();
4687 return nullptr;
Ian Rogersad0b3a32012-04-16 14:50:24 -07004688 } else if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(),
4689 field->GetAccessFlags())) {
David Sehr709b0702016-10-13 09:12:37 -07004690 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access static field " << field->PrettyField()
Ian Rogersad0b3a32012-04-16 14:50:24 -07004691 << " from " << GetDeclaringClass();
Ian Rogers7b078e82014-09-10 14:44:24 -07004692 return nullptr;
Ian Rogersd81871c2011-10-03 13:57:23 -07004693 } else if (!field->IsStatic()) {
David Sehr709b0702016-10-13 09:12:37 -07004694 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << field->PrettyField() << " to be static";
Ian Rogers7b078e82014-09-10 14:44:24 -07004695 return nullptr;
Ian Rogersd81871c2011-10-03 13:57:23 -07004696 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004697 return field;
Ian Rogersd81871c2011-10-03 13:57:23 -07004698}
4699
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004700template <bool kVerifierDebug>
4701ArtField* MethodVerifier<kVerifierDebug>::GetInstanceField(const RegType& obj_type, int field_idx) {
Andreas Gampeb34981b2019-05-06 13:00:40 -07004702 if (!obj_type.IsZeroOrNull() && !obj_type.IsReferenceTypes()) {
4703 // Trying to read a field from something that isn't a reference.
4704 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "instance field access on object that has "
4705 << "non-reference type " << obj_type;
4706 return nullptr;
4707 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004708 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
Aart Bik31883642016-06-06 15:02:44 -07004709 // Check access to class.
Andreas Gampe98be1a92017-08-28 08:25:45 -07004710 const RegType& klass_type = ResolveClass<CheckAccess::kYes>(field_id.class_idx_);
Ian Rogersad0b3a32012-04-16 14:50:24 -07004711 if (klass_type.IsConflict()) {
4712 AppendToLastFailMessage(StringPrintf(" in attempt to access instance field %d (%s) in %s",
4713 field_idx, dex_file_->GetFieldName(field_id),
4714 dex_file_->GetFieldDeclaringClassDescriptor(field_id)));
Ian Rogers7b078e82014-09-10 14:44:24 -07004715 return nullptr;
Ian Rogers90040192011-12-16 08:54:29 -08004716 }
jeffhao8cd6dda2012-02-22 10:15:34 -08004717 if (klass_type.IsUnresolvedTypes()) {
Andreas Gampe629be512017-08-25 17:09:32 -07004718 // Accessibility checks depend on resolved fields.
David Brazdil2bb2fbd2018-11-13 18:24:26 +00004719 DCHECK(klass_type.Equals(GetDeclaringClass()) ||
4720 !failures_.empty() ||
4721 IsSdkVersionSetAndLessThan(api_level_, SdkVersion::kP));
Andreas Gampe629be512017-08-25 17:09:32 -07004722
Ian Rogers7b078e82014-09-10 14:44:24 -07004723 return nullptr; // Can't resolve Class so no more to do here
Ian Rogers90040192011-12-16 08:54:29 -08004724 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004725 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Vladimir Markoe11dd502017-12-08 14:09:45 +00004726 ArtField* field = class_linker->ResolveFieldJLS(field_idx, dex_cache_, class_loader_);
David Brazdilca3c8c32016-09-06 14:04:48 +01004727
4728 // Record result of the field resolution attempt.
4729 VerifierDeps::MaybeRecordFieldResolution(*dex_file_, field_idx, field);
4730
Ian Rogers7b078e82014-09-10 14:44:24 -07004731 if (field == nullptr) {
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07004732 VLOG(verifier) << "Unable to resolve instance field " << field_idx << " ("
Ian Rogersf4028cc2011-11-02 14:56:39 -07004733 << dex_file_->GetFieldName(field_id) << ") in "
4734 << dex_file_->GetFieldDeclaringClassDescriptor(field_id);
Ian Rogers7b078e82014-09-10 14:44:24 -07004735 DCHECK(self_->IsExceptionPending());
4736 self_->ClearException();
4737 return nullptr;
Andreas Gampeeed3a5d2017-11-29 14:58:34 -08004738 } else if (obj_type.IsZeroOrNull()) {
Aart Bik31883642016-06-06 15:02:44 -07004739 // Cannot infer and check type, however, access will cause null pointer exception.
4740 // Fall through into a few last soft failure checks below.
Ian Rogerse1758fe2012-04-19 11:31:15 -07004741 } else {
David Brazdil0d638bb2016-07-27 15:29:25 +01004742 std::string temp;
Mathieu Chartier3398c782016-09-30 10:27:43 -07004743 ObjPtr<mirror::Class> klass = field->GetDeclaringClass();
Ian Rogersd8f69b02014-09-10 21:43:52 +00004744 const RegType& field_klass =
Vladimir Markobcf17522018-06-01 13:14:32 +01004745 FromClass(klass->GetDescriptor(&temp), klass, klass->CannotBeAssignedFromOtherTypes());
David Brazdil68b5c0b2016-01-19 14:25:29 +00004746 if (obj_type.IsUninitializedTypes()) {
Ian Rogersad0b3a32012-04-16 14:50:24 -07004747 // Field accesses through uninitialized references are only allowable for constructors where
David Brazdil68b5c0b2016-01-19 14:25:29 +00004748 // the field is declared in this class.
4749 // Note: this IsConstructor check is technically redundant, as UninitializedThis should only
4750 // appear in constructors.
4751 if (!obj_type.IsUninitializedThisReference() ||
4752 !IsConstructor() ||
4753 !field_klass.Equals(GetDeclaringClass())) {
David Sehr709b0702016-10-13 09:12:37 -07004754 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access instance field " << field->PrettyField()
David Brazdil68b5c0b2016-01-19 14:25:29 +00004755 << " of a not fully initialized object within the context"
David Sehr709b0702016-10-13 09:12:37 -07004756 << " of " << dex_file_->PrettyMethod(dex_method_idx_);
David Brazdil68b5c0b2016-01-19 14:25:29 +00004757 return nullptr;
4758 }
David Brazdilca3c8c32016-09-06 14:04:48 +01004759 } else if (!field_klass.IsAssignableFrom(obj_type, this)) {
Ian Rogersad0b3a32012-04-16 14:50:24 -07004760 // Trying to access C1.field1 using reference of type C2, which is neither C1 or a sub-class
4761 // of C1. For resolution to occur the declared class of the field must be compatible with
4762 // obj_type, we've discovered this wasn't so, so report the field didn't exist.
Andreas Gampe66596242016-04-14 10:55:04 -07004763 VerifyError type;
4764 bool is_aot = Runtime::Current()->IsAotCompiler();
4765 if (is_aot && (field_klass.IsUnresolvedTypes() || obj_type.IsUnresolvedTypes())) {
4766 // Compiler & unresolved types involved, retry at runtime.
4767 type = VerifyError::VERIFY_ERROR_NO_CLASS;
4768 } else {
Andreas Gampe8f4ade02016-04-15 10:09:16 -07004769 // Classes known (resolved; and thus assignability check is precise), or we are at runtime
4770 // and still missing classes. This is a hard failure.
Andreas Gampe66596242016-04-14 10:55:04 -07004771 type = VerifyError::VERIFY_ERROR_BAD_CLASS_HARD;
4772 }
David Sehr709b0702016-10-13 09:12:37 -07004773 Fail(type) << "cannot access instance field " << field->PrettyField()
Andreas Gampe66596242016-04-14 10:55:04 -07004774 << " from object of type " << obj_type;
Ian Rogers7b078e82014-09-10 14:44:24 -07004775 return nullptr;
Ian Rogersad0b3a32012-04-16 14:50:24 -07004776 }
Ian Rogersd81871c2011-10-03 13:57:23 -07004777 }
Aart Bik31883642016-06-06 15:02:44 -07004778
4779 // Few last soft failure checks.
4780 if (!GetDeclaringClass().CanAccessMember(field->GetDeclaringClass(),
4781 field->GetAccessFlags())) {
David Sehr709b0702016-10-13 09:12:37 -07004782 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot access instance field " << field->PrettyField()
Aart Bik31883642016-06-06 15:02:44 -07004783 << " from " << GetDeclaringClass();
4784 return nullptr;
4785 } else if (field->IsStatic()) {
David Sehr709b0702016-10-13 09:12:37 -07004786 Fail(VERIFY_ERROR_CLASS_CHANGE) << "expected field " << field->PrettyField()
Aart Bik31883642016-06-06 15:02:44 -07004787 << " to not be static";
4788 return nullptr;
4789 }
4790
4791 return field;
Ian Rogersd81871c2011-10-03 13:57:23 -07004792}
4793
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004794template <bool kVerifierDebug>
4795template <FieldAccessType kAccType>
4796void MethodVerifier<kVerifierDebug>::VerifyISFieldAccess(const Instruction* inst,
4797 const RegType& insn_type,
4798 bool is_primitive,
4799 bool is_static) {
Nicolas Geoffray69b1cf12018-03-21 10:44:58 +00004800 uint32_t field_idx = GetFieldIdxOfFieldAccess(inst, is_static);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004801 ArtField* field;
Ian Rogersb94a27b2011-10-26 00:33:41 -07004802 if (is_static) {
Ian Rogersf4028cc2011-11-02 14:56:39 -07004803 field = GetStaticField(field_idx);
Ian Rogersb94a27b2011-10-26 00:33:41 -07004804 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -07004805 const RegType& object_type = work_line_->GetRegisterType(this, inst->VRegB_22c());
David Brazdil68b5c0b2016-01-19 14:25:29 +00004806
4807 // One is not allowed to access fields on uninitialized references, except to write to
4808 // fields in the constructor (before calling another constructor).
4809 // GetInstanceField does an assignability check which will fail for uninitialized types.
4810 // We thus modify the type if the uninitialized reference is a "this" reference (this also
4811 // checks at the same time that we're verifying a constructor).
4812 bool should_adjust = (kAccType == FieldAccessType::kAccPut) &&
4813 object_type.IsUninitializedThisReference();
4814 const RegType& adjusted_type = should_adjust
4815 ? GetRegTypeCache()->FromUninitialized(object_type)
4816 : object_type;
4817 field = GetInstanceField(adjusted_type, field_idx);
Andreas Gampe896df402014-10-20 22:25:29 -07004818 if (UNLIKELY(have_pending_hard_failure_)) {
4819 return;
4820 }
Alex Light4a2c8fc2016-02-12 11:01:54 -08004821 if (should_adjust) {
4822 if (field == nullptr) {
4823 Fail(VERIFY_ERROR_BAD_CLASS_SOFT) << "Might be accessing a superclass instance field prior "
4824 << "to the superclass being initialized in "
David Sehr709b0702016-10-13 09:12:37 -07004825 << dex_file_->PrettyMethod(dex_method_idx_);
Alex Light4a2c8fc2016-02-12 11:01:54 -08004826 } else if (field->GetDeclaringClass() != GetDeclaringClass().GetClass()) {
4827 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "cannot access superclass instance field "
David Sehr709b0702016-10-13 09:12:37 -07004828 << field->PrettyField() << " of a not fully initialized "
Alex Light4a2c8fc2016-02-12 11:01:54 -08004829 << "object within the context of "
David Sehr709b0702016-10-13 09:12:37 -07004830 << dex_file_->PrettyMethod(dex_method_idx_);
Alex Light4a2c8fc2016-02-12 11:01:54 -08004831 return;
4832 }
4833 }
Ian Rogersb94a27b2011-10-26 00:33:41 -07004834 }
Ian Rogersd8f69b02014-09-10 21:43:52 +00004835 const RegType* field_type = nullptr;
Ian Rogers7b078e82014-09-10 14:44:24 -07004836 if (field != nullptr) {
Andreas Gampe896df402014-10-20 22:25:29 -07004837 if (kAccType == FieldAccessType::kAccPut) {
4838 if (field->IsFinal() && field->GetDeclaringClass() != GetDeclaringClass().GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -07004839 Fail(VERIFY_ERROR_ACCESS_FIELD) << "cannot modify final field " << field->PrettyField()
Andreas Gampe896df402014-10-20 22:25:29 -07004840 << " from other class " << GetDeclaringClass();
Aart Bikc2bc2652016-05-23 14:58:49 -07004841 // Keep hunting for possible hard fails.
Andreas Gampe896df402014-10-20 22:25:29 -07004842 }
4843 }
4844
Mathieu Chartier3398c782016-09-30 10:27:43 -07004845 ObjPtr<mirror::Class> field_type_class =
Vladimir Marko208f6702017-12-08 12:00:50 +00004846 can_load_classes_ ? field->ResolveType() : field->LookupResolvedType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004847 if (field_type_class != nullptr) {
Mathieu Chartier3398c782016-09-30 10:27:43 -07004848 field_type = &FromClass(field->GetTypeDescriptor(),
Vladimir Markobcf17522018-06-01 13:14:32 +01004849 field_type_class,
Andreas Gampef23f33d2015-06-23 14:18:17 -07004850 field_type_class->CannotBeAssignedFromOtherTypes());
Mathieu Chartiereae2fb22014-01-14 14:31:25 -08004851 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -07004852 DCHECK(!can_load_classes_ || self_->IsExceptionPending());
4853 self_->ClearException();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004854 }
David Brazdil2bb2fbd2018-11-13 18:24:26 +00004855 } else if (IsSdkVersionSetAndAtLeast(api_level_, SdkVersion::kP)) {
Andreas Gampe7da4c402017-08-25 11:30:48 -07004856 // If we don't have the field (it seems we failed resolution) and this is a PUT, we need to
4857 // redo verification at runtime as the field may be final, unless the field id shows it's in
4858 // the same class.
4859 //
4860 // For simplicity, it is OK to not distinguish compile-time vs runtime, and post this an
4861 // ACCESS_FIELD failure at runtime. This has the same effect as NO_FIELD - punting the class
4862 // to the access-checks interpreter.
4863 //
4864 // Note: see b/34966607. This and above may be changed in the future.
4865 if (kAccType == FieldAccessType::kAccPut) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004866 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
Andreas Gampe7da4c402017-08-25 11:30:48 -07004867 const char* field_class_descriptor = dex_file_->GetFieldDeclaringClassDescriptor(field_id);
Andreas Gampe51de69e2019-04-19 15:14:14 -07004868 const RegType* field_class_type = &reg_types_.FromDescriptor(class_loader_.Get(),
Andreas Gampe7da4c402017-08-25 11:30:48 -07004869 field_class_descriptor,
4870 false);
4871 if (!field_class_type->Equals(GetDeclaringClass())) {
4872 Fail(VERIFY_ERROR_ACCESS_FIELD) << "could not check field put for final field modify of "
4873 << field_class_descriptor
4874 << "."
4875 << dex_file_->GetFieldName(field_id)
4876 << " from other class "
4877 << GetDeclaringClass();
4878 }
4879 }
Ian Rogers0d604842012-04-16 14:50:24 -07004880 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004881 if (field_type == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004882 const dex::FieldId& field_id = dex_file_->GetFieldId(field_idx);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004883 const char* descriptor = dex_file_->GetFieldTypeDescriptor(field_id);
Andreas Gampe51de69e2019-04-19 15:14:14 -07004884 field_type = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004885 }
Sebastien Hertz757b3042014-03-28 14:34:28 +01004886 DCHECK(field_type != nullptr);
Sebastien Hertz5243e912013-05-21 10:55:07 +02004887 const uint32_t vregA = (is_static) ? inst->VRegA_21c() : inst->VRegA_22c();
Andreas Gampe896df402014-10-20 22:25:29 -07004888 static_assert(kAccType == FieldAccessType::kAccPut || kAccType == FieldAccessType::kAccGet,
4889 "Unexpected third access type");
4890 if (kAccType == FieldAccessType::kAccPut) {
4891 // sput or iput.
4892 if (is_primitive) {
4893 VerifyPrimitivePut(*field_type, insn_type, vregA);
Ian Rogersad0b3a32012-04-16 14:50:24 -07004894 } else {
David Brazdilca3c8c32016-09-06 14:04:48 +01004895 if (!insn_type.IsAssignableFrom(*field_type, this)) {
Vladimir Marko414000e2015-06-23 17:45:21 +01004896 // If the field type is not a reference, this is a global failure rather than
4897 // a class change failure as the instructions and the descriptors for the type
4898 // should have been consistent within the same file at compile time.
4899 VerifyError error = field_type->IsReferenceTypes() ? VERIFY_ERROR_BAD_CLASS_SOFT
4900 : VERIFY_ERROR_BAD_CLASS_HARD;
David Sehr709b0702016-10-13 09:12:37 -07004901 Fail(error) << "expected field " << ArtField::PrettyField(field)
Vladimir Marko414000e2015-06-23 17:45:21 +01004902 << " to be compatible with type '" << insn_type
4903 << "' but found type '" << *field_type
4904 << "' in put-object";
Andreas Gampe896df402014-10-20 22:25:29 -07004905 return;
4906 }
4907 work_line_->VerifyRegisterType(this, vregA, *field_type);
Ian Rogersad0b3a32012-04-16 14:50:24 -07004908 }
Andreas Gampe896df402014-10-20 22:25:29 -07004909 } else if (kAccType == FieldAccessType::kAccGet) {
4910 // sget or iget.
4911 if (is_primitive) {
4912 if (field_type->Equals(insn_type) ||
4913 (field_type->IsFloat() && insn_type.IsInteger()) ||
4914 (field_type->IsDouble() && insn_type.IsLong())) {
4915 // expected that read is of the correct primitive type or that int reads are reading
4916 // floats or long reads are reading doubles
4917 } else {
4918 // This is a global failure rather than a class change failure as the instructions and
4919 // the descriptors for the type should have been consistent within the same file at
4920 // compile time
David Sehr709b0702016-10-13 09:12:37 -07004921 Fail(VERIFY_ERROR_BAD_CLASS_HARD) << "expected field " << ArtField::PrettyField(field)
Andreas Gampe896df402014-10-20 22:25:29 -07004922 << " to be of type '" << insn_type
4923 << "' but found type '" << *field_type << "' in get";
4924 return;
4925 }
Mathieu Chartiereae2fb22014-01-14 14:31:25 -08004926 } else {
David Brazdilca3c8c32016-09-06 14:04:48 +01004927 if (!insn_type.IsAssignableFrom(*field_type, this)) {
Vladimir Marko414000e2015-06-23 17:45:21 +01004928 // If the field type is not a reference, this is a global failure rather than
4929 // a class change failure as the instructions and the descriptors for the type
4930 // should have been consistent within the same file at compile time.
4931 VerifyError error = field_type->IsReferenceTypes() ? VERIFY_ERROR_BAD_CLASS_SOFT
4932 : VERIFY_ERROR_BAD_CLASS_HARD;
David Sehr709b0702016-10-13 09:12:37 -07004933 Fail(error) << "expected field " << ArtField::PrettyField(field)
Vladimir Marko414000e2015-06-23 17:45:21 +01004934 << " to be compatible with type '" << insn_type
4935 << "' but found type '" << *field_type
4936 << "' in get-object";
Andreas Gampe890da292015-07-06 17:20:18 -07004937 if (error != VERIFY_ERROR_BAD_CLASS_HARD) {
Andreas Gampead238ce2015-08-24 21:13:08 -07004938 work_line_->SetRegisterType<LockOp::kClear>(this, vregA, reg_types_.Conflict());
Andreas Gampe890da292015-07-06 17:20:18 -07004939 }
Andreas Gampe896df402014-10-20 22:25:29 -07004940 return;
4941 }
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004942 }
Andreas Gampe896df402014-10-20 22:25:29 -07004943 if (!field_type->IsLowHalf()) {
Andreas Gampead238ce2015-08-24 21:13:08 -07004944 work_line_->SetRegisterType<LockOp::kClear>(this, vregA, *field_type);
Andreas Gampe896df402014-10-20 22:25:29 -07004945 } else {
4946 work_line_->SetRegisterTypeWide(this, vregA, *field_type, field_type->HighHalf(&reg_types_));
4947 }
Ian Rogersad0b3a32012-04-16 14:50:24 -07004948 } else {
Andreas Gampe896df402014-10-20 22:25:29 -07004949 LOG(FATAL) << "Unexpected case.";
Ian Rogersd81871c2011-10-03 13:57:23 -07004950 }
4951}
4952
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004953template <bool kVerifierDebug>
4954bool MethodVerifier<kVerifierDebug>::UpdateRegisters(uint32_t next_insn,
4955 RegisterLine* merge_line,
4956 bool update_merge_line) {
Ian Rogersd81871c2011-10-03 13:57:23 -07004957 bool changed = true;
4958 RegisterLine* target_line = reg_table_.GetLine(next_insn);
Mathieu Chartierde40d472015-10-15 17:47:48 -07004959 if (!GetInstructionFlags(next_insn).IsVisitedOrChanged()) {
jeffhaobdb76512011-09-07 11:43:16 -07004960 /*
Ian Rogersd81871c2011-10-03 13:57:23 -07004961 * We haven't processed this instruction before, and we haven't touched the registers here, so
4962 * there's nothing to "merge". Copy the registers over and mark it as changed. (This is the
4963 * only way a register can transition out of "unknown", so this is not just an optimization.)
jeffhaobdb76512011-09-07 11:43:16 -07004964 */
Andreas Gampea727e372015-08-25 09:22:37 -07004965 target_line->CopyFromLine(merge_line);
Mathieu Chartierde40d472015-10-15 17:47:48 -07004966 if (GetInstructionFlags(next_insn).IsReturn()) {
Jeff Haob24b4a72013-07-31 13:47:31 -07004967 // Verify that the monitor stack is empty on return.
Andreas Gampea727e372015-08-25 09:22:37 -07004968 merge_line->VerifyMonitorStackEmpty(this);
4969
Ian Rogersb8c78592013-07-25 23:52:52 +00004970 // For returns we only care about the operand to the return, all other registers are dead.
4971 // Initialize them as conflicts so they don't add to GC and deoptimization information.
Mathieu Chartier3da1d0f2017-11-06 20:02:24 -08004972 const Instruction* ret_inst = &code_item_accessor_.InstructionAt(next_insn);
Andreas Gampea727e372015-08-25 09:22:37 -07004973 AdjustReturnLine(this, ret_inst, target_line);
Aart Bik31883642016-06-06 15:02:44 -07004974 // Directly bail if a hard failure was found.
Aart Bikb0526322016-06-01 14:06:00 -07004975 if (have_pending_hard_failure_) {
4976 return false;
4977 }
Ian Rogersb8c78592013-07-25 23:52:52 +00004978 }
jeffhaobdb76512011-09-07 11:43:16 -07004979 } else {
Mathieu Chartier361e04a2016-02-16 14:06:35 -08004980 RegisterLineArenaUniquePtr copy;
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004981 if (kVerifierDebug) {
Andreas Gamped09c0592019-04-19 15:44:05 -07004982 copy.reset(RegisterLine::Create(target_line->NumRegs(), allocator_, GetRegTypeCache()));
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004983 copy->CopyFromLine(target_line);
4984 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004985 changed = target_line->MergeRegisters(this, merge_line);
Ian Rogersad0b3a32012-04-16 14:50:24 -07004986 if (have_pending_hard_failure_) {
Ian Rogersd81871c2011-10-03 13:57:23 -07004987 return false;
jeffhaobdb76512011-09-07 11:43:16 -07004988 }
Andreas Gampe99db7bb2019-04-19 23:05:47 -07004989 if (kVerifierDebug && changed) {
Elliott Hughes398f64b2012-03-26 18:05:48 -07004990 LogVerifyInfo() << "Merging at [" << reinterpret_cast<void*>(work_insn_idx_) << "]"
Elliott Hughesc073b072012-05-24 19:29:17 -07004991 << " to [" << reinterpret_cast<void*>(next_insn) << "]: " << "\n"
Ian Rogers7b078e82014-09-10 14:44:24 -07004992 << copy->Dump(this) << " MERGE\n"
4993 << merge_line->Dump(this) << " ==\n"
Andreas Gampe2ad6cce2019-04-11 16:17:39 -07004994 << target_line->Dump(this);
jeffhaobdb76512011-09-07 11:43:16 -07004995 }
Ian Rogersebbdd872014-07-07 23:53:08 -07004996 if (update_merge_line && changed) {
4997 merge_line->CopyFromLine(target_line);
4998 }
jeffhaobdb76512011-09-07 11:43:16 -07004999 }
Ian Rogersd81871c2011-10-03 13:57:23 -07005000 if (changed) {
Andreas Gampe51de69e2019-04-19 15:14:14 -07005001 GetModifiableInstructionFlags(next_insn).SetChanged();
jeffhaobdb76512011-09-07 11:43:16 -07005002 }
5003 return true;
5004}
5005
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005006template <bool kVerifierDebug>
5007const RegType& MethodVerifier<kVerifierDebug>::GetMethodReturnType() {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005008 if (return_type_ == nullptr) {
Nicolas Geoffrayb041a402017-11-13 15:16:22 +00005009 if (method_being_verified_ != nullptr) {
Vladimir Markob45528c2017-07-27 14:14:28 +01005010 ObjPtr<mirror::Class> return_type_class = can_load_classes_
Nicolas Geoffrayb041a402017-11-13 15:16:22 +00005011 ? method_being_verified_->ResolveReturnType()
5012 : method_being_verified_->LookupResolvedReturnType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005013 if (return_type_class != nullptr) {
Nicolas Geoffrayb041a402017-11-13 15:16:22 +00005014 return_type_ = &FromClass(method_being_verified_->GetReturnTypeDescriptor(),
Vladimir Markobcf17522018-06-01 13:14:32 +01005015 return_type_class,
Andreas Gampef23f33d2015-06-23 14:18:17 -07005016 return_type_class->CannotBeAssignedFromOtherTypes());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005017 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -07005018 DCHECK(!can_load_classes_ || self_->IsExceptionPending());
5019 self_->ClearException();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005020 }
5021 }
5022 if (return_type_ == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005023 const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
5024 const dex::ProtoId& proto_id = dex_file_->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005025 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005026 const char* descriptor = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(return_type_idx));
Andreas Gampe51de69e2019-04-19 15:14:14 -07005027 return_type_ = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005028 }
5029 }
5030 return *return_type_;
Ian Rogersad0b3a32012-04-16 14:50:24 -07005031}
5032
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005033template <bool kVerifierDebug>
5034const RegType& MethodVerifier<kVerifierDebug>::GetDeclaringClass() {
Ian Rogers7b078e82014-09-10 14:44:24 -07005035 if (declaring_class_ == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005036 const dex::MethodId& method_id = dex_file_->GetMethodId(dex_method_idx_);
Brian Carlstrom93c33962013-07-26 10:37:43 -07005037 const char* descriptor
5038 = dex_file_->GetTypeDescriptor(dex_file_->GetTypeId(method_id.class_idx_));
Nicolas Geoffrayb041a402017-11-13 15:16:22 +00005039 if (method_being_verified_ != nullptr) {
Vladimir Marko2cffc5d2018-05-29 15:40:56 +01005040 ObjPtr<mirror::Class> klass = method_being_verified_->GetDeclaringClass();
Mathieu Chartierde40d472015-10-15 17:47:48 -07005041 declaring_class_ = &FromClass(descriptor, klass, klass->CannotBeAssignedFromOtherTypes());
Ian Rogers637c65b2013-05-31 11:46:00 -07005042 } else {
Andreas Gampe51de69e2019-04-19 15:14:14 -07005043 declaring_class_ = &reg_types_.FromDescriptor(class_loader_.Get(), descriptor, false);
Ian Rogers637c65b2013-05-31 11:46:00 -07005044 }
Ian Rogersad0b3a32012-04-16 14:50:24 -07005045 }
Ian Rogers637c65b2013-05-31 11:46:00 -07005046 return *declaring_class_;
Ian Rogersad0b3a32012-04-16 14:50:24 -07005047}
5048
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005049template <bool kVerifierDebug>
5050const RegType& MethodVerifier<kVerifierDebug>::DetermineCat1Constant(int32_t value, bool precise) {
Sebastien Hertz849600b2013-12-20 10:28:08 +01005051 if (precise) {
5052 // Precise constant type.
5053 return reg_types_.FromCat1Const(value, true);
5054 } else {
5055 // Imprecise constant type.
5056 if (value < -32768) {
5057 return reg_types_.IntConstant();
5058 } else if (value < -128) {
5059 return reg_types_.ShortConstant();
5060 } else if (value < 0) {
5061 return reg_types_.ByteConstant();
5062 } else if (value == 0) {
5063 return reg_types_.Zero();
5064 } else if (value == 1) {
5065 return reg_types_.One();
5066 } else if (value < 128) {
5067 return reg_types_.PosByteConstant();
5068 } else if (value < 32768) {
5069 return reg_types_.PosShortConstant();
5070 } else if (value < 65536) {
5071 return reg_types_.CharConstant();
5072 } else {
5073 return reg_types_.IntConstant();
5074 }
5075 }
5076}
5077
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005078template <bool kVerifierDebug>
5079const RegType& MethodVerifier<kVerifierDebug>::FromClass(const char* descriptor,
5080 ObjPtr<mirror::Class> klass,
5081 bool precise) {
Andreas Gampefc25ae92019-04-19 22:22:57 -07005082 DCHECK(klass != nullptr);
5083 if (precise && !klass->IsInstantiable() && !klass->IsPrimitive()) {
5084 Fail(VerifyError::VERIFY_ERROR_NO_CLASS) << "Could not create precise reference for "
5085 << "non-instantiable klass " << descriptor;
5086 precise = false;
5087 }
5088 return reg_types_.FromClass(descriptor, klass, precise);
5089}
5090
Andreas Gampefc25ae92019-04-19 22:22:57 -07005091} // namespace
5092} // namespace impl
5093
5094MethodVerifier::MethodVerifier(Thread* self,
5095 const DexFile* dex_file,
5096 const dex::CodeItem* code_item,
5097 uint32_t dex_method_idx,
5098 bool can_load_classes,
5099 bool allow_thread_suspension,
5100 bool allow_soft_failures)
5101 : self_(self),
5102 arena_stack_(Runtime::Current()->GetArenaPool()),
5103 allocator_(&arena_stack_),
5104 reg_types_(can_load_classes, allocator_, allow_thread_suspension),
5105 reg_table_(allocator_),
5106 work_insn_idx_(dex::kDexNoIndex),
5107 dex_method_idx_(dex_method_idx),
5108 dex_file_(dex_file),
5109 code_item_accessor_(*dex_file, code_item),
5110 have_pending_hard_failure_(false),
5111 have_pending_runtime_throw_failure_(false),
5112 have_pending_experimental_failure_(false),
5113 have_any_pending_runtime_throw_failure_(false),
5114 encountered_failure_types_(0),
5115 can_load_classes_(can_load_classes),
5116 allow_soft_failures_(allow_soft_failures),
5117 has_check_casts_(false),
5118 link_(nullptr) {
5119 self->PushVerifier(this);
5120}
5121
5122MethodVerifier::~MethodVerifier() {
5123 Thread::Current()->PopVerifier(this);
5124 STLDeleteElements(&failure_messages_);
5125}
5126
5127MethodVerifier::FailureData MethodVerifier::VerifyMethod(Thread* self,
5128 uint32_t method_idx,
5129 const DexFile* dex_file,
5130 Handle<mirror::DexCache> dex_cache,
5131 Handle<mirror::ClassLoader> class_loader,
5132 const dex::ClassDef& class_def,
5133 const dex::CodeItem* code_item,
5134 ArtMethod* method,
5135 uint32_t method_access_flags,
5136 CompilerCallbacks* callbacks,
5137 bool allow_soft_failures,
5138 HardFailLogMode log_level,
5139 bool need_precise_constants,
5140 uint32_t api_level,
5141 std::string* hard_failure_msg) {
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005142 if (VLOG_IS_ON(verifier_debug)) {
5143 return VerifyMethod<true>(self,
5144 method_idx,
5145 dex_file,
5146 dex_cache,
5147 class_loader,
5148 class_def,
5149 code_item,
5150 method,
5151 method_access_flags,
5152 callbacks,
5153 allow_soft_failures,
5154 log_level,
5155 need_precise_constants,
5156 api_level,
5157 hard_failure_msg);
5158 } else {
5159 return VerifyMethod<false>(self,
5160 method_idx,
5161 dex_file,
5162 dex_cache,
5163 class_loader,
5164 class_def,
5165 code_item,
5166 method,
5167 method_access_flags,
5168 callbacks,
5169 allow_soft_failures,
5170 log_level,
5171 need_precise_constants,
5172 api_level,
5173 hard_failure_msg);
5174 }
5175}
5176
5177template <bool kVerifierDebug>
5178MethodVerifier::FailureData MethodVerifier::VerifyMethod(Thread* self,
5179 uint32_t method_idx,
5180 const DexFile* dex_file,
5181 Handle<mirror::DexCache> dex_cache,
5182 Handle<mirror::ClassLoader> class_loader,
5183 const dex::ClassDef& class_def,
5184 const dex::CodeItem* code_item,
5185 ArtMethod* method,
5186 uint32_t method_access_flags,
5187 CompilerCallbacks* callbacks,
5188 bool allow_soft_failures,
5189 HardFailLogMode log_level,
5190 bool need_precise_constants,
5191 uint32_t api_level,
5192 std::string* hard_failure_msg) {
Andreas Gampefc25ae92019-04-19 22:22:57 -07005193 MethodVerifier::FailureData result;
5194 uint64_t start_ns = kTimeVerifyMethod ? NanoTime() : 0;
5195
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005196 impl::MethodVerifier<kVerifierDebug> verifier(self,
5197 dex_file,
5198 dex_cache,
5199 class_loader,
5200 class_def,
5201 code_item,
5202 method_idx,
5203 method,
5204 method_access_flags,
5205 /* can_load_classes= */ true,
5206 allow_soft_failures,
5207 need_precise_constants,
5208 /* verify to dump */ false,
5209 /* allow_thread_suspension= */ true,
Alex Lighte48fd0b2019-05-20 10:04:44 -07005210 /* fill_register_lines= */ false,
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005211 api_level);
Andreas Gampefc25ae92019-04-19 22:22:57 -07005212 if (verifier.Verify()) {
5213 // Verification completed, however failures may be pending that didn't cause the verification
5214 // to hard fail.
5215 CHECK(!verifier.have_pending_hard_failure_);
5216
5217 if (code_item != nullptr && callbacks != nullptr) {
5218 // Let the interested party know that the method was verified.
5219 callbacks->MethodVerified(&verifier);
5220 }
5221
5222 if (verifier.failures_.size() != 0) {
5223 if (VLOG_IS_ON(verifier)) {
5224 verifier.DumpFailures(VLOG_STREAM(verifier) << "Soft verification failures in "
5225 << dex_file->PrettyMethod(method_idx) << "\n");
5226 }
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005227 if (kVerifierDebug) {
Andreas Gampefc25ae92019-04-19 22:22:57 -07005228 LOG(INFO) << verifier.info_messages_.str();
5229 verifier.Dump(LOG_STREAM(INFO));
5230 }
5231 result.kind = FailureKind::kSoftFailure;
5232 if (method != nullptr &&
5233 !CanCompilerHandleVerificationFailure(verifier.encountered_failure_types_)) {
5234 method->SetDontCompile();
5235 }
5236 }
5237 if (method != nullptr) {
5238 if (verifier.HasInstructionThatWillThrow()) {
5239 method->SetDontCompile();
5240 if (Runtime::Current()->IsAotCompiler() &&
5241 (callbacks != nullptr) && !callbacks->IsBootImage()) {
5242 // When compiling apps, make HasInstructionThatWillThrow a soft error to trigger
5243 // re-verification at runtime.
5244 // The dead code after the throw is not verified and might be invalid. This may cause
5245 // the JIT compiler to crash since it assumes that all the code is valid.
5246 //
5247 // There's a strong assumption that the entire boot image is verified and all its dex
5248 // code is valid (even the dead and unverified one). As such this is done only for apps.
5249 // (CompilerDriver DCHECKs in VerifyClassVisitor that methods from boot image are
5250 // fully verified).
5251 result.kind = FailureKind::kSoftFailure;
5252 }
5253 }
5254 if ((verifier.encountered_failure_types_ & VerifyError::VERIFY_ERROR_LOCKING) != 0) {
5255 method->SetMustCountLocks();
5256 }
5257 }
5258 } else {
5259 // Bad method data.
5260 CHECK_NE(verifier.failures_.size(), 0U);
5261
5262 if (UNLIKELY(verifier.have_pending_experimental_failure_)) {
5263 // Failed due to being forced into interpreter. This is ok because
5264 // we just want to skip verification.
5265 result.kind = FailureKind::kSoftFailure;
5266 } else {
5267 CHECK(verifier.have_pending_hard_failure_);
5268 if (VLOG_IS_ON(verifier)) {
5269 log_level = std::max(HardFailLogMode::kLogVerbose, log_level);
5270 }
5271 if (log_level >= HardFailLogMode::kLogVerbose) {
5272 LogSeverity severity;
5273 switch (log_level) {
5274 case HardFailLogMode::kLogVerbose:
5275 severity = LogSeverity::VERBOSE;
5276 break;
5277 case HardFailLogMode::kLogWarning:
5278 severity = LogSeverity::WARNING;
5279 break;
5280 case HardFailLogMode::kLogInternalFatal:
5281 severity = LogSeverity::FATAL_WITHOUT_ABORT;
5282 break;
5283 default:
5284 LOG(FATAL) << "Unsupported log-level " << static_cast<uint32_t>(log_level);
5285 UNREACHABLE();
5286 }
5287 verifier.DumpFailures(LOG_STREAM(severity) << "Verification error in "
5288 << dex_file->PrettyMethod(method_idx)
5289 << "\n");
5290 }
5291 if (hard_failure_msg != nullptr) {
5292 CHECK(!verifier.failure_messages_.empty());
5293 *hard_failure_msg =
5294 verifier.failure_messages_[verifier.failure_messages_.size() - 1]->str();
5295 }
5296 result.kind = FailureKind::kHardFailure;
5297
5298 if (callbacks != nullptr) {
5299 // Let the interested party know that we failed the class.
5300 ClassReference ref(dex_file, dex_file->GetIndexForClassDef(class_def));
5301 callbacks->ClassRejected(ref);
5302 }
5303 }
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005304 if (kVerifierDebug || VLOG_IS_ON(verifier)) {
Andreas Gampefc25ae92019-04-19 22:22:57 -07005305 LOG(ERROR) << verifier.info_messages_.str();
5306 verifier.Dump(LOG_STREAM(ERROR));
5307 }
5308 // Under verifier-debug, dump the complete log into the error message.
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005309 if (kVerifierDebug && hard_failure_msg != nullptr) {
Andreas Gampefc25ae92019-04-19 22:22:57 -07005310 hard_failure_msg->append("\n");
5311 hard_failure_msg->append(verifier.info_messages_.str());
5312 hard_failure_msg->append("\n");
5313 std::ostringstream oss;
5314 verifier.Dump(oss);
5315 hard_failure_msg->append(oss.str());
5316 }
5317 }
5318 if (kTimeVerifyMethod) {
5319 uint64_t duration_ns = NanoTime() - start_ns;
5320 if (duration_ns > MsToNs(Runtime::Current()->GetVerifierLoggingThresholdMs())) {
Andreas Gampeefdd1b02019-05-07 12:30:10 -07005321 double bytecodes_per_second =
5322 verifier.code_item_accessor_.InsnsSizeInCodeUnits() / (duration_ns * 1e-9);
Andreas Gampefc25ae92019-04-19 22:22:57 -07005323 LOG(WARNING) << "Verification of " << dex_file->PrettyMethod(method_idx)
5324 << " took " << PrettyDuration(duration_ns)
Andreas Gampeefdd1b02019-05-07 12:30:10 -07005325 << (impl::IsLargeMethod(verifier.CodeItem()) ? " (large method)" : "")
5326 << " (" << StringPrintf("%.2f", bytecodes_per_second) << " bytecodes/s)";
Andreas Gampefc25ae92019-04-19 22:22:57 -07005327 }
5328 }
5329 result.types = verifier.encountered_failure_types_;
5330 return result;
5331}
5332
Alex Lighte48fd0b2019-05-20 10:04:44 -07005333MethodVerifier* MethodVerifier::CalculateVerificationInfo(
5334 Thread* self,
5335 ArtMethod* method,
5336 Handle<mirror::DexCache> dex_cache,
5337 Handle<mirror::ClassLoader> class_loader) {
5338 std::unique_ptr<impl::MethodVerifier<false>> verifier(
5339 new impl::MethodVerifier<false>(self,
5340 method->GetDexFile(),
5341 dex_cache,
5342 class_loader,
5343 *method->GetDeclaringClass()->GetClassDef(),
5344 method->GetCodeItem(),
5345 method->GetDexMethodIndex(),
5346 method,
5347 method->GetAccessFlags(),
5348 /* can_load_classes= */ false,
5349 /* allow_soft_failures= */ true,
5350 /* need_precise_constants= */ true,
5351 /* verify_to_dump= */ false,
5352 /* allow_thread_suspension= */ false,
5353 /* fill_register_lines= */ true,
5354 /* api_level = */ 0));
5355 verifier->Verify();
5356 if (VLOG_IS_ON(verifier)) {
5357 verifier->DumpFailures(VLOG_STREAM(verifier));
5358 VLOG(verifier) << verifier->info_messages_.str();
5359 verifier->Dump(VLOG_STREAM(verifier));
5360 }
5361 if (verifier->have_pending_hard_failure_) {
5362 return nullptr;
5363 } else {
5364 return verifier.release();
5365 }
5366}
5367
Andreas Gampefc25ae92019-04-19 22:22:57 -07005368MethodVerifier* MethodVerifier::VerifyMethodAndDump(Thread* self,
5369 VariableIndentationOutputStream* vios,
5370 uint32_t dex_method_idx,
5371 const DexFile* dex_file,
5372 Handle<mirror::DexCache> dex_cache,
5373 Handle<mirror::ClassLoader> class_loader,
5374 const dex::ClassDef& class_def,
5375 const dex::CodeItem* code_item,
5376 ArtMethod* method,
5377 uint32_t method_access_flags,
5378 uint32_t api_level) {
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005379 impl::MethodVerifier<false>* verifier = new impl::MethodVerifier<false>(
5380 self,
5381 dex_file,
5382 dex_cache,
5383 class_loader,
5384 class_def,
5385 code_item,
5386 dex_method_idx,
5387 method,
5388 method_access_flags,
5389 /* can_load_classes= */ true,
5390 /* allow_soft_failures= */ true,
5391 /* need_precise_constants= */ true,
5392 /* verify_to_dump= */ true,
5393 /* allow_thread_suspension= */ true,
Alex Lighte48fd0b2019-05-20 10:04:44 -07005394 /* fill_register_lines= */ false,
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005395 api_level);
Andreas Gampefc25ae92019-04-19 22:22:57 -07005396 verifier->Verify();
5397 verifier->DumpFailures(vios->Stream());
5398 vios->Stream() << verifier->info_messages_.str();
5399 // Only dump and return if no hard failures. Otherwise the verifier may be not fully initialized
5400 // and querying any info is dangerous/can abort.
5401 if (verifier->have_pending_hard_failure_) {
5402 delete verifier;
5403 return nullptr;
5404 } else {
5405 verifier->Dump(vios);
5406 return verifier;
5407 }
5408}
5409
5410void MethodVerifier::FindLocksAtDexPc(
5411 ArtMethod* m,
5412 uint32_t dex_pc,
5413 std::vector<MethodVerifier::DexLockInfo>* monitor_enter_dex_pcs,
5414 uint32_t api_level) {
5415 StackHandleScope<2> hs(Thread::Current());
5416 Handle<mirror::DexCache> dex_cache(hs.NewHandle(m->GetDexCache()));
5417 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(m->GetClassLoader()));
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005418 impl::MethodVerifier<false> verifier(hs.Self(),
5419 m->GetDexFile(),
5420 dex_cache,
5421 class_loader,
5422 m->GetClassDef(),
5423 m->GetCodeItem(),
5424 m->GetDexMethodIndex(),
5425 m,
5426 m->GetAccessFlags(),
5427 /* can_load_classes= */ false,
5428 /* allow_soft_failures= */ true,
5429 /* need_precise_constants= */ false,
5430 /* verify_to_dump= */ false,
5431 /* allow_thread_suspension= */ false,
Alex Lighte48fd0b2019-05-20 10:04:44 -07005432 /* fill_register_lines= */ false,
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005433 api_level);
Andreas Gampefc25ae92019-04-19 22:22:57 -07005434 verifier.interesting_dex_pc_ = dex_pc;
5435 verifier.monitor_enter_dex_pcs_ = monitor_enter_dex_pcs;
5436 verifier.FindLocksAtDexPc();
5437}
5438
5439MethodVerifier* MethodVerifier::CreateVerifier(Thread* self,
5440 const DexFile* dex_file,
5441 Handle<mirror::DexCache> dex_cache,
5442 Handle<mirror::ClassLoader> class_loader,
5443 const dex::ClassDef& class_def,
5444 const dex::CodeItem* code_item,
5445 uint32_t method_idx,
5446 ArtMethod* method,
5447 uint32_t access_flags,
5448 bool can_load_classes,
5449 bool allow_soft_failures,
5450 bool need_precise_constants,
5451 bool verify_to_dump,
5452 bool allow_thread_suspension,
5453 uint32_t api_level) {
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005454 return new impl::MethodVerifier<false>(self,
5455 dex_file,
5456 dex_cache,
5457 class_loader,
5458 class_def,
5459 code_item,
5460 method_idx,
5461 method,
5462 access_flags,
5463 can_load_classes,
5464 allow_soft_failures,
5465 need_precise_constants,
5466 verify_to_dump,
5467 allow_thread_suspension,
Alex Lighte48fd0b2019-05-20 10:04:44 -07005468 /* fill_register_lines= */ false,
Andreas Gampe99db7bb2019-04-19 23:05:47 -07005469 api_level);
Andreas Gampefc25ae92019-04-19 22:22:57 -07005470}
5471
Elliott Hughes0a1038b2012-06-14 16:24:17 -07005472void MethodVerifier::Init() {
Sameer Abu Asal51a5fb72013-02-19 14:25:01 -08005473 art::verifier::RegTypeCache::Init();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08005474}
5475
Elliott Hughes0a1038b2012-06-14 16:24:17 -07005476void MethodVerifier::Shutdown() {
Sameer Abu Asal51a5fb72013-02-19 14:25:01 -08005477 verifier::RegTypeCache::ShutDown();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08005478}
jeffhaod1224c72012-02-29 13:43:08 -08005479
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07005480void MethodVerifier::VisitStaticRoots(RootVisitor* visitor) {
5481 RegTypeCache::VisitStaticRoots(visitor);
Mathieu Chartier7c438b12014-09-12 17:01:24 -07005482}
5483
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07005484void MethodVerifier::VisitRoots(RootVisitor* visitor, const RootInfo& root_info) {
5485 reg_types_.VisitRoots(visitor, root_info);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005486}
5487
Andreas Gampefc25ae92019-04-19 22:22:57 -07005488std::ostream& MethodVerifier::Fail(VerifyError error) {
5489 // Mark the error type as encountered.
5490 encountered_failure_types_ |= static_cast<uint32_t>(error);
5491
5492 switch (error) {
5493 case VERIFY_ERROR_NO_CLASS:
5494 case VERIFY_ERROR_NO_FIELD:
5495 case VERIFY_ERROR_NO_METHOD:
5496 case VERIFY_ERROR_ACCESS_CLASS:
5497 case VERIFY_ERROR_ACCESS_FIELD:
5498 case VERIFY_ERROR_ACCESS_METHOD:
5499 case VERIFY_ERROR_INSTANTIATION:
5500 case VERIFY_ERROR_CLASS_CHANGE:
5501 case VERIFY_ERROR_FORCE_INTERPRETER:
5502 case VERIFY_ERROR_LOCKING:
5503 if (Runtime::Current()->IsAotCompiler() || !can_load_classes_) {
5504 // If we're optimistically running verification at compile time, turn NO_xxx, ACCESS_xxx,
5505 // class change and instantiation errors into soft verification errors so that we re-verify
5506 // at runtime. We may fail to find or to agree on access because of not yet available class
5507 // loaders, or class loaders that will differ at runtime. In these cases, we don't want to
5508 // affect the soundness of the code being compiled. Instead, the generated code runs "slow
5509 // paths" that dynamically perform the verification and cause the behavior to be that akin
5510 // to an interpreter.
5511 error = VERIFY_ERROR_BAD_CLASS_SOFT;
5512 } else {
5513 // If we fail again at runtime, mark that this instruction would throw and force this
5514 // method to be executed using the interpreter with checks.
5515 have_pending_runtime_throw_failure_ = true;
5516
5517 // We need to save the work_line if the instruction wasn't throwing before. Otherwise we'll
5518 // try to merge garbage.
5519 // Note: this assumes that Fail is called before we do any work_line modifications.
5520 // Note: this can fail before we touch any instruction, for the signature of a method. So
5521 // add a check.
5522 if (work_insn_idx_ < dex::kDexNoIndex) {
5523 const Instruction& inst = code_item_accessor_.InstructionAt(work_insn_idx_);
5524 int opcode_flags = Instruction::FlagsOf(inst.Opcode());
5525
5526 if ((opcode_flags & Instruction::kThrow) == 0 &&
5527 GetInstructionFlags(work_insn_idx_).IsInTry()) {
5528 saved_line_->CopyFromLine(work_line_.get());
5529 }
5530 }
5531 }
5532 break;
5533
5534 // Indication that verification should be retried at runtime.
5535 case VERIFY_ERROR_BAD_CLASS_SOFT:
5536 if (!allow_soft_failures_) {
5537 have_pending_hard_failure_ = true;
5538 }
5539 break;
5540
5541 // Hard verification failures at compile time will still fail at runtime, so the class is
5542 // marked as rejected to prevent it from being compiled.
5543 case VERIFY_ERROR_BAD_CLASS_HARD: {
5544 have_pending_hard_failure_ = true;
5545 break;
5546 }
Andreas Gampef23f33d2015-06-23 14:18:17 -07005547 }
Andreas Gampefc25ae92019-04-19 22:22:57 -07005548 failures_.push_back(error);
5549 std::string location(StringPrintf("%s: [0x%X] ", dex_file_->PrettyMethod(dex_method_idx_).c_str(),
5550 work_insn_idx_));
5551 std::ostringstream* failure_message = new std::ostringstream(location, std::ostringstream::ate);
5552 failure_messages_.push_back(failure_message);
5553 return *failure_message;
Andreas Gampef23f33d2015-06-23 14:18:17 -07005554}
5555
Andreas Gampefc25ae92019-04-19 22:22:57 -07005556ScopedNewLine MethodVerifier::LogVerifyInfo() {
5557 ScopedNewLine ret{info_messages_};
5558 ret << "VFY: " << dex_file_->PrettyMethod(dex_method_idx_)
5559 << '[' << reinterpret_cast<void*>(work_insn_idx_) << "] : ";
5560 return ret;
5561}
5562
5563static FailureKind FailureKindMax(FailureKind fk1, FailureKind fk2) {
5564 static_assert(FailureKind::kNoFailure < FailureKind::kSoftFailure
5565 && FailureKind::kSoftFailure < FailureKind::kHardFailure,
5566 "Unexpected FailureKind order");
5567 return std::max(fk1, fk2);
5568}
5569
5570void MethodVerifier::FailureData::Merge(const MethodVerifier::FailureData& fd) {
5571 kind = FailureKindMax(kind, fd.kind);
5572 types |= fd.types;
Andreas Gampe51de69e2019-04-19 15:14:14 -07005573}
5574
Ian Rogersd81871c2011-10-03 13:57:23 -07005575} // namespace verifier
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005576} // namespace art