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