blob: a30d65ef0a90d667541e9a16cad52a0efebc75f9 [file] [log] [blame]
Christopher Ferris723cf9b2017-01-19 20:08:48 -08001/*
2 * Copyright (C) 2016 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 <errno.h>
18#include <fcntl.h>
19#include <sys/mman.h>
20#include <sys/ptrace.h>
21#include <sys/stat.h>
22#include <sys/types.h>
23#include <sys/uio.h>
24#include <unistd.h>
25
26#include <algorithm>
27#include <memory>
28
29#include <android-base/unique_fd.h>
30
Christopher Ferrisd226a512017-07-14 10:37:19 -070031#include <unwindstack/Memory.h>
32
33#include "Check.h"
34
Christopher Ferrise3286732017-12-07 17:41:18 -080035namespace unwindstack {
36
37static size_t ProcessVmRead(pid_t pid, uint64_t remote_src, void* dst, size_t len) {
Josh Gao29c53782017-09-26 14:11:37 -070038
39 // Split up the remote read across page boundaries.
40 // From the manpage:
41 // A partial read/write may result if one of the remote_iov elements points to an invalid
42 // memory region in the remote process.
43 //
44 // Partial transfers apply at the granularity of iovec elements. These system calls won't
45 // perform a partial transfer that splits a single iovec element.
46 constexpr size_t kMaxIovecs = 64;
47 struct iovec src_iovs[kMaxIovecs];
Josh Gao29c53782017-09-26 14:11:37 -070048
49 uint64_t cur = remote_src;
Christopher Ferris3dfd2ae2017-12-15 20:00:59 -080050 size_t total_read = 0;
Josh Gao29c53782017-09-26 14:11:37 -070051 while (len > 0) {
Christopher Ferris3dfd2ae2017-12-15 20:00:59 -080052 struct iovec dst_iov = {
53 .iov_base = &reinterpret_cast<uint8_t*>(dst)[total_read], .iov_len = len,
54 };
55
56 size_t iovecs_used = 0;
57 while (len > 0) {
58 if (iovecs_used == kMaxIovecs) {
59 break;
60 }
61
62 // struct iovec uses void* for iov_base.
63 if (cur >= UINTPTR_MAX) {
64 errno = EFAULT;
65 return total_read;
66 }
67
68 src_iovs[iovecs_used].iov_base = reinterpret_cast<void*>(cur);
69
70 uintptr_t misalignment = cur & (getpagesize() - 1);
71 size_t iov_len = getpagesize() - misalignment;
72 iov_len = std::min(iov_len, len);
73
74 len -= iov_len;
75 if (__builtin_add_overflow(cur, iov_len, &cur)) {
76 errno = EFAULT;
77 return total_read;
78 }
79
80 src_iovs[iovecs_used].iov_len = iov_len;
81 ++iovecs_used;
Josh Gao29c53782017-09-26 14:11:37 -070082 }
83
Christopher Ferris3dfd2ae2017-12-15 20:00:59 -080084 ssize_t rc = process_vm_readv(pid, &dst_iov, 1, src_iovs, iovecs_used, 0);
85 if (rc == -1) {
86 return total_read;
Josh Gao29c53782017-09-26 14:11:37 -070087 }
Christopher Ferris3dfd2ae2017-12-15 20:00:59 -080088 total_read += rc;
Josh Gao29c53782017-09-26 14:11:37 -070089 }
Christopher Ferris3dfd2ae2017-12-15 20:00:59 -080090 return total_read;
Josh Gao29c53782017-09-26 14:11:37 -070091}
92
Christopher Ferrise3286732017-12-07 17:41:18 -080093static bool PtraceReadLong(pid_t pid, uint64_t addr, long* value) {
94 // ptrace() returns -1 and sets errno when the operation fails.
95 // To disambiguate -1 from a valid result, we clear errno beforehand.
96 errno = 0;
97 *value = ptrace(PTRACE_PEEKTEXT, pid, reinterpret_cast<void*>(addr), nullptr);
98 if (*value == -1 && errno) {
99 return false;
100 }
101 return true;
102}
103
104static size_t PtraceRead(pid_t pid, uint64_t addr, void* dst, size_t bytes) {
105 // Make sure that there is no overflow.
106 uint64_t max_size;
107 if (__builtin_add_overflow(addr, bytes, &max_size)) {
108 return 0;
109 }
110
111 size_t bytes_read = 0;
112 long data;
113 size_t align_bytes = addr & (sizeof(long) - 1);
114 if (align_bytes != 0) {
115 if (!PtraceReadLong(pid, addr & ~(sizeof(long) - 1), &data)) {
116 return 0;
117 }
118 size_t copy_bytes = std::min(sizeof(long) - align_bytes, bytes);
119 memcpy(dst, reinterpret_cast<uint8_t*>(&data) + align_bytes, copy_bytes);
120 addr += copy_bytes;
121 dst = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(dst) + copy_bytes);
122 bytes -= copy_bytes;
123 bytes_read += copy_bytes;
124 }
125
126 for (size_t i = 0; i < bytes / sizeof(long); i++) {
127 if (!PtraceReadLong(pid, addr, &data)) {
128 return bytes_read;
129 }
130 memcpy(dst, &data, sizeof(long));
131 dst = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(dst) + sizeof(long));
132 addr += sizeof(long);
133 bytes_read += sizeof(long);
134 }
135
136 size_t left_over = bytes & (sizeof(long) - 1);
137 if (left_over) {
138 if (!PtraceReadLong(pid, addr, &data)) {
139 return bytes_read;
140 }
141 memcpy(dst, &data, left_over);
142 bytes_read += left_over;
143 }
144 return bytes_read;
145}
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800146
Josh Gaoef35aa52017-10-18 11:44:51 -0700147bool Memory::ReadFully(uint64_t addr, void* dst, size_t size) {
Josh Gaob8377632017-10-18 11:52:53 -0700148 size_t rc = Read(addr, dst, size);
Josh Gao29c53782017-09-26 14:11:37 -0700149 return rc == size;
150}
151
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800152bool Memory::ReadString(uint64_t addr, std::string* string, uint64_t max_read) {
153 string->clear();
154 uint64_t bytes_read = 0;
155 while (bytes_read < max_read) {
156 uint8_t value;
Josh Gaoef35aa52017-10-18 11:44:51 -0700157 if (!ReadFully(addr, &value, sizeof(value))) {
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800158 return false;
159 }
160 if (value == '\0') {
161 return true;
162 }
163 string->push_back(value);
164 addr++;
165 bytes_read++;
166 }
167 return false;
168}
169
Christopher Ferris5f118512017-09-01 11:17:16 -0700170std::shared_ptr<Memory> Memory::CreateProcessMemory(pid_t pid) {
171 if (pid == getpid()) {
172 return std::shared_ptr<Memory>(new MemoryLocal());
173 }
174 return std::shared_ptr<Memory>(new MemoryRemote(pid));
175}
176
Christopher Ferrisef640102018-11-14 15:36:45 -0800177std::shared_ptr<Memory> Memory::CreateProcessMemoryCached(pid_t pid) {
178 if (pid == getpid()) {
179 return std::shared_ptr<Memory>(new MemoryCache(new MemoryLocal()));
180 }
181 return std::shared_ptr<Memory>(new MemoryCache(new MemoryRemote(pid)));
182}
183
Josh Gaob8377632017-10-18 11:52:53 -0700184size_t MemoryBuffer::Read(uint64_t addr, void* dst, size_t size) {
Josh Gao29c53782017-09-26 14:11:37 -0700185 if (addr >= raw_.size()) {
186 return 0;
Christopher Ferris3958f802017-02-01 15:44:40 -0800187 }
Josh Gao29c53782017-09-26 14:11:37 -0700188
189 size_t bytes_left = raw_.size() - static_cast<size_t>(addr);
190 const unsigned char* actual_base = static_cast<const unsigned char*>(raw_.data()) + addr;
191 size_t actual_len = std::min(bytes_left, size);
192
193 memcpy(dst, actual_base, actual_len);
194 return actual_len;
Christopher Ferris3958f802017-02-01 15:44:40 -0800195}
196
197uint8_t* MemoryBuffer::GetPtr(size_t offset) {
198 if (offset < raw_.size()) {
199 return &raw_[offset];
200 }
201 return nullptr;
202}
203
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800204MemoryFileAtOffset::~MemoryFileAtOffset() {
Christopher Ferris3958f802017-02-01 15:44:40 -0800205 Clear();
206}
207
208void MemoryFileAtOffset::Clear() {
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800209 if (data_) {
210 munmap(&data_[-offset_], size_ + offset_);
211 data_ = nullptr;
212 }
213}
214
Christopher Ferris3958f802017-02-01 15:44:40 -0800215bool MemoryFileAtOffset::Init(const std::string& file, uint64_t offset, uint64_t size) {
216 // Clear out any previous data if it exists.
217 Clear();
218
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800219 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC)));
220 if (fd == -1) {
221 return false;
222 }
223 struct stat buf;
224 if (fstat(fd, &buf) == -1) {
225 return false;
226 }
227 if (offset >= static_cast<uint64_t>(buf.st_size)) {
228 return false;
229 }
230
231 offset_ = offset & (getpagesize() - 1);
232 uint64_t aligned_offset = offset & ~(getpagesize() - 1);
Christopher Ferrisf447c8e2017-04-03 12:39:47 -0700233 if (aligned_offset > static_cast<uint64_t>(buf.st_size) ||
234 offset > static_cast<uint64_t>(buf.st_size)) {
235 return false;
236 }
237
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800238 size_ = buf.st_size - aligned_offset;
Christopher Ferrisf447c8e2017-04-03 12:39:47 -0700239 uint64_t max_size;
240 if (!__builtin_add_overflow(size, offset_, &max_size) && max_size < size_) {
Christopher Ferris3958f802017-02-01 15:44:40 -0800241 // Truncate the mapped size.
Christopher Ferrisf447c8e2017-04-03 12:39:47 -0700242 size_ = max_size;
Christopher Ferris3958f802017-02-01 15:44:40 -0800243 }
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800244 void* map = mmap(nullptr, size_, PROT_READ, MAP_PRIVATE, fd, aligned_offset);
245 if (map == MAP_FAILED) {
246 return false;
247 }
248
249 data_ = &reinterpret_cast<uint8_t*>(map)[offset_];
250 size_ -= offset_;
251
252 return true;
253}
254
Josh Gaob8377632017-10-18 11:52:53 -0700255size_t MemoryFileAtOffset::Read(uint64_t addr, void* dst, size_t size) {
Josh Gao29c53782017-09-26 14:11:37 -0700256 if (addr >= size_) {
257 return 0;
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800258 }
Josh Gao29c53782017-09-26 14:11:37 -0700259
260 size_t bytes_left = size_ - static_cast<size_t>(addr);
261 const unsigned char* actual_base = static_cast<const unsigned char*>(data_) + addr;
262 size_t actual_len = std::min(bytes_left, size);
263
264 memcpy(dst, actual_base, actual_len);
265 return actual_len;
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800266}
267
Josh Gaob8377632017-10-18 11:52:53 -0700268size_t MemoryRemote::Read(uint64_t addr, void* dst, size_t size) {
Christopher Ferrise714ed22017-12-04 14:23:58 -0800269#if !defined(__LP64__)
Christopher Ferrise3286732017-12-07 17:41:18 -0800270 // Cannot read an address greater than 32 bits in a 32 bit context.
Christopher Ferrise714ed22017-12-04 14:23:58 -0800271 if (addr > UINT32_MAX) {
272 return 0;
273 }
274#endif
Christopher Ferrise3286732017-12-07 17:41:18 -0800275
276 size_t (*read_func)(pid_t, uint64_t, void*, size_t) =
277 reinterpret_cast<size_t (*)(pid_t, uint64_t, void*, size_t)>(read_redirect_func_.load());
278 if (read_func != nullptr) {
279 return read_func(pid_, addr, dst, size);
280 } else {
281 // Prefer process_vm_read, try it first. If it doesn't work, use the
282 // ptrace function. If at least one of them returns at least some data,
283 // set that as the permanent function to use.
284 // This assumes that if process_vm_read works once, it will continue
285 // to work.
286 size_t bytes = ProcessVmRead(pid_, addr, dst, size);
287 if (bytes > 0) {
288 read_redirect_func_ = reinterpret_cast<uintptr_t>(ProcessVmRead);
289 return bytes;
290 }
291 bytes = PtraceRead(pid_, addr, dst, size);
292 if (bytes > 0) {
293 read_redirect_func_ = reinterpret_cast<uintptr_t>(PtraceRead);
294 }
295 return bytes;
296 }
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800297}
298
Josh Gaob8377632017-10-18 11:52:53 -0700299size_t MemoryLocal::Read(uint64_t addr, void* dst, size_t size) {
Christopher Ferrise3286732017-12-07 17:41:18 -0800300 return ProcessVmRead(getpid(), addr, dst, size);
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800301}
302
Josh Gao29c53782017-09-26 14:11:37 -0700303MemoryRange::MemoryRange(const std::shared_ptr<Memory>& memory, uint64_t begin, uint64_t length,
304 uint64_t offset)
305 : memory_(memory), begin_(begin), length_(length), offset_(offset) {}
306
Josh Gaob8377632017-10-18 11:52:53 -0700307size_t MemoryRange::Read(uint64_t addr, void* dst, size_t size) {
Josh Gao29c53782017-09-26 14:11:37 -0700308 if (addr < offset_) {
309 return 0;
Christopher Ferrisf447c8e2017-04-03 12:39:47 -0700310 }
311
Josh Gao29c53782017-09-26 14:11:37 -0700312 uint64_t read_offset = addr - offset_;
313 if (read_offset >= length_) {
314 return 0;
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800315 }
Josh Gao29c53782017-09-26 14:11:37 -0700316
317 uint64_t read_length = std::min(static_cast<uint64_t>(size), length_ - read_offset);
318 uint64_t read_addr;
319 if (__builtin_add_overflow(read_offset, begin_, &read_addr)) {
320 return 0;
321 }
322
Josh Gaob8377632017-10-18 11:52:53 -0700323 return memory_->Read(read_addr, dst, read_length);
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800324}
325
Christopher Ferris9d5712c2018-10-01 21:01:09 -0700326void MemoryRanges::Insert(MemoryRange* memory) {
327 maps_.emplace(memory->offset() + memory->length(), memory);
328}
329
330size_t MemoryRanges::Read(uint64_t addr, void* dst, size_t size) {
331 auto entry = maps_.upper_bound(addr);
332 if (entry != maps_.end()) {
333 return entry->second->Read(addr, dst, size);
334 }
335 return 0;
336}
337
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800338bool MemoryOffline::Init(const std::string& file, uint64_t offset) {
Josh Gao29c53782017-09-26 14:11:37 -0700339 auto memory_file = std::make_shared<MemoryFileAtOffset>();
340 if (!memory_file->Init(file, offset)) {
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800341 return false;
342 }
Josh Gao29c53782017-09-26 14:11:37 -0700343
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800344 // The first uint64_t value is the start of memory.
Josh Gao29c53782017-09-26 14:11:37 -0700345 uint64_t start;
Josh Gaoef35aa52017-10-18 11:44:51 -0700346 if (!memory_file->ReadFully(0, &start, sizeof(start))) {
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800347 return false;
348 }
Josh Gao29c53782017-09-26 14:11:37 -0700349
350 uint64_t size = memory_file->Size();
351 if (__builtin_sub_overflow(size, sizeof(start), &size)) {
352 return false;
353 }
354
355 memory_ = std::make_unique<MemoryRange>(memory_file, sizeof(start), size, start);
Christopher Ferris723cf9b2017-01-19 20:08:48 -0800356 return true;
357}
358
Josh Gaob8377632017-10-18 11:52:53 -0700359size_t MemoryOffline::Read(uint64_t addr, void* dst, size_t size) {
Josh Gao29c53782017-09-26 14:11:37 -0700360 if (!memory_) {
361 return 0;
Christopher Ferrisf447c8e2017-04-03 12:39:47 -0700362 }
363
Josh Gaob8377632017-10-18 11:52:53 -0700364 return memory_->Read(addr, dst, size);
Christopher Ferrisf447c8e2017-04-03 12:39:47 -0700365}
Christopher Ferrisd226a512017-07-14 10:37:19 -0700366
Christopher Ferris6633b0c2018-04-03 16:03:28 -0700367MemoryOfflineBuffer::MemoryOfflineBuffer(const uint8_t* data, uint64_t start, uint64_t end)
368 : data_(data), start_(start), end_(end) {}
369
370void MemoryOfflineBuffer::Reset(const uint8_t* data, uint64_t start, uint64_t end) {
371 data_ = data;
372 start_ = start;
373 end_ = end;
374}
375
376size_t MemoryOfflineBuffer::Read(uint64_t addr, void* dst, size_t size) {
377 if (addr < start_ || addr >= end_) {
378 return 0;
379 }
380
381 size_t read_length = std::min(size, static_cast<size_t>(end_ - addr));
382 memcpy(dst, &data_[addr - start_], read_length);
383 return read_length;
384}
385
Christopher Ferris150db122017-12-20 18:49:01 -0800386MemoryOfflineParts::~MemoryOfflineParts() {
387 for (auto memory : memories_) {
388 delete memory;
389 }
390}
391
392size_t MemoryOfflineParts::Read(uint64_t addr, void* dst, size_t size) {
393 if (memories_.empty()) {
394 return 0;
395 }
396
397 // Do a read on each memory object, no support for reading across the
398 // different memory objects.
399 for (MemoryOffline* memory : memories_) {
400 size_t bytes = memory->Read(addr, dst, size);
401 if (bytes != 0) {
402 return bytes;
403 }
404 }
405 return 0;
406}
407
Christopher Ferrisef640102018-11-14 15:36:45 -0800408size_t MemoryCache::Read(uint64_t addr, void* dst, size_t size) {
409 // Only bother caching and looking at the cache if this is a small read for now.
410 if (size > 64) {
411 return impl_->Read(addr, dst, size);
412 }
413
414 uint64_t addr_page = addr >> kCacheBits;
415 auto entry = cache_.find(addr_page);
416 uint8_t* cache_dst;
417 if (entry != cache_.end()) {
418 cache_dst = entry->second;
419 } else {
420 cache_dst = cache_[addr_page];
421 if (!impl_->ReadFully(addr_page << kCacheBits, cache_dst, kCacheSize)) {
422 // Erase the entry.
423 cache_.erase(addr_page);
424 return impl_->Read(addr, dst, size);
425 }
426 }
427 size_t max_read = ((addr_page + 1) << kCacheBits) - addr;
428 if (size <= max_read) {
429 memcpy(dst, &cache_dst[addr & kCacheMask], size);
430 return size;
431 }
432
433 // The read crossed into another cached entry, since a read can only cross
434 // into one extra cached page, duplicate the code rather than looping.
435 memcpy(dst, &cache_dst[addr & kCacheMask], max_read);
436 dst = &reinterpret_cast<uint8_t*>(dst)[max_read];
437 addr_page++;
438
439 entry = cache_.find(addr_page);
440 if (entry != cache_.end()) {
441 cache_dst = entry->second;
442 } else {
443 cache_dst = cache_[addr_page];
444 if (!impl_->ReadFully(addr_page << kCacheBits, cache_dst, kCacheSize)) {
445 // Erase the entry.
446 cache_.erase(addr_page);
447 return impl_->Read(addr_page << kCacheBits, dst, size - max_read) + max_read;
448 }
449 }
450 memcpy(dst, cache_dst, size - max_read);
451 return size;
452}
453
Christopher Ferrisd226a512017-07-14 10:37:19 -0700454} // namespace unwindstack