blob: 8e363c4fa3b6ad64a1abb9d95b9e35bc87206cdd [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);
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -080047 LOG(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);
62 file_.reset(new File(fd, GetFilename()));
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()));
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 int unlink_result = unlink(filename_.c_str());
92 CHECK_EQ(0, unlink_result);
93}
94
95CommonRuntimeTest::CommonRuntimeTest() {}
96CommonRuntimeTest::~CommonRuntimeTest() {}
97
98void CommonRuntimeTest::SetEnvironmentVariables(std::string& android_data) {
99 if (IsHost()) {
100 // $ANDROID_ROOT is set on the device, but not necessarily on the host.
101 // But it needs to be set so that icu4c can find its locale data.
102 const char* android_root_from_env = getenv("ANDROID_ROOT");
103 if (android_root_from_env == nullptr) {
104 // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
105 const char* android_host_out = getenv("ANDROID_HOST_OUT");
106 if (android_host_out != nullptr) {
107 setenv("ANDROID_ROOT", android_host_out, 1);
108 } else {
109 // Build it from ANDROID_BUILD_TOP or cwd
110 std::string root;
111 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
112 if (android_build_top != nullptr) {
113 root += android_build_top;
114 } else {
115 // Not set by build server, so default to current directory
116 char* cwd = getcwd(nullptr, 0);
117 setenv("ANDROID_BUILD_TOP", cwd, 1);
118 root += cwd;
119 free(cwd);
120 }
121#if defined(__linux__)
122 root += "/out/host/linux-x86";
123#elif defined(__APPLE__)
124 root += "/out/host/darwin-x86";
125#else
126#error unsupported OS
127#endif
128 setenv("ANDROID_ROOT", root.c_str(), 1);
129 }
130 }
131 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
132
133 // Not set by build server, so default
134 if (getenv("ANDROID_HOST_OUT") == nullptr) {
135 setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
136 }
137 }
138
139 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
140 android_data = (IsHost() ? "/tmp/art-data-XXXXXX" : "/data/dalvik-cache/art-data-XXXXXX");
141 if (mkdtemp(&android_data[0]) == nullptr) {
142 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
143 }
144 setenv("ANDROID_DATA", android_data.c_str(), 1);
145}
146
147const DexFile* CommonRuntimeTest::LoadExpectSingleDexFile(const char* location) {
148 std::vector<const DexFile*> dex_files;
149 std::string error_msg;
150 if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
151 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
152 return nullptr;
153 } else {
154 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
155 return dex_files[0];
156 }
157}
158
159void CommonRuntimeTest::SetUp() {
160 SetEnvironmentVariables(android_data_);
161 dalvik_cache_.append(android_data_.c_str());
162 dalvik_cache_.append("/dalvik-cache");
163 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
164 ASSERT_EQ(mkdir_result, 0);
165
166 std::string error_msg;
167 java_lang_dex_file_ = LoadExpectSingleDexFile(GetLibCoreDexFileName().c_str());
168 boot_class_path_.push_back(java_lang_dex_file_);
169
170 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
171 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
172
173 callbacks_.reset(new NoopCompilerCallbacks());
174
175 RuntimeOptions options;
176 options.push_back(std::make_pair("bootclasspath", &boot_class_path_));
177 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
178 options.push_back(std::make_pair(min_heap_string.c_str(), nullptr));
179 options.push_back(std::make_pair(max_heap_string.c_str(), nullptr));
180 options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
181 SetUpRuntimeOptions(&options);
182 if (!Runtime::Create(options, false)) {
183 LOG(FATAL) << "Failed to create runtime";
184 return;
185 }
186 runtime_.reset(Runtime::Current());
187 class_linker_ = runtime_->GetClassLinker();
188 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
189 class_linker_->RunRootClinits();
190
191 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
192 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
193 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
194
195 // We're back in native, take the opportunity to initialize well known classes.
196 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
197
198 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
199 // pool is created by the runtime.
200 runtime_->GetHeap()->CreateThreadPool();
201 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
202}
203
Alex Lighta59dd802014-07-02 16:28:08 -0700204
205void CommonRuntimeTest::ClearDirectory(const char* dirpath) {
206 ASSERT_TRUE(dirpath != nullptr);
207 DIR* dir = opendir(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700208 ASSERT_TRUE(dir != nullptr);
209 dirent* e;
Alex Lighta59dd802014-07-02 16:28:08 -0700210 struct stat s;
Ian Rogerse63db272014-07-15 15:36:11 -0700211 while ((e = readdir(dir)) != nullptr) {
212 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
213 continue;
214 }
215 std::string filename(dalvik_cache_);
216 filename.push_back('/');
217 filename.append(e->d_name);
Alex Lighta59dd802014-07-02 16:28:08 -0700218 int stat_result = lstat(filename.c_str(), &s);
219 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
220 if (S_ISDIR(s.st_mode)) {
221 ClearDirectory(filename.c_str());
222 int rmdir_result = rmdir(filename.c_str());
223 ASSERT_EQ(0, rmdir_result) << filename;
224 } else {
225 int unlink_result = unlink(filename.c_str());
226 ASSERT_EQ(0, unlink_result) << filename;
227 }
Ian Rogerse63db272014-07-15 15:36:11 -0700228 }
229 closedir(dir);
Alex Lighta59dd802014-07-02 16:28:08 -0700230}
231
232void CommonRuntimeTest::TearDown() {
233 const char* android_data = getenv("ANDROID_DATA");
234 ASSERT_TRUE(android_data != nullptr);
235 ClearDirectory(dalvik_cache_.c_str());
Ian Rogerse63db272014-07-15 15:36:11 -0700236 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
237 ASSERT_EQ(0, rmdir_cache_result);
238 int rmdir_data_result = rmdir(android_data_.c_str());
239 ASSERT_EQ(0, rmdir_data_result);
240
241 // icu4c has a fixed 10-element array "gCommonICUDataArray".
242 // If we run > 10 tests, we fill that array and u_setCommonData fails.
243 // There's a function to clear the array, but it's not public...
244 typedef void (*IcuCleanupFn)();
245 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
246 CHECK(sym != nullptr) << dlerror();
247 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
248 (*icu_cleanup_fn)();
249
250 STLDeleteElements(&opened_dex_files_);
251
252 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
253}
254
255std::string CommonRuntimeTest::GetLibCoreDexFileName() {
256 return GetDexFileName("core-libart");
257}
258
259std::string CommonRuntimeTest::GetDexFileName(const std::string& jar_prefix) {
260 if (IsHost()) {
261 const char* host_dir = getenv("ANDROID_HOST_OUT");
262 CHECK(host_dir != nullptr);
263 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
264 }
265 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
266}
267
268std::string CommonRuntimeTest::GetTestAndroidRoot() {
269 if (IsHost()) {
270 const char* host_dir = getenv("ANDROID_HOST_OUT");
271 CHECK(host_dir != nullptr);
272 return host_dir;
273 }
274 return GetAndroidRoot();
275}
276
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700277// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
278#ifdef ART_TARGET
279#ifndef ART_TARGET_NATIVETEST_DIR
280#error "ART_TARGET_NATIVETEST_DIR not set."
281#endif
282// Wrap it as a string literal.
283#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
284#else
285#define ART_TARGET_NATIVETEST_DIR_STRING ""
286#endif
287
Ian Rogerse63db272014-07-15 15:36:11 -0700288std::vector<const DexFile*> CommonRuntimeTest::OpenTestDexFiles(const char* name) {
289 CHECK(name != nullptr);
290 std::string filename;
291 if (IsHost()) {
292 filename += getenv("ANDROID_HOST_OUT");
293 filename += "/framework/";
294 } else {
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700295 filename += ART_TARGET_NATIVETEST_DIR_STRING;
Ian Rogerse63db272014-07-15 15:36:11 -0700296 }
297 filename += "art-gtest-";
298 filename += name;
299 filename += ".jar";
300 std::string error_msg;
301 std::vector<const DexFile*> dex_files;
302 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
303 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
304 for (const DexFile* dex_file : dex_files) {
305 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
306 CHECK(dex_file->IsReadOnly());
307 }
308 opened_dex_files_.insert(opened_dex_files_.end(), dex_files.begin(), dex_files.end());
309 return dex_files;
310}
311
312const DexFile* CommonRuntimeTest::OpenTestDexFile(const char* name) {
313 std::vector<const DexFile*> vector = OpenTestDexFiles(name);
314 EXPECT_EQ(1U, vector.size());
315 return vector[0];
316}
317
318jobject CommonRuntimeTest::LoadDex(const char* dex_name) {
319 std::vector<const DexFile*> dex_files = OpenTestDexFiles(dex_name);
320 CHECK_NE(0U, dex_files.size());
321 for (const DexFile* dex_file : dex_files) {
322 class_linker_->RegisterDexFile(*dex_file);
323 }
324 ScopedObjectAccessUnchecked soa(Thread::Current());
325 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
326 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
327 jobject class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
328 soa.Self()->SetClassLoaderOverride(soa.Decode<mirror::ClassLoader*>(class_loader_local.get()));
329 Runtime::Current()->SetCompileTimeClassPath(class_loader, dex_files);
330 return class_loader;
331}
332
333CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
334 vm_->check_jni_abort_hook = Hook;
335 vm_->check_jni_abort_hook_data = &actual_;
336}
337
338CheckJniAbortCatcher::~CheckJniAbortCatcher() {
339 vm_->check_jni_abort_hook = nullptr;
340 vm_->check_jni_abort_hook_data = nullptr;
341 EXPECT_TRUE(actual_.empty()) << actual_;
342}
343
344void CheckJniAbortCatcher::Check(const char* expected_text) {
345 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
346 << "Expected to find: " << expected_text << "\n"
347 << "In the output : " << actual_;
348 actual_.clear();
349}
350
351void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
352 // We use += because when we're hooking the aborts like this, multiple problems can be found.
353 *reinterpret_cast<std::string*>(data) += reason;
354}
355
356} // namespace art
357
358namespace std {
359
360template <typename T>
361std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
362os << ::art::ToString(rhs);
363return os;
364}
365
366} // namespace std