blob: ac6d44b950fae75bffbf145ca7f52f9d91d15bfc [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
Elliott Hughes5ced6722014-07-09 15:31:20 -070029#include "../../external/icu/icu4c/source/common/unicode/uvernum.h"
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -080030#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());
Sebastien Hertz4e99b3d2014-06-24 14:35:40 +0200209 class_linker_->RunRootClinits();
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800210
211 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
212 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
213 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
214
215 // We're back in native, take the opportunity to initialize well known classes.
216 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
217
218 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
219 // pool is created by the runtime.
220 runtime_->GetHeap()->CreateThreadPool();
221 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
222 }
223
224 // Allow subclases such as CommonCompilerTest to add extra options.
225 virtual void SetUpRuntimeOptions(Runtime::Options *options) {}
226
227 virtual void TearDown() {
228 const char* android_data = getenv("ANDROID_DATA");
229 ASSERT_TRUE(android_data != nullptr);
230 DIR* dir = opendir(dalvik_cache_.c_str());
231 ASSERT_TRUE(dir != nullptr);
232 dirent* e;
233 while ((e = readdir(dir)) != nullptr) {
234 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
235 continue;
236 }
237 std::string filename(dalvik_cache_);
238 filename.push_back('/');
239 filename.append(e->d_name);
240 int unlink_result = unlink(filename.c_str());
241 ASSERT_EQ(0, unlink_result);
242 }
243 closedir(dir);
244 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
245 ASSERT_EQ(0, rmdir_cache_result);
246 int rmdir_data_result = rmdir(android_data_.c_str());
247 ASSERT_EQ(0, rmdir_data_result);
248
249 // icu4c has a fixed 10-element array "gCommonICUDataArray".
250 // If we run > 10 tests, we fill that array and u_setCommonData fails.
251 // There's a function to clear the array, but it's not public...
252 typedef void (*IcuCleanupFn)();
253 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
Andreas Gampe833a4852014-05-21 18:46:59 -0700254 CHECK(sym != nullptr) << dlerror();
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800255 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
256 (*icu_cleanup_fn)();
257
258 STLDeleteElements(&opened_dex_files_);
259
260 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
261 }
262
263 std::string GetLibCoreDexFileName() {
264 return GetDexFileName("core-libart");
265 }
266
267 std::string GetDexFileName(const std::string& jar_prefix) {
268 if (IsHost()) {
269 const char* host_dir = getenv("ANDROID_HOST_OUT");
270 CHECK(host_dir != nullptr);
271 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
272 }
273 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
274 }
275
276 std::string GetTestAndroidRoot() {
277 if (IsHost()) {
278 const char* host_dir = getenv("ANDROID_HOST_OUT");
279 CHECK(host_dir != nullptr);
280 return host_dir;
281 }
282 return GetAndroidRoot();
283 }
284
Andreas Gampe833a4852014-05-21 18:46:59 -0700285 std::vector<const DexFile*> OpenTestDexFiles(const char* name)
286 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800287 CHECK(name != nullptr);
288 std::string filename;
289 if (IsHost()) {
290 filename += getenv("ANDROID_HOST_OUT");
291 filename += "/framework/";
292 } else {
293 filename += "/data/nativetest/art/";
294 }
Ian Rogersafd9acc2014-06-17 08:21:54 -0700295 filename += "art-gtest-";
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800296 filename += name;
297 filename += ".jar";
298 std::string error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700299 std::vector<const DexFile*> dex_files;
300 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
301 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
302 for (const DexFile* dex_file : dex_files) {
303 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
304 CHECK(dex_file->IsReadOnly());
305 }
306 opened_dex_files_.insert(opened_dex_files_.end(), dex_files.begin(), dex_files.end());
307 return dex_files;
308 }
309
310 const DexFile* OpenTestDexFile(const char* name)
311 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
312 std::vector<const DexFile*> vector = OpenTestDexFiles(name);
313 EXPECT_EQ(1U, vector.size());
314 return vector[0];
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800315 }
316
317 jobject LoadDex(const char* dex_name) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700318 std::vector<const DexFile*> dex_files = OpenTestDexFiles(dex_name);
319 CHECK_NE(0U, dex_files.size());
320 for (const DexFile* dex_file : dex_files) {
321 class_linker_->RegisterDexFile(*dex_file);
322 }
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800323 ScopedObjectAccessUnchecked soa(Thread::Current());
324 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
325 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
326 jobject class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
327 soa.Self()->SetClassLoaderOverride(soa.Decode<mirror::ClassLoader*>(class_loader_local.get()));
Andreas Gampe833a4852014-05-21 18:46:59 -0700328 Runtime::Current()->SetCompileTimeClassPath(class_loader, dex_files);
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800329 return class_loader;
330 }
331
332 std::string android_data_;
333 std::string dalvik_cache_;
334 const DexFile* java_lang_dex_file_; // owned by runtime_
335 std::vector<const DexFile*> boot_class_path_;
Ian Rogers700a4022014-05-19 16:49:03 -0700336 std::unique_ptr<Runtime> runtime_;
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800337 // Owned by the runtime
338 ClassLinker* class_linker_;
339
340 private:
341 NoopCompilerCallbacks callbacks_;
342 std::vector<const DexFile*> opened_dex_files_;
343};
344
345// Sets a CheckJni abort hook to catch failures. Note that this will cause CheckJNI to carry on
346// rather than aborting, so be careful!
347class CheckJniAbortCatcher {
348 public:
349 CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
350 vm_->check_jni_abort_hook = Hook;
351 vm_->check_jni_abort_hook_data = &actual_;
352 }
353
354 ~CheckJniAbortCatcher() {
355 vm_->check_jni_abort_hook = nullptr;
356 vm_->check_jni_abort_hook_data = nullptr;
357 EXPECT_TRUE(actual_.empty()) << actual_;
358 }
359
360 void Check(const char* expected_text) {
361 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
362 << "Expected to find: " << expected_text << "\n"
363 << "In the output : " << actual_;
364 actual_.clear();
365 }
366
367 private:
368 static void Hook(void* data, const std::string& reason) {
369 // We use += because when we're hooking the aborts like this, multiple problems can be found.
370 *reinterpret_cast<std::string*>(data) += reason;
371 }
372
373 JavaVMExt* vm_;
374 std::string actual_;
375
376 DISALLOW_COPY_AND_ASSIGN(CheckJniAbortCatcher);
377};
378
379// TODO: These tests were disabled for portable when we went to having
380// MCLinker link LLVM ELF output because we no longer just have code
381// blobs in memory. We'll need to dlopen to load and relocate
382// temporary output to resurrect these tests.
383#define TEST_DISABLED_FOR_PORTABLE() \
384 if (kUsePortableCompiler) { \
385 printf("WARNING: TEST DISABLED FOR PORTABLE\n"); \
386 return; \
387 }
388
Hiroshi Yamauchi05b15d62014-03-19 12:57:56 -0700389// TODO: When heap reference poisoning works with the compiler, get rid of this.
390#define TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING() \
391 if (kPoisonHeapReferences) { \
392 printf("WARNING: TEST DISABLED FOR HEAP REFERENCE POISONING\n"); \
393 return; \
394 }
395
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800396} // namespace art
397
398namespace std {
399
400// TODO: isn't gtest supposed to be able to print STL types for itself?
401template <typename T>
402std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
403 os << ::art::ToString(rhs);
404 return os;
405}
406
407} // namespace std
408
409#endif // ART_RUNTIME_COMMON_RUNTIME_TEST_H_