blob: d48ac9d6b1e8172cfe4597c03b2ee829e79c71b2 [file] [log] [blame]
Elliott Hugheseb02a122012-06-12 11:35:40 -07001/*
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
Ian Rogerse63db272014-07-15 15:36:11 -070017#include "common_runtime_test.h"
18
19#include <dirent.h>
20#include <dlfcn.h>
21#include <fcntl.h>
22#include <ScopedLocalRef.h>
Andreas Gampe369810a2015-01-14 19:53:31 -080023#include <stdlib.h>
Ian Rogerse63db272014-07-15 15:36:11 -070024
25#include "../../external/icu/icu4c/source/common/unicode/uvernum.h"
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -070026#include "base/macros.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080027#include "base/logging.h"
Ian Rogerse63db272014-07-15 15:36:11 -070028#include "base/stl_util.h"
29#include "base/stringprintf.h"
30#include "base/unix_file/fd_file.h"
31#include "class_linker.h"
32#include "compiler_callbacks.h"
33#include "dex_file.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070034#include "gc_root-inl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070035#include "gc/heap.h"
Elliott Hugheseb02a122012-06-12 11:35:40 -070036#include "gtest/gtest.h"
Ian Rogerse63db272014-07-15 15:36:11 -070037#include "jni_internal.h"
38#include "mirror/class_loader.h"
39#include "noop_compiler_callbacks.h"
40#include "os.h"
41#include "runtime-inl.h"
42#include "scoped_thread_state_change.h"
43#include "thread.h"
44#include "well_known_classes.h"
Elliott Hugheseb02a122012-06-12 11:35:40 -070045
46int main(int argc, char **argv) {
Andreas Gampe369810a2015-01-14 19:53:31 -080047 // Gtests can be very noisy. For example, an executable with multiple tests will trigger native
48 // bridge warnings. The following line reduces the minimum log severity to ERROR and suppresses
49 // everything else. In case you want to see all messages, comment out the line.
50 setenv("ANDROID_LOG_TAGS", "*:e", 1);
51
Elliott Hugheseb02a122012-06-12 11:35:40 -070052 art::InitLogging(argv);
Ian Rogersc7dd2952014-10-21 23:31:19 -070053 LOG(::art::INFO) << "Running main() from common_runtime_test.cc...";
Elliott Hugheseb02a122012-06-12 11:35:40 -070054 testing::InitGoogleTest(&argc, argv);
55 return RUN_ALL_TESTS();
56}
Ian Rogerse63db272014-07-15 15:36:11 -070057
58namespace art {
59
60ScratchFile::ScratchFile() {
61 // ANDROID_DATA needs to be set
62 CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
63 "Are you subclassing RuntimeTest?";
64 filename_ = getenv("ANDROID_DATA");
65 filename_ += "/TmpFile-XXXXXX";
66 int fd = mkstemp(&filename_[0]);
67 CHECK_NE(-1, fd);
Andreas Gampe4303ba92014-11-06 01:00:46 -080068 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070069}
70
71ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix) {
72 filename_ = other.GetFilename();
73 filename_ += suffix;
74 int fd = open(filename_.c_str(), O_RDWR | O_CREAT, 0666);
75 CHECK_NE(-1, fd);
Andreas Gampe4303ba92014-11-06 01:00:46 -080076 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070077}
78
79ScratchFile::ScratchFile(File* file) {
80 CHECK(file != NULL);
81 filename_ = file->GetPath();
82 file_.reset(file);
83}
84
85ScratchFile::~ScratchFile() {
86 Unlink();
87}
88
89int ScratchFile::GetFd() const {
90 return file_->Fd();
91}
92
Andreas Gampee21dc3d2014-12-08 16:59:43 -080093void ScratchFile::Close() {
Andreas Gampe4303ba92014-11-06 01:00:46 -080094 if (file_.get() != nullptr) {
95 if (file_->FlushCloseOrErase() != 0) {
96 PLOG(WARNING) << "Error closing scratch file.";
97 }
98 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -080099}
100
101void ScratchFile::Unlink() {
102 if (!OS::FileExists(filename_.c_str())) {
103 return;
104 }
105 Close();
Ian Rogerse63db272014-07-15 15:36:11 -0700106 int unlink_result = unlink(filename_.c_str());
107 CHECK_EQ(0, unlink_result);
108}
109
110CommonRuntimeTest::CommonRuntimeTest() {}
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800111CommonRuntimeTest::~CommonRuntimeTest() {
112 // Ensure the dex files are cleaned up before the runtime.
113 loaded_dex_files_.clear();
114 runtime_.reset();
115}
Ian Rogerse63db272014-07-15 15:36:11 -0700116
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700117void CommonRuntimeTest::SetUpAndroidRoot() {
Ian Rogerse63db272014-07-15 15:36:11 -0700118 if (IsHost()) {
119 // $ANDROID_ROOT is set on the device, but not necessarily on the host.
120 // But it needs to be set so that icu4c can find its locale data.
121 const char* android_root_from_env = getenv("ANDROID_ROOT");
122 if (android_root_from_env == nullptr) {
123 // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
124 const char* android_host_out = getenv("ANDROID_HOST_OUT");
125 if (android_host_out != nullptr) {
126 setenv("ANDROID_ROOT", android_host_out, 1);
127 } else {
128 // Build it from ANDROID_BUILD_TOP or cwd
129 std::string root;
130 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
131 if (android_build_top != nullptr) {
132 root += android_build_top;
133 } else {
134 // Not set by build server, so default to current directory
135 char* cwd = getcwd(nullptr, 0);
136 setenv("ANDROID_BUILD_TOP", cwd, 1);
137 root += cwd;
138 free(cwd);
139 }
140#if defined(__linux__)
141 root += "/out/host/linux-x86";
142#elif defined(__APPLE__)
143 root += "/out/host/darwin-x86";
144#else
145#error unsupported OS
146#endif
147 setenv("ANDROID_ROOT", root.c_str(), 1);
148 }
149 }
150 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
151
152 // Not set by build server, so default
153 if (getenv("ANDROID_HOST_OUT") == nullptr) {
154 setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
155 }
156 }
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700157}
Ian Rogerse63db272014-07-15 15:36:11 -0700158
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700159void CommonRuntimeTest::SetUpAndroidData(std::string& android_data) {
Ian Rogerse63db272014-07-15 15:36:11 -0700160 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
Andreas Gampe5a79fde2014-08-06 13:12:26 -0700161 if (IsHost()) {
162 const char* tmpdir = getenv("TMPDIR");
163 if (tmpdir != nullptr && tmpdir[0] != 0) {
164 android_data = tmpdir;
165 } else {
166 android_data = "/tmp";
167 }
168 } else {
169 android_data = "/data/dalvik-cache";
170 }
171 android_data += "/art-data-XXXXXX";
Ian Rogerse63db272014-07-15 15:36:11 -0700172 if (mkdtemp(&android_data[0]) == nullptr) {
173 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
174 }
175 setenv("ANDROID_DATA", android_data.c_str(), 1);
176}
177
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700178void CommonRuntimeTest::TearDownAndroidData(const std::string& android_data, bool fail_on_error) {
179 if (fail_on_error) {
180 ASSERT_EQ(rmdir(android_data.c_str()), 0);
181 } else {
182 rmdir(android_data.c_str());
183 }
184}
185
Igor Murashkin37743352014-11-13 14:38:00 -0800186std::string CommonRuntimeTest::GetCoreArtLocation() {
187 return GetCoreFileLocation("art");
188}
189
190std::string CommonRuntimeTest::GetCoreOatLocation() {
191 return GetCoreFileLocation("oat");
192}
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700193
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800194std::unique_ptr<const DexFile> CommonRuntimeTest::LoadExpectSingleDexFile(const char* location) {
195 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700196 std::string error_msg;
197 if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
198 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800199 UNREACHABLE();
Ian Rogerse63db272014-07-15 15:36:11 -0700200 } else {
201 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800202 return std::move(dex_files[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700203 }
204}
205
206void CommonRuntimeTest::SetUp() {
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700207 SetUpAndroidRoot();
208 SetUpAndroidData(android_data_);
Ian Rogerse63db272014-07-15 15:36:11 -0700209 dalvik_cache_.append(android_data_.c_str());
210 dalvik_cache_.append("/dalvik-cache");
211 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
212 ASSERT_EQ(mkdir_result, 0);
213
Ian Rogerse63db272014-07-15 15:36:11 -0700214 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
215 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
216
217 callbacks_.reset(new NoopCompilerCallbacks());
218
219 RuntimeOptions options;
Richard Uhlerc2752592015-01-02 13:28:22 -0800220 std::string boot_class_path_string = "-Xbootclasspath:" + GetLibCoreDexFileName();
221 options.push_back(std::make_pair(boot_class_path_string, nullptr));
Ian Rogerse63db272014-07-15 15:36:11 -0700222 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
Richard Uhlerc2752592015-01-02 13:28:22 -0800223 options.push_back(std::make_pair(min_heap_string, nullptr));
224 options.push_back(std::make_pair(max_heap_string, nullptr));
Ian Rogerse63db272014-07-15 15:36:11 -0700225 options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
226 SetUpRuntimeOptions(&options);
227 if (!Runtime::Create(options, false)) {
228 LOG(FATAL) << "Failed to create runtime";
229 return;
230 }
231 runtime_.reset(Runtime::Current());
232 class_linker_ = runtime_->GetClassLinker();
233 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
234 class_linker_->RunRootClinits();
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800235 boot_class_path_ = class_linker_->GetBootClassPath();
236 java_lang_dex_file_ = boot_class_path_[0];
237
Ian Rogerse63db272014-07-15 15:36:11 -0700238
239 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
240 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
241 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
242
243 // We're back in native, take the opportunity to initialize well known classes.
244 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
245
246 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
247 // pool is created by the runtime.
248 runtime_->GetHeap()->CreateThreadPool();
249 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
Richard Uhlerc2752592015-01-02 13:28:22 -0800250
251 // Get the boot class path from the runtime so it can be used in tests.
252 boot_class_path_ = class_linker_->GetBootClassPath();
253 ASSERT_FALSE(boot_class_path_.empty());
254 java_lang_dex_file_ = boot_class_path_[0];
Ian Rogerse63db272014-07-15 15:36:11 -0700255}
256
Alex Lighta59dd802014-07-02 16:28:08 -0700257void CommonRuntimeTest::ClearDirectory(const char* dirpath) {
258 ASSERT_TRUE(dirpath != nullptr);
259 DIR* dir = opendir(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700260 ASSERT_TRUE(dir != nullptr);
261 dirent* e;
Alex Lighta59dd802014-07-02 16:28:08 -0700262 struct stat s;
Ian Rogerse63db272014-07-15 15:36:11 -0700263 while ((e = readdir(dir)) != nullptr) {
264 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
265 continue;
266 }
Jeff Haof0a3f092014-07-24 16:26:09 -0700267 std::string filename(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700268 filename.push_back('/');
269 filename.append(e->d_name);
Alex Lighta59dd802014-07-02 16:28:08 -0700270 int stat_result = lstat(filename.c_str(), &s);
271 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
272 if (S_ISDIR(s.st_mode)) {
273 ClearDirectory(filename.c_str());
274 int rmdir_result = rmdir(filename.c_str());
275 ASSERT_EQ(0, rmdir_result) << filename;
276 } else {
277 int unlink_result = unlink(filename.c_str());
278 ASSERT_EQ(0, unlink_result) << filename;
279 }
Ian Rogerse63db272014-07-15 15:36:11 -0700280 }
281 closedir(dir);
Alex Lighta59dd802014-07-02 16:28:08 -0700282}
283
284void CommonRuntimeTest::TearDown() {
285 const char* android_data = getenv("ANDROID_DATA");
286 ASSERT_TRUE(android_data != nullptr);
287 ClearDirectory(dalvik_cache_.c_str());
Ian Rogerse63db272014-07-15 15:36:11 -0700288 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
289 ASSERT_EQ(0, rmdir_cache_result);
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700290 TearDownAndroidData(android_data_, true);
Ian Rogerse63db272014-07-15 15:36:11 -0700291
292 // icu4c has a fixed 10-element array "gCommonICUDataArray".
293 // If we run > 10 tests, we fill that array and u_setCommonData fails.
294 // There's a function to clear the array, but it's not public...
295 typedef void (*IcuCleanupFn)();
296 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
297 CHECK(sym != nullptr) << dlerror();
298 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
299 (*icu_cleanup_fn)();
300
Ian Rogerse63db272014-07-15 15:36:11 -0700301 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
302}
303
304std::string CommonRuntimeTest::GetLibCoreDexFileName() {
305 return GetDexFileName("core-libart");
306}
307
308std::string CommonRuntimeTest::GetDexFileName(const std::string& jar_prefix) {
309 if (IsHost()) {
310 const char* host_dir = getenv("ANDROID_HOST_OUT");
311 CHECK(host_dir != nullptr);
312 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
313 }
314 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
315}
316
317std::string CommonRuntimeTest::GetTestAndroidRoot() {
318 if (IsHost()) {
319 const char* host_dir = getenv("ANDROID_HOST_OUT");
320 CHECK(host_dir != nullptr);
321 return host_dir;
322 }
323 return GetAndroidRoot();
324}
325
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700326// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
327#ifdef ART_TARGET
328#ifndef ART_TARGET_NATIVETEST_DIR
329#error "ART_TARGET_NATIVETEST_DIR not set."
330#endif
331// Wrap it as a string literal.
332#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
333#else
334#define ART_TARGET_NATIVETEST_DIR_STRING ""
335#endif
336
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800337std::vector<std::unique_ptr<const DexFile>> CommonRuntimeTest::OpenTestDexFiles(const char* name) {
Ian Rogerse63db272014-07-15 15:36:11 -0700338 CHECK(name != nullptr);
339 std::string filename;
340 if (IsHost()) {
341 filename += getenv("ANDROID_HOST_OUT");
342 filename += "/framework/";
343 } else {
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700344 filename += ART_TARGET_NATIVETEST_DIR_STRING;
Ian Rogerse63db272014-07-15 15:36:11 -0700345 }
346 filename += "art-gtest-";
347 filename += name;
348 filename += ".jar";
349 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800350 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700351 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
352 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800353 for (auto& dex_file : dex_files) {
Ian Rogerse63db272014-07-15 15:36:11 -0700354 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
355 CHECK(dex_file->IsReadOnly());
356 }
Ian Rogerse63db272014-07-15 15:36:11 -0700357 return dex_files;
358}
359
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800360std::unique_ptr<const DexFile> CommonRuntimeTest::OpenTestDexFile(const char* name) {
361 std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700362 EXPECT_EQ(1U, vector.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800363 return std::move(vector[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700364}
365
366jobject CommonRuntimeTest::LoadDex(const char* dex_name) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800367 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name);
368 std::vector<const DexFile*> class_path;
Ian Rogerse63db272014-07-15 15:36:11 -0700369 CHECK_NE(0U, dex_files.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800370 for (auto& dex_file : dex_files) {
371 class_path.push_back(dex_file.get());
Ian Rogerse63db272014-07-15 15:36:11 -0700372 class_linker_->RegisterDexFile(*dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800373 loaded_dex_files_.push_back(std::move(dex_file));
Ian Rogerse63db272014-07-15 15:36:11 -0700374 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700375 Thread* self = Thread::Current();
376 JNIEnvExt* env = self->GetJniEnv();
377 ScopedLocalRef<jobject> class_loader_local(env,
378 env->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
379 jobject class_loader = env->NewGlobalRef(class_loader_local.get());
380 self->SetClassLoaderOverride(class_loader_local.get());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800381 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path);
Ian Rogerse63db272014-07-15 15:36:11 -0700382 return class_loader;
383}
384
Igor Murashkin37743352014-11-13 14:38:00 -0800385std::string CommonRuntimeTest::GetCoreFileLocation(const char* suffix) {
386 CHECK(suffix != nullptr);
387
388 std::string location;
389 if (IsHost()) {
390 const char* host_dir = getenv("ANDROID_HOST_OUT");
391 CHECK(host_dir != NULL);
392 location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
393 } else {
394 location = StringPrintf("/data/art-test/core.%s", suffix);
395 }
396
397 return location;
398}
399
Ian Rogerse63db272014-07-15 15:36:11 -0700400CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700401 vm_->SetCheckJniAbortHook(Hook, &actual_);
Ian Rogerse63db272014-07-15 15:36:11 -0700402}
403
404CheckJniAbortCatcher::~CheckJniAbortCatcher() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700405 vm_->SetCheckJniAbortHook(nullptr, nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -0700406 EXPECT_TRUE(actual_.empty()) << actual_;
407}
408
409void CheckJniAbortCatcher::Check(const char* expected_text) {
410 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
411 << "Expected to find: " << expected_text << "\n"
412 << "In the output : " << actual_;
413 actual_.clear();
414}
415
416void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
417 // We use += because when we're hooking the aborts like this, multiple problems can be found.
418 *reinterpret_cast<std::string*>(data) += reason;
419}
420
421} // namespace art
422
423namespace std {
424
425template <typename T>
426std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
427os << ::art::ToString(rhs);
428return os;
429}
430
431} // namespace std