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