blob: f6a5efc547824cf1c2fa0cc3aad7b1c1cff0c0ce [file] [log] [blame]
Elliott Hugheseb02a122012-06-12 11:35:40 -07001/*
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
Ian Rogerse63db272014-07-15 15:36:11 -070017#include "common_runtime_test.h"
18
19#include <dirent.h>
20#include <dlfcn.h>
21#include <fcntl.h>
Andreas Gampe369810a2015-01-14 19:53:31 -080022#include <stdlib.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070023#include <cstdio>
Andreas Gampe373a9b52017-10-18 09:01:57 -070024#include "nativehelper/scoped_local_ref.h"
Ian Rogerse63db272014-07-15 15:36:11 -070025
Andreas Gampe46ee31b2016-12-14 10:11:49 -080026#include "android-base/stringprintf.h"
Andreas Gampefdb7a612017-11-01 15:11:13 -070027#include <unicode/uvernum.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080028
Mathieu Chartiere401d142015-04-22 13:56:20 -070029#include "art_field-inl.h"
David Sehr891a50e2017-10-27 17:01:07 -070030#include "base/file_utils.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080031#include "base/logging.h"
Steven Morelande431e272017-07-18 16:53:49 -070032#include "base/macros.h"
David Sehr79e26072018-04-06 17:58:50 -070033#include "base/mem_map.h"
David Sehrc431b9d2018-03-02 12:01:51 -080034#include "base/mutex.h"
35#include "base/os.h"
Andreas Gampedcc528d2017-12-07 13:37:10 -080036#include "base/runtime_debug.h"
Ian Rogerse63db272014-07-15 15:36:11 -070037#include "base/stl_util.h"
Ian Rogerse63db272014-07-15 15:36:11 -070038#include "base/unix_file/fd_file.h"
39#include "class_linker.h"
Andreas Gampeb8e7c372018-02-20 18:24:55 -080040#include "class_loader_utils.h"
Ian Rogerse63db272014-07-15 15:36:11 -070041#include "compiler_callbacks.h"
David Sehr013fd802018-01-11 22:55:24 -080042#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080043#include "dex/dex_file-inl.h"
44#include "dex/dex_file_loader.h"
David Sehr67bf42e2018-02-26 16:43:04 -080045#include "dex/primitive.h"
Ian Rogerse63db272014-07-15 15:36:11 -070046#include "gc/heap.h"
Steven Morelande431e272017-07-18 16:53:49 -070047#include "gc_root-inl.h"
Elliott Hugheseb02a122012-06-12 11:35:40 -070048#include "gtest/gtest.h"
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070049#include "handle_scope-inl.h"
Andreas Gampe9b5cba42015-03-11 09:53:50 -070050#include "interpreter/unstarted_runtime.h"
Andreas Gampec15a2f42017-04-21 12:09:39 -070051#include "java_vm_ext.h"
Ian Rogerse63db272014-07-15 15:36:11 -070052#include "jni_internal.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070053#include "mirror/class-inl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070054#include "mirror/class_loader.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070055#include "native/dalvik_system_DexFile.h"
Ian Rogerse63db272014-07-15 15:36:11 -070056#include "noop_compiler_callbacks.h"
Ian Rogerse63db272014-07-15 15:36:11 -070057#include "runtime-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070058#include "scoped_thread_state_change-inl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070059#include "thread.h"
60#include "well_known_classes.h"
Elliott Hugheseb02a122012-06-12 11:35:40 -070061
62int main(int argc, char **argv) {
Andreas Gampe369810a2015-01-14 19:53:31 -080063 // Gtests can be very noisy. For example, an executable with multiple tests will trigger native
64 // bridge warnings. The following line reduces the minimum log severity to ERROR and suppresses
65 // everything else. In case you want to see all messages, comment out the line.
Nicolas Geoffraya7a47592015-11-24 09:17:30 +000066 setenv("ANDROID_LOG_TAGS", "*:e", 1);
Andreas Gampe369810a2015-01-14 19:53:31 -080067
David Sehrc431b9d2018-03-02 12:01:51 -080068 art::Locks::Init();
Andreas Gampe51d80cc2017-06-21 21:05:13 -070069 art::InitLogging(argv, art::Runtime::Abort);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -070070 LOG(INFO) << "Running main() from common_runtime_test.cc...";
Elliott Hugheseb02a122012-06-12 11:35:40 -070071 testing::InitGoogleTest(&argc, argv);
72 return RUN_ALL_TESTS();
73}
Ian Rogerse63db272014-07-15 15:36:11 -070074
75namespace art {
76
Andreas Gampe46ee31b2016-12-14 10:11:49 -080077using android::base::StringPrintf;
78
Ian Rogerse63db272014-07-15 15:36:11 -070079ScratchFile::ScratchFile() {
80 // ANDROID_DATA needs to be set
81 CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
82 "Are you subclassing RuntimeTest?";
83 filename_ = getenv("ANDROID_DATA");
84 filename_ += "/TmpFile-XXXXXX";
85 int fd = mkstemp(&filename_[0]);
Andreas Gampe29d38e72016-03-23 15:31:51 +000086 CHECK_NE(-1, fd) << strerror(errno) << " for " << filename_;
Andreas Gampe4303ba92014-11-06 01:00:46 -080087 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070088}
89
Mathieu Chartier866d8742016-09-21 15:24:18 -070090ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix)
91 : ScratchFile(other.GetFilename() + suffix) {}
92
93ScratchFile::ScratchFile(const std::string& filename) : filename_(filename) {
Ian Rogerse63db272014-07-15 15:36:11 -070094 int fd = open(filename_.c_str(), O_RDWR | O_CREAT, 0666);
95 CHECK_NE(-1, fd);
Andreas Gampe4303ba92014-11-06 01:00:46 -080096 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070097}
98
99ScratchFile::ScratchFile(File* file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700100 CHECK(file != nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -0700101 filename_ = file->GetPath();
102 file_.reset(file);
103}
104
Mathieu Chartier866d8742016-09-21 15:24:18 -0700105ScratchFile::ScratchFile(ScratchFile&& other) {
106 *this = std::move(other);
107}
108
109ScratchFile& ScratchFile::operator=(ScratchFile&& other) {
110 if (GetFile() != other.GetFile()) {
111 std::swap(filename_, other.filename_);
112 std::swap(file_, other.file_);
113 }
114 return *this;
115}
116
Ian Rogerse63db272014-07-15 15:36:11 -0700117ScratchFile::~ScratchFile() {
118 Unlink();
119}
120
121int ScratchFile::GetFd() const {
122 return file_->Fd();
123}
124
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800125void ScratchFile::Close() {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800126 if (file_.get() != nullptr) {
127 if (file_->FlushCloseOrErase() != 0) {
128 PLOG(WARNING) << "Error closing scratch file.";
129 }
130 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800131}
132
133void ScratchFile::Unlink() {
134 if (!OS::FileExists(filename_.c_str())) {
135 return;
136 }
137 Close();
Ian Rogerse63db272014-07-15 15:36:11 -0700138 int unlink_result = unlink(filename_.c_str());
139 CHECK_EQ(0, unlink_result);
140}
141
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700142static bool unstarted_initialized_ = false;
143
Andreas Gampe48864112017-01-19 17:23:17 -0800144CommonRuntimeTestImpl::CommonRuntimeTestImpl()
145 : class_linker_(nullptr), java_lang_dex_file_(nullptr) {
146}
Mathieu Chartier91c91162016-01-15 09:48:15 -0800147
148CommonRuntimeTestImpl::~CommonRuntimeTestImpl() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800149 // Ensure the dex files are cleaned up before the runtime.
150 loaded_dex_files_.clear();
151 runtime_.reset();
152}
Ian Rogerse63db272014-07-15 15:36:11 -0700153
Mathieu Chartier91c91162016-01-15 09:48:15 -0800154void CommonRuntimeTestImpl::SetUpAndroidRoot() {
Ian Rogerse63db272014-07-15 15:36:11 -0700155 if (IsHost()) {
156 // $ANDROID_ROOT is set on the device, but not necessarily on the host.
157 // But it needs to be set so that icu4c can find its locale data.
158 const char* android_root_from_env = getenv("ANDROID_ROOT");
159 if (android_root_from_env == nullptr) {
160 // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
161 const char* android_host_out = getenv("ANDROID_HOST_OUT");
162 if (android_host_out != nullptr) {
163 setenv("ANDROID_ROOT", android_host_out, 1);
164 } else {
165 // Build it from ANDROID_BUILD_TOP or cwd
166 std::string root;
167 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
168 if (android_build_top != nullptr) {
169 root += android_build_top;
170 } else {
171 // Not set by build server, so default to current directory
172 char* cwd = getcwd(nullptr, 0);
173 setenv("ANDROID_BUILD_TOP", cwd, 1);
174 root += cwd;
175 free(cwd);
176 }
177#if defined(__linux__)
178 root += "/out/host/linux-x86";
179#elif defined(__APPLE__)
180 root += "/out/host/darwin-x86";
181#else
182#error unsupported OS
183#endif
184 setenv("ANDROID_ROOT", root.c_str(), 1);
185 }
186 }
187 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
188
189 // Not set by build server, so default
190 if (getenv("ANDROID_HOST_OUT") == nullptr) {
191 setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
192 }
193 }
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700194}
Ian Rogerse63db272014-07-15 15:36:11 -0700195
Mathieu Chartier91c91162016-01-15 09:48:15 -0800196void CommonRuntimeTestImpl::SetUpAndroidData(std::string& android_data) {
Ian Rogerse63db272014-07-15 15:36:11 -0700197 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
Andreas Gampe5a79fde2014-08-06 13:12:26 -0700198 if (IsHost()) {
199 const char* tmpdir = getenv("TMPDIR");
200 if (tmpdir != nullptr && tmpdir[0] != 0) {
201 android_data = tmpdir;
202 } else {
203 android_data = "/tmp";
204 }
205 } else {
206 android_data = "/data/dalvik-cache";
207 }
208 android_data += "/art-data-XXXXXX";
Ian Rogerse63db272014-07-15 15:36:11 -0700209 if (mkdtemp(&android_data[0]) == nullptr) {
210 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
211 }
212 setenv("ANDROID_DATA", android_data.c_str(), 1);
213}
214
Mathieu Chartier91c91162016-01-15 09:48:15 -0800215void CommonRuntimeTestImpl::TearDownAndroidData(const std::string& android_data,
216 bool fail_on_error) {
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700217 if (fail_on_error) {
218 ASSERT_EQ(rmdir(android_data.c_str()), 0);
219 } else {
220 rmdir(android_data.c_str());
221 }
222}
223
David Srbecky3e52aa42015-04-12 07:45:18 +0100224// Helper - find directory with the following format:
225// ${ANDROID_BUILD_TOP}/${subdir1}/${subdir2}-${version}/${subdir3}/bin/
226static std::string GetAndroidToolsDir(const std::string& subdir1,
227 const std::string& subdir2,
228 const std::string& subdir3) {
229 std::string root;
230 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
231 if (android_build_top != nullptr) {
232 root = android_build_top;
233 } else {
234 // Not set by build server, so default to current directory
235 char* cwd = getcwd(nullptr, 0);
236 setenv("ANDROID_BUILD_TOP", cwd, 1);
237 root = cwd;
238 free(cwd);
239 }
240
241 std::string toolsdir = root + "/" + subdir1;
242 std::string founddir;
243 DIR* dir;
244 if ((dir = opendir(toolsdir.c_str())) != nullptr) {
245 float maxversion = 0;
246 struct dirent* entry;
247 while ((entry = readdir(dir)) != nullptr) {
248 std::string format = subdir2 + "-%f";
249 float version;
250 if (std::sscanf(entry->d_name, format.c_str(), &version) == 1) {
251 if (version > maxversion) {
252 maxversion = version;
253 founddir = toolsdir + "/" + entry->d_name + "/" + subdir3 + "/bin/";
254 }
255 }
256 }
257 closedir(dir);
258 }
259
260 if (founddir.empty()) {
Roland Levillain91d65e02016-01-19 15:59:16 +0000261 ADD_FAILURE() << "Cannot find Android tools directory.";
David Srbecky3e52aa42015-04-12 07:45:18 +0100262 }
263 return founddir;
264}
265
Mathieu Chartier91c91162016-01-15 09:48:15 -0800266std::string CommonRuntimeTestImpl::GetAndroidHostToolsDir() {
David Srbecky3e52aa42015-04-12 07:45:18 +0100267 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/host",
268 "x86_64-linux-glibc2.15",
269 "x86_64-linux");
270}
271
Mathieu Chartier91c91162016-01-15 09:48:15 -0800272std::string CommonRuntimeTestImpl::GetAndroidTargetToolsDir(InstructionSet isa) {
David Srbecky3e52aa42015-04-12 07:45:18 +0100273 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000274 case InstructionSet::kArm:
275 case InstructionSet::kThumb2:
David Srbecky3e52aa42015-04-12 07:45:18 +0100276 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/arm",
277 "arm-linux-androideabi",
278 "arm-linux-androideabi");
Vladimir Marko33bff252017-11-01 14:35:42 +0000279 case InstructionSet::kArm64:
David Srbecky3e52aa42015-04-12 07:45:18 +0100280 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/aarch64",
281 "aarch64-linux-android",
282 "aarch64-linux-android");
Vladimir Marko33bff252017-11-01 14:35:42 +0000283 case InstructionSet::kX86:
284 case InstructionSet::kX86_64:
David Srbecky3e52aa42015-04-12 07:45:18 +0100285 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/x86",
286 "x86_64-linux-android",
287 "x86_64-linux-android");
Vladimir Marko33bff252017-11-01 14:35:42 +0000288 case InstructionSet::kMips:
289 case InstructionSet::kMips64:
David Srbecky3e52aa42015-04-12 07:45:18 +0100290 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/mips",
291 "mips64el-linux-android",
292 "mips64el-linux-android");
Vladimir Marko33bff252017-11-01 14:35:42 +0000293 case InstructionSet::kNone:
David Srbecky3e52aa42015-04-12 07:45:18 +0100294 break;
295 }
296 ADD_FAILURE() << "Invalid isa " << isa;
297 return "";
298}
299
Mathieu Chartier91c91162016-01-15 09:48:15 -0800300std::string CommonRuntimeTestImpl::GetCoreArtLocation() {
Igor Murashkin37743352014-11-13 14:38:00 -0800301 return GetCoreFileLocation("art");
302}
303
Mathieu Chartier91c91162016-01-15 09:48:15 -0800304std::string CommonRuntimeTestImpl::GetCoreOatLocation() {
Igor Murashkin37743352014-11-13 14:38:00 -0800305 return GetCoreFileLocation("oat");
306}
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700307
Mathieu Chartier91c91162016-01-15 09:48:15 -0800308std::unique_ptr<const DexFile> CommonRuntimeTestImpl::LoadExpectSingleDexFile(
309 const char* location) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800310 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700311 std::string error_msg;
Richard Uhler66d874d2015-01-15 09:37:19 -0800312 MemMap::Init();
Aart Bik37d6a3b2016-06-21 18:30:10 -0700313 static constexpr bool kVerifyChecksum = true;
David Sehr013fd802018-01-11 22:55:24 -0800314 const ArtDexFileLoader dex_file_loader;
315 if (!dex_file_loader.Open(
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100316 location, location, /* verify */ true, kVerifyChecksum, &error_msg, &dex_files)) {
Ian Rogerse63db272014-07-15 15:36:11 -0700317 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800318 UNREACHABLE();
Ian Rogerse63db272014-07-15 15:36:11 -0700319 } else {
320 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800321 return std::move(dex_files[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700322 }
323}
324
Mathieu Chartier91c91162016-01-15 09:48:15 -0800325void CommonRuntimeTestImpl::SetUp() {
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700326 SetUpAndroidRoot();
327 SetUpAndroidData(android_data_);
Ian Rogerse63db272014-07-15 15:36:11 -0700328 dalvik_cache_.append(android_data_.c_str());
329 dalvik_cache_.append("/dalvik-cache");
330 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
331 ASSERT_EQ(mkdir_result, 0);
332
Ian Rogerse63db272014-07-15 15:36:11 -0700333 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
334 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
335
Ian Rogerse63db272014-07-15 15:36:11 -0700336
337 RuntimeOptions options;
Narayan Kamathd1ef4362015-11-12 11:49:06 +0000338 std::string boot_class_path_string = "-Xbootclasspath";
339 for (const std::string &core_dex_file_name : GetLibCoreDexFileNames()) {
340 boot_class_path_string += ":";
341 boot_class_path_string += core_dex_file_name;
342 }
343
Richard Uhlerc2752592015-01-02 13:28:22 -0800344 options.push_back(std::make_pair(boot_class_path_string, nullptr));
Ian Rogerse63db272014-07-15 15:36:11 -0700345 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
Richard Uhlerc2752592015-01-02 13:28:22 -0800346 options.push_back(std::make_pair(min_heap_string, nullptr));
347 options.push_back(std::make_pair(max_heap_string, nullptr));
Andreas Gampe1c5b42f2017-06-15 18:20:45 -0700348 options.push_back(std::make_pair("-XX:SlowDebug=true", nullptr));
Andreas Gampe46c4c852017-06-21 19:49:08 -0700349 static bool gSlowDebugTestFlag = false;
350 RegisterRuntimeDebugFlag(&gSlowDebugTestFlag);
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700351
352 callbacks_.reset(new NoopCompilerCallbacks());
353
Ian Rogerse63db272014-07-15 15:36:11 -0700354 SetUpRuntimeOptions(&options);
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800355
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700356 // Install compiler-callbacks if SetupRuntimeOptions hasn't deleted them.
357 if (callbacks_.get() != nullptr) {
358 options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
359 }
360
Richard Uhler66d874d2015-01-15 09:37:19 -0800361 PreRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700362 if (!Runtime::Create(options, false)) {
363 LOG(FATAL) << "Failed to create runtime";
364 return;
365 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800366 PostRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700367 runtime_.reset(Runtime::Current());
368 class_linker_ = runtime_->GetClassLinker();
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700369
Andreas Gampea00f0122015-12-16 16:54:35 -0800370 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
371 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
372 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
373
374 // Get the boot class path from the runtime so it can be used in tests.
375 boot_class_path_ = class_linker_->GetBootClassPath();
376 ASSERT_FALSE(boot_class_path_.empty());
377 java_lang_dex_file_ = boot_class_path_[0];
378
379 FinalizeSetup();
Andreas Gampe46c4c852017-06-21 19:49:08 -0700380
381 // Ensure that we're really running with debug checks enabled.
382 CHECK(gSlowDebugTestFlag);
Andreas Gampea00f0122015-12-16 16:54:35 -0800383}
384
Mathieu Chartier91c91162016-01-15 09:48:15 -0800385void CommonRuntimeTestImpl::FinalizeSetup() {
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700386 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
387 // set up.
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700388 if (!unstarted_initialized_) {
Andreas Gampe799681b2015-05-15 19:24:12 -0700389 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700390 unstarted_initialized_ = true;
391 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700392
Andreas Gampea00f0122015-12-16 16:54:35 -0800393 {
394 ScopedObjectAccess soa(Thread::Current());
395 class_linker_->RunRootClinits();
396 }
Ian Rogerse63db272014-07-15 15:36:11 -0700397
398 // We're back in native, take the opportunity to initialize well known classes.
399 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
400
401 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
402 // pool is created by the runtime.
403 runtime_->GetHeap()->CreateThreadPool();
404 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700405 // Reduce timinig-dependent flakiness in OOME behavior (eg StubTest.AllocObject).
406 runtime_->GetHeap()->SetMinIntervalHomogeneousSpaceCompactionByOom(0U);
Ian Rogerse63db272014-07-15 15:36:11 -0700407}
408
Mathieu Chartierf70fe3d2017-06-21 15:24:02 -0700409void CommonRuntimeTestImpl::ClearDirectory(const char* dirpath, bool recursive) {
Alex Lighta59dd802014-07-02 16:28:08 -0700410 ASSERT_TRUE(dirpath != nullptr);
411 DIR* dir = opendir(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700412 ASSERT_TRUE(dir != nullptr);
413 dirent* e;
Alex Lighta59dd802014-07-02 16:28:08 -0700414 struct stat s;
Ian Rogerse63db272014-07-15 15:36:11 -0700415 while ((e = readdir(dir)) != nullptr) {
416 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
417 continue;
418 }
Jeff Haof0a3f092014-07-24 16:26:09 -0700419 std::string filename(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700420 filename.push_back('/');
421 filename.append(e->d_name);
Alex Lighta59dd802014-07-02 16:28:08 -0700422 int stat_result = lstat(filename.c_str(), &s);
423 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
424 if (S_ISDIR(s.st_mode)) {
Mathieu Chartierf70fe3d2017-06-21 15:24:02 -0700425 if (recursive) {
426 ClearDirectory(filename.c_str());
427 int rmdir_result = rmdir(filename.c_str());
428 ASSERT_EQ(0, rmdir_result) << filename;
429 }
Alex Lighta59dd802014-07-02 16:28:08 -0700430 } else {
431 int unlink_result = unlink(filename.c_str());
432 ASSERT_EQ(0, unlink_result) << filename;
433 }
Ian Rogerse63db272014-07-15 15:36:11 -0700434 }
435 closedir(dir);
Alex Lighta59dd802014-07-02 16:28:08 -0700436}
437
Mathieu Chartier91c91162016-01-15 09:48:15 -0800438void CommonRuntimeTestImpl::TearDown() {
Alex Lighta59dd802014-07-02 16:28:08 -0700439 const char* android_data = getenv("ANDROID_DATA");
440 ASSERT_TRUE(android_data != nullptr);
441 ClearDirectory(dalvik_cache_.c_str());
Ian Rogerse63db272014-07-15 15:36:11 -0700442 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
443 ASSERT_EQ(0, rmdir_cache_result);
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700444 TearDownAndroidData(android_data_, true);
Andreas Gampe3f41a012016-02-18 16:53:41 -0800445 dalvik_cache_.clear();
Ian Rogerse63db272014-07-15 15:36:11 -0700446
Andreas Gampe48864112017-01-19 17:23:17 -0800447 if (runtime_ != nullptr) {
448 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
449 }
Ian Rogerse63db272014-07-15 15:36:11 -0700450}
451
Andreas Gampec7d4a582015-09-30 11:52:02 -0700452static std::string GetDexFileName(const std::string& jar_prefix, bool host) {
453 std::string path;
454 if (host) {
Ian Rogerse63db272014-07-15 15:36:11 -0700455 const char* host_dir = getenv("ANDROID_HOST_OUT");
456 CHECK(host_dir != nullptr);
Andreas Gampec7d4a582015-09-30 11:52:02 -0700457 path = host_dir;
458 } else {
459 path = GetAndroidRoot();
Ian Rogerse63db272014-07-15 15:36:11 -0700460 }
Andreas Gampec7d4a582015-09-30 11:52:02 -0700461
462 std::string suffix = host
463 ? "-hostdex" // The host version.
464 : "-testdex"; // The unstripped target version.
465
466 return StringPrintf("%s/framework/%s%s.jar", path.c_str(), jar_prefix.c_str(), suffix.c_str());
467}
468
Mathieu Chartier91c91162016-01-15 09:48:15 -0800469std::vector<std::string> CommonRuntimeTestImpl::GetLibCoreDexFileNames() {
Andreas Gampec7d4a582015-09-30 11:52:02 -0700470 return std::vector<std::string>({GetDexFileName("core-oj", IsHost()),
471 GetDexFileName("core-libart", IsHost())});
Ian Rogerse63db272014-07-15 15:36:11 -0700472}
473
Mathieu Chartier91c91162016-01-15 09:48:15 -0800474std::string CommonRuntimeTestImpl::GetTestAndroidRoot() {
Ian Rogerse63db272014-07-15 15:36:11 -0700475 if (IsHost()) {
476 const char* host_dir = getenv("ANDROID_HOST_OUT");
477 CHECK(host_dir != nullptr);
478 return host_dir;
479 }
480 return GetAndroidRoot();
481}
482
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700483// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
484#ifdef ART_TARGET
485#ifndef ART_TARGET_NATIVETEST_DIR
486#error "ART_TARGET_NATIVETEST_DIR not set."
487#endif
488// Wrap it as a string literal.
489#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
490#else
491#define ART_TARGET_NATIVETEST_DIR_STRING ""
492#endif
493
Andreas Gampee1459ae2016-06-29 09:36:30 -0700494std::string CommonRuntimeTestImpl::GetTestDexFileName(const char* name) const {
Ian Rogerse63db272014-07-15 15:36:11 -0700495 CHECK(name != nullptr);
496 std::string filename;
497 if (IsHost()) {
498 filename += getenv("ANDROID_HOST_OUT");
499 filename += "/framework/";
500 } else {
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700501 filename += ART_TARGET_NATIVETEST_DIR_STRING;
Ian Rogerse63db272014-07-15 15:36:11 -0700502 }
503 filename += "art-gtest-";
504 filename += name;
505 filename += ".jar";
Richard Uhler66d874d2015-01-15 09:37:19 -0800506 return filename;
507}
508
Mathieu Chartier91c91162016-01-15 09:48:15 -0800509std::vector<std::unique_ptr<const DexFile>> CommonRuntimeTestImpl::OpenTestDexFiles(
510 const char* name) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800511 std::string filename = GetTestDexFileName(name);
Aart Bik37d6a3b2016-06-21 18:30:10 -0700512 static constexpr bool kVerifyChecksum = true;
Ian Rogerse63db272014-07-15 15:36:11 -0700513 std::string error_msg;
David Sehr013fd802018-01-11 22:55:24 -0800514 const ArtDexFileLoader dex_file_loader;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800515 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800516 bool success = dex_file_loader.Open(filename.c_str(),
517 filename.c_str(),
518 /* verify */ true,
519 kVerifyChecksum,
520 &error_msg, &dex_files);
Ian Rogerse63db272014-07-15 15:36:11 -0700521 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800522 for (auto& dex_file : dex_files) {
Ian Rogerse63db272014-07-15 15:36:11 -0700523 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
524 CHECK(dex_file->IsReadOnly());
525 }
Ian Rogerse63db272014-07-15 15:36:11 -0700526 return dex_files;
527}
528
Mathieu Chartier91c91162016-01-15 09:48:15 -0800529std::unique_ptr<const DexFile> CommonRuntimeTestImpl::OpenTestDexFile(const char* name) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800530 std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700531 EXPECT_EQ(1U, vector.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800532 return std::move(vector[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700533}
534
Mathieu Chartier91c91162016-01-15 09:48:15 -0800535std::vector<const DexFile*> CommonRuntimeTestImpl::GetDexFiles(jobject jclass_loader) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700536 ScopedObjectAccess soa(Thread::Current());
537
Calin Juravlec79470d2017-07-12 17:37:42 -0700538 StackHandleScope<1> hs(soa.Self());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700539 Handle<mirror::ClassLoader> class_loader = hs.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700540 soa.Decode<mirror::ClassLoader>(jclass_loader));
Calin Juravlec79470d2017-07-12 17:37:42 -0700541 return GetDexFiles(soa, class_loader);
542}
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700543
Calin Juravlec79470d2017-07-12 17:37:42 -0700544std::vector<const DexFile*> CommonRuntimeTestImpl::GetDexFiles(
545 ScopedObjectAccess& soa,
546 Handle<mirror::ClassLoader> class_loader) {
Calin Juravlec79470d2017-07-12 17:37:42 -0700547 DCHECK(
548 (class_loader->GetClass() ==
549 soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader)) ||
550 (class_loader->GetClass() ==
551 soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_DelegateLastClassLoader)));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700552
Andreas Gampeb8e7c372018-02-20 18:24:55 -0800553 std::vector<const DexFile*> ret;
554 VisitClassLoaderDexFiles(soa,
555 class_loader,
556 [&](const DexFile* cp_dex_file) {
557 if (cp_dex_file == nullptr) {
558 LOG(WARNING) << "Null DexFile";
559 } else {
560 ret.push_back(cp_dex_file);
561 }
562 return true;
563 });
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700564 return ret;
565}
566
Mathieu Chartier91c91162016-01-15 09:48:15 -0800567const DexFile* CommonRuntimeTestImpl::GetFirstDexFile(jobject jclass_loader) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700568 std::vector<const DexFile*> tmp(GetDexFiles(jclass_loader));
569 DCHECK(!tmp.empty());
570 const DexFile* ret = tmp[0];
571 DCHECK(ret != nullptr);
572 return ret;
573}
574
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +0100575jobject CommonRuntimeTestImpl::LoadMultiDex(const char* first_dex_name,
576 const char* second_dex_name) {
577 std::vector<std::unique_ptr<const DexFile>> first_dex_files = OpenTestDexFiles(first_dex_name);
578 std::vector<std::unique_ptr<const DexFile>> second_dex_files = OpenTestDexFiles(second_dex_name);
579 std::vector<const DexFile*> class_path;
580 CHECK_NE(0U, first_dex_files.size());
581 CHECK_NE(0U, second_dex_files.size());
582 for (auto& dex_file : first_dex_files) {
583 class_path.push_back(dex_file.get());
584 loaded_dex_files_.push_back(std::move(dex_file));
585 }
586 for (auto& dex_file : second_dex_files) {
587 class_path.push_back(dex_file.get());
588 loaded_dex_files_.push_back(std::move(dex_file));
589 }
590
591 Thread* self = Thread::Current();
592 jobject class_loader = Runtime::Current()->GetClassLinker()->CreatePathClassLoader(self,
593 class_path);
594 self->SetClassLoaderOverride(class_loader);
595 return class_loader;
596}
597
Mathieu Chartier91c91162016-01-15 09:48:15 -0800598jobject CommonRuntimeTestImpl::LoadDex(const char* dex_name) {
Calin Juravle7865ac72017-06-28 11:03:12 -0700599 jobject class_loader = LoadDexInPathClassLoader(dex_name, nullptr);
600 Thread::Current()->SetClassLoaderOverride(class_loader);
601 return class_loader;
602}
603
604jobject CommonRuntimeTestImpl::LoadDexInWellKnownClassLoader(const std::string& dex_name,
605 jclass loader_class,
606 jobject parent_loader) {
607 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name.c_str());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800608 std::vector<const DexFile*> class_path;
Ian Rogerse63db272014-07-15 15:36:11 -0700609 CHECK_NE(0U, dex_files.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800610 for (auto& dex_file : dex_files) {
611 class_path.push_back(dex_file.get());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800612 loaded_dex_files_.push_back(std::move(dex_file));
Ian Rogerse63db272014-07-15 15:36:11 -0700613 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700614 Thread* self = Thread::Current();
Calin Juravle7865ac72017-06-28 11:03:12 -0700615 ScopedObjectAccess soa(self);
616
617 jobject result = Runtime::Current()->GetClassLinker()->CreateWellKnownClassLoader(
618 self,
619 class_path,
620 loader_class,
621 parent_loader);
622
623 {
624 // Verify we build the correct chain.
625
626 ObjPtr<mirror::ClassLoader> actual_class_loader = soa.Decode<mirror::ClassLoader>(result);
627 // Verify that the result has the correct class.
628 CHECK_EQ(soa.Decode<mirror::Class>(loader_class), actual_class_loader->GetClass());
629 // Verify that the parent is not null. The boot class loader will be set up as a
630 // proper object.
631 ObjPtr<mirror::ClassLoader> actual_parent(actual_class_loader->GetParent());
632 CHECK(actual_parent != nullptr);
633
634 if (parent_loader != nullptr) {
635 // We were given a parent. Verify that it's what we expect.
636 ObjPtr<mirror::ClassLoader> expected_parent = soa.Decode<mirror::ClassLoader>(parent_loader);
637 CHECK_EQ(expected_parent, actual_parent);
638 } else {
639 // No parent given. The parent must be the BootClassLoader.
640 CHECK(Runtime::Current()->GetClassLinker()->IsBootClassLoader(soa, actual_parent));
641 }
642 }
643
644 return result;
645}
646
647jobject CommonRuntimeTestImpl::LoadDexInPathClassLoader(const std::string& dex_name,
648 jobject parent_loader) {
649 return LoadDexInWellKnownClassLoader(dex_name,
650 WellKnownClasses::dalvik_system_PathClassLoader,
651 parent_loader);
652}
653
654jobject CommonRuntimeTestImpl::LoadDexInDelegateLastClassLoader(const std::string& dex_name,
655 jobject parent_loader) {
656 return LoadDexInWellKnownClassLoader(dex_name,
657 WellKnownClasses::dalvik_system_DelegateLastClassLoader,
658 parent_loader);
Ian Rogerse63db272014-07-15 15:36:11 -0700659}
660
Mathieu Chartier91c91162016-01-15 09:48:15 -0800661std::string CommonRuntimeTestImpl::GetCoreFileLocation(const char* suffix) {
Igor Murashkin37743352014-11-13 14:38:00 -0800662 CHECK(suffix != nullptr);
663
664 std::string location;
665 if (IsHost()) {
666 const char* host_dir = getenv("ANDROID_HOST_OUT");
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700667 CHECK(host_dir != nullptr);
Richard Uhler67e1dc52017-02-06 16:50:17 +0000668 location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
Igor Murashkin37743352014-11-13 14:38:00 -0800669 } else {
Richard Uhler67e1dc52017-02-06 16:50:17 +0000670 location = StringPrintf("/data/art-test/core.%s", suffix);
Igor Murashkin37743352014-11-13 14:38:00 -0800671 }
672
673 return location;
674}
675
Calin Juravlec79470d2017-07-12 17:37:42 -0700676std::string CommonRuntimeTestImpl::CreateClassPath(
677 const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
678 CHECK(!dex_files.empty());
679 std::string classpath = dex_files[0]->GetLocation();
680 for (size_t i = 1; i < dex_files.size(); i++) {
681 classpath += ":" + dex_files[i]->GetLocation();
682 }
683 return classpath;
684}
685
686std::string CommonRuntimeTestImpl::CreateClassPathWithChecksums(
687 const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
688 CHECK(!dex_files.empty());
689 std::string classpath = dex_files[0]->GetLocation() + "*" +
690 std::to_string(dex_files[0]->GetLocationChecksum());
691 for (size_t i = 1; i < dex_files.size(); i++) {
692 classpath += ":" + dex_files[i]->GetLocation() + "*" +
693 std::to_string(dex_files[i]->GetLocationChecksum());
694 }
695 return classpath;
696}
697
Andreas Gampe26761f72017-07-20 18:00:39 -0700698void CommonRuntimeTestImpl::FillHeap(Thread* self,
699 ClassLinker* class_linker,
700 VariableSizedHandleScope* handle_scope) {
701 DCHECK(handle_scope != nullptr);
702
703 Runtime::Current()->GetHeap()->SetIdealFootprint(1 * GB);
704
705 // Class java.lang.Object.
706 Handle<mirror::Class> c(handle_scope->NewHandle(
707 class_linker->FindSystemClass(self, "Ljava/lang/Object;")));
708 // Array helps to fill memory faster.
709 Handle<mirror::Class> ca(handle_scope->NewHandle(
710 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
711
712 // Start allocating with ~128K
713 size_t length = 128 * KB;
714 while (length > 40) {
715 const int32_t array_length = length / 4; // Object[] has elements of size 4.
716 MutableHandle<mirror::Object> h(handle_scope->NewHandle<mirror::Object>(
717 mirror::ObjectArray<mirror::Object>::Alloc(self, ca.Get(), array_length)));
718 if (self->IsExceptionPending() || h == nullptr) {
719 self->ClearException();
720
721 // Try a smaller length
722 length = length / 2;
723 // Use at most a quarter the reported free space.
724 size_t mem = Runtime::Current()->GetHeap()->GetFreeMemory();
725 if (length * 4 > mem) {
726 length = mem / 4;
727 }
728 }
729 }
730
731 // Allocate simple objects till it fails.
732 while (!self->IsExceptionPending()) {
733 handle_scope->NewHandle<mirror::Object>(c->AllocObject(self));
734 }
735 self->ClearException();
736}
737
738void CommonRuntimeTestImpl::SetUpRuntimeOptionsForFillHeap(RuntimeOptions *options) {
739 // Use a smaller heap
740 bool found = false;
741 for (std::pair<std::string, const void*>& pair : *options) {
742 if (pair.first.find("-Xmx") == 0) {
743 pair.first = "-Xmx4M"; // Smallest we can go.
744 found = true;
745 }
746 }
747 if (!found) {
748 options->emplace_back("-Xmx4M", nullptr);
749 }
750}
751
Ian Rogerse63db272014-07-15 15:36:11 -0700752CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700753 vm_->SetCheckJniAbortHook(Hook, &actual_);
Ian Rogerse63db272014-07-15 15:36:11 -0700754}
755
756CheckJniAbortCatcher::~CheckJniAbortCatcher() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700757 vm_->SetCheckJniAbortHook(nullptr, nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -0700758 EXPECT_TRUE(actual_.empty()) << actual_;
759}
760
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700761void CheckJniAbortCatcher::Check(const std::string& expected_text) {
762 Check(expected_text.c_str());
763}
764
Ian Rogerse63db272014-07-15 15:36:11 -0700765void CheckJniAbortCatcher::Check(const char* expected_text) {
766 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
767 << "Expected to find: " << expected_text << "\n"
768 << "In the output : " << actual_;
769 actual_.clear();
770}
771
772void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
773 // We use += because when we're hooking the aborts like this, multiple problems can be found.
774 *reinterpret_cast<std::string*>(data) += reason;
775}
776
777} // namespace art