blob: af843dc241db44fbdf71e52c631fdaf8eb8a9b10 [file] [log] [blame]
Gediminas Ramanauskas2f0b8852013-03-14 13:52:32 -07001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Douglas Anderson4719ee72020-09-18 10:55:49 -07005#include <base/files/file_path.h>
6#include <base/files/file_util.h>
7
Alex Vakulenko262be3f2014-07-30 15:25:50 -07008#include "debugd/src/memory_tool.h"
Gediminas Ramanauskas2f0b8852013-03-14 13:52:32 -07009
Alex Vakulenko262be3f2014-07-30 15:25:50 -070010#include "debugd/src/process_with_id.h"
Gediminas Ramanauskas2f0b8852013-03-14 13:52:32 -070011
Gediminas Ramanauskas2f0b8852013-03-14 13:52:32 -070012namespace debugd {
13
Ben Chana0011d82014-05-13 00:19:29 -070014namespace {
15
16const char kMemtesterpath[] = "/usr/sbin/memtester";
Douglas Anderson4719ee72020-09-18 10:55:49 -070017constexpr char kOomScoreAdjFileFormat[] = "/proc/%d/oom_score_adj";
18constexpr char kOomScoreKillable[] = "1000";
Ben Chana0011d82014-05-13 00:19:29 -070019
20} // namespace
Gediminas Ramanauskas2f0b8852013-03-14 13:52:32 -070021
Eric Caruso0b241882018-04-04 13:43:46 -070022std::string MemtesterTool::Start(const base::ScopedFD& outfd,
Eric Carusoc93a15c2017-04-24 16:15:12 -070023 const uint32_t& memory) {
Ben Chan0d840a72018-09-27 00:24:48 -070024 ProcessWithId* p =
25 CreateProcess(false /* sandboxed */, false /* access_root_mount_ns */);
Gediminas Ramanauskas2f0b8852013-03-14 13:52:32 -070026 if (!p)
27 return "";
28
29 p->AddArg(kMemtesterpath);
Eric Caruso96d03d32017-04-25 18:01:17 -070030 p->AddArg(base::StringPrintf("%u", memory));
Gediminas Ramanauskas2f0b8852013-03-14 13:52:32 -070031 p->AddArg("1");
Eric Caruso0b241882018-04-04 13:43:46 -070032 p->BindFd(outfd.get(), STDOUT_FILENO);
33 p->BindFd(outfd.get(), STDERR_FILENO);
Gediminas Ramanauskas2f0b8852013-03-14 13:52:32 -070034 LOG(INFO) << "memtester: running process id: " << p->id();
35 p->Start();
Douglas Anderson4719ee72020-09-18 10:55:49 -070036
37 // Make it the most killable possible instead of the default (unkillable).
38 base::FilePath oom_file(base::StringPrintf(kOomScoreAdjFileFormat, p->pid()));
39 ssize_t bytes_written =
40 base::WriteFile(oom_file, kOomScoreKillable, strlen(kOomScoreKillable));
41 if (bytes_written < 0 ||
42 static_cast<size_t>(bytes_written) < strlen(kOomScoreKillable))
43 PLOG(WARNING) << "memtester: can't write OOM score, got: " << bytes_written;
44
Gediminas Ramanauskas2f0b8852013-03-14 13:52:32 -070045 return p->id();
46}
47
Ben Chana0011d82014-05-13 00:19:29 -070048} // namespace debugd