File: dump_process.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (262 lines) | stat: -rw-r--r-- 8,462 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <limits>
#include <string>
#include <vector>

#include "base/containers/span.h"
#include "base/debug/proc_maps_linux.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"

namespace {

using base::debug::MappedMemoryRegion;
constexpr size_t kPageSize = 1 << 12;

// See https://www.kernel.org/doc/Documentation/vm/pagemap.txt.
struct PageMapEntry {
  uint64_t pfn_or_swap : 55;
  uint64_t soft_dirty : 1;
  uint64_t exclusively_mapped : 1;
  uint64_t unused : 4;
  uint64_t file_mapped_or_shared_anon : 1;
  uint64_t swapped : 1;
  uint64_t present : 1;
};
static_assert(sizeof(PageMapEntry) == sizeof(uint64_t), "Wrong bitfield size");

// Calls ptrace() on a process, and detaches in the destructor.
class ScopedPtracer {
 public:
  ScopedPtracer(pid_t pid) : pid_(pid), is_attached_(false) {
    // ptrace() delivers a SIGSTOP signal to one thread in the target process,
    // unless it is already stopped. Since we want to stop the whole process,
    // kill() it first.
    if (kill(pid, SIGSTOP)) {
      PLOG(ERROR) << "Cannot stop the process group of " << pid;
      return;
    }

    if (ptrace(PTRACE_ATTACH, pid, nullptr, nullptr)) {
      PLOG(ERROR) << "Unable to attach to " << pid;
      return;
    }
    // ptrace(PTRACE_ATTACH) sends a SISTOP signal to the process, need to wait
    // for it.
    int status;
    pid_t ret = HANDLE_EINTR(waitpid(pid, &status, 0));
    if (ret != pid) {
      PLOG(ERROR) << "Waiting for the process failed";
      return;
    }
    if (!WIFSTOPPED(status)) {
      LOG(ERROR) << "The process is not stopped";
      ptrace(PTRACE_DETACH, pid, 0, 0);
      return;
    }
    is_attached_ = true;
  }

  ~ScopedPtracer() {
    if (!is_attached_)
      return;
    if (ptrace(PTRACE_DETACH, pid_, 0, 0)) {
      PLOG(ERROR) << "Cannot detach from " << pid_;
    }
    pid_t process_group_id = getpgid(pid_);
    if (killpg(process_group_id, SIGCONT)) {
      PLOG(ERROR) << "Cannot resume the process " << pid_;
      return;
    }
  }

  bool IsAttached() const { return is_attached_; }

 private:
  pid_t pid_;
  bool is_attached_;
};

bool ParseProcMaps(pid_t pid, std::vector<MappedMemoryRegion>* regions) {
  std::string path = base::StringPrintf("/proc/%d/maps", pid);
  std::string proc_maps;
  bool ok = base::ReadFileToString(base::FilePath(path), &proc_maps);
  if (!ok) {
    LOG(ERROR) << "Cannot read " << path;
    return false;
  }
  ok = base::debug::ParseProcMaps(proc_maps, regions);
  if (!ok) {
    LOG(ERROR) << "Cannot parse " << path;
    return false;
  }
  return true;
}

// Keep anonynmous rw-p regions.
bool ShouldDump(const MappedMemoryRegion& region) {
  const auto rw_p = MappedMemoryRegion::READ | MappedMemoryRegion::WRITE |
                    MappedMemoryRegion::PRIVATE;
  if (region.permissions != rw_p)
    return false;
  if (base::StartsWith(region.path, "/", base::CompareCase::SENSITIVE) ||
      base::StartsWith(region.path, "[stack]", base::CompareCase::SENSITIVE)) {
    return false;
  }
  return true;
}

base::File OpenProcPidFile(const char* filename, pid_t pid) {
  std::string path = base::StringPrintf("/proc/%d/%s", pid, filename);
  auto file = base::File(base::FilePath(path),
                         base::File::FLAG_OPEN | base::File::FLAG_READ);
  if (!file.IsValid()) {
    PLOG(ERROR) << "Cannot open " << path;
  }
  return file;
}

bool DumpRegion(const MappedMemoryRegion& region,
                pid_t pid,
                base::File* proc_mem,
                base::File* proc_pagemap) {
  size_t size_in_pages = (region.end - region.start) / kPageSize;
  std::string output_path = base::StringPrintf("%d-%" PRIuS "-%" PRIuS ".dump",
                                               pid, region.start, region.end);
  base::File output_file(base::FilePath(output_path),
                         base::File::FLAG_WRITE | base::File::FLAG_CREATE);
  if (!output_file.IsValid()) {
    PLOG(ERROR) << "Cannot open " << output_path;
    return false;
  }
  std::string metadata_path = output_path + std::string(".metadata");
  base::File metadata_file(base::FilePath(metadata_path),
                           base::File::FLAG_WRITE | base::File::FLAG_CREATE);
  if (!metadata_file.IsValid()) {
    PLOG(ERROR) << "Cannot open " << metadata_path;
    return false;
  }

  // Dump metadata.
  // Important: Metadata must be dumped before the data, as reading from
  // /proc/pid/mem will move the data back from swap, so dumping metadata
  // later would not show anything in swap.
  // This also means that dumping the same process twice will result in
  // inaccurate metadata.
  for (size_t i = 0; i < size_in_pages; ++i) {
    // See https://www.kernel.org/doc/Documentation/vm/pagemap.txt
    // 64 bits per page.
    int64_t pagemap_offset =
        ((region.start / kPageSize) + i) * sizeof(PageMapEntry);
    PageMapEntry entry;
    proc_pagemap->Seek(base::File::FROM_BEGIN, pagemap_offset);
    int size_read = proc_pagemap->ReadAtCurrentPos(
        reinterpret_cast<char*>(&entry), sizeof(PageMapEntry));
    if (size_read != sizeof(PageMapEntry)) {
      PLOG(ERROR) << "Cannot read from /proc/pid/pagemap at offset "
                  << pagemap_offset;
      return false;
    }
    std::string metadata = base::StringPrintf(
        "%c%c\n", entry.present ? '1' : '0', entry.swapped ? '1' : '0');
    metadata_file.WriteAtCurrentPos(base::as_byte_span(metadata));
  }

  // Writing data page by page to avoid allocating too much memory.
  std::vector<char> buffer(kPageSize);
  for (size_t i = 0; i < size_in_pages; ++i) {
    uint64_t address = region.start + i * kPageSize;
    // Works because the upper half of the address space is reserved for the
    // kernel on at least ARM64 and x86_64 bit architectures.
    CHECK(address <= std::numeric_limits<int64_t>::max());
    proc_mem->Seek(base::File::FROM_BEGIN, static_cast<int64_t>(address));
    int size_read = proc_mem->ReadAtCurrentPos(&buffer[0], kPageSize);
    if (size_read != kPageSize) {
      PLOG(ERROR) << "Cannot read from /proc/pid/mem at offset " << address;
      return false;
    }

    int64_t output_offset = i * kPageSize;
    int size_written = output_file.Write(output_offset, &buffer[0], kPageSize);
    if (size_written != kPageSize) {
      PLOG(ERROR) << "Cannot write to output file";
      return false;
    }
  }

  return true;
}

// Dumps the content of all the anonymous rw-p mappings in a given process to
// disk.
bool DumpMappings(pid_t pid) {
  LOG(INFO) << "Attaching to " << pid;
  // ptrace() is not required to read the process's memory, but the permissions
  // to attach to the target process is.
  // Attach anyway to make it clearer when this fails.
  ScopedPtracer tracer(pid);
  if (!tracer.IsAttached())
    return false;

  LOG(INFO) << "Reading /proc/pid/maps";
  std::vector<base::debug::MappedMemoryRegion> regions;
  bool ok = ParseProcMaps(pid, &regions);
  if (!ok)
    return false;

  base::File proc_mem = OpenProcPidFile("mem", pid);
  if (!proc_mem.IsValid())
    return false;
  base::File proc_pagemap = OpenProcPidFile("pagemap", pid);
  if (!proc_pagemap.IsValid())
    return false;

  for (const auto& region : regions) {
    if (!ShouldDump(region))
      continue;
    std::string message =
        base::StringPrintf("%" PRIuS "-%" PRIuS " (size %" PRIuS ")",
                           region.start, region.end, region.end - region.start);
    LOG(INFO) << "Dumping " << message;
    ok = DumpRegion(region, pid, &proc_mem, &proc_pagemap);
    if (!ok) {
      LOG(WARNING) << "Failed to dump region";
    }
  }
  return true;
}

}  // namespace

int main(int argc, char** argv) {
  CHECK(sysconf(_SC_PAGESIZE) == kPageSize);

  if (argc != 2) {
    LOG(ERROR) << "Usage: " << argv[0] << " <pid>";
    return 1;
  }
  pid_t pid;
  bool ok = base::StringToInt(argv[1], &pid);
  if (!ok) {
    LOG(ERROR) << "Cannot parse PID";
    return 1;
  }

  ok = DumpMappings(pid);
  return ok ? 0 : 1;
}