1 // Copyright (c) 2005 - 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: Arun Sharma
32 // Produce stack trace using libunwind
34 #include "utilities.h"
37 #define UNW_LOCAL_ONLY
38 #include <libunwind.h>
40 #include "glog/raw_logging.h"
41 #include "stacktrace.h"
43 _START_GOOGLE_NAMESPACE_
45 // Sometimes, we can try to get a stack trace from within a stack
46 // trace, because libunwind can call mmap (maybe indirectly via an
47 // internal mmap based memory allocator), and that mmap gets trapped
48 // and causes a stack-trace request. If were to try to honor that
49 // recursive request, we'd end up with infinite recursion or deadlock.
50 // Luckily, it's safe to ignore those subsequent traces. In such
51 // cases, we return 0 to indicate the situation.
52 static bool g_now_entering = false;
54 // If you change this function, also change GetStackFrames below.
55 int GetStackTrace(void** result, int max_depth, int skip_count) {
61 if (sync_val_compare_and_swap(&g_now_entering, false, true)) {
66 RAW_CHECK(unw_init_local(&cursor, &uc) >= 0, "unw_init_local failed");
67 skip_count++; // Do not include the "GetStackTrace" frame
69 while (n < max_depth) {
70 int ret = unw_get_reg(&cursor, UNW_REG_IP, (unw_word_t *) &ip);
78 ret = unw_step(&cursor);
83 g_now_entering = false;
87 _END_GOOGLE_NAMESPACE_