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 logFileInitial = "/tmp/xds-gdb.log"
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")
67 log.Debugf("Exit: code=%v, err=%s", code, err)
74 var uri, prjID, rPath, logLevel, logFile, sdkid, confFile, gdbNative string
78 // Init Logger and set temporary file and level for the 1st part
79 // IOW while XDS_LOGLEVEL and XDS_LOGFILE options are not parsed
80 logFile = logFileInitial
81 fdL, err := os.OpenFile(logFileInitial, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
83 msgErr := fmt.Sprintf("Cannot create log file %s", logFileInitial)
84 exitError(syscall.EPERM, msgErr)
86 log.Formatter = &logrus.TextFormatter{}
88 log.Level = logrus.DebugLevel
90 uri = "localhost:8000"
91 logLevel = defaultLogLevel
93 // Create a new App instance
96 app.Usage = "wrapper on gdb for X(cross) Development System."
97 app.Version = AppVersion + " (" + AppSubVersion + ")"
98 app.Authors = appAuthors
99 app.Copyright = appCopyright
100 app.Metadata = make(map[string]interface{})
101 app.Metadata["version"] = AppVersion
102 app.Metadata["git-tag"] = AppSubVersion
103 app.Metadata["logger"] = log
105 app.Flags = []cli.Flag{
108 Usage: "list existing xds projects",
109 Destination: &listProject,
113 appEnvVars := []EnvVar{
116 Usage: "env config file to source on startup",
117 Destination: &confFile,
120 Name: "XDS_LOGLEVEL",
121 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
122 Destination: &logLevel,
126 Usage: "logging file",
127 Destination: &logFile,
130 Name: "XDS_NATIVE_GDB",
131 Usage: "use native gdb instead of remote XDS server",
132 Destination: &gdbNative,
135 Name: "XDS_PROJECT_ID",
136 Usage: "project ID you want to build (mandatory variable)",
141 Usage: "relative path into project",
146 Usage: "Cross Sdk ID to use to build project",
150 Name: "XDS_SERVER_URL",
151 Usage: "remote XDS server url",
156 // Process gdb arguments
157 log.Debugf("xds-gdb started with args: %v", os.Args)
158 args := make([]string, len(os.Args))
160 gdbArgs := make([]string, len(os.Args))
162 // Split xds-xxx options from gdb options
163 copy(gdbArgs, os.Args[1:])
164 for idx, a := range os.Args[1:] {
165 // Specific case to print help or version of xds-gdb
167 case "--help", "-h", "--version", "-v":
171 // Detect skip option (IOW '--') to split arguments
172 copy(args, os.Args[0:idx+1])
173 copy(gdbArgs, os.Args[idx+2:])
179 // Parse gdb arguments to detect:
180 // --tty option: used for inferior/ tty of debugged program
181 // -x/--command option: XDS env vars may be set within gdb command file
184 for idx, a := range gdbArgs {
186 case strings.HasPrefix(a, "--tty="):
187 clientPty = a[len("--tty="):]
191 case strings.HasPrefix(a, "-tty"):
192 clientPty = gdbArgs[idx+1]
196 case strings.HasPrefix(a, "--command="):
197 gdbCmdFile = a[len("--command="):]
199 case a == "--command":
200 case strings.HasPrefix(a, "-x"):
201 gdbCmdFile = gdbArgs[idx+1]
205 // Source config env file
206 // (we cannot use confFile var because env variables setting is just after)
207 envMap, confFile, err := loadConfigEnvFile(os.Getenv("XDS_CONFIG"), gdbCmdFile)
209 // Only rise an error when args is not set (IOW when --help or --version is not set)
212 exitError(syscall.ENOENT, err.Error())
216 // Managed env vars and create help
217 dynDesc := "\nENVIRONMENT VARIABLES:"
218 for _, ev := range appEnvVars {
219 dynDesc += fmt.Sprintf("\n %s \t\t %s", ev.Name, ev.Usage)
220 if evVal, evExist := os.LookupEnv(ev.Name); evExist && ev.Destination != nil {
221 *ev.Destination = evVal
224 app.Description = "gdb wrapper for X(cross) Development System\n"
225 app.Description += "\n"
226 app.Description += " Two debugging models are supported:\n"
227 app.Description += " - xds remote debugging requiring an XDS server and allowing cross debug\n"
228 app.Description += " - native debugging\n"
229 app.Description += " By default xds remote debug is used and you need to define XDS_NATIVE_GDB to\n"
230 app.Description += " use native gdb debug mode instead.\n"
231 app.Description += "\n"
232 app.Description += " xds-gdb configuration (see variables list below) can be set using:\n"
233 app.Description += " - a config file (XDS_CONFIG)\n"
234 app.Description += " - or environment variables\n"
235 app.Description += " - or by setting variables within gdb ini file (commented line including :XDS-ENV: tag)\n"
236 app.Description += " Example of gdb ini file where we define project and sdk ID:\n"
237 app.Description += " # :XDS-ENV: XDS_PROJECT_ID=IW7B4EE-DBY4Z74_myProject\n"
238 app.Description += " # :XDS-ENV: XDS_SDK_ID=poky-agl_aarch64_3.99.1+snapshot\n"
239 app.Description += "\n"
240 app.Description += dynDesc + "\n"
243 app.Action = func(ctx *cli.Context) error {
245 curDir, _ := os.Getwd()
247 // Now set logger level and log file to correct/env var settings
248 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
249 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", logLevel)
250 return cli.NewExitError(msg, int(syscall.EINVAL))
252 log.Infof("Switch log level to %s", logLevel)
254 if logFile != logFileInitial {
255 log.Infof("Switch logging to log file %s", logFile)
257 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
259 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
260 return cli.NewExitError(msgErr, int(syscall.EPERM))
266 // Build env variables
268 for k, v := range envMap {
269 env = append(env, k+"="+v)
272 // Create cross or native gdb interface
275 gdb = NewGdbNative(log, gdbArgs, env)
277 gdb = NewGdbXds(log, gdbArgs, env)
278 gdb.SetConfig("uri", uri)
279 gdb.SetConfig("prjID", prjID)
280 gdb.SetConfig("sdkID", sdkid)
281 gdb.SetConfig("rPath", rPath)
282 gdb.SetConfig("listProject", listProject)
286 log.Infof("Original arguments: %v", os.Args)
287 log.Infof("Current directory : %v", curDir)
288 log.Infof("Use confFile : '%s'", confFile)
289 log.Infof("Execute : /exec %v %v", gdb.Cmd(), gdb.Args())
291 // Properly report invalid init file error
292 gdbCommandFileError := ""
293 for i, a := range gdbArgs {
295 gdbCommandFileError = gdbArgs[i+1] + ": No such file or directory."
297 } else if strings.HasPrefix(a, "--command=") {
298 gdbCommandFileError = strings.TrimLeft(a, "--command=") + ": No such file or directory."
302 log.Infof("Add detection of error: <%s>", gdbCommandFileError)
304 // Init gdb subprocess management
305 if code, err := gdb.Init(); err != nil {
306 return cli.NewExitError(err.Error(), code)
309 exitChan := make(chan exitResult, 1)
311 gdb.OnError(func(err error) {
312 fmt.Println("ERROR: ", err.Error())
315 gdb.OnDisconnect(func(err error) {
316 fmt.Println("Disconnection: ", err.Error())
317 exitChan <- exitResult{err, int(syscall.ESHUTDOWN)}
320 gdb.Read(func(timestamp, stdout, stderr string) {
322 fmt.Printf("%s", stdout)
323 log.Debugf("Recv OUT: <%s>", stdout)
326 fmt.Fprintf(os.Stderr, "%s", stderr)
327 log.Debugf("Recv ERR: <%s>", stderr)
330 // Correctly report error about init file
331 if gdbCommandFileError != "" && strings.Contains(stdout, gdbCommandFileError) {
332 fmt.Fprintf(os.Stderr, "ERROR: "+gdbCommandFileError)
333 log.Errorf("ERROR: " + gdbCommandFileError)
334 if err := gdb.SendSignal(syscall.SIGTERM); err != nil {
335 log.Errorf("Error while sending signal: %s", err.Error())
337 exitChan <- exitResult{err, int(syscall.ENOENT)}
341 gdb.OnExit(func(code int, err error) {
342 exitChan <- exitResult{err, code}
345 // Handle client tty / pts
347 log.Infoln("Client tty detected: %v\n", clientPty)
349 cpFd, err := os.OpenFile(clientPty, os.O_RDWR, 0)
351 return cli.NewExitError(err.Error(), int(syscall.EPERM))
356 /* XXX TODO - implement stdin to send data to debugged program
358 reader := bufio.NewReader(cpFd)
359 sc := bufio.NewScanner(reader)
362 iosk.Emit(apiv1.ExecInferiorInEvent, data+"\n")
363 log.Debugf("Inferior IN: <%v>", data)
366 log.Warnf("Inferior Stdin scanner exit, close stdin (err=%v)", sc.Err())
372 gdb.InferiorRead(func(timestamp, stdout, stderr string) {
374 fmt.Fprintf(cpFd, "%s", stdout)
375 log.Debugf("Inferior OUT: <%s>", stdout)
378 fmt.Fprintf(cpFd, "%s", stderr)
379 log.Debugf("Inferior ERR: <%s>", stderr)
384 // Allow to overwrite some gdb commands
385 var overwriteMap = make(map[string]string)
386 if overEnv, exist := os.LookupEnv("XDS_OVERWRITE_COMMANDS"); exist {
387 overEnvS := strings.TrimSpace(overEnv)
388 if len(overEnvS) > 0 {
389 // Extract overwrite commands from env variable
390 for _, def := range strings.Split(overEnvS, ",") {
391 if kv := strings.Split(def, ":"); len(kv) == 2 {
392 overwriteMap[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1])
394 return cli.NewExitError(
395 fmt.Errorf("Invalid definition in XDS_OVERWRITE_COMMANDS (%s)", def),
401 overwriteMap["-exec-run"] = "-exec-continue"
402 overwriteMap["-file-exec-and-symbols"] = "-file-exec-file"
404 log.Debugf("overwriteMap = %v", overwriteMap)
406 // Send stdin though WS
409 reader := bufio.NewReader(os.Stdin)
412 sc := bufio.NewScanner(reader)
416 // overwrite some commands
417 for key, value := range overwriteMap {
418 if strings.Contains(command, key) {
419 command = strings.Replace(command, key, value, 1)
420 log.Debugf("OVERWRITE %s -> %s", key, value)
423 gdb.Write(command + "\n")
424 log.Debugf("Send: <%v>", command)
426 log.Infof("Stdin scanner exit, close stdin (err=%v)", sc.Err())
428 // CTRL-D exited scanner, so send it explicitly
430 time.Sleep(time.Millisecond * 100)
432 if paranoia--; paranoia <= 0 {
433 msg := "Abnormal loop detected on stdin"
434 log.Errorf("Abnormal loop detected on stdin")
435 gdb.SendSignal(syscall.SIGTERM)
436 exitChan <- exitResult{fmt.Errorf(msg), int(syscall.ELOOP)}
441 // Handling all Signals
442 sigs := make(chan os.Signal, 1)
448 if err := gdb.SendSignal(sig); err != nil {
449 log.Errorf("Error while sending signal: %s", err.Error())
455 if code, err := gdb.Start(clientPty != ""); err != nil {
456 return cli.NewExitError(err.Error(), code)
461 case res := <-exitChan:
464 log.Infoln("Exit successfully")
466 if res.error != nil {
467 log.Infoln("Exit with ERROR: ", res.error.Error())
468 errStr = res.error.Error()
470 return cli.NewExitError(errStr, res.code)
478 func loadConfigEnvFile(confFile, gdbCmdFile string) (map[string]string, string, error) {
480 envMap := make(map[string]string)
482 // 1- if no confFile set, use setting from gdb command file is option
483 // --command/-x is set
484 if confFile == "" && gdbCmdFile != "" {
485 log.Infof("Try extract config from gdbCmdFile: %s", gdbCmdFile)
486 confFile, err = extractEnvFromCmdFile(gdbCmdFile)
488 defer os.Remove(confFile)
491 return envMap, confFile, fmt.Errorf(err.Error())
494 // 2- search xds-gdb.env file in various locations
496 curDir, _ := os.Getwd()
497 if u, err := user.Current(); err == nil {
498 xdsEnvFile := "xds-gdb.env"
499 for _, d := range []string{
501 path.Join(curDir, "..", ".."),
502 path.Join(curDir, "../../target"),
503 path.Join(u.HomeDir, ".xds"),
505 confFile = path.Join(d, xdsEnvFile)
506 log.Infof("Search config in %s", confFile)
507 if common.Exists(confFile) {
515 log.Infof("NO valid conf file found!")
516 return envMap, "", nil
519 log.Infof("Use conf file: %s", confFile)
520 if !common.Exists(confFile) {
521 return envMap, confFile, fmt.Errorf("Error no env config file not found")
523 if err = godotenv.Load(confFile); err != nil {
524 return envMap, confFile, fmt.Errorf("Error loading env config file " + confFile)
526 if envMap, err = godotenv.Read(confFile); err != nil {
527 return envMap, confFile, fmt.Errorf("Error reading env config file " + confFile)
529 return envMap, confFile, nil
533 extractEnvFromCmdFile: extract xds-gdb env variable from gdb command file
534 All commented lines (#) in gdb command file that start with ':XDS-ENV:' prefix
535 will be considered as XDS env commands. For example the 3 syntaxes below
537 # :XDS-ENV: XDS_PROJECT_ID=IW7B4EE-DBY4Z74_myProject
538 #:XDS-ENV:XDS_SDK_ID=poky-agl_aarch64_3.99.1+snapshot
539 # :XDS-ENV: export XDS_SERVER_URL=localhost:8800
541 func extractEnvFromCmdFile(cmdFile string) (string, error) {
542 if !common.Exists(cmdFile) {
545 cFd, err := os.Open(cmdFile)
547 return "", fmt.Errorf("Cannot open %s : %s", cmdFile, err.Error())
552 scanner := bufio.NewScanner(cFd)
554 lines = append(lines, scanner.Text())
556 if err = scanner.Err(); err != nil {
557 return "", fmt.Errorf("Cannot parse %s : %s", cmdFile, err.Error())
560 envFile, err := ioutil.TempFile("", "xds-gdb_env.ini")
562 return "", fmt.Errorf("Error while creating temporary env file: %s", err.Error())
564 envFileName := envFile.Name()
565 defer envFile.Close()
568 for _, ln := range lines {
569 ln = strings.TrimSpace(ln)
570 if strings.HasPrefix(ln, "#") && strings.Contains(ln, ":XDS-ENV:") {
571 env := strings.SplitAfterN(ln, ":XDS-ENV:", 2)
574 if _, err := envFile.WriteString(strings.TrimSpace(env[1]) + "\n"); err != nil {
575 return "", fmt.Errorf("Error write into temporary env file: %s", err.Error())
578 log.Warnf("Error while decoding line %s", ln)
590 return envFileName, nil