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