common_runtime_test.cc revision 1fe5e5cce85a3cdc64a8d226a8ef4e6134c2b9eb
1/* 2 * Copyright (C) 2012 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#include "common_runtime_test.h" 18 19#include <dirent.h> 20#include <dlfcn.h> 21#include <fcntl.h> 22#include <ScopedLocalRef.h> 23 24#include "../../external/icu/icu4c/source/common/unicode/uvernum.h" 25#include "base/macros.h" 26#include "base/logging.h" 27#include "base/stl_util.h" 28#include "base/stringprintf.h" 29#include "base/unix_file/fd_file.h" 30#include "class_linker.h" 31#include "compiler_callbacks.h" 32#include "dex_file.h" 33#include "gc/heap.h" 34#include "gtest/gtest.h" 35#include "jni_internal.h" 36#include "mirror/class_loader.h" 37#include "noop_compiler_callbacks.h" 38#include "os.h" 39#include "runtime-inl.h" 40#include "scoped_thread_state_change.h" 41#include "thread.h" 42#include "well_known_classes.h" 43 44int main(int argc, char **argv) { 45 art::InitLogging(argv); 46 LOG(INFO) << "Running main() from common_runtime_test.cc..."; 47 testing::InitGoogleTest(&argc, argv); 48 return RUN_ALL_TESTS(); 49} 50 51namespace art { 52 53ScratchFile::ScratchFile() { 54 // ANDROID_DATA needs to be set 55 CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) << 56 "Are you subclassing RuntimeTest?"; 57 filename_ = getenv("ANDROID_DATA"); 58 filename_ += "/TmpFile-XXXXXX"; 59 int fd = mkstemp(&filename_[0]); 60 CHECK_NE(-1, fd); 61 file_.reset(new File(fd, GetFilename())); 62} 63 64ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix) { 65 filename_ = other.GetFilename(); 66 filename_ += suffix; 67 int fd = open(filename_.c_str(), O_RDWR | O_CREAT, 0666); 68 CHECK_NE(-1, fd); 69 file_.reset(new File(fd, GetFilename())); 70} 71 72ScratchFile::ScratchFile(File* file) { 73 CHECK(file != NULL); 74 filename_ = file->GetPath(); 75 file_.reset(file); 76} 77 78ScratchFile::~ScratchFile() { 79 Unlink(); 80} 81 82int ScratchFile::GetFd() const { 83 return file_->Fd(); 84} 85 86void ScratchFile::Unlink() { 87 if (!OS::FileExists(filename_.c_str())) { 88 return; 89 } 90 int unlink_result = unlink(filename_.c_str()); 91 CHECK_EQ(0, unlink_result); 92} 93 94CommonRuntimeTest::CommonRuntimeTest() {} 95CommonRuntimeTest::~CommonRuntimeTest() {} 96 97void CommonRuntimeTest::SetEnvironmentVariables(std::string& android_data) { 98 if (IsHost()) { 99 // $ANDROID_ROOT is set on the device, but not necessarily on the host. 100 // But it needs to be set so that icu4c can find its locale data. 101 const char* android_root_from_env = getenv("ANDROID_ROOT"); 102 if (android_root_from_env == nullptr) { 103 // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set. 104 const char* android_host_out = getenv("ANDROID_HOST_OUT"); 105 if (android_host_out != nullptr) { 106 setenv("ANDROID_ROOT", android_host_out, 1); 107 } else { 108 // Build it from ANDROID_BUILD_TOP or cwd 109 std::string root; 110 const char* android_build_top = getenv("ANDROID_BUILD_TOP"); 111 if (android_build_top != nullptr) { 112 root += android_build_top; 113 } else { 114 // Not set by build server, so default to current directory 115 char* cwd = getcwd(nullptr, 0); 116 setenv("ANDROID_BUILD_TOP", cwd, 1); 117 root += cwd; 118 free(cwd); 119 } 120#if defined(__linux__) 121 root += "/out/host/linux-x86"; 122#elif defined(__APPLE__) 123 root += "/out/host/darwin-x86"; 124#else 125#error unsupported OS 126#endif 127 setenv("ANDROID_ROOT", root.c_str(), 1); 128 } 129 } 130 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>. 131 132 // Not set by build server, so default 133 if (getenv("ANDROID_HOST_OUT") == nullptr) { 134 setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1); 135 } 136 } 137 138 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache 139 android_data = (IsHost() ? "/tmp/art-data-XXXXXX" : "/data/dalvik-cache/art-data-XXXXXX"); 140 if (mkdtemp(&android_data[0]) == nullptr) { 141 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed"; 142 } 143 setenv("ANDROID_DATA", android_data.c_str(), 1); 144} 145 146const DexFile* CommonRuntimeTest::LoadExpectSingleDexFile(const char* location) { 147 std::vector<const DexFile*> dex_files; 148 std::string error_msg; 149 if (!DexFile::Open(location, location, &error_msg, &dex_files)) { 150 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n"; 151 return nullptr; 152 } else { 153 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location; 154 return dex_files[0]; 155 } 156} 157 158void CommonRuntimeTest::SetUp() { 159 SetEnvironmentVariables(android_data_); 160 dalvik_cache_.append(android_data_.c_str()); 161 dalvik_cache_.append("/dalvik-cache"); 162 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700); 163 ASSERT_EQ(mkdir_result, 0); 164 165 std::string error_msg; 166 java_lang_dex_file_ = LoadExpectSingleDexFile(GetLibCoreDexFileName().c_str()); 167 boot_class_path_.push_back(java_lang_dex_file_); 168 169 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB)); 170 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB)); 171 172 callbacks_.reset(new NoopCompilerCallbacks()); 173 174 RuntimeOptions options; 175 options.push_back(std::make_pair("bootclasspath", &boot_class_path_)); 176 options.push_back(std::make_pair("-Xcheck:jni", nullptr)); 177 options.push_back(std::make_pair(min_heap_string.c_str(), nullptr)); 178 options.push_back(std::make_pair(max_heap_string.c_str(), nullptr)); 179 options.push_back(std::make_pair("compilercallbacks", callbacks_.get())); 180 SetUpRuntimeOptions(&options); 181 if (!Runtime::Create(options, false)) { 182 LOG(FATAL) << "Failed to create runtime"; 183 return; 184 } 185 runtime_.reset(Runtime::Current()); 186 class_linker_ = runtime_->GetClassLinker(); 187 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod()); 188 class_linker_->RunRootClinits(); 189 190 // Runtime::Create acquired the mutator_lock_ that is normally given away when we 191 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess. 192 Thread::Current()->TransitionFromRunnableToSuspended(kNative); 193 194 // We're back in native, take the opportunity to initialize well known classes. 195 WellKnownClasses::Init(Thread::Current()->GetJniEnv()); 196 197 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread 198 // pool is created by the runtime. 199 runtime_->GetHeap()->CreateThreadPool(); 200 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test 201} 202 203 204void CommonRuntimeTest::ClearDirectory(const char* dirpath) { 205 ASSERT_TRUE(dirpath != nullptr); 206 DIR* dir = opendir(dirpath); 207 ASSERT_TRUE(dir != nullptr); 208 dirent* e; 209 struct stat s; 210 while ((e = readdir(dir)) != nullptr) { 211 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) { 212 continue; 213 } 214 std::string filename(dalvik_cache_); 215 filename.push_back('/'); 216 filename.append(e->d_name); 217 int stat_result = lstat(filename.c_str(), &s); 218 ASSERT_EQ(0, stat_result) << "unable to stat " << filename; 219 if (S_ISDIR(s.st_mode)) { 220 ClearDirectory(filename.c_str()); 221 int rmdir_result = rmdir(filename.c_str()); 222 ASSERT_EQ(0, rmdir_result) << filename; 223 } else { 224 int unlink_result = unlink(filename.c_str()); 225 ASSERT_EQ(0, unlink_result) << filename; 226 } 227 } 228 closedir(dir); 229} 230 231void CommonRuntimeTest::TearDown() { 232 const char* android_data = getenv("ANDROID_DATA"); 233 ASSERT_TRUE(android_data != nullptr); 234 ClearDirectory(dalvik_cache_.c_str()); 235 int rmdir_cache_result = rmdir(dalvik_cache_.c_str()); 236 ASSERT_EQ(0, rmdir_cache_result); 237 int rmdir_data_result = rmdir(android_data_.c_str()); 238 ASSERT_EQ(0, rmdir_data_result); 239 240 // icu4c has a fixed 10-element array "gCommonICUDataArray". 241 // If we run > 10 tests, we fill that array and u_setCommonData fails. 242 // There's a function to clear the array, but it's not public... 243 typedef void (*IcuCleanupFn)(); 244 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT); 245 CHECK(sym != nullptr) << dlerror(); 246 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym); 247 (*icu_cleanup_fn)(); 248 249 STLDeleteElements(&opened_dex_files_); 250 251 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test 252} 253 254std::string CommonRuntimeTest::GetLibCoreDexFileName() { 255 return GetDexFileName("core-libart"); 256} 257 258std::string CommonRuntimeTest::GetDexFileName(const std::string& jar_prefix) { 259 if (IsHost()) { 260 const char* host_dir = getenv("ANDROID_HOST_OUT"); 261 CHECK(host_dir != nullptr); 262 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str()); 263 } 264 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str()); 265} 266 267std::string CommonRuntimeTest::GetTestAndroidRoot() { 268 if (IsHost()) { 269 const char* host_dir = getenv("ANDROID_HOST_OUT"); 270 CHECK(host_dir != nullptr); 271 return host_dir; 272 } 273 return GetAndroidRoot(); 274} 275 276// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set. 277#ifdef ART_TARGET 278#ifndef ART_TARGET_NATIVETEST_DIR 279#error "ART_TARGET_NATIVETEST_DIR not set." 280#endif 281// Wrap it as a string literal. 282#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/" 283#else 284#define ART_TARGET_NATIVETEST_DIR_STRING "" 285#endif 286 287std::vector<const DexFile*> CommonRuntimeTest::OpenTestDexFiles(const char* name) { 288 CHECK(name != nullptr); 289 std::string filename; 290 if (IsHost()) { 291 filename += getenv("ANDROID_HOST_OUT"); 292 filename += "/framework/"; 293 } else { 294 filename += ART_TARGET_NATIVETEST_DIR_STRING; 295 } 296 filename += "art-gtest-"; 297 filename += name; 298 filename += ".jar"; 299 std::string error_msg; 300 std::vector<const DexFile*> dex_files; 301 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files); 302 CHECK(success) << "Failed to open '" << filename << "': " << error_msg; 303 for (const DexFile* dex_file : dex_files) { 304 CHECK_EQ(PROT_READ, dex_file->GetPermissions()); 305 CHECK(dex_file->IsReadOnly()); 306 } 307 opened_dex_files_.insert(opened_dex_files_.end(), dex_files.begin(), dex_files.end()); 308 return dex_files; 309} 310 311const DexFile* CommonRuntimeTest::OpenTestDexFile(const char* name) { 312 std::vector<const DexFile*> vector = OpenTestDexFiles(name); 313 EXPECT_EQ(1U, vector.size()); 314 return vector[0]; 315} 316 317jobject CommonRuntimeTest::LoadDex(const char* dex_name) { 318 std::vector<const DexFile*> dex_files = OpenTestDexFiles(dex_name); 319 CHECK_NE(0U, dex_files.size()); 320 for (const DexFile* dex_file : dex_files) { 321 class_linker_->RegisterDexFile(*dex_file); 322 } 323 ScopedObjectAccessUnchecked soa(Thread::Current()); 324 ScopedLocalRef<jobject> class_loader_local(soa.Env(), 325 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader)); 326 jobject class_loader = soa.Env()->NewGlobalRef(class_loader_local.get()); 327 soa.Self()->SetClassLoaderOverride(soa.Decode<mirror::ClassLoader*>(class_loader_local.get())); 328 Runtime::Current()->SetCompileTimeClassPath(class_loader, dex_files); 329 return class_loader; 330} 331 332CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) { 333 vm_->check_jni_abort_hook = Hook; 334 vm_->check_jni_abort_hook_data = &actual_; 335} 336 337CheckJniAbortCatcher::~CheckJniAbortCatcher() { 338 vm_->check_jni_abort_hook = nullptr; 339 vm_->check_jni_abort_hook_data = nullptr; 340 EXPECT_TRUE(actual_.empty()) << actual_; 341} 342 343void CheckJniAbortCatcher::Check(const char* expected_text) { 344 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n" 345 << "Expected to find: " << expected_text << "\n" 346 << "In the output : " << actual_; 347 actual_.clear(); 348} 349 350void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) { 351 // We use += because when we're hooking the aborts like this, multiple problems can be found. 352 *reinterpret_cast<std::string*>(data) += reason; 353} 354 355} // namespace art 356 357namespace std { 358 359template <typename T> 360std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) { 361os << ::art::ToString(rhs); 362return os; 363} 364 365} // namespace std 366