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 "base/logging.h"
24 #include "base/stl_util.h"
25 #include "dex_file.h"
26 #include "dex_instruction.h"
27 #include "dex_instruction-inl.h"
28 #include "base/mutex.h"
29 #include "base/mutex-inl.h"
30 #include "mirror/art_method.h"
31 #include "mirror/art_method-inl.h"
32 #include "mirror/class.h"
33 #include "mirror/class-inl.h"
34 #include "mirror/dex_cache.h"
35 #include "mirror/dex_cache-inl.h"
36 #include "mirror/object.h"
37 #include "mirror/object-inl.h"
38 #include "verifier/dex_gc_map.h"
39 #include "verifier/method_verifier.h"
40 #include "verifier/method_verifier-inl.h"
41 #include "verifier/register_line.h"
42 #include "verifier/register_line-inl.h"
43 
44 namespace art {
45 
Create(verifier::MethodVerifier * method_verifier,bool compile)46 const VerifiedMethod* VerifiedMethod::Create(verifier::MethodVerifier* method_verifier,
47                                              bool compile) {
48   std::unique_ptr<VerifiedMethod> verified_method(new VerifiedMethod);
49   if (compile) {
50     /* Generate a register map. */
51     if (!verified_method->GenerateGcMap(method_verifier)) {
52       return nullptr;  // Not a real failure, but a failure to encode.
53     }
54     if (kIsDebugBuild) {
55       VerifyGcMap(method_verifier, verified_method->dex_gc_map_);
56     }
57 
58     // TODO: move this out when DEX-to-DEX supports devirtualization.
59     if (method_verifier->HasVirtualOrInterfaceInvokes()) {
60       verified_method->GenerateDevirtMap(method_verifier);
61     }
62   }
63 
64   if (method_verifier->HasCheckCasts()) {
65     verified_method->GenerateSafeCastSet(method_verifier);
66   }
67   return verified_method.release();
68 }
69 
GetDevirtTarget(uint32_t dex_pc) const70 const MethodReference* VerifiedMethod::GetDevirtTarget(uint32_t dex_pc) const {
71   auto it = devirt_map_.find(dex_pc);
72   return (it != devirt_map_.end()) ? &it->second : nullptr;
73 }
74 
IsSafeCast(uint32_t pc) const75 bool VerifiedMethod::IsSafeCast(uint32_t pc) const {
76   return std::binary_search(safe_cast_set_.begin(), safe_cast_set_.end(), pc);
77 }
78 
GenerateGcMap(verifier::MethodVerifier * method_verifier)79 bool VerifiedMethod::GenerateGcMap(verifier::MethodVerifier* method_verifier) {
80   DCHECK(dex_gc_map_.empty());
81   size_t num_entries, ref_bitmap_bits, pc_bits;
82   ComputeGcMapSizes(method_verifier, &num_entries, &ref_bitmap_bits, &pc_bits);
83   // There's a single byte to encode the size of each bitmap.
84   if (ref_bitmap_bits >= (8 /* bits per byte */ * 8192 /* 13-bit size */ )) {
85     LOG(WARNING) << "Cannot encode GC map for method with " << ref_bitmap_bits << " registers: "
86                  << PrettyMethod(method_verifier->GetMethodReference().dex_method_index,
87                                  *method_verifier->GetMethodReference().dex_file);
88     return false;
89   }
90   size_t ref_bitmap_bytes = (ref_bitmap_bits + 7) / 8;
91   // There are 2 bytes to encode the number of entries.
92   if (num_entries >= 65536) {
93     LOG(WARNING) << "Cannot encode GC map for method with " << num_entries << " entries: "
94                  << PrettyMethod(method_verifier->GetMethodReference().dex_method_index,
95                                  *method_verifier->GetMethodReference().dex_file);
96     return false;
97   }
98   size_t pc_bytes;
99   verifier::RegisterMapFormat format;
100   if (pc_bits <= 8) {
101     format = verifier::kRegMapFormatCompact8;
102     pc_bytes = 1;
103   } else if (pc_bits <= 16) {
104     format = verifier::kRegMapFormatCompact16;
105     pc_bytes = 2;
106   } else {
107     LOG(WARNING) << "Cannot encode GC map for method with "
108                  << (1 << pc_bits) << " instructions (number is rounded up to nearest power of 2): "
109                  << PrettyMethod(method_verifier->GetMethodReference().dex_method_index,
110                                  *method_verifier->GetMethodReference().dex_file);
111     return false;
112   }
113   size_t table_size = ((pc_bytes + ref_bitmap_bytes) * num_entries) + 4;
114   dex_gc_map_.reserve(table_size);
115   // Write table header.
116   dex_gc_map_.push_back(format | ((ref_bitmap_bytes & ~0xFF) >> 5));
117   dex_gc_map_.push_back(ref_bitmap_bytes & 0xFF);
118   dex_gc_map_.push_back(num_entries & 0xFF);
119   dex_gc_map_.push_back((num_entries >> 8) & 0xFF);
120   // Write table data.
121   const DexFile::CodeItem* code_item = method_verifier->CodeItem();
122   for (size_t i = 0; i < code_item->insns_size_in_code_units_; i++) {
123     if (method_verifier->GetInstructionFlags(i).IsCompileTimeInfoPoint()) {
124       dex_gc_map_.push_back(i & 0xFF);
125       if (pc_bytes == 2) {
126         dex_gc_map_.push_back((i >> 8) & 0xFF);
127       }
128       verifier::RegisterLine* line = method_verifier->GetRegLine(i);
129       line->WriteReferenceBitMap(dex_gc_map_, ref_bitmap_bytes);
130     }
131   }
132   DCHECK_EQ(dex_gc_map_.size(), table_size);
133   return true;
134 }
135 
VerifyGcMap(verifier::MethodVerifier * method_verifier,const std::vector<uint8_t> & data)136 void VerifiedMethod::VerifyGcMap(verifier::MethodVerifier* method_verifier,
137                                  const std::vector<uint8_t>& data) {
138   // Check that for every GC point there is a map entry, there aren't entries for non-GC points,
139   // that the table data is well formed and all references are marked (or not) in the bitmap.
140   verifier::DexPcToReferenceMap map(&data[0]);
141   DCHECK_EQ(data.size(), map.RawSize());
142   size_t map_index = 0;
143   const DexFile::CodeItem* code_item = method_verifier->CodeItem();
144   for (size_t i = 0; i < code_item->insns_size_in_code_units_; i++) {
145     const uint8_t* reg_bitmap = map.FindBitMap(i, false);
146     if (method_verifier->GetInstructionFlags(i).IsCompileTimeInfoPoint()) {
147       DCHECK_LT(map_index, map.NumEntries());
148       DCHECK_EQ(map.GetDexPc(map_index), i);
149       DCHECK_EQ(map.GetBitMap(map_index), reg_bitmap);
150       map_index++;
151       verifier::RegisterLine* line = method_verifier->GetRegLine(i);
152       for (size_t j = 0; j < code_item->registers_size_; j++) {
153         if (line->GetRegisterType(j).IsNonZeroReferenceTypes()) {
154           DCHECK_LT(j / 8, map.RegWidth());
155           DCHECK_EQ((reg_bitmap[j / 8] >> (j % 8)) & 1, 1);
156         } else if ((j / 8) < map.RegWidth()) {
157           DCHECK_EQ((reg_bitmap[j / 8] >> (j % 8)) & 1, 0);
158         } else {
159           // If a register doesn't contain a reference then the bitmap may be shorter than the line.
160         }
161       }
162     } else {
163       DCHECK(i >= 65536 || reg_bitmap == NULL);
164     }
165   }
166 }
167 
ComputeGcMapSizes(verifier::MethodVerifier * method_verifier,size_t * gc_points,size_t * ref_bitmap_bits,size_t * log2_max_gc_pc)168 void VerifiedMethod::ComputeGcMapSizes(verifier::MethodVerifier* method_verifier,
169                                        size_t* gc_points, size_t* ref_bitmap_bits,
170                                        size_t* log2_max_gc_pc) {
171   size_t local_gc_points = 0;
172   size_t max_insn = 0;
173   size_t max_ref_reg = -1;
174   const DexFile::CodeItem* code_item = method_verifier->CodeItem();
175   for (size_t i = 0; i < code_item->insns_size_in_code_units_; i++) {
176     if (method_verifier->GetInstructionFlags(i).IsCompileTimeInfoPoint()) {
177       local_gc_points++;
178       max_insn = i;
179       verifier::RegisterLine* line = method_verifier->GetRegLine(i);
180       max_ref_reg = line->GetMaxNonZeroReferenceReg(max_ref_reg);
181     }
182   }
183   *gc_points = local_gc_points;
184   *ref_bitmap_bits = max_ref_reg + 1;  // If max register is 0 we need 1 bit to encode (ie +1).
185   size_t i = 0;
186   while ((1U << i) <= max_insn) {
187     i++;
188   }
189   *log2_max_gc_pc = i;
190 }
191 
GenerateDevirtMap(verifier::MethodVerifier * method_verifier)192 void VerifiedMethod::GenerateDevirtMap(verifier::MethodVerifier* method_verifier) {
193   // It is risky to rely on reg_types for sharpening in cases of soft
194   // verification, we might end up sharpening to a wrong implementation. Just abort.
195   if (method_verifier->HasFailures()) {
196     return;
197   }
198 
199   const DexFile::CodeItem* code_item = method_verifier->CodeItem();
200   const uint16_t* insns = code_item->insns_;
201   const Instruction* inst = Instruction::At(insns);
202   const Instruction* end = Instruction::At(insns + code_item->insns_size_in_code_units_);
203 
204   for (; inst < end; inst = inst->Next()) {
205     bool is_virtual   = (inst->Opcode() == Instruction::INVOKE_VIRTUAL) ||
206         (inst->Opcode() ==  Instruction::INVOKE_VIRTUAL_RANGE);
207     bool is_interface = (inst->Opcode() == Instruction::INVOKE_INTERFACE) ||
208         (inst->Opcode() == Instruction::INVOKE_INTERFACE_RANGE);
209 
210     if (!is_interface && !is_virtual) {
211       continue;
212     }
213     // Get reg type for register holding the reference to the object that will be dispatched upon.
214     uint32_t dex_pc = inst->GetDexPc(insns);
215     verifier::RegisterLine* line = method_verifier->GetRegLine(dex_pc);
216     bool is_range = (inst->Opcode() ==  Instruction::INVOKE_VIRTUAL_RANGE) ||
217         (inst->Opcode() ==  Instruction::INVOKE_INTERFACE_RANGE);
218     verifier::RegType&
219         reg_type(line->GetRegisterType(is_range ? inst->VRegC_3rc() : inst->VRegC_35c()));
220 
221     if (!reg_type.HasClass()) {
222       // We will compute devirtualization information only when we know the Class of the reg type.
223       continue;
224     }
225     mirror::Class* reg_class = reg_type.GetClass();
226     if (reg_class->IsInterface()) {
227       // We can't devirtualize when the known type of the register is an interface.
228       continue;
229     }
230     if (reg_class->IsAbstract() && !reg_class->IsArrayClass()) {
231       // We can't devirtualize abstract classes except on arrays of abstract classes.
232       continue;
233     }
234     mirror::ArtMethod* abstract_method = method_verifier->GetDexCache()->GetResolvedMethod(
235         is_range ? inst->VRegB_3rc() : inst->VRegB_35c());
236     if (abstract_method == NULL) {
237       // If the method is not found in the cache this means that it was never found
238       // by ResolveMethodAndCheckAccess() called when verifying invoke_*.
239       continue;
240     }
241     // Find the concrete method.
242     mirror::ArtMethod* concrete_method = NULL;
243     if (is_interface) {
244       concrete_method = reg_type.GetClass()->FindVirtualMethodForInterface(abstract_method);
245     }
246     if (is_virtual) {
247       concrete_method = reg_type.GetClass()->FindVirtualMethodForVirtual(abstract_method);
248     }
249     if (concrete_method == NULL || concrete_method->IsAbstract()) {
250       // In cases where concrete_method is not found, or is abstract, continue to the next invoke.
251       continue;
252     }
253     if (reg_type.IsPreciseReference() || concrete_method->IsFinal() ||
254         concrete_method->GetDeclaringClass()->IsFinal()) {
255       // If we knew exactly the class being dispatched upon, or if the target method cannot be
256       // overridden record the target to be used in the compiler driver.
257       MethodReference concrete_ref(
258           concrete_method->GetDeclaringClass()->GetDexCache()->GetDexFile(),
259           concrete_method->GetDexMethodIndex());
260       devirt_map_.Put(dex_pc, concrete_ref);
261     }
262   }
263 }
264 
GenerateSafeCastSet(verifier::MethodVerifier * method_verifier)265 void VerifiedMethod::GenerateSafeCastSet(verifier::MethodVerifier* method_verifier) {
266   /*
267    * Walks over the method code and adds any cast instructions in which
268    * the type cast is implicit to a set, which is used in the code generation
269    * to elide these casts.
270    */
271   if (method_verifier->HasFailures()) {
272     return;
273   }
274   const DexFile::CodeItem* code_item = method_verifier->CodeItem();
275   const Instruction* inst = Instruction::At(code_item->insns_);
276   const Instruction* end = Instruction::At(code_item->insns_ +
277                                            code_item->insns_size_in_code_units_);
278 
279   for (; inst < end; inst = inst->Next()) {
280     Instruction::Code code = inst->Opcode();
281     if ((code == Instruction::CHECK_CAST) || (code == Instruction::APUT_OBJECT)) {
282       uint32_t dex_pc = inst->GetDexPc(code_item->insns_);
283       const verifier::RegisterLine* line = method_verifier->GetRegLine(dex_pc);
284       bool is_safe_cast = false;
285       if (code == Instruction::CHECK_CAST) {
286         verifier::RegType& reg_type(line->GetRegisterType(inst->VRegA_21c()));
287         verifier::RegType& cast_type =
288             method_verifier->ResolveCheckedClass(inst->VRegB_21c());
289         is_safe_cast = cast_type.IsStrictlyAssignableFrom(reg_type);
290       } else {
291         verifier::RegType& array_type(line->GetRegisterType(inst->VRegB_23x()));
292         // We only know its safe to assign to an array if the array type is precise. For example,
293         // an Object[] can have any type of object stored in it, but it may also be assigned a
294         // String[] in which case the stores need to be of Strings.
295         if (array_type.IsPreciseReference()) {
296           verifier::RegType& value_type(line->GetRegisterType(inst->VRegA_23x()));
297           verifier::RegType& component_type = method_verifier->GetRegTypeCache()
298               ->GetComponentType(array_type, method_verifier->GetClassLoader());
299           is_safe_cast = component_type.IsStrictlyAssignableFrom(value_type);
300         }
301       }
302       if (is_safe_cast) {
303         // Verify ordering for push_back() to the sorted vector.
304         DCHECK(safe_cast_set_.empty() || safe_cast_set_.back() < dex_pc);
305         safe_cast_set_.push_back(dex_pc);
306       }
307     }
308   }
309 }
310 
311 }  // namespace art
312