blob: cef070369178ceada961b6c19df389e4396d1bb6 [file] [log] [blame]
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -08001/*
2 * Copyright (C) 2011 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
17#ifndef ART_RUNTIME_COMMON_RUNTIME_TEST_H_
18#define ART_RUNTIME_COMMON_RUNTIME_TEST_H_
19
20#include <dirent.h>
21#include <dlfcn.h>
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +000022#include <stdlib.h>
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -080023#include <sys/mman.h>
24#include <sys/stat.h>
25#include <sys/types.h>
26#include <fstream>
27
28#include "../../external/icu4c/common/unicode/uvernum.h"
29#include "base/macros.h"
30#include "base/stl_util.h"
31#include "base/stringprintf.h"
32#include "base/unix_file/fd_file.h"
33#include "class_linker.h"
34#include "compiler_callbacks.h"
35#include "dex_file-inl.h"
36#include "entrypoints/entrypoint_utils.h"
37#include "gc/heap.h"
38#include "gtest/gtest.h"
39#include "instruction_set.h"
40#include "interpreter/interpreter.h"
41#include "mirror/class_loader.h"
42#include "oat_file.h"
43#include "object_utils.h"
44#include "os.h"
45#include "runtime.h"
46#include "scoped_thread_state_change.h"
47#include "ScopedLocalRef.h"
48#include "thread.h"
49#include "utils.h"
50#include "UniquePtr.h"
51#include "verifier/method_verifier.h"
52#include "verifier/method_verifier-inl.h"
53#include "well_known_classes.h"
54
55namespace art {
56
57class ScratchFile {
58 public:
59 ScratchFile() {
60 filename_ = getenv("ANDROID_DATA");
61 filename_ += "/TmpFile-XXXXXX";
62 int fd = mkstemp(&filename_[0]);
63 CHECK_NE(-1, fd);
64 file_.reset(new File(fd, GetFilename()));
65 }
66
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +000067 ScratchFile(const ScratchFile& other, const char* suffix) {
68 filename_ = other.GetFilename();
69 filename_ += suffix;
70 int fd = open(filename_.c_str(), O_RDWR | O_CREAT, 0666);
71 CHECK_NE(-1, fd);
72 file_.reset(new File(fd, GetFilename()));
73 }
74
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -080075 ~ScratchFile() {
76 int unlink_result = unlink(filename_.c_str());
77 CHECK_EQ(0, unlink_result);
78 }
79
80 const std::string& GetFilename() const {
81 return filename_;
82 }
83
84 File* GetFile() const {
85 return file_.get();
86 }
87
88 int GetFd() const {
89 return file_->Fd();
90 }
91
92 private:
93 std::string filename_;
94 UniquePtr<File> file_;
95};
96
97class NoopCompilerCallbacks : public CompilerCallbacks {
98 public:
99 NoopCompilerCallbacks() {}
100 virtual ~NoopCompilerCallbacks() {}
101 virtual bool MethodVerified(verifier::MethodVerifier* verifier) {
102 return true;
103 }
104 virtual void ClassRejected(ClassReference ref) {}
105};
106
107class CommonRuntimeTest : public testing::Test {
108 public:
109 static void SetEnvironmentVariables(std::string& android_data) {
110 if (IsHost()) {
111 // $ANDROID_ROOT is set on the device, but not on the host.
112 // We need to set this so that icu4c can find its locale data.
113 std::string root;
114 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
115 if (android_build_top != nullptr) {
116 root += android_build_top;
117 } else {
118 // Not set by build server, so default to current directory
119 char* cwd = getcwd(nullptr, 0);
120 setenv("ANDROID_BUILD_TOP", cwd, 1);
121 root += cwd;
122 free(cwd);
123 }
124#if defined(__linux__)
125 root += "/out/host/linux-x86";
126#elif defined(__APPLE__)
127 root += "/out/host/darwin-x86";
128#else
129#error unsupported OS
130#endif
131 setenv("ANDROID_ROOT", root.c_str(), 1);
132 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
133
134 // Not set by build server, so default
135 if (getenv("ANDROID_HOST_OUT") == nullptr) {
136 setenv("ANDROID_HOST_OUT", root.c_str(), 1);
137 }
138 }
139
140 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
141 android_data = (IsHost() ? "/tmp/art-data-XXXXXX" : "/data/dalvik-cache/art-data-XXXXXX");
142 if (mkdtemp(&android_data[0]) == nullptr) {
143 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
144 }
145 setenv("ANDROID_DATA", android_data.c_str(), 1);
146 }
147
148 protected:
149 static bool IsHost() {
150 return !kIsTargetBuild;
151 }
152
153 virtual void SetUp() {
154 SetEnvironmentVariables(android_data_);
155 dalvik_cache_.append(android_data_.c_str());
156 dalvik_cache_.append("/dalvik-cache");
157 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
158 ASSERT_EQ(mkdir_result, 0);
159
160 std::string error_msg;
161 java_lang_dex_file_ = DexFile::Open(GetLibCoreDexFileName().c_str(),
162 GetLibCoreDexFileName().c_str(), &error_msg);
163 if (java_lang_dex_file_ == nullptr) {
164 LOG(FATAL) << "Could not open .dex file '" << GetLibCoreDexFileName() << "': "
165 << error_msg << "\n";
166 }
167 boot_class_path_.push_back(java_lang_dex_file_);
168
169 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
170 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
171
172 Runtime::Options options;
173 options.push_back(std::make_pair("bootclasspath", &boot_class_path_));
174 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
175 options.push_back(std::make_pair(min_heap_string.c_str(), nullptr));
176 options.push_back(std::make_pair(max_heap_string.c_str(), nullptr));
177 options.push_back(std::make_pair("compilercallbacks", &callbacks_));
178 SetUpRuntimeOptions(&options);
179 if (!Runtime::Create(options, false)) {
180 LOG(FATAL) << "Failed to create runtime";
181 return;
182 }
183 runtime_.reset(Runtime::Current());
184 class_linker_ = runtime_->GetClassLinker();
185 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
186
187 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
188 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
189 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
190
191 // We're back in native, take the opportunity to initialize well known classes.
192 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
193
194 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
195 // pool is created by the runtime.
196 runtime_->GetHeap()->CreateThreadPool();
197 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
198 }
199
200 // Allow subclases such as CommonCompilerTest to add extra options.
201 virtual void SetUpRuntimeOptions(Runtime::Options *options) {}
202
203 virtual void TearDown() {
204 const char* android_data = getenv("ANDROID_DATA");
205 ASSERT_TRUE(android_data != nullptr);
206 DIR* dir = opendir(dalvik_cache_.c_str());
207 ASSERT_TRUE(dir != nullptr);
208 dirent* e;
209 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);
216 int unlink_result = unlink(filename.c_str());
217 ASSERT_EQ(0, unlink_result);
218 }
219 closedir(dir);
220 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
221 ASSERT_EQ(0, rmdir_cache_result);
222 int rmdir_data_result = rmdir(android_data_.c_str());
223 ASSERT_EQ(0, rmdir_data_result);
224
225 // icu4c has a fixed 10-element array "gCommonICUDataArray".
226 // If we run > 10 tests, we fill that array and u_setCommonData fails.
227 // There's a function to clear the array, but it's not public...
228 typedef void (*IcuCleanupFn)();
229 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
230 CHECK(sym != nullptr);
231 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
232 (*icu_cleanup_fn)();
233
234 STLDeleteElements(&opened_dex_files_);
235
236 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
237 }
238
239 std::string GetLibCoreDexFileName() {
240 return GetDexFileName("core-libart");
241 }
242
243 std::string GetDexFileName(const std::string& jar_prefix) {
244 if (IsHost()) {
245 const char* host_dir = getenv("ANDROID_HOST_OUT");
246 CHECK(host_dir != nullptr);
247 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
248 }
249 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
250 }
251
252 std::string GetTestAndroidRoot() {
253 if (IsHost()) {
254 const char* host_dir = getenv("ANDROID_HOST_OUT");
255 CHECK(host_dir != nullptr);
256 return host_dir;
257 }
258 return GetAndroidRoot();
259 }
260
261 const DexFile* OpenTestDexFile(const char* name) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
262 CHECK(name != nullptr);
263 std::string filename;
264 if (IsHost()) {
265 filename += getenv("ANDROID_HOST_OUT");
266 filename += "/framework/";
267 } else {
268 filename += "/data/nativetest/art/";
269 }
270 filename += "art-test-dex-";
271 filename += name;
272 filename += ".jar";
273 std::string error_msg;
274 const DexFile* dex_file = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg);
275 CHECK(dex_file != nullptr) << "Failed to open '" << filename << "': " << error_msg;
276 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
277 CHECK(dex_file->IsReadOnly());
278 opened_dex_files_.push_back(dex_file);
279 return dex_file;
280 }
281
282 jobject LoadDex(const char* dex_name) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
283 const DexFile* dex_file = OpenTestDexFile(dex_name);
284 CHECK(dex_file != nullptr);
285 class_linker_->RegisterDexFile(*dex_file);
286 std::vector<const DexFile*> class_path;
287 class_path.push_back(dex_file);
288 ScopedObjectAccessUnchecked soa(Thread::Current());
289 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
290 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
291 jobject class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
292 soa.Self()->SetClassLoaderOverride(soa.Decode<mirror::ClassLoader*>(class_loader_local.get()));
293 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path);
294 return class_loader;
295 }
296
297 std::string android_data_;
298 std::string dalvik_cache_;
299 const DexFile* java_lang_dex_file_; // owned by runtime_
300 std::vector<const DexFile*> boot_class_path_;
301 UniquePtr<Runtime> runtime_;
302 // Owned by the runtime
303 ClassLinker* class_linker_;
304
305 private:
306 NoopCompilerCallbacks callbacks_;
307 std::vector<const DexFile*> opened_dex_files_;
308};
309
310// Sets a CheckJni abort hook to catch failures. Note that this will cause CheckJNI to carry on
311// rather than aborting, so be careful!
312class CheckJniAbortCatcher {
313 public:
314 CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
315 vm_->check_jni_abort_hook = Hook;
316 vm_->check_jni_abort_hook_data = &actual_;
317 }
318
319 ~CheckJniAbortCatcher() {
320 vm_->check_jni_abort_hook = nullptr;
321 vm_->check_jni_abort_hook_data = nullptr;
322 EXPECT_TRUE(actual_.empty()) << actual_;
323 }
324
325 void Check(const char* expected_text) {
326 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
327 << "Expected to find: " << expected_text << "\n"
328 << "In the output : " << actual_;
329 actual_.clear();
330 }
331
332 private:
333 static void Hook(void* data, const std::string& reason) {
334 // We use += because when we're hooking the aborts like this, multiple problems can be found.
335 *reinterpret_cast<std::string*>(data) += reason;
336 }
337
338 JavaVMExt* vm_;
339 std::string actual_;
340
341 DISALLOW_COPY_AND_ASSIGN(CheckJniAbortCatcher);
342};
343
344// TODO: These tests were disabled for portable when we went to having
345// MCLinker link LLVM ELF output because we no longer just have code
346// blobs in memory. We'll need to dlopen to load and relocate
347// temporary output to resurrect these tests.
348#define TEST_DISABLED_FOR_PORTABLE() \
349 if (kUsePortableCompiler) { \
350 printf("WARNING: TEST DISABLED FOR PORTABLE\n"); \
351 return; \
352 }
353
354} // namespace art
355
356namespace std {
357
358// TODO: isn't gtest supposed to be able to print STL types for itself?
359template <typename T>
360std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
361 os << ::art::ToString(rhs);
362 return os;
363}
364
365} // namespace std
366
367#endif // ART_RUNTIME_COMMON_RUNTIME_TEST_H_