blob: 03b33e962a903a540559047dd881cba6776d39f1 [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
87void ScratchFile::Unlink() {
88 if (!OS::FileExists(filename_.c_str())) {
89 return;
90 }
Andreas Gampe4303ba92014-11-06 01:00:46 -080091 if (file_.get() != nullptr) {
92 if (file_->FlushCloseOrErase() != 0) {
93 PLOG(WARNING) << "Error closing scratch file.";
94 }
95 }
Ian Rogerse63db272014-07-15 15:36:11 -070096 int unlink_result = unlink(filename_.c_str());
97 CHECK_EQ(0, unlink_result);
98}
99
100CommonRuntimeTest::CommonRuntimeTest() {}
101CommonRuntimeTest::~CommonRuntimeTest() {}
102
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700103void CommonRuntimeTest::SetUpAndroidRoot() {
Ian Rogerse63db272014-07-15 15:36:11 -0700104 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 }
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700143}
Ian Rogerse63db272014-07-15 15:36:11 -0700144
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700145void CommonRuntimeTest::SetUpAndroidData(std::string& android_data) {
Ian Rogerse63db272014-07-15 15:36:11 -0700146 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
Andreas Gampe5a79fde2014-08-06 13:12:26 -0700147 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";
Ian Rogerse63db272014-07-15 15:36:11 -0700158 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
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700164void 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
172
Ian Rogerse63db272014-07-15 15:36:11 -0700173const DexFile* CommonRuntimeTest::LoadExpectSingleDexFile(const char* location) {
174 std::vector<const DexFile*> dex_files;
175 std::string error_msg;
176 if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
177 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
178 return nullptr;
179 } else {
180 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
181 return dex_files[0];
182 }
183}
184
185void CommonRuntimeTest::SetUp() {
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700186 SetUpAndroidRoot();
187 SetUpAndroidData(android_data_);
Ian Rogerse63db272014-07-15 15:36:11 -0700188 dalvik_cache_.append(android_data_.c_str());
189 dalvik_cache_.append("/dalvik-cache");
190 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
191 ASSERT_EQ(mkdir_result, 0);
192
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700193 MemMap::Init(); // For LoadExpectSingleDexFile
194
Ian Rogerse63db272014-07-15 15:36:11 -0700195 std::string error_msg;
196 java_lang_dex_file_ = LoadExpectSingleDexFile(GetLibCoreDexFileName().c_str());
197 boot_class_path_.push_back(java_lang_dex_file_);
198
199 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
200 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
201
202 callbacks_.reset(new NoopCompilerCallbacks());
203
204 RuntimeOptions options;
205 options.push_back(std::make_pair("bootclasspath", &boot_class_path_));
206 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
207 options.push_back(std::make_pair(min_heap_string.c_str(), nullptr));
208 options.push_back(std::make_pair(max_heap_string.c_str(), nullptr));
209 options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
210 SetUpRuntimeOptions(&options);
211 if (!Runtime::Create(options, false)) {
212 LOG(FATAL) << "Failed to create runtime";
213 return;
214 }
215 runtime_.reset(Runtime::Current());
216 class_linker_ = runtime_->GetClassLinker();
217 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
218 class_linker_->RunRootClinits();
219
220 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
221 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
222 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
223
224 // We're back in native, take the opportunity to initialize well known classes.
225 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
226
227 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
228 // pool is created by the runtime.
229 runtime_->GetHeap()->CreateThreadPool();
230 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
231}
232
Alex Lighta59dd802014-07-02 16:28:08 -0700233void CommonRuntimeTest::ClearDirectory(const char* dirpath) {
234 ASSERT_TRUE(dirpath != nullptr);
235 DIR* dir = opendir(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700236 ASSERT_TRUE(dir != nullptr);
237 dirent* e;
Alex Lighta59dd802014-07-02 16:28:08 -0700238 struct stat s;
Ian Rogerse63db272014-07-15 15:36:11 -0700239 while ((e = readdir(dir)) != nullptr) {
240 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
241 continue;
242 }
Jeff Haof0a3f092014-07-24 16:26:09 -0700243 std::string filename(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700244 filename.push_back('/');
245 filename.append(e->d_name);
Alex Lighta59dd802014-07-02 16:28:08 -0700246 int stat_result = lstat(filename.c_str(), &s);
247 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
248 if (S_ISDIR(s.st_mode)) {
249 ClearDirectory(filename.c_str());
250 int rmdir_result = rmdir(filename.c_str());
251 ASSERT_EQ(0, rmdir_result) << filename;
252 } else {
253 int unlink_result = unlink(filename.c_str());
254 ASSERT_EQ(0, unlink_result) << filename;
255 }
Ian Rogerse63db272014-07-15 15:36:11 -0700256 }
257 closedir(dir);
Alex Lighta59dd802014-07-02 16:28:08 -0700258}
259
260void CommonRuntimeTest::TearDown() {
261 const char* android_data = getenv("ANDROID_DATA");
262 ASSERT_TRUE(android_data != nullptr);
263 ClearDirectory(dalvik_cache_.c_str());
Ian Rogerse63db272014-07-15 15:36:11 -0700264 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
265 ASSERT_EQ(0, rmdir_cache_result);
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700266 TearDownAndroidData(android_data_, true);
Ian Rogerse63db272014-07-15 15:36:11 -0700267
268 // icu4c has a fixed 10-element array "gCommonICUDataArray".
269 // If we run > 10 tests, we fill that array and u_setCommonData fails.
270 // There's a function to clear the array, but it's not public...
271 typedef void (*IcuCleanupFn)();
272 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
273 CHECK(sym != nullptr) << dlerror();
274 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
275 (*icu_cleanup_fn)();
276
277 STLDeleteElements(&opened_dex_files_);
278
279 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
280}
281
282std::string CommonRuntimeTest::GetLibCoreDexFileName() {
283 return GetDexFileName("core-libart");
284}
285
286std::string CommonRuntimeTest::GetDexFileName(const std::string& jar_prefix) {
287 if (IsHost()) {
288 const char* host_dir = getenv("ANDROID_HOST_OUT");
289 CHECK(host_dir != nullptr);
290 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
291 }
292 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
293}
294
295std::string CommonRuntimeTest::GetTestAndroidRoot() {
296 if (IsHost()) {
297 const char* host_dir = getenv("ANDROID_HOST_OUT");
298 CHECK(host_dir != nullptr);
299 return host_dir;
300 }
301 return GetAndroidRoot();
302}
303
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700304// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
305#ifdef ART_TARGET
306#ifndef ART_TARGET_NATIVETEST_DIR
307#error "ART_TARGET_NATIVETEST_DIR not set."
308#endif
309// Wrap it as a string literal.
310#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
311#else
312#define ART_TARGET_NATIVETEST_DIR_STRING ""
313#endif
314
Ian Rogerse63db272014-07-15 15:36:11 -0700315std::vector<const DexFile*> CommonRuntimeTest::OpenTestDexFiles(const char* name) {
316 CHECK(name != nullptr);
317 std::string filename;
318 if (IsHost()) {
319 filename += getenv("ANDROID_HOST_OUT");
320 filename += "/framework/";
321 } else {
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700322 filename += ART_TARGET_NATIVETEST_DIR_STRING;
Ian Rogerse63db272014-07-15 15:36:11 -0700323 }
324 filename += "art-gtest-";
325 filename += name;
326 filename += ".jar";
327 std::string error_msg;
328 std::vector<const DexFile*> dex_files;
329 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
330 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
331 for (const DexFile* dex_file : dex_files) {
332 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
333 CHECK(dex_file->IsReadOnly());
334 }
335 opened_dex_files_.insert(opened_dex_files_.end(), dex_files.begin(), dex_files.end());
336 return dex_files;
337}
338
339const DexFile* CommonRuntimeTest::OpenTestDexFile(const char* name) {
340 std::vector<const DexFile*> vector = OpenTestDexFiles(name);
341 EXPECT_EQ(1U, vector.size());
342 return vector[0];
343}
344
345jobject CommonRuntimeTest::LoadDex(const char* dex_name) {
346 std::vector<const DexFile*> dex_files = OpenTestDexFiles(dex_name);
347 CHECK_NE(0U, dex_files.size());
348 for (const DexFile* dex_file : dex_files) {
349 class_linker_->RegisterDexFile(*dex_file);
350 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700351 Thread* self = Thread::Current();
352 JNIEnvExt* env = self->GetJniEnv();
353 ScopedLocalRef<jobject> class_loader_local(env,
354 env->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
355 jobject class_loader = env->NewGlobalRef(class_loader_local.get());
356 self->SetClassLoaderOverride(class_loader_local.get());
Ian Rogerse63db272014-07-15 15:36:11 -0700357 Runtime::Current()->SetCompileTimeClassPath(class_loader, dex_files);
358 return class_loader;
359}
360
361CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700362 vm_->SetCheckJniAbortHook(Hook, &actual_);
Ian Rogerse63db272014-07-15 15:36:11 -0700363}
364
365CheckJniAbortCatcher::~CheckJniAbortCatcher() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700366 vm_->SetCheckJniAbortHook(nullptr, nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -0700367 EXPECT_TRUE(actual_.empty()) << actual_;
368}
369
370void CheckJniAbortCatcher::Check(const char* expected_text) {
371 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
372 << "Expected to find: " << expected_text << "\n"
373 << "In the output : " << actual_;
374 actual_.clear();
375}
376
377void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
378 // We use += because when we're hooking the aborts like this, multiple problems can be found.
379 *reinterpret_cast<std::string*>(data) += reason;
380}
381
382} // namespace art
383
384namespace std {
385
386template <typename T>
387std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
388os << ::art::ToString(rhs);
389return os;
390}
391
392} // namespace std