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