common_runtime_test.cc revision 5a79fdecffbea657ebecd4cf19078925239eb1c3
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::SetEnvironmentVariables(std::string& android_data) {
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  // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
140  if (IsHost()) {
141    const char* tmpdir = getenv("TMPDIR");
142    if (tmpdir != nullptr && tmpdir[0] != 0) {
143      android_data = tmpdir;
144    } else {
145      android_data = "/tmp";
146    }
147  } else {
148    android_data = "/data/dalvik-cache";
149  }
150  android_data += "/art-data-XXXXXX";
151  if (mkdtemp(&android_data[0]) == nullptr) {
152    PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
153  }
154  setenv("ANDROID_DATA", android_data.c_str(), 1);
155}
156
157const DexFile* CommonRuntimeTest::LoadExpectSingleDexFile(const char* location) {
158  std::vector<const DexFile*> dex_files;
159  std::string error_msg;
160  if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
161    LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
162    return nullptr;
163  } else {
164    CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
165    return dex_files[0];
166  }
167}
168
169void CommonRuntimeTest::SetUp() {
170  SetEnvironmentVariables(android_data_);
171  dalvik_cache_.append(android_data_.c_str());
172  dalvik_cache_.append("/dalvik-cache");
173  int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
174  ASSERT_EQ(mkdir_result, 0);
175
176  std::string error_msg;
177  java_lang_dex_file_ = LoadExpectSingleDexFile(GetLibCoreDexFileName().c_str());
178  boot_class_path_.push_back(java_lang_dex_file_);
179
180  std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
181  std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
182
183  callbacks_.reset(new NoopCompilerCallbacks());
184
185  RuntimeOptions 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_.get()));
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  class_linker_->RunRootClinits();
200
201  // Runtime::Create acquired the mutator_lock_ that is normally given away when we
202  // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
203  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
204
205  // We're back in native, take the opportunity to initialize well known classes.
206  WellKnownClasses::Init(Thread::Current()->GetJniEnv());
207
208  // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
209  // pool is created by the runtime.
210  runtime_->GetHeap()->CreateThreadPool();
211  runtime_->GetHeap()->VerifyHeap();  // Check for heap corruption before the test
212}
213
214
215void CommonRuntimeTest::ClearDirectory(const char* dirpath) {
216  ASSERT_TRUE(dirpath != nullptr);
217  DIR* dir = opendir(dirpath);
218  ASSERT_TRUE(dir != nullptr);
219  dirent* e;
220  struct stat s;
221  while ((e = readdir(dir)) != nullptr) {
222    if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
223      continue;
224    }
225    std::string filename(dirpath);
226    filename.push_back('/');
227    filename.append(e->d_name);
228    int stat_result = lstat(filename.c_str(), &s);
229    ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
230    if (S_ISDIR(s.st_mode)) {
231      ClearDirectory(filename.c_str());
232      int rmdir_result = rmdir(filename.c_str());
233      ASSERT_EQ(0, rmdir_result) << filename;
234    } else {
235      int unlink_result = unlink(filename.c_str());
236      ASSERT_EQ(0, unlink_result) << filename;
237    }
238  }
239  closedir(dir);
240}
241
242void CommonRuntimeTest::TearDown() {
243  const char* android_data = getenv("ANDROID_DATA");
244  ASSERT_TRUE(android_data != nullptr);
245  ClearDirectory(dalvik_cache_.c_str());
246  int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
247  ASSERT_EQ(0, rmdir_cache_result);
248  int rmdir_data_result = rmdir(android_data_.c_str());
249  ASSERT_EQ(0, rmdir_data_result);
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::GetLibCoreOatFileName() {
279  return GetOatFileName("core");
280}
281
282std::string CommonRuntimeTest::GetOatFileName(const std::string& oat_prefix) {
283  if (IsHost()) {
284    const char* host_dir = getenv("ANDROID_HOST_OUT");
285    CHECK(host_dir != nullptr);
286    return StringPrintf("%s/framework/%s.art", host_dir, oat_prefix.c_str());
287  }
288  return StringPrintf("%s/framework/%s.art", GetAndroidRoot(), oat_prefix.c_str());
289}
290
291std::string CommonRuntimeTest::GetTestAndroidRoot() {
292  if (IsHost()) {
293    const char* host_dir = getenv("ANDROID_HOST_OUT");
294    CHECK(host_dir != nullptr);
295    return host_dir;
296  }
297  return GetAndroidRoot();
298}
299
300// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
301#ifdef ART_TARGET
302#ifndef ART_TARGET_NATIVETEST_DIR
303#error "ART_TARGET_NATIVETEST_DIR not set."
304#endif
305// Wrap it as a string literal.
306#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
307#else
308#define ART_TARGET_NATIVETEST_DIR_STRING ""
309#endif
310
311std::vector<const DexFile*> CommonRuntimeTest::OpenTestDexFiles(const char* name) {
312  CHECK(name != nullptr);
313  std::string filename;
314  if (IsHost()) {
315    filename += getenv("ANDROID_HOST_OUT");
316    filename += "/framework/";
317  } else {
318    filename += ART_TARGET_NATIVETEST_DIR_STRING;
319  }
320  filename += "art-gtest-";
321  filename += name;
322  filename += ".jar";
323  std::string error_msg;
324  std::vector<const DexFile*> dex_files;
325  bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
326  CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
327  for (const DexFile* dex_file : dex_files) {
328    CHECK_EQ(PROT_READ, dex_file->GetPermissions());
329    CHECK(dex_file->IsReadOnly());
330  }
331  opened_dex_files_.insert(opened_dex_files_.end(), dex_files.begin(), dex_files.end());
332  return dex_files;
333}
334
335const DexFile* CommonRuntimeTest::OpenTestDexFile(const char* name) {
336  std::vector<const DexFile*> vector = OpenTestDexFiles(name);
337  EXPECT_EQ(1U, vector.size());
338  return vector[0];
339}
340
341jobject CommonRuntimeTest::LoadDex(const char* dex_name) {
342  std::vector<const DexFile*> dex_files = OpenTestDexFiles(dex_name);
343  CHECK_NE(0U, dex_files.size());
344  for (const DexFile* dex_file : dex_files) {
345    class_linker_->RegisterDexFile(*dex_file);
346  }
347  ScopedObjectAccessUnchecked soa(Thread::Current());
348  ScopedLocalRef<jobject> class_loader_local(soa.Env(),
349      soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
350  jobject class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
351  soa.Self()->SetClassLoaderOverride(soa.Decode<mirror::ClassLoader*>(class_loader_local.get()));
352  Runtime::Current()->SetCompileTimeClassPath(class_loader, dex_files);
353  return class_loader;
354}
355
356CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
357  vm_->check_jni_abort_hook = Hook;
358  vm_->check_jni_abort_hook_data = &actual_;
359}
360
361CheckJniAbortCatcher::~CheckJniAbortCatcher() {
362  vm_->check_jni_abort_hook = nullptr;
363  vm_->check_jni_abort_hook_data = nullptr;
364  EXPECT_TRUE(actual_.empty()) << actual_;
365}
366
367void CheckJniAbortCatcher::Check(const char* expected_text) {
368  EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
369      << "Expected to find: " << expected_text << "\n"
370      << "In the output   : " << actual_;
371  actual_.clear();
372}
373
374void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
375  // We use += because when we're hooking the aborts like this, multiple problems can be found.
376  *reinterpret_cast<std::string*>(data) += reason;
377}
378
379}  // namespace art
380
381namespace std {
382
383template <typename T>
384std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
385os << ::art::ToString(rhs);
386return os;
387}
388
389}  // namespace std
390