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