common_runtime_test.cc 21.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Ian Rogers's avatar
Ian Rogers committed
17 18
#include "common_runtime_test.h"

19
#include <cstdio>
Ian Rogers's avatar
Ian Rogers committed
20 21 22 23
#include <dirent.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <ScopedLocalRef.h>
24
#include <stdlib.h>
Ian Rogers's avatar
Ian Rogers committed
25 26

#include "../../external/icu/icu4c/source/common/unicode/uvernum.h"
27
#include "art_field-inl.h"
Andreas Gampe's avatar
Andreas Gampe committed
28
#include "base/macros.h"
29
#include "base/logging.h"
Ian Rogers's avatar
Ian Rogers committed
30 31 32 33 34
#include "base/stl_util.h"
#include "base/stringprintf.h"
#include "base/unix_file/fd_file.h"
#include "class_linker.h"
#include "compiler_callbacks.h"
35
#include "dex_file-inl.h"
36
#include "gc_root-inl.h"
Ian Rogers's avatar
Ian Rogers committed
37
#include "gc/heap.h"
38
#include "gtest/gtest.h"
39
#include "handle_scope-inl.h"
Andreas Gampe's avatar
Andreas Gampe committed
40
#include "interpreter/unstarted_runtime.h"
Ian Rogers's avatar
Ian Rogers committed
41
#include "jni_internal.h"
42
#include "mirror/class-inl.h"
Ian Rogers's avatar
Ian Rogers committed
43
#include "mirror/class_loader.h"
44
#include "mem_map.h"
45
#include "native/dalvik_system_DexFile.h"
Ian Rogers's avatar
Ian Rogers committed
46 47
#include "noop_compiler_callbacks.h"
#include "os.h"
48
#include "primitive.h"
Ian Rogers's avatar
Ian Rogers committed
49 50 51 52
#include "runtime-inl.h"
#include "scoped_thread_state_change.h"
#include "thread.h"
#include "well_known_classes.h"
53 54

int main(int argc, char **argv) {
55 56 57
  // Gtests can be very noisy. For example, an executable with multiple tests will trigger native
  // bridge warnings. The following line reduces the minimum log severity to ERROR and suppresses
  // everything else. In case you want to see all messages, comment out the line.
58
  setenv("ANDROID_LOG_TAGS", "*:e", 1);
59

60
  art::InitLogging(argv);
Ian Rogers's avatar
Ian Rogers committed
61
  LOG(::art::INFO) << "Running main() from common_runtime_test.cc...";
62 63 64
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
Ian Rogers's avatar
Ian Rogers committed
65 66 67 68 69 70 71 72 73 74

namespace art {

ScratchFile::ScratchFile() {
  // ANDROID_DATA needs to be set
  CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
      "Are you subclassing RuntimeTest?";
  filename_ = getenv("ANDROID_DATA");
  filename_ += "/TmpFile-XXXXXX";
  int fd = mkstemp(&filename_[0]);
75
  CHECK_NE(-1, fd) << strerror(errno) << " for " << filename_;
76
  file_.reset(new File(fd, GetFilename(), true));
Ian Rogers's avatar
Ian Rogers committed
77 78 79 80 81 82 83
}

ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix) {
  filename_ = other.GetFilename();
  filename_ += suffix;
  int fd = open(filename_.c_str(), O_RDWR | O_CREAT, 0666);
  CHECK_NE(-1, fd);
84
  file_.reset(new File(fd, GetFilename(), true));
Ian Rogers's avatar
Ian Rogers committed
85 86 87
}

ScratchFile::ScratchFile(File* file) {
Mathieu Chartier's avatar
Mathieu Chartier committed
88
  CHECK(file != nullptr);
Ian Rogers's avatar
Ian Rogers committed
89 90 91 92 93 94 95 96 97 98 99 100
  filename_ = file->GetPath();
  file_.reset(file);
}

ScratchFile::~ScratchFile() {
  Unlink();
}

int ScratchFile::GetFd() const {
  return file_->Fd();
}

101
void ScratchFile::Close() {
102 103 104 105 106
  if (file_.get() != nullptr) {
    if (file_->FlushCloseOrErase() != 0) {
      PLOG(WARNING) << "Error closing scratch file.";
    }
  }
107 108 109 110 111 112 113
}

void ScratchFile::Unlink() {
  if (!OS::FileExists(filename_.c_str())) {
    return;
  }
  Close();
Ian Rogers's avatar
Ian Rogers committed
114 115 116 117
  int unlink_result = unlink(filename_.c_str());
  CHECK_EQ(0, unlink_result);
}

Andreas Gampe's avatar
Andreas Gampe committed
118 119
static bool unstarted_initialized_ = false;

120 121 122
CommonRuntimeTestImpl::CommonRuntimeTestImpl() {}

CommonRuntimeTestImpl::~CommonRuntimeTestImpl() {
123 124 125 126
  // Ensure the dex files are cleaned up before the runtime.
  loaded_dex_files_.clear();
  runtime_.reset();
}
Ian Rogers's avatar
Ian Rogers committed
127

128
void CommonRuntimeTestImpl::SetUpAndroidRoot() {
Ian Rogers's avatar
Ian Rogers committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
  if (IsHost()) {
    // $ANDROID_ROOT is set on the device, but not necessarily on the host.
    // But it needs to be set so that icu4c can find its locale data.
    const char* android_root_from_env = getenv("ANDROID_ROOT");
    if (android_root_from_env == nullptr) {
      // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
      const char* android_host_out = getenv("ANDROID_HOST_OUT");
      if (android_host_out != nullptr) {
        setenv("ANDROID_ROOT", android_host_out, 1);
      } else {
        // Build it from ANDROID_BUILD_TOP or cwd
        std::string root;
        const char* android_build_top = getenv("ANDROID_BUILD_TOP");
        if (android_build_top != nullptr) {
          root += android_build_top;
        } else {
          // Not set by build server, so default to current directory
          char* cwd = getcwd(nullptr, 0);
          setenv("ANDROID_BUILD_TOP", cwd, 1);
          root += cwd;
          free(cwd);
        }
#if defined(__linux__)
        root += "/out/host/linux-x86";
#elif defined(__APPLE__)
        root += "/out/host/darwin-x86";
#else
#error unsupported OS
#endif
        setenv("ANDROID_ROOT", root.c_str(), 1);
      }
    }
    setenv("LD_LIBRARY_PATH", ":", 0);  // Required by java.lang.System.<clinit>.

    // Not set by build server, so default
    if (getenv("ANDROID_HOST_OUT") == nullptr) {
      setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
    }
  }
168
}
Ian Rogers's avatar
Ian Rogers committed
169

170
void CommonRuntimeTestImpl::SetUpAndroidData(std::string& android_data) {
Ian Rogers's avatar
Ian Rogers committed
171
  // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
172 173 174 175 176 177 178 179 180 181 182
  if (IsHost()) {
    const char* tmpdir = getenv("TMPDIR");
    if (tmpdir != nullptr && tmpdir[0] != 0) {
      android_data = tmpdir;
    } else {
      android_data = "/tmp";
    }
  } else {
    android_data = "/data/dalvik-cache";
  }
  android_data += "/art-data-XXXXXX";
Ian Rogers's avatar
Ian Rogers committed
183 184 185 186 187 188
  if (mkdtemp(&android_data[0]) == nullptr) {
    PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
  }
  setenv("ANDROID_DATA", android_data.c_str(), 1);
}

189 190
void CommonRuntimeTestImpl::TearDownAndroidData(const std::string& android_data,
                                                bool fail_on_error) {
191 192 193 194 195 196 197
  if (fail_on_error) {
    ASSERT_EQ(rmdir(android_data.c_str()), 0);
  } else {
    rmdir(android_data.c_str());
  }
}

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
// Helper - find directory with the following format:
// ${ANDROID_BUILD_TOP}/${subdir1}/${subdir2}-${version}/${subdir3}/bin/
static std::string GetAndroidToolsDir(const std::string& subdir1,
                                      const std::string& subdir2,
                                      const std::string& subdir3) {
  std::string root;
  const char* android_build_top = getenv("ANDROID_BUILD_TOP");
  if (android_build_top != nullptr) {
    root = android_build_top;
  } else {
    // Not set by build server, so default to current directory
    char* cwd = getcwd(nullptr, 0);
    setenv("ANDROID_BUILD_TOP", cwd, 1);
    root = cwd;
    free(cwd);
  }

  std::string toolsdir = root + "/" + subdir1;
  std::string founddir;
  DIR* dir;
  if ((dir = opendir(toolsdir.c_str())) != nullptr) {
    float maxversion = 0;
    struct dirent* entry;
    while ((entry = readdir(dir)) != nullptr) {
      std::string format = subdir2 + "-%f";
      float version;
      if (std::sscanf(entry->d_name, format.c_str(), &version) == 1) {
        if (version > maxversion) {
          maxversion = version;
          founddir = toolsdir + "/" + entry->d_name + "/" + subdir3 + "/bin/";
        }
      }
    }
    closedir(dir);
  }

  if (founddir.empty()) {
235
    ADD_FAILURE() << "Cannot find Android tools directory.";
236 237 238 239
  }
  return founddir;
}

240
std::string CommonRuntimeTestImpl::GetAndroidHostToolsDir() {
241 242 243 244 245
  return GetAndroidToolsDir("prebuilts/gcc/linux-x86/host",
                            "x86_64-linux-glibc2.15",
                            "x86_64-linux");
}

246
std::string CommonRuntimeTestImpl::GetAndroidTargetToolsDir(InstructionSet isa) {
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  switch (isa) {
    case kArm:
    case kThumb2:
      return GetAndroidToolsDir("prebuilts/gcc/linux-x86/arm",
                                "arm-linux-androideabi",
                                "arm-linux-androideabi");
    case kArm64:
      return GetAndroidToolsDir("prebuilts/gcc/linux-x86/aarch64",
                                "aarch64-linux-android",
                                "aarch64-linux-android");
    case kX86:
    case kX86_64:
      return GetAndroidToolsDir("prebuilts/gcc/linux-x86/x86",
                                "x86_64-linux-android",
                                "x86_64-linux-android");
    case kMips:
    case kMips64:
      return GetAndroidToolsDir("prebuilts/gcc/linux-x86/mips",
                                "mips64el-linux-android",
                                "mips64el-linux-android");
    case kNone:
      break;
  }
  ADD_FAILURE() << "Invalid isa " << isa;
  return "";
}

274
std::string CommonRuntimeTestImpl::GetCoreArtLocation() {
275 276 277
  return GetCoreFileLocation("art");
}

278
std::string CommonRuntimeTestImpl::GetCoreOatLocation() {
279 280
  return GetCoreFileLocation("oat");
}
281

282 283
std::unique_ptr<const DexFile> CommonRuntimeTestImpl::LoadExpectSingleDexFile(
    const char* location) {
284
  std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogers's avatar
Ian Rogers committed
285
  std::string error_msg;
286
  MemMap::Init();
Ian Rogers's avatar
Ian Rogers committed
287 288
  if (!DexFile::Open(location, location, &error_msg, &dex_files)) {
    LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
289
    UNREACHABLE();
Ian Rogers's avatar
Ian Rogers committed
290 291
  } else {
    CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
292
    return std::move(dex_files[0]);
Ian Rogers's avatar
Ian Rogers committed
293 294 295
  }
}

296
void CommonRuntimeTestImpl::SetUp() {
297 298
  SetUpAndroidRoot();
  SetUpAndroidData(android_data_);
Ian Rogers's avatar
Ian Rogers committed
299 300 301 302 303 304 305 306 307 308
  dalvik_cache_.append(android_data_.c_str());
  dalvik_cache_.append("/dalvik-cache");
  int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
  ASSERT_EQ(mkdir_result, 0);

  std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
  std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));


  RuntimeOptions options;
Narayan Kamath's avatar
Narayan Kamath committed
309
  std::string boot_class_path_string = "-Xbootclasspath";
310
  for (const std::string &core_dex_file_name : GetLibCoreDexFileNames()) {
Narayan Kamath's avatar
Narayan Kamath committed
311 312
    boot_class_path_string += ":";
    boot_class_path_string += core_dex_file_name;
313
  }
Ian Rogers's avatar
Ian Rogers committed
314

315
  options.push_back(std::make_pair(boot_class_path_string, nullptr));
Ian Rogers's avatar
Ian Rogers committed
316
  options.push_back(std::make_pair("-Xcheck:jni", nullptr));
317 318
  options.push_back(std::make_pair(min_heap_string, nullptr));
  options.push_back(std::make_pair(max_heap_string, nullptr));
319 320 321

  callbacks_.reset(new NoopCompilerCallbacks());

Ian Rogers's avatar
Ian Rogers committed
322
  SetUpRuntimeOptions(&options);
323

324 325 326 327 328
  // Install compiler-callbacks if SetupRuntimeOptions hasn't deleted them.
  if (callbacks_.get() != nullptr) {
    options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
  }

329
  PreRuntimeCreate();
Ian Rogers's avatar
Ian Rogers committed
330 331 332 333
  if (!Runtime::Create(options, false)) {
    LOG(FATAL) << "Failed to create runtime";
    return;
  }
334
  PostRuntimeCreate();
Ian Rogers's avatar
Ian Rogers committed
335 336 337
  runtime_.reset(Runtime::Current());
  class_linker_ = runtime_->GetClassLinker();
  class_linker_->FixupDexCaches(runtime_->GetResolutionMethod());
338

339 340 341 342 343 344 345 346 347 348 349 350
  // Runtime::Create acquired the mutator_lock_ that is normally given away when we
  // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
  Thread::Current()->TransitionFromRunnableToSuspended(kNative);

  // Get the boot class path from the runtime so it can be used in tests.
  boot_class_path_ = class_linker_->GetBootClassPath();
  ASSERT_FALSE(boot_class_path_.empty());
  java_lang_dex_file_ = boot_class_path_[0];

  FinalizeSetup();
}

351
void CommonRuntimeTestImpl::FinalizeSetup() {
352 353
  // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
  // set up.
Andreas Gampe's avatar
Andreas Gampe committed
354
  if (!unstarted_initialized_) {
355
    interpreter::UnstartedRuntime::Initialize();
Andreas Gampe's avatar
Andreas Gampe committed
356 357
    unstarted_initialized_ = true;
  }
358

359 360 361 362
  {
    ScopedObjectAccess soa(Thread::Current());
    class_linker_->RunRootClinits();
  }
Ian Rogers's avatar
Ian Rogers committed
363 364 365 366 367 368 369 370

  // We're back in native, take the opportunity to initialize well known classes.
  WellKnownClasses::Init(Thread::Current()->GetJniEnv());

  // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
  // pool is created by the runtime.
  runtime_->GetHeap()->CreateThreadPool();
  runtime_->GetHeap()->VerifyHeap();  // Check for heap corruption before the test
371 372
  // Reduce timinig-dependent flakiness in OOME behavior (eg StubTest.AllocObject).
  runtime_->GetHeap()->SetMinIntervalHomogeneousSpaceCompactionByOom(0U);
Ian Rogers's avatar
Ian Rogers committed
373 374
}

375
void CommonRuntimeTestImpl::ClearDirectory(const char* dirpath) {
376 377
  ASSERT_TRUE(dirpath != nullptr);
  DIR* dir = opendir(dirpath);
Ian Rogers's avatar
Ian Rogers committed
378 379
  ASSERT_TRUE(dir != nullptr);
  dirent* e;
380
  struct stat s;
Ian Rogers's avatar
Ian Rogers committed
381 382 383 384
  while ((e = readdir(dir)) != nullptr) {
    if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
      continue;
    }
385
    std::string filename(dirpath);
Ian Rogers's avatar
Ian Rogers committed
386 387
    filename.push_back('/');
    filename.append(e->d_name);
388 389 390 391 392 393 394 395 396 397
    int stat_result = lstat(filename.c_str(), &s);
    ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
    if (S_ISDIR(s.st_mode)) {
      ClearDirectory(filename.c_str());
      int rmdir_result = rmdir(filename.c_str());
      ASSERT_EQ(0, rmdir_result) << filename;
    } else {
      int unlink_result = unlink(filename.c_str());
      ASSERT_EQ(0, unlink_result) << filename;
    }
Ian Rogers's avatar
Ian Rogers committed
398 399
  }
  closedir(dir);
400 401
}

402
void CommonRuntimeTestImpl::TearDown() {
403 404 405
  const char* android_data = getenv("ANDROID_DATA");
  ASSERT_TRUE(android_data != nullptr);
  ClearDirectory(dalvik_cache_.c_str());
Ian Rogers's avatar
Ian Rogers committed
406 407
  int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
  ASSERT_EQ(0, rmdir_cache_result);
408
  TearDownAndroidData(android_data_, true);
409
  dalvik_cache_.clear();
Ian Rogers's avatar
Ian Rogers committed
410 411 412 413 414 415 416 417 418 419 420

  // icu4c has a fixed 10-element array "gCommonICUDataArray".
  // If we run > 10 tests, we fill that array and u_setCommonData fails.
  // There's a function to clear the array, but it's not public...
  typedef void (*IcuCleanupFn)();
  void* sym = dlsym(RTLD_DEFAULT, "u_cleanup_" U_ICU_VERSION_SHORT);
  CHECK(sym != nullptr) << dlerror();
  IcuCleanupFn icu_cleanup_fn = reinterpret_cast<IcuCleanupFn>(sym);
  (*icu_cleanup_fn)();

  Runtime::Current()->GetHeap()->VerifyHeap();  // Check for heap corruption after the test
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

  // Manually closing the JNI libraries.
  // Runtime does not support repeatedly doing JNI->CreateVM, thus we need to manually clean up the
  // dynamic linking loader so that gtests would not fail.
  // Bug: 25785594
  if (runtime_->IsStarted()) {
    {
      // We retrieve the handle by calling dlopen on the library. To close it, we need to call
      // dlclose twice, the first time to undo our dlopen and the second time to actually unload it.
      // See man dlopen.
      void* handle = dlopen("libjavacore.so", RTLD_LAZY);
      dlclose(handle);
      CHECK_EQ(0, dlclose(handle));
    }
    {
      void* handle = dlopen("libopenjdkd.so", RTLD_LAZY);
      dlclose(handle);
      CHECK_EQ(0, dlclose(handle));
    }
  }
Ian Rogers's avatar
Ian Rogers committed
441 442
}

443 444 445
static std::string GetDexFileName(const std::string& jar_prefix, bool host) {
  std::string path;
  if (host) {
Ian Rogers's avatar
Ian Rogers committed
446 447
    const char* host_dir = getenv("ANDROID_HOST_OUT");
    CHECK(host_dir != nullptr);
448 449 450
    path = host_dir;
  } else {
    path = GetAndroidRoot();
Ian Rogers's avatar
Ian Rogers committed
451
  }
452 453 454 455 456 457 458 459

  std::string suffix = host
      ? "-hostdex"                 // The host version.
      : "-testdex";                // The unstripped target version.

  return StringPrintf("%s/framework/%s%s.jar", path.c_str(), jar_prefix.c_str(), suffix.c_str());
}

460
std::vector<std::string> CommonRuntimeTestImpl::GetLibCoreDexFileNames() {
461 462
  return std::vector<std::string>({GetDexFileName("core-oj", IsHost()),
                                   GetDexFileName("core-libart", IsHost())});
Ian Rogers's avatar
Ian Rogers committed
463 464
}

465
std::string CommonRuntimeTestImpl::GetTestAndroidRoot() {
Ian Rogers's avatar
Ian Rogers committed
466 467 468 469 470 471 472 473
  if (IsHost()) {
    const char* host_dir = getenv("ANDROID_HOST_OUT");
    CHECK(host_dir != nullptr);
    return host_dir;
  }
  return GetAndroidRoot();
}

Andreas Gampe's avatar
Andreas Gampe committed
474 475 476 477 478 479 480 481 482 483 484
// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
#ifdef ART_TARGET
#ifndef ART_TARGET_NATIVETEST_DIR
#error "ART_TARGET_NATIVETEST_DIR not set."
#endif
// Wrap it as a string literal.
#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
#else
#define ART_TARGET_NATIVETEST_DIR_STRING ""
#endif

485
std::string CommonRuntimeTestImpl::GetTestDexFileName(const char* name) {
Ian Rogers's avatar
Ian Rogers committed
486 487 488 489 490 491
  CHECK(name != nullptr);
  std::string filename;
  if (IsHost()) {
    filename += getenv("ANDROID_HOST_OUT");
    filename += "/framework/";
  } else {
Andreas Gampe's avatar
Andreas Gampe committed
492
    filename += ART_TARGET_NATIVETEST_DIR_STRING;
Ian Rogers's avatar
Ian Rogers committed
493 494 495 496
  }
  filename += "art-gtest-";
  filename += name;
  filename += ".jar";
497 498 499
  return filename;
}

500 501
std::vector<std::unique_ptr<const DexFile>> CommonRuntimeTestImpl::OpenTestDexFiles(
    const char* name) {
502
  std::string filename = GetTestDexFileName(name);
Ian Rogers's avatar
Ian Rogers committed
503
  std::string error_msg;
504
  std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogers's avatar
Ian Rogers committed
505 506
  bool success = DexFile::Open(filename.c_str(), filename.c_str(), &error_msg, &dex_files);
  CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
507
  for (auto& dex_file : dex_files) {
Ian Rogers's avatar
Ian Rogers committed
508 509 510 511 512 513
    CHECK_EQ(PROT_READ, dex_file->GetPermissions());
    CHECK(dex_file->IsReadOnly());
  }
  return dex_files;
}

514
std::unique_ptr<const DexFile> CommonRuntimeTestImpl::OpenTestDexFile(const char* name) {
515
  std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
Ian Rogers's avatar
Ian Rogers committed
516
  EXPECT_EQ(1U, vector.size());
517
  return std::move(vector[0]);
Ian Rogers's avatar
Ian Rogers committed
518 519
}

520
std::vector<const DexFile*> CommonRuntimeTestImpl::GetDexFiles(jobject jclass_loader) {
521 522 523 524
  std::vector<const DexFile*> ret;

  ScopedObjectAccess soa(Thread::Current());

Mathieu Chartier's avatar
Mathieu Chartier committed
525
  StackHandleScope<2> hs(soa.Self());
526 527 528 529 530 531 532 533 534 535
  Handle<mirror::ClassLoader> class_loader = hs.NewHandle(
      soa.Decode<mirror::ClassLoader*>(jclass_loader));

  DCHECK_EQ(class_loader->GetClass(),
            soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
  DCHECK_EQ(class_loader->GetParent()->GetClass(),
            soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader));

  // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
  // We need to get the DexPathList and loop through it.
Mathieu Chartier's avatar
Mathieu Chartier committed
536 537 538
  ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
  ArtField* dex_file_field =
      soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
539 540 541
  mirror::Object* dex_path_list =
      soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
      GetObject(class_loader.Get());
Mathieu Chartier's avatar
Mathieu Chartier committed
542
  if (dex_path_list != nullptr && dex_file_field!= nullptr && cookie_field != nullptr) {
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
    // DexPathList has an array dexElements of Elements[] which each contain a dex file.
    mirror::Object* dex_elements_obj =
        soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
        GetObject(dex_path_list);
    // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
    // at the mCookie which is a DexFile vector.
    if (dex_elements_obj != nullptr) {
      Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
          hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
      for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
        mirror::Object* element = dex_elements->GetWithoutChecks(i);
        if (element == nullptr) {
          // Should never happen, fall back to java code to throw a NPE.
          break;
        }
        mirror::Object* dex_file = dex_file_field->GetObject(element);
        if (dex_file != nullptr) {
          mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
          DCHECK(long_array != nullptr);
          int32_t long_array_size = long_array->GetLength();
563
          for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
            const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
                long_array->GetWithoutChecks(j)));
            if (cp_dex_file == nullptr) {
              LOG(WARNING) << "Null DexFile";
              continue;
            }
            ret.push_back(cp_dex_file);
          }
        }
      }
    }
  }

  return ret;
}

580
const DexFile* CommonRuntimeTestImpl::GetFirstDexFile(jobject jclass_loader) {
581 582 583 584 585 586 587
  std::vector<const DexFile*> tmp(GetDexFiles(jclass_loader));
  DCHECK(!tmp.empty());
  const DexFile* ret = tmp[0];
  DCHECK(ret != nullptr);
  return ret;
}

588
jobject CommonRuntimeTestImpl::LoadDex(const char* dex_name) {
589 590
  std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name);
  std::vector<const DexFile*> class_path;
Ian Rogers's avatar
Ian Rogers committed
591
  CHECK_NE(0U, dex_files.size());
592 593 594
  for (auto& dex_file : dex_files) {
    class_path.push_back(dex_file.get());
    loaded_dex_files_.push_back(std::move(dex_file));
Ian Rogers's avatar
Ian Rogers committed
595
  }
596

597
  Thread* self = Thread::Current();
598
  jobject class_loader = Runtime::Current()->GetClassLinker()->CreatePathClassLoader(self,
599
                                                                                     class_path);
600
  self->SetClassLoaderOverride(class_loader);
Ian Rogers's avatar
Ian Rogers committed
601 602 603
  return class_loader;
}

604
std::string CommonRuntimeTestImpl::GetCoreFileLocation(const char* suffix) {
605 606 607 608 609
  CHECK(suffix != nullptr);

  std::string location;
  if (IsHost()) {
    const char* host_dir = getenv("ANDROID_HOST_OUT");
Mathieu Chartier's avatar
Mathieu Chartier committed
610
    CHECK(host_dir != nullptr);
611 612 613 614 615 616 617 618
    location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
  } else {
    location = StringPrintf("/data/art-test/core.%s", suffix);
  }

  return location;
}

Ian Rogers's avatar
Ian Rogers committed
619
CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
620
  vm_->SetCheckJniAbortHook(Hook, &actual_);
Ian Rogers's avatar
Ian Rogers committed
621 622 623
}

CheckJniAbortCatcher::~CheckJniAbortCatcher() {
624
  vm_->SetCheckJniAbortHook(nullptr, nullptr);
Ian Rogers's avatar
Ian Rogers committed
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
  EXPECT_TRUE(actual_.empty()) << actual_;
}

void CheckJniAbortCatcher::Check(const char* expected_text) {
  EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
      << "Expected to find: " << expected_text << "\n"
      << "In the output   : " << actual_;
  actual_.clear();
}

void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
  // We use += because when we're hooking the aborts like this, multiple problems can be found.
  *reinterpret_cast<std::string*>(data) += reason;
}

}  // namespace art

namespace std {

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& rhs) {
os << ::art::ToString(rhs);
return os;
}

}  // namespace std