sanitizer_stacktrace.cc revision 90b0f1e3ba126bb2e92ab51ef379c98782c23d90
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  CHECK(size == 0 && trace[0] == pc);
111  size = 1;
112  uhwptr *frame = (uhwptr *)bp;
113  uhwptr *prev_frame = frame - 1;
114  if (stack_top < 4096) return;  // Sanity check for stack top.
115  // Avoid infinite loop when frame == frame[0] by using frame > prev_frame.
116  while (frame > prev_frame &&
117         frame < (uhwptr *)stack_top - 2 &&
118         frame > (uhwptr *)stack_bottom &&
119         IsAligned((uptr)frame, sizeof(*frame)) &&
120         size < max_size) {
121    uhwptr pc1 = frame[1];
122    if (pc1 != pc) {
123      trace[size++] = (uptr) pc1;
124    }
125    prev_frame = frame;
126    frame = (uhwptr *)frame[0];
127  }
128}
129
130void StackTrace::PopStackFrames(uptr count) {
131  CHECK(size >= count);
132  size -= count;
133  for (uptr i = 0; i < size; i++) {
134    trace[i] = trace[i + count];
135  }
136}
137
138// On 32-bits we don't compress stack traces.
139// On 64-bits we compress stack traces: if a given pc differes slightly from
140// the previous one, we record a 31-bit offset instead of the full pc.
141SANITIZER_INTERFACE_ATTRIBUTE
142uptr StackTrace::CompressStack(StackTrace *stack, u32 *compressed, uptr size) {
143#if SANITIZER_WORDSIZE == 32
144  // Don't compress, just copy.
145  uptr res = 0;
146  for (uptr i = 0; i < stack->size && i < size; i++) {
147    compressed[i] = stack->trace[i];
148    res++;
149  }
150  if (stack->size < size)
151    compressed[stack->size] = 0;
152#else  // 64 bits, compress.
153  uptr prev_pc = 0;
154  const uptr kMaxOffset = (1ULL << 30) - 1;
155  uptr c_index = 0;
156  uptr res = 0;
157  for (uptr i = 0, n = stack->size; i < n; i++) {
158    uptr pc = stack->trace[i];
159    if (!pc) break;
160    if ((s64)pc < 0) break;
161    // Printf("C pc[%zu] %zx\n", i, pc);
162    if (prev_pc - pc < kMaxOffset || pc - prev_pc < kMaxOffset) {
163      uptr offset = (s64)(pc - prev_pc);
164      offset |= (1U << 31);
165      if (c_index >= size) break;
166      // Printf("C co[%zu] offset %zx\n", i, offset);
167      compressed[c_index++] = offset;
168    } else {
169      uptr hi = pc >> 32;
170      uptr lo = (pc << 32) >> 32;
171      CHECK_EQ((hi & (1 << 31)), 0);
172      if (c_index + 1 >= size) break;
173      // Printf("C co[%zu] hi/lo: %zx %zx\n", c_index, hi, lo);
174      compressed[c_index++] = hi;
175      compressed[c_index++] = lo;
176    }
177    res++;
178    prev_pc = pc;
179  }
180  if (c_index < size)
181    compressed[c_index] = 0;
182  if (c_index + 1 < size)
183    compressed[c_index + 1] = 0;
184#endif  // SANITIZER_WORDSIZE
185
186  // debug-only code
187#if 0
188  StackTrace check_stack;
189  UncompressStack(&check_stack, compressed, size);
190  if (res < check_stack.size) {
191    Printf("res %zu check_stack.size %zu; c_size %zu\n", res,
192           check_stack.size, size);
193  }
194  // |res| may be greater than check_stack.size, because
195  // UncompressStack(CompressStack(stack)) eliminates the 0x0 frames.
196  CHECK(res >= check_stack.size);
197  CHECK_EQ(0, REAL(memcmp)(check_stack.trace, stack->trace,
198                          check_stack.size * sizeof(uptr)));
199#endif
200
201  return res;
202}
203
204SANITIZER_INTERFACE_ATTRIBUTE
205void StackTrace::UncompressStack(StackTrace *stack,
206                                 u32 *compressed, uptr size) {
207#if SANITIZER_WORDSIZE == 32
208  // Don't uncompress, just copy.
209  stack->size = 0;
210  for (uptr i = 0; i < size && i < kStackTraceMax; i++) {
211    if (!compressed[i]) break;
212    stack->size++;
213    stack->trace[i] = compressed[i];
214  }
215#else  // 64 bits, uncompress
216  uptr prev_pc = 0;
217  stack->size = 0;
218  for (uptr i = 0; i < size && stack->size < kStackTraceMax; i++) {
219    u32 x = compressed[i];
220    uptr pc = 0;
221    if (x & (1U << 31)) {
222      // Printf("U co[%zu] offset: %x\n", i, x);
223      // this is an offset
224      s32 offset = x;
225      offset = (offset << 1) >> 1;  // remove the 31-byte and sign-extend.
226      pc = prev_pc + offset;
227      CHECK(pc);
228    } else {
229      // CHECK(i + 1 < size);
230      if (i + 1 >= size) break;
231      uptr hi = x;
232      uptr lo = compressed[i+1];
233      // Printf("U co[%zu] hi/lo: %zx %zx\n", i, hi, lo);
234      i++;
235      pc = (hi << 32) | lo;
236      if (!pc) break;
237    }
238    // Printf("U pc[%zu] %zx\n", stack->size, pc);
239    stack->trace[stack->size++] = pc;
240    prev_pc = pc;
241  }
242#endif  // SANITIZER_WORDSIZE
243}
244
245}  // namespace __sanitizer
246