Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

77 linhas
2.2 KiB

  1. #pragma once
  2. #include "platform.hpp"
  3. #include "allocation_stats.hpp"
  4. #if defined FTB_WINDOWS
  5. # include <dbghelp.h>
  6. #else
  7. # ifdef FTB_LINUX_STACK_TRACE_USE_GDB
  8. # include <stdio.h>
  9. # include <stdlib.h>
  10. # include <sys/wait.h>
  11. # include <unistd.h>
  12. # include <sys/prctl.h>
  13. # else
  14. # include <execinfo.h>
  15. # include <unistd.h>
  16. # include "stdio.h"
  17. # include "stdlib.h"
  18. # endif
  19. #endif
  20. auto print_stacktrace() -> void {
  21. #if defined FTB_WINDOWS
  22. printf("Stacktrace: \n");
  23. unsigned int i;
  24. void * stack[ 100 ];
  25. HANDLE process;
  26. SYMBOL_INFO * symbol;
  27. symbol = ( SYMBOL_INFO * )calloc( sizeof( SYMBOL_INFO ) + 256 * sizeof( char ), 1 );
  28. symbol->MaxNameLen = 255;
  29. symbol->SizeOfStruct = sizeof( SYMBOL_INFO );
  30. unsigned short frames;
  31. frames = CaptureStackBackTrace( 1, 100, stack, NULL );
  32. process = GetCurrentProcess();
  33. SymInitialize( process, NULL, TRUE );
  34. for( i = 0; i < frames; i++ ) {
  35. SymFromAddr( process, ( DWORD64 )( stack[ i ] ), 0, symbol );
  36. printf( " %3i: %s\n", frames - i - 1, symbol->Name);
  37. }
  38. fflush(stdout);
  39. #else
  40. #ifdef FTB_LINUX_STACK_TRACE_USE_GDB
  41. printf("Stacktrace: \n");
  42. char pid_buf[30];
  43. sprintf(pid_buf, "%d", getpid());
  44. char name_buf[512];
  45. name_buf[readlink("/proc/self/exe", name_buf, 511)]=0;
  46. prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
  47. int child_pid = fork();
  48. if (!child_pid) {
  49. dup2(2,1); // redirect output to stderr - edit: unnecessary?
  50. execl("/usr/bin/gdb", "gdb", "--batch", "-n", "-ex", "thread", "-ex", "bt", name_buf, pid_buf, NULL);
  51. abort(); /* If gdb failed to start */
  52. } else {
  53. waitpid(child_pid,NULL,0);
  54. }
  55. #else
  56. // NOTE(Felix): Don't forget to compile with "-rdynamic"
  57. printf("Stacktrace (this is unmagled -- sorry): \n");
  58. char **strings;
  59. size_t i, size;
  60. enum Constexpr { MAX_SIZE = 1024 };
  61. void *array[MAX_SIZE];
  62. size = backtrace(array, MAX_SIZE);
  63. strings = backtrace_symbols(array, size);
  64. for (i = 0; i < size; i++)
  65. printf(" %3lu: %s\n", size - i - 1, strings[i]);
  66. puts("");
  67. ftb_free(strings);
  68. #endif
  69. #endif
  70. }