1 /*
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  */
16 
17 #include "common_compiler_test.h"
18 
19 #include <type_traits>
20 
21 #include "arch/instruction_set_features.h"
22 #include "art_field-inl.h"
23 #include "art_method-inl.h"
24 #include "base/callee_save_type.h"
25 #include "base/casts.h"
26 #include "base/enums.h"
27 #include "base/utils.h"
28 #include "class_linker.h"
29 #include "compiled_method-inl.h"
30 #include "dex/descriptors_names.h"
31 #include "dex/verification_results.h"
32 #include "driver/compiled_method_storage.h"
33 #include "driver/compiler_options.h"
34 #include "jni/java_vm_ext.h"
35 #include "interpreter/interpreter.h"
36 #include "mirror/class-inl.h"
37 #include "mirror/class_loader.h"
38 #include "mirror/dex_cache.h"
39 #include "mirror/object-inl.h"
40 #include "oat_quick_method_header.h"
41 #include "scoped_thread_state_change-inl.h"
42 #include "thread-current-inl.h"
43 #include "utils/atomic_dex_ref_map-inl.h"
44 
45 namespace art {
46 
CommonCompilerTest()47 CommonCompilerTest::CommonCompilerTest() {}
~CommonCompilerTest()48 CommonCompilerTest::~CommonCompilerTest() {}
49 
MakeExecutable(ArtMethod * method,const CompiledMethod * compiled_method)50 void CommonCompilerTest::MakeExecutable(ArtMethod* method, const CompiledMethod* compiled_method) {
51   CHECK(method != nullptr);
52   // If the code size is 0 it means the method was skipped due to profile guided compilation.
53   if (compiled_method != nullptr && compiled_method->GetQuickCode().size() != 0u) {
54     ArrayRef<const uint8_t> code = compiled_method->GetQuickCode();
55     const uint32_t code_size = code.size();
56     ArrayRef<const uint8_t> vmap_table = compiled_method->GetVmapTable();
57     const uint32_t vmap_table_offset = vmap_table.empty() ? 0u
58         : sizeof(OatQuickMethodHeader) + vmap_table.size();
59     OatQuickMethodHeader method_header(vmap_table_offset, code_size);
60 
61     header_code_and_maps_chunks_.push_back(std::vector<uint8_t>());
62     std::vector<uint8_t>* chunk = &header_code_and_maps_chunks_.back();
63     const size_t max_padding = GetInstructionSetAlignment(compiled_method->GetInstructionSet());
64     const size_t size = vmap_table.size() + sizeof(method_header) + code_size;
65     chunk->reserve(size + max_padding);
66     chunk->resize(sizeof(method_header));
67     static_assert(std::is_trivially_copyable<OatQuickMethodHeader>::value, "Cannot use memcpy");
68     memcpy(&(*chunk)[0], &method_header, sizeof(method_header));
69     chunk->insert(chunk->begin(), vmap_table.begin(), vmap_table.end());
70     chunk->insert(chunk->end(), code.begin(), code.end());
71     CHECK_EQ(chunk->size(), size);
72     const void* unaligned_code_ptr = chunk->data() + (size - code_size);
73     size_t offset = dchecked_integral_cast<size_t>(reinterpret_cast<uintptr_t>(unaligned_code_ptr));
74     size_t padding = compiled_method->AlignCode(offset) - offset;
75     // Make sure no resizing takes place.
76     CHECK_GE(chunk->capacity(), chunk->size() + padding);
77     chunk->insert(chunk->begin(), padding, 0);
78     const void* code_ptr = reinterpret_cast<const uint8_t*>(unaligned_code_ptr) + padding;
79     CHECK_EQ(code_ptr, static_cast<const void*>(chunk->data() + (chunk->size() - code_size)));
80     MakeExecutable(code_ptr, code.size());
81     const void* method_code = CompiledMethod::CodePointer(code_ptr,
82                                                           compiled_method->GetInstructionSet());
83     LOG(INFO) << "MakeExecutable " << method->PrettyMethod() << " code=" << method_code;
84     method->SetEntryPointFromQuickCompiledCode(method_code);
85   } else {
86     // No code? You must mean to go into the interpreter.
87     // Or the generic JNI...
88     class_linker_->SetEntryPointsToInterpreter(method);
89   }
90 }
91 
MakeExecutable(const void * code_start,size_t code_length)92 void CommonCompilerTest::MakeExecutable(const void* code_start, size_t code_length) {
93   CHECK(code_start != nullptr);
94   CHECK_NE(code_length, 0U);
95   uintptr_t data = reinterpret_cast<uintptr_t>(code_start);
96   uintptr_t base = RoundDown(data, kPageSize);
97   uintptr_t limit = RoundUp(data + code_length, kPageSize);
98   uintptr_t len = limit - base;
99   // Remove hwasan tag.  This is done in kernel in newer versions.  This supports older kernels.
100   void* base_ptr = HWASanUntag(reinterpret_cast<void*>(base));
101   int result = mprotect(base_ptr, len, PROT_READ | PROT_WRITE | PROT_EXEC);
102   CHECK_EQ(result, 0);
103 
104   CHECK(FlushCpuCaches(reinterpret_cast<void*>(base), reinterpret_cast<void*>(base + len)));
105 }
106 
SetUp()107 void CommonCompilerTest::SetUp() {
108   CommonRuntimeTest::SetUp();
109   {
110     ScopedObjectAccess soa(Thread::Current());
111 
112     runtime_->SetInstructionSet(instruction_set_);
113     for (uint32_t i = 0; i < static_cast<uint32_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
114       CalleeSaveType type = CalleeSaveType(i);
115       if (!runtime_->HasCalleeSaveMethod(type)) {
116         runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
117       }
118     }
119   }
120 }
121 
ApplyInstructionSet()122 void CommonCompilerTest::ApplyInstructionSet() {
123   // Copy local instruction_set_ and instruction_set_features_ to *compiler_options_;
124   CHECK(instruction_set_features_ != nullptr);
125   if (instruction_set_ == InstructionSet::kThumb2) {
126     CHECK_EQ(InstructionSet::kArm, instruction_set_features_->GetInstructionSet());
127   } else {
128     CHECK_EQ(instruction_set_, instruction_set_features_->GetInstructionSet());
129   }
130   compiler_options_->instruction_set_ = instruction_set_;
131   compiler_options_->instruction_set_features_ =
132       InstructionSetFeatures::FromBitmap(instruction_set_, instruction_set_features_->AsBitmap());
133   CHECK(compiler_options_->instruction_set_features_->Equals(instruction_set_features_.get()));
134 }
135 
OverrideInstructionSetFeatures(InstructionSet instruction_set,const std::string & variant)136 void CommonCompilerTest::OverrideInstructionSetFeatures(InstructionSet instruction_set,
137                                                         const std::string& variant) {
138   instruction_set_ = instruction_set;
139   std::string error_msg;
140   instruction_set_features_ =
141       InstructionSetFeatures::FromVariant(instruction_set, variant, &error_msg);
142   CHECK(instruction_set_features_ != nullptr) << error_msg;
143 
144   if (compiler_options_ != nullptr) {
145     ApplyInstructionSet();
146   }
147 }
148 
SetUpRuntimeOptions(RuntimeOptions * options)149 void CommonCompilerTest::SetUpRuntimeOptions(RuntimeOptions* options) {
150   CommonRuntimeTest::SetUpRuntimeOptions(options);
151 
152   compiler_options_.reset(new CompilerOptions);
153   verification_results_.reset(new VerificationResults(compiler_options_.get()));
154 
155   ApplyInstructionSet();
156 }
157 
GetCompilerKind() const158 Compiler::Kind CommonCompilerTest::GetCompilerKind() const {
159   return compiler_kind_;
160 }
161 
SetCompilerKind(Compiler::Kind compiler_kind)162 void CommonCompilerTest::SetCompilerKind(Compiler::Kind compiler_kind) {
163   compiler_kind_ = compiler_kind;
164 }
165 
TearDown()166 void CommonCompilerTest::TearDown() {
167   verification_results_.reset();
168   compiler_options_.reset();
169 
170   CommonRuntimeTest::TearDown();
171 }
172 
CompileMethod(ArtMethod * method)173 void CommonCompilerTest::CompileMethod(ArtMethod* method) {
174   CHECK(method != nullptr);
175   TimingLogger timings("CommonCompilerTest::CompileMethod", false, false);
176   TimingLogger::ScopedTiming t(__FUNCTION__, &timings);
177   CompiledMethodStorage storage(/*swap_fd=*/ -1);
178   CompiledMethod* compiled_method = nullptr;
179   {
180     DCHECK(!Runtime::Current()->IsStarted());
181     Thread* self = Thread::Current();
182     StackHandleScope<2> hs(self);
183     std::unique_ptr<Compiler> compiler(
184         Compiler::Create(*compiler_options_, &storage, compiler_kind_));
185     const DexFile& dex_file = *method->GetDexFile();
186     Handle<mirror::DexCache> dex_cache = hs.NewHandle(class_linker_->FindDexCache(self, dex_file));
187     Handle<mirror::ClassLoader> class_loader = hs.NewHandle(method->GetClassLoader());
188     compiler_options_->verification_results_ = verification_results_.get();
189     if (method->IsNative()) {
190       compiled_method = compiler->JniCompile(method->GetAccessFlags(),
191                                              method->GetDexMethodIndex(),
192                                              dex_file,
193                                              dex_cache);
194     } else {
195       verification_results_->AddDexFile(&dex_file);
196       verification_results_->CreateVerifiedMethodFor(
197           MethodReference(&dex_file, method->GetDexMethodIndex()));
198       compiled_method = compiler->Compile(method->GetCodeItem(),
199                                           method->GetAccessFlags(),
200                                           method->GetInvokeType(),
201                                           method->GetClassDefIndex(),
202                                           method->GetDexMethodIndex(),
203                                           class_loader,
204                                           dex_file,
205                                           dex_cache);
206     }
207     compiler_options_->verification_results_ = nullptr;
208   }
209   CHECK(method != nullptr);
210   {
211     TimingLogger::ScopedTiming t2("MakeExecutable", &timings);
212     MakeExecutable(method, compiled_method);
213   }
214   CompiledMethod::ReleaseSwapAllocatedCompiledMethod(&storage, compiled_method);
215 }
216 
CompileDirectMethod(Handle<mirror::ClassLoader> class_loader,const char * class_name,const char * method_name,const char * signature)217 void CommonCompilerTest::CompileDirectMethod(Handle<mirror::ClassLoader> class_loader,
218                                              const char* class_name, const char* method_name,
219                                              const char* signature) {
220   std::string class_descriptor(DotToDescriptor(class_name));
221   Thread* self = Thread::Current();
222   ObjPtr<mirror::Class> klass =
223       class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
224   CHECK(klass != nullptr) << "Class not found " << class_name;
225   auto pointer_size = class_linker_->GetImagePointerSize();
226   ArtMethod* method = klass->FindClassMethod(method_name, signature, pointer_size);
227   CHECK(method != nullptr && method->IsDirect()) << "Direct method not found: "
228       << class_name << "." << method_name << signature;
229   CompileMethod(method);
230 }
231 
CompileVirtualMethod(Handle<mirror::ClassLoader> class_loader,const char * class_name,const char * method_name,const char * signature)232 void CommonCompilerTest::CompileVirtualMethod(Handle<mirror::ClassLoader> class_loader,
233                                               const char* class_name, const char* method_name,
234                                               const char* signature) {
235   std::string class_descriptor(DotToDescriptor(class_name));
236   Thread* self = Thread::Current();
237   ObjPtr<mirror::Class> klass =
238       class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
239   CHECK(klass != nullptr) << "Class not found " << class_name;
240   auto pointer_size = class_linker_->GetImagePointerSize();
241   ArtMethod* method = klass->FindClassMethod(method_name, signature, pointer_size);
242   CHECK(method != nullptr && !method->IsDirect()) << "Virtual method not found: "
243       << class_name << "." << method_name << signature;
244   CompileMethod(method);
245 }
246 
ClearBootImageOption()247 void CommonCompilerTest::ClearBootImageOption() {
248   compiler_options_->image_type_ = CompilerOptions::ImageType::kNone;
249 }
250 
251 }  // namespace art
252