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