• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "common_art_test.h"
18 
19 #include <dirent.h>
20 #include <dlfcn.h>
21 #include <fcntl.h>
22 #include <ftw.h>
23 #include <libgen.h>
24 #include <stdlib.h>
25 #include <sys/capability.h>
26 #include <unistd.h>
27 
28 #include <cstdio>
29 #include <filesystem>
30 #include <functional>
31 
32 #include "android-base/file.h"
33 #include "android-base/logging.h"
34 #include "android-base/process.h"
35 #include "android-base/scopeguard.h"
36 #include "android-base/stringprintf.h"
37 #include "android-base/unique_fd.h"
38 #include "art_field-inl.h"
39 #include "base/file_utils.h"
40 #include "base/logging.h"
41 #include "base/macros.h"
42 #include "base/mem_map.h"
43 #include "base/mutex.h"
44 #include "base/os.h"
45 #include "base/runtime_debug.h"
46 #include "base/scoped_cap.h"
47 #include "base/stl_util.h"
48 #include "base/testing.h"
49 #include "base/unix_file/fd_file.h"
50 #include "dex/art_dex_file_loader.h"
51 #include "dex/dex_file-inl.h"
52 #include "dex/dex_file_loader.h"
53 #include "dex/primitive.h"
54 #include "gtest/gtest.h"
55 #include "nativehelper/scoped_local_ref.h"
56 
57 namespace art {
58 
59 using android::base::StringPrintf;
60 
ScratchDir(bool keep_files)61 ScratchDir::ScratchDir(bool keep_files) : keep_files_(keep_files) {
62   // ANDROID_DATA needs to be set
63   CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
64       "Are you subclassing RuntimeTest?";
65   path_ = getenv("ANDROID_DATA");
66   path_ += "/tmp-XXXXXX";
67   bool ok = (mkdtemp(&path_[0]) != nullptr);
68   CHECK(ok) << strerror(errno) << " for " << path_;
69   path_ += "/";
70 }
71 
~ScratchDir()72 ScratchDir::~ScratchDir() {
73   if (!keep_files_) {
74     std::filesystem::remove_all(path_);
75   }
76 }
77 
ScratchFile()78 ScratchFile::ScratchFile() {
79   // ANDROID_DATA needs to be set
80   CHECK_NE(static_cast<char*>(nullptr), getenv("ANDROID_DATA")) <<
81       "Are you subclassing RuntimeTest?";
82   filename_ = getenv("ANDROID_DATA");
83   filename_ += "/TmpFile-XXXXXX";
84   int fd = mkstemp(&filename_[0]);
85   CHECK_NE(-1, fd) << strerror(errno) << " for " << filename_;
86   file_.reset(new File(fd, GetFilename(), true));
87 }
88 
ScratchFile(const ScratchFile & other,const char * suffix)89 ScratchFile::ScratchFile(const ScratchFile& other, const char* suffix)
90     : ScratchFile(other.GetFilename() + suffix) {}
91 
ScratchFile(const std::string & filename)92 ScratchFile::ScratchFile(const std::string& filename) : filename_(filename) {
93   int fd = open(filename_.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666);
94   CHECK_NE(-1, fd);
95   file_.reset(new File(fd, GetFilename(), true));
96 }
97 
ScratchFile(File * file)98 ScratchFile::ScratchFile(File* file) {
99   CHECK(file != nullptr);
100   filename_ = file->GetPath();
101   file_.reset(file);
102 }
103 
ScratchFile(ScratchFile && other)104 ScratchFile::ScratchFile(ScratchFile&& other) noexcept {
105   *this = std::move(other);
106 }
107 
operator =(ScratchFile && other)108 ScratchFile& ScratchFile::operator=(ScratchFile&& other) noexcept {
109   if (GetFile() != other.GetFile()) {
110     std::swap(filename_, other.filename_);
111     std::swap(file_, other.file_);
112   }
113   return *this;
114 }
115 
~ScratchFile()116 ScratchFile::~ScratchFile() {
117   Unlink();
118 }
119 
GetFd() const120 int ScratchFile::GetFd() const {
121   return file_->Fd();
122 }
123 
Close()124 void ScratchFile::Close() {
125   if (file_ != nullptr) {
126     if (file_->FlushCloseOrErase() != 0) {
127       PLOG(WARNING) << "Error closing scratch file.";
128     }
129     file_.reset();
130   }
131 }
132 
Unlink()133 void ScratchFile::Unlink() {
134   if (!OS::FileExists(filename_.c_str())) {
135     return;
136   }
137   Close();
138   int unlink_result = unlink(filename_.c_str());
139   CHECK_EQ(0, unlink_result);
140 }
141 
142 // Temporarily drops all root capabilities when the test is run as root. This is a noop otherwise.
ScopedUnroot()143 android::base::ScopeGuard<std::function<void()>> ScopedUnroot() {
144   ScopedCap old_cap(cap_get_proc());
145   CHECK_NE(old_cap.Get(), nullptr);
146   ScopedCap new_cap(cap_dup(old_cap.Get()));
147   CHECK_NE(new_cap.Get(), nullptr);
148   CHECK_EQ(cap_clear_flag(new_cap.Get(), CAP_EFFECTIVE), 0);
149   CHECK_EQ(cap_set_proc(new_cap.Get()), 0);
150   // `old_cap` is actually not shared with anyone else, but we have to wrap it with a `shared_ptr`
151   // because `std::function` requires captures to be copyable.
152   return android::base::make_scope_guard(
153       [old_cap = std::make_shared<ScopedCap>(std::move(old_cap))]() {
154         CHECK_EQ(cap_set_proc(old_cap->Get()), 0);
155       });
156 }
157 
158 // Temporarily drops write permission on a file/directory.
ScopedInaccessible(const std::string & path)159 android::base::ScopeGuard<std::function<void()>> ScopedInaccessible(const std::string& path) {
160   std::filesystem::perms old_perms = std::filesystem::status(path).permissions();
161   std::filesystem::permissions(path, std::filesystem::perms::none);
162   return android::base::make_scope_guard([=]() { std::filesystem::permissions(path, old_perms); });
163 }
164 
SetUpAndroidRootEnvVars()165 void CommonArtTestImpl::SetUpAndroidRootEnvVars() {
166   if (IsHost()) {
167     std::string android_host_out = GetAndroidHostOut();
168 
169     // Environment variable ANDROID_ROOT is set on the device, but not
170     // necessarily on the host.
171     const char* android_root_from_env = getenv("ANDROID_ROOT");
172     if (android_root_from_env == nullptr) {
173       // Use ANDROID_HOST_OUT for ANDROID_ROOT.
174       setenv("ANDROID_ROOT", android_host_out.c_str(), 1);
175       android_root_from_env = getenv("ANDROID_ROOT");
176     }
177 
178     // Environment variable ANDROID_I18N_ROOT is set on the device, but not
179     // necessarily on the host. It needs to be set so that various libraries
180     // like libcore / icu4j / icu4c can find their data files.
181     const char* android_i18n_root_from_env = getenv("ANDROID_I18N_ROOT");
182     if (android_i18n_root_from_env == nullptr) {
183       // Use ${ANDROID_I18N_OUT}/com.android.i18n for ANDROID_I18N_ROOT.
184       std::string android_i18n_root = android_host_out;
185       android_i18n_root += "/com.android.i18n";
186       setenv("ANDROID_I18N_ROOT", android_i18n_root.c_str(), 1);
187     }
188 
189     // Environment variable ANDROID_ART_ROOT is set on the device, but not
190     // necessarily on the host. It needs to be set so that various libraries
191     // like libcore / icu4j / icu4c can find their data files.
192     const char* android_art_root_from_env = getenv("ANDROID_ART_ROOT");
193     if (android_art_root_from_env == nullptr) {
194       // Use ${ANDROID_HOST_OUT}/com.android.art for ANDROID_ART_ROOT.
195       std::string android_art_root = android_host_out;
196       android_art_root += "/com.android.art";
197       setenv("ANDROID_ART_ROOT", android_art_root.c_str(), 1);
198     }
199 
200     // Environment variable ANDROID_TZDATA_ROOT is set on the device, but not
201     // necessarily on the host. It needs to be set so that various libraries
202     // like libcore / icu4j / icu4c can find their data files.
203     const char* android_tzdata_root_from_env = getenv("ANDROID_TZDATA_ROOT");
204     if (android_tzdata_root_from_env == nullptr) {
205       // Use ${ANDROID_HOST_OUT}/com.android.tzdata for ANDROID_TZDATA_ROOT.
206       std::string android_tzdata_root = android_host_out;
207       android_tzdata_root += "/com.android.tzdata";
208       setenv("ANDROID_TZDATA_ROOT", android_tzdata_root.c_str(), 1);
209     }
210 
211     setenv("LD_LIBRARY_PATH", ":", 0);  // Required by java.lang.System.<clinit>.
212   }
213 }
214 
SetUpAndroidDataDir(std::string & android_data)215 void CommonArtTestImpl::SetUpAndroidDataDir(std::string& android_data) {
216   if (IsHost()) {
217     const char* tmpdir = getenv("TMPDIR");
218     if (tmpdir != nullptr && tmpdir[0] != 0) {
219       android_data = tmpdir;
220     } else {
221       android_data = "/tmp";
222     }
223   } else {
224     // On target, we cannot use `/mnt/sdcard` because it is mounted `noexec`,
225     // nor `/data/dalvik-cache` as it is not accessible on `user` builds.
226     // Instead, use `/data/local/tmp`, which does not require any special
227     // permission.
228     android_data = "/data/local/tmp";
229   }
230   android_data += "/art-data-XXXXXX";
231   if (mkdtemp(&android_data[0]) == nullptr) {
232     PLOG(FATAL) << "mkdtemp(\"" << &android_data[0] << "\") failed";
233   }
234   setenv("ANDROID_DATA", android_data.c_str(), 1);
235 }
236 
SetUp()237 void CommonArtTestImpl::SetUp() {
238   // Some tests clear these and when running with --no_isolate this can cause
239   // later tests to fail
240   Locks::Init();
241   MemMap::Init();
242   SetUpAndroidRootEnvVars();
243   SetUpAndroidDataDir(android_data_);
244 
245   // Re-use the data temporary directory for /system_ext tests
246   android_system_ext_.append(android_data_);
247   android_system_ext_.append("/system_ext");
248   int mkdir_result = mkdir(android_system_ext_.c_str(), 0700);
249   ASSERT_EQ(mkdir_result, 0);
250   setenv("SYSTEM_EXT_ROOT", android_system_ext_.c_str(), 1);
251 
252   std::string system_ext_framework = android_system_ext_ + "/framework";
253   mkdir_result = mkdir(system_ext_framework.c_str(), 0700);
254   ASSERT_EQ(mkdir_result, 0);
255 
256   dalvik_cache_.append(android_data_);
257   dalvik_cache_.append("/dalvik-cache");
258   mkdir_result = mkdir(dalvik_cache_.c_str(), 0700);
259   ASSERT_EQ(mkdir_result, 0);
260 
261   if (kIsDebugBuild) {
262     static bool gSlowDebugTestFlag = false;
263     RegisterRuntimeDebugFlag(&gSlowDebugTestFlag);
264     SetRuntimeDebugFlagsEnabled(true);
265     CHECK(gSlowDebugTestFlag);
266   }
267 }
268 
TearDownAndroidDataDir(const std::string & android_data,bool fail_on_error)269 void CommonArtTestImpl::TearDownAndroidDataDir(const std::string& android_data,
270                                                bool fail_on_error) {
271   if (fail_on_error) {
272     ASSERT_EQ(rmdir(android_data.c_str()), 0);
273   } else {
274     rmdir(android_data.c_str());
275   }
276 }
277 
278 // Get prebuilt binary tool.
279 // The paths need to be updated when Android prebuilts update.
GetAndroidTool(const char * name,InstructionSet)280 std::string CommonArtTestImpl::GetAndroidTool(const char* name, InstructionSet) {
281 #ifndef ART_CLANG_PATH
282   UNUSED(name);
283   LOG(FATAL) << "There are no prebuilt tools available.";
284   UNREACHABLE();
285 #else
286   std::string path = GetAndroidBuildTop() + ART_CLANG_PATH + "/bin/";
287   CHECK(OS::DirectoryExists(path.c_str())) << path;
288   path += name;
289   CHECK(OS::FileExists(path.c_str())) << path;
290   return path;
291 #endif
292 }
293 
GetCoreArtLocation()294 std::string CommonArtTestImpl::GetCoreArtLocation() {
295   return GetCoreFileLocation("art");
296 }
297 
GetCoreOatLocation()298 std::string CommonArtTestImpl::GetCoreOatLocation() {
299   return GetCoreFileLocation("oat");
300 }
301 
LoadExpectSingleDexFile(const char * location)302 std::unique_ptr<const DexFile> CommonArtTestImpl::LoadExpectSingleDexFile(const char* location) {
303   std::vector<std::unique_ptr<const DexFile>> dex_files;
304   std::string error_msg;
305   MemMap::Init();
306   static constexpr bool kVerifyChecksum = true;
307   std::string filename(IsHost() ? GetAndroidBuildTop() + location : location);
308   ArtDexFileLoader dex_file_loader(filename.c_str(), std::string(location));
309   if (!dex_file_loader.Open(/* verify= */ true, kVerifyChecksum, &error_msg, &dex_files)) {
310     LOG(FATAL) << "Could not open .dex file '" << filename << "': " << error_msg << "\n";
311     UNREACHABLE();
312   }
313   CHECK_EQ(1U, dex_files.size()) << "Expected only one dex file in " << filename;
314   return std::move(dex_files[0]);
315 }
316 
ClearDirectory(const char * dirpath,bool recursive)317 void CommonArtTestImpl::ClearDirectory(const char* dirpath, bool recursive) {
318   CHECK(dirpath != nullptr) << std::string(dirpath);
319   DIR* dir = opendir(dirpath);
320   CHECK(dir != nullptr) << std::string(dirpath);
321   dirent* e;
322   struct stat s;
323   while ((e = readdir(dir)) != nullptr) {
324     if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
325       continue;
326     }
327     std::string filename(dirpath);
328     filename.push_back('/');
329     filename.append(e->d_name);
330     int stat_result = lstat(filename.c_str(), &s);
331     ASSERT_EQ(0, stat_result) << "unable to stat " << filename;
332     if (S_ISDIR(s.st_mode)) {
333       if (recursive) {
334         ClearDirectory(filename.c_str());
335         int rmdir_result = rmdir(filename.c_str());
336         ASSERT_EQ(0, rmdir_result) << filename;
337       }
338     } else {
339       int unlink_result = unlink(filename.c_str());
340       ASSERT_EQ(0, unlink_result) << filename;
341     }
342   }
343   closedir(dir);
344 }
345 
TearDown()346 void CommonArtTestImpl::TearDown() {
347   const char* android_data = getenv("ANDROID_DATA");
348   ASSERT_TRUE(android_data != nullptr);
349   ClearDirectory(dalvik_cache_.c_str());
350   int rmdir_cache_result = rmdir(dalvik_cache_.c_str());
351   ASSERT_EQ(0, rmdir_cache_result);
352   ClearDirectory(android_system_ext_.c_str(), true);
353   rmdir_cache_result = rmdir(android_system_ext_.c_str());
354   ASSERT_EQ(0, rmdir_cache_result);
355   TearDownAndroidDataDir(android_data_, true);
356   dalvik_cache_.clear();
357   android_system_ext_.clear();
358 }
359 
GetLibCoreModuleNames() const360 std::vector<std::string> CommonArtTestImpl::GetLibCoreModuleNames() const {
361   return art::testing::GetLibCoreModuleNames();
362 }
363 
364 // Check that for target builds we have ART_TARGET_NATIVETEST_DIR set.
365 #ifdef ART_TARGET
366 #ifndef ART_TARGET_NATIVETEST_DIR
367 #error "ART_TARGET_NATIVETEST_DIR not set."
368 #endif
369 // Wrap it as a string literal.
370 #define ART_TARGET_NATIVETEST_DIR_STRING STRINGIFY(ART_TARGET_NATIVETEST_DIR) "/"
371 #else
372 #define ART_TARGET_NATIVETEST_DIR_STRING ""
373 #endif
374 
GetTestDexFileName(const char * name) const375 std::string CommonArtTestImpl::GetTestDexFileName(const char* name) const {
376   CHECK(name != nullptr);
377   // The needed jar files for gtest are located next to the gtest binary itself.
378   std::string executable_dir = android::base::GetExecutableDirectory();
379   for (auto ext : {".jar", ".dex"}) {
380     std::string path = executable_dir + "/art-gtest-jars-" + name + ext;
381     if (OS::FileExists(path.c_str())) {
382       return path;
383     }
384   }
385   LOG(FATAL) << "Test file " << name << " not found";
386   UNREACHABLE();
387 }
388 
OpenDexFiles(const char * filename)389 std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenDexFiles(const char* filename) {
390   static constexpr bool kVerify = true;
391   static constexpr bool kVerifyChecksum = true;
392   std::string error_msg;
393   ArtDexFileLoader dex_file_loader(filename);
394   std::vector<std::unique_ptr<const DexFile>> dex_files;
395   bool success = dex_file_loader.Open(kVerify, kVerifyChecksum, &error_msg, &dex_files);
396   CHECK(success) << "Failed to open '" << filename << "': " << error_msg;
397   for (auto& dex_file : dex_files) {
398     CHECK(dex_file->IsReadOnly());
399   }
400   return dex_files;
401 }
402 
OpenDexFile(const char * filename)403 std::unique_ptr<const DexFile> CommonArtTestImpl::OpenDexFile(const char* filename) {
404   std::vector<std::unique_ptr<const DexFile>> dex_files(OpenDexFiles(filename));
405   CHECK_EQ(dex_files.size(), 1u) << "Expected only one dex file";
406   return std::move(dex_files[0]);
407 }
408 
OpenTestDexFiles(const char * name)409 std::vector<std::unique_ptr<const DexFile>> CommonArtTestImpl::OpenTestDexFiles(
410     const char* name) {
411   return OpenDexFiles(GetTestDexFileName(name).c_str());
412 }
413 
OpenTestDexFile(const char * name)414 std::unique_ptr<const DexFile> CommonArtTestImpl::OpenTestDexFile(const char* name) {
415   return OpenDexFile(GetTestDexFileName(name).c_str());
416 }
417 
GetImageDirectory()418 std::string CommonArtTestImpl::GetImageDirectory() {
419   if (IsHost()) {
420     return GetHostBootClasspathInstallRoot() + "/apex/art_boot_images/javalib";
421   }
422   // On device, the boot image is generated by `generate-boot-image`.
423   // In a standalone test, the boot image is located next to the gtest binary itself.
424   std::string path = android::base::GetExecutableDirectory() + "/art_boot_images";
425   if (OS::DirectoryExists(path.c_str())) {
426     return path;
427   }
428   // In a chroot environment prepared by scripts, the boot image is located in a predefined
429   // location on /system.
430   path = "/system/framework/art_boot_images";
431   if (OS::DirectoryExists(path.c_str())) {
432     return path;
433   }
434   // In art-target-gtest-chroot, the boot image is located in a predefined location on /data because
435   // /system is a mount point that replicates the real one on device.
436   path = "/data/local/tmp/art_boot_images";
437   if (OS::DirectoryExists(path.c_str())) {
438     return path;
439   }
440   LOG(FATAL) << "Boot image not found";
441   UNREACHABLE();
442 }
443 
GetCoreFileLocation(const char * suffix)444 std::string CommonArtTestImpl::GetCoreFileLocation(const char* suffix) {
445   CHECK(suffix != nullptr);
446   return GetImageDirectory() + "/boot." + suffix;
447 }
448 
CreateClassPath(const std::vector<std::unique_ptr<const DexFile>> & dex_files)449 std::string CommonArtTestImpl::CreateClassPath(
450     const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
451   CHECK(!dex_files.empty());
452   std::string classpath = dex_files[0]->GetLocation();
453   for (size_t i = 1; i < dex_files.size(); i++) {
454     classpath += ":" + dex_files[i]->GetLocation();
455   }
456   return classpath;
457 }
458 
CreateClassPathWithChecksums(const std::vector<std::unique_ptr<const DexFile>> & dex_files)459 std::string CommonArtTestImpl::CreateClassPathWithChecksums(
460     const std::vector<std::unique_ptr<const DexFile>>& dex_files) {
461   CHECK(!dex_files.empty());
462   uint32_t checksum = DexFileLoader::GetMultiDexChecksum(dex_files);
463   return dex_files[0]->GetLocation() + "*" + std::to_string(checksum);
464 }
465 
ForkAndExec(const std::vector<std::string> & argv,const PostForkFn & post_fork,const OutputHandlerFn & handler)466 CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
467     const std::vector<std::string>& argv,
468     const PostForkFn& post_fork,
469     const OutputHandlerFn& handler) {
470   ForkAndExecResult result;
471   result.status_code = 0;
472   result.stage = ForkAndExecResult::kLink;
473 
474   std::vector<const char*> c_args;
475   c_args.reserve(argv.size() + 1);
476   for (const std::string& str : argv) {
477     c_args.push_back(str.c_str());
478   }
479   c_args.push_back(nullptr);
480 
481   android::base::unique_fd link[2];
482   {
483     int link_fd[2];
484 
485     if (pipe(link_fd) == -1) {
486       return result;
487     }
488     link[0].reset(link_fd[0]);
489     link[1].reset(link_fd[1]);
490   }
491 
492   result.stage = ForkAndExecResult::kFork;
493 
494   pid_t pid = fork();
495   if (pid == -1) {
496     return result;
497   }
498 
499   // Special return code for failures between fork and exec. Pick something that
500   // the command is unlikely to use.
501   constexpr int kPostForkFailure = 134;
502 
503   if (pid == 0) {
504     if (!post_fork()) {
505       LOG(ERROR) << "Failed post-fork function";
506       exit(kPostForkFailure);
507       UNREACHABLE();
508     }
509 
510     // Redirect stdout and stderr.
511     dup2(link[1].get(), STDOUT_FILENO);
512     dup2(link[1].get(), STDERR_FILENO);
513 
514     link[0].reset();
515     link[1].reset();
516 
517     execv(c_args[0], const_cast<char* const*>(c_args.data()));
518     PLOG(ERROR) << "Failed to execv " << c_args[0];
519     exit(kPostForkFailure);
520     UNREACHABLE();
521   }
522 
523   result.stage = ForkAndExecResult::kWaitpid;
524   link[1].reset();
525 
526   char buffer[128] = { 0 };
527   ssize_t bytes_read = 0;
528   while (TEMP_FAILURE_RETRY(bytes_read = read(link[0].get(), buffer, 128)) > 0) {
529     handler(buffer, bytes_read);
530   }
531   handler(buffer, 0u);  // End with a virtual write of zero length to simplify clients.
532 
533   link[0].reset();
534 
535   if (waitpid(pid, &result.status_code, 0) == -1) {
536     return result;
537   }
538 
539   result.stage = ForkAndExecResult::kFinished;
540 
541   if (WIFEXITED(result.status_code) && WEXITSTATUS(result.status_code) == kPostForkFailure) {
542     LOG(WARNING) << "ForkAndExec likely failed between fork and exec";
543   }
544 
545   return result;
546 }
547 
ForkAndExec(const std::vector<std::string> & argv,const PostForkFn & post_fork,std::string * output)548 CommonArtTestImpl::ForkAndExecResult CommonArtTestImpl::ForkAndExec(
549     const std::vector<std::string>& argv, const PostForkFn& post_fork, std::string* output) {
550   auto string_collect_fn = [output](char* buf, size_t len) {
551     *output += std::string(buf, len);
552   };
553   return ForkAndExec(argv, post_fork, string_collect_fn);
554 }
555 
GetPidByName(const std::string & process_name)556 std::vector<pid_t> GetPidByName(const std::string& process_name) {
557   std::vector<pid_t> results;
558   for (pid_t pid : android::base::AllPids{}) {
559     std::string cmdline;
560     if (!android::base::ReadFileToString(StringPrintf("/proc/%d/cmdline", pid), &cmdline)) {
561       continue;
562     }
563     // Take the first argument.
564     size_t pos = cmdline.find('\0');
565     if (pos != std::string::npos) {
566       cmdline.resize(pos);
567     }
568     if (cmdline == process_name) {
569       results.push_back(pid);
570     }
571   }
572   return results;
573 }
574 
575 }  // namespace art
576