1 // xds-gdb: a wrapper on gdb tool for X(cross) Development System.
18 "github.com/Sirupsen/logrus"
19 "github.com/codegangsta/cli"
20 common "github.com/iotbzh/xds-common/golib"
21 "github.com/joho/godotenv"
24 var appAuthors = []cli.Author{
25 cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
28 // AppName name of this application
29 var AppName = "xds-gdb"
31 // AppVersion Version of this application
33 var AppVersion = "?.?.?"
35 // AppSubVersion is the git tag id added to version string
36 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
38 var AppSubVersion = "unknown-dev"
41 var log = logrus.New()
42 var earlyLog = []string{}
44 // Application details
46 appCopyright = "Apache-2.0"
47 defaultLogLevel = "warning"
51 type exitResult struct {
56 // EnvVar - Environment variables used by application
63 // exitError terminates this program with the specified error
64 func exitError(code syscall.Errno, f string, a ...interface{}) {
65 err := fmt.Sprintf(f, a...)
66 fmt.Fprintf(os.Stderr, err+"\n")
72 var uri, prjID, rPath, logLevel, logFile, sdkid, confFile, gdbNative string
76 uri = "localhost:8000"
77 logLevel = defaultLogLevel
79 // Create a new App instance
82 app.Usage = "wrapper on gdb for X(cross) Development System."
83 app.Version = AppVersion + " (" + AppSubVersion + ")"
84 app.Authors = appAuthors
85 app.Copyright = appCopyright
86 app.Metadata = make(map[string]interface{})
87 app.Metadata["version"] = AppVersion
88 app.Metadata["git-tag"] = AppSubVersion
89 app.Metadata["logger"] = log
91 app.Flags = []cli.Flag{
94 Usage: "list existing xds projects",
95 Destination: &listProject,
99 appEnvVars := []EnvVar{
102 Usage: "env config file to source on startup",
103 Destination: &confFile,
106 Name: "XDS_LOGLEVEL",
107 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
108 Destination: &logLevel,
112 Usage: "logging file",
113 Destination: &logFile,
116 Name: "XDS_NATIVE_GDB",
117 Usage: "use native gdb instead of remote XDS server",
118 Destination: &gdbNative,
121 Name: "XDS_PROJECT_ID",
122 Usage: "project ID you want to build (mandatory variable)",
127 Usage: "relative path into project",
132 Usage: "Cross Sdk ID to use to build project",
136 Name: "XDS_SERVER_URL",
137 Usage: "remote XDS server url",
142 // Process gdb arguments
143 args := make([]string, len(os.Args))
145 gdbArgs := make([]string, len(os.Args))
147 // Split xds-xxx options from gdb options
148 copy(gdbArgs, os.Args[1:])
149 for idx, a := range os.Args[1:] {
150 // Specific case to print help or version of xds-gdb
152 case "--help", "-h", "--version", "-v":
156 // Detect skip option (IOW '--') to split arguments
157 copy(args, os.Args[0:idx+1])
158 copy(gdbArgs, os.Args[idx+2:])
164 // Parse gdb arguments to detect:
165 // --tty option: used for inferior/ tty of debugged program
166 // -x/--command option: XDS env vars may be set within gdb command file
169 for idx, a := range gdbArgs {
171 case strings.HasPrefix(a, "--tty="):
172 clientPty = a[len("--tty="):]
176 case strings.HasPrefix(a, "-tty"):
177 clientPty = gdbArgs[idx+1]
181 case strings.HasPrefix(a, "--command="):
182 gdbCmdFile = a[len("--command="):]
184 case a == "--command":
185 case strings.HasPrefix(a, "-x"):
186 gdbCmdFile = gdbArgs[idx+1]
190 // Source config env file
191 // (we cannot use confFile var because env variables setting is just after)
192 envMap, confFile, err := loadConfigEnvFile(os.Getenv("XDS_CONFIG"), gdbCmdFile)
194 exitError(syscall.ENOENT, err.Error())
197 // Managed env vars and create help
198 dynDesc := "\nENVIRONMENT VARIABLES:"
199 for _, ev := range appEnvVars {
200 dynDesc += fmt.Sprintf("\n %s \t\t %s", ev.Name, ev.Usage)
201 if evVal, evExist := os.LookupEnv(ev.Name); evExist && ev.Destination != nil {
202 *ev.Destination = evVal
205 app.Description = "gdb wrapper for X(cross) Development System\n"
206 app.Description += "\n"
207 app.Description += " Two debugging models are supported:\n"
208 app.Description += " - xds remote debugging requiring an XDS server and allowing cross debug\n"
209 app.Description += " - native debugging\n"
210 app.Description += " By default xds remote debug is used and you need to define XDS_NATIVE_GDB to\n"
211 app.Description += " use native gdb debug mode instead.\n"
212 app.Description += "\n"
213 app.Description += " xds-gdb configuration (see variables list below) can be set using:\n"
214 app.Description += " - a config file (XDS_CONFIG)\n"
215 app.Description += " - or environment variables\n"
216 app.Description += " - or by setting variables within gdb ini file (commented line including :XDS-ENV: tag)\n"
217 app.Description += " Example of gdb ini file where we define project and sdk ID:\n"
218 app.Description += " # :XDS-ENV: XDS_PROJECT_ID=IW7B4EE-DBY4Z74_myProject\n"
219 app.Description += " # :XDS-ENV: XDS_SDK_ID=poky-agl_aarch64_3.99.1+snapshot\n"
220 app.Description += "\n"
221 app.Description += dynDesc + "\n"
224 app.Action = func(ctx *cli.Context) error {
226 curDir, _ := os.Getwd()
228 // Set logger level, formatter and log file
229 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
230 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", logLevel)
231 return cli.NewExitError(msg, int(syscall.EINVAL))
233 log.Formatter = &logrus.TextFormatter{}
235 // Always log into a file
237 logFile = "/tmp/xds-gdb.log"
239 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
241 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
242 return cli.NewExitError(msgErr, int(syscall.EPERM))
246 // Build env variables
248 for k, v := range envMap {
249 env = append(env, k+"="+v)
252 // Create cross or native gdb interface
255 gdb = NewGdbNative(log, gdbArgs, env)
257 gdb = NewGdbXds(log, gdbArgs, env)
258 gdb.SetConfig("uri", uri)
259 gdb.SetConfig("prjID", prjID)
260 gdb.SetConfig("sdkID", sdkid)
261 gdb.SetConfig("rPath", rPath)
262 gdb.SetConfig("listProject", listProject)
266 for _, msg := range earlyLog {
271 log.Infof("Original arguments: %v", os.Args)
272 log.Infof("Current directory : %v", curDir)
273 log.Infof("Use confFile : '%s'", confFile)
274 log.Infof("Execute : /exec %v %v", gdb.Cmd(), gdb.Args())
276 // Properly report invalid init file error
277 gdbCommandFileError := ""
278 for i, a := range gdbArgs {
280 gdbCommandFileError = gdbArgs[i+1] + ": No such file or directory."
282 } else if strings.HasPrefix(a, "--command=") {
283 gdbCommandFileError = strings.TrimLeft(a, "--command=") + ": No such file or directory."
287 log.Infof("Add detection of error: <%s>", gdbCommandFileError)
289 // Init gdb subprocess management
290 if code, err := gdb.Init(); err != nil {
291 return cli.NewExitError(err.Error(), code)
294 exitChan := make(chan exitResult, 1)
296 gdb.OnError(func(err error) {
297 fmt.Println("ERROR: ", err.Error())
300 gdb.OnDisconnect(func(err error) {
301 fmt.Println("Disconnection: ", err.Error())
302 exitChan <- exitResult{err, int(syscall.ESHUTDOWN)}
305 gdb.Read(func(timestamp, stdout, stderr string) {
307 fmt.Printf("%s", stdout)
308 log.Debugf("Recv OUT: <%s>", stdout)
311 fmt.Fprintf(os.Stderr, "%s", stderr)
312 log.Debugf("Recv ERR: <%s>", stderr)
315 // Correctly report error about init file
316 if gdbCommandFileError != "" && strings.Contains(stdout, gdbCommandFileError) {
317 fmt.Fprintf(os.Stderr, "ERROR: "+gdbCommandFileError)
318 log.Errorf("ERROR: " + gdbCommandFileError)
319 if err := gdb.SendSignal(syscall.SIGTERM); err != nil {
320 log.Errorf("Error while sending signal: %s", err.Error())
322 exitChan <- exitResult{err, int(syscall.ENOENT)}
326 gdb.OnExit(func(code int, err error) {
327 exitChan <- exitResult{err, code}
330 // Handle client tty / pts
332 log.Infoln("Client tty detected: %v\n", clientPty)
334 cpFd, err := os.OpenFile(clientPty, os.O_RDWR, 0)
336 return cli.NewExitError(err.Error(), int(syscall.EPERM))
341 /* XXX TODO - implement stdin to send data to debugged program
343 reader := bufio.NewReader(cpFd)
344 sc := bufio.NewScanner(reader)
347 iosk.Emit(apiv1.ExecInferiorInEvent, data+"\n")
348 log.Debugf("Inferior IN: <%v>", data)
351 log.Warnf("Inferior Stdin scanner exit, close stdin (err=%v)", sc.Err())
357 gdb.InferiorRead(func(timestamp, stdout, stderr string) {
359 fmt.Fprintf(cpFd, "%s", stdout)
360 log.Debugf("Inferior OUT: <%s>", stdout)
363 fmt.Fprintf(cpFd, "%s", stderr)
364 log.Debugf("Inferior ERR: <%s>", stderr)
369 // Allow to overwrite some gdb commands
370 var overwriteMap = make(map[string]string)
371 if overEnv, exist := os.LookupEnv("XDS_OVERWRITE_COMMANDS"); exist {
372 overEnvS := strings.TrimSpace(overEnv)
373 if len(overEnvS) > 0 {
374 // Extract overwrite commands from env variable
375 for _, def := range strings.Split(overEnvS, ",") {
376 if kv := strings.Split(def, ":"); len(kv) == 2 {
377 overwriteMap[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1])
379 return cli.NewExitError(
380 fmt.Errorf("Invalid definition in XDS_OVERWRITE_COMMANDS (%s)", def),
386 overwriteMap["-exec-run"] = "-exec-continue"
387 overwriteMap["-file-exec-and-symbols"] = "-file-exec-file"
389 log.Debugf("overwriteMap = %v", overwriteMap)
391 // Send stdin though WS
394 reader := bufio.NewReader(os.Stdin)
397 sc := bufio.NewScanner(reader)
401 // overwrite some commands
402 for key, value := range overwriteMap {
403 if strings.Contains(command, key) {
404 command = strings.Replace(command, key, value, 1)
405 log.Debugf("OVERWRITE %s -> %s", key, value)
408 gdb.Write(command + "\n")
409 log.Debugf("Send: <%v>", command)
411 log.Infof("Stdin scanner exit, close stdin (err=%v)", sc.Err())
413 // CTRL-D exited scanner, so send it explicitly
415 time.Sleep(time.Millisecond * 100)
417 if paranoia--; paranoia <= 0 {
418 msg := "Abnormal loop detected on stdin"
419 log.Errorf("Abnormal loop detected on stdin")
420 gdb.SendSignal(syscall.SIGTERM)
421 exitChan <- exitResult{fmt.Errorf(msg), int(syscall.ELOOP)}
426 // Handling all Signals
427 sigs := make(chan os.Signal, 1)
433 if err := gdb.SendSignal(sig); err != nil {
434 log.Errorf("Error while sending signal: %s", err.Error())
440 if code, err := gdb.Start(clientPty != ""); err != nil {
441 return cli.NewExitError(err.Error(), code)
446 case res := <-exitChan:
449 log.Infoln("Exit successfully")
451 if res.error != nil {
452 log.Infoln("Exit with ERROR: ", res.error.Error())
453 errStr = res.error.Error()
455 return cli.NewExitError(errStr, res.code)
463 func loadConfigEnvFile(confFile, gdbCmdFile string) (map[string]string, string, error) {
465 envMap := make(map[string]string)
467 // 1- if no confFile set, use setting from gdb command file is option
468 // --command/-x is set
469 if confFile == "" && gdbCmdFile != "" {
470 logEarly("Try extract config from gdbCmdFile: %s", gdbCmdFile)
471 confFile, err = extractEnvFromCmdFile(gdbCmdFile)
473 defer os.Remove(confFile)
476 return envMap, confFile, fmt.Errorf(err.Error())
479 // 2- search xds-gdb.env file in various locations
481 curDir, _ := os.Getwd()
482 if u, err := user.Current(); err == nil {
483 xdsEnvFile := "xds-gdb.env"
484 for _, d := range []string{
486 path.Join(curDir, "..", ".."),
487 path.Join(curDir, "../../target"),
488 path.Join(u.HomeDir, ".xds"),
490 confFile = path.Join(d, xdsEnvFile)
491 logEarly("Search config in %s", confFile)
492 if common.Exists(confFile) {
500 return envMap, "", nil
503 if !common.Exists(confFile) {
504 return envMap, confFile, fmt.Errorf("Error no env config file not found")
506 if err = godotenv.Load(confFile); err != nil {
507 return envMap, confFile, fmt.Errorf("Error loading env config file " + confFile)
509 if envMap, err = godotenv.Read(confFile); err != nil {
510 return envMap, confFile, fmt.Errorf("Error reading env config file " + confFile)
512 return envMap, confFile, nil
516 extractEnvFromCmdFile: extract xds-gdb env variable from gdb command file
517 All commented lines (#) in gdb command file that start with ':XDS-ENV:' prefix
518 will be considered as XDS env commands. For example the 3 syntaxes below
520 # :XDS-ENV: XDS_PROJECT_ID=IW7B4EE-DBY4Z74_myProject
521 #:XDS-ENV:XDS_SDK_ID=poky-agl_aarch64_3.99.1+snapshot
522 # :XDS-ENV: export XDS_SERVER_URL=localhost:8800
524 func extractEnvFromCmdFile(cmdFile string) (string, error) {
525 if !common.Exists(cmdFile) {
528 cFd, err := os.Open(cmdFile)
530 return "", fmt.Errorf("Cannot open %s : %s", cmdFile, err.Error())
535 scanner := bufio.NewScanner(cFd)
537 lines = append(lines, scanner.Text())
539 if err = scanner.Err(); err != nil {
540 return "", fmt.Errorf("Cannot parse %s : %s", cmdFile, err.Error())
543 envFile, err := ioutil.TempFile("", "xds-gdb_env.ini")
545 return "", fmt.Errorf("Error while creating temporary env file: %s", err.Error())
547 envFileName := envFile.Name()
548 defer envFile.Close()
551 for _, ln := range lines {
552 ln = strings.TrimSpace(ln)
553 if strings.HasPrefix(ln, "#") && strings.Contains(ln, ":XDS-ENV:") {
554 env := strings.SplitAfterN(ln, ":XDS-ENV:", 2)
557 if _, err := envFile.WriteString(strings.TrimSpace(env[1]) + "\n"); err != nil {
558 return "", fmt.Errorf("Error write into temporary env file: %s", err.Error())
561 log.Warnf("Error while decoding line %s", ln)
573 return envFileName, nil
576 func logEarly(format string, a ...interface{}) {
577 earlyLog = append(earlyLog, fmt.Sprintf(format, a...))