common_runtime_test.cc revision f896965072343a2d6ad64d46a61112b10b3645dd
1/*
2 * Copyright (C) 2012 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#include "common_runtime_test.h"
18
19#include <dirent.h>
20#include <dlfcn.h>
21#include <fcntl.h>
22#include <ScopedLocalRef.h>
23
24#include "../../external/icu/icu4c/source/common/unicode/uvernum.h"
25#include "base/macros.h"
26#include "base/logging.h"
27#include "base/stl_util.h"
28#include "base/stringprintf.h"
29#include "base/unix_file/fd_file.h"
30#include "class_linker.h"
31#include "compiler_callbacks.h"
32#include "dex_file.h"
33#include "gc_root-inl.h"
34#include "gc/heap.h"
35#include "gtest/gtest.h"
36#include "jni_internal.h"
37#include "mirror/class_loader.h"
38#include "noop_compiler_callbacks.h"
39#include "os.h"
40#include "runtime-inl.h"
41#include "scoped_thread_state_change.h"
42#include "thread.h"
43#include "well_known_classes.h"
44
45int main(int argc, char **argv) {
46  art::InitLogging(argv);
47  LOG(INFO) << "Running main() from common_runtime_test.cc...";
48  testing::InitGoogleTest(&argc, argv);
49  return RUN_ALL_TESTS();
50}
51
52namespace art {
53
54ScratchFile::ScratchFile() {
55  // ANDROID_DATA needs to be set
56  CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
57      "Are you subclassing RuntimeTest?";
58  filename_ = getenv("ANDROID_DATA");
59  filename_ += "/TmpFile-XXXXXX";
60  int fd = mkstemp(&filename_[0]);
61  CHECK_NE(-1, fd);
62  file_.reset(new File(fd, GetFilename()));
63}
64
65ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix) {
66  filename_ = other.GetFilename();
67  filename_ += suffix;
68  int fd = open(filename_.c_str(), O_RDWR | O_CREAT, 0666);
69  CHECK_NE(-1, fd);
70  file_.reset(new File(fd, GetFilename()));
71}
72
73ScratchFile::ScratchFile(File* file) {
74  CHECK(file != NULL);
75  filename_ = file->GetPath();
76  file_.reset(file);
77}
78
79ScratchFile::~ScratchFile() {
80  Unlink();
81}
82
83int ScratchFile::GetFd() const {
84  return file_->Fd();
85}
86
87void ScratchFile::Unlink() {
88  if (!OS::FileExists(filename_.c_str())) {
89    return;
90  }
91  int unlink_result = unlink(filename_.c_str());
92  CHECK_EQ(0, unlink_result);
93}
94
95CommonRuntimeTest::CommonRuntimeTest() {}
96CommonRuntimeTest::~CommonRuntimeTest() {}
97
98void CommonRuntimeTest::SetUpAndroidRoot() {
99  if (IsHost()) {
100    // $ANDROID_ROOT is set on the device, but not necessarily on the host.
101    // But it needs to be set so that icu4c can find its locale data.
102    const char* android_root_from_env = getenv("ANDROID_ROOT");
103    if (android_root_from_env == nullptr) {
104      // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
105      const char* android_host_out = getenv("ANDROID_HOST_OUT");
106      if (android_host_out != nullptr) {
107        setenv("ANDROID_ROOT", android_host_out, 1);
108      } else {
109        // Build it from ANDROID_BUILD_TOP or cwd
110        std::string root;
111        const char* android_build_top = getenv("ANDROID_BUILD_TOP");
112        if (android_build_top != nullptr) {
113          root += android_build_top;
114        } else {
115          // Not set by build server, so default to current directory
116          char* cwd = getcwd(nullptr, 0);
117          setenv("ANDROID_BUILD_TOP", cwd, 1);
118          root += cwd;
119          free(cwd);
120        }
121#if defined(__linux__)
122        root += "/out/host/linux-x86";
123#elif defined(__APPLE__)
124        root += "/out/host/darwin-x86";
125#else
126#error unsupported OS
127#endif
128        setenv("ANDROID_ROOT", root.c_str(), 1);
129      }
130    }
131    setenv("LD_LIBRARY_PATH", ":", 0);  // Required by java.lang.System.<clinit>.
132
133    // Not set by build server, so default
134    if (getenv("ANDROID_HOST_OUT") == nullptr) {
135      setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
136    }
137  }
138}
139
140void CommonRuntimeTest::SetUpAndroidData(std::string& android_data) {
141  // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
142  android_data = (IsHost() ? "/tmp/art-data-XXXXXX" : "/data/dalvik-cache/art-data-XXXXXX");
143  if (mkdtemp(&android_data[0]) == nullptr) {
144    PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
145  }
146  setenv("ANDROID_DATA", android_data.c_str(), 1);
147}
148
149void CommonRuntimeTest::TearDownAndroidData(const std::string& android_data, bool fail_on_error) {
150  if (fail_on_error) {
151    ASSERT_EQ(rmdir(android_data.c_str()), 0);
152  } else {
153    rmdir(android_data.c_str());
154  }
155}
156
157
158const DexFile* CommonRuntimeTest::LoadExpectSingleDexFile(const char* location) {
159  std::vector<const DexFile*> dex_files;
160  std::string error_msg;
161  if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
162    LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
163    return nullptr;
164  } else {
165    CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
166    return dex_files[0];
167  }
168}
169
170void CommonRuntimeTest::SetUp() {
171  SetUpAndroidRoot();
172  SetUpAndroidData(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;
179  java_lang_dex_file_ = LoadExpectSingleDexFile(GetLibCoreDexFileName().c_str());
180  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  callbacks_.reset(new NoopCompilerCallbacks());
186
187  RuntimeOptions options;
188  options.push_back(std::make_pair("bootclasspath", &boot_class_path_));
189  options.push_back(std::make_pair("-Xcheck:jni", nullptr));
190  options.push_back(std::make_pair(min_heap_string.c_str(), nullptr));
191  options.push_back(std::make_pair(max_heap_string.c_str(), nullptr));
192  options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
193  SetUpRuntimeOptions(&options);
194  if (!Runtime::Create(options, false)) {
195    LOG(FATAL) << "Failed to create runtime";
196    return;
197  }
198  runtime_.reset(Runtime::Current());
199  class_linker_ = runtime_->GetClassLinker();
200  class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
201  class_linker_->RunRootClinits();
202
203  // Runtime::Create acquired the mutator_lock_ that is normally given away when we
204  // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
205  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
206
207  // We're back in native, take the opportunity to initialize well known classes.
208  WellKnownClasses::Init(Thread::Current()->GetJniEnv());
209
210  // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
211  // pool is created by the runtime.
212  runtime_->GetHeap()->CreateThreadPool();
213  runtime_->GetHeap()->VerifyHeap();  // Check for heap corruption before the test
214}
215
216void CommonRuntimeTest::ClearDirectory(const char* dirpath) {
217  ASSERT_TRUE(dirpath != nullptr);
218  DIR* dir = opendir(dirpath);
219  ASSERT_TRUE(dir != nullptr);
220  dirent* e;
221  struct stat s;
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 stat_result = lstat(filename.c_str(), &s);
230    ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
231    if (S_ISDIR(s.st_mode)) {
232      ClearDirectory(filename.c_str());
233      int rmdir_result = rmdir(filename.c_str());
234      ASSERT_EQ(0, rmdir_result) << filename;
235    } else {
236      int unlink_result = unlink(filename.c_str());
237      ASSERT_EQ(0, unlink_result) << filename;
238    }
239  }
240  closedir(dir);
241}
242
243void CommonRuntimeTest::TearDown() {
244  const char* android_data = getenv("ANDROID_DATA");
245  ASSERT_TRUE(android_data != nullptr);
246  ClearDirectory(dalvik_cache_.c_str());
247  int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
248  ASSERT_EQ(0, rmdir_cache_result);
249  TearDownAndroidData(android_data_, true);
250
251  // icu4c has a fixed 10-element array "gCommonICUDataArray".
252  // If we run > 10 tests, we fill that array and u_setCommonData fails.
253  // There's a function to clear the array, but it's not public...
254  typedef void (*IcuCleanupFn)();
255  void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
256  CHECK(sym != nullptr) << dlerror();
257  IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
258  (*icu_cleanup_fn)();
259
260  STLDeleteElements(&opened_dex_files_);
261
262  Runtime::Current()->GetHeap()->VerifyHeap();  // Check for heap corruption after the test
263}
264
265std::string CommonRuntimeTest::GetLibCoreDexFileName() {
266  return GetDexFileName("core-libart");
267}
268
269std::string CommonRuntimeTest::GetDexFileName(const std::string& jar_prefix) {
270  if (IsHost()) {
271    const char* host_dir = getenv("ANDROID_HOST_OUT");
272    CHECK(host_dir != nullptr);
273    return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
274  }
275  return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
276}
277
278std::string CommonRuntimeTest::GetTestAndroidRoot() {
279  if (IsHost()) {
280    const char* host_dir = getenv("ANDROID_HOST_OUT");
281    CHECK(host_dir != nullptr);
282    return host_dir;
283  }
284  return GetAndroidRoot();
285}
286
287// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
288#ifdef ART_TARGET
289#ifndef ART_TARGET_NATIVETEST_DIR
290#error "ART_TARGET_NATIVETEST_DIR not set."
291#endif
292// Wrap it as a string literal.
293#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
294#else
295#define ART_TARGET_NATIVETEST_DIR_STRING ""
296#endif
297
298std::vector<const DexFile*> CommonRuntimeTest::OpenTestDexFiles(const char* name) {
299  CHECK(name != nullptr);
300  std::string filename;
301  if (IsHost()) {
302    filename += getenv("ANDROID_HOST_OUT");
303    filename += "/framework/";
304  } else {
305    filename += ART_TARGET_NATIVETEST_DIR_STRING;
306  }
307  filename += "art-gtest-";
308  filename += name;
309  filename += ".jar";
310  std::string error_msg;
311  std::vector<const DexFile*> dex_files;
312  bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
313  CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
314  for (const DexFile* dex_file : dex_files) {
315    CHECK_EQ(PROT_READ, dex_file->GetPermissions());
316    CHECK(dex_file->IsReadOnly());
317  }
318  opened_dex_files_.insert(opened_dex_files_.end(), dex_files.begin(), dex_files.end());
319  return dex_files;
320}
321
322const DexFile* CommonRuntimeTest::OpenTestDexFile(const char* name) {
323  std::vector<const DexFile*> vector = OpenTestDexFiles(name);
324  EXPECT_EQ(1U, vector.size());
325  return vector[0];
326}
327
328jobject CommonRuntimeTest::LoadDex(const char* dex_name) {
329  std::vector<const DexFile*> dex_files = OpenTestDexFiles(dex_name);
330  CHECK_NE(0U, dex_files.size());
331  for (const DexFile* dex_file : dex_files) {
332    class_linker_->RegisterDexFile(*dex_file);
333  }
334  ScopedObjectAccessUnchecked soa(Thread::Current());
335  ScopedLocalRef<jobject> class_loader_local(soa.Env(),
336      soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
337  jobject class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
338  soa.Self()->SetClassLoaderOverride(soa.Decode<mirror::ClassLoader*>(class_loader_local.get()));
339  Runtime::Current()->SetCompileTimeClassPath(class_loader, dex_files);
340  return class_loader;
341}
342
343CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
344  vm_->check_jni_abort_hook = Hook;
345  vm_->check_jni_abort_hook_data = &actual_;
346}
347
348CheckJniAbortCatcher::~CheckJniAbortCatcher() {
349  vm_->check_jni_abort_hook = nullptr;
350  vm_->check_jni_abort_hook_data = nullptr;
351  EXPECT_TRUE(actual_.empty()) << actual_;
352}
353
354void CheckJniAbortCatcher::Check(const char* expected_text) {
355  EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
356      << "Expected to find: " << expected_text << "\n"
357      << "In the output   : " << actual_;
358  actual_.clear();
359}
360
361void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
362  // We use += because when we're hooking the aborts like this, multiple problems can be found.
363  *reinterpret_cast<std::string*>(data) += reason;
364}
365
366}  // namespace art
367
368namespace std {
369
370template <typename T>
371std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
372os << ::art::ToString(rhs);
373return os;
374}
375
376}  // namespace std
377