blob: 1df4c05e368e88660dea167940550f937630dc4e [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()) {
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
Andreas Gampe833a4852014-05-21 18:46:59 -0700159 const DexFile* LoadExpectSingleDexFile(const char* location) {
160 std::vector<const DexFile*> dex_files;
161 std::string error_msg;
162 if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
163 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
164 return nullptr;
165 } else {
166 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
167 return dex_files[0];
168 }
169 }
170
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800171 virtual void SetUp() {
172 SetEnvironmentVariables(android_data_);
173 dalvik_cache_.append(android_data_.c_str());
174 dalvik_cache_.append("/dalvik-cache");
175 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
176 ASSERT_EQ(mkdir_result, 0);
177
178 std::string error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700179 java_lang_dex_file_ = LoadExpectSingleDexFile(GetLibCoreDexFileName().c_str());
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800180 boot_class_path_.push_back(java_lang_dex_file_);
181
182 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
183 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
184
185 Runtime::Options options;
186 options.push_back(std::make_pair("bootclasspath", &boot_class_path_));
187 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
188 options.push_back(std::make_pair(min_heap_string.c_str(), nullptr));
189 options.push_back(std::make_pair(max_heap_string.c_str(), nullptr));
190 options.push_back(std::make_pair("compilercallbacks", &callbacks_));
191 SetUpRuntimeOptions(&options);
192 if (!Runtime::Create(options, false)) {
193 LOG(FATAL) << "Failed to create runtime";
194 return;
195 }
196 runtime_.reset(Runtime::Current());
197 class_linker_ = runtime_->GetClassLinker();
198 class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
199
200 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
201 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
202 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
203
204 // We're back in native, take the opportunity to initialize well known classes.
205 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
206
207 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
208 // pool is created by the runtime.
209 runtime_->GetHeap()->CreateThreadPool();
210 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
211 }
212
213 // Allow subclases such as CommonCompilerTest to add extra options.
214 virtual void SetUpRuntimeOptions(Runtime::Options *options) {}
215
216 virtual void TearDown() {
217 const char* android_data = getenv("ANDROID_DATA");
218 ASSERT_TRUE(android_data != nullptr);
219 DIR* dir = opendir(dalvik_cache_.c_str());
220 ASSERT_TRUE(dir != nullptr);
221 dirent* e;
222 while ((e = readdir(dir)) != nullptr) {
223 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
224 continue;
225 }
226 std::string filename(dalvik_cache_);
227 filename.push_back('/');
228 filename.append(e->d_name);
229 int unlink_result = unlink(filename.c_str());
230 ASSERT_EQ(0, unlink_result);
231 }
232 closedir(dir);
233 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
234 ASSERT_EQ(0, rmdir_cache_result);
235 int rmdir_data_result = rmdir(android_data_.c_str());
236 ASSERT_EQ(0, rmdir_data_result);
237
238 // icu4c has a fixed 10-element array "gCommonICUDataArray".
239 // If we run > 10 tests, we fill that array and u_setCommonData fails.
240 // There's a function to clear the array, but it's not public...
241 typedef void (*IcuCleanupFn)();
242 void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
Andreas Gampe833a4852014-05-21 18:46:59 -0700243 CHECK(sym != nullptr) << dlerror();
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800244 IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
245 (*icu_cleanup_fn)();
246
247 STLDeleteElements(&opened_dex_files_);
248
249 Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
250 }
251
252 std::string GetLibCoreDexFileName() {
253 return GetDexFileName("core-libart");
254 }
255
256 std::string GetDexFileName(const std::string& jar_prefix) {
257 if (IsHost()) {
258 const char* host_dir = getenv("ANDROID_HOST_OUT");
259 CHECK(host_dir != nullptr);
260 return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
261 }
262 return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
263 }
264
265 std::string GetTestAndroidRoot() {
266 if (IsHost()) {
267 const char* host_dir = getenv("ANDROID_HOST_OUT");
268 CHECK(host_dir != nullptr);
269 return host_dir;
270 }
271 return GetAndroidRoot();
272 }
273
Andreas Gampe833a4852014-05-21 18:46:59 -0700274 std::vector<const DexFile*> OpenTestDexFiles(const char* name)
275 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800276 CHECK(name != nullptr);
277 std::string filename;
278 if (IsHost()) {
279 filename += getenv("ANDROID_HOST_OUT");
280 filename += "/framework/";
281 } else {
282 filename += "/data/nativetest/art/";
283 }
Ian Rogersafd9acc2014-06-17 08:21:54 -0700284 filename += "art-gtest-";
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800285 filename += name;
286 filename += ".jar";
287 std::string error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700288 std::vector<const DexFile*> dex_files;
289 bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
290 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
291 for (const DexFile* dex_file : dex_files) {
292 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
293 CHECK(dex_file->IsReadOnly());
294 }
295 opened_dex_files_.insert(opened_dex_files_.end(), dex_files.begin(), dex_files.end());
296 return dex_files;
297 }
298
299 const DexFile* OpenTestDexFile(const char* name)
300 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
301 std::vector<const DexFile*> vector = OpenTestDexFiles(name);
302 EXPECT_EQ(1U, vector.size());
303 return vector[0];
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800304 }
305
306 jobject LoadDex(const char* dex_name) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700307 std::vector<const DexFile*> dex_files = OpenTestDexFiles(dex_name);
308 CHECK_NE(0U, dex_files.size());
309 for (const DexFile* dex_file : dex_files) {
310 class_linker_->RegisterDexFile(*dex_file);
311 }
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800312 ScopedObjectAccessUnchecked soa(Thread::Current());
313 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
314 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
315 jobject class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
316 soa.Self()->SetClassLoaderOverride(soa.Decode<mirror::ClassLoader*>(class_loader_local.get()));
Andreas Gampe833a4852014-05-21 18:46:59 -0700317 Runtime::Current()->SetCompileTimeClassPath(class_loader, dex_files);
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800318 return class_loader;
319 }
320
321 std::string android_data_;
322 std::string dalvik_cache_;
323 const DexFile* java_lang_dex_file_; // owned by runtime_
324 std::vector<const DexFile*> boot_class_path_;
Ian Rogers700a4022014-05-19 16:49:03 -0700325 std::unique_ptr<Runtime> runtime_;
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800326 // Owned by the runtime
327 ClassLinker* class_linker_;
328
329 private:
330 NoopCompilerCallbacks callbacks_;
331 std::vector<const DexFile*> opened_dex_files_;
332};
333
334// Sets a CheckJni abort hook to catch failures. Note that this will cause CheckJNI to carry on
335// rather than aborting, so be careful!
336class CheckJniAbortCatcher {
337 public:
338 CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
339 vm_->check_jni_abort_hook = Hook;
340 vm_->check_jni_abort_hook_data = &actual_;
341 }
342
343 ~CheckJniAbortCatcher() {
344 vm_->check_jni_abort_hook = nullptr;
345 vm_->check_jni_abort_hook_data = nullptr;
346 EXPECT_TRUE(actual_.empty()) << actual_;
347 }
348
349 void Check(const char* expected_text) {
350 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
351 << "Expected to find: " << expected_text << "\n"
352 << "In the output : " << actual_;
353 actual_.clear();
354 }
355
356 private:
357 static void Hook(void* data, const std::string& reason) {
358 // We use += because when we're hooking the aborts like this, multiple problems can be found.
359 *reinterpret_cast<std::string*>(data) += reason;
360 }
361
362 JavaVMExt* vm_;
363 std::string actual_;
364
365 DISALLOW_COPY_AND_ASSIGN(CheckJniAbortCatcher);
366};
367
368// TODO: These tests were disabled for portable when we went to having
369// MCLinker link LLVM ELF output because we no longer just have code
370// blobs in memory. We'll need to dlopen to load and relocate
371// temporary output to resurrect these tests.
372#define TEST_DISABLED_FOR_PORTABLE() \
373 if (kUsePortableCompiler) { \
374 printf("WARNING: TEST DISABLED FOR PORTABLE\n"); \
375 return; \
376 }
377
Hiroshi Yamauchi05b15d62014-03-19 12:57:56 -0700378// TODO: When heap reference poisoning works with the compiler, get rid of this.
379#define TEST_DISABLED_FOR_HEAP_REFERENCE_POISONING() \
380 if (kPoisonHeapReferences) { \
381 printf("WARNING: TEST DISABLED FOR HEAP REFERENCE POISONING\n"); \
382 return; \
383 }
384
Brian Carlstroma1ce1fe2014-02-24 23:23:58 -0800385} // namespace art
386
387namespace std {
388
389// TODO: isn't gtest supposed to be able to print STL types for itself?
390template <typename T>
391std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
392 os << ::art::ToString(rhs);
393 return os;
394}
395
396} // namespace std
397
398#endif // ART_RUNTIME_COMMON_RUNTIME_TEST_H_