sanitizer_stacktrace.cc revision 583025ddc52988cdcedb5dee57e0d66a0c586340
1//===-- sanitizer_stacktrace.cc -------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is shared between AddressSanitizer and ThreadSanitizer
11// run-time libraries.
12//===----------------------------------------------------------------------===//
13
14#include "sanitizer_common.h"
15#include "sanitizer_procmaps.h"
16#include "sanitizer_stacktrace.h"
17#include "sanitizer_symbolizer.h"
18
19namespace __sanitizer {
20const char *StripPathPrefix(const char *filepath,
21                            const char *strip_file_prefix) {
22  if (filepath == 0) return 0;
23  if (filepath == internal_strstr(filepath, strip_file_prefix))
24    return filepath + internal_strlen(strip_file_prefix);
25  return filepath;
26}
27
28// ----------------------- StackTrace ----------------------------- {{{1
29uptr StackTrace::GetPreviousInstructionPc(uptr pc) {
30#ifdef __arm__
31  // Cancel Thumb bit.
32  pc = pc & (~1);
33#endif
34#if defined(__powerpc__) || defined(__powerpc64__)
35  // PCs are always 4 byte aligned.
36  return pc - 4;
37#elif defined(__sparc__)
38  return pc - 8;
39#else
40  return pc - 1;
41#endif
42}
43
44static void PrintStackFramePrefix(uptr frame_num, uptr pc) {
45  Printf("    #%zu 0x%zx", frame_num, pc);
46}
47
48static void PrintSourceLocation(const char *file, int line, int column,
49                                const char *strip_file_prefix) {
50  CHECK(file);
51  Printf(" %s", StripPathPrefix(file, strip_file_prefix));
52  if (line > 0) {
53    Printf(":%d", line);
54    if (column > 0)
55      Printf(":%d", column);
56  }
57}
58
59static void PrintModuleAndOffset(const char *module, uptr offset,
60                                 const char *strip_file_prefix) {
61  Printf(" (%s+0x%zx)", StripPathPrefix(module, strip_file_prefix), offset);
62}
63
64void StackTrace::PrintStack(const uptr *addr, uptr size,
65                            bool symbolize, const char *strip_file_prefix,
66                            SymbolizeCallback symbolize_callback ) {
67  MemoryMappingLayout proc_maps(/*cache_enabled*/true);
68  InternalScopedBuffer<char> buff(GetPageSizeCached() * 2);
69  InternalScopedBuffer<AddressInfo> addr_frames(64);
70  uptr frame_num = 0;
71  for (uptr i = 0; i < size && addr[i]; i++) {
72    // PCs in stack traces are actually the return addresses, that is,
73    // addresses of the next instructions after the call.
74    uptr pc = GetPreviousInstructionPc(addr[i]);
75    uptr addr_frames_num = 0;  // The number of stack frames for current
76                               // instruction address.
77    if (symbolize_callback) {
78      if (symbolize_callback((void*)pc, buff.data(), buff.size())) {
79        addr_frames_num = 1;
80        PrintStackFramePrefix(frame_num, pc);
81        // We can't know anything about the string returned by external
82        // symbolizer, but if it starts with filename, try to strip path prefix
83        // from it.
84        Printf(" %s\n", StripPathPrefix(buff.data(), strip_file_prefix));
85        frame_num++;
86      }
87    }
88    if (symbolize && addr_frames_num == 0) {
89      // Use our own (online) symbolizer, if necessary.
90      addr_frames_num = SymbolizeCode(pc, addr_frames.data(),
91                                      addr_frames.size());
92      for (uptr j = 0; j < addr_frames_num; j++) {
93        AddressInfo &info = addr_frames[j];
94        PrintStackFramePrefix(frame_num, pc);
95        if (info.function) {
96          Printf(" in %s", info.function);
97        }
98        if (info.file) {
99          PrintSourceLocation(info.file, info.line, info.column,
100                              strip_file_prefix);
101        } else if (info.module) {
102          PrintModuleAndOffset(info.module, info.module_offset,
103                               strip_file_prefix);
104        }
105        Printf("\n");
106        info.Clear();
107        frame_num++;
108      }
109    }
110    if (addr_frames_num == 0) {
111      // If online symbolization failed, try to output at least module and
112      // offset for instruction.
113      PrintStackFramePrefix(frame_num, pc);
114      uptr offset;
115      if (proc_maps.GetObjectNameAndOffset(pc, &offset,
116                                           buff.data(), buff.size(),
117                                           /* protection */0)) {
118        PrintModuleAndOffset(buff.data(), offset, strip_file_prefix);
119      }
120      Printf("\n");
121      frame_num++;
122    }
123  }
124}
125
126uptr StackTrace::GetCurrentPc() {
127  return GET_CALLER_PC();
128}
129
130void StackTrace::FastUnwindStack(uptr pc, uptr bp,
131                                 uptr stack_top, uptr stack_bottom) {
132  CHECK(size == 0 && trace[0] == pc);
133  size = 1;
134  uhwptr *frame = (uhwptr *)bp;
135  uhwptr *prev_frame = frame - 1;
136  // Avoid infinite loop when frame == frame[0] by using frame > prev_frame.
137  while (frame > prev_frame &&
138         frame < (uhwptr *)stack_top - 2 &&
139         frame > (uhwptr *)stack_bottom &&
140         IsAligned((uptr)frame, sizeof(*frame)) &&
141         size < max_size) {
142    uhwptr pc1 = frame[1];
143    if (pc1 != pc) {
144      trace[size++] = (uptr) pc1;
145    }
146    prev_frame = frame;
147    frame = (uhwptr *)frame[0];
148  }
149}
150
151void StackTrace::PopStackFrames(uptr count) {
152  CHECK(size >= count);
153  size -= count;
154  for (uptr i = 0; i < size; i++) {
155    trace[i] = trace[i + count];
156  }
157}
158
159// On 32-bits we don't compress stack traces.
160// On 64-bits we compress stack traces: if a given pc differes slightly from
161// the previous one, we record a 31-bit offset instead of the full pc.
162SANITIZER_INTERFACE_ATTRIBUTE
163uptr StackTrace::CompressStack(StackTrace *stack, u32 *compressed, uptr size) {
164#if SANITIZER_WORDSIZE == 32
165  // Don't compress, just copy.
166  uptr res = 0;
167  for (uptr i = 0; i < stack->size && i < size; i++) {
168    compressed[i] = stack->trace[i];
169    res++;
170  }
171  if (stack->size < size)
172    compressed[stack->size] = 0;
173#else  // 64 bits, compress.
174  uptr prev_pc = 0;
175  const uptr kMaxOffset = (1ULL << 30) - 1;
176  uptr c_index = 0;
177  uptr res = 0;
178  for (uptr i = 0, n = stack->size; i < n; i++) {
179    uptr pc = stack->trace[i];
180    if (!pc) break;
181    if ((s64)pc < 0) break;
182    // Printf("C pc[%zu] %zx\n", i, pc);
183    if (prev_pc - pc < kMaxOffset || pc - prev_pc < kMaxOffset) {
184      uptr offset = (s64)(pc - prev_pc);
185      offset |= (1U << 31);
186      if (c_index >= size) break;
187      // Printf("C co[%zu] offset %zx\n", i, offset);
188      compressed[c_index++] = offset;
189    } else {
190      uptr hi = pc >> 32;
191      uptr lo = (pc << 32) >> 32;
192      CHECK_EQ((hi & (1 << 31)), 0);
193      if (c_index + 1 >= size) break;
194      // Printf("C co[%zu] hi/lo: %zx %zx\n", c_index, hi, lo);
195      compressed[c_index++] = hi;
196      compressed[c_index++] = lo;
197    }
198    res++;
199    prev_pc = pc;
200  }
201  if (c_index < size)
202    compressed[c_index] = 0;
203  if (c_index + 1 < size)
204    compressed[c_index + 1] = 0;
205#endif  // SANITIZER_WORDSIZE
206
207  // debug-only code
208#if 0
209  StackTrace check_stack;
210  UncompressStack(&check_stack, compressed, size);
211  if (res < check_stack.size) {
212    Printf("res %zu check_stack.size %zu; c_size %zu\n", res,
213           check_stack.size, size);
214  }
215  // |res| may be greater than check_stack.size, because
216  // UncompressStack(CompressStack(stack)) eliminates the 0x0 frames.
217  CHECK(res >= check_stack.size);
218  CHECK_EQ(0, REAL(memcmp)(check_stack.trace, stack->trace,
219                          check_stack.size * sizeof(uptr)));
220#endif
221
222  return res;
223}
224
225SANITIZER_INTERFACE_ATTRIBUTE
226void StackTrace::UncompressStack(StackTrace *stack,
227                                 u32 *compressed, uptr size) {
228#if SANITIZER_WORDSIZE == 32
229  // Don't uncompress, just copy.
230  stack->size = 0;
231  for (uptr i = 0; i < size && i < kStackTraceMax; i++) {
232    if (!compressed[i]) break;
233    stack->size++;
234    stack->trace[i] = compressed[i];
235  }
236#else  // 64 bits, uncompress
237  uptr prev_pc = 0;
238  stack->size = 0;
239  for (uptr i = 0; i < size && stack->size < kStackTraceMax; i++) {
240    u32 x = compressed[i];
241    uptr pc = 0;
242    if (x & (1U << 31)) {
243      // Printf("U co[%zu] offset: %x\n", i, x);
244      // this is an offset
245      s32 offset = x;
246      offset = (offset << 1) >> 1;  // remove the 31-byte and sign-extend.
247      pc = prev_pc + offset;
248      CHECK(pc);
249    } else {
250      // CHECK(i + 1 < size);
251      if (i + 1 >= size) break;
252      uptr hi = x;
253      uptr lo = compressed[i+1];
254      // Printf("U co[%zu] hi/lo: %zx %zx\n", i, hi, lo);
255      i++;
256      pc = (hi << 32) | lo;
257      if (!pc) break;
258    }
259    // Printf("U pc[%zu] %zx\n", stack->size, pc);
260    stack->trace[stack->size++] = pc;
261    prev_pc = pc;
262  }
263#endif  // SANITIZER_WORDSIZE
264}
265
266}  // namespace __sanitizer
267