• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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 "stack_map_stream.h"
18 
19 #include <memory>
20 #include <vector>
21 
22 #include "art_method-inl.h"
23 #include "base/globals.h"
24 #include "base/stl_util.h"
25 #include "class_linker.h"
26 #include "dex/dex_file.h"
27 #include "dex/dex_file_types.h"
28 #include "driver/compiler_options.h"
29 #include "optimizing/code_generator.h"
30 #include "optimizing/nodes.h"
31 #include "optimizing/optimizing_compiler.h"
32 #include "runtime.h"
33 #include "scoped_thread_state_change-inl.h"
34 #include "stack_map.h"
35 
36 namespace art HIDDEN {
37 
38 constexpr static bool kVerifyStackMaps = kIsDebugBuild;
39 
GetStackMapNativePcOffset(size_t i)40 uint32_t StackMapStream::GetStackMapNativePcOffset(size_t i) {
41   return StackMap::UnpackNativePc(stack_maps_[i][StackMap::kPackedNativePc], instruction_set_);
42 }
43 
SetStackMapNativePcOffset(size_t i,uint32_t native_pc_offset)44 void StackMapStream::SetStackMapNativePcOffset(size_t i, uint32_t native_pc_offset) {
45   stack_maps_[i][StackMap::kPackedNativePc] =
46       StackMap::PackNativePc(native_pc_offset, instruction_set_);
47 }
48 
BeginMethod(size_t frame_size_in_bytes,size_t core_spill_mask,size_t fp_spill_mask,uint32_t num_dex_registers,bool baseline,bool debuggable)49 void StackMapStream::BeginMethod(size_t frame_size_in_bytes,
50                                  size_t core_spill_mask,
51                                  size_t fp_spill_mask,
52                                  uint32_t num_dex_registers,
53                                  bool baseline,
54                                  bool debuggable) {
55   DCHECK(!in_method_) << "Mismatched Begin/End calls";
56   in_method_ = true;
57   DCHECK_EQ(packed_frame_size_, 0u) << "BeginMethod was already called";
58 
59   DCHECK_ALIGNED(frame_size_in_bytes, kStackAlignment);
60   packed_frame_size_ = frame_size_in_bytes / kStackAlignment;
61   core_spill_mask_ = core_spill_mask;
62   fp_spill_mask_ = fp_spill_mask;
63   num_dex_registers_ = num_dex_registers;
64   baseline_ = baseline;
65   debuggable_ = debuggable;
66 
67   if (kVerifyStackMaps) {
68     dchecks_.emplace_back([=](const CodeInfo& code_info) {
69       DCHECK_EQ(code_info.packed_frame_size_, frame_size_in_bytes / kStackAlignment);
70       DCHECK_EQ(code_info.core_spill_mask_, core_spill_mask);
71       DCHECK_EQ(code_info.fp_spill_mask_, fp_spill_mask);
72       DCHECK_EQ(code_info.number_of_dex_registers_, num_dex_registers);
73     });
74   }
75 }
76 
EndMethod(size_t code_size)77 void StackMapStream::EndMethod(size_t code_size) {
78   DCHECK(in_method_) << "Mismatched Begin/End calls";
79   in_method_ = false;
80   code_size_ = code_size;
81 
82   // Read the stack masks now. The compiler might have updated them.
83   for (size_t i = 0; i < lazy_stack_masks_.size(); i++) {
84     BitVector* stack_mask = lazy_stack_masks_[i];
85     if (stack_mask != nullptr && stack_mask->GetNumberOfBits() != 0) {
86       stack_maps_[i][StackMap::kStackMaskIndex] =
87           stack_masks_.Dedup(stack_mask->GetRawStorage(), stack_mask->GetNumberOfBits());
88     }
89   }
90 
91   if (kIsDebugBuild) {
92     uint32_t packed_code_size = StackMap::PackNativePc(code_size, instruction_set_);
93     for (size_t i = 0; i < stack_maps_.size(); i++) {
94       DCHECK_LE(stack_maps_[i][StackMap::kPackedNativePc], packed_code_size);
95     }
96   }
97 
98   if (kVerifyStackMaps) {
99     dchecks_.emplace_back([=](const CodeInfo& code_info) {
100         CHECK_EQ(code_info.code_size_, code_size);
101     });
102   }
103 }
104 
BeginStackMapEntry(uint32_t dex_pc,uint32_t native_pc_offset,uint32_t register_mask,BitVector * stack_mask,StackMap::Kind kind,bool needs_vreg_info,const std::vector<uint32_t> & dex_pc_list_for_catch_verification)105 void StackMapStream::BeginStackMapEntry(
106     uint32_t dex_pc,
107     uint32_t native_pc_offset,
108     uint32_t register_mask,
109     BitVector* stack_mask,
110     StackMap::Kind kind,
111     bool needs_vreg_info,
112     const std::vector<uint32_t>& dex_pc_list_for_catch_verification) {
113   DCHECK(in_method_) << "Call BeginMethod first";
114   DCHECK(!in_stack_map_) << "Mismatched Begin/End calls";
115   in_stack_map_ = true;
116 
117   DCHECK_IMPLIES(!dex_pc_list_for_catch_verification.empty(), kind == StackMap::Kind::Catch);
118   DCHECK_IMPLIES(!dex_pc_list_for_catch_verification.empty(), kIsDebugBuild);
119 
120   current_stack_map_ = BitTableBuilder<StackMap>::Entry();
121   current_stack_map_[StackMap::kKind] = static_cast<uint32_t>(kind);
122   current_stack_map_[StackMap::kPackedNativePc] =
123       StackMap::PackNativePc(native_pc_offset, instruction_set_);
124   current_stack_map_[StackMap::kDexPc] = dex_pc;
125   if (stack_maps_.size() > 0) {
126     // Check that non-catch stack maps are sorted by pc.
127     // Catch stack maps are at the end and may be unordered.
128     if (stack_maps_.back()[StackMap::kKind] == StackMap::Kind::Catch) {
129       DCHECK(current_stack_map_[StackMap::kKind] == StackMap::Kind::Catch);
130     } else if (current_stack_map_[StackMap::kKind] != StackMap::Kind::Catch) {
131       DCHECK_LE(stack_maps_.back()[StackMap::kPackedNativePc],
132                 current_stack_map_[StackMap::kPackedNativePc]);
133     }
134   }
135   if (register_mask != 0) {
136     uint32_t shift = LeastSignificantBit(register_mask);
137     BitTableBuilder<RegisterMask>::Entry entry;
138     entry[RegisterMask::kValue] = register_mask >> shift;
139     entry[RegisterMask::kShift] = shift;
140     current_stack_map_[StackMap::kRegisterMaskIndex] = register_masks_.Dedup(&entry);
141   }
142   // The compiler assumes the bit vector will be read during PrepareForFillIn(),
143   // and it might modify the data before that. Therefore, just store the pointer.
144   // See ClearSpillSlotsFromLoopPhisInStackMap in code_generator.h.
145   lazy_stack_masks_.push_back(stack_mask);
146   current_inline_infos_.clear();
147   current_dex_registers_.clear();
148   expected_num_dex_registers_ = needs_vreg_info  ? num_dex_registers_ : 0u;
149 
150   if (kVerifyStackMaps) {
151     size_t stack_map_index = stack_maps_.size();
152     // Create lambda method, which will be executed at the very end to verify data.
153     // Parameters and local variables will be captured(stored) by the lambda "[=]".
154     dchecks_.emplace_back([=](const CodeInfo& code_info) {
155       if (kind == StackMap::Kind::Default || kind == StackMap::Kind::OSR) {
156         StackMap stack_map = code_info.GetStackMapForNativePcOffset(native_pc_offset,
157                                                                     instruction_set_);
158         CHECK_EQ(stack_map.Row(), stack_map_index);
159       } else if (kind == StackMap::Kind::Catch) {
160         StackMap stack_map = code_info.GetCatchStackMapForDexPc(
161             ArrayRef<const uint32_t>(dex_pc_list_for_catch_verification));
162         CHECK_EQ(stack_map.Row(), stack_map_index);
163       }
164       StackMap stack_map = code_info.GetStackMapAt(stack_map_index);
165       CHECK_EQ(stack_map.GetNativePcOffset(instruction_set_), native_pc_offset);
166       CHECK_EQ(stack_map.GetKind(), static_cast<uint32_t>(kind));
167       CHECK_EQ(stack_map.GetDexPc(), dex_pc);
168       CHECK_EQ(code_info.GetRegisterMaskOf(stack_map), register_mask);
169       BitMemoryRegion seen_stack_mask = code_info.GetStackMaskOf(stack_map);
170       CHECK_GE(seen_stack_mask.size_in_bits(), stack_mask ? stack_mask->GetNumberOfBits() : 0);
171       for (size_t b = 0; b < seen_stack_mask.size_in_bits(); b++) {
172         CHECK_EQ(seen_stack_mask.LoadBit(b), stack_mask != nullptr && stack_mask->IsBitSet(b));
173       }
174     });
175   }
176 }
177 
EndStackMapEntry()178 void StackMapStream::EndStackMapEntry() {
179   DCHECK(in_stack_map_) << "Mismatched Begin/End calls";
180   in_stack_map_ = false;
181 
182   // Generate index into the InlineInfo table.
183   size_t inlining_depth = current_inline_infos_.size();
184   if (!current_inline_infos_.empty()) {
185     current_inline_infos_.back()[InlineInfo::kIsLast] = InlineInfo::kLast;
186     current_stack_map_[StackMap::kInlineInfoIndex] =
187         inline_infos_.Dedup(current_inline_infos_.data(), current_inline_infos_.size());
188   }
189 
190   // Generate delta-compressed dex register map.
191   size_t num_dex_registers = current_dex_registers_.size();
192   if (!current_dex_registers_.empty()) {
193     DCHECK_EQ(expected_num_dex_registers_, current_dex_registers_.size());
194     CreateDexRegisterMap();
195   }
196 
197   stack_maps_.Add(current_stack_map_);
198 
199   if (kVerifyStackMaps) {
200     size_t stack_map_index = stack_maps_.size() - 1;
201     dchecks_.emplace_back([=](const CodeInfo& code_info) {
202       StackMap stack_map = code_info.GetStackMapAt(stack_map_index);
203       CHECK_EQ(stack_map.HasDexRegisterMap(), (num_dex_registers != 0));
204       CHECK_EQ(stack_map.HasInlineInfo(), (inlining_depth != 0));
205       CHECK_EQ(code_info.GetInlineInfosOf(stack_map).size(), inlining_depth);
206     });
207   }
208 }
209 
BeginInlineInfoEntry(ArtMethod * method,uint32_t dex_pc,uint32_t num_dex_registers,const DexFile * outer_dex_file,const CodeGenerator * codegen)210 void StackMapStream::BeginInlineInfoEntry(ArtMethod* method,
211                                           uint32_t dex_pc,
212                                           uint32_t num_dex_registers,
213                                           const DexFile* outer_dex_file,
214                                           const CodeGenerator* codegen) {
215   DCHECK(in_stack_map_) << "Call BeginStackMapEntry first";
216   DCHECK(!in_inline_info_) << "Mismatched Begin/End calls";
217   in_inline_info_ = true;
218   DCHECK_EQ(expected_num_dex_registers_, current_dex_registers_.size());
219 
220   expected_num_dex_registers_ += num_dex_registers;
221 
222   BitTableBuilder<InlineInfo>::Entry entry;
223   entry[InlineInfo::kIsLast] = InlineInfo::kMore;
224   entry[InlineInfo::kDexPc] = dex_pc;
225   entry[InlineInfo::kNumberOfDexRegisters] = static_cast<uint32_t>(expected_num_dex_registers_);
226   if (EncodeArtMethodInInlineInfo(method)) {
227     entry[InlineInfo::kArtMethodHi] = High32Bits(reinterpret_cast<uintptr_t>(method));
228     entry[InlineInfo::kArtMethodLo] = Low32Bits(reinterpret_cast<uintptr_t>(method));
229   } else {
230     uint32_t is_in_bootclasspath = MethodInfo::kKindNonBCP;
231     uint32_t dexfile_index = MethodInfo::kSameDexFile;
232     if (dex_pc != static_cast<uint32_t>(-1)) {
233       ScopedObjectAccess soa(Thread::Current());
234       const DexFile* dex_file = method->GetDexFile();
235       if (!IsSameDexFile(*outer_dex_file, *dex_file)) {
236         if (method->GetDeclaringClass()->IsBootStrapClassLoaded()) {
237           ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
238           const std::vector<const DexFile*>& boot_class_path = class_linker->GetBootClassPath();
239           auto it = std::find_if(
240               boot_class_path.begin(), boot_class_path.end(), [dex_file](const DexFile* df) {
241                 return IsSameDexFile(*df, *dex_file);
242               });
243           is_in_bootclasspath = MethodInfo::kKindBCP;
244           dexfile_index = std::distance(boot_class_path.begin(), it);
245         } else {
246           const std::vector<const DexFile*>& dex_files =
247               codegen->GetCompilerOptions().GetDexFilesForOatFile();
248           auto it = std::find_if(dex_files.begin(), dex_files.end(), [dex_file](const DexFile* df) {
249             return IsSameDexFile(*df, *dex_file);
250           });
251           // No need to set is_in_bootclasspath since the default value works.
252           dexfile_index = std::distance(dex_files.begin(), it);
253         }
254       }
255     }
256     uint32_t dex_method_index = method->GetDexMethodIndex();
257     entry[InlineInfo::kMethodInfoIndex] =
258         method_infos_.Dedup({dex_method_index, is_in_bootclasspath, dexfile_index});
259   }
260   current_inline_infos_.push_back(entry);
261 
262   if (kVerifyStackMaps) {
263     size_t stack_map_index = stack_maps_.size();
264     size_t depth = current_inline_infos_.size() - 1;
265     dchecks_.emplace_back([=](const CodeInfo& code_info) {
266       StackMap stack_map = code_info.GetStackMapAt(stack_map_index);
267       InlineInfo inline_info = code_info.GetInlineInfosOf(stack_map)[depth];
268       CHECK_EQ(inline_info.GetDexPc(), dex_pc);
269       bool encode_art_method = EncodeArtMethodInInlineInfo(method);
270       CHECK_EQ(inline_info.EncodesArtMethod(), encode_art_method);
271       if (encode_art_method) {
272         CHECK_EQ(inline_info.GetArtMethod(), method);
273       } else {
274         MethodInfo method_info = code_info.GetMethodInfoOf(inline_info);
275         CHECK_EQ(method_info.GetMethodIndex(), method->GetDexMethodIndex());
276         CHECK(method_info.GetDexFileIndexKind() == MethodInfo::kKindNonBCP ||
277               method_info.GetDexFileIndexKind() == MethodInfo::kKindBCP);
278         ScopedObjectAccess soa(Thread::Current());
279         if (inline_info.GetDexPc() != static_cast<uint32_t>(-1) &&
280             !IsSameDexFile(*outer_dex_file, *method->GetDexFile())) {
281           if (method->GetDeclaringClass()->IsBootStrapClassLoaded()) {
282             CHECK_EQ(method_info.GetDexFileIndexKind(), MethodInfo::kKindBCP);
283             ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
284             const std::vector<const DexFile*>& boot_class_path = class_linker->GetBootClassPath();
285             DCHECK_LT(method_info.GetDexFileIndex(), boot_class_path.size());
286             CHECK(IsSameDexFile(*boot_class_path[method_info.GetDexFileIndex()],
287                                 *method->GetDexFile()));
288           } else {
289             CHECK_EQ(method_info.GetDexFileIndexKind(), MethodInfo::kKindNonBCP);
290             const std::vector<const DexFile*>& dex_files =
291                 codegen->GetCompilerOptions().GetDexFilesForOatFile();
292             DCHECK_LT(method_info.GetDexFileIndex(), dex_files.size());
293             CHECK(IsSameDexFile(*dex_files[method_info.GetDexFileIndex()], *method->GetDexFile()));
294           }
295         }
296       }
297     });
298   }
299 }
300 
EndInlineInfoEntry()301 void StackMapStream::EndInlineInfoEntry() {
302   DCHECK(in_inline_info_) << "Mismatched Begin/End calls";
303   in_inline_info_ = false;
304   DCHECK_EQ(expected_num_dex_registers_, current_dex_registers_.size());
305 }
306 
307 // Create delta-compressed dex register map based on the current list of DexRegisterLocations.
308 // All dex registers for a stack map are concatenated - inlined registers are just appended.
CreateDexRegisterMap()309 void StackMapStream::CreateDexRegisterMap() {
310   // These are fields rather than local variables so that we can reuse the reserved memory.
311   temp_dex_register_mask_.ClearAllBits();
312   temp_dex_register_map_.clear();
313 
314   // Ensure that the arrays that hold previous state are big enough to be safely indexed below.
315   if (previous_dex_registers_.size() < current_dex_registers_.size()) {
316     previous_dex_registers_.resize(current_dex_registers_.size(), DexRegisterLocation::None());
317     dex_register_timestamp_.resize(current_dex_registers_.size(), 0u);
318   }
319 
320   // Set bit in the mask for each register that has been changed since the previous stack map.
321   // Modified registers are stored in the catalogue and the catalogue index added to the list.
322   for (size_t i = 0; i < current_dex_registers_.size(); i++) {
323     DexRegisterLocation reg = current_dex_registers_[i];
324     // Distance is difference between this index and the index of last modification.
325     uint32_t distance = stack_maps_.size() - dex_register_timestamp_[i];
326     if (previous_dex_registers_[i] != reg || distance > kMaxDexRegisterMapSearchDistance) {
327       BitTableBuilder<DexRegisterInfo>::Entry entry;
328       entry[DexRegisterInfo::kKind] = static_cast<uint32_t>(reg.GetKind());
329       entry[DexRegisterInfo::kPackedValue] =
330           DexRegisterInfo::PackValue(reg.GetKind(), reg.GetValue());
331       uint32_t index = reg.IsLive() ? dex_register_catalog_.Dedup(&entry) : kNoValue;
332       temp_dex_register_mask_.SetBit(i);
333       temp_dex_register_map_.push_back({index});
334       previous_dex_registers_[i] = reg;
335       dex_register_timestamp_[i] = stack_maps_.size();
336     }
337   }
338 
339   // Set the mask and map for the current StackMap (which includes inlined registers).
340   if (temp_dex_register_mask_.GetNumberOfBits() != 0) {
341     current_stack_map_[StackMap::kDexRegisterMaskIndex] =
342         dex_register_masks_.Dedup(temp_dex_register_mask_.GetRawStorage(),
343                                   temp_dex_register_mask_.GetNumberOfBits());
344   }
345   if (!current_dex_registers_.empty()) {
346     current_stack_map_[StackMap::kDexRegisterMapIndex] =
347         dex_register_maps_.Dedup(temp_dex_register_map_.data(),
348                                  temp_dex_register_map_.size());
349   }
350 
351   if (kVerifyStackMaps) {
352     size_t stack_map_index = stack_maps_.size();
353     // We need to make copy of the current registers for later (when the check is run).
354     auto expected_dex_registers = std::make_shared<dchecked_vector<DexRegisterLocation>>(
355         current_dex_registers_.begin(), current_dex_registers_.end());
356     dchecks_.emplace_back([=](const CodeInfo& code_info) {
357       StackMap stack_map = code_info.GetStackMapAt(stack_map_index);
358       uint32_t expected_reg = 0;
359       for (DexRegisterLocation reg : code_info.GetDexRegisterMapOf(stack_map)) {
360         CHECK_EQ((*expected_dex_registers)[expected_reg++], reg);
361       }
362       for (InlineInfo inline_info : code_info.GetInlineInfosOf(stack_map)) {
363         DexRegisterMap map = code_info.GetInlineDexRegisterMapOf(stack_map, inline_info);
364         for (DexRegisterLocation reg : map) {
365           CHECK_EQ((*expected_dex_registers)[expected_reg++], reg);
366         }
367       }
368       CHECK_EQ(expected_reg, expected_dex_registers->size());
369     });
370   }
371 }
372 
Encode()373 ScopedArenaVector<uint8_t> StackMapStream::Encode() {
374   DCHECK(in_stack_map_ == false) << "Mismatched Begin/End calls";
375   DCHECK(in_inline_info_ == false) << "Mismatched Begin/End calls";
376 
377   uint32_t flags = (inline_infos_.size() > 0) ? CodeInfo::kHasInlineInfo : 0;
378   flags |= baseline_ ? CodeInfo::kIsBaseline : 0;
379   flags |= debuggable_ ? CodeInfo::kIsDebuggable : 0;
380   DCHECK_LE(flags, kVarintMax);  // Ensure flags can be read directly as byte.
381   uint32_t bit_table_flags = 0;
382   ForEachBitTable([&bit_table_flags](size_t i, auto bit_table) {
383     if (bit_table->size() != 0) {  // Record which bit-tables are stored.
384       bit_table_flags |= 1 << i;
385     }
386   });
387 
388   ScopedArenaVector<uint8_t> buffer(allocator_->Adapter(kArenaAllocStackMapStream));
389   BitMemoryWriter<ScopedArenaVector<uint8_t>> out(&buffer);
390   out.WriteInterleavedVarints(std::array<uint32_t, CodeInfo::kNumHeaders>{
391     flags,
392     code_size_,
393     packed_frame_size_,
394     core_spill_mask_,
395     fp_spill_mask_,
396     num_dex_registers_,
397     bit_table_flags,
398   });
399   ForEachBitTable([&out](size_t, auto bit_table) {
400     if (bit_table->size() != 0) {  // Skip empty bit-tables.
401       bit_table->Encode(out);
402     }
403   });
404 
405   // Verify that we can load the CodeInfo and check some essentials.
406   size_t number_of_read_bits;
407   CodeInfo code_info(buffer.data(), &number_of_read_bits);
408   CHECK_EQ(number_of_read_bits, out.NumberOfWrittenBits());
409   CHECK_EQ(code_info.GetNumberOfStackMaps(), stack_maps_.size());
410   CHECK_EQ(CodeInfo::HasInlineInfo(buffer.data()), inline_infos_.size() > 0);
411   CHECK_EQ(CodeInfo::IsBaseline(buffer.data()), baseline_);
412 
413   // Verify all written data (usually only in debug builds).
414   if (kVerifyStackMaps) {
415     for (const auto& dcheck : dchecks_) {
416       dcheck(code_info);
417     }
418   }
419 
420   return buffer;
421 }
422 
423 }  // namespace art
424