blob: fdbc9c22c34b70b773e3da23c02710195cb3811a [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>
Ian Rogers700a4022014-05-19 16:49:03 -070027#include <memory>
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -080028
29#include "../../external/icu4c/common/unicode/uvernum.h"
30#include "base/macros.h"
31#include "base/stl_util.h"
32#include "base/stringprintf.h"
33#include "base/unix_file/fd_file.h"
34#include "class_linker.h"
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -080035#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"
Brian Carlstromc0a1b182014-03-04 23:19:06 -080042#include "noop_compiler_callbacks.h"
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -080043#include "oat_file.h"
44#include "object_utils.h"
45#include "os.h"
46#include "runtime.h"
47#include "scoped_thread_state_change.h"
48#include "ScopedLocalRef.h"
49#include "thread.h"
50#include "utils.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_;
Ian Rogers700a4022014-05-19 16:49:03 -0700110 std::unique_ptr<File> file_;
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800111};
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()) {
Andreas Gampe86f56622014-06-25 17:22:59 -0700117 // $ANDROID_ROOT is set on the device, but not necessarily on the host.
118 // But it needs to be set so that icu4c can find its locale data.
119 const char* android_root_from_env = getenv("ANDROID_ROOT");
120 if (android_root_from_env == nullptr) {
121 // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
122 const char* android_host_out = getenv("ANDROID_HOST_OUT");
123 if (android_host_out != nullptr) {
124 setenv("ANDROID_ROOT", android_host_out, 1);
125 } else {
126 // Build it from ANDROID_BUILD_TOP or cwd
127 std::string root;
128 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
129 if (android_build_top != nullptr) {
130 root += android_build_top;
131 } else {
132 // Not set by build server, so default to current directory
133 char* cwd = getcwd(nullptr, 0);
134 setenv("ANDROID_BUILD_TOP", cwd, 1);
135 root += cwd;
136 free(cwd);
137 }
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800138#if defined(__linux__)
Andreas Gampe86f56622014-06-25 17:22:59 -0700139 root += "/out/host/linux-x86";
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800140#elif defined(__APPLE__)
Andreas Gampe86f56622014-06-25 17:22:59 -0700141 root += "/out/host/darwin-x86";
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800142#else
143#error unsupported OS
144#endif
Andreas Gampe86f56622014-06-25 17:22:59 -0700145 setenv("ANDROID_ROOT", root.c_str(), 1);
146 }
147 }
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800148 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
149
150 // Not set by build server, so default
151 if (getenv("ANDROID_HOST_OUT") == nullptr) {
Andreas Gampe86f56622014-06-25 17:22:59 -0700152 setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800153 }
154 }
155
156 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
157 android_data = (IsHost() ? "/tmp/art-data-XXXXXX" : "/data/dalvik-cache/art-data-XXXXXX");
158 if (mkdtemp(&android_data[0]) == nullptr) {
159 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
160 }
161 setenv("ANDROID_DATA", android_data.c_str(), 1);
162 }
163
164 protected:
165 static bool IsHost() {
166 return !kIsTargetBuild;
167 }
168
Andreas Gampe833a4852014-05-21 18:46:59 -0700169 const DexFile* LoadExpectSingleDexFile(const char* location) {
170 std::vector<const DexFile*> dex_files;
171 std::string error_msg;
172 if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
173 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
174 return nullptr;
175 } else {
176 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
177 return dex_files[0];
178 }
179 }
180
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800181 virtual void SetUp() {
182 SetEnvironmentVariables(android_data_);
183 dalvik_cache_.append(android_data_.c_str());
184 dalvik_cache_.append("/dalvik-cache");
185 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
186 ASSERT_EQ(mkdir_result, 0);
187
188 std::string error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700189 java_lang_dex_file_ = LoadExpectSingleDexFile(GetLibCoreDexFileName().c_str());
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800190 boot_class_path_.push_back(java_lang_dex_file_);
191
192 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
193 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
194
195 Runtime::Options options;
196 options.push_back(std::make_pair("bootclasspath", &boot_class_path_));
197 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
198 options.push_back(std::make_pair(min_heap_string.c_str(), nullptr));
199 options.push_back(std::make_pair(max_heap_string.c_str(), nullptr));
200 options.push_back(std::make_pair("compilercallbacks", &callbacks_));
201 SetUpRuntimeOptions(&options);
202 if (!Runtime::Create(options, false)) {
203 LOG(FATAL) << "Failed to create runtime";
204 return;
205 }
206 runtime_.reset(Runtime::Current());
207 class_linker_ = runtime_->GetClassLinker();
208 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
209
210 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
211 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
212 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
213
214 // We're back in native, take the opportunity to initialize well known classes.
215 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
216
217 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
218 // pool is created by the runtime.
219 runtime_->GetHeap()->CreateThreadPool();
220 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
221 }
222
223 // Allow subclases such as CommonCompilerTest to add extra options.
224 virtual void SetUpRuntimeOptions(Runtime::Options *options) {}
225
226 virtual void TearDown() {
227 const char* android_data = getenv("ANDROID_DATA");
228 ASSERT_TRUE(android_data != nullptr);
229 DIR* dir = opendir(dalvik_cache_.c_str());
230 ASSERT_TRUE(dir != nullptr);
231 dirent* e;
232 while ((e = readdir(dir)) != nullptr) {
233 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
234 continue;
235 }
236 std::string filename(dalvik_cache_);
237 filename.push_back('/');
238 filename.append(e->d_name);
239 int unlink_result = unlink(filename.c_str());
240 ASSERT_EQ(0, unlink_result);
241 }
242 closedir(dir);
243 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
244 ASSERT_EQ(0, rmdir_cache_result);
245 int rmdir_data_result = rmdir(android_data_.c_str());
246 ASSERT_EQ(0, rmdir_data_result);
247
248 // icu4c has a fixed 10-element array "gCommonICUDataArray".
249 // If we run > 10 tests, we fill that array and u_setCommonData fails.
250 // There's a function to clear the array, but it's not public...
251 typedef void (*IcuCleanupFn)();
252 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
Andreas Gampe833a4852014-05-21 18:46:59 -0700253 CHECK(sym != nullptr) << dlerror();
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800254 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
255 (*icu_cleanup_fn)();
256
257 STLDeleteElements(&opened_dex_files_);
258
259 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
260 }
261
262 std::string GetLibCoreDexFileName() {
263 return GetDexFileName("core-libart");
264 }
265
266 std::string GetDexFileName(const std::string& jar_prefix) {
267 if (IsHost()) {
268 const char* host_dir = getenv("ANDROID_HOST_OUT");
269 CHECK(host_dir != nullptr);
270 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
271 }
272 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
273 }
274
275 std::string GetTestAndroidRoot() {
276 if (IsHost()) {
277 const char* host_dir = getenv("ANDROID_HOST_OUT");
278 CHECK(host_dir != nullptr);
279 return host_dir;
280 }
281 return GetAndroidRoot();
282 }
283
Andreas Gampe833a4852014-05-21 18:46:59 -0700284 std::vector<const DexFile*> OpenTestDexFiles(const char* name)
285 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800286 CHECK(name != nullptr);
287 std::string filename;
288 if (IsHost()) {
289 filename += getenv("ANDROID_HOST_OUT");
290 filename += "/framework/";
291 } else {
292 filename += "/data/nativetest/art/";
293 }
Ian Rogersafd9acc2014-06-17 08:21:54 -0700294 filename += "art-gtest-";
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800295 filename += name;
296 filename += ".jar";
297 std::string error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700298 std::vector<const DexFile*> dex_files;
299 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
300 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
301 for (const DexFile* dex_file : dex_files) {
302 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
303 CHECK(dex_file->IsReadOnly());
304 }
305 opened_dex_files_.insert(opened_dex_files_.end(), dex_files.begin(), dex_files.end());
306 return dex_files;
307 }
308
309 const DexFile* OpenTestDexFile(const char* name)
310 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
311 std::vector<const DexFile*> vector = OpenTestDexFiles(name);
312 EXPECT_EQ(1U, vector.size());
313 return vector[0];
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800314 }
315
316 jobject LoadDex(const char* dex_name) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700317 std::vector<const DexFile*> dex_files = OpenTestDexFiles(dex_name);
318 CHECK_NE(0U, dex_files.size());
319 for (const DexFile* dex_file : dex_files) {
320 class_linker_->RegisterDexFile(*dex_file);
321 }
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800322 ScopedObjectAccessUnchecked soa(Thread::Current());
323 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
324 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
325 jobject class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
326 soa.Self()->SetClassLoaderOverride(soa.Decode<mirror::ClassLoader*>(class_loader_local.get()));
Andreas Gampe833a4852014-05-21 18:46:59 -0700327 Runtime::Current()->SetCompileTimeClassPath(class_loader, dex_files);
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800328 return class_loader;
329 }
330
331 std::string android_data_;
332 std::string dalvik_cache_;
333 const DexFile* java_lang_dex_file_; // owned by runtime_
334 std::vector<const DexFile*> boot_class_path_;
Ian Rogers700a4022014-05-19 16:49:03 -0700335 std::unique_ptr<Runtime> runtime_;
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800336 // Owned by the runtime
337 ClassLinker* class_linker_;
338
339 private:
340 NoopCompilerCallbacks callbacks_;
341 std::vector<const DexFile*> opened_dex_files_;
342};
343
344// Sets a CheckJni abort hook to catch failures. Note that this will cause CheckJNI to carry on
345// rather than aborting, so be careful!
346class CheckJniAbortCatcher {
347 public:
348 CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
349 vm_->check_jni_abort_hook = Hook;
350 vm_->check_jni_abort_hook_data = &actual_;
351 }
352
353 ~CheckJniAbortCatcher() {
354 vm_->check_jni_abort_hook = nullptr;
355 vm_->check_jni_abort_hook_data = nullptr;
356 EXPECT_TRUE(actual_.empty()) << actual_;
357 }
358
359 void Check(const char* expected_text) {
360 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
361 << "Expected to find: " << expected_text << "\n"
362 << "In the output : " << actual_;
363 actual_.clear();
364 }
365
366 private:
367 static void Hook(void* data, const std::string& reason) {
368 // We use += because when we're hooking the aborts like this, multiple problems can be found.
369 *reinterpret_cast<std::string*>(data) += reason;
370 }
371
372 JavaVMExt* vm_;
373 std::string actual_;
374
375 DISALLOW_COPY_AND_ASSIGN(CheckJniAbortCatcher);
376};
377
378// TODO: These tests were disabled for portable when we went to having
379// MCLinker link LLVM ELF output because we no longer just have code
380// blobs in memory. We'll need to dlopen to load and relocate
381// temporary output to resurrect these tests.
382#define TEST_DISABLED_FOR_PORTABLE() \
383 if (kUsePortableCompiler) { \
384 printf("WARNING: TEST DISABLED FOR PORTABLE\n"); \
385 return; \
386 }
387
Hiroshi Yamauchi05b15d62014-03-19 12:57:56 -0700388// TODO: When heap reference poisoning works with the compiler, get rid of this.
389#define TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING() \
390 if (kPoisonHeapReferences) { \
391 printf("WARNING: TEST DISABLED FOR HEAP REFERENCE POISONING\n"); \
392 return; \
393 }
394
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800395} // namespace art
396
397namespace std {
398
399// TODO: isn't gtest supposed to be able to print STL types for itself?
400template <typename T>
401std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
402 os << ::art::ToString(rhs);
403 return os;
404}
405
406} // namespace std
407
408#endif // ART_RUNTIME_COMMON_RUNTIME_TEST_H_