• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_RUNTIME_VERIFIER_REGISTER_LINE_H_
18 #define ART_RUNTIME_VERIFIER_REGISTER_LINE_H_
19 
20 #include <limits>
21 #include <memory>
22 #include <vector>
23 
24 #include <android-base/logging.h>
25 
26 #include "base/arena_containers.h"
27 #include "base/locks.h"
28 #include "base/macros.h"
29 #include "base/safe_map.h"
30 #include "reg_type.h"
31 
32 namespace art HIDDEN {
33 
34 class Instruction;
35 
36 namespace verifier {
37 
38 class MethodVerifier;
39 class RegType;
40 class RegTypeCache;
41 
42 /*
43  * Register type categories, for type checking.
44  *
45  * The spec says category 1 includes boolean, byte, char, short, int, float, reference, and
46  * returnAddress. Category 2 includes long and double.
47  *
48  * We treat object references separately, so we have "category1nr". We don't support jsr/ret, so
49  * there is no "returnAddress" type.
50  */
51 enum TypeCategory {
52   kTypeCategoryUnknown = 0,
53   kTypeCategory1nr = 1,         // boolean, byte, char, short, int, float
54   kTypeCategory2 = 2,           // long, double
55   kTypeCategoryRef = 3,         // object reference
56 };
57 
58 // What to do with the lock levels when setting the register type.
59 enum class LockOp {
60   kClear,                       // Clear the lock levels recorded.
61   kKeep                         // Leave the lock levels alone.
62 };
63 
64 // During verification, we associate one of these with every "interesting" instruction. We track
65 // the status of all registers, and (if the method has any monitor-enter instructions) maintain a
66 // stack of entered monitors (identified by code unit offset).
67 class RegisterLine {
68  public:
69   using RegisterStackMask = uint32_t;
70   // A map from register to a bit vector of indices into the monitors_ stack.
71   using RegToLockDepthsMap = ArenaSafeMap<uint32_t, RegisterStackMask>;
72 
73   // Maximum number of nested monitors to track before giving up and
74   // taking the slow path.
75   static constexpr size_t kMaxMonitorStackDepth =
76       std::numeric_limits<RegisterStackMask>::digits;
77 
78   // Create a register line of num_regs registers.
79   static RegisterLine* Create(size_t num_regs, ArenaAllocator& allocator);
80 
81   // Copy reference (or conflict) register.
82   void CopyReference(uint32_t vdst, uint32_t vsrc, const RegType& type)
83       REQUIRES_SHARED(Locks::mutator_lock_);
84 
85   // Implement "move-result". Copy the category-1 value from the result register to another
86   // register, and reset the result register.
87   void CopyResultRegister1(MethodVerifier* verifier, uint32_t vdst, bool is_reference)
88       REQUIRES_SHARED(Locks::mutator_lock_);
89 
90   // Implement "move-result-wide". Copy the category-2 value from the result register to another
91   // register, and reset the result register.
92   void CopyResultRegister2(MethodVerifier* verifier, uint32_t vdst)
93       REQUIRES_SHARED(Locks::mutator_lock_);
94 
95   // Set the invisible result register to unknown
96   void SetResultTypeToUnknown() REQUIRES_SHARED(Locks::mutator_lock_);
97 
98   // Set the type of register N, verifying that the register is valid.  If "newType" is the "Lo"
99   // part of a 64-bit value, register N+1 will be set to "newType+1".
100   // The register index was validated during the static pass, so we don't need to check it here.
101   //
102   // LockOp::kClear should be used by default; it will clear the lock levels associated with the
103   // register. An example is setting the register type because an instruction writes to the
104   // register.
105   // LockOp::kKeep keeps the lock levels of the register and only changes the register type. This
106   // is typical when the underlying value did not change, but we have "different" type information
107   // available now. An example is sharpening types after a check-cast. Note that when given kKeep,
108   // the new_type is dchecked to be a reference type.
109   ALWAYS_INLINE void SetRegisterType(uint32_t vdst, RegType::Kind new_kind)
110       REQUIRES_SHARED(Locks::mutator_lock_);
111   template <LockOp kLockOp>
112   ALWAYS_INLINE void SetRegisterType(uint32_t vdst, const RegType& new_type)
113       REQUIRES_SHARED(Locks::mutator_lock_);
114 
115   void SetRegisterTypeWide(uint32_t vdst, RegType::Kind new_kind1, RegType::Kind new_kind2)
116       REQUIRES_SHARED(Locks::mutator_lock_);
117   void SetRegisterTypeWide(uint32_t vdst, const RegType& new_type1, const RegType& new_type2)
118       REQUIRES_SHARED(Locks::mutator_lock_);
119 
120   /* Set the type of the "result" register. */
121   void SetResultRegisterType(const RegType& new_type)
122       REQUIRES_SHARED(Locks::mutator_lock_);
123 
124   void SetResultRegisterTypeWide(const RegType& new_type1, const RegType& new_type2)
125       REQUIRES_SHARED(Locks::mutator_lock_);
126 
127   /*
128    * Set register type for a `new-instance` instruction.
129    * For `new-instance`, we additionally record the allocation dex pc for vreg `vdst`.
130    * This is used to keep track of registers that hold the same uninitialized reference,
131    * so that we can update them all when a constructor is called on any of them.
132    */
133   void SetRegisterTypeForNewInstance(uint32_t vdst, const RegType& uninit_type, uint32_t dex_pc)
134       REQUIRES_SHARED(Locks::mutator_lock_);
135 
136   // Get the id of the register tyoe of register vsrc.
137   uint16_t GetRegisterTypeId(uint32_t vsrc) const;
138 
139   // Get the type of register vsrc.
140   const RegType& GetRegisterType(MethodVerifier* verifier, uint32_t vsrc) const;
141 
142   void CopyFromLine(const RegisterLine* src);
143 
144   std::string Dump(MethodVerifier* verifier) const REQUIRES_SHARED(Locks::mutator_lock_);
145 
FillWithGarbage()146   void FillWithGarbage() {
147     memset(&line_, 0xf1, num_regs_ * sizeof(uint16_t));
148     monitors_.clear();
149     reg_to_lock_depths_.clear();
150   }
151 
152   /*
153    * In debug mode, assert that the register line does not contain an uninitialized register
154    * type for a `new-instance` allocation at a specific dex pc. We do this check before recording
155    * the uninitialized register type and dex pc for a `new-instance` instruction.
156    */
157   void DCheckUniqueNewInstanceDexPc(MethodVerifier* verifier, uint32_t dex_pc)
158       REQUIRES_SHARED(Locks::mutator_lock_);
159 
160   /*
161    * Update all registers holding the uninitialized type currently recorded for vreg `vsrc` to
162    * instead hold the corresponding initialized reference type. This is called when an appropriate
163    * constructor is invoked -- all copies of the reference must be marked as initialized.
164    */
165   void MarkRefsAsInitialized(MethodVerifier* verifier, uint32_t vsrc)
166       REQUIRES_SHARED(Locks::mutator_lock_);
167 
SetThisInitialized()168   void SetThisInitialized() {
169     this_initialized_ = true;
170   }
171 
CopyThisInitialized(const RegisterLine & src)172   void CopyThisInitialized(const RegisterLine& src) {
173     this_initialized_ = src.this_initialized_;
174   }
175 
176   /*
177    * Check constraints on constructor return. Specifically, make sure that the "this" argument got
178    * initialized.
179    * The "this" argument to <init> uses code offset kUninitThisArgAddr, which puts it at the start
180    * of the list in slot 0. If we see a register with an uninitialized slot 0 reference, we know it
181    * somehow didn't get initialized.
182    */
183   bool CheckConstructorReturn(MethodVerifier* verifier) const;
184 
185   // Compare two register lines. Returns 0 if they match.
186   // Using this for a sort is unwise, since the value can change based on machine endianness.
CompareLine(const RegisterLine * line2)187   int CompareLine(const RegisterLine* line2) const {
188     if (monitors_ != line2->monitors_) {
189       return 1;
190     }
191     // TODO: DCHECK(reg_to_lock_depths_ == line2->reg_to_lock_depths_);
192     return memcmp(&line_, &line2->line_, num_regs_ * sizeof(uint16_t));
193   }
194 
NumRegs()195   size_t NumRegs() const {
196     return num_regs_;
197   }
198 
199   // Return how many bytes of memory a register line uses.
200   ALWAYS_INLINE static size_t ComputeSize(size_t num_regs);
201 
202   // Verify/push monitor onto the monitor stack, locking the value in reg_idx at location insn_idx.
203   void PushMonitor(
204       MethodVerifier* verifier, uint32_t vreg, const RegType& reg_type, int32_t insn_idx)
205       REQUIRES_SHARED(Locks::mutator_lock_);
206 
207   // Verify/pop monitor from monitor stack ensuring that we believe the monitor is locked
208   void PopMonitor(MethodVerifier* verifier, uint32_t vreg, const RegType& reg_type)
209       REQUIRES_SHARED(Locks::mutator_lock_);
210 
211   // Stack of currently held monitors and where they were locked
MonitorStackDepth()212   size_t MonitorStackDepth() const {
213     return monitors_.size();
214   }
215 
216   // We expect no monitors to be held at certain points, such a method returns. Verify the stack
217   // is empty, queueing a LOCKING error else.
218   void VerifyMonitorStackEmpty(MethodVerifier* verifier) const;
219 
220   bool MergeRegisters(MethodVerifier* verifier, const RegisterLine* incoming_line)
221       REQUIRES_SHARED(Locks::mutator_lock_);
222 
GetMonitorEnterCount()223   size_t GetMonitorEnterCount() const {
224     return monitors_.size();
225   }
226 
GetMonitorEnterDexPc(size_t i)227   uint32_t GetMonitorEnterDexPc(size_t i) const {
228     return monitors_[i];
229   }
230 
231   // We give access to the lock depth map to avoid an expensive poll loop for FindLocksAtDexPC.
232   template <typename T>
IterateRegToLockDepths(T fn)233   void IterateRegToLockDepths(T fn) const {
234     for (const auto& pair : reg_to_lock_depths_) {
235       const uint32_t reg = pair.first;
236       uint32_t depths = pair.second;
237       uint32_t depth = 0;
238       while (depths != 0) {
239         if ((depths & 1) != 0) {
240           fn(reg, depth);
241         }
242         depths >>= 1;
243         depth++;
244       }
245     }
246   }
247 
248  private:
249   // For uninitialized types we need to check for allocation dex pc mismatch when merging.
250   // This does not apply to uninitialized "this" reference types.
251   static bool NeedsAllocationDexPc(const RegType& reg_type);
252 
253   void EnsureAllocationDexPcsAvailable();
254 
255   template <LockOp kLockOp>
256   ALWAYS_INLINE void SetRegisterTypeImpl(uint32_t vdst, uint16_t new_id)
257       REQUIRES_SHARED(Locks::mutator_lock_);
258   void SetRegisterTypeWideImpl(uint32_t vdst, uint16_t new_id1, uint16_t new_id2)
259       REQUIRES_SHARED(Locks::mutator_lock_);
260 
CopyRegToLockDepth(size_t dst,size_t src)261   void CopyRegToLockDepth(size_t dst, size_t src) {
262     // Note: We do not clear the entry for `dst` before copying, so we need to `Overwrite()`
263     // or `erase()`. This preserves the lock depths in the unlikely case that `dst == src`.
264     auto it = reg_to_lock_depths_.find(src);
265     if (it != reg_to_lock_depths_.end()) {
266       reg_to_lock_depths_.Overwrite(dst, it->second);
267     } else {
268       reg_to_lock_depths_.erase(dst);
269     }
270   }
271 
IsSetLockDepth(size_t reg,size_t depth)272   bool IsSetLockDepth(size_t reg, size_t depth) {
273     auto it = reg_to_lock_depths_.find(reg);
274     if (it != reg_to_lock_depths_.end()) {
275       return (it->second & (1 << depth)) != 0;
276     } else {
277       return false;
278     }
279   }
280 
SetRegToLockDepth(size_t reg,size_t depth)281   bool SetRegToLockDepth(size_t reg, size_t depth) {
282     CHECK_LT(depth, kMaxMonitorStackDepth);
283     if (IsSetLockDepth(reg, depth)) {
284       return false;  // Register already holds lock so locking twice is erroneous.
285     }
286     auto it = reg_to_lock_depths_.find(reg);
287     if (it == reg_to_lock_depths_.end()) {
288       reg_to_lock_depths_.Put(reg, 1 << depth);
289     } else {
290       it->second |= (1 << depth);
291     }
292     return true;
293   }
294 
295   void ClearRegToLockDepth(size_t reg, size_t depth);
296 
ClearAllRegToLockDepths(size_t reg)297   void ClearAllRegToLockDepths(size_t reg) {
298     reg_to_lock_depths_.erase(reg);
299   }
300 
301   RegisterLine(size_t num_regs, ArenaAllocator& allocator);
302 
303   static constexpr uint32_t kNoDexPc = static_cast<uint32_t>(-1);
304 
305   // Length of reg_types_
306   const uint32_t num_regs_;
307 
308   // Storage for the result register's type, valid after an invocation.
309   uint16_t result_[2];
310 
311   // Track allocation dex pcs for `new-instance` results moved to other registers.
312   uint32_t* allocation_dex_pcs_;
313 
314   // A stack of monitor enter locations.
315   ArenaVector<uint32_t> monitors_;
316 
317   // A map from register to a bit vector of indices into the monitors_ stack. As we pop the monitor
318   // stack we verify that monitor-enter/exit are correctly nested. That is, if there was a
319   // monitor-enter on v5 and then on v6, we expect the monitor-exit to be on v6 then on v5.
320   RegToLockDepthsMap reg_to_lock_depths_;
321 
322   // Whether "this" initialization (a constructor supercall) has happened.
323   bool this_initialized_;
324 
325   // An array of RegType Ids associated with each dex register.
326   uint16_t line_[1];
327 
328   friend class RegisterLineArenaDelete;
329 
330   DISALLOW_COPY_AND_ASSIGN(RegisterLine);
331 };
332 
333 class RegisterLineArenaDelete : public ArenaDelete<RegisterLine> {
334  public:
335   void operator()(RegisterLine* ptr) const;
336 };
337 
338 using RegisterLineArenaUniquePtr = std::unique_ptr<RegisterLine, RegisterLineArenaDelete>;
339 
340 }  // namespace verifier
341 }  // namespace art
342 
343 #endif  // ART_RUNTIME_VERIFIER_REGISTER_LINE_H_
344