common_runtime_test.cc revision 892fc96694b51ac7a896dacd75af5b235f955825
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#include <stdlib.h>
24
25#include "../../external/icu/icu4c/source/common/unicode/uvernum.h"
26#include "base/macros.h"
27#include "base/logging.h"
28#include "base/stl_util.h"
29#include "base/stringprintf.h"
30#include "base/unix_file/fd_file.h"
31#include "class_linker.h"
32#include "compiler_callbacks.h"
33#include "dex_file.h"
34#include "gc_root-inl.h"
35#include "gc/heap.h"
36#include "gtest/gtest.h"
37#include "jni_internal.h"
38#include "mirror/class_loader.h"
39#include "mem_map.h"
40#include "noop_compiler_callbacks.h"
41#include "os.h"
42#include "runtime-inl.h"
43#include "scoped_thread_state_change.h"
44#include "thread.h"
45#include "well_known_classes.h"
46
47int main(int argc, char **argv) {
48  // Gtests can be very noisy. For example, an executable with multiple tests will trigger native
49  // bridge warnings. The following line reduces the minimum log severity to ERROR and suppresses
50  // everything else. In case you want to see all messages, comment out the line.
51  setenv("ANDROID_LOG_TAGS", "*:e", 1);
52
53  art::InitLogging(argv);
54  LOG(::art::INFO) << "Running main() from common_runtime_test.cc...";
55  testing::InitGoogleTest(&argc, argv);
56  return RUN_ALL_TESTS();
57}
58
59namespace art {
60
61ScratchFile::ScratchFile() {
62  // ANDROID_DATA needs to be set
63  CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
64      "Are you subclassing RuntimeTest?";
65  filename_ = getenv("ANDROID_DATA");
66  filename_ += "/TmpFile-XXXXXX";
67  int fd = mkstemp(&filename_[0]);
68  CHECK_NE(-1, fd);
69  file_.reset(new File(fd, GetFilename(), true));
70}
71
72ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix) {
73  filename_ = other.GetFilename();
74  filename_ += suffix;
75  int fd = open(filename_.c_str(), O_RDWR | O_CREAT, 0666);
76  CHECK_NE(-1, fd);
77  file_.reset(new File(fd, GetFilename(), true));
78}
79
80ScratchFile::ScratchFile(File* file) {
81  CHECK(file != NULL);
82  filename_ = file->GetPath();
83  file_.reset(file);
84}
85
86ScratchFile::~ScratchFile() {
87  Unlink();
88}
89
90int ScratchFile::GetFd() const {
91  return file_->Fd();
92}
93
94void ScratchFile::Close() {
95  if (file_.get() != nullptr) {
96    if (file_->FlushCloseOrErase() != 0) {
97      PLOG(WARNING) << "Error closing scratch file.";
98    }
99  }
100}
101
102void ScratchFile::Unlink() {
103  if (!OS::FileExists(filename_.c_str())) {
104    return;
105  }
106  Close();
107  int unlink_result = unlink(filename_.c_str());
108  CHECK_EQ(0, unlink_result);
109}
110
111CommonRuntimeTest::CommonRuntimeTest() {}
112CommonRuntimeTest::~CommonRuntimeTest() {
113  // Ensure the dex files are cleaned up before the runtime.
114  loaded_dex_files_.clear();
115  runtime_.reset();
116}
117
118void CommonRuntimeTest::SetUpAndroidRoot() {
119  if (IsHost()) {
120    // $ANDROID_ROOT is set on the device, but not necessarily on the host.
121    // But it needs to be set so that icu4c can find its locale data.
122    const char* android_root_from_env = getenv("ANDROID_ROOT");
123    if (android_root_from_env == nullptr) {
124      // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
125      const char* android_host_out = getenv("ANDROID_HOST_OUT");
126      if (android_host_out != nullptr) {
127        setenv("ANDROID_ROOT", android_host_out, 1);
128      } else {
129        // Build it from ANDROID_BUILD_TOP or cwd
130        std::string root;
131        const char* android_build_top = getenv("ANDROID_BUILD_TOP");
132        if (android_build_top != nullptr) {
133          root += android_build_top;
134        } else {
135          // Not set by build server, so default to current directory
136          char* cwd = getcwd(nullptr, 0);
137          setenv("ANDROID_BUILD_TOP", cwd, 1);
138          root += cwd;
139          free(cwd);
140        }
141#if defined(__linux__)
142        root += "/out/host/linux-x86";
143#elif defined(__APPLE__)
144        root += "/out/host/darwin-x86";
145#else
146#error unsupported OS
147#endif
148        setenv("ANDROID_ROOT", root.c_str(), 1);
149      }
150    }
151    setenv("LD_LIBRARY_PATH", ":", 0);  // Required by java.lang.System.<clinit>.
152
153    // Not set by build server, so default
154    if (getenv("ANDROID_HOST_OUT") == nullptr) {
155      setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
156    }
157  }
158}
159
160void CommonRuntimeTest::SetUpAndroidData(std::string& android_data) {
161  // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
162  if (IsHost()) {
163    const char* tmpdir = getenv("TMPDIR");
164    if (tmpdir != nullptr && tmpdir[0] != 0) {
165      android_data = tmpdir;
166    } else {
167      android_data = "/tmp";
168    }
169  } else {
170    android_data = "/data/dalvik-cache";
171  }
172  android_data += "/art-data-XXXXXX";
173  if (mkdtemp(&android_data[0]) == nullptr) {
174    PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
175  }
176  setenv("ANDROID_DATA", android_data.c_str(), 1);
177}
178
179void CommonRuntimeTest::TearDownAndroidData(const std::string& android_data, bool fail_on_error) {
180  if (fail_on_error) {
181    ASSERT_EQ(rmdir(android_data.c_str()), 0);
182  } else {
183    rmdir(android_data.c_str());
184  }
185}
186
187std::string CommonRuntimeTest::GetCoreArtLocation() {
188  return GetCoreFileLocation("art");
189}
190
191std::string CommonRuntimeTest::GetCoreOatLocation() {
192  return GetCoreFileLocation("oat");
193}
194
195std::unique_ptr<const DexFile> CommonRuntimeTest::LoadExpectSingleDexFile(const char* location) {
196  std::vector<std::unique_ptr<const DexFile>> dex_files;
197  std::string error_msg;
198  MemMap::Init();
199  if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
200    LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
201    UNREACHABLE();
202  } else {
203    CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
204    return std::move(dex_files[0]);
205  }
206}
207
208void CommonRuntimeTest::SetUp() {
209  SetUpAndroidRoot();
210  SetUpAndroidData(android_data_);
211  dalvik_cache_.append(android_data_.c_str());
212  dalvik_cache_.append("/dalvik-cache");
213  int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
214  ASSERT_EQ(mkdir_result, 0);
215
216  std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
217  std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
218
219  callbacks_.reset(new NoopCompilerCallbacks());
220
221  RuntimeOptions options;
222  std::string boot_class_path_string = "-Xbootclasspath:" + GetLibCoreDexFileName();
223  options.push_back(std::make_pair(boot_class_path_string, nullptr));
224  options.push_back(std::make_pair("-Xcheck:jni", nullptr));
225  options.push_back(std::make_pair(min_heap_string, nullptr));
226  options.push_back(std::make_pair(max_heap_string, nullptr));
227  options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
228  SetUpRuntimeOptions(&options);
229
230  PreRuntimeCreate();
231  if (!Runtime::Create(options, false)) {
232    LOG(FATAL) << "Failed to create runtime";
233    return;
234  }
235  PostRuntimeCreate();
236  runtime_.reset(Runtime::Current());
237  class_linker_ = runtime_->GetClassLinker();
238  class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
239  class_linker_->RunRootClinits();
240  boot_class_path_ = class_linker_->GetBootClassPath();
241  java_lang_dex_file_ = boot_class_path_[0];
242
243
244  // Runtime::Create acquired the mutator_lock_ that is normally given away when we
245  // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
246  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
247
248  // We're back in native, take the opportunity to initialize well known classes.
249  WellKnownClasses::Init(Thread::Current()->GetJniEnv());
250
251  // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
252  // pool is created by the runtime.
253  runtime_->GetHeap()->CreateThreadPool();
254  runtime_->GetHeap()->VerifyHeap();  // Check for heap corruption before the test
255
256  // Get the boot class path from the runtime so it can be used in tests.
257  boot_class_path_ = class_linker_->GetBootClassPath();
258  ASSERT_FALSE(boot_class_path_.empty());
259  java_lang_dex_file_ = boot_class_path_[0];
260}
261
262void CommonRuntimeTest::ClearDirectory(const char* dirpath) {
263  ASSERT_TRUE(dirpath != nullptr);
264  DIR* dir = opendir(dirpath);
265  ASSERT_TRUE(dir != nullptr);
266  dirent* e;
267  struct stat s;
268  while ((e = readdir(dir)) != nullptr) {
269    if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
270      continue;
271    }
272    std::string filename(dirpath);
273    filename.push_back('/');
274    filename.append(e->d_name);
275    int stat_result = lstat(filename.c_str(), &s);
276    ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
277    if (S_ISDIR(s.st_mode)) {
278      ClearDirectory(filename.c_str());
279      int rmdir_result = rmdir(filename.c_str());
280      ASSERT_EQ(0, rmdir_result) << filename;
281    } else {
282      int unlink_result = unlink(filename.c_str());
283      ASSERT_EQ(0, unlink_result) << filename;
284    }
285  }
286  closedir(dir);
287}
288
289void CommonRuntimeTest::TearDown() {
290  const char* android_data = getenv("ANDROID_DATA");
291  ASSERT_TRUE(android_data != nullptr);
292  ClearDirectory(dalvik_cache_.c_str());
293  int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
294  ASSERT_EQ(0, rmdir_cache_result);
295  TearDownAndroidData(android_data_, true);
296
297  // icu4c has a fixed 10-element array "gCommonICUDataArray".
298  // If we run > 10 tests, we fill that array and u_setCommonData fails.
299  // There's a function to clear the array, but it's not public...
300  typedef void (*IcuCleanupFn)();
301  void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
302  CHECK(sym != nullptr) << dlerror();
303  IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
304  (*icu_cleanup_fn)();
305
306  Runtime::Current()->GetHeap()->VerifyHeap();  // Check for heap corruption after the test
307}
308
309std::string CommonRuntimeTest::GetLibCoreDexFileName() {
310  return GetDexFileName("core-libart");
311}
312
313std::string CommonRuntimeTest::GetDexFileName(const std::string& jar_prefix) {
314  if (IsHost()) {
315    const char* host_dir = getenv("ANDROID_HOST_OUT");
316    CHECK(host_dir != nullptr);
317    return StringPrintf("%s/framework/%s-hostdex.jar", host_dir, jar_prefix.c_str());
318  }
319  return StringPrintf("%s/framework/%s.jar", GetAndroidRoot(), jar_prefix.c_str());
320}
321
322std::string CommonRuntimeTest::GetTestAndroidRoot() {
323  if (IsHost()) {
324    const char* host_dir = getenv("ANDROID_HOST_OUT");
325    CHECK(host_dir != nullptr);
326    return host_dir;
327  }
328  return GetAndroidRoot();
329}
330
331// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
332#ifdef ART_TARGET
333#ifndef ART_TARGET_NATIVETEST_DIR
334#error "ART_TARGET_NATIVETEST_DIR not set."
335#endif
336// Wrap it as a string literal.
337#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
338#else
339#define ART_TARGET_NATIVETEST_DIR_STRING ""
340#endif
341
342std::string CommonRuntimeTest::GetTestDexFileName(const char* name) {
343  CHECK(name != nullptr);
344  std::string filename;
345  if (IsHost()) {
346    filename += getenv("ANDROID_HOST_OUT");
347    filename += "/framework/";
348  } else {
349    filename += ART_TARGET_NATIVETEST_DIR_STRING;
350  }
351  filename += "art-gtest-";
352  filename += name;
353  filename += ".jar";
354  return filename;
355}
356
357std::vector<std::unique_ptr<const DexFile>> CommonRuntimeTest::OpenTestDexFiles(const char* name) {
358  std::string filename = GetTestDexFileName(name);
359  std::string error_msg;
360  std::vector<std::unique_ptr<const DexFile>> dex_files;
361  bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
362  CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
363  for (auto& dex_file : dex_files) {
364    CHECK_EQ(PROT_READ, dex_file->GetPermissions());
365    CHECK(dex_file->IsReadOnly());
366  }
367  return dex_files;
368}
369
370std::unique_ptr<const DexFile> CommonRuntimeTest::OpenTestDexFile(const char* name) {
371  std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
372  EXPECT_EQ(1U, vector.size());
373  return std::move(vector[0]);
374}
375
376jobject CommonRuntimeTest::LoadDex(const char* dex_name) {
377  std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name);
378  std::vector<const DexFile*> class_path;
379  CHECK_NE(0U, dex_files.size());
380  for (auto& dex_file : dex_files) {
381    class_path.push_back(dex_file.get());
382    class_linker_->RegisterDexFile(*dex_file);
383    loaded_dex_files_.push_back(std::move(dex_file));
384  }
385  Thread* self = Thread::Current();
386  JNIEnvExt* env = self->GetJniEnv();
387  ScopedLocalRef<jobject> class_loader_local(env,
388      env->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
389  jobject class_loader = env->NewGlobalRef(class_loader_local.get());
390  self->SetClassLoaderOverride(class_loader_local.get());
391  Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path);
392  return class_loader;
393}
394
395std::string CommonRuntimeTest::GetCoreFileLocation(const char* suffix) {
396  CHECK(suffix != nullptr);
397
398  std::string location;
399  if (IsHost()) {
400    const char* host_dir = getenv("ANDROID_HOST_OUT");
401    CHECK(host_dir != NULL);
402    location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
403  } else {
404    location = StringPrintf("/data/art-test/core.%s", suffix);
405  }
406
407  return location;
408}
409
410CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
411  vm_->SetCheckJniAbortHook(Hook, &actual_);
412}
413
414CheckJniAbortCatcher::~CheckJniAbortCatcher() {
415  vm_->SetCheckJniAbortHook(nullptr, nullptr);
416  EXPECT_TRUE(actual_.empty()) << actual_;
417}
418
419void CheckJniAbortCatcher::Check(const char* expected_text) {
420  EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
421      << "Expected to find: " << expected_text << "\n"
422      << "In the output   : " << actual_;
423  actual_.clear();
424}
425
426void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
427  // We use += because when we're hooking the aborts like this, multiple problems can be found.
428  *reinterpret_cast<std::string*>(data) += reason;
429}
430
431}  // namespace art
432
433namespace std {
434
435template <typename T>
436std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
437os << ::art::ToString(rhs);
438return os;
439}
440
441}  // namespace std
442