blob: e017699b04c6903c7610c5cd9717c4ca93ad9f9a [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>
23
24#include "../../external/icu/icu4c/source/common/unicode/uvernum.h"
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -070025#include "base/macros.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080026#include "base/logging.h"
Ian Rogerse63db272014-07-15 15:36:11 -070027#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"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070033#include "gc_root-inl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070034#include "gc/heap.h"
Elliott Hugheseb02a122012-06-12 11:35:40 -070035#include "gtest/gtest.h"
Ian Rogerse63db272014-07-15 15:36:11 -070036#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"
Elliott Hugheseb02a122012-06-12 11:35:40 -070044
45int main(int argc, char **argv) {
46 art::InitLogging(argv);
Ian Rogersc7dd2952014-10-21 23:31:19 -070047 LOG(::art::INFO) << "Running main() from common_runtime_test.cc...";
Elliott Hugheseb02a122012-06-12 11:35:40 -070048 testing::InitGoogleTest(&argc, argv);
49 return RUN_ALL_TESTS();
50}
Ian Rogerse63db272014-07-15 15:36:11 -070051
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);
Andreas Gampe4303ba92014-11-06 01:00:46 -080062 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070063}
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);
Andreas Gampe4303ba92014-11-06 01:00:46 -080070 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070071}
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
Andreas Gampee21dc3d2014-12-08 16:59:43 -080087void ScratchFile::Close() {
Andreas Gampe4303ba92014-11-06 01:00:46 -080088 if (file_.get() != nullptr) {
89 if (file_->FlushCloseOrErase() != 0) {
90 PLOG(WARNING) << "Error closing scratch file.";
91 }
92 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -080093}
94
95void ScratchFile::Unlink() {
96 if (!OS::FileExists(filename_.c_str())) {
97 return;
98 }
99 Close();
Ian Rogerse63db272014-07-15 15:36:11 -0700100 int unlink_result = unlink(filename_.c_str());
101 CHECK_EQ(0, unlink_result);
102}
103
104CommonRuntimeTest::CommonRuntimeTest() {}
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800105CommonRuntimeTest::~CommonRuntimeTest() {
106 // Ensure the dex files are cleaned up before the runtime.
107 loaded_dex_files_.clear();
108 runtime_.reset();
109}
Ian Rogerse63db272014-07-15 15:36:11 -0700110
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700111void CommonRuntimeTest::SetUpAndroidRoot() {
Ian Rogerse63db272014-07-15 15:36:11 -0700112 if (IsHost()) {
113 // $ANDROID_ROOT is set on the device, but not necessarily on the host.
114 // But it needs to be set so that icu4c can find its locale data.
115 const char* android_root_from_env = getenv("ANDROID_ROOT");
116 if (android_root_from_env == nullptr) {
117 // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
118 const char* android_host_out = getenv("ANDROID_HOST_OUT");
119 if (android_host_out != nullptr) {
120 setenv("ANDROID_ROOT", android_host_out, 1);
121 } else {
122 // Build it from ANDROID_BUILD_TOP or cwd
123 std::string root;
124 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
125 if (android_build_top != nullptr) {
126 root += android_build_top;
127 } else {
128 // Not set by build server, so default to current directory
129 char* cwd = getcwd(nullptr, 0);
130 setenv("ANDROID_BUILD_TOP", cwd, 1);
131 root += cwd;
132 free(cwd);
133 }
134#if defined(__linux__)
135 root += "/out/host/linux-x86";
136#elif defined(__APPLE__)
137 root += "/out/host/darwin-x86";
138#else
139#error unsupported OS
140#endif
141 setenv("ANDROID_ROOT", root.c_str(), 1);
142 }
143 }
144 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
145
146 // Not set by build server, so default
147 if (getenv("ANDROID_HOST_OUT") == nullptr) {
148 setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
149 }
150 }
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700151}
Ian Rogerse63db272014-07-15 15:36:11 -0700152
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700153void CommonRuntimeTest::SetUpAndroidData(std::string& android_data) {
Ian Rogerse63db272014-07-15 15:36:11 -0700154 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
Andreas Gampe5a79fde2014-08-06 13:12:26 -0700155 if (IsHost()) {
156 const char* tmpdir = getenv("TMPDIR");
157 if (tmpdir != nullptr && tmpdir[0] != 0) {
158 android_data = tmpdir;
159 } else {
160 android_data = "/tmp";
161 }
162 } else {
163 android_data = "/data/dalvik-cache";
164 }
165 android_data += "/art-data-XXXXXX";
Ian Rogerse63db272014-07-15 15:36:11 -0700166 if (mkdtemp(&android_data[0]) == nullptr) {
167 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
168 }
169 setenv("ANDROID_DATA", android_data.c_str(), 1);
170}
171
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700172void CommonRuntimeTest::TearDownAndroidData(const std::string& android_data, bool fail_on_error) {
173 if (fail_on_error) {
174 ASSERT_EQ(rmdir(android_data.c_str()), 0);
175 } else {
176 rmdir(android_data.c_str());
177 }
178}
179
Igor Murashkin37743352014-11-13 14:38:00 -0800180std::string CommonRuntimeTest::GetCoreArtLocation() {
181 return GetCoreFileLocation("art");
182}
183
184std::string CommonRuntimeTest::GetCoreOatLocation() {
185 return GetCoreFileLocation("oat");
186}
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700187
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800188std::unique_ptr<const DexFile> CommonRuntimeTest::LoadExpectSingleDexFile(const char* location) {
189 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700190 std::string error_msg;
191 if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
192 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800193 UNREACHABLE();
Ian Rogerse63db272014-07-15 15:36:11 -0700194 } else {
195 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800196 return std::move(dex_files[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700197 }
198}
199
200void CommonRuntimeTest::SetUp() {
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700201 SetUpAndroidRoot();
202 SetUpAndroidData(android_data_);
Ian Rogerse63db272014-07-15 15:36:11 -0700203 dalvik_cache_.append(android_data_.c_str());
204 dalvik_cache_.append("/dalvik-cache");
205 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
206 ASSERT_EQ(mkdir_result, 0);
207
Ian Rogerse63db272014-07-15 15:36:11 -0700208 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
209 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
210
211 callbacks_.reset(new NoopCompilerCallbacks());
212
213 RuntimeOptions options;
Richard Uhlerc2752592015-01-02 13:28:22 -0800214 std::string boot_class_path_string = "-Xbootclasspath:" + GetLibCoreDexFileName();
215 options.push_back(std::make_pair(boot_class_path_string, nullptr));
Ian Rogerse63db272014-07-15 15:36:11 -0700216 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
Richard Uhlerc2752592015-01-02 13:28:22 -0800217 options.push_back(std::make_pair(min_heap_string, nullptr));
218 options.push_back(std::make_pair(max_heap_string, nullptr));
Ian Rogerse63db272014-07-15 15:36:11 -0700219 options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
220 SetUpRuntimeOptions(&options);
221 if (!Runtime::Create(options, false)) {
222 LOG(FATAL) << "Failed to create runtime";
223 return;
224 }
225 runtime_.reset(Runtime::Current());
226 class_linker_ = runtime_->GetClassLinker();
227 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
228 class_linker_->RunRootClinits();
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800229 boot_class_path_ = class_linker_->GetBootClassPath();
230 java_lang_dex_file_ = boot_class_path_[0];
231
Ian Rogerse63db272014-07-15 15:36:11 -0700232
233 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
234 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
235 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
236
237 // We're back in native, take the opportunity to initialize well known classes.
238 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
239
240 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
241 // pool is created by the runtime.
242 runtime_->GetHeap()->CreateThreadPool();
243 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
Richard Uhlerc2752592015-01-02 13:28:22 -0800244
245 // Get the boot class path from the runtime so it can be used in tests.
246 boot_class_path_ = class_linker_->GetBootClassPath();
247 ASSERT_FALSE(boot_class_path_.empty());
248 java_lang_dex_file_ = boot_class_path_[0];
Ian Rogerse63db272014-07-15 15:36:11 -0700249}
250
Alex Lighta59dd802014-07-02 16:28:08 -0700251void CommonRuntimeTest::ClearDirectory(const char* dirpath) {
252 ASSERT_TRUE(dirpath != nullptr);
253 DIR* dir = opendir(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700254 ASSERT_TRUE(dir != nullptr);
255 dirent* e;
Alex Lighta59dd802014-07-02 16:28:08 -0700256 struct stat s;
Ian Rogerse63db272014-07-15 15:36:11 -0700257 while ((e = readdir(dir)) != nullptr) {
258 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
259 continue;
260 }
Jeff Haof0a3f092014-07-24 16:26:09 -0700261 std::string filename(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700262 filename.push_back('/');
263 filename.append(e->d_name);
Alex Lighta59dd802014-07-02 16:28:08 -0700264 int stat_result = lstat(filename.c_str(), &s);
265 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
266 if (S_ISDIR(s.st_mode)) {
267 ClearDirectory(filename.c_str());
268 int rmdir_result = rmdir(filename.c_str());
269 ASSERT_EQ(0, rmdir_result) << filename;
270 } else {
271 int unlink_result = unlink(filename.c_str());
272 ASSERT_EQ(0, unlink_result) << filename;
273 }
Ian Rogerse63db272014-07-15 15:36:11 -0700274 }
275 closedir(dir);
Alex Lighta59dd802014-07-02 16:28:08 -0700276}
277
278void CommonRuntimeTest::TearDown() {
279 const char* android_data = getenv("ANDROID_DATA");
280 ASSERT_TRUE(android_data != nullptr);
281 ClearDirectory(dalvik_cache_.c_str());
Ian Rogerse63db272014-07-15 15:36:11 -0700282 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
283 ASSERT_EQ(0, rmdir_cache_result);
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700284 TearDownAndroidData(android_data_, true);
Ian Rogerse63db272014-07-15 15:36:11 -0700285
286 // icu4c has a fixed 10-element array "gCommonICUDataArray".
287 // If we run > 10 tests, we fill that array and u_setCommonData fails.
288 // There's a function to clear the array, but it's not public...
289 typedef void (*IcuCleanupFn)();
290 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
291 CHECK(sym != nullptr) << dlerror();
292 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
293 (*icu_cleanup_fn)();
294
Ian Rogerse63db272014-07-15 15:36:11 -0700295 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
296}
297
298std::string CommonRuntimeTest::GetLibCoreDexFileName() {
299 return GetDexFileName("core-libart");
300}
301
302std::string CommonRuntimeTest::GetDexFileName(const std::string& jar_prefix) {
303 if (IsHost()) {
304 const char* host_dir = getenv("ANDROID_HOST_OUT");
305 CHECK(host_dir != nullptr);
306 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
307 }
308 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
309}
310
311std::string CommonRuntimeTest::GetTestAndroidRoot() {
312 if (IsHost()) {
313 const char* host_dir = getenv("ANDROID_HOST_OUT");
314 CHECK(host_dir != nullptr);
315 return host_dir;
316 }
317 return GetAndroidRoot();
318}
319
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700320// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
321#ifdef ART_TARGET
322#ifndef ART_TARGET_NATIVETEST_DIR
323#error "ART_TARGET_NATIVETEST_DIR not set."
324#endif
325// Wrap it as a string literal.
326#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
327#else
328#define ART_TARGET_NATIVETEST_DIR_STRING ""
329#endif
330
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800331std::vector<std::unique_ptr<const DexFile>> CommonRuntimeTest::OpenTestDexFiles(const char* name) {
Ian Rogerse63db272014-07-15 15:36:11 -0700332 CHECK(name != nullptr);
333 std::string filename;
334 if (IsHost()) {
335 filename += getenv("ANDROID_HOST_OUT");
336 filename += "/framework/";
337 } else {
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700338 filename += ART_TARGET_NATIVETEST_DIR_STRING;
Ian Rogerse63db272014-07-15 15:36:11 -0700339 }
340 filename += "art-gtest-";
341 filename += name;
342 filename += ".jar";
343 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800344 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700345 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
346 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800347 for (auto& dex_file : dex_files) {
Ian Rogerse63db272014-07-15 15:36:11 -0700348 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
349 CHECK(dex_file->IsReadOnly());
350 }
Ian Rogerse63db272014-07-15 15:36:11 -0700351 return dex_files;
352}
353
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800354std::unique_ptr<const DexFile> CommonRuntimeTest::OpenTestDexFile(const char* name) {
355 std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700356 EXPECT_EQ(1U, vector.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800357 return std::move(vector[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700358}
359
360jobject CommonRuntimeTest::LoadDex(const char* dex_name) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800361 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name);
362 std::vector<const DexFile*> class_path;
Ian Rogerse63db272014-07-15 15:36:11 -0700363 CHECK_NE(0U, dex_files.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800364 for (auto& dex_file : dex_files) {
365 class_path.push_back(dex_file.get());
Ian Rogerse63db272014-07-15 15:36:11 -0700366 class_linker_->RegisterDexFile(*dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800367 loaded_dex_files_.push_back(std::move(dex_file));
Ian Rogerse63db272014-07-15 15:36:11 -0700368 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700369 Thread* self = Thread::Current();
370 JNIEnvExt* env = self->GetJniEnv();
371 ScopedLocalRef<jobject> class_loader_local(env,
372 env->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
373 jobject class_loader = env->NewGlobalRef(class_loader_local.get());
374 self->SetClassLoaderOverride(class_loader_local.get());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800375 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path);
Ian Rogerse63db272014-07-15 15:36:11 -0700376 return class_loader;
377}
378
Igor Murashkin37743352014-11-13 14:38:00 -0800379std::string CommonRuntimeTest::GetCoreFileLocation(const char* suffix) {
380 CHECK(suffix != nullptr);
381
382 std::string location;
383 if (IsHost()) {
384 const char* host_dir = getenv("ANDROID_HOST_OUT");
385 CHECK(host_dir != NULL);
386 location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
387 } else {
388 location = StringPrintf("/data/art-test/core.%s", suffix);
389 }
390
391 return location;
392}
393
Ian Rogerse63db272014-07-15 15:36:11 -0700394CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700395 vm_->SetCheckJniAbortHook(Hook, &actual_);
Ian Rogerse63db272014-07-15 15:36:11 -0700396}
397
398CheckJniAbortCatcher::~CheckJniAbortCatcher() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700399 vm_->SetCheckJniAbortHook(nullptr, nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -0700400 EXPECT_TRUE(actual_.empty()) << actual_;
401}
402
403void CheckJniAbortCatcher::Check(const char* expected_text) {
404 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
405 << "Expected to find: " << expected_text << "\n"
406 << "In the output : " << actual_;
407 actual_.clear();
408}
409
410void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
411 // We use += because when we're hooking the aborts like this, multiple problems can be found.
412 *reinterpret_cast<std::string*>(data) += reason;
413}
414
415} // namespace art
416
417namespace std {
418
419template <typename T>
420std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
421os << ::art::ToString(rhs);
422return os;
423}
424
425} // namespace std