-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathmem.cpp
More file actions
514 lines (434 loc) Β· 14.3 KB
/
mem.cpp
File metadata and controls
514 lines (434 loc) Β· 14.3 KB
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
#include <algorithm>
#include <cerrno>
#include <cstring>
#include <fstream>
#include <ios>
#include <memory>
#include <sys/uio.h>
#include <syscall.h>
#include <system_error>
#include <unistd.h>
#include <utility>
#include "corefile.h"
#include "logging.h"
#include "mem.h"
namespace pystack {
using elf_unique_ptr = std::unique_ptr<Elf, std::function<void(Elf*)>>;
static ssize_t
_process_vm_readv(
pid_t pid,
const struct iovec* lvec,
unsigned long liovcnt,
const struct iovec* rvec,
unsigned long riovcnt,
unsigned long flags)
{
return syscall(SYS_process_vm_readv, pid, lvec, liovcnt, rvec, riovcnt, flags);
}
static const std::string PERM_MESSAGE = "Operation not permitted";
static const size_t CACHE_CAPACITY = 5e+7; // 50MB
VirtualMap::VirtualMap(
uintptr_t start,
uintptr_t end,
unsigned long filesize,
std::string flags,
unsigned long offset,
std::string device,
unsigned long inode,
std::string pathname)
: d_start(start)
, d_end(end)
, d_filesize(filesize)
, d_flags(std::move(flags))
, d_offset(offset)
, d_device(std::move(device))
, d_inode(inode)
, d_path(std::move(pathname))
{
}
bool
VirtualMap::containsAddr(remote_addr_t addr) const
{
return d_start <= addr && addr < d_end;
}
uintptr_t
VirtualMap::Start() const
{
return d_start;
}
uintptr_t
VirtualMap::End() const
{
return d_end;
}
unsigned long
VirtualMap::FileSize() const
{
return d_filesize;
}
const std::string&
VirtualMap::Flags() const
{
return d_flags;
}
unsigned long
VirtualMap::Offset() const
{
return d_offset;
}
const std::string&
VirtualMap::Device() const
{
return d_device;
}
unsigned long
VirtualMap::Inode() const
{
return d_inode;
}
const std::string&
VirtualMap::Path() const
{
return d_path;
}
size_t
VirtualMap::Size() const
{
return d_end - d_start;
}
LRUCache::LRUCache(size_t capacity)
: d_cache_capacity(capacity)
, d_size(0){};
void
LRUCache::put(uintptr_t key, std::vector<char>&& value)
{
size_t value_size = value.size();
if (!can_fit(value_size)) {
return;
}
auto it = d_cache.find(key);
if (it != d_cache.end()) {
d_cache_list.erase(it->second.it);
d_cache.erase(it);
}
while (d_size + value_size > d_cache_capacity) {
d_cache.erase(d_cache_list.back().key);
d_size -= d_cache_list.back().size;
d_cache_list.pop_back();
}
d_cache_list.push_front(LRUCache::ListNode{key, value_size});
d_cache[key] = LRUCache::CacheValue{std::move(value), d_cache_list.begin()};
d_size += value_size;
}
const std::vector<char>&
LRUCache::get(uintptr_t key)
{
auto it = d_cache.find(key);
if (it == d_cache.end()) {
throw std::range_error("There is no such key in the cache");
} else {
auto node_it = it->second.it;
d_cache_list.splice(d_cache_list.begin(), d_cache_list, node_it);
return it->second.data;
}
}
bool
LRUCache::exists(uintptr_t key)
{
return (d_cache.find(key) != d_cache.end());
}
bool
LRUCache::can_fit(size_t size)
{
return d_cache_capacity >= size;
}
ProcessMemoryManager::ProcessMemoryManager(pid_t pid, const std::vector<VirtualMap>& vmaps)
: d_pid(pid)
, d_vmaps(vmaps)
, d_lru_cache(CACHE_CAPACITY)
{
}
ProcessMemoryManager::ProcessMemoryManager(pid_t pid)
: d_pid(pid)
, d_lru_cache(CACHE_CAPACITY)
{
}
ssize_t
ProcessMemoryManager::readChunk(remote_addr_t addr, size_t len, char* dst) const
{
if (d_memfile || getenv("_PYSTACK_NO_PROCESS_VM_READV") != nullptr) {
return readChunkThroughMemFile(addr, len, dst);
} else {
return readChunkDirect(addr, len, dst);
}
}
ssize_t
ProcessMemoryManager::readChunkDirect(remote_addr_t addr, size_t len, char* dst) const
{
struct iovec local[1];
struct iovec remote[1];
ssize_t result = 0;
ssize_t read = 0;
do {
local[0].iov_base = dst + result;
local[0].iov_len = len - result;
remote[0].iov_base = reinterpret_cast<uint8_t*>(addr) + result;
remote[0].iov_len = len - result;
read = _process_vm_readv(d_pid, local, 1, remote, 1, 0);
if (read < 0) {
if (errno == EFAULT) {
throw InvalidRemoteAddress();
} else if (errno == EPERM) {
throw std::runtime_error(PERM_MESSAGE);
} else if (errno == ENOSYS) {
LOG(DEBUG) << "process_vm_readv not compiled in kernel, falling back to /proc/PID/mem";
return readChunkThroughMemFile(addr, len, dst);
}
throw std::system_error(errno, std::generic_category());
}
result += read;
} while ((size_t)read != local[0].iov_len);
return result;
}
ssize_t
ProcessMemoryManager::readChunkThroughMemFile(remote_addr_t addr, size_t len, char* dst) const
{
if (!d_memfile) {
std::string filepath = "/proc/" + std::to_string(d_pid) + "/mem";
d_memfile = file_unique_ptr(fopen(filepath.c_str(), "r"), fclose);
if (!d_memfile) {
if (errno == EPERM || errno == EACCES) {
LOG(ERROR) << "Permission denied opening file " << filepath;
throw std::runtime_error(PERM_MESSAGE);
}
LOG(ERROR) << "Failed to open file " << filepath << ": " << std::strerror(errno);
throw std::runtime_error("Failed to open " + filepath);
}
}
fseeko(d_memfile.get(), addr, SEEK_SET);
if (static_cast<off_t>(addr) != ftello(d_memfile.get())
|| len != fread(dst, 1, len, d_memfile.get()))
{
throw InvalidRemoteAddress();
}
return static_cast<ssize_t>(len);
}
ssize_t
ProcessMemoryManager::copyMemoryFromProcess(remote_addr_t addr, size_t len, void* dst) const
{
auto vmap = std::find_if(d_vmaps.begin(), d_vmaps.end(), [&](const auto& vmap) {
return vmap.containsAddr(addr) && vmap.containsAddr(addr + len - 1);
});
if (vmap == d_vmaps.end() || !d_lru_cache.can_fit(vmap->Size())) {
return readChunk(addr, len, reinterpret_cast<char*>(dst));
}
uintptr_t key = vmap->Start();
size_t chunk_size = vmap->Size();
remote_addr_t vmap_start_addr = vmap->Start();
size_t offset_addr = addr - vmap_start_addr;
if (!d_lru_cache.exists(key)) {
std::vector<char> buf(chunk_size);
try {
readChunk(vmap_start_addr, chunk_size, buf.data());
d_lru_cache.put(key, std::move(buf));
} catch (const InvalidRemoteAddress&) {
// The full vmap read failed (e.g. guard pages in JIT mappings).
// Fall back to reading just the requested bytes directly.
return readChunk(addr, len, reinterpret_cast<char*>(dst));
}
}
std::memcpy(dst, d_lru_cache.get(key).data() + offset_addr, len);
return len;
}
bool
ProcessMemoryManager::isAddressValid(remote_addr_t addr, const VirtualMap& map) const
{
if (addr == (uintptr_t) nullptr) {
return false;
}
return map.Start() <= addr && addr < map.End();
}
CorefileRemoteMemoryManager::CorefileRemoteMemoryManager(
std::shared_ptr<CoreFileAnalyzer> analyzer,
std::vector<VirtualMap>& vmaps)
: d_analyzer(std::move(analyzer))
, d_vmaps(vmaps)
{
CoreFileExtractor extractor{d_analyzer};
d_shared_libs = extractor.ModuleInformation();
const char* filename = d_analyzer->d_filename.c_str();
int fd = open(filename, O_RDONLY);
if (fd == -1) {
LOG(ERROR) << "Failed to open a file " << filename;
throw RemoteMemCopyError();
}
StatusCode ret = readCorefile(fd, filename);
int close_ret = close(fd);
if (close_ret == -1) {
LOG(ERROR) << "Failed to close a file " << filename;
throw RemoteMemCopyError();
}
if (ret == StatusCode::ERROR) {
throw RemoteMemCopyError();
}
}
CorefileRemoteMemoryManager::StatusCode
CorefileRemoteMemoryManager::readCorefile(int fd, const char* filename) noexcept
{
struct stat fileInfo = {0};
if (fstat(fd, &fileInfo) == -1) {
LOG(ERROR) << "Failed to get a file size for a file " << filename;
return StatusCode::ERROR;
}
if (fileInfo.st_size == 0) {
LOG(ERROR) << "File " << filename << " is empty";
return StatusCode::ERROR;
}
d_corefile_size = fileInfo.st_size;
void* map = mmap(0, d_corefile_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (map == MAP_FAILED) {
LOG(ERROR) << "Failed to mmap a file " << filename;
return StatusCode::ERROR;
}
d_corefile_data = std::unique_ptr<char, std::function<void(char*)>>(
reinterpret_cast<char*>(map),
[this](auto addr) {
if (munmap(addr, d_corefile_size) == -1) {
LOG(ERROR) << "Failed to un-mmap a file " << d_analyzer->d_filename.c_str();
}
});
int madvise_result = madvise(d_corefile_data.get(), d_corefile_size, MADV_RANDOM);
if (madvise_result == -1) {
LOG(WARNING) << "Madvise for a file " << filename << " failed";
}
return StatusCode::SUCCESS;
}
ssize_t
CorefileRemoteMemoryManager::copyMemoryFromProcess(remote_addr_t addr, size_t size, void* destination)
const
{
off_t offset_in_file = 0;
StatusCode ret = getMemoryLocationFromCore(addr, &offset_in_file);
if (ret == StatusCode::SUCCESS) {
if (size > d_corefile_size || static_cast<size_t>(offset_in_file) > d_corefile_size - size) {
throw InvalidRemoteAddress();
}
memcpy(destination, d_corefile_data.get() + offset_in_file, size);
return size;
}
// The memory may be in the data segment of some shared library
const std::string* filename = nullptr;
ret = getMemoryLocationFromElf(addr, &filename, &offset_in_file);
if (ret == StatusCode::ERROR) {
throw InvalidRemoteAddress();
}
std::ifstream is(*filename, std::ifstream::binary);
if (is) {
is.seekg(offset_in_file);
is.read((char*)destination, size);
} else {
LOG(ERROR) << "Failed to read memory from file " << *filename;
throw InvalidRemoteAddress();
}
return size;
}
CorefileRemoteMemoryManager::StatusCode
CorefileRemoteMemoryManager::getMemoryLocationFromCore(remote_addr_t addr, off_t* offset_in_file) const
{
auto corefile_it = std::find_if(d_vmaps.cbegin(), d_vmaps.cend(), [&](auto& map) {
// When considering if the data is in the core file, we need to check if the address is
// within the chunk of the segment in the core file. map.End() corresponds
// to the end of the segment in memory when the process was alive but when the core was
// created not all that data will be in the core, so we need to use map.FileSize()
// to get the end of the segment in the core file.
uintptr_t fileEnd = map.Start() + map.FileSize();
return (map.Start() <= addr && addr < fileEnd) && (map.FileSize() != 0 && map.Offset() != 0);
});
if (corefile_it == d_vmaps.cend()) {
return StatusCode::ERROR;
}
off_t base = corefile_it->Offset() - corefile_it->Start();
*offset_in_file = base + addr;
return StatusCode::SUCCESS;
}
CorefileRemoteMemoryManager::StatusCode
CorefileRemoteMemoryManager::initLoadSegments(const std::string& filename) const
{
file_unique_ptr file(fopen(filename.c_str(), "r"), fclose);
if (!file || fileno(file.get()) == -1) {
return StatusCode::ERROR;
}
auto elf = elf_unique_ptr(elf_begin(fileno(file.get()), ELF_C_READ_MMAP, nullptr), elf_end);
if (!elf) {
return StatusCode::ERROR;
}
std::vector<ElfLoadSegment> segments;
size_t phnum;
if (elf_getphdrnum(elf.get(), &phnum) == 0) {
for (size_t i = 0; i < phnum; i++) {
GElf_Phdr phdr_mem;
GElf_Phdr* phdr = gelf_getphdr(elf.get(), i, &phdr_mem);
if (phdr == nullptr) {
LOG(WARNING) << "Failed to read program header " << i << " from " << filename.c_str()
<< " (" << elf_errmsg(elf_errno()) << ")";
continue;
}
if (phdr->p_type == PT_LOAD) {
segments.push_back(
{.vaddr = phdr->p_vaddr, .offset = phdr->p_offset, .size = phdr->p_filesz});
}
}
}
if (!segments.empty()) {
d_elf_load_segments_cache[filename] = std::move(segments);
return StatusCode::SUCCESS;
}
return StatusCode::ERROR;
}
CorefileRemoteMemoryManager::StatusCode
CorefileRemoteMemoryManager::getMemoryLocationFromElf(
remote_addr_t addr,
const std::string** filename,
off_t* offset_in_file) const
{
auto shared_libs_it = std::find_if(d_shared_libs.cbegin(), d_shared_libs.cend(), [&](auto& map) {
return map.start <= addr && addr < map.end;
});
if (shared_libs_it == d_shared_libs.cend()) {
return StatusCode::ERROR;
}
*filename = &shared_libs_it->filename;
// Check if we have cached segments for this file
auto cache_it = d_elf_load_segments_cache.find(**filename);
if (cache_it == d_elf_load_segments_cache.end()) {
// Initialize segments if not in cache
if (initLoadSegments(**filename) != StatusCode::SUCCESS) {
return StatusCode::ERROR;
}
cache_it = d_elf_load_segments_cache.find(**filename);
}
// Get the load address of the elf file from its first segment
remote_addr_t elf_load_addr = cache_it->second[0].vaddr;
// Now relocate the address to the elf file
remote_addr_t symbol_vaddr = addr - shared_libs_it->start + elf_load_addr;
// Find the segment containing this address
for (const auto& segment : cache_it->second) {
if (symbol_vaddr >= segment.vaddr && symbol_vaddr < segment.vaddr + segment.size) {
*offset_in_file = (symbol_vaddr - segment.vaddr) + segment.offset;
return StatusCode::SUCCESS;
}
}
LOG(ERROR) << "Failed to find the correct segment for address " << std::hex << std::showbase << addr
<< " (with vaddr offset " << symbol_vaddr << ")"
<< " in file " << **filename;
return StatusCode::ERROR;
}
bool
CorefileRemoteMemoryManager::isAddressValid(remote_addr_t addr, const VirtualMap& map) const
{
if (addr == (uintptr_t) nullptr) {
return false;
}
return map.Start() <= addr && addr < map.Start() + map.Size();
}
} // namespace pystack