blob: e7a1374d5f8c15e05bc53c2a676704b7e8e72e13 [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"
Andreas Gampedcc528d2017-12-07 13:37:10 -080033#include "base/runtime_debug.h"
Ian Rogerse63db272014-07-15 15:36:11 -070034#include "base/stl_util.h"
Ian Rogerse63db272014-07-15 15:36:11 -070035#include "base/unix_file/fd_file.h"
36#include "class_linker.h"
Andreas Gampeb8e7c372018-02-20 18:24:55 -080037#include "class_loader_utils.h"
Ian Rogerse63db272014-07-15 15:36:11 -070038#include "compiler_callbacks.h"
David Sehr013fd802018-01-11 22:55:24 -080039#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080040#include "dex/dex_file-inl.h"
41#include "dex/dex_file_loader.h"
David Sehr67bf42e2018-02-26 16:43:04 -080042#include "dex/primitive.h"
Ian Rogerse63db272014-07-15 15:36:11 -070043#include "gc/heap.h"
Steven Morelande431e272017-07-18 16:53:49 -070044#include "gc_root-inl.h"
Elliott Hugheseb02a122012-06-12 11:35:40 -070045#include "gtest/gtest.h"
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070046#include "handle_scope-inl.h"
Andreas Gampe9b5cba42015-03-11 09:53:50 -070047#include "interpreter/unstarted_runtime.h"
Andreas Gampec15a2f42017-04-21 12:09:39 -070048#include "java_vm_ext.h"
Ian Rogerse63db272014-07-15 15:36:11 -070049#include "jni_internal.h"
Steven Morelande431e272017-07-18 16:53:49 -070050#include "mem_map.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070051#include "mirror/class-inl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070052#include "mirror/class_loader.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070053#include "native/dalvik_system_DexFile.h"
Ian Rogerse63db272014-07-15 15:36:11 -070054#include "noop_compiler_callbacks.h"
55#include "os.h"
56#include "runtime-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070057#include "scoped_thread_state_change-inl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070058#include "thread.h"
59#include "well_known_classes.h"
Elliott Hugheseb02a122012-06-12 11:35:40 -070060
61int main(int argc, char **argv) {
Andreas Gampe369810a2015-01-14 19:53:31 -080062 // Gtests can be very noisy. For example, an executable with multiple tests will trigger native
63 // bridge warnings. The following line reduces the minimum log severity to ERROR and suppresses
64 // everything else. In case you want to see all messages, comment out the line.
Nicolas Geoffraya7a47592015-11-24 09:17:30 +000065 setenv("ANDROID_LOG_TAGS", "*:e", 1);
Andreas Gampe369810a2015-01-14 19:53:31 -080066
Andreas Gampe51d80cc2017-06-21 21:05:13 -070067 art::InitLogging(argv, art::Runtime::Abort);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -070068 LOG(INFO) << "Running main() from common_runtime_test.cc...";
Elliott Hugheseb02a122012-06-12 11:35:40 -070069 testing::InitGoogleTest(&argc, argv);
70 return RUN_ALL_TESTS();
71}
Ian Rogerse63db272014-07-15 15:36:11 -070072
73namespace art {
74
Andreas Gampe46ee31b2016-12-14 10:11:49 -080075using android::base::StringPrintf;
76
Ian Rogerse63db272014-07-15 15:36:11 -070077ScratchFile::ScratchFile() {
78 // ANDROID_DATA needs to be set
79 CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
80 "Are you subclassing RuntimeTest?";
81 filename_ = getenv("ANDROID_DATA");
82 filename_ += "/TmpFile-XXXXXX";
83 int fd = mkstemp(&filename_[0]);
Andreas Gampe29d38e72016-03-23 15:31:51 +000084 CHECK_NE(-1, fd) << strerror(errno) << " for " << filename_;
Andreas Gampe4303ba92014-11-06 01:00:46 -080085 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070086}
87
Mathieu Chartier866d8742016-09-21 15:24:18 -070088ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix)
89 : ScratchFile(other.GetFilename() + suffix) {}
90
91ScratchFile::ScratchFile(const std::string& filename) : filename_(filename) {
Ian Rogerse63db272014-07-15 15:36:11 -070092 int fd = open(filename_.c_str(), O_RDWR | O_CREAT, 0666);
93 CHECK_NE(-1, fd);
Andreas Gampe4303ba92014-11-06 01:00:46 -080094 file_.reset(new File(fd, GetFilename(), true));
Ian Rogerse63db272014-07-15 15:36:11 -070095}
96
97ScratchFile::ScratchFile(File* file) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070098 CHECK(file != nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -070099 filename_ = file->GetPath();
100 file_.reset(file);
101}
102
Mathieu Chartier866d8742016-09-21 15:24:18 -0700103ScratchFile::ScratchFile(ScratchFile&& other) {
104 *this = std::move(other);
105}
106
107ScratchFile& ScratchFile::operator=(ScratchFile&& other) {
108 if (GetFile() != other.GetFile()) {
109 std::swap(filename_, other.filename_);
110 std::swap(file_, other.file_);
111 }
112 return *this;
113}
114
Ian Rogerse63db272014-07-15 15:36:11 -0700115ScratchFile::~ScratchFile() {
116 Unlink();
117}
118
119int ScratchFile::GetFd() const {
120 return file_->Fd();
121}
122
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800123void ScratchFile::Close() {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800124 if (file_.get() != nullptr) {
125 if (file_->FlushCloseOrErase() != 0) {
126 PLOG(WARNING) << "Error closing scratch file.";
127 }
128 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800129}
130
131void ScratchFile::Unlink() {
132 if (!OS::FileExists(filename_.c_str())) {
133 return;
134 }
135 Close();
Ian Rogerse63db272014-07-15 15:36:11 -0700136 int unlink_result = unlink(filename_.c_str());
137 CHECK_EQ(0, unlink_result);
138}
139
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700140static bool unstarted_initialized_ = false;
141
Andreas Gampe48864112017-01-19 17:23:17 -0800142CommonRuntimeTestImpl::CommonRuntimeTestImpl()
143 : class_linker_(nullptr), java_lang_dex_file_(nullptr) {
144}
Mathieu Chartier91c91162016-01-15 09:48:15 -0800145
146CommonRuntimeTestImpl::~CommonRuntimeTestImpl() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800147 // Ensure the dex files are cleaned up before the runtime.
148 loaded_dex_files_.clear();
149 runtime_.reset();
150}
Ian Rogerse63db272014-07-15 15:36:11 -0700151
Mathieu Chartier91c91162016-01-15 09:48:15 -0800152void CommonRuntimeTestImpl::SetUpAndroidRoot() {
Ian Rogerse63db272014-07-15 15:36:11 -0700153 if (IsHost()) {
154 // $ANDROID_ROOT is set on the device, but not necessarily on the host.
155 // But it needs to be set so that icu4c can find its locale data.
156 const char* android_root_from_env = getenv("ANDROID_ROOT");
157 if (android_root_from_env == nullptr) {
158 // Use ANDROID_HOST_OUT for ANDROID_ROOT if it is set.
159 const char* android_host_out = getenv("ANDROID_HOST_OUT");
160 if (android_host_out != nullptr) {
161 setenv("ANDROID_ROOT", android_host_out, 1);
162 } else {
163 // Build it from ANDROID_BUILD_TOP or cwd
164 std::string root;
165 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
166 if (android_build_top != nullptr) {
167 root += android_build_top;
168 } else {
169 // Not set by build server, so default to current directory
170 char* cwd = getcwd(nullptr, 0);
171 setenv("ANDROID_BUILD_TOP", cwd, 1);
172 root += cwd;
173 free(cwd);
174 }
175#if defined(__linux__)
176 root += "/out/host/linux-x86";
177#elif defined(__APPLE__)
178 root += "/out/host/darwin-x86";
179#else
180#error unsupported OS
181#endif
182 setenv("ANDROID_ROOT", root.c_str(), 1);
183 }
184 }
185 setenv("LD_LIBRARY_PATH", ":", 0); // Required by java.lang.System.<clinit>.
186
187 // Not set by build server, so default
188 if (getenv("ANDROID_HOST_OUT") == nullptr) {
189 setenv("ANDROID_HOST_OUT", getenv("ANDROID_ROOT"), 1);
190 }
191 }
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700192}
Ian Rogerse63db272014-07-15 15:36:11 -0700193
Mathieu Chartier91c91162016-01-15 09:48:15 -0800194void CommonRuntimeTestImpl::SetUpAndroidData(std::string& android_data) {
Ian Rogerse63db272014-07-15 15:36:11 -0700195 // On target, Cannot use /mnt/sdcard because it is mounted noexec, so use subdir of dalvik-cache
Andreas Gampe5a79fde2014-08-06 13:12:26 -0700196 if (IsHost()) {
197 const char* tmpdir = getenv("TMPDIR");
198 if (tmpdir != nullptr && tmpdir[0] != 0) {
199 android_data = tmpdir;
200 } else {
201 android_data = "/tmp";
202 }
203 } else {
204 android_data = "/data/dalvik-cache";
205 }
206 android_data += "/art-data-XXXXXX";
Ian Rogerse63db272014-07-15 15:36:11 -0700207 if (mkdtemp(&android_data[0]) == nullptr) {
208 PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
209 }
210 setenv("ANDROID_DATA", android_data.c_str(), 1);
211}
212
Mathieu Chartier91c91162016-01-15 09:48:15 -0800213void CommonRuntimeTestImpl::TearDownAndroidData(const std::string& android_data,
214 bool fail_on_error) {
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700215 if (fail_on_error) {
216 ASSERT_EQ(rmdir(android_data.c_str()), 0);
217 } else {
218 rmdir(android_data.c_str());
219 }
220}
221
David Srbecky3e52aa42015-04-12 07:45:18 +0100222// Helper - find directory with the following format:
223// ${ANDROID_BUILD_TOP}/${subdir1}/${subdir2}-${version}/${subdir3}/bin/
224static std::string GetAndroidToolsDir(const std::string& subdir1,
225 const std::string& subdir2,
226 const std::string& subdir3) {
227 std::string root;
228 const char* android_build_top = getenv("ANDROID_BUILD_TOP");
229 if (android_build_top != nullptr) {
230 root = android_build_top;
231 } else {
232 // Not set by build server, so default to current directory
233 char* cwd = getcwd(nullptr, 0);
234 setenv("ANDROID_BUILD_TOP", cwd, 1);
235 root = cwd;
236 free(cwd);
237 }
238
239 std::string toolsdir = root + "/" + subdir1;
240 std::string founddir;
241 DIR* dir;
242 if ((dir = opendir(toolsdir.c_str())) != nullptr) {
243 float maxversion = 0;
244 struct dirent* entry;
245 while ((entry = readdir(dir)) != nullptr) {
246 std::string format = subdir2 + "-%f";
247 float version;
248 if (std::sscanf(entry->d_name, format.c_str(), &version) == 1) {
249 if (version > maxversion) {
250 maxversion = version;
251 founddir = toolsdir + "/" + entry->d_name + "/" + subdir3 + "/bin/";
252 }
253 }
254 }
255 closedir(dir);
256 }
257
258 if (founddir.empty()) {
Roland Levillain91d65e02016-01-19 15:59:16 +0000259 ADD_FAILURE() << "Cannot find Android tools directory.";
David Srbecky3e52aa42015-04-12 07:45:18 +0100260 }
261 return founddir;
262}
263
Mathieu Chartier91c91162016-01-15 09:48:15 -0800264std::string CommonRuntimeTestImpl::GetAndroidHostToolsDir() {
David Srbecky3e52aa42015-04-12 07:45:18 +0100265 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/host",
266 "x86_64-linux-glibc2.15",
267 "x86_64-linux");
268}
269
Mathieu Chartier91c91162016-01-15 09:48:15 -0800270std::string CommonRuntimeTestImpl::GetAndroidTargetToolsDir(InstructionSet isa) {
David Srbecky3e52aa42015-04-12 07:45:18 +0100271 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000272 case InstructionSet::kArm:
273 case InstructionSet::kThumb2:
David Srbecky3e52aa42015-04-12 07:45:18 +0100274 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/arm",
275 "arm-linux-androideabi",
276 "arm-linux-androideabi");
Vladimir Marko33bff252017-11-01 14:35:42 +0000277 case InstructionSet::kArm64:
David Srbecky3e52aa42015-04-12 07:45:18 +0100278 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/aarch64",
279 "aarch64-linux-android",
280 "aarch64-linux-android");
Vladimir Marko33bff252017-11-01 14:35:42 +0000281 case InstructionSet::kX86:
282 case InstructionSet::kX86_64:
David Srbecky3e52aa42015-04-12 07:45:18 +0100283 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/x86",
284 "x86_64-linux-android",
285 "x86_64-linux-android");
Vladimir Marko33bff252017-11-01 14:35:42 +0000286 case InstructionSet::kMips:
287 case InstructionSet::kMips64:
David Srbecky3e52aa42015-04-12 07:45:18 +0100288 return GetAndroidToolsDir("prebuilts/gcc/linux-x86/mips",
289 "mips64el-linux-android",
290 "mips64el-linux-android");
Vladimir Marko33bff252017-11-01 14:35:42 +0000291 case InstructionSet::kNone:
David Srbecky3e52aa42015-04-12 07:45:18 +0100292 break;
293 }
294 ADD_FAILURE() << "Invalid isa " << isa;
295 return "";
296}
297
Mathieu Chartier91c91162016-01-15 09:48:15 -0800298std::string CommonRuntimeTestImpl::GetCoreArtLocation() {
Igor Murashkin37743352014-11-13 14:38:00 -0800299 return GetCoreFileLocation("art");
300}
301
Mathieu Chartier91c91162016-01-15 09:48:15 -0800302std::string CommonRuntimeTestImpl::GetCoreOatLocation() {
Igor Murashkin37743352014-11-13 14:38:00 -0800303 return GetCoreFileLocation("oat");
304}
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700305
Mathieu Chartier91c91162016-01-15 09:48:15 -0800306std::unique_ptr<const DexFile> CommonRuntimeTestImpl::LoadExpectSingleDexFile(
307 const char* location) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800308 std::vector<std::unique_ptr<const DexFile>> dex_files;
Ian Rogerse63db272014-07-15 15:36:11 -0700309 std::string error_msg;
Richard Uhler66d874d2015-01-15 09:37:19 -0800310 MemMap::Init();
Aart Bik37d6a3b2016-06-21 18:30:10 -0700311 static constexpr bool kVerifyChecksum = true;
David Sehr013fd802018-01-11 22:55:24 -0800312 const ArtDexFileLoader dex_file_loader;
313 if (!dex_file_loader.Open(
Nicolas Geoffray095c6c92017-10-19 13:59:55 +0100314 location, location, /* verify */ true, kVerifyChecksum, &error_msg, &dex_files)) {
Ian Rogerse63db272014-07-15 15:36:11 -0700315 LOG(FATAL) << "Could not open .dex file '" << location << "': " << error_msg << "\n";
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800316 UNREACHABLE();
Ian Rogerse63db272014-07-15 15:36:11 -0700317 } else {
318 CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << location;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800319 return std::move(dex_files[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700320 }
321}
322
Mathieu Chartier91c91162016-01-15 09:48:15 -0800323void CommonRuntimeTestImpl::SetUp() {
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700324 SetUpAndroidRoot();
325 SetUpAndroidData(android_data_);
Ian Rogerse63db272014-07-15 15:36:11 -0700326 dalvik_cache_.append(android_data_.c_str());
327 dalvik_cache_.append("/dalvik-cache");
328 int mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
329 ASSERT_EQ(mkdir_result, 0);
330
Ian Rogerse63db272014-07-15 15:36:11 -0700331 std::string min_heap_string(StringPrintf("-Xms%zdm", gc::Heap::kDefaultInitialSize / MB));
332 std::string max_heap_string(StringPrintf("-Xmx%zdm", gc::Heap::kDefaultMaximumSize / MB));
333
Ian Rogerse63db272014-07-15 15:36:11 -0700334
335 RuntimeOptions options;
Narayan Kamathd1ef4362015-11-12 11:49:06 +0000336 std::string boot_class_path_string = "-Xbootclasspath";
337 for (const std::string &core_dex_file_name : GetLibCoreDexFileNames()) {
338 boot_class_path_string += ":";
339 boot_class_path_string += core_dex_file_name;
340 }
341
Richard Uhlerc2752592015-01-02 13:28:22 -0800342 options.push_back(std::make_pair(boot_class_path_string, nullptr));
Ian Rogerse63db272014-07-15 15:36:11 -0700343 options.push_back(std::make_pair("-Xcheck:jni", nullptr));
Richard Uhlerc2752592015-01-02 13:28:22 -0800344 options.push_back(std::make_pair(min_heap_string, nullptr));
345 options.push_back(std::make_pair(max_heap_string, nullptr));
Andreas Gampe1c5b42f2017-06-15 18:20:45 -0700346 options.push_back(std::make_pair("-XX:SlowDebug=true", nullptr));
Andreas Gampe46c4c852017-06-21 19:49:08 -0700347 static bool gSlowDebugTestFlag = false;
348 RegisterRuntimeDebugFlag(&gSlowDebugTestFlag);
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700349
350 callbacks_.reset(new NoopCompilerCallbacks());
351
Ian Rogerse63db272014-07-15 15:36:11 -0700352 SetUpRuntimeOptions(&options);
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800353
Andreas Gampebb9c6b12015-03-29 13:56:36 -0700354 // Install compiler-callbacks if SetupRuntimeOptions hasn't deleted them.
355 if (callbacks_.get() != nullptr) {
356 options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
357 }
358
Richard Uhler66d874d2015-01-15 09:37:19 -0800359 PreRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700360 if (!Runtime::Create(options, false)) {
361 LOG(FATAL) << "Failed to create runtime";
362 return;
363 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800364 PostRuntimeCreate();
Ian Rogerse63db272014-07-15 15:36:11 -0700365 runtime_.reset(Runtime::Current());
366 class_linker_ = runtime_->GetClassLinker();
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700367
Andreas Gampea00f0122015-12-16 16:54:35 -0800368 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
369 // Runtime::Start, give it away now and then switch to a more managable ScopedObjectAccess.
370 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
371
372 // Get the boot class path from the runtime so it can be used in tests.
373 boot_class_path_ = class_linker_->GetBootClassPath();
374 ASSERT_FALSE(boot_class_path_.empty());
375 java_lang_dex_file_ = boot_class_path_[0];
376
377 FinalizeSetup();
Andreas Gampe46c4c852017-06-21 19:49:08 -0700378
379 // Ensure that we're really running with debug checks enabled.
380 CHECK(gSlowDebugTestFlag);
Andreas Gampea00f0122015-12-16 16:54:35 -0800381}
382
Mathieu Chartier91c91162016-01-15 09:48:15 -0800383void CommonRuntimeTestImpl::FinalizeSetup() {
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700384 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
385 // set up.
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700386 if (!unstarted_initialized_) {
Andreas Gampe799681b2015-05-15 19:24:12 -0700387 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe9b5cba42015-03-11 09:53:50 -0700388 unstarted_initialized_ = true;
389 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700390
Andreas Gampea00f0122015-12-16 16:54:35 -0800391 {
392 ScopedObjectAccess soa(Thread::Current());
393 class_linker_->RunRootClinits();
394 }
Ian Rogerse63db272014-07-15 15:36:11 -0700395
396 // We're back in native, take the opportunity to initialize well known classes.
397 WellKnownClasses::Init(Thread::Current()->GetJniEnv());
398
399 // Create the heap thread pool so that the GC runs in parallel for tests. Normally, the thread
400 // pool is created by the runtime.
401 runtime_->GetHeap()->CreateThreadPool();
402 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption before the test
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700403 // Reduce timinig-dependent flakiness in OOME behavior (eg StubTest.AllocObject).
404 runtime_->GetHeap()->SetMinIntervalHomogeneousSpaceCompactionByOom(0U);
Ian Rogerse63db272014-07-15 15:36:11 -0700405}
406
Mathieu Chartierf70fe3d2017-06-21 15:24:02 -0700407void CommonRuntimeTestImpl::ClearDirectory(const char* dirpath, bool recursive) {
Alex Lighta59dd802014-07-02 16:28:08 -0700408 ASSERT_TRUE(dirpath != nullptr);
409 DIR* dir = opendir(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700410 ASSERT_TRUE(dir != nullptr);
411 dirent* e;
Alex Lighta59dd802014-07-02 16:28:08 -0700412 struct stat s;
Ian Rogerse63db272014-07-15 15:36:11 -0700413 while ((e = readdir(dir)) != nullptr) {
414 if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
415 continue;
416 }
Jeff Haof0a3f092014-07-24 16:26:09 -0700417 std::string filename(dirpath);
Ian Rogerse63db272014-07-15 15:36:11 -0700418 filename.push_back('/');
419 filename.append(e->d_name);
Alex Lighta59dd802014-07-02 16:28:08 -0700420 int stat_result = lstat(filename.c_str(), &s);
421 ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
422 if (S_ISDIR(s.st_mode)) {
Mathieu Chartierf70fe3d2017-06-21 15:24:02 -0700423 if (recursive) {
424 ClearDirectory(filename.c_str());
425 int rmdir_result = rmdir(filename.c_str());
426 ASSERT_EQ(0, rmdir_result) << filename;
427 }
Alex Lighta59dd802014-07-02 16:28:08 -0700428 } else {
429 int unlink_result = unlink(filename.c_str());
430 ASSERT_EQ(0, unlink_result) << filename;
431 }
Ian Rogerse63db272014-07-15 15:36:11 -0700432 }
433 closedir(dir);
Alex Lighta59dd802014-07-02 16:28:08 -0700434}
435
Mathieu Chartier91c91162016-01-15 09:48:15 -0800436void CommonRuntimeTestImpl::TearDown() {
Alex Lighta59dd802014-07-02 16:28:08 -0700437 const char* android_data = getenv("ANDROID_DATA");
438 ASSERT_TRUE(android_data != nullptr);
439 ClearDirectory(dalvik_cache_.c_str());
Ian Rogerse63db272014-07-15 15:36:11 -0700440 int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
441 ASSERT_EQ(0, rmdir_cache_result);
Andreas Gampe7747c8d2014-08-06 14:53:03 -0700442 TearDownAndroidData(android_data_, true);
Andreas Gampe3f41a012016-02-18 16:53:41 -0800443 dalvik_cache_.clear();
Ian Rogerse63db272014-07-15 15:36:11 -0700444
Andreas Gampe48864112017-01-19 17:23:17 -0800445 if (runtime_ != nullptr) {
446 runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption after the test
447 }
Ian Rogerse63db272014-07-15 15:36:11 -0700448}
449
Andreas Gampec7d4a582015-09-30 11:52:02 -0700450static std::string GetDexFileName(const std::string& jar_prefix, bool host) {
451 std::string path;
452 if (host) {
Ian Rogerse63db272014-07-15 15:36:11 -0700453 const char* host_dir = getenv("ANDROID_HOST_OUT");
454 CHECK(host_dir != nullptr);
Andreas Gampec7d4a582015-09-30 11:52:02 -0700455 path = host_dir;
456 } else {
457 path = GetAndroidRoot();
Ian Rogerse63db272014-07-15 15:36:11 -0700458 }
Andreas Gampec7d4a582015-09-30 11:52:02 -0700459
460 std::string suffix = host
461 ? "-hostdex" // The host version.
462 : "-testdex"; // The unstripped target version.
463
464 return StringPrintf("%s/framework/%s%s.jar", path.c_str(), jar_prefix.c_str(), suffix.c_str());
465}
466
Mathieu Chartier91c91162016-01-15 09:48:15 -0800467std::vector<std::string> CommonRuntimeTestImpl::GetLibCoreDexFileNames() {
Andreas Gampec7d4a582015-09-30 11:52:02 -0700468 return std::vector<std::string>({GetDexFileName("core-oj", IsHost()),
469 GetDexFileName("core-libart", IsHost())});
Ian Rogerse63db272014-07-15 15:36:11 -0700470}
471
Mathieu Chartier91c91162016-01-15 09:48:15 -0800472std::string CommonRuntimeTestImpl::GetTestAndroidRoot() {
Ian Rogerse63db272014-07-15 15:36:11 -0700473 if (IsHost()) {
474 const char* host_dir = getenv("ANDROID_HOST_OUT");
475 CHECK(host_dir != nullptr);
476 return host_dir;
477 }
478 return GetAndroidRoot();
479}
480
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700481// Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
482#ifdef ART_TARGET
483#ifndef ART_TARGET_NATIVETEST_DIR
484#error "ART_TARGET_NATIVETEST_DIR not set."
485#endif
486// Wrap it as a string literal.
487#define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
488#else
489#define ART_TARGET_NATIVETEST_DIR_STRING ""
490#endif
491
Andreas Gampee1459ae2016-06-29 09:36:30 -0700492std::string CommonRuntimeTestImpl::GetTestDexFileName(const char* name) const {
Ian Rogerse63db272014-07-15 15:36:11 -0700493 CHECK(name != nullptr);
494 std::string filename;
495 if (IsHost()) {
496 filename += getenv("ANDROID_HOST_OUT");
497 filename += "/framework/";
498 } else {
Andreas Gampe1fe5e5c2014-07-11 21:14:35 -0700499 filename += ART_TARGET_NATIVETEST_DIR_STRING;
Ian Rogerse63db272014-07-15 15:36:11 -0700500 }
501 filename += "art-gtest-";
502 filename += name;
503 filename += ".jar";
Richard Uhler66d874d2015-01-15 09:37:19 -0800504 return filename;
505}
506
Mathieu Chartier91c91162016-01-15 09:48:15 -0800507std::vector<std::unique_ptr<const DexFile>> CommonRuntimeTestImpl::OpenTestDexFiles(
508 const char* name) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800509 std::string filename = GetTestDexFileName(name);
Aart Bik37d6a3b2016-06-21 18:30:10 -0700510 static constexpr bool kVerifyChecksum = true;
Ian Rogerse63db272014-07-15 15:36:11 -0700511 std::string error_msg;
David Sehr013fd802018-01-11 22:55:24 -0800512 const ArtDexFileLoader dex_file_loader;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800513 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr013fd802018-01-11 22:55:24 -0800514 bool success = dex_file_loader.Open(filename.c_str(),
515 filename.c_str(),
516 /* verify */ true,
517 kVerifyChecksum,
518 &error_msg, &dex_files);
Ian Rogerse63db272014-07-15 15:36:11 -0700519 CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800520 for (auto& dex_file : dex_files) {
Ian Rogerse63db272014-07-15 15:36:11 -0700521 CHECK_EQ(PROT_READ, dex_file->GetPermissions());
522 CHECK(dex_file->IsReadOnly());
523 }
Ian Rogerse63db272014-07-15 15:36:11 -0700524 return dex_files;
525}
526
Mathieu Chartier91c91162016-01-15 09:48:15 -0800527std::unique_ptr<const DexFile> CommonRuntimeTestImpl::OpenTestDexFile(const char* name) {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800528 std::vector<std::unique_ptr<const DexFile>> vector = OpenTestDexFiles(name);
Ian Rogerse63db272014-07-15 15:36:11 -0700529 EXPECT_EQ(1U, vector.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800530 return std::move(vector[0]);
Ian Rogerse63db272014-07-15 15:36:11 -0700531}
532
Mathieu Chartier91c91162016-01-15 09:48:15 -0800533std::vector<const DexFile*> CommonRuntimeTestImpl::GetDexFiles(jobject jclass_loader) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700534 ScopedObjectAccess soa(Thread::Current());
535
Calin Juravlec79470d2017-07-12 17:37:42 -0700536 StackHandleScope<1> hs(soa.Self());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700537 Handle<mirror::ClassLoader> class_loader = hs.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700538 soa.Decode<mirror::ClassLoader>(jclass_loader));
Calin Juravlec79470d2017-07-12 17:37:42 -0700539 return GetDexFiles(soa, class_loader);
540}
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700541
Calin Juravlec79470d2017-07-12 17:37:42 -0700542std::vector<const DexFile*> CommonRuntimeTestImpl::GetDexFiles(
543 ScopedObjectAccess& soa,
544 Handle<mirror::ClassLoader> class_loader) {
Calin Juravlec79470d2017-07-12 17:37:42 -0700545 DCHECK(
546 (class_loader->GetClass() ==
547 soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader)) ||
548 (class_loader->GetClass() ==
549 soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_DelegateLastClassLoader)));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700550
Andreas Gampeb8e7c372018-02-20 18:24:55 -0800551 std::vector<const DexFile*> ret;
552 VisitClassLoaderDexFiles(soa,
553 class_loader,
554 [&](const DexFile* cp_dex_file) {
555 if (cp_dex_file == nullptr) {
556 LOG(WARNING) << "Null DexFile";
557 } else {
558 ret.push_back(cp_dex_file);
559 }
560 return true;
561 });
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700562 return ret;
563}
564
Mathieu Chartier91c91162016-01-15 09:48:15 -0800565const DexFile* CommonRuntimeTestImpl::GetFirstDexFile(jobject jclass_loader) {
Andreas Gampe81c6f8d2015-03-25 17:19:53 -0700566 std::vector<const DexFile*> tmp(GetDexFiles(jclass_loader));
567 DCHECK(!tmp.empty());
568 const DexFile* ret = tmp[0];
569 DCHECK(ret != nullptr);
570 return ret;
571}
572
Nicolas Geoffrayd01f60c2016-10-28 14:45:48 +0100573jobject CommonRuntimeTestImpl::LoadMultiDex(const char* first_dex_name,
574 const char* second_dex_name) {
575 std::vector<std::unique_ptr<const DexFile>> first_dex_files = OpenTestDexFiles(first_dex_name);
576 std::vector<std::unique_ptr<const DexFile>> second_dex_files = OpenTestDexFiles(second_dex_name);
577 std::vector<const DexFile*> class_path;
578 CHECK_NE(0U, first_dex_files.size());
579 CHECK_NE(0U, second_dex_files.size());
580 for (auto& dex_file : first_dex_files) {
581 class_path.push_back(dex_file.get());
582 loaded_dex_files_.push_back(std::move(dex_file));
583 }
584 for (auto& dex_file : second_dex_files) {
585 class_path.push_back(dex_file.get());
586 loaded_dex_files_.push_back(std::move(dex_file));
587 }
588
589 Thread* self = Thread::Current();
590 jobject class_loader = Runtime::Current()->GetClassLinker()->CreatePathClassLoader(self,
591 class_path);
592 self->SetClassLoaderOverride(class_loader);
593 return class_loader;
594}
595
Mathieu Chartier91c91162016-01-15 09:48:15 -0800596jobject CommonRuntimeTestImpl::LoadDex(const char* dex_name) {
Calin Juravle7865ac72017-06-28 11:03:12 -0700597 jobject class_loader = LoadDexInPathClassLoader(dex_name, nullptr);
598 Thread::Current()->SetClassLoaderOverride(class_loader);
599 return class_loader;
600}
601
602jobject CommonRuntimeTestImpl::LoadDexInWellKnownClassLoader(const std::string& dex_name,
603 jclass loader_class,
604 jobject parent_loader) {
605 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenTestDexFiles(dex_name.c_str());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800606 std::vector<const DexFile*> class_path;
Ian Rogerse63db272014-07-15 15:36:11 -0700607 CHECK_NE(0U, dex_files.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800608 for (auto& dex_file : dex_files) {
609 class_path.push_back(dex_file.get());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800610 loaded_dex_files_.push_back(std::move(dex_file));
Ian Rogerse63db272014-07-15 15:36:11 -0700611 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700612 Thread* self = Thread::Current();
Calin Juravle7865ac72017-06-28 11:03:12 -0700613 ScopedObjectAccess soa(self);
614
615 jobject result = Runtime::Current()->GetClassLinker()->CreateWellKnownClassLoader(
616 self,
617 class_path,
618 loader_class,
619 parent_loader);
620
621 {
622 // Verify we build the correct chain.
623
624 ObjPtr<mirror::ClassLoader> actual_class_loader = soa.Decode<mirror::ClassLoader>(result);
625 // Verify that the result has the correct class.
626 CHECK_EQ(soa.Decode<mirror::Class>(loader_class), actual_class_loader->GetClass());
627 // Verify that the parent is not null. The boot class loader will be set up as a
628 // proper object.
629 ObjPtr<mirror::ClassLoader> actual_parent(actual_class_loader->GetParent());
630 CHECK(actual_parent != nullptr);
631
632 if (parent_loader != nullptr) {
633 // We were given a parent. Verify that it's what we expect.
634 ObjPtr<mirror::ClassLoader> expected_parent = soa.Decode<mirror::ClassLoader>(parent_loader);
635 CHECK_EQ(expected_parent, actual_parent);
636 } else {
637 // No parent given. The parent must be the BootClassLoader.
638 CHECK(Runtime::Current()->GetClassLinker()->IsBootClassLoader(soa, actual_parent));
639 }
640 }
641
642 return result;
643}
644
645jobject CommonRuntimeTestImpl::LoadDexInPathClassLoader(const std::string& dex_name,
646 jobject parent_loader) {
647 return LoadDexInWellKnownClassLoader(dex_name,
648 WellKnownClasses::dalvik_system_PathClassLoader,
649 parent_loader);
650}
651
652jobject CommonRuntimeTestImpl::LoadDexInDelegateLastClassLoader(const std::string& dex_name,
653 jobject parent_loader) {
654 return LoadDexInWellKnownClassLoader(dex_name,
655 WellKnownClasses::dalvik_system_DelegateLastClassLoader,
656 parent_loader);
Ian Rogerse63db272014-07-15 15:36:11 -0700657}
658
Mathieu Chartier91c91162016-01-15 09:48:15 -0800659std::string CommonRuntimeTestImpl::GetCoreFileLocation(const char* suffix) {
Igor Murashkin37743352014-11-13 14:38:00 -0800660 CHECK(suffix != nullptr);
661
662 std::string location;
663 if (IsHost()) {
664 const char* host_dir = getenv("ANDROID_HOST_OUT");
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700665 CHECK(host_dir != nullptr);
Richard Uhler67e1dc52017-02-06 16:50:17 +0000666 location = StringPrintf("%s/framework/core.%s", host_dir, suffix);
Igor Murashkin37743352014-11-13 14:38:00 -0800667 } else {
Richard Uhler67e1dc52017-02-06 16:50:17 +0000668 location = StringPrintf("/data/art-test/core.%s", suffix);
Igor Murashkin37743352014-11-13 14:38:00 -0800669 }
670
671 return location;
672}
673
Calin Juravlec79470d2017-07-12 17:37:42 -0700674std::string CommonRuntimeTestImpl::CreateClassPath(
675 const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
676 CHECK(!dex_files.empty());
677 std::string classpath = dex_files[0]->GetLocation();
678 for (size_t i = 1; i < dex_files.size(); i++) {
679 classpath += ":" + dex_files[i]->GetLocation();
680 }
681 return classpath;
682}
683
684std::string CommonRuntimeTestImpl::CreateClassPathWithChecksums(
685 const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
686 CHECK(!dex_files.empty());
687 std::string classpath = dex_files[0]->GetLocation() + "*" +
688 std::to_string(dex_files[0]->GetLocationChecksum());
689 for (size_t i = 1; i < dex_files.size(); i++) {
690 classpath += ":" + dex_files[i]->GetLocation() + "*" +
691 std::to_string(dex_files[i]->GetLocationChecksum());
692 }
693 return classpath;
694}
695
Andreas Gampe26761f72017-07-20 18:00:39 -0700696void CommonRuntimeTestImpl::FillHeap(Thread* self,
697 ClassLinker* class_linker,
698 VariableSizedHandleScope* handle_scope) {
699 DCHECK(handle_scope != nullptr);
700
701 Runtime::Current()->GetHeap()->SetIdealFootprint(1 * GB);
702
703 // Class java.lang.Object.
704 Handle<mirror::Class> c(handle_scope->NewHandle(
705 class_linker->FindSystemClass(self, "Ljava/lang/Object;")));
706 // Array helps to fill memory faster.
707 Handle<mirror::Class> ca(handle_scope->NewHandle(
708 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
709
710 // Start allocating with ~128K
711 size_t length = 128 * KB;
712 while (length > 40) {
713 const int32_t array_length = length / 4; // Object[] has elements of size 4.
714 MutableHandle<mirror::Object> h(handle_scope->NewHandle<mirror::Object>(
715 mirror::ObjectArray<mirror::Object>::Alloc(self, ca.Get(), array_length)));
716 if (self->IsExceptionPending() || h == nullptr) {
717 self->ClearException();
718
719 // Try a smaller length
720 length = length / 2;
721 // Use at most a quarter the reported free space.
722 size_t mem = Runtime::Current()->GetHeap()->GetFreeMemory();
723 if (length * 4 > mem) {
724 length = mem / 4;
725 }
726 }
727 }
728
729 // Allocate simple objects till it fails.
730 while (!self->IsExceptionPending()) {
731 handle_scope->NewHandle<mirror::Object>(c->AllocObject(self));
732 }
733 self->ClearException();
734}
735
736void CommonRuntimeTestImpl::SetUpRuntimeOptionsForFillHeap(RuntimeOptions *options) {
737 // Use a smaller heap
738 bool found = false;
739 for (std::pair<std::string, const void*>& pair : *options) {
740 if (pair.first.find("-Xmx") == 0) {
741 pair.first = "-Xmx4M"; // Smallest we can go.
742 found = true;
743 }
744 }
745 if (!found) {
746 options->emplace_back("-Xmx4M", nullptr);
747 }
748}
749
Ian Rogerse63db272014-07-15 15:36:11 -0700750CheckJniAbortCatcher::CheckJniAbortCatcher() : vm_(Runtime::Current()->GetJavaVM()) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700751 vm_->SetCheckJniAbortHook(Hook, &actual_);
Ian Rogerse63db272014-07-15 15:36:11 -0700752}
753
754CheckJniAbortCatcher::~CheckJniAbortCatcher() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700755 vm_->SetCheckJniAbortHook(nullptr, nullptr);
Ian Rogerse63db272014-07-15 15:36:11 -0700756 EXPECT_TRUE(actual_.empty()) << actual_;
757}
758
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700759void CheckJniAbortCatcher::Check(const std::string& expected_text) {
760 Check(expected_text.c_str());
761}
762
Ian Rogerse63db272014-07-15 15:36:11 -0700763void CheckJniAbortCatcher::Check(const char* expected_text) {
764 EXPECT_TRUE(actual_.find(expected_text) != std::string::npos) << "\n"
765 << "Expected to find: " << expected_text << "\n"
766 << "In the output : " << actual_;
767 actual_.clear();
768}
769
770void CheckJniAbortCatcher::Hook(void* data, const std::string& reason) {
771 // We use += because when we're hooking the aborts like this, multiple problems can be found.
772 *reinterpret_cast<std::string*>(data) += reason;
773}
774
775} // namespace art