• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 using RuntimeOptions = std::vector<std::pair<std::string, const void*>>;
70 class Thread;
71 class VariableSizedHandleScope;
72 
73 class CommonRuntimeTestImpl : public CommonArtTestImpl {
74  public:
75   CommonRuntimeTestImpl();
76   virtual ~CommonRuntimeTestImpl();
77 
78   // A helper function to fill the heap.
79   static void FillHeap(Thread* self,
80                        ClassLinker* class_linker,
81                        VariableSizedHandleScope* handle_scope)
82       REQUIRES_SHARED(Locks::mutator_lock_);
83   // A helper to set up a small heap (4M) to make FillHeap faster.
84   static void SetUpRuntimeOptionsForFillHeap(RuntimeOptions *options);
85 
86   template <typename Mutator>
MutateDexFile(File * output_dex,const std::string & input_jar,const Mutator & mutator)87   bool MutateDexFile(File* output_dex, const std::string& input_jar, const Mutator& mutator) {
88     std::vector<std::unique_ptr<const DexFile>> dex_files;
89     std::string error_msg;
90     const ArtDexFileLoader dex_file_loader;
91     CHECK(dex_file_loader.Open(input_jar.c_str(),
92                                input_jar.c_str(),
93                                /*verify=*/ true,
94                                /*verify_checksum=*/ true,
95                                &error_msg,
96                                &dex_files)) << 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 ATTRIBUTE_UNUSED)139   virtual void SetUpRuntimeOptions(RuntimeOptions* options ATTRIBUTE_UNUSED) {}
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   jobject LoadDexInPathClassLoader(const std::string& dex_name,
156                                    jobject parent_loader,
157                                    jobject shared_libraries = nullptr,
158                                    jobject shared_libraries_after = nullptr);
159   jobject LoadDexInPathClassLoader(const std::vector<std::string>& dex_names,
160                                    jobject parent_loader,
161                                    jobject shared_libraries = nullptr,
162                                    jobject shared_libraries_after = 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                                         jobject shared_libraries_after = nullptr);
170 
171   void VisitDexes(ArrayRef<const std::string> dexes,
172                   const std::function<void(MethodReference)>& method_visitor,
173                   const std::function<void(TypeReference)>& class_visitor,
174                   size_t method_frequency = 1u,
175                   size_t class_frequency = 1u);
176 
177   void GenerateProfile(ArrayRef<const std::string> dexes,
178                        File* out_file,
179                        size_t method_frequency = 1u,
180                        size_t type_frequency = 1u,
181                        bool for_boot_image = false);
182   void GenerateBootProfile(ArrayRef<const std::string> dexes,
183                            File* out_file,
184                            size_t method_frequency = 1u,
185                            size_t type_frequency = 1u) {
186     return GenerateProfile(
187         dexes, out_file, method_frequency, type_frequency, /*for_boot_image=*/ true);
188   }
189 
190   std::unique_ptr<Runtime> runtime_;
191 
192   // The class_linker_, java_lang_dex_file_, and boot_class_path_ are all
193   // owned by the runtime.
194   ClassLinker* class_linker_;
195   const DexFile* java_lang_dex_file_;
196   std::vector<const DexFile*> boot_class_path_;
197 
198   // Get the dex files from a PathClassLoader or DelegateLastClassLoader.
199   // This only looks into the current class loader and does not recurse into the parents.
200   std::vector<const DexFile*> GetDexFiles(jobject jclass_loader);
201   std::vector<const DexFile*> GetDexFiles(ScopedObjectAccess& soa,
202                                           Handle<mirror::ClassLoader> class_loader)
203     REQUIRES_SHARED(Locks::mutator_lock_);
204 
205   // Get the first dex file from a PathClassLoader. Will abort if it is null.
206   const DexFile* GetFirstDexFile(jobject jclass_loader);
207 
208   std::unique_ptr<CompilerCallbacks> callbacks_;
209 
210   bool use_boot_image_;
211 
212   virtual void SetUp();
213 
214   virtual void TearDown();
215 
216   // Called to finish up runtime creation and filling test fields. By default runs root
217   // initializers, initialize well-known classes, and creates the heap thread pool.
218   virtual void FinalizeSetup();
219 
220   // Returns the directory where the pre-compiled boot.art can be found.
221   static std::string GetImageLocation();
222   static std::string GetSystemImageFile();
223 
224   static void EnterTransactionMode();
225   static void ExitTransactionMode();
226   static void RollbackAndExitTransactionMode() REQUIRES_SHARED(Locks::mutator_lock_);
227   static bool IsTransactionAborted();
228 };
229 
230 template <typename TestType>
231 class CommonRuntimeTestBase : public TestType, public CommonRuntimeTestImpl {
232  public:
CommonRuntimeTestBase()233   CommonRuntimeTestBase() {}
~CommonRuntimeTestBase()234   virtual ~CommonRuntimeTestBase() {}
235 
236  protected:
SetUp()237   void SetUp() override {
238     CommonRuntimeTestImpl::SetUp();
239   }
240 
TearDown()241   void TearDown() override {
242     CommonRuntimeTestImpl::TearDown();
243   }
244 };
245 
246 using CommonRuntimeTest = CommonRuntimeTestBase<testing::Test>;
247 
248 template <typename Param>
249 using CommonRuntimeTestWithParam = CommonRuntimeTestBase<testing::TestWithParam<Param>>;
250 
251 // Sets a CheckJni abort hook to catch failures. Note that this will cause CheckJNI to carry on
252 // rather than aborting, so be careful!
253 class CheckJniAbortCatcher {
254  public:
255   CheckJniAbortCatcher();
256 
257   ~CheckJniAbortCatcher();
258 
259   void Check(const std::string& expected_text);
260   void Check(const char* expected_text);
261 
262  private:
263   static void Hook(void* data, const std::string& reason);
264 
265   JavaVMExt* const vm_;
266   std::string actual_;
267 
268   DISALLOW_COPY_AND_ASSIGN(CheckJniAbortCatcher);
269 };
270 
271 #define TEST_DISABLED() \
272   do { \
273     printf("WARNING: TEST DISABLED\n"); \
274     return; \
275   } while (false)
276 
277 #define TEST_DISABLED_FOR_ARM() \
278   if (kRuntimeISA == InstructionSet::kArm || kRuntimeISA == InstructionSet::kThumb2) { \
279     printf("WARNING: TEST DISABLED FOR ARM\n"); \
280     return; \
281   }
282 
283 #define TEST_DISABLED_FOR_ARM64() \
284   if (kRuntimeISA == InstructionSet::kArm64) { \
285     printf("WARNING: TEST DISABLED FOR ARM64\n"); \
286     return; \
287   }
288 
289 #define TEST_DISABLED_FOR_X86() \
290   if (kRuntimeISA == InstructionSet::kX86) { \
291     printf("WARNING: TEST DISABLED FOR X86\n"); \
292     return; \
293   }
294 
295 #define TEST_DISABLED_FOR_X86_64() \
296   if (kRuntimeISA == InstructionSet::kX86_64) { \
297     printf("WARNING: TEST DISABLED FOR X86_64\n"); \
298     return; \
299   }
300 
301 #define TEST_DISABLED_FOR_STRING_COMPRESSION() \
302   if (mirror::kUseStringCompression) { \
303     printf("WARNING: TEST DISABLED FOR STRING COMPRESSION\n"); \
304     return; \
305   }
306 
307 #define TEST_DISABLED_WITHOUT_BAKER_READ_BARRIERS() \
308   if (!kEmitCompilerReadBarrier || !kUseBakerReadBarrier) { \
309     printf("WARNING: TEST DISABLED FOR GC WITHOUT BAKER READ BARRIER\n"); \
310     return; \
311   }
312 
313 #define TEST_DISABLED_FOR_HEAP_POISONING() \
314   if (kPoisonHeapReferences) { \
315     printf("WARNING: TEST DISABLED FOR HEAP POISONING\n"); \
316     return; \
317   }
318 
319 #define TEST_DISABLED_FOR_MEMORY_TOOL_WITH_HEAP_POISONING_WITHOUT_READ_BARRIERS() \
320   if (kRunningOnMemoryTool && kPoisonHeapReferences && !kEmitCompilerReadBarrier) { \
321     printf("WARNING: TEST DISABLED FOR MEMORY TOOL WITH HEAP POISONING WITHOUT READ BARRIERS\n"); \
322     return; \
323   }
324 
325 #define TEST_DISABLED_FOR_KERNELS_WITH_CACHE_SEGFAULT() \
326   if (CacheOperationsMaySegFault()) { \
327     printf("WARNING: TEST DISABLED ON KERNEL THAT SEGFAULT ON CACHE OPERATIONS\n"); \
328     return; \
329   }
330 
331 }  // namespace art
332 
333 #endif  // ART_RUNTIME_COMMON_RUNTIME_TEST_H_
334