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 #ifndef ART_RUNTIME_COMMON_RUNTIME_TEST_H_
18 #define ART_RUNTIME_COMMON_RUNTIME_TEST_H_
19
20 #include <gtest/gtest.h>
21 #include <jni.h>
22
23 #include <functional>
24 #include <string>
25
26 #include <android-base/logging.h>
27
28 #include "arch/instruction_set.h"
29 #include "base/common_art_test.h"
30 #include "base/locks.h"
31 #include "base/os.h"
32 #include "base/unix_file/fd_file.h"
33 #include "dex/art_dex_file_loader.h"
34 #include "dex/compact_dex_level.h"
35 // TODO: Add inl file and avoid including inl.
36 #include "obj_ptr-inl.h"
37 #include "runtime_globals.h"
38 #include "scoped_thread_state_change-inl.h"
39
40 namespace art {
41
42 class MethodReference;
43 class TypeReference;
44
45 using LogSeverity = android::base::LogSeverity;
46 using ScopedLogSeverity = android::base::ScopedLogSeverity;
47
48 template<class MirrorType>
MakeObjPtr(MirrorType * ptr)49 static inline ObjPtr<MirrorType> MakeObjPtr(MirrorType* ptr) {
50 return ptr;
51 }
52
53 template<class MirrorType>
MakeObjPtr(ObjPtr<MirrorType> ptr)54 static inline ObjPtr<MirrorType> MakeObjPtr(ObjPtr<MirrorType> ptr) {
55 return ptr;
56 }
57
58 // OBJ pointer helpers to avoid needing .Decode everywhere.
59 #define EXPECT_OBJ_PTR_EQ(a, b) EXPECT_EQ(MakeObjPtr(a).Ptr(), MakeObjPtr(b).Ptr())
60 #define ASSERT_OBJ_PTR_EQ(a, b) ASSERT_EQ(MakeObjPtr(a).Ptr(), MakeObjPtr(b).Ptr())
61 #define EXPECT_OBJ_PTR_NE(a, b) EXPECT_NE(MakeObjPtr(a).Ptr(), MakeObjPtr(b).Ptr())
62 #define ASSERT_OBJ_PTR_NE(a, b) ASSERT_NE(MakeObjPtr(a).Ptr(), MakeObjPtr(b).Ptr())
63
64 class ClassLinker;
65 class CompilerCallbacks;
66 class DexFile;
67 class JavaVMExt;
68 class Runtime;
69 typedef std::vector<std::pair<std::string, const void*>> RuntimeOptions;
70 class Thread;
71 class VariableSizedHandleScope;
72
73 class CommonRuntimeTestImpl : public CommonArtTestImpl {
74 public:
75 CommonRuntimeTestImpl();
76 virtual ~CommonRuntimeTestImpl();
77
78 static std::string GetAndroidTargetToolsDir(InstructionSet isa);
79
80 // A helper function to fill the heap.
81 static void FillHeap(Thread* self,
82 ClassLinker* class_linker,
83 VariableSizedHandleScope* handle_scope)
84 REQUIRES_SHARED(Locks::mutator_lock_);
85 // A helper to set up a small heap (4M) to make FillHeap faster.
86 static void SetUpRuntimeOptionsForFillHeap(RuntimeOptions *options);
87
88 template <typename Mutator>
MutateDexFile(File * output_dex,const std::string & input_jar,const Mutator & mutator)89 bool MutateDexFile(File* output_dex, const std::string& input_jar, const Mutator& mutator) {
90 std::vector<std::unique_ptr<const DexFile>> dex_files;
91 std::string error_msg;
92 const ArtDexFileLoader dex_file_loader;
93 CHECK(dex_file_loader.Open(input_jar.c_str(),
94 input_jar.c_str(),
95 /*verify=*/ true,
96 /*verify_checksum=*/ true,
97 &error_msg,
98 &dex_files)) << error_msg;
99 EXPECT_EQ(dex_files.size(), 1u) << "Only one input dex is supported";
100 const std::unique_ptr<const DexFile>& dex = dex_files[0];
101 CHECK(dex->EnableWrite()) << "Failed to enable write";
102 DexFile* dex_file = const_cast<DexFile*>(dex.get());
103 mutator(dex_file);
104 const_cast<DexFile::Header&>(dex_file->GetHeader()).checksum_ = dex_file->CalculateChecksum();
105 if (!output_dex->WriteFully(dex->Begin(), dex->Size())) {
106 return false;
107 }
108 if (output_dex->Flush() != 0) {
109 PLOG(FATAL) << "Could not flush the output file.";
110 }
111 return true;
112 }
113
114 void MakeInterpreted(ObjPtr<mirror::Class> klass)
115 REQUIRES_SHARED(Locks::mutator_lock_);
116
117 bool StartDex2OatCommandLine(/*out*/std::vector<std::string>* argv,
118 /*out*/std::string* error_msg,
119 bool use_runtime_bcp_and_image = true);
120
121 bool CompileBootImage(const std::vector<std::string>& extra_args,
122 const std::string& image_file_name_prefix,
123 ArrayRef<const std::string> dex_files,
124 ArrayRef<const std::string> dex_locations,
125 std::string* error_msg,
126 const std::string& use_fd_prefix = "");
127
128 bool CompileBootImage(const std::vector<std::string>& extra_args,
129 const std::string& image_file_name_prefix,
130 ArrayRef<const std::string> dex_files,
131 std::string* error_msg,
132 const std::string& use_fd_prefix = "") {
133 return CompileBootImage(
134 extra_args, image_file_name_prefix, dex_files, dex_files, error_msg, use_fd_prefix);
135 }
136
137 bool RunDex2Oat(const std::vector<std::string>& args, std::string* error_msg);
138
139 protected:
140 // Allow subclases such as CommonCompilerTest to add extra options.
SetUpRuntimeOptions(RuntimeOptions * options ATTRIBUTE_UNUSED)141 virtual void SetUpRuntimeOptions(RuntimeOptions* options ATTRIBUTE_UNUSED) {}
142
143 // Called before the runtime is created.
PreRuntimeCreate()144 virtual void PreRuntimeCreate() {}
145
146 // Called after the runtime is created.
PostRuntimeCreate()147 virtual void PostRuntimeCreate() {}
148
149 // Loads the test dex file identified by the given dex_name into a PathClassLoader.
150 // Returns the created class loader.
151 jobject LoadDex(const char* dex_name) REQUIRES_SHARED(Locks::mutator_lock_);
152 // Loads the test dex file identified by the given first_dex_name and second_dex_name
153 // into a PathClassLoader. Returns the created class loader.
154 jobject LoadMultiDex(const char* first_dex_name, const char* second_dex_name)
155 REQUIRES_SHARED(Locks::mutator_lock_);
156
157 jobject LoadDexInPathClassLoader(const std::string& dex_name,
158 jobject parent_loader,
159 jobject shared_libraries = nullptr);
160 jobject LoadDexInPathClassLoader(const std::vector<std::string>& dex_names,
161 jobject parent_loader,
162 jobject shared_libraries = nullptr);
163 jobject LoadDexInDelegateLastClassLoader(const std::string& dex_name, jobject parent_loader);
164 jobject LoadDexInInMemoryDexClassLoader(const std::string& dex_name, jobject parent_loader);
165 jobject LoadDexInWellKnownClassLoader(const std::vector<std::string>& dex_names,
166 jclass loader_class,
167 jobject parent_loader,
168 jobject shared_libraries = nullptr);
169
170 void VisitDexes(ArrayRef<const std::string> dexes,
171 const std::function<void(MethodReference)>& method_visitor,
172 const std::function<void(TypeReference)>& class_visitor,
173 size_t method_frequency = 1u,
174 size_t class_frequency = 1u);
175
176 void GenerateProfile(ArrayRef<const std::string> dexes,
177 File* out_file,
178 size_t method_frequency = 1u,
179 size_t type_frequency = 1u);
180
181 std::unique_ptr<Runtime> runtime_;
182
183 // The class_linker_, java_lang_dex_file_, and boot_class_path_ are all
184 // owned by the runtime.
185 ClassLinker* class_linker_;
186 const DexFile* java_lang_dex_file_;
187 std::vector<const DexFile*> boot_class_path_;
188
189 // Get the dex files from a PathClassLoader or DelegateLastClassLoader.
190 // This only looks into the current class loader and does not recurse into the parents.
191 std::vector<const DexFile*> GetDexFiles(jobject jclass_loader);
192 std::vector<const DexFile*> GetDexFiles(ScopedObjectAccess& soa,
193 Handle<mirror::ClassLoader> class_loader)
194 REQUIRES_SHARED(Locks::mutator_lock_);
195
196 // Get the first dex file from a PathClassLoader. Will abort if it is null.
197 const DexFile* GetFirstDexFile(jobject jclass_loader);
198
199 std::unique_ptr<CompilerCallbacks> callbacks_;
200
201 virtual void SetUp();
202
203 virtual void TearDown();
204
205 // Called to finish up runtime creation and filling test fields. By default runs root
206 // initializers, initialize well-known classes, and creates the heap thread pool.
207 virtual void FinalizeSetup();
208
209 // Returns the directory where the pre-compiled core.art can be found.
210 static std::string GetImageDirectory();
211 static std::string GetImageLocation();
212 static std::string GetSystemImageFile();
213
214 static void EnterTransactionMode();
215 static void ExitTransactionMode();
216 static void RollbackAndExitTransactionMode() REQUIRES_SHARED(Locks::mutator_lock_);
217 static bool IsTransactionAborted();
218 };
219
220 template <typename TestType>
221 class CommonRuntimeTestBase : public TestType, public CommonRuntimeTestImpl {
222 public:
CommonRuntimeTestBase()223 CommonRuntimeTestBase() {}
~CommonRuntimeTestBase()224 virtual ~CommonRuntimeTestBase() {}
225
226 protected:
SetUp()227 void SetUp() override {
228 CommonRuntimeTestImpl::SetUp();
229 }
230
TearDown()231 void TearDown() override {
232 CommonRuntimeTestImpl::TearDown();
233 }
234 };
235
236 using CommonRuntimeTest = CommonRuntimeTestBase<testing::Test>;
237
238 template <typename Param>
239 using CommonRuntimeTestWithParam = CommonRuntimeTestBase<testing::TestWithParam<Param>>;
240
241 // Sets a CheckJni abort hook to catch failures. Note that this will cause CheckJNI to carry on
242 // rather than aborting, so be careful!
243 class CheckJniAbortCatcher {
244 public:
245 CheckJniAbortCatcher();
246
247 ~CheckJniAbortCatcher();
248
249 void Check(const std::string& expected_text);
250 void Check(const char* expected_text);
251
252 private:
253 static void Hook(void* data, const std::string& reason);
254
255 JavaVMExt* const vm_;
256 std::string actual_;
257
258 DISALLOW_COPY_AND_ASSIGN(CheckJniAbortCatcher);
259 };
260
261 #define TEST_DISABLED() \
262 do { \
263 printf("WARNING: TEST DISABLED\n"); \
264 return; \
265 } while (false)
266
267 #define TEST_DISABLED_FOR_ARM() \
268 if (kRuntimeISA == InstructionSet::kArm || kRuntimeISA == InstructionSet::kThumb2) { \
269 printf("WARNING: TEST DISABLED FOR ARM\n"); \
270 return; \
271 }
272
273 #define TEST_DISABLED_FOR_ARM64() \
274 if (kRuntimeISA == InstructionSet::kArm64) { \
275 printf("WARNING: TEST DISABLED FOR ARM64\n"); \
276 return; \
277 }
278
279 #define TEST_DISABLED_FOR_X86() \
280 if (kRuntimeISA == InstructionSet::kX86) { \
281 printf("WARNING: TEST DISABLED FOR X86\n"); \
282 return; \
283 }
284
285 #define TEST_DISABLED_FOR_X86_64() \
286 if (kRuntimeISA == InstructionSet::kX86_64) { \
287 printf("WARNING: TEST DISABLED FOR X86_64\n"); \
288 return; \
289 }
290
291 #define TEST_DISABLED_FOR_STRING_COMPRESSION() \
292 if (mirror::kUseStringCompression) { \
293 printf("WARNING: TEST DISABLED FOR STRING COMPRESSION\n"); \
294 return; \
295 }
296
297 #define TEST_DISABLED_WITHOUT_BAKER_READ_BARRIERS() \
298 if (!kEmitCompilerReadBarrier || !kUseBakerReadBarrier) { \
299 printf("WARNING: TEST DISABLED FOR GC WITHOUT BAKER READ BARRIER\n"); \
300 return; \
301 }
302
303 #define TEST_DISABLED_FOR_HEAP_POISONING() \
304 if (kPoisonHeapReferences) { \
305 printf("WARNING: TEST DISABLED FOR HEAP POISONING\n"); \
306 return; \
307 }
308
309 #define TEST_DISABLED_FOR_MEMORY_TOOL_WITH_HEAP_POISONING_WITHOUT_READ_BARRIERS() \
310 if (kRunningOnMemoryTool && kPoisonHeapReferences && !kEmitCompilerReadBarrier) { \
311 printf("WARNING: TEST DISABLED FOR MEMORY TOOL WITH HEAP POISONING WITHOUT READ BARRIERS\n"); \
312 return; \
313 }
314
315 #define TEST_DISABLED_FOR_KERNELS_WITH_CACHE_SEGFAULT() \
316 if (CacheOperationsMaySegFault()) { \
317 printf("WARNING: TEST DISABLED ON KERNEL THAT SEGFAULT ON CACHE OPERATIONS\n"); \
318 return; \
319 }
320
321 } // namespace art
322
323 #endif // ART_RUNTIME_COMMON_RUNTIME_TEST_H_
324