/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8                                :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney                              â
â                                                                              â
â Permission to use, copy, modify, and/or distribute this software for         â
â any purpose with or without fee is hereby granted, provided that the         â
â above copyright notice and this permission notice appear in all copies.      â
â                                                                              â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL                â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED                â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE             â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL         â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR        â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER               â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR             â
â PERFORMANCE OF THIS SOFTWARE.                                                â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/fmt/fmt.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/log/color.internal.h"
#include "libc/log/gdb.h"
#include "libc/log/internal.h"
#include "libc/log/log.h"
#include "libc/nexgen32e/stackframe.h"
#include "libc/nexgen32e/vendor.internal.h"
#include "libc/paths.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/symbols.internal.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/fileno.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/w.h"

/**
 * Launches GDB debugger GUI for current process.
 *
 * This function abstracts the toilsome details of configuring the best
 * possible UX for debugging your app, for varying levels of available
 * information, on most of the various platforms.
 *
 * Before calling this function, consider placing ShowCrashReports() in
 * your main function and calling DebugBreak() wherever you want; it's
 * safer. Also note the "GDB" environment variable can be set to empty
 * string, as a fail-safe for disabling this behavior.
 *
 * @param continuetoaddr can be a code address, 0, or -1 for auto
 * @return gdb pid if continuing, 0 if detached, or -1 w/ errno
 * @note this is called via eponymous spinlock macro wrapper
 */
relegated int(AttachDebugger)(intptr_t continuetoaddr) {
  int pid, ttyfd;
  struct StackFrame *bp;
  char pidstr[11], breakcmd[40];
  const char *se, *elf, *gdb, *rewind, *layout;
  __restore_tty();
  if (IsGenuineBlink() || !(gdb = GetGdbPath()) || !isatty(0) || !isatty(1) ||
      (ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC)) == -1) {
    return -1;
  }
  ksnprintf(pidstr, sizeof(pidstr), "%u", getpid());
  layout = "layout asm";
  if ((elf = FindDebugBinary())) {
    se = "-se";
    if (fileexists(__FILE__)) layout = "layout src";
  } else {
    se = "-q";
    elf = "-q";
  }
  if (continuetoaddr) {
    if (continuetoaddr == -1) {
      bp = __builtin_frame_address(0);
      continuetoaddr = bp->addr;
    }
    rewind = "-ex";
    ksnprintf(breakcmd, sizeof(breakcmd), "%s *%#p", "break", continuetoaddr);
  } else {
    rewind = NULL;
    breakcmd[0] = '\0';
  }
  if (!(pid = fork())) {
    dup2(ttyfd, 0);
    dup2(ttyfd, 1);
    execv(gdb, (char *const[]){
                   "gdb",    "--tui",
                   "-p",     pidstr,
                   se,       elf,
                   "-ex",    "set osabi GNU/Linux",
                   "-ex",    "set complaints 0",
                   "-ex",    "set confirm off",
                   "-ex",    layout,
                   "-ex",    "layout reg",
                   "-ex",    "set var g_gdbsync = 1",
                   "-q",     rewind,
                   breakcmd, "-ex",
                   "c",      NULL,
               });
    abort();
  }
  return pid;
}
