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", "--list", "-ls":
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)
208 log.Infof("Load env config: envMap=%v, confFile=%v, err=%v", envMap, confFile, err)
210 // Only rise an error when args is not set (IOW when --help or --version is not set)
213 exitError(syscall.ENOENT, err.Error())
217 // Managed env vars and create help
218 dynDesc := "\nENVIRONMENT VARIABLES:"
219 for _, ev := range appEnvVars {
220 dynDesc += fmt.Sprintf("\n %s \t\t %s", ev.Name, ev.Usage)
221 if evVal, evExist := os.LookupEnv(ev.Name); evExist && ev.Destination != nil {
222 *ev.Destination = evVal
225 app.Description = "gdb wrapper for X(cross) Development System\n"
226 app.Description += "\n"
227 app.Description += " Two debugging models are supported:\n"
228 app.Description += " - xds remote debugging requiring an XDS server and allowing cross debug\n"
229 app.Description += " - native debugging\n"
230 app.Description += " By default xds remote debug is used and you need to define XDS_NATIVE_GDB to\n"
231 app.Description += " use native gdb debug mode instead.\n"
232 app.Description += "\n"
233 app.Description += " xds-gdb configuration (see variables list below) can be set using:\n"
234 app.Description += " - a config file (XDS_CONFIG)\n"
235 app.Description += " - or environment variables\n"
236 app.Description += " - or by setting variables within gdb ini file (commented line including :XDS-ENV: tag)\n"
237 app.Description += " Example of gdb ini file where we define project and sdk ID:\n"
238 app.Description += " # :XDS-ENV: XDS_PROJECT_ID=IW7B4EE-DBY4Z74_myProject\n"
239 app.Description += " # :XDS-ENV: XDS_SDK_ID=poky-agl_aarch64_3.99.1+snapshot\n"
240 app.Description += "\n"
241 app.Description += dynDesc + "\n"
244 app.Action = func(ctx *cli.Context) error {
246 curDir, _ := os.Getwd()
248 // Build env variables
250 for k, v := range envMap {
251 env = append(env, k+"="+v)
254 // Now set logger level and log file to correct/env var settings
255 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
256 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", logLevel)
257 return cli.NewExitError(msg, int(syscall.EINVAL))
259 log.Infof("Switch log level to %s", logLevel)
261 if logFile != logFileInitial {
262 log.Infof("Switch logging to log file %s", logFile)
264 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
266 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
267 return cli.NewExitError(msgErr, int(syscall.EPERM))
273 // Create cross or native gdb interface
276 gdb = NewGdbNative(log, gdbArgs, env)
278 gdb = NewGdbXds(log, gdbArgs, env)
279 gdb.SetConfig("uri", uri)
280 gdb.SetConfig("prjID", prjID)
281 gdb.SetConfig("sdkID", sdkid)
282 gdb.SetConfig("rPath", rPath)
283 gdb.SetConfig("listProject", listProject)
287 log.Infof("Original arguments: %v", os.Args)
288 log.Infof("Current directory : %v", curDir)
289 log.Infof("Use confFile : '%s'", confFile)
290 log.Infof("Execute : /exec %v %v", gdb.Cmd(), gdb.Args())
292 // Properly report invalid init file error
293 gdbCommandFileError := ""
294 for i, a := range gdbArgs {
296 gdbCommandFileError = gdbArgs[i+1] + ": No such file or directory."
298 } else if strings.HasPrefix(a, "--command=") {
299 gdbCommandFileError = strings.TrimLeft(a, "--command=") + ": No such file or directory."
303 log.Infof("Add detection of error: <%s>", gdbCommandFileError)
305 // Init gdb subprocess management
306 if code, err := gdb.Init(); err != nil {
307 return cli.NewExitError(err.Error(), code)
310 exitChan := make(chan exitResult, 1)
312 gdb.OnError(func(err error) {
313 fmt.Println("ERROR: ", err.Error())
316 gdb.OnDisconnect(func(err error) {
317 fmt.Println("Disconnection: ", err.Error())
318 exitChan <- exitResult{err, int(syscall.ESHUTDOWN)}
321 gdb.Read(func(timestamp, stdout, stderr string) {
323 fmt.Printf("%s", stdout)
324 log.Debugf("Recv OUT: <%s>", stdout)
327 fmt.Fprintf(os.Stderr, "%s", stderr)
328 log.Debugf("Recv ERR: <%s>", stderr)
331 // Correctly report error about init file
332 if gdbCommandFileError != "" && strings.Contains(stdout, gdbCommandFileError) {
333 fmt.Fprintf(os.Stderr, "ERROR: "+gdbCommandFileError)
334 log.Errorf("ERROR: " + gdbCommandFileError)
335 if err := gdb.SendSignal(syscall.SIGTERM); err != nil {
336 log.Errorf("Error while sending signal: %s", err.Error())
338 exitChan <- exitResult{err, int(syscall.ENOENT)}
342 gdb.OnExit(func(code int, err error) {
343 exitChan <- exitResult{err, code}
346 // Handle client tty / pts
348 log.Infoln("Client tty detected: %v\n", clientPty)
350 cpFd, err := os.OpenFile(clientPty, os.O_RDWR, 0)
352 return cli.NewExitError(err.Error(), int(syscall.EPERM))
357 /* XXX TODO - implement stdin to send data to debugged program
359 reader := bufio.NewReader(cpFd)
360 sc := bufio.NewScanner(reader)
363 iosk.Emit(apiv1.ExecInferiorInEvent, data+"\n")
364 log.Debugf("Inferior IN: <%v>", data)
367 log.Warnf("Inferior Stdin scanner exit, close stdin (err=%v)", sc.Err())
373 gdb.InferiorRead(func(timestamp, stdout, stderr string) {
375 fmt.Fprintf(cpFd, "%s", stdout)
376 log.Debugf("Inferior OUT: <%s>", stdout)
379 fmt.Fprintf(cpFd, "%s", stderr)
380 log.Debugf("Inferior ERR: <%s>", stderr)
385 // Allow to overwrite some gdb commands
386 var overwriteMap = make(map[string]string)
387 if overEnv, exist := os.LookupEnv("XDS_OVERWRITE_COMMANDS"); exist {
388 overEnvS := strings.TrimSpace(overEnv)
389 if len(overEnvS) > 0 {
390 // Extract overwrite commands from env variable
391 for _, def := range strings.Split(overEnvS, ",") {
392 if kv := strings.Split(def, ":"); len(kv) == 2 {
393 overwriteMap[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1])
395 return cli.NewExitError(
396 fmt.Errorf("Invalid definition in XDS_OVERWRITE_COMMANDS (%s)", def),
402 overwriteMap["-exec-run"] = "-exec-continue"
403 overwriteMap["-file-exec-and-symbols"] = "-file-exec-file"
405 log.Debugf("overwriteMap = %v", overwriteMap)
407 // Send stdin though WS
410 reader := bufio.NewReader(os.Stdin)
413 sc := bufio.NewScanner(reader)
417 // overwrite some commands
418 for key, value := range overwriteMap {
419 if strings.Contains(command, key) {
420 command = strings.Replace(command, key, value, 1)
421 log.Debugf("OVERWRITE %s -> %s", key, value)
424 gdb.Write(command + "\n")
425 log.Debugf("Send: <%v>", command)
427 log.Infof("Stdin scanner exit, close stdin (err=%v)", sc.Err())
429 // CTRL-D exited scanner, so send it explicitly
431 time.Sleep(time.Millisecond * 100)
433 if paranoia--; paranoia <= 0 {
434 msg := "Abnormal loop detected on stdin"
435 log.Errorf("Abnormal loop detected on stdin")
436 gdb.SendSignal(syscall.SIGTERM)
437 exitChan <- exitResult{fmt.Errorf(msg), int(syscall.ELOOP)}
442 // Handling all Signals
443 sigs := make(chan os.Signal, 1)
449 if err := gdb.SendSignal(sig); err != nil {
450 log.Errorf("Error while sending signal: %s", err.Error())
456 if code, err := gdb.Start(clientPty != ""); err != nil {
457 return cli.NewExitError(err.Error(), code)
462 case res := <-exitChan:
465 log.Infoln("Exit successfully")
467 if res.error != nil {
468 log.Infoln("Exit with ERROR: ", res.error.Error())
469 errStr = res.error.Error()
471 return cli.NewExitError(errStr, res.code)
479 func loadConfigEnvFile(confFile, gdbCmdFile string) (map[string]string, string, error) {
481 envMap := make(map[string]string)
483 // 1- if no confFile set, use setting from gdb command file is option
484 // --command/-x is set
485 if confFile == "" && gdbCmdFile != "" {
486 log.Infof("Try extract config from gdbCmdFile: %s", gdbCmdFile)
487 confFile, err = extractEnvFromCmdFile(gdbCmdFile)
489 defer os.Remove(confFile)
492 log.Infof("Extraction from gdbCmdFile failed: %v", err.Error())
495 // 2- search xds-gdb.env file in various locations
497 curDir, _ := os.Getwd()
498 if u, err := user.Current(); err == nil {
499 xdsEnvFile := "xds-gdb.env"
500 for _, d := range []string{
502 path.Join(curDir, ".."),
503 path.Join(curDir, "target"),
504 path.Join(u.HomeDir, ".config", "xds"),
506 confFile = path.Join(d, xdsEnvFile)
507 log.Infof("Search config in %s", confFile)
508 if common.Exists(confFile) {
516 log.Infof("NO valid conf file found!")
517 return envMap, "", nil
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)
530 return envMap, confFile, nil
534 extractEnvFromCmdFile: extract xds-gdb env variable from gdb command file
535 All commented lines (#) in gdb command file that start with ':XDS-ENV:' prefix
536 will be considered as XDS env commands. For example the 3 syntaxes below
538 # :XDS-ENV: XDS_PROJECT_ID=IW7B4EE-DBY4Z74_myProject
539 #:XDS-ENV:XDS_SDK_ID=poky-agl_aarch64_3.99.1+snapshot
540 # :XDS-ENV: export XDS_SERVER_URL=localhost:8800
542 func extractEnvFromCmdFile(cmdFile string) (string, error) {
543 if !common.Exists(cmdFile) {
546 cFd, err := os.Open(cmdFile)
548 return "", fmt.Errorf("Cannot open %s : %s", cmdFile, err.Error())
553 scanner := bufio.NewScanner(cFd)
555 lines = append(lines, scanner.Text())
557 if err = scanner.Err(); err != nil {
558 return "", fmt.Errorf("Cannot parse %s : %s", cmdFile, err.Error())
561 envFile, err := ioutil.TempFile("", "xds-gdb_env.ini")
563 return "", fmt.Errorf("Error while creating temporary env file: %s", err.Error())
565 envFileName := envFile.Name()
566 defer envFile.Close()
569 for _, ln := range lines {
570 ln = strings.TrimSpace(ln)
571 if strings.HasPrefix(ln, "#") && strings.Contains(ln, ":XDS-ENV:") {
572 env := strings.SplitAfterN(ln, ":XDS-ENV:", 2)
575 if _, err := envFile.WriteString(strings.TrimSpace(env[1]) + "\n"); err != nil {
576 return "", fmt.Errorf("Error write into temporary env file: %s", err.Error())
579 log.Warnf("Error while decoding line %s", ln)
591 return envFileName, nil