Async-signal-safe symbolizer, fatal signal handler
[folly.git] / folly / experimental / symbolizer / Symbolizer.cpp
1 /*
2  * Copyright 2013 Facebook, Inc.
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 // Must be first to ensure that UNW_LOCAL_ONLY is defined
18 #define UNW_LOCAL_ONLY 1
19 #include <libunwind.h>
20
21 #include "folly/experimental/symbolizer/Symbolizer.h"
22
23 #include <limits.h>
24
25 #include "folly/Conv.h"
26 #include "folly/FileUtil.h"
27 #include "folly/String.h"
28
29 #include "folly/experimental/symbolizer/Elf.h"
30 #include "folly/experimental/symbolizer/Dwarf.h"
31 #include "folly/experimental/symbolizer/LineReader.h"
32
33 namespace folly {
34 namespace symbolizer {
35
36 namespace {
37
38 /**
39  * Read a hex value.
40  */
41 uintptr_t readHex(StringPiece& sp) {
42   uintptr_t val = 0;
43   const char* p = sp.begin();
44   for (; p != sp.end(); ++p) {
45     unsigned int v;
46     if (*p >= '0' && *p <= '9') {
47       v = (*p - '0');
48     } else if (*p >= 'a' && *p <= 'f') {
49       v = (*p - 'a') + 10;
50     } else if (*p >= 'A' && *p <= 'F') {
51       v = (*p - 'A') + 10;
52     } else {
53       break;
54     }
55     val = (val << 4) + v;
56   }
57   sp.assign(p, sp.end());
58   return val;
59 }
60
61 /**
62  * Skip over non-space characters.
63  */
64 void skipNS(StringPiece& sp) {
65   const char* p = sp.begin();
66   for (; p != sp.end() && (*p != ' ' && *p != '\t'); ++p) { }
67   sp.assign(p, sp.end());
68 }
69
70 /**
71  * Skip over space and tab characters.
72  */
73 void skipWS(StringPiece& sp) {
74   const char* p = sp.begin();
75   for (; p != sp.end() && (*p == ' ' || *p == '\t'); ++p) { }
76   sp.assign(p, sp.end());
77 }
78
79 /**
80  * Parse a line from /proc/self/maps
81  */
82 bool parseProcMapsLine(StringPiece line,
83                        uintptr_t& from, uintptr_t& to,
84                        StringPiece& fileName) {
85   // from     to       perm offset   dev   inode             path
86   // 00400000-00405000 r-xp 00000000 08:03 35291182          /bin/cat
87   if (line.empty()) {
88     return false;
89   }
90
91   // Remove trailing newline, if any
92   if (line.back() == '\n') {
93     line.pop_back();
94   }
95
96   // from
97   from = readHex(line);
98   if (line.empty() || line.front() != '-') {
99     return false;
100   }
101   line.pop_front();
102
103   // to
104   to = readHex(line);
105   if (line.empty() || line.front() != ' ') {
106     return false;
107   }
108   line.pop_front();
109
110   // perms
111   skipNS(line);
112   if (line.empty() || line.front() != ' ') {
113     return false;
114   }
115   line.pop_front();
116
117   uintptr_t fileOffset = readHex(line);
118   if (line.empty() || line.front() != ' ') {
119     return false;
120   }
121   line.pop_front();
122   if (fileOffset != 0) {
123     return false;  // main mapping starts at 0
124   }
125
126   // dev
127   skipNS(line);
128   if (line.empty() || line.front() != ' ') {
129     return false;
130   }
131   line.pop_front();
132
133   // inode
134   skipNS(line);
135   if (line.empty() || line.front() != ' ') {
136     return false;
137   }
138
139   skipWS(line);
140   if (line.empty()) {
141     fileName.clear();
142     return true;
143   }
144
145   fileName = line;
146   return true;
147 }
148
149 }  // namespace
150
151 ssize_t getStackTrace(AddressInfo* addresses,
152                       size_t maxAddresses,
153                       size_t skip) {
154   unw_context_t uctx;
155   int r = unw_getcontext(&uctx);
156   if (r < 0) {
157     return -1;
158   }
159
160   unw_cursor_t cursor;
161   size_t idx = 0;
162   bool first = true;
163   while (idx < maxAddresses) {
164     if (first) {
165       first = false;
166       r = unw_init_local(&cursor, &uctx);
167     } else {
168       r = unw_step(&cursor);
169       if (r == 0) {
170         break;
171       }
172     }
173     if (r < 0) {
174       return -1;
175     }
176
177     if (skip != 0) {
178       --skip;
179       continue;
180     }
181     unw_word_t ip;
182     int rr = unw_get_reg(&cursor, UNW_REG_IP, &ip);
183     if (rr < 0) {
184       return -1;
185     }
186
187     // If error, assume not a signal frame
188     rr = unw_is_signal_frame(&cursor);
189
190     addresses[idx++] = AddressInfo(ip, (rr > 0));
191   }
192
193   if (r < 0) {
194     return -1;
195   }
196
197   return idx;
198 }
199
200 void Symbolizer::symbolize(AddressInfo* addresses, size_t addressCount) {
201   size_t remaining = 0;
202   for (size_t i = 0; i < addressCount; ++i) {
203     auto& ainfo = addresses[i];
204     if (!ainfo.found) {
205       ++remaining;
206       ainfo.name.clear();
207       ainfo.location = Dwarf::LocationInfo();
208     }
209   }
210
211   if (remaining == 0) {  // we're done
212     return;
213   }
214
215   int fd = openNoInt("/proc/self/maps", O_RDONLY);
216   if (fd == -1) {
217     return;
218   }
219
220   char buf[PATH_MAX + 100];  // Long enough for any line
221   LineReader reader(fd, buf, sizeof(buf));
222
223   char fileNameBuf[PATH_MAX];
224
225   while (remaining != 0) {
226     StringPiece line;
227     if (reader.readLine(line) != LineReader::kReading) {
228       break;
229     }
230
231     // Parse line
232     uintptr_t from;
233     uintptr_t to;
234     StringPiece fileName;
235     if (!parseProcMapsLine(line, from, to, fileName)) {
236       continue;
237     }
238
239     bool first = true;
240     ElfFile* elfFile = nullptr;
241
242     // See if any addresses are here
243     for (size_t i = 0; i < addressCount; ++i) {
244       auto& ainfo = addresses[i];
245       if (ainfo.found) {
246         continue;
247       }
248
249       uintptr_t address = ainfo.address;
250
251       // If the next address (closer to the top of the stack) was a signal
252       // frame, then this is the *resume* address, which is the address
253       // after the location where the signal was caught. This might be in
254       // the next function, so subtract 1 before symbolizing.
255       if (i != 0 && addresses[i-1].isSignalFrame) {
256         --address;
257       }
258
259       if (from > address || address >= to) {
260         continue;
261       }
262
263       // Found
264       ainfo.found = true;
265       --remaining;
266
267       // Open the file on first use
268       if (first) {
269         first = false;
270         if (fileCount_ < kMaxFiles &&
271             !fileName.empty() &&
272             fileName.size() < sizeof(fileNameBuf)) {
273           memcpy(fileNameBuf, fileName.data(), fileName.size());
274           fileNameBuf[fileName.size()] = '\0';
275           auto& f = files_[fileCount_++];
276           if (f.openNoThrow(fileNameBuf) != -1) {
277             elfFile = &f;
278           }
279         }
280       }
281
282       if (!elfFile) {
283         continue;
284       }
285
286       // Undo relocation
287       uintptr_t fileAddress = address - from + elfFile->getBaseAddress();
288       auto sym = elfFile->getDefinitionByAddress(fileAddress);
289       if (!sym.first) {
290         continue;
291       }
292       auto name = elfFile->getSymbolName(sym);
293       if (name) {
294         ainfo.name = name;
295       }
296
297       Dwarf(elfFile).findAddress(fileAddress, ainfo.location);
298     }
299   }
300
301   closeNoInt(fd);
302 }
303
304 namespace {
305 const char kHexChars[] = "0123456789abcdef";
306 }  // namespace
307
308 void SymbolizePrinter::print(const AddressInfo& ainfo) {
309   uintptr_t address = ainfo.address;
310   // Can't use sprintf, not async-signal-safe
311   static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
312   char buf[] = "    @ 0000000000000000";
313   char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));
314   const char padBuf[] = "                       ";
315   folly::StringPiece pad(padBuf,
316                          sizeof(padBuf) - 1 - (16 - 2 * sizeof(uintptr_t)));
317   char* p = end;
318   *p-- = '\0';
319   while (address != 0) {
320     *p-- = kHexChars[address & 0xf];
321     address >>= 4;
322   }
323   doPrint(folly::StringPiece(buf, end));
324
325   char mangledBuf[1024];
326   if (!ainfo.found) {
327     doPrint(" (not found)\n");
328     return;
329   }
330
331   if (ainfo.name.empty()) {
332     doPrint(" (unknown)\n");
333   } else if (ainfo.name.size() >= sizeof(mangledBuf)) {
334     doPrint(" ");
335     doPrint(ainfo.name);
336     doPrint("\n");
337   } else {
338     memcpy(mangledBuf, ainfo.name.data(), ainfo.name.size());
339     mangledBuf[ainfo.name.size()] = '\0';
340
341     char demangledBuf[1024];
342     demangle(mangledBuf, demangledBuf, sizeof(demangledBuf));
343     doPrint(" ");
344     doPrint(demangledBuf);
345     doPrint("\n");
346   }
347
348   char fileBuf[PATH_MAX];
349   fileBuf[0] = '\0';
350   if (ainfo.location.hasFileAndLine) {
351     ainfo.location.file.toBuffer(fileBuf, sizeof(fileBuf));
352     doPrint(pad);
353     doPrint(fileBuf);
354
355     char buf[22];
356     uint32_t n = uint64ToBufferUnsafe(ainfo.location.line, buf);
357     doPrint(":");
358     doPrint(StringPiece(buf, n));
359     doPrint("\n");
360   }
361
362   if (ainfo.location.hasMainFile) {
363     char mainFileBuf[PATH_MAX];
364     mainFileBuf[0] = '\0';
365     ainfo.location.mainFile.toBuffer(mainFileBuf, sizeof(mainFileBuf));
366     if (!ainfo.location.hasFileAndLine || strcmp(fileBuf, mainFileBuf)) {
367       doPrint(pad);
368       doPrint("-> ");
369       doPrint(mainFileBuf);
370       doPrint("\n");
371     }
372   }
373 }
374
375 void SymbolizePrinter::print(const AddressInfo* addresses,
376                              size_t addressCount) {
377   for (size_t i = 0; i < addressCount; ++i) {
378     auto& ainfo = addresses[i];
379     print(ainfo);
380   }
381 }
382
383 void OStreamSymbolizePrinter::doPrint(StringPiece sp) {
384   out_ << sp;
385 }
386
387 void FDSymbolizePrinter::doPrint(StringPiece sp) {
388   writeFull(fd_, sp.data(), sp.size());
389 }
390
391 std::ostream& operator<<(std::ostream& out, const AddressInfo& ainfo) {
392   OStreamSymbolizePrinter osp(out);
393   osp.print(ainfo);
394   return out;
395 }
396
397 }  // namespace symbolizer
398 }  // namespace folly