debug.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package shared
  2. import (
  3. "fmt"
  4. "os"
  5. "os/exec"
  6. "strings"
  7. "syscall"
  8. )
  9. var (
  10. isDebugging bool
  11. )
  12. // Finds the Delve binary to use. Either uses the SOONG_DELVE_PATH environment
  13. // variable or if that is unset, looks at $PATH.
  14. func ResolveDelveBinary() string {
  15. result := os.Getenv("SOONG_DELVE_PATH")
  16. if result == "" {
  17. result, _ = exec.LookPath("dlv")
  18. }
  19. return result
  20. }
  21. // Returns whether the current process is running under Delve due to
  22. // ReexecWithDelveMaybe().
  23. func IsDebugging() bool {
  24. return isDebugging
  25. }
  26. // Re-executes the binary in question under the control of Delve when
  27. // delveListen is not the empty string. delvePath gives the path to the Delve.
  28. func ReexecWithDelveMaybe(delveListen, delvePath string) {
  29. isDebugging = os.Getenv("SOONG_DELVE_REEXECUTED") == "true"
  30. if isDebugging || delveListen == "" {
  31. return
  32. }
  33. if delvePath == "" {
  34. fmt.Fprintln(os.Stderr, "Delve debugging requested but failed to find dlv")
  35. os.Exit(1)
  36. }
  37. soongDelveEnv := []string{}
  38. for _, env := range os.Environ() {
  39. idx := strings.IndexRune(env, '=')
  40. if idx != -1 {
  41. soongDelveEnv = append(soongDelveEnv, env)
  42. }
  43. }
  44. soongDelveEnv = append(soongDelveEnv, "SOONG_DELVE_REEXECUTED=true")
  45. dlvArgv := []string{
  46. delvePath,
  47. "--listen=:" + delveListen,
  48. "--headless=true",
  49. "--api-version=2",
  50. "exec",
  51. os.Args[0],
  52. "--",
  53. }
  54. dlvArgv = append(dlvArgv, os.Args[1:]...)
  55. syscall.Exec(delvePath, dlvArgv, soongDelveEnv)
  56. fmt.Fprintln(os.Stderr, "exec() failed while trying to reexec with Delve")
  57. os.Exit(1)
  58. }