// cc -g -O0 -ftrapv -Wno-uninitialized -Wno-maybe-uninitialized -Wno-discarded-qualifiers -fsanitize=undefined -fsanitize=float-divide-by-zero -fsanitize-undefined-trap-on-error -fsanitize=float-cast-overflow -fno-sanitize-recover=all -fstack-protector-all monitor.c -o monitor -lm -lbacktrace

// This is a test of a mechanism to both trap runtime errors (the kind that can be caught primarily
// by the hardware - internal consistency checks such as array bound errors are still to come) - and
// to display a source-level backtrace that shows the local variables.  With a bit of tweaking we
// should be able to separate out %own variables from locals that are on the stack.

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <limits.h>
#include <fenv.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <backtrace.h>  // Ported lesson: Include libbacktrace for line numbers

typedef struct FrameContext {
  const char *fn_name;
  void (*print_locals)(void);
  uintptr_t pc_addr;  // Ported lesson: Store runtime function PC
  struct FrameContext *parent;
} FrameContext;

FrameContext  root_frame           = {"main", NULL, 0, NULL};
FrameContext *current_stream_frame = &root_frame;

static int zero;

// Note: the trick with taking the initial label address is specifically to work around a problem
// that arises due to nested procedure declarations causing the apparent address of the nested
// procedure to be in the thunk that is created on the stack.  Using the address of a label
// within the code gives us a real address to use in determining the procedure name from the
// debugging info embedded in the code when compiled with -g.

#define INSERT_BEFORE(name)                                                                         \
  __label__ __trace_loc;                                                                            \
  __trace_loc:; /* The semicolon creates an empty statement so the label is valid */                \
  auto void name##_backtrace(void);                                                                 \
  FrameContext frame = {#name, name##_backtrace, (uintptr_t) && __trace_loc, current_stream_frame}; \
  current_stream_frame = &frame;

#define INSERT_AFTER(name, fmt, vars...)                                                                      \
  current_stream_frame = frame.parent;                                                                        \
  void name##_backtrace(void) {                                                                               \
    const char *display_name = (strncmp(frame.fn_name, "_imp_", 5) == 0) ? frame.fn_name + 5 : frame.fn_name; \
    /*fprintf(stderr, "%s:\n", display_name);*/                                                               \
    fprintf(stderr, fmt, ##vars);                                                                             \
  }

#define RETURN_WITH_RESULT(value)           \
  do { current_stream_frame = frame.parent; \
       return value; } while (0)

#define RETURN                              \
  do { current_stream_frame = frame.parent; \
       return; } while (0)


// Global container to store the found stack address
static uintptr_t dynamic_abort_pc = 0;

static int __attribute__((no_instrument_function))
find_user_pc_callback(void *data, uintptr_t pc, const char *filename, int lineno, const char *function) {
  // If we find a frame with a valid file and function name that is NOT part of the runtime tracking library,
  // it means we successfully exited libc/signal space and found our actual Imp/C source code!
  if (filename && function && strncmp(function, "_imp_", 5) != 0 && strcmp(function, "imp_line_callback") != 0) {
    dynamic_abort_pc = pc;
    return 1; // Stop walking the physical stack immediately
  }
  return 0; // Keep walking
}

const char* __attribute__ ((noinline,no_instrument_function)) get_sigill_reason(int code) {
  switch (code) {
  case ILL_ILLOPC: return "Illegal Opcode (Emitted by GCC for UBSan/ftrapv traps)";
  case ILL_ILLOPN: return "Illegal Operand";
  case ILL_ILLADR: return "Illegal Addressing Mode";
  case ILL_ILLTRP: return "Illegal Trap";
  case ILL_PRVOPC: return "Privileged Opcode";
  case ILL_PRVREG: return "Privileged Register";
  case ILL_COPROC: return "Coprocessor Error";
  case ILL_BADSTK: return "Internal Stack Error";
  default:         return "Undefined Runtime Violation";
  }
}

const char* __attribute__ ((noinline,no_instrument_function)) get_sigfpe_reason(int code) {
  switch (code) {
  case FPE_INTDIV: return "Integer Division by Zero";
  case FPE_INTOVF: return "Integer Overflow";
  case FPE_FLTDIV: return "Floating-Point Division by Zero";
  case FPE_FLTOVF: return "Floating-Point Overflow";
  case FPE_FLTUND: return "Floating-Point Underflow";
  case FPE_FLTRES: return "Floating-Point Inexact Result";
  case FPE_FLTINV: return "Invalid Floating-Point Operation (e.g., sNaN Access)";
  case FPE_FLTSUB: return "Subscript Out of Range";
  default:         return "Floating-Point Arithmetic Error";
  }
}

const char* __attribute__ ((noinline,no_instrument_function)) get_sigsegv_reason(int code) {
  switch (code) {
  case SEGV_MAPERR: return "Address Not Mapped to Object (e.g., NULL Pointer Dereference)";
  case SEGV_ACCERR: return "Invalid Permissions for Mapped Object";
  default:          return "Segmentation Fault / Invalid Memory Reference";
  }
}

static int test_num = -1;

// Global backtrace state initialized in main via backtrace_create_state(argv[0], 1, ...)
static struct backtrace_state *global_bt_state = NULL;

// Buffers to capture line numbers from libbacktrace synchronously
static char cb_filename[256] = {0};
static int cb_lineno = 0;



// This specific function name is automatically called by the sanitizer before aborting
static int __attribute__((no_instrument_function))
imp_line_callback(void *v, uintptr_t pc, const char *filename, int lineno, const char *function);

// Global storage for the auto-init pattern detected at startup
uint64_t IMP_UNASSIGNED_PATTERN_64 = 0;
uint32_t IMP_UNASSIGNED_PATTERN_32 = 0;
uint16_t IMP_UNASSIGNED_PATTERN_16 = 0;
uint8_t  IMP_UNASSIGNED_PATTERN_8  = 0;

// At the top of your file, update the declaration:
void __attribute__ ((noinline,no_instrument_function)) _imp_monitor_internal(uintptr_t caller_pc);


#ifdef NEVER
// Define a macro that users call instead of the raw function:
#define _imp_monitor()                                             \
  do {                                                             \
    fflush(stdout);                                                \
    fprintf(stderr, "\nMONITOR ENTERED FROM IMP\n\n");             \
    _imp_monitor_internal((uintptr_t)__builtin_return_address(0)); \
  } while (0)
#endif

// Updated macro using local statement labels to anchor the exact call location
#define _imp_monitor()                                             \
  do {                                                             \
  __label__ __mon_loc; __mon_loc:;                               \
  fflush(stdout);                                                \
  fprintf(stderr, "\nMONITOR ENTERED FROM IMP\n\n");             \
  _imp_monitor_internal((uintptr_t)&&__mon_loc);                 \
  } while (0)


void __attribute__ ((noinline,no_instrument_function)) _imp_report_error(char *vs, void *caller_addr, char *reason) {

  fflush(stdout);

  // This could eventually be moved to the default signal handler, but for
  // now we'll skip raising a signal and report it directly.  No use yet of
  // libbacktrace, but just reporting the line and file is going to be
  // pretty helpful.
  
  char exe_path[1024];
  char addr_str[32];
  FILE *pipe;
  char func_line[512] = { '\0' };
  char loc_line[256];
  ssize_t len;
  char cmd[2048];

  // or could use global imp_argv[0] below:
  if ((len = readlink("/proc/self/exe", exe_path, sizeof(exe_path)-1)) == -1) { perror("readlink"); exit(EXIT_FAILURE); }
  exe_path[len] = '\0';

  sprintf(addr_str, "0x%lx", (unsigned long)caller_addr);

  snprintf(cmd, sizeof(cmd), "addr2line -e %s -f %s 2>&1 | grep -v \"addr2line: Dwarf Error: Can't find .debug_ranges section.\"", exe_path, addr_str);
  if (!(pipe = popen(cmd, "r"))) { perror("popen"); exit(EXIT_FAILURE); }

  char *rc=fgets(func_line, sizeof(func_line), pipe);(void)rc;
  if (fgets(loc_line, sizeof(loc_line), pipe)) {
    loc_line[strcspn(loc_line, "\n")] = 0;
    fprintf(stderr, "\nMONITOR ENTERED FROM IMP - %s %s\n\n", reason, vs);
  }
  pclose(pipe);

  _imp_monitor_internal((uintptr_t)caller_addr);
  
  exit(EXIT_FAILURE);
}

void __attribute__ ((noinline,no_instrument_function)) _imp_report_unass_error(char *vs, void *caller_addr) {
  _imp_report_error(vs, caller_addr, "UNASSIGNED VARIABLE");
}

void __attribute__ ((noinline,no_instrument_function)) _imp_report_unass_ptr_error(char *vs, void *caller_addr) {
  _imp_report_error(vs, caller_addr, "UNASSIGNED POINTER");
}

void __attribute__ ((noinline,no_instrument_function)) _imp_report_null_ptr_error(char *vs, void *caller_addr) {
  _imp_report_error(vs, caller_addr, "NULL POINTER");
}

// I'm trying to remember why I did not implement these as "inline".  It seems now it would be so much more efficient.
// Was it because I previously called __builtin_return_address(0) in this procedure rather than at the caller's level?
int __attribute__ ((noinline,no_instrument_function)) _imp_ucheck_int(uint32_t v, char *vs, void *caller_addr) {
  if ((uint32_t)v == IMP_UNASSIGNED_PATTERN_32) _imp_report_unass_error(vs,caller_addr);
  return v;
}
//#define _ui(v) _imp_ucheck_int((uint32_t)(v), #v, __builtin_return_address(0))

int __attribute__ ((noinline,no_instrument_function)) _imp_ucheck_longlongint(uint64_t v, char *vs, void *caller_addr) {
  if ((uint64_t)v == IMP_UNASSIGNED_PATTERN_64) _imp_report_unass_error(vs,caller_addr);
  return v;
}
//#define _ul(v) _imp_ucheck_longlongint((uint64_t)(v), #v, __builtin_return_address(0))

void * __attribute__ ((noinline,no_instrument_function)) _imp_ucheck_ptr(void *v, char *vs, void *caller_addr) {
  if ((uint32_t)v == 0)                         _imp_report_null_ptr_error (vs,caller_addr);
  if ((uint32_t)v == IMP_UNASSIGNED_PATTERN_32) _imp_report_unass_ptr_error(vs,caller_addr);
  return v;
}
//#define _up(ptr) ( (typeof(ptr)) _imp_ucheck_ptr(ptr,#ptr,__builtin_return_address(0)) )

// We would like to have avoided separate tests for float and double, because in imp everything
// is calculated at double and truncated when writing result to a float.  But it looks like we
// can't get away with that...

double __attribute__ ((noinline,no_instrument_function)) _imp_urcheck_double(double v, char *vs, void *caller_addr) {
  // binary representations of float and double as supported by gcc would be: 0xFEFEFEFE and 0xFEFEFEFEFEFEFEFE
  // and as implemented by Imp77 0x80808080 and 0x8080808080808080
  if (memcmp(&v, &IMP_UNASSIGNED_PATTERN_64, sizeof(double)) == 0) _imp_report_unass_error(vs,__builtin_return_address(0));
  // Hack to allow for float value ending up in a double!:
  if ((v == -0X1.FDFDFCP+126) || (v == -0X1.EFEFEFEFEFEFEP+1008)) _imp_report_unass_error(vs,__builtin_return_address(0));
  return v; // Pass assigned value through untouched!
}
//#define _ud(v) _imp_urcheck_double(v, #v, __builtin_return_address(0))

float __attribute__ ((noinline,no_instrument_function)) _imp_urcheck_float(float v, char *vs, void *caller_addr) {
  if (memcmp(&v, &IMP_UNASSIGNED_PATTERN_32, sizeof(float)) == 0) _imp_report_unass_error(vs,__builtin_return_address(0));
  return v; // Pass assigned value through untouched!
}
//#define _uf(v) _imp_urcheck_float(v, #v, __builtin_return_address(0))

//--
// --- REVISED VALUE CHECKING MACROS USING LOCAL LABELS ---

#define _ui(v) ({ \
  __label__ __chk_loc; __chk_loc:; \
  _imp_ucheck_int((uint32_t)(v), #v, (void*)&&__chk_loc); \
    })

#define _ul(v) ({ \
  __label__ __chk_loc; __chk_loc:; \
  _imp_ucheck_longlongint((uint64_t)(v), #v, (void*)&&__chk_loc); \
    })

#define _up(ptr) ({ \
  __label__ __chk_loc; __chk_loc:; \
  (typeof(ptr))_imp_ucheck_ptr(ptr, #ptr, (void*)&&__chk_loc); \
    })

#define _ud(v) ({ \
  __label__ __chk_loc; __chk_loc:; \
  _imp_urcheck_double(v, #v, (void*)&&__chk_loc); \
    })

#define _uf(v) ({ \
  __label__ __chk_loc; __chk_loc:; \
  _imp_urcheck_float(v, #v, (void*)&&__chk_loc); \
    })



// allow for multiple printf parameters wrapped in cstring()...
#define cstring(str) ({ volatile size_t maxlen = 4 * 256 + 4; char tmp[maxlen]; cstring_inner((str), tmp); })

char __attribute__ ((noinline,no_instrument_function)) *cstring_inner(char *impstring, char *local) {
  char ch, *s = local;
  *s++ = '"';
  while ((ch = *impstring++) != '\0') switch (ch) {
    case '\n': *s++ = '\\'; *s++ = 'n';  break;
    case '\t': *s++ = '\\'; *s++ = 't';  break;
    case '\r': *s++ = '\\'; *s++ = 'r';  break;
    case '\\': *s++ = '\\'; *s++ = '\\'; break;
    case '"':  *s++ = '\\'; *s++ = '"';  break;
    default: if (ch >= 32 && ch <= 126) *s++ = ch; else s += sprintf(s, "\\x%02X", (unsigned char)ch);
  }
  *s++ = '"'; *s = '\0';
  return local;
}

void __attribute__ ((noinline,no_instrument_function)) detect_unassigned_pattern(void) {
  volatile struct { uint64_t pattern; } dummy;
  if (dummy.pattern != 0 && (dummy.pattern >> 32) == (dummy.pattern & 0xFFFFFFFF) &&
      ((dummy.pattern >> 16) & 0xFFFF) == (dummy.pattern & 0xFFFF) &&
      ((dummy.pattern >> 8) & 0xFF) == (dummy.pattern & 0xFF)) {
    IMP_UNASSIGNED_PATTERN_64 = dummy.pattern;
  } else {
    IMP_UNASSIGNED_PATTERN_64 = 0x8080808080808080;
  }
  IMP_UNASSIGNED_PATTERN_32 = IMP_UNASSIGNED_PATTERN_64 & 0xFFFFFFFF;
  IMP_UNASSIGNED_PATTERN_16 = IMP_UNASSIGNED_PATTERN_32 &     0xFFFF;
  IMP_UNASSIGNED_PATTERN_8  = IMP_UNASSIGNED_PATTERN_16 &       0xFF;
  //fprintf(stderr, "Using 0x%08lx as the unassigned pattern\n", (long int)IMP_UNASSIGNED_PATTERN_64);
}

const char* __attribute__ ((noinline,no_instrument_function)) get_signal_macro_name(int sig) {
  // Array size based on the maximum possible signal number on your platform
  static const char* const sig_names[_NSIG] = {
    [SIGINT]  = "SIGINT",
    [SIGILL]  = "SIGILL",
    [SIGABRT] = "SIGABRT",
    [SIGFPE]  = "SIGFPE",
    [SIGSEGV] = "SIGSEGV",
    [SIGTERM] = "SIGTERM",
    [SIGPIPE] = "SIGPIPE",
    [SIGQUIT] = "SIGQUIT",
#ifdef SIGSYS
    [SIGSYS]  = "SIGSYS",
#endif
  };

  if (sig >= 0 && sig < _NSIG && sig_names[sig] != NULL) {
    return sig_names[sig];
  }
  return "SIGNAL";
}


void __attribute__ ((noinline,no_instrument_function)) _imp_signal_handler(int sig, siginfo_t *info, void *ucontext) {
  signal(sig, SIG_DFL);

  fflush(stdout);
  fprintf(stderr, "MONITOR ENTERED FROM IMP - %s %d", get_signal_macro_name(sig), sig);
  
  if (info != NULL) {
    fprintf(stderr, " (Code %d:", info->si_code);
    if (sig == SIGILL)       fprintf(stderr, " %s)", get_sigill_reason(info->si_code));
    else if (sig == SIGFPE)  fprintf(stderr, " %s)", get_sigfpe_reason(info->si_code));
    else if (sig == SIGSEGV) fprintf(stderr, " %s)", get_sigsegv_reason(info->si_code));
    else                     fprintf(stderr, " %s)", strsignal(sig));
  } else fprintf(stderr, " (%s)", strsignal(sig));

  uintptr_t fault_pc = 0;
  if (info != NULL && (sig == SIGFPE || sig == SIGSEGV || sig == SIGBUS || sig == SIGILL)) {
    fault_pc = (uintptr_t)info->si_addr; // Pure hardware PC reference
  }

  // If it's a software signal (like SIGABRT), use libbacktrace to find the true user code PC
  if (!fault_pc && global_bt_state) {
    dynamic_abort_pc = 0;
    backtrace_full(global_bt_state, 0, find_user_pc_callback, NULL, NULL);
    fault_pc = dynamic_abort_pc;
  }

  // Final emergency fallback
  if (!fault_pc) {
    fault_pc = (uintptr_t)__builtin_return_address(0);
  }
  fprintf(stderr, "\n\n");
  
  _imp_monitor_internal(fault_pc);
  exit(128 + sig);
}


#ifdef NEVER

void __attribute__ ((noinline,no_instrument_function)) _imp_signal_handler(int sig, siginfo_t *info, void *ucontext) {
  signal(sig, SIG_DFL);

  fflush(stdout);
  fprintf(stderr, "\nMONITOR ENTERED FROM %s", get_signal_macro_name(sig));
  if (info != NULL) {
    fprintf(stderr, " %d %d", info->si_signo, info->si_code);
  }
  fprintf(stderr, ": %s\n\n", strsignal(sig));

  uintptr_t fault_pc = 0;
  if (info != NULL && (sig == SIGFPE || sig == SIGSEGV || sig == SIGBUS || sig == SIGILL)) {
    fault_pc = (uintptr_t)info->si_addr; // Pure hardware PC reference
  }

  // If it's a software signal (like SIGABRT), use libbacktrace to find the true user code PC
  if (!fault_pc && global_bt_state) {
    dynamic_abort_pc = 0;
    // Walk the physical stack frames safely across any CPU architecture
    backtrace_full(global_bt_state, 0, find_user_pc_callback, NULL, NULL);
    fault_pc = dynamic_abort_pc;
  }

  // Final emergency fallback
  if (!fault_pc) {
    fault_pc = (uintptr_t)__builtin_return_address(0);
  }

  _imp_monitor_internal(fault_pc);
  exit(128 + sig);
}
#endif


#ifdef NEVER
void __attribute__ ((noinline,no_instrument_function)) _imp_signal_handler(int sig, siginfo_t *info, void *ucontext) {
  signal(sig, SIG_DFL);

  fflush(stdout);
  fprintf(stderr, "\nMONITOR ENTERED FROM %s", get_signal_macro_name(sig));
  if (info != NULL) {
    fprintf(stderr, " %d %d", info->si_signo, info->si_code);
  }
  fprintf(stderr, ": %s\n\n", strsignal(sig));

  uintptr_t fault_pc = 0;
  if (info != NULL && (sig == SIGFPE || sig == SIGSEGV || sig == SIGBUS || sig == SIGILL)) {
    fault_pc = (uintptr_t)info->si_addr; // Pure hardware PC reference
  }

  if (!fault_pc) {
    fault_pc = (uintptr_t)__builtin_return_address(0);
  }

  _imp_monitor_internal(fault_pc);
  exit(128 + sig);
}
#endif

void __attribute__ ((noinline,no_instrument_function)) __ubsan_on_report(void) {
  fflush(stdout);
  fprintf(stderr, "\nMONITOR ENTERED FROM UBSAN\n\n");

  _imp_monitor_internal((uintptr_t)__builtin_return_address(0));
  exit(EXIT_FAILURE);
}

void __attribute__ ((noinline,no_instrument_function)) init_imp_runtime(const char *filename) {
  static int init = 0;
  if (init) return;
  init = 1;
  
  feenableexcept(FE_INVALID | FE_DIVBYZERO);

  global_bt_state = backtrace_create_state(filename, 0, NULL, NULL);

  struct sigaction sa;
  sa.sa_sigaction = _imp_signal_handler;
  sa.sa_flags = SA_SIGINFO;
  sigemptyset(&sa.sa_mask);

  sigaction(SIGFPE,  &sa, NULL);
  sigaction(SIGSEGV, &sa, NULL);
  sigaction(SIGBUS,  &sa, NULL);
  sigaction(SIGILL,  &sa, NULL);
  sigaction(SIGTRAP, &sa, NULL);
  sigaction(SIGABRT, &sa, NULL);

  detect_unassigned_pattern();
}

static int __attribute__((no_instrument_function)) 
imp_line_callback(void *v, uintptr_t pc, const char *filename, int lineno, const char *function) {
  if (filename || lineno) {
    const char *target_fn = (const char *)v;
    
    // If we are filtering for a specific routine frame, verify the debug symbol matches
    if (target_fn && function && strcmp(function, target_fn) != 0) {
      return 0; // Keep walking up the DWARF tree to find the correct enclosing scope
    }

    const char *basename = strrchr(filename, '/');
    if (basename) filename = basename + 1;

    strncpy(cb_filename, filename ? filename : "unknown", sizeof(cb_filename) - 1);
    cb_filename[sizeof(cb_filename) - 1] = '\0';
    cb_lineno = lineno;
    
    return 1; // Found the precise line matching our current routine! Stop walking.
  }
  return 0;
}


// Native, safe line extractor that reads the original source file on-demand
void __attribute__ ((noinline,no_instrument_function)) print_source_line_preview(const char *filename, int target_line) {
  if (!filename || target_line <= 0) return;

  FILE *file = fopen(filename, "r");
  if (!file) {
    // Fail silently if source file isn't present in current directory path
    return; 
  }

  char line_buffer[1024];
  int current_line = 1;
    
  // Skip down the file stream until the matching index line is reached
  while (fgets(line_buffer, sizeof(line_buffer), file)) {
    if (current_line == target_line) {
      // Strip off any trailing newline markers to keep formatting controlled
      line_buffer[strcspn(line_buffer, "\n")] = '\0';
            
      // Print out an illuminated, structured statement window
      fprintf(stderr, "\"%s\":%d   %s\n\n", filename, target_line, line_buffer);
      break;
    }
    current_line++;
  }
  fclose(file);
}

void __attribute__ ((noinline,no_instrument_function)) _imp_monitor_internal(uintptr_t caller_pc) {
  FrameContext *curr = current_stream_frame;
  int is_innermost_frame = 1;

  while (curr != NULL) {
    cb_filename[0] = '\0';
    cb_lineno = 0;

    if (global_bt_state) {
      if (is_innermost_frame && caller_pc) {
        backtrace_pcinfo(global_bt_state, caller_pc, imp_line_callback, NULL, (void *)curr->fn_name);
      }
      
      if (cb_lineno == 0 && curr->pc_addr) {
        backtrace_pcinfo(global_bt_state, curr->pc_addr, imp_line_callback, NULL, (void *)curr->fn_name);
      }
    }

    const char *block_name = (strcmp(curr->fn_name, "main") == 0) ? "%begin/%endofprogram" : curr->fn_name;

    if (is_innermost_frame && (cb_filename != NULL) && (cb_lineno > 0)) print_source_line_preview(cb_filename, cb_lineno);

    if (cb_lineno > 0) {
      fprintf(stderr, "ENTERED FROM LINE %d OF %s", cb_lineno, block_name);
    } else {
      fprintf(stderr, "ENTERED FROM %s", block_name);
    }

    if (curr->print_locals != NULL) {
      curr->print_locals();
    }
    fprintf(stderr, "\n");

    is_innermost_frame = 0; 
    curr = curr->parent;

  }
}

#ifdef NEVER
void __attribute__ ((noinline,no_instrument_function)) _imp_monitor_internal(uintptr_t caller_pc) {
  FrameContext *curr = current_stream_frame;
  int is_innermost_frame = 1;

  while (curr != NULL) {
    cb_filename[0] = '\0';
    cb_lineno = 0;

    if (global_bt_state) {
      if (is_innermost_frame && caller_pc) {
        // FIX: Pass curr->fn_name instead of NULL. This ensures that for unnested test blocks
        // like test_explicit_abort, libbacktrace will pass by the initial prologue functions 
        // and find the true caller line context mapped inside that matching runtime block.
        backtrace_pcinfo(global_bt_state, caller_pc, imp_line_callback, NULL, (void *)curr->fn_name);
      }
      
      if (cb_lineno == 0 && curr->pc_addr) {
        backtrace_pcinfo(global_bt_state, curr->pc_addr, imp_line_callback, NULL, (void *)curr->fn_name);
      }
    }

    const char *block_name = (strcmp(curr->fn_name, "main") == 0) ? "%begin/%endofprogram" : curr->fn_name;

    if (is_innermost_frame && (cb_filename != NULL) && (cb_lineno > 0)) print_source_line_preview(cb_filename, cb_lineno);

    if (cb_lineno > 0) {
      fprintf(stderr, "ENTERED FROM LINE %d OF %s", cb_lineno, block_name);
    } else {
      fprintf(stderr, "ENTERED FROM %s", block_name);
    }

    if (curr->print_locals != NULL) {
      curr->print_locals();
    }
    fprintf(stderr, "\n");

    is_innermost_frame = 0; 
    curr = curr->parent;
  }
}
#endif

int main(int argc, char **argv) {
  __label__ __main_trace_loc;
  __main_trace_loc:;
  auto void main_backtrace(void);
  init_imp_runtime(argc > 0 ? argv[0] : "monitor");
  FrameContext main_frame = {"main", main_backtrace, (uintptr_t) &&__main_trace_loc, NULL};
  current_stream_frame = &main_frame;

  
  void test_div_zero(void) {
    INSERT_BEFORE(test_div_zero);
    
    int local_a = 100;
    int local_b = 0;
    printf("[Test 1] Attempting Integer Division by Zero...\n");
    int result = local_a / local_b;
    printf("Result: %d\n", result);
    
    INSERT_AFTER(test_div_zero, "():\n  LOCALA = %d\n  LOCALB = %d\n  RESULT = %d\n", local_a, local_b, result);
  }

  void test_unassigned_pointer(void) {
    INSERT_BEFORE(test_unassigned_pointer);
    
    int *unass_ptr; memset(&unass_ptr, IMP_UNASSIGNED_PATTERN_8, sizeof(int *));
    int offset_context = 77;
    printf("[Test 2] Reading Unassigned Pointer (val: %08x)...\n", (uint32_t)unass_ptr);
    int value = *_up(unass_ptr);
    printf("Value: %d, Context: %d\n", value, offset_context);

    INSERT_AFTER(test_unassigned_pointer, "():\n  UNASSIGNEDPTR = %p\n  OFFSETCONTEXT = %d\n  VALUE = %d\n", unass_ptr, offset_context, value);
  }

  void test_unassigned_float(void) {
    INSERT_BEFORE(test_unassigned_float);
    
    float unassigned_real; memset(&unassigned_real, IMP_UNASSIGNED_PATTERN_8, sizeof(float));
    float multiplier = 2.5f;
    printf("[Test 3] Operating on Unassigned Float (sNaN)...\n");
    float result = _uf(unassigned_real) * _uf(multiplier);
    printf("Result: %f\n", result);
    
    INSERT_AFTER(test_unassigned_float, "():\n  UNASSIGNEDREAL = %f\n  MULTIPLIER = %f\n  RESULT = %f\n", unassigned_real,
                 multiplier, result);
  }

  void test_integer_overflow(void) {
    INSERT_BEFORE(test_integer_overflow);
    
    int max_val = INT_MAX;
    int increment = 1;
    printf("[Test 4] Triggering Signed Integer Overflow (%d + %d)...\n", max_val, increment);
    int overflowed = max_val + increment;
    printf("Result: %d\n", overflowed);
    
    INSERT_AFTER(test_integer_overflow, "():\n  MAXVAL = %d\n  INCREMENT = %d\n  OVERFLOWED = %d\n", max_val, increment,
                 overflowed);
  }

  void test_stack_smash(void) {
    INSERT_BEFORE(test_stack_smash);
    
    char small_buffer[8];
    const char *large_input = "THIS_STRING_IS_WAY_TOO_LONG_FOR_THE_DESTINATION_BUFFER";
    printf("[Test 5] Smashing Stack Frame...\n");
    strcpy(small_buffer, large_input);
    
    INSERT_AFTER(test_stack_smash, "():\n  \n");
  }

  void test_invalid_shift(void) {
    INSERT_BEFORE(test_invalid_shift);
    
    int bitmask = 1;
    int shift_amount = 64;
    printf("[Test 6] Executing Invalid Bitshift (%d << %d)...\n", bitmask, shift_amount);
    int shifted = bitmask << shift_amount;
    printf("Result: %d\n", shifted);
    
    INSERT_AFTER(test_invalid_shift, "():\n  BITMASK = %d\n  SHIFTAMOUNT = %d\n  SHIFTED = %d\n", bitmask, shift_amount, shifted);
  }

  void test_float_cast_overflow(void) {
    INSERT_BEFORE(test_float_cast_overflow);
    
    double huge_val = 1e18;
    printf("[Test 7] Casting Overflowing Float to Int (%e)...\n", huge_val);
    int converted = (int)huge_val;
    printf("Result: %d\n", converted);

    INSERT_AFTER(test_float_cast_overflow, "():\n  HUGEVAL = %f\n  CONVERTED = %d\n", huge_val, converted);
  }

  void test_explicit_abort(void) {
    INSERT_BEFORE(test_explicit_abort);
    
    int event_event = 8;
    const char *error_msg = "Array index of FRED(0) out of bounds for %integer %array fred(1:10)";
    
    printf("[Test 8] %%signal %d - %s\n", event_event, error_msg);
    abort(); // or raise SIGUSR?

    INSERT_AFTER(test_explicit_abort, "():\n  IMPERRORCODE = %d\n  ERRORMSG=%s\n", event_event, cstring(error_msg));
  }

  void test_unassigned_integer(void) {
    INSERT_BEFORE(test_unassigned_integer);
    
    int unassigned_integer; memset(&unassigned_integer, IMP_UNASSIGNED_PATTERN_8, sizeof(int));
    int multiplier = 3;
    printf("[Test 9] Operating on Unassigned Integer...\n");
    int result = _ui(unassigned_integer) * _ui(multiplier);
    printf("Result: %d\n", result);
    
    INSERT_AFTER(test_unassigned_integer, "():\n  UNASSIGNEDINTEGER = 0x%08X\n  MULTIPLIER = %d\n  RESULT = %d\n", unassigned_integer, multiplier, result);
  }

  void test_null_pointer(void) {
    INSERT_BEFORE(test_null_pointer);
    
    int *null_ptr; memset(&null_ptr, 0, sizeof(int *));
    int offset_context = 77;
    printf("[Test 10] Reading NULL Pointer (val: %08x)...\n", (uint32_t)null_ptr);
    int value = *_up(null_ptr);
    printf("Value: %d, Context: %d\n", value, offset_context);

    INSERT_AFTER(test_null_pointer, "():\n  NULLPTR = %p\n  OFFSETCONTEXT = %d\n  VALUE = %d\n", null_ptr, offset_context, value);
  }

  void PROCA(int depth) {
    __label__ __trace_loc_a;
    auto void PROCA_backtrace(void);
    __trace_loc_a:;
    FrameContext frame = {"PROCA", PROCA_backtrace, (uintptr_t) && __trace_loc_a, current_stream_frame};
    current_stream_frame = &frame;
    
    void PROCB(int depth) {
      __label__ __trace_loc_b;
      auto void PROCB_backtrace(void);
      __trace_loc_b:;
      FrameContext frame = {"PROCB", PROCB_backtrace, (uintptr_t) && __trace_loc_b, current_stream_frame};
      current_stream_frame = &frame;
      
      float BTHRESHOLD = 0.5f * depth;
      int BID = 999 + depth;
      printf("Executing PROCB (Depth %d)...\n", depth);
      if (depth == 2) {
        printf("Running Test Procedure #%d...\n", test_num);
        switch (test_num) {
          case 0:
            printf("Calling %%MONITOR from Imp and then resuming execution...\n");
            _imp_monitor();
            break;
          case 1:
            test_div_zero();
            break;
          case 2:
            test_unassigned_pointer();
            break;
          case 3:
            test_unassigned_float();
            break;
          case 4:
            test_integer_overflow();
            break;
          case 5:
            test_stack_smash();
            break;
          case 6:
            test_invalid_shift();
            break;
          case 7:
            test_float_cast_overflow();
            break;
          case 8:
            test_explicit_abort();
            break;
          case 9:
            test_unassigned_integer();
            break;
          case 10:
            test_null_pointer();
            break;
        }
      }
      if (depth <= 4) PROCA(depth + 1);
      printf("Back in PROCB (Depth %d).\n", depth);

      current_stream_frame = frame.parent;
      void PROCB_backtrace(void) {
        fprintf(stderr, "(DEPTH=%d):\n  BTHRESHOLD = %f\n  BID = %d\n", depth, BTHRESHOLD, BID);
      }
    }
    
    int AMETRIC = 100 * depth;
    const char *ASTATUS = "Active in A";
    printf("Executing PROCA (Depth %d)...\n", depth);
    PROCB(depth);
    printf("Back in PROCA (Depth %d).\n", depth);
    
    current_stream_frame = frame.parent;
    void PROCA_backtrace(void) {
      fprintf(stderr, "(DEPTH=%d):\n  AMETRIC = %d\n  ASTATUS = %s\n", depth, AMETRIC, cstring(ASTATUS));
    }
  }

  void print_usage(const char *prog_name) {
    printf("Usage: %s <test_number 1..11>\n", prog_name);
    printf("  0: Explicit call to %%MONITOR from Imp (then resumed computation)\n");
    printf("  1: Integer Division by Zero (SIGFPE)\n");
    printf("  2: Unassigned pointer (i2c/perms test)\n");
    printf("  3: Unassigned Float Access / sNaN (SIGFPE)\n");
    printf("  4: Signed Integer Overflow (SIGILL via -ftrapv)\n");
    printf("  5: Stack Buffer Overflow (SIGABRT via -fstack-protector)\n");
    printf("  6: Invalid Bitshift (SIGILL via UBSan)\n");
    printf("  7: Float Cast Overflow (SIGILL via UBSan)\n");
    printf("  8: Explicit Abort / Imp %%signal 0 (SIGABRT)\n");
    printf("  9: Unassigned Integer (i2c/perms test)\n");
    printf(" 10: NULL pointer (i2c/perms test or SIGSEGV)\n");
    printf(" 11: An error forced at the top-level %%begin/%%endofprogram block\n");
  }
  
  int MAIN_RUN_COUNT = 1;
  const char *MAIN_ENV = "Consider this string random %begin/%endofprogram data...";

  if (argc < 2) {
    print_usage(argv[0]);
    return 1;
  }
  
  test_num = atoi(argv[1]);
  if (test_num < 0 || test_num > 10) {
    if (test_num == 11) {
      // Caught at the top level of %begin/%endofprogram (i.e. C's main()) which was not the case with the first draft...
      test_num = test_num / zero; 
    }

    printf("Error: Invalid test selection '%s'. Must be between 0 and 11.\n\n", argv[1]);
    print_usage(argv[0]);
    return 1;
  }
  
  printf("Starting Main Program Execution Loop...\n");
  PROCA(1);
  printf("Main execution block finished cleanly.\n");

  void main_backtrace(void) {
    fprintf(stderr, "(ARGC=%d, ARGV=%p):\n  MAINRUNCOUNT = %d\n  MAINENV = %s\n  TESTNUM = %d\n", argc, argv, MAIN_RUN_COUNT, cstring((char*)MAIN_ENV), test_num);
  }

  return 0;
}
