-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
crashinfounix.cpp
518 lines (472 loc) · 15.9 KB
/
crashinfounix.cpp
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
515
516
517
518
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "createdump.h"
#ifndef PT_ARM_EXIDX
#define PT_ARM_EXIDX 0x70000001 /* See llvm ELF.h */
#endif
extern CrashInfo* g_crashInfo;
int g_readProcessMemoryErrno = 0;
bool GetStatus(pid_t pid, pid_t* ppid, pid_t* tgid, std::string* name);
bool
CrashInfo::Initialize()
{
char memPath[128];
_snprintf_s(memPath, sizeof(memPath), sizeof(memPath), "/proc/%lu/mem", m_pid);
m_fd = open(memPath, O_RDONLY);
if (m_fd == -1)
{
int err = errno;
const char* message = "Problem accessing memory";
if (err == EPERM || err == EACCES)
{
message = "The process or container does not have permissions or access";
}
else if (err == ENOENT)
{
message = "Invalid process id";
}
printf_error("%s: open(%s) FAILED %s (%d)\n", message, memPath, strerror(err), err);
return false;
}
// Get the process info
if (!GetStatus(m_pid, &m_ppid, &m_tgid, &m_name))
{
return false;
}
m_canUseProcVmReadSyscall = true;
return true;
}
void
CrashInfo::CleanupAndResumeProcess()
{
// Resume all the threads suspended in EnumerateAndSuspendThreads
for (ThreadInfo* thread : m_threads)
{
if (ptrace(PTRACE_DETACH, thread->Tid(), nullptr, nullptr) != -1)
{
int waitStatus;
waitpid(thread->Tid(), &waitStatus, __WALL);
}
}
if (m_fd != -1)
{
close(m_fd);
m_fd = -1;
}
}
//
// Suspends all the threads and creating a list of them. Should be the before gathering any info about the process.
//
bool
CrashInfo::EnumerateAndSuspendThreads()
{
char taskPath[128];
snprintf(taskPath, sizeof(taskPath), "/proc/%d/task", m_pid);
DIR* taskDir = opendir(taskPath);
if (taskDir == nullptr)
{
printf_error("Problem enumerating threads: opendir(%s) FAILED %s (%d)\n", taskPath, strerror(errno), errno);
return false;
}
struct dirent* entry;
while ((entry = readdir(taskDir)) != nullptr)
{
pid_t tid = static_cast<pid_t>(strtol(entry->d_name, nullptr, 10));
if (tid != 0)
{
// Reference: http://stackoverflow.com/questions/18577956/how-to-use-ptrace-to-get-a-consistent-view-of-multiple-threads
if (ptrace(PTRACE_ATTACH, tid, nullptr, nullptr) != -1)
{
int waitStatus;
waitpid(tid, &waitStatus, __WALL);
}
else
{
printf_error("Problem suspending threads: ptrace(ATTACH, %d) FAILED %s (%d)\n", tid, strerror(errno), errno);
closedir(taskDir);
return false;
}
// Add to the list of threads
ThreadInfo* thread = new ThreadInfo(*this, tid);
m_threads.push_back(thread);
}
}
closedir(taskDir);
return true;
}
//
// Get the auxv entries to use and add to the core dump
//
bool
CrashInfo::GetAuxvEntries()
{
char auxvPath[128];
snprintf(auxvPath, sizeof(auxvPath), "/proc/%d/auxv", m_pid);
int fd = open(auxvPath, O_RDONLY, 0);
if (fd == -1)
{
printf_error("Problem reading aux info: open(%s) FAILED %s (%d)\n", auxvPath, strerror(errno), errno);
return false;
}
bool result = false;
elf_aux_entry auxvEntry;
while (read(fd, &auxvEntry, sizeof(elf_aux_entry)) == sizeof(elf_aux_entry))
{
m_auxvEntries.push_back(auxvEntry);
if (auxvEntry.a_type == AT_NULL)
{
break;
}
if (auxvEntry.a_type < AT_MAX)
{
m_auxvValues[auxvEntry.a_type] = auxvEntry.a_un.a_val;
TRACE("AUXV: %" PRIu " = %" PRIxA "\n", auxvEntry.a_type, auxvEntry.a_un.a_val);
result = true;
}
}
close(fd);
return result;
}
//
// Get the module mappings for the core dump NT_FILE notes
//
bool
CrashInfo::EnumerateMemoryRegions()
{
// Here we read /proc/<pid>/maps file in order to parse it and figure out what it says
// about a library we are looking for. This file looks something like this:
//
// [address] [perms] [offset] [dev] [inode] [pathname] - HEADER is not preset in an actual file
//
// 35b1800000-35b1820000 r-xp 00000000 08:02 135522 /usr/lib64/ld-2.15.so
// 35b1a1f000-35b1a20000 r--p 0001f000 08:02 135522 /usr/lib64/ld-2.15.so
// 35b1a20000-35b1a21000 rw-p 00020000 08:02 135522 /usr/lib64/ld-2.15.so
// 35b1a21000-35b1a22000 rw-p 00000000 00:00 0 [heap]
// 35b1c00000-35b1dac000 r-xp 00000000 08:02 135870 /usr/lib64/libc-2.15.so
// 35b1dac000-35b1fac000 ---p 001ac000 08:02 135870 /usr/lib64/libc-2.15.so
// 35b1fac000-35b1fb0000 r--p 001ac000 08:02 135870 /usr/lib64/libc-2.15.so
// 35b1fb0000-35b1fb2000 rw-p 001b0000 08:02 135870 /usr/lib64/libc-2.15.so
char* line = nullptr;
size_t lineLen = 0;
int count = 0;
ssize_t read;
// Making something like: /proc/123/maps
char mapPath[128];
int chars = snprintf(mapPath, sizeof(mapPath), "/proc/%d/maps", m_pid);
assert(chars > 0 && (size_t)chars <= sizeof(mapPath));
FILE* mapsFile = fopen(mapPath, "r");
if (mapsFile == nullptr)
{
printf_error("Problem reading maps file: fopen(%s) FAILED %s (%d)\n", mapPath, strerror(errno), errno);
return false;
}
// linuxGateAddress is the beginning of the kernel's mapping of
// linux-gate.so in the process. It doesn't actually show up in the
// maps list as a filename, but it can be found using the AT_SYSINFO_EHDR
// aux vector entry, which gives the information necessary to special
// case its entry when creating the list of mappings.
// See http://www.trilithium.com/johan/2005/08/linux-gate/ for more
// information.
const void* linuxGateAddress = (const void*)m_auxvValues[AT_SYSINFO_EHDR];
// Reading maps file line by line
while ((read = getline(&line, &lineLen, mapsFile)) != -1)
{
uint64_t start, end, offset;
char* permissions = nullptr;
char* moduleName = nullptr;
int c = sscanf(line, "%" PRIx64 "-%" PRIx64 " %m[-rwxsp] %" PRIx64 " %*[:0-9a-f] %*d %m[^\n]\n", &start, &end, &permissions, &offset, &moduleName);
if (c == 4 || c == 5)
{
// r = read
// w = write
// x = execute
// s = shared
// p = private (copy on write)
uint32_t regionFlags = 0;
if (strchr(permissions, 'r')) {
regionFlags |= PF_R;
}
if (strchr(permissions, 'w')) {
regionFlags |= PF_W;
}
if (strchr(permissions, 'x')) {
regionFlags |= PF_X;
}
if (strchr(permissions, 's')) {
regionFlags |= MEMORY_REGION_FLAG_SHARED;
}
if (strchr(permissions, 'p')) {
regionFlags |= MEMORY_REGION_FLAG_PRIVATE;
}
MemoryRegion memoryRegion(regionFlags, start, end, offset, std::string(moduleName != nullptr ? moduleName : ""));
if (moduleName != nullptr && *moduleName == '/')
{
m_moduleMappings.insert(memoryRegion);
m_cbModuleMappings += memoryRegion.Size();
}
else
{
m_otherMappings.insert(memoryRegion);
}
if (linuxGateAddress != nullptr && reinterpret_cast<void*>(start) == linuxGateAddress)
{
InsertMemoryRegion(memoryRegion);
}
free(moduleName);
free(permissions);
}
}
if (g_diagnostics)
{
TRACE("Module mappings (%06llx):\n", m_cbModuleMappings / PAGE_SIZE);
for (const MemoryRegion& region : m_moduleMappings)
{
region.Trace();
}
TRACE("Other mappings:\n");
for (const MemoryRegion& region : m_otherMappings)
{
region.Trace();
}
}
free(line); // We didn't allocate line, but as per contract of getline we should free it
fclose(mapsFile);
return true;
}
//
// All the shared (native) module info to the core dump
//
bool
CrashInfo::GetDSOInfo()
{
Phdr* phdrAddr = reinterpret_cast<Phdr*>(m_auxvValues[AT_PHDR]);
int phnum = m_auxvValues[AT_PHNUM];
assert(m_auxvValues[AT_PHENT] == sizeof(Phdr));
assert(phnum != PN_XNUM);
return EnumerateElfInfo(phdrAddr, phnum);
}
//
// Add all the necessary ELF headers to the core dump
//
void
CrashInfo::VisitModule(uint64_t baseAddress, std::string& moduleName)
{
if (baseAddress == 0 || baseAddress == m_auxvValues[AT_SYSINFO_EHDR]) {
return;
}
// For reasons unknown the main app singlefile module name is empty in the DSO. This replaces
// it with the one found in the /proc/<pid>/maps.
if (moduleName.empty())
{
MemoryRegion search(0, baseAddress, baseAddress + PAGE_SIZE);
const MemoryRegion* region = SearchMemoryRegions(m_moduleMappings, search);
if (region != nullptr)
{
moduleName = region->FileName();
TRACE("VisitModule using module name from mappings '%s'\n", moduleName.c_str());
}
}
AddModuleInfo(false, baseAddress, nullptr, moduleName);
if (m_coreclrPath.empty())
{
size_t last = moduleName.rfind(DIRECTORY_SEPARATOR_STR_A MAKEDLLNAME_A("coreclr"));
if (last != std::string::npos)
{
m_coreclrPath = moduleName.substr(0, last + 1);
m_runtimeBaseAddress = baseAddress;
// Now populate the elfreader with the runtime module info and
// lookup the DAC table symbol to ensure that all the memory
// necessary is in the core dump.
if (PopulateForSymbolLookup(baseAddress))
{
uint64_t symbolOffset;
if (!TryLookupSymbol(DACCESS_TABLE_SYMBOL, &symbolOffset))
{
TRACE("TryLookupSymbol(" DACCESS_TABLE_SYMBOL ") FAILED\n");
}
}
}
else if (g_checkForSingleFile)
{
if (PopulateForSymbolLookup(baseAddress))
{
uint64_t symbolOffset;
if (TryLookupSymbol("DotNetRuntimeInfo", &symbolOffset))
{
m_coreclrPath = GetDirectory(moduleName);
m_runtimeBaseAddress = baseAddress;
RuntimeInfo runtimeInfo { };
if (ReadMemory((void*)(baseAddress + symbolOffset), &runtimeInfo, sizeof(RuntimeInfo)))
{
if (strcmp(runtimeInfo.Signature, RUNTIME_INFO_SIGNATURE) == 0)
{
TRACE("Found valid single-file runtime info\n");
}
}
}
}
}
}
EnumerateProgramHeaders(baseAddress);
}
// Helper for PAL_GetUnwindInfoSize. Reads memory directly without adding it to the memory region list.
BOOL
ReadMemoryAdapter(PVOID address, PVOID buffer, SIZE_T size)
{
size_t read = 0;
return g_crashInfo->ReadProcessMemory(address, buffer, size, &read);
}
//
// Called for each program header adding the build id note, unwind frame
// region and module addresses to the crash info.
//
void
CrashInfo::VisitProgramHeader(uint64_t loadbias, uint64_t baseAddress, Phdr* phdr)
{
switch (phdr->p_type)
{
case PT_DYNAMIC:
case PT_NOTE:
#if defined(TARGET_ARM)
case PT_ARM_EXIDX:
#endif
if (phdr->p_vaddr != 0 && phdr->p_memsz != 0)
{
InsertMemoryRegion(loadbias + phdr->p_vaddr, phdr->p_memsz);
}
break;
case PT_GNU_EH_FRAME:
if (phdr->p_vaddr != 0 && phdr->p_memsz != 0)
{
uint64_t ehFrameHdrStart = loadbias + phdr->p_vaddr;
uint64_t ehFrameHdrSize = phdr->p_memsz;
TRACE("VisitProgramHeader: ehFrameHdrStart %016llx ehFrameHdrSize %08llx\n", ehFrameHdrStart, ehFrameHdrSize);
InsertMemoryRegion(ehFrameHdrStart, ehFrameHdrSize);
uint64_t ehFrameStart;
uint64_t ehFrameSize;
if (PAL_GetUnwindInfoSize(baseAddress, ehFrameHdrStart, ReadMemoryAdapter, &ehFrameStart, &ehFrameSize))
{
TRACE("VisitProgramHeader: ehFrameStart %016llx ehFrameSize %08llx\n", ehFrameStart, ehFrameSize);
if (ehFrameStart != 0 && ehFrameSize != 0)
{
InsertMemoryRegion(ehFrameStart, ehFrameSize);
}
}
else
{
TRACE("VisitProgramHeader: PAL_GetUnwindInfoSize FAILED\n");
}
}
break;
case PT_LOAD:
AddModuleAddressRange(loadbias + phdr->p_vaddr, loadbias + phdr->p_vaddr + phdr->p_memsz, baseAddress);
break;
}
}
//
// Get the memory region flags for a start address
//
uint32_t
CrashInfo::GetMemoryRegionFlags(uint64_t start)
{
MemoryRegion search(0, start, start + PAGE_SIZE, 0);
const MemoryRegion* region = SearchMemoryRegions(m_moduleMappings, search);
if (region != nullptr) {
return region->Flags();
}
region = SearchMemoryRegions(m_otherMappings, search);
if (region != nullptr) {
return region->Flags();
}
TRACE("GetMemoryRegionFlags: FAILED\n");
return PF_R | PF_W | PF_X;
}
//
// Read raw memory
//
bool
CrashInfo::ReadProcessMemory(void* address, void* buffer, size_t size, size_t* read)
{
assert(buffer != nullptr);
assert(read != nullptr);
*read = 0;
#ifdef HAVE_PROCESS_VM_READV
if (m_canUseProcVmReadSyscall)
{
iovec local{ buffer, size };
iovec remote{ address, size };
*read = process_vm_readv(m_pid, &local, 1, &remote, 1, 0);
}
if (!m_canUseProcVmReadSyscall || (*read == (size_t)-1 && (errno == EPERM || errno == ENOSYS)))
#endif
{
// If we've failed, avoid going through expensive syscalls
// After all, the use of process_vm_readv is largely as a
// performance optimization.
m_canUseProcVmReadSyscall = false;
assert(m_fd != -1);
*read = pread64(m_fd, buffer, size, (off64_t)address);
}
if (*read == (size_t)-1)
{
// Preserve errno for the ELF dump writer call
g_readProcessMemoryErrno = errno;
TRACE_VERBOSE("ReadProcessMemory FAILED addr: %" PRIA PRIx " size: %zu error: %s (%d)\n", address, size, strerror(g_readProcessMemoryErrno), g_readProcessMemoryErrno);
return false;
}
return true;
}
//
// Get the process or thread status
//
bool
GetStatus(pid_t pid, pid_t* ppid, pid_t* tgid, std::string* name)
{
char statusPath[128];
snprintf(statusPath, sizeof(statusPath), "/proc/%d/status", pid);
FILE *statusFile = fopen(statusPath, "r");
if (statusFile == nullptr)
{
printf_error("GetStatus fopen(%s) FAILED %s (%d)\n", statusPath, strerror(errno), errno);
return false;
}
*ppid = -1;
char *line = nullptr;
size_t lineLen = 0;
ssize_t read;
while ((read = getline(&line, &lineLen, statusFile)) != -1)
{
if (strncmp("PPid:\t", line, 6) == 0)
{
*ppid = atoll(line + 6);
}
else if (strncmp("Tgid:\t", line, 6) == 0)
{
*tgid = atoll(line + 6);
}
else if (strncmp("Name:\t", line, 6) == 0)
{
if (name != nullptr)
{
char* n = strchr(line + 6, '\n');
if (n != nullptr)
{
*n = '\0';
}
*name = line + 6;
}
}
}
free(line);
fclose(statusFile);
return true;
}
void
ModuleInfo::LoadModule()
{
if (m_module == nullptr)
{
m_module = dlopen(m_moduleName.c_str(), RTLD_LAZY);
m_localBaseAddress = ((struct link_map*)m_module)->l_addr;
}
}