Home | History | Annotate | Download | only in runtime
      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 <string>
     24 
     25 #include <android-base/logging.h>
     26 
     27 #include "arch/instruction_set.h"
     28 #include "base/mutex.h"
     29 #include "base/os.h"
     30 #include "base/unix_file/fd_file.h"
     31 #include "dex/art_dex_file_loader.h"
     32 #include "dex/compact_dex_level.h"
     33 #include "globals.h"
     34 // TODO: Add inl file and avoid including inl.
     35 #include "obj_ptr-inl.h"
     36 #include "scoped_thread_state_change-inl.h"
     37 
     38 namespace art {
     39 
     40 using LogSeverity = android::base::LogSeverity;
     41 using ScopedLogSeverity = android::base::ScopedLogSeverity;
     42 
     43 // OBJ pointer helpers to avoid needing .Decode everywhere.
     44 #define EXPECT_OBJ_PTR_EQ(a, b) EXPECT_EQ(MakeObjPtr(a).Ptr(), MakeObjPtr(b).Ptr());
     45 #define ASSERT_OBJ_PTR_EQ(a, b) ASSERT_EQ(MakeObjPtr(a).Ptr(), MakeObjPtr(b).Ptr());
     46 #define EXPECT_OBJ_PTR_NE(a, b) EXPECT_NE(MakeObjPtr(a).Ptr(), MakeObjPtr(b).Ptr());
     47 #define ASSERT_OBJ_PTR_NE(a, b) ASSERT_NE(MakeObjPtr(a).Ptr(), MakeObjPtr(b).Ptr());
     48 
     49 class ClassLinker;
     50 class CompilerCallbacks;
     51 class DexFile;
     52 class JavaVMExt;
     53 class Runtime;
     54 typedef std::vector<std::pair<std::string, const void*>> RuntimeOptions;
     55 class Thread;
     56 class VariableSizedHandleScope;
     57 
     58 class ScratchFile {
     59  public:
     60   ScratchFile();
     61 
     62   explicit ScratchFile(const std::string& filename);
     63 
     64   ScratchFile(const ScratchFile& other, const char* suffix);
     65 
     66   ScratchFile(ScratchFile&& other);
     67 
     68   ScratchFile& operator=(ScratchFile&& other);
     69 
     70   explicit ScratchFile(File* file);
     71 
     72   ~ScratchFile();
     73 
     74   const std::string& GetFilename() const {
     75     return filename_;
     76   }
     77 
     78   File* GetFile() const {
     79     return file_.get();
     80   }
     81 
     82   int GetFd() const;
     83 
     84   void Close();
     85   void Unlink();
     86 
     87  private:
     88   std::string filename_;
     89   std::unique_ptr<File> file_;
     90 };
     91 
     92 class CommonRuntimeTestImpl {
     93  public:
     94   CommonRuntimeTestImpl();
     95   virtual ~CommonRuntimeTestImpl();
     96   static void SetUpAndroidRoot();
     97 
     98   // Note: setting up ANDROID_DATA may create a temporary directory. If this is used in a
     99   // non-derived class, be sure to also call the corresponding tear-down below.
    100   static void SetUpAndroidData(std::string& android_data);
    101 
    102   static void TearDownAndroidData(const std::string& android_data, bool fail_on_error);
    103 
    104   // Gets the paths of the libcore dex files.
    105   static std::vector<std::string> GetLibCoreDexFileNames();
    106 
    107   // Returns bin directory which contains host's prebuild tools.
    108   static std::string GetAndroidHostToolsDir();
    109 
    110   // Returns bin directory which contains target's prebuild tools.
    111   static std::string GetAndroidTargetToolsDir(InstructionSet isa);
    112 
    113   // Retuerns the filename for a test dex (i.e. XandY or ManyMethods).
    114   std::string GetTestDexFileName(const char* name) const;
    115 
    116   // A helper function to fill the heap.
    117   static void FillHeap(Thread* self,
    118                        ClassLinker* class_linker,
    119                        VariableSizedHandleScope* handle_scope)
    120       REQUIRES_SHARED(Locks::mutator_lock_);
    121   // A helper to set up a small heap (4M) to make FillHeap faster.
    122   static void SetUpRuntimeOptionsForFillHeap(RuntimeOptions *options);
    123 
    124   template <typename Mutator>
    125   bool MutateDexFile(File* output_dex, const std::string& input_jar, const Mutator& mutator) {
    126     std::vector<std::unique_ptr<const DexFile>> dex_files;
    127     std::string error_msg;
    128     const ArtDexFileLoader dex_file_loader;
    129     CHECK(dex_file_loader.Open(input_jar.c_str(),
    130                                input_jar.c_str(),
    131                                /*verify*/ true,
    132                                /*verify_checksum*/ true,
    133                                &error_msg,
    134                                &dex_files)) << error_msg;
    135     EXPECT_EQ(dex_files.size(), 1u) << "Only one input dex is supported";
    136     const std::unique_ptr<const DexFile>& dex = dex_files[0];
    137     CHECK(dex->EnableWrite()) << "Failed to enable write";
    138     DexFile* dex_file = const_cast<DexFile*>(dex.get());
    139     mutator(dex_file);
    140     const_cast<DexFile::Header&>(dex_file->GetHeader()).checksum_ = dex_file->CalculateChecksum();
    141     if (!output_dex->WriteFully(dex->Begin(), dex->Size())) {
    142       return false;
    143     }
    144     if (output_dex->Flush() != 0) {
    145       PLOG(FATAL) << "Could not flush the output file.";
    146     }
    147     return true;
    148   }
    149 
    150  protected:
    151   // Allow subclases such as CommonCompilerTest to add extra options.
    152   virtual void SetUpRuntimeOptions(RuntimeOptions* options ATTRIBUTE_UNUSED) {}
    153 
    154   // Called before the runtime is created.
    155   virtual void PreRuntimeCreate() {}
    156 
    157   // Called after the runtime is created.
    158   virtual void PostRuntimeCreate() {}
    159 
    160   static bool IsHost() {
    161     return !kIsTargetBuild;
    162   }
    163 
    164   // File location to core.art, e.g. $ANDROID_HOST_OUT/system/framework/core.art
    165   static std::string GetCoreArtLocation();
    166 
    167   // File location to core.oat, e.g. $ANDROID_HOST_OUT/system/framework/core.oat
    168   static std::string GetCoreOatLocation();
    169 
    170   std::unique_ptr<const DexFile> LoadExpectSingleDexFile(const char* location);
    171 
    172   void ClearDirectory(const char* dirpath, bool recursive = true);
    173 
    174   std::string GetTestAndroidRoot();
    175 
    176   std::vector<std::unique_ptr<const DexFile>> OpenTestDexFiles(const char* name);
    177 
    178   std::unique_ptr<const DexFile> OpenTestDexFile(const char* name);
    179 
    180   // Loads the test dex file identified by the given dex_name into a PathClassLoader.
    181   // Returns the created class loader.
    182   jobject LoadDex(const char* dex_name) REQUIRES_SHARED(Locks::mutator_lock_);
    183   // Loads the test dex file identified by the given first_dex_name and second_dex_name
    184   // into a PathClassLoader. Returns the created class loader.
    185   jobject LoadMultiDex(const char* first_dex_name, const char* second_dex_name)
    186       REQUIRES_SHARED(Locks::mutator_lock_);
    187 
    188   jobject LoadDexInPathClassLoader(const std::string& dex_name, jobject parent_loader);
    189   jobject LoadDexInDelegateLastClassLoader(const std::string& dex_name, jobject parent_loader);
    190   jobject LoadDexInWellKnownClassLoader(const std::string& dex_name,
    191                                         jclass loader_class,
    192                                         jobject parent_loader);
    193 
    194   std::string android_data_;
    195   std::string dalvik_cache_;
    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(ScopedObjectAccess& soa,
    209                                           Handle<mirror::ClassLoader> class_loader)
    210     REQUIRES_SHARED(Locks::mutator_lock_);
    211 
    212   // Get the first dex file from a PathClassLoader. Will abort if it is null.
    213   const DexFile* GetFirstDexFile(jobject jclass_loader);
    214 
    215   std::unique_ptr<CompilerCallbacks> callbacks_;
    216 
    217   virtual void SetUp();
    218 
    219   virtual void TearDown();
    220 
    221   // Called to finish up runtime creation and filling test fields. By default runs root
    222   // initializers, initialize well-known classes, and creates the heap thread pool.
    223   virtual void FinalizeSetup();
    224 
    225   // Creates the class path string for the given dex files (the list of dex file locations
    226   // separated by ':').
    227   std::string CreateClassPath(
    228       const std::vector<std::unique_ptr<const DexFile>>& dex_files);
    229   // Same as CreateClassPath but add the dex file checksum after each location. The separator
    230   // is '*'.
    231   std::string CreateClassPathWithChecksums(
    232       const std::vector<std::unique_ptr<const DexFile>>& dex_files);
    233 
    234  private:
    235   static std::string GetCoreFileLocation(const char* suffix);
    236 
    237   std::vector<std::unique_ptr<const DexFile>> loaded_dex_files_;
    238 };
    239 
    240 template <typename TestType>
    241 class CommonRuntimeTestBase : public TestType, public CommonRuntimeTestImpl {
    242  public:
    243   CommonRuntimeTestBase() {}
    244   virtual ~CommonRuntimeTestBase() {}
    245 
    246  protected:
    247   virtual void SetUp() OVERRIDE {
    248     CommonRuntimeTestImpl::SetUp();
    249   }
    250 
    251   virtual void TearDown() OVERRIDE {
    252     CommonRuntimeTestImpl::TearDown();
    253   }
    254 };
    255 
    256 using CommonRuntimeTest = CommonRuntimeTestBase<testing::Test>;
    257 
    258 template <typename Param>
    259 using CommonRuntimeTestWithParam = CommonRuntimeTestBase<testing::TestWithParam<Param>>;
    260 
    261 // Sets a CheckJni abort hook to catch failures. Note that this will cause CheckJNI to carry on
    262 // rather than aborting, so be careful!
    263 class CheckJniAbortCatcher {
    264  public:
    265   CheckJniAbortCatcher();
    266 
    267   ~CheckJniAbortCatcher();
    268 
    269   void Check(const std::string& expected_text);
    270   void Check(const char* expected_text);
    271 
    272  private:
    273   static void Hook(void* data, const std::string& reason);
    274 
    275   JavaVMExt* const vm_;
    276   std::string actual_;
    277 
    278   DISALLOW_COPY_AND_ASSIGN(CheckJniAbortCatcher);
    279 };
    280 
    281 #define TEST_DISABLED_FOR_TARGET() \
    282   if (kIsTargetBuild) { \
    283     printf("WARNING: TEST DISABLED FOR TARGET\n"); \
    284     return; \
    285   }
    286 
    287 #define TEST_DISABLED_FOR_MIPS() \
    288   if (kRuntimeISA == InstructionSet::kMips) { \
    289     printf("WARNING: TEST DISABLED FOR MIPS\n"); \
    290     return; \
    291   }
    292 
    293 #define TEST_DISABLED_FOR_X86() \
    294   if (kRuntimeISA == InstructionSet::kX86) { \
    295     printf("WARNING: TEST DISABLED FOR X86\n"); \
    296     return; \
    297   }
    298 
    299 #define TEST_DISABLED_FOR_STRING_COMPRESSION() \
    300   if (mirror::kUseStringCompression) { \
    301     printf("WARNING: TEST DISABLED FOR STRING COMPRESSION\n"); \
    302     return; \
    303   }
    304 
    305 #define TEST_DISABLED_WITHOUT_BAKER_READ_BARRIERS() \
    306   if (!kEmitCompilerReadBarrier || !kUseBakerReadBarrier) { \
    307     printf("WARNING: TEST DISABLED FOR GC WITHOUT BAKER READ BARRIER\n"); \
    308     return; \
    309   }
    310 
    311 #define TEST_DISABLED_FOR_NON_STATIC_HOST_BUILDS() \
    312   if (!kHostStaticBuildEnabled) { \
    313     printf("WARNING: TEST DISABLED FOR NON-STATIC HOST BUILDS\n"); \
    314     return; \
    315   }
    316 
    317 #define TEST_DISABLED_FOR_MEMORY_TOOL() \
    318   if (RUNNING_ON_MEMORY_TOOL > 0) { \
    319     printf("WARNING: TEST DISABLED FOR MEMORY TOOL\n"); \
    320     return; \
    321   }
    322 
    323 #define TEST_DISABLED_FOR_MEMORY_TOOL_VALGRIND() \
    324   if (RUNNING_ON_MEMORY_TOOL > 0 && kMemoryToolIsValgrind) { \
    325     printf("WARNING: TEST DISABLED FOR MEMORY TOOL VALGRIND\n"); \
    326     return; \
    327   }
    328 
    329 #define TEST_DISABLED_FOR_MEMORY_TOOL_ASAN() \
    330   if (RUNNING_ON_MEMORY_TOOL > 0 && !kMemoryToolIsValgrind) { \
    331     printf("WARNING: TEST DISABLED FOR MEMORY TOOL ASAN\n"); \
    332     return; \
    333   }
    334 
    335 #define TEST_DISABLED_FOR_COMPACT_DEX() \
    336   if (kDefaultCompactDexLevel != CompactDexLevel::kCompactDexLevelNone) { \
    337     printf("WARNING: TEST DISABLED FOR COMPACT DEX\n"); \
    338     return; \
    339   }
    340 
    341 #define TEST_DISABLED_FOR_HEAP_POISONING() \
    342   if (kPoisonHeapReferences) { \
    343     printf("WARNING: TEST DISABLED FOR HEAP POISONING\n"); \
    344     return; \
    345   }
    346 }  // namespace art
    347 
    348 #endif  // ART_RUNTIME_COMMON_RUNTIME_TEST_H_
    349