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