common_runtime_test.cc revision c275259449ec57987e52d3ab1eda3272b994488f
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(::art::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(), true));
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(), true));
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::Close() {
88  if (file_.get() != nullptr) {
89    if (file_->FlushCloseOrErase() != 0) {
90      PLOG(WARNING) << "Error closing scratch file.";
91    }
92  }
93}
94
95void ScratchFile::Unlink() {
96  if (!OS::FileExists(filename_.c_str())) {
97    return;
98  }
99  Close();
100  int unlink_result = unlink(filename_.c_str());
101  CHECK_EQ(0, unlink_result);
102}
103
104CommonRuntimeTest::CommonRuntimeTest() {}
105CommonRuntimeTest::~CommonRuntimeTest() {}
106
107void CommonRuntimeTest::SetUpAndroidRoot() {
108  if (IsHost()) {
109    // $ANDROID_ROOT is set on the device, but not necessarily on the host.
110    // But it needs to be set so that icu4c can find its locale data.
111    const char* android_root_from_env = getenv("ANDROID_ROOT");
112    if (android_root_from_env == nullptr) {
113      // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
114      const char* android_host_out = getenv("ANDROID_HOST_OUT");
115      if (android_host_out != nullptr) {
116        setenv("ANDROID_ROOT", android_host_out, 1);
117      } else {
118        // Build it from ANDROID_BUILD_TOP or cwd
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      }
139    }
140    setenv("LD_LIBRARY_PATH", ":", 0);  // Required by java.lang.System.<clinit>.
141
142    // Not set by build server, so default
143    if (getenv("ANDROID_HOST_OUT") == nullptr) {
144      setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
145    }
146  }
147}
148
149void CommonRuntimeTest::SetUpAndroidData(std::string& android_data) {
150  // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
151  if (IsHost()) {
152    const char* tmpdir = getenv("TMPDIR");
153    if (tmpdir != nullptr && tmpdir[0] != 0) {
154      android_data = tmpdir;
155    } else {
156      android_data = "/tmp";
157    }
158  } else {
159    android_data = "/data/dalvik-cache";
160  }
161  android_data += "/art-data-XXXXXX";
162  if (mkdtemp(&android_data[0]) == nullptr) {
163    PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
164  }
165  setenv("ANDROID_DATA", android_data.c_str(), 1);
166}
167
168void CommonRuntimeTest::TearDownAndroidData(const std::string& android_data, bool fail_on_error) {
169  if (fail_on_error) {
170    ASSERT_EQ(rmdir(android_data.c_str()), 0);
171  } else {
172    rmdir(android_data.c_str());
173  }
174}
175
176std::string CommonRuntimeTest::GetCoreArtLocation() {
177  return GetCoreFileLocation("art");
178}
179
180std::string CommonRuntimeTest::GetCoreOatLocation() {
181  return GetCoreFileLocation("oat");
182}
183
184const DexFile* CommonRuntimeTest::LoadExpectSingleDexFile(const char* location) {
185  std::vector<const DexFile*> dex_files;
186  std::string error_msg;
187  if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
188    LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
189    return nullptr;
190  } else {
191    CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
192    return dex_files[0];
193  }
194}
195
196void CommonRuntimeTest::SetUp() {
197  SetUpAndroidRoot();
198  SetUpAndroidData(android_data_);
199  dalvik_cache_.append(android_data_.c_str());
200  dalvik_cache_.append("/dalvik-cache");
201  int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
202  ASSERT_EQ(mkdir_result, 0);
203
204  std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
205  std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
206
207  callbacks_.reset(new NoopCompilerCallbacks());
208
209  RuntimeOptions options;
210  std::string boot_class_path_string = "-Xbootclasspath:" + GetLibCoreDexFileName();
211  options.push_back(std::make_pair(boot_class_path_string, nullptr));
212  options.push_back(std::make_pair("-Xcheck:jni", nullptr));
213  options.push_back(std::make_pair(min_heap_string, nullptr));
214  options.push_back(std::make_pair(max_heap_string, nullptr));
215  options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
216  SetUpRuntimeOptions(&options);
217  if (!Runtime::Create(options, false)) {
218    LOG(FATAL) << "Failed to create runtime";
219    return;
220  }
221  runtime_.reset(Runtime::Current());
222  class_linker_ = runtime_->GetClassLinker();
223  class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
224  class_linker_->RunRootClinits();
225
226  // Runtime::Create acquired the mutator_lock_ that is normally given away when we
227  // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
228  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
229
230  // We're back in native, take the opportunity to initialize well known classes.
231  WellKnownClasses::Init(Thread::Current()->GetJniEnv());
232
233  // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
234  // pool is created by the runtime.
235  runtime_->GetHeap()->CreateThreadPool();
236  runtime_->GetHeap()->VerifyHeap();  // Check for heap corruption before the test
237
238  // Get the boot class path from the runtime so it can be used in tests.
239  boot_class_path_ = class_linker_->GetBootClassPath();
240  ASSERT_FALSE(boot_class_path_.empty());
241  java_lang_dex_file_ = boot_class_path_[0];
242}
243
244void CommonRuntimeTest::ClearDirectory(const char* dirpath) {
245  ASSERT_TRUE(dirpath != nullptr);
246  DIR* dir = opendir(dirpath);
247  ASSERT_TRUE(dir != nullptr);
248  dirent* e;
249  struct stat s;
250  while ((e = readdir(dir)) != nullptr) {
251    if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
252      continue;
253    }
254    std::string filename(dirpath);
255    filename.push_back('/');
256    filename.append(e->d_name);
257    int stat_result = lstat(filename.c_str(), &s);
258    ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
259    if (S_ISDIR(s.st_mode)) {
260      ClearDirectory(filename.c_str());
261      int rmdir_result = rmdir(filename.c_str());
262      ASSERT_EQ(0, rmdir_result) << filename;
263    } else {
264      int unlink_result = unlink(filename.c_str());
265      ASSERT_EQ(0, unlink_result) << filename;
266    }
267  }
268  closedir(dir);
269}
270
271void CommonRuntimeTest::TearDown() {
272  const char* android_data = getenv("ANDROID_DATA");
273  ASSERT_TRUE(android_data != nullptr);
274  ClearDirectory(dalvik_cache_.c_str());
275  int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
276  ASSERT_EQ(0, rmdir_cache_result);
277  TearDownAndroidData(android_data_, true);
278
279  // icu4c has a fixed 10-element array "gCommonICUDataArray".
280  // If we run > 10 tests, we fill that array and u_setCommonData fails.
281  // There's a function to clear the array, but it's not public...
282  typedef void (*IcuCleanupFn)();
283  void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
284  CHECK(sym != nullptr) << dlerror();
285  IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
286  (*icu_cleanup_fn)();
287
288  STLDeleteElements(&opened_dex_files_);
289
290  Runtime::Current()->GetHeap()->VerifyHeap();  // Check for heap corruption after the test
291}
292
293std::string CommonRuntimeTest::GetLibCoreDexFileName() {
294  return GetDexFileName("core-libart");
295}
296
297std::string CommonRuntimeTest::GetDexFileName(const std::string& jar_prefix) {
298  if (IsHost()) {
299    const char* host_dir = getenv("ANDROID_HOST_OUT");
300    CHECK(host_dir != nullptr);
301    return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
302  }
303  return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
304}
305
306std::string CommonRuntimeTest::GetTestAndroidRoot() {
307  if (IsHost()) {
308    const char* host_dir = getenv("ANDROID_HOST_OUT");
309    CHECK(host_dir != nullptr);
310    return host_dir;
311  }
312  return GetAndroidRoot();
313}
314
315// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
316#ifdef ART_TARGET
317#ifndef ART_TARGET_NATIVETEST_DIR
318#error "ART_TARGET_NATIVETEST_DIR not set."
319#endif
320// Wrap it as a string literal.
321#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
322#else
323#define ART_TARGET_NATIVETEST_DIR_STRING ""
324#endif
325
326std::vector<const DexFile*> CommonRuntimeTest::OpenTestDexFiles(const char* name) {
327  CHECK(name != nullptr);
328  std::string filename;
329  if (IsHost()) {
330    filename += getenv("ANDROID_HOST_OUT");
331    filename += "/framework/";
332  } else {
333    filename += ART_TARGET_NATIVETEST_DIR_STRING;
334  }
335  filename += "art-gtest-";
336  filename += name;
337  filename += ".jar";
338  std::string error_msg;
339  std::vector<const DexFile*> dex_files;
340  bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
341  CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
342  for (const DexFile* dex_file : dex_files) {
343    CHECK_EQ(PROT_READ, dex_file->GetPermissions());
344    CHECK(dex_file->IsReadOnly());
345  }
346  opened_dex_files_.insert(opened_dex_files_.end(), dex_files.begin(), dex_files.end());
347  return dex_files;
348}
349
350const DexFile* CommonRuntimeTest::OpenTestDexFile(const char* name) {
351  std::vector<const DexFile*> vector = OpenTestDexFiles(name);
352  EXPECT_EQ(1U, vector.size());
353  return vector[0];
354}
355
356jobject CommonRuntimeTest::LoadDex(const char* dex_name) {
357  std::vector<const DexFile*> dex_files = OpenTestDexFiles(dex_name);
358  CHECK_NE(0U, dex_files.size());
359  for (const DexFile* dex_file : dex_files) {
360    class_linker_->RegisterDexFile(*dex_file);
361  }
362  Thread* self = Thread::Current();
363  JNIEnvExt* env = self->GetJniEnv();
364  ScopedLocalRef<jobject> class_loader_local(env,
365      env->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
366  jobject class_loader = env->NewGlobalRef(class_loader_local.get());
367  self->SetClassLoaderOverride(class_loader_local.get());
368  Runtime::Current()->SetCompileTimeClassPath(class_loader, dex_files);
369  return class_loader;
370}
371
372std::string CommonRuntimeTest::GetCoreFileLocation(const char* suffix) {
373  CHECK(suffix != nullptr);
374
375  std::string location;
376  if (IsHost()) {
377    const char* host_dir = getenv("ANDROID_HOST_OUT");
378    CHECK(host_dir != NULL);
379    location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
380  } else {
381    location = StringPrintf("/data/art-test/core.%s", suffix);
382  }
383
384  return location;
385}
386
387CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
388  vm_->SetCheckJniAbortHook(Hook, &actual_);
389}
390
391CheckJniAbortCatcher::~CheckJniAbortCatcher() {
392  vm_->SetCheckJniAbortHook(nullptr, nullptr);
393  EXPECT_TRUE(actual_.empty()) << actual_;
394}
395
396void CheckJniAbortCatcher::Check(const char* expected_text) {
397  EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
398      << "Expected to find: " << expected_text << "\n"
399      << "In the output   : " << actual_;
400  actual_.clear();
401}
402
403void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
404  // We use += because when we're hooking the aborts like this, multiple problems can be found.
405  *reinterpret_cast<std::string*>(data) += reason;
406}
407
408}  // namespace art
409
410namespace std {
411
412template <typename T>
413std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
414os << ::art::ToString(rhs);
415return os;
416}
417
418}  // namespace std
419