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