1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "verified_method.h"
18 
19 #include <algorithm>
20 #include <memory>
21 #include <vector>
22 
23 #include "art_method-inl.h"
24 #include "base/logging.h"
25 #include "base/stl_util.h"
26 #include "dex_file.h"
27 #include "dex_instruction-inl.h"
28 #include "dex_instruction_utils.h"
29 #include "mirror/class-inl.h"
30 #include "mirror/dex_cache-inl.h"
31 #include "mirror/object-inl.h"
32 #include "utils.h"
33 #include "verifier/dex_gc_map.h"
34 #include "verifier/method_verifier-inl.h"
35 #include "verifier/reg_type-inl.h"
36 #include "verifier/register_line-inl.h"
37 
38 namespace art {
39 
Create(verifier::MethodVerifier * method_verifier,bool compile)40 const VerifiedMethod* VerifiedMethod::Create(verifier::MethodVerifier* method_verifier,
41                                              bool compile) {
42   std::unique_ptr<VerifiedMethod> verified_method(new VerifiedMethod);
43   verified_method->has_verification_failures_ = method_verifier->HasFailures();
44   verified_method->has_runtime_throw_ = method_verifier->HasInstructionThatWillThrow();
45   if (compile) {
46     /* Generate a register map. */
47     if (!verified_method->GenerateGcMap(method_verifier)) {
48       return nullptr;  // Not a real failure, but a failure to encode.
49     }
50     if (kIsDebugBuild) {
51       VerifyGcMap(method_verifier, verified_method->dex_gc_map_);
52     }
53 
54     // TODO: move this out when DEX-to-DEX supports devirtualization.
55     if (method_verifier->HasVirtualOrInterfaceInvokes()) {
56       verified_method->GenerateDevirtMap(method_verifier);
57     }
58 
59     // Only need dequicken info for JIT so far.
60     if (Runtime::Current()->UseJit() && !verified_method->GenerateDequickenMap(method_verifier)) {
61       return nullptr;
62     }
63   }
64 
65   if (method_verifier->HasCheckCasts()) {
66     verified_method->GenerateSafeCastSet(method_verifier);
67   }
68 
69   verified_method->SetStringInitPcRegMap(method_verifier->GetStringInitPcRegMap());
70 
71   return verified_method.release();
72 }
73 
GetDevirtTarget(uint32_t dex_pc) const74 const MethodReference* VerifiedMethod::GetDevirtTarget(uint32_t dex_pc) const {
75   auto it = devirt_map_.find(dex_pc);
76   return (it != devirt_map_.end()) ? &it->second : nullptr;
77 }
78 
GetDequickenIndex(uint32_t dex_pc) const79 const DexFileReference* VerifiedMethod::GetDequickenIndex(uint32_t dex_pc) const {
80   DCHECK(Runtime::Current()->UseJit());
81   auto it = dequicken_map_.find(dex_pc);
82   return (it != dequicken_map_.end()) ? &it->second : nullptr;
83 }
84 
IsSafeCast(uint32_t pc) const85 bool VerifiedMethod::IsSafeCast(uint32_t pc) const {
86   return std::binary_search(safe_cast_set_.begin(), safe_cast_set_.end(), pc);
87 }
88 
GenerateGcMap(verifier::MethodVerifier * method_verifier)89 bool VerifiedMethod::GenerateGcMap(verifier::MethodVerifier* method_verifier) {
90   DCHECK(dex_gc_map_.empty());
91   size_t num_entries, ref_bitmap_bits, pc_bits;
92   ComputeGcMapSizes(method_verifier, &num_entries, &ref_bitmap_bits, &pc_bits);
93   const size_t ref_bitmap_bytes = RoundUp(ref_bitmap_bits, kBitsPerByte) / kBitsPerByte;
94   static constexpr size_t kFormatBits = 3;
95   // We have 16 - kFormatBits available for the ref_bitmap_bytes.
96   if ((ref_bitmap_bytes >> (16u - kFormatBits)) != 0) {
97     LOG(WARNING) << "Cannot encode GC map for method with " << ref_bitmap_bits << " registers: "
98                  << PrettyMethod(method_verifier->GetMethodReference().dex_method_index,
99                                  *method_verifier->GetMethodReference().dex_file);
100     return false;
101   }
102   // There are 2 bytes to encode the number of entries.
103   if (num_entries >= 65536) {
104     LOG(WARNING) << "Cannot encode GC map for method with " << num_entries << " entries: "
105                  << PrettyMethod(method_verifier->GetMethodReference().dex_method_index,
106                                  *method_verifier->GetMethodReference().dex_file);
107     return false;
108   }
109   size_t pc_bytes;
110   verifier::RegisterMapFormat format;
111   if (pc_bits <= kBitsPerByte) {
112     format = verifier::kRegMapFormatCompact8;
113     pc_bytes = 1;
114   } else if (pc_bits <= kBitsPerByte * 2) {
115     format = verifier::kRegMapFormatCompact16;
116     pc_bytes = 2;
117   } else {
118     LOG(WARNING) << "Cannot encode GC map for method with "
119                  << (1 << pc_bits) << " instructions (number is rounded up to nearest power of 2): "
120                  << PrettyMethod(method_verifier->GetMethodReference().dex_method_index,
121                                  *method_verifier->GetMethodReference().dex_file);
122     return false;
123   }
124   size_t table_size = ((pc_bytes + ref_bitmap_bytes) * num_entries) + 4;
125   dex_gc_map_.reserve(table_size);
126   // Write table header.
127   dex_gc_map_.push_back(format | ((ref_bitmap_bytes & ~0xFF) >> (kBitsPerByte - kFormatBits)));
128   dex_gc_map_.push_back(ref_bitmap_bytes & 0xFF);
129   dex_gc_map_.push_back(num_entries & 0xFF);
130   dex_gc_map_.push_back((num_entries >> 8) & 0xFF);
131   // Write table data.
132   const DexFile::CodeItem* code_item = method_verifier->CodeItem();
133   for (size_t i = 0; i < code_item->insns_size_in_code_units_; i++) {
134     if (method_verifier->GetInstructionFlags(i).IsCompileTimeInfoPoint()) {
135       dex_gc_map_.push_back(i & 0xFF);
136       if (pc_bytes == 2) {
137         dex_gc_map_.push_back((i >> 8) & 0xFF);
138       }
139       verifier::RegisterLine* line = method_verifier->GetRegLine(i);
140       line->WriteReferenceBitMap(method_verifier, &dex_gc_map_, ref_bitmap_bytes);
141     }
142   }
143   DCHECK_EQ(dex_gc_map_.size(), table_size);
144   return true;
145 }
146 
VerifyGcMap(verifier::MethodVerifier * method_verifier,const std::vector<uint8_t> & data)147 void VerifiedMethod::VerifyGcMap(verifier::MethodVerifier* method_verifier,
148                                  const std::vector<uint8_t>& data) {
149   // Check that for every GC point there is a map entry, there aren't entries for non-GC points,
150   // that the table data is well formed and all references are marked (or not) in the bitmap.
151   verifier::DexPcToReferenceMap map(&data[0]);
152   CHECK_EQ(data.size(), map.RawSize()) << map.NumEntries() << " " << map.RegWidth();
153   size_t map_index = 0;
154   const DexFile::CodeItem* code_item = method_verifier->CodeItem();
155   for (size_t i = 0; i < code_item->insns_size_in_code_units_; i++) {
156     const uint8_t* reg_bitmap = map.FindBitMap(i, false);
157     if (method_verifier->GetInstructionFlags(i).IsCompileTimeInfoPoint()) {
158       DCHECK_LT(map_index, map.NumEntries());
159       DCHECK_EQ(map.GetDexPc(map_index), i);
160       DCHECK_EQ(map.GetBitMap(map_index), reg_bitmap);
161       map_index++;
162       verifier::RegisterLine* line = method_verifier->GetRegLine(i);
163       for (size_t j = 0; j < code_item->registers_size_; j++) {
164         if (line->GetRegisterType(method_verifier, j).IsNonZeroReferenceTypes()) {
165           DCHECK_LT(j / kBitsPerByte, map.RegWidth());
166           DCHECK_EQ((reg_bitmap[j / kBitsPerByte] >> (j % kBitsPerByte)) & 1, 1);
167         } else if ((j / kBitsPerByte) < map.RegWidth()) {
168           DCHECK_EQ((reg_bitmap[j / kBitsPerByte] >> (j % kBitsPerByte)) & 1, 0);
169         } else {
170           // If a register doesn't contain a reference then the bitmap may be shorter than the line.
171         }
172       }
173     } else {
174       DCHECK(i >= 65536 || reg_bitmap == nullptr);
175     }
176   }
177 }
178 
ComputeGcMapSizes(verifier::MethodVerifier * method_verifier,size_t * gc_points,size_t * ref_bitmap_bits,size_t * log2_max_gc_pc)179 void VerifiedMethod::ComputeGcMapSizes(verifier::MethodVerifier* method_verifier,
180                                        size_t* gc_points, size_t* ref_bitmap_bits,
181                                        size_t* log2_max_gc_pc) {
182   size_t local_gc_points = 0;
183   size_t max_insn = 0;
184   size_t max_ref_reg = -1;
185   const DexFile::CodeItem* code_item = method_verifier->CodeItem();
186   for (size_t i = 0; i < code_item->insns_size_in_code_units_; i++) {
187     if (method_verifier->GetInstructionFlags(i).IsCompileTimeInfoPoint()) {
188       local_gc_points++;
189       max_insn = i;
190       verifier::RegisterLine* line = method_verifier->GetRegLine(i);
191       max_ref_reg = line->GetMaxNonZeroReferenceReg(method_verifier, max_ref_reg);
192     }
193   }
194   *gc_points = local_gc_points;
195   *ref_bitmap_bits = max_ref_reg + 1;  // If max register is 0 we need 1 bit to encode (ie +1).
196   size_t i = 0;
197   while ((1U << i) <= max_insn) {
198     i++;
199   }
200   *log2_max_gc_pc = i;
201 }
202 
GenerateDequickenMap(verifier::MethodVerifier * method_verifier)203 bool VerifiedMethod::GenerateDequickenMap(verifier::MethodVerifier* method_verifier) {
204   if (method_verifier->HasFailures()) {
205     return false;
206   }
207   const DexFile::CodeItem* code_item = method_verifier->CodeItem();
208   const uint16_t* insns = code_item->insns_;
209   const Instruction* inst = Instruction::At(insns);
210   const Instruction* end = Instruction::At(insns + code_item->insns_size_in_code_units_);
211   for (; inst < end; inst = inst->Next()) {
212     const bool is_virtual_quick = inst->Opcode() == Instruction::INVOKE_VIRTUAL_QUICK;
213     const bool is_range_quick = inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK;
214     if (is_virtual_quick || is_range_quick) {
215       uint32_t dex_pc = inst->GetDexPc(insns);
216       verifier::RegisterLine* line = method_verifier->GetRegLine(dex_pc);
217       ArtMethod* method =
218           method_verifier->GetQuickInvokedMethod(inst, line, is_range_quick, true);
219       if (method == nullptr) {
220         // It can be null if the line wasn't verified since it was unreachable.
221         return false;
222       }
223       // The verifier must know what the type of the object was or else we would have gotten a
224       // failure. Put the dex method index in the dequicken map since we need this to get number of
225       // arguments in the compiler.
226       dequicken_map_.Put(dex_pc, DexFileReference(method->GetDexFile(),
227                                                   method->GetDexMethodIndex()));
228     } else if (IsInstructionIGetQuickOrIPutQuick(inst->Opcode())) {
229       uint32_t dex_pc = inst->GetDexPc(insns);
230       verifier::RegisterLine* line = method_verifier->GetRegLine(dex_pc);
231       ArtField* field = method_verifier->GetQuickFieldAccess(inst, line);
232       if (field == nullptr) {
233         // It can be null if the line wasn't verified since it was unreachable.
234         return false;
235       }
236       // The verifier must know what the type of the field was or else we would have gotten a
237       // failure. Put the dex field index in the dequicken map since we need this for lowering
238       // in the compiler.
239       // TODO: Putting a field index in a method reference is gross.
240       dequicken_map_.Put(dex_pc, DexFileReference(field->GetDexFile(), field->GetDexFieldIndex()));
241     }
242   }
243   return true;
244 }
245 
GenerateDevirtMap(verifier::MethodVerifier * method_verifier)246 void VerifiedMethod::GenerateDevirtMap(verifier::MethodVerifier* method_verifier) {
247   // It is risky to rely on reg_types for sharpening in cases of soft
248   // verification, we might end up sharpening to a wrong implementation. Just abort.
249   if (method_verifier->HasFailures()) {
250     return;
251   }
252 
253   const DexFile::CodeItem* code_item = method_verifier->CodeItem();
254   const uint16_t* insns = code_item->insns_;
255   const Instruction* inst = Instruction::At(insns);
256   const Instruction* end = Instruction::At(insns + code_item->insns_size_in_code_units_);
257 
258   for (; inst < end; inst = inst->Next()) {
259     const bool is_virtual = inst->Opcode() == Instruction::INVOKE_VIRTUAL ||
260         inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE;
261     const bool is_interface = inst->Opcode() == Instruction::INVOKE_INTERFACE ||
262         inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE;
263 
264     if (!is_interface && !is_virtual) {
265       continue;
266     }
267     // Get reg type for register holding the reference to the object that will be dispatched upon.
268     uint32_t dex_pc = inst->GetDexPc(insns);
269     verifier::RegisterLine* line = method_verifier->GetRegLine(dex_pc);
270     const bool is_range = inst->Opcode() == Instruction::INVOKE_VIRTUAL_RANGE ||
271         inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE;
272     const verifier::RegType&
273         reg_type(line->GetRegisterType(method_verifier,
274                                        is_range ? inst->VRegC_3rc() : inst->VRegC_35c()));
275 
276     if (!reg_type.HasClass()) {
277       // We will compute devirtualization information only when we know the Class of the reg type.
278       continue;
279     }
280     mirror::Class* reg_class = reg_type.GetClass();
281     if (reg_class->IsInterface()) {
282       // We can't devirtualize when the known type of the register is an interface.
283       continue;
284     }
285     if (reg_class->IsAbstract() && !reg_class->IsArrayClass()) {
286       // We can't devirtualize abstract classes except on arrays of abstract classes.
287       continue;
288     }
289     auto* cl = Runtime::Current()->GetClassLinker();
290     size_t pointer_size = cl->GetImagePointerSize();
291     ArtMethod* abstract_method = method_verifier->GetDexCache()->GetResolvedMethod(
292         is_range ? inst->VRegB_3rc() : inst->VRegB_35c(), pointer_size);
293     if (abstract_method == nullptr) {
294       // If the method is not found in the cache this means that it was never found
295       // by ResolveMethodAndCheckAccess() called when verifying invoke_*.
296       continue;
297     }
298     // Find the concrete method.
299     ArtMethod* concrete_method = nullptr;
300     if (is_interface) {
301       concrete_method = reg_type.GetClass()->FindVirtualMethodForInterface(
302           abstract_method, pointer_size);
303     }
304     if (is_virtual) {
305       concrete_method = reg_type.GetClass()->FindVirtualMethodForVirtual(
306           abstract_method, pointer_size);
307     }
308     if (concrete_method == nullptr || concrete_method->IsAbstract()) {
309       // In cases where concrete_method is not found, or is abstract, continue to the next invoke.
310       continue;
311     }
312     if (reg_type.IsPreciseReference() || concrete_method->IsFinal() ||
313         concrete_method->GetDeclaringClass()->IsFinal()) {
314       // If we knew exactly the class being dispatched upon, or if the target method cannot be
315       // overridden record the target to be used in the compiler driver.
316       devirt_map_.Put(dex_pc, concrete_method->ToMethodReference());
317     }
318   }
319 }
320 
GenerateSafeCastSet(verifier::MethodVerifier * method_verifier)321 void VerifiedMethod::GenerateSafeCastSet(verifier::MethodVerifier* method_verifier) {
322   /*
323    * Walks over the method code and adds any cast instructions in which
324    * the type cast is implicit to a set, which is used in the code generation
325    * to elide these casts.
326    */
327   if (method_verifier->HasFailures()) {
328     return;
329   }
330   const DexFile::CodeItem* code_item = method_verifier->CodeItem();
331   const Instruction* inst = Instruction::At(code_item->insns_);
332   const Instruction* end = Instruction::At(code_item->insns_ +
333                                            code_item->insns_size_in_code_units_);
334 
335   for (; inst < end; inst = inst->Next()) {
336     Instruction::Code code = inst->Opcode();
337     if ((code == Instruction::CHECK_CAST) || (code == Instruction::APUT_OBJECT)) {
338       uint32_t dex_pc = inst->GetDexPc(code_item->insns_);
339       if (!method_verifier->GetInstructionFlags(dex_pc).IsVisited()) {
340         // Do not attempt to quicken this instruction, it's unreachable anyway.
341         continue;
342       }
343       const verifier::RegisterLine* line = method_verifier->GetRegLine(dex_pc);
344       bool is_safe_cast = false;
345       if (code == Instruction::CHECK_CAST) {
346         const verifier::RegType& reg_type(line->GetRegisterType(method_verifier,
347                                                                 inst->VRegA_21c()));
348         const verifier::RegType& cast_type =
349             method_verifier->ResolveCheckedClass(inst->VRegB_21c());
350         is_safe_cast = cast_type.IsStrictlyAssignableFrom(reg_type);
351       } else {
352         const verifier::RegType& array_type(line->GetRegisterType(method_verifier,
353                                                                   inst->VRegB_23x()));
354         // We only know its safe to assign to an array if the array type is precise. For example,
355         // an Object[] can have any type of object stored in it, but it may also be assigned a
356         // String[] in which case the stores need to be of Strings.
357         if (array_type.IsPreciseReference()) {
358           const verifier::RegType& value_type(line->GetRegisterType(method_verifier,
359                                                                     inst->VRegA_23x()));
360           const verifier::RegType& component_type = method_verifier->GetRegTypeCache()
361               ->GetComponentType(array_type, method_verifier->GetClassLoader());
362           is_safe_cast = component_type.IsStrictlyAssignableFrom(value_type);
363         }
364       }
365       if (is_safe_cast) {
366         // Verify ordering for push_back() to the sorted vector.
367         DCHECK(safe_cast_set_.empty() || safe_cast_set_.back() < dex_pc);
368         safe_cast_set_.push_back(dex_pc);
369       }
370     }
371   }
372 }
373 
374 }  // namespace art
375