Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-09 07:49:13

0001 /*
0002  * Copyright (c) 2019 Opticks Team. All Rights Reserved.
0003  *
0004  * This file is part of Opticks
0005  * (see https://bitbucket.org/simoncblyth/opticks).
0006  *
0007  * Licensed under the Apache License, Version 2.0 (the "License"); 
0008  * you may not use this file except in compliance with the License.  
0009  * You may obtain a copy of the License at
0010  *
0011  *   http://www.apache.org/licenses/LICENSE-2.0
0012  *
0013  * Unless required by applicable law or agreed to in writing, software 
0014  * distributed under the License is distributed on an "AS IS" BASIS, 
0015  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
0016  * See the License for the specific language governing permissions and 
0017  * limitations under the License.
0018  */
0019 
0020 // https://eli.thegreenplace.net/2015/programmatic-access-to-the-call-stack-in-c/
0021 
0022 #define UNW_LOCAL_ONLY
0023 #include <libunwind.h>
0024 #include <stdio.h>
0025 
0026 // Call this function to get a backtrace.
0027 void backtrace() {
0028   unw_cursor_t cursor;
0029   unw_context_t context;
0030 
0031   // Initialize cursor to current frame for local unwinding.
0032   unw_getcontext(&context);
0033   unw_init_local(&cursor, &context);
0034 
0035   // Unwind frames one by one, going up the frame stack.
0036   while (unw_step(&cursor) > 0) {
0037     unw_word_t offset, pc;
0038     unw_get_reg(&cursor, UNW_REG_IP, &pc);
0039     if (pc == 0) {
0040       break;
0041     }
0042     printf("0x%lx:", pc);
0043 
0044     char sym[256];
0045     if (unw_get_proc_name(&cursor, sym, sizeof(sym), &offset) == 0) {
0046       printf(" (%s+0x%lx)\n", sym, offset);
0047     } else {
0048       printf(" -- error: unable to obtain symbol name for this frame\n");
0049     }
0050   }
0051 }
0052 
0053 void foo() {
0054   backtrace(); // <-------- backtrace here!
0055 }
0056 
0057 void bar() {
0058   foo();
0059 }
0060 
0061 int main(int argc, char **argv) {
0062   bar();
0063 
0064   return 0;
0065 }