2 * Copyright (C) 2017 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 * xds-gdb: a wrapper on gdb tool for X(cross) Development System.
37 "github.com/Sirupsen/logrus"
38 "github.com/codegangsta/cli"
39 common "github.com/iotbzh/xds-common/golib"
40 "github.com/joho/godotenv"
43 var appAuthors = []cli.Author{
44 cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
47 // AppName name of this application
48 var AppName = "xds-gdb"
50 // AppVersion Version of this application
52 var AppVersion = "?.?.?"
54 // AppSubVersion is the git tag id added to version string
55 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
57 var AppSubVersion = "unknown-dev"
60 var log = logrus.New()
61 var logFileInitial = "/tmp/xds-gdb.log"
63 // Application details
65 appCopyright = "Copyright (C) 2017 IoT.bzh - Apache-2.0"
66 defaultLogLevel = "warning"
70 type exitResult struct {
75 // EnvVar - Environment variables used by application
82 // exitError terminates this program with the specified error
83 func exitError(code syscall.Errno, f string, a ...interface{}) {
84 err := fmt.Sprintf(f, a...)
85 fmt.Fprintf(os.Stderr, err+"\n")
86 log.Debugf("Exit: code=%v, err=%s", code, err)
93 var uri, prjID, rPath, logLevel, logFile, sdkid, confFile, gdbNative string
97 // Init Logger and set temporary file and level for the 1st part
98 // IOW while XDS_LOGLEVEL and XDS_LOGFILE options are not parsed
99 logFile = logFileInitial
100 fdL, err := os.OpenFile(logFileInitial, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
102 msgErr := fmt.Sprintf("Cannot create log file %s", logFileInitial)
103 exitError(syscall.EPERM, msgErr)
105 log.Formatter = &logrus.TextFormatter{}
107 log.Level = logrus.DebugLevel
109 uri = "localhost:8000"
110 logLevel = defaultLogLevel
112 // Create a new App instance
115 app.Usage = "wrapper on gdb for X(cross) Development System."
116 app.Version = AppVersion + " (" + AppSubVersion + ")"
117 app.Authors = appAuthors
118 app.Copyright = appCopyright
119 app.Metadata = make(map[string]interface{})
120 app.Metadata["version"] = AppVersion
121 app.Metadata["git-tag"] = AppSubVersion
122 app.Metadata["logger"] = log
124 app.Flags = []cli.Flag{
127 Usage: "list existing xds projects",
128 Destination: &listProject,
132 appEnvVars := []EnvVar{
135 Usage: "env config file to source on startup",
136 Destination: &confFile,
139 Name: "XDS_LOGLEVEL",
140 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)",
141 Destination: &logLevel,
145 Usage: "logging file (default: " + logFileInitial + ")",
146 Destination: &logFile,
149 Name: "XDS_NATIVE_GDB",
150 Usage: "use native gdb instead of remote XDS server",
151 Destination: &gdbNative,
154 Name: "XDS_PROJECT_ID",
155 Usage: "project ID you want to build (mandatory variable)",
160 Usage: "relative path into project",
165 Usage: "Cross Sdk ID to use to build project",
169 Name: "XDS_SERVER_URL",
170 Usage: "remote XDS server url",
175 // Process gdb arguments
176 log.Debugf("xds-gdb started with args: %v", os.Args)
177 args := make([]string, len(os.Args))
179 gdbArgs := make([]string, len(os.Args))
181 // Split xds-xxx options from gdb options
182 copy(gdbArgs, os.Args[1:])
183 for idx, a := range os.Args[1:] {
184 // Specific case to print help or version of xds-gdb
186 case "--help", "-h", "--version", "-v", "--list", "-ls":
190 // Detect skip option (IOW '--') to split arguments
191 copy(args, os.Args[0:idx+1])
192 copy(gdbArgs, os.Args[idx+2:])
198 // Parse gdb arguments to detect:
199 // --tty option: used for inferior/ tty of debugged program
200 // -x/--command option: XDS env vars may be set within gdb command file
203 for idx, a := range gdbArgs {
205 case strings.HasPrefix(a, "--tty="):
206 clientPty = a[len("--tty="):]
210 case strings.HasPrefix(a, "-tty"):
211 clientPty = gdbArgs[idx+1]
215 case strings.HasPrefix(a, "--command="):
216 gdbCmdFile = a[len("--command="):]
218 case a == "--command":
219 case strings.HasPrefix(a, "-x"):
220 gdbCmdFile = gdbArgs[idx+1]
224 // Source config env file
225 // (we cannot use confFile var because env variables setting is just after)
226 envMap, confFile, err := loadConfigEnvFile(os.Getenv("XDS_CONFIG"), gdbCmdFile)
227 log.Infof("Load env config: envMap=%v, confFile=%v, err=%v", envMap, confFile, err)
229 // Only rise an error when args is not set (IOW when --help or --version is not set)
232 exitError(syscall.ENOENT, err.Error())
236 // Managed env vars and create help
237 dynDesc := "\nENVIRONMENT VARIABLES:"
238 for _, ev := range appEnvVars {
239 dynDesc += fmt.Sprintf("\n %s \t\t %s", ev.Name, ev.Usage)
240 if evVal, evExist := os.LookupEnv(ev.Name); evExist && ev.Destination != nil {
241 *ev.Destination = evVal
244 app.Description = "gdb wrapper for X(cross) Development System\n"
245 app.Description += "\n"
246 app.Description += " Two debugging models are supported:\n"
247 app.Description += " - xds remote debugging requiring an XDS server and allowing cross debug\n"
248 app.Description += " - native debugging\n"
249 app.Description += " By default xds remote debug is used and you need to define XDS_NATIVE_GDB to\n"
250 app.Description += " use native gdb debug mode instead.\n"
251 app.Description += "\n"
252 app.Description += " xds-gdb configuration (see variables list below) can be set using:\n"
253 app.Description += " - a config file (XDS_CONFIG)\n"
254 app.Description += " - or environment variables\n"
255 app.Description += " - or by setting variables within gdb ini file (commented line including :XDS-ENV: tag)\n"
256 app.Description += " Example of gdb ini file where we define project and sdk ID:\n"
257 app.Description += " # :XDS-ENV: XDS_PROJECT_ID=IW7B4EE-DBY4Z74_myProject\n"
258 app.Description += " # :XDS-ENV: XDS_SDK_ID=poky-agl_aarch64_3.99.1+snapshot\n"
259 app.Description += "\n"
260 app.Description += dynDesc + "\n"
263 app.Action = func(ctx *cli.Context) error {
265 curDir, _ := os.Getwd()
267 // Build env variables
269 for k, v := range envMap {
270 env = append(env, k+"="+v)
273 // Now set logger level and log file to correct/env var settings
274 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
275 msg := fmt.Sprintf("Invalid log level : \"%v\"\n", logLevel)
276 return cli.NewExitError(msg, int(syscall.EINVAL))
278 log.Infof("Switch log level to %s", logLevel)
280 if logFile != logFileInitial {
281 log.Infof("Switch logging to log file %s", logFile)
283 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
285 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
286 return cli.NewExitError(msgErr, int(syscall.EPERM))
292 // Create cross or native gdb interface
295 gdb = NewGdbNative(log, gdbArgs, env)
297 gdb = NewGdbXds(log, gdbArgs, env)
298 gdb.SetConfig("uri", uri)
299 gdb.SetConfig("prjID", prjID)
300 gdb.SetConfig("sdkID", sdkid)
301 gdb.SetConfig("rPath", rPath)
302 gdb.SetConfig("listProject", listProject)
306 log.Infof("Original arguments: %v", os.Args)
307 log.Infof("Current directory : %v", curDir)
308 log.Infof("Use confFile : '%s'", confFile)
309 log.Infof("Execute : /exec %v %v", gdb.Cmd(), gdb.Args())
311 // Properly report invalid init file error
312 gdbCommandFileError := ""
313 for i, a := range gdbArgs {
315 gdbCommandFileError = gdbArgs[i+1] + ": No such file or directory."
317 } else if strings.HasPrefix(a, "--command=") {
318 gdbCommandFileError = strings.TrimLeft(a, "--command=") + ": No such file or directory."
322 log.Infof("Add detection of error: <%s>", gdbCommandFileError)
324 // Init gdb subprocess management
325 if code, err := gdb.Init(); err != nil {
326 return cli.NewExitError(err.Error(), code)
329 exitChan := make(chan exitResult, 1)
331 gdb.OnError(func(err error) {
332 fmt.Println("ERROR: ", err.Error())
335 gdb.OnDisconnect(func(err error) {
336 fmt.Println("Disconnection: ", err.Error())
337 exitChan <- exitResult{err, int(syscall.ESHUTDOWN)}
340 gdb.Read(func(timestamp, stdout, stderr string) {
342 fmt.Printf("%s", stdout)
343 log.Debugf("Recv OUT: <%s>", stdout)
346 fmt.Fprintf(os.Stderr, "%s", stderr)
347 log.Debugf("Recv ERR: <%s>", stderr)
350 // Correctly report error about init file
351 if gdbCommandFileError != "" && strings.Contains(stdout, gdbCommandFileError) {
352 fmt.Fprintf(os.Stderr, "ERROR: "+gdbCommandFileError)
353 log.Errorf("ERROR: " + gdbCommandFileError)
354 if err := gdb.SendSignal(syscall.SIGTERM); err != nil {
355 log.Errorf("Error while sending signal: %s", err.Error())
357 exitChan <- exitResult{err, int(syscall.ENOENT)}
361 gdb.OnExit(func(code int, err error) {
362 exitChan <- exitResult{err, code}
365 // Handle client tty / pts
367 log.Infoln("Client tty detected: %v", clientPty)
369 cpFd, err := os.OpenFile(clientPty, os.O_RDWR, 0)
371 return cli.NewExitError(err.Error(), int(syscall.EPERM))
376 /* XXX TODO - implement stdin to send data to debugged program
378 reader := bufio.NewReader(cpFd)
379 sc := bufio.NewScanner(reader)
382 iosk.Emit(xaapiv1.ExecInferiorInEvent, data+"\n")
383 log.Debugf("Inferior IN: <%v>", data)
386 log.Warnf("Inferior Stdin scanner exit, close stdin (err=%v)", sc.Err())
392 gdb.InferiorRead(func(timestamp, stdout, stderr string) {
394 fmt.Fprintf(cpFd, "%s", stdout)
395 log.Debugf("Inferior OUT: <%s>", stdout)
398 fmt.Fprintf(cpFd, "%s", stderr)
399 log.Debugf("Inferior ERR: <%s>", stderr)
404 // Allow to overwrite some gdb commands
405 var overwriteMap = make(map[string]string)
406 if overEnv, exist := os.LookupEnv("XDS_OVERWRITE_COMMANDS"); exist {
407 overEnvS := strings.TrimSpace(overEnv)
408 if len(overEnvS) > 0 {
409 // Extract overwrite commands from env variable
410 for _, def := range strings.Split(overEnvS, ",") {
411 if kv := strings.Split(def, ":"); len(kv) == 2 {
412 overwriteMap[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1])
414 return cli.NewExitError(
415 fmt.Errorf("Invalid definition in XDS_OVERWRITE_COMMANDS (%s)", def),
421 overwriteMap["-exec-run"] = "-exec-continue"
422 overwriteMap["-file-exec-and-symbols"] = "-file-exec-file"
424 log.Debugf("overwriteMap = %v", overwriteMap)
426 // Send stdin though WS
429 reader := bufio.NewReader(os.Stdin)
431 // Enable workaround to correctly close connection
432 // except if XDS_GDBSERVER_EXIT_NOFIX is defined
433 _, gdbExitNoFix := os.LookupEnv("XDS_GDBSERVER_EXIT_NOFIX")
436 sc := bufio.NewScanner(reader)
440 // overwrite some commands
441 for key, value := range overwriteMap {
442 if strings.Contains(command, key) {
443 command = strings.Replace(command, key, value, 1)
444 log.Debugf("OVERWRITE %s -> %s", key, value)
448 // Send SIGINT to stop debugged process execution before sending -gdb-exit command
449 if !gdbExitNoFix && strings.Contains(command, "-gdb-exit") {
450 log.Infof("Detection of -gdb-exit, exiting...")
451 if err := gdb.SendSignal(syscall.SIGINT); err != nil {
452 log.Errorf("Error while sending signal SIGINT : %s", err.Error())
454 time.Sleep(time.Millisecond * 200)
457 gdb.Write(command + "\n")
458 log.Debugf("Send: <%v>", command)
460 log.Infof("Stdin scanner exit, close stdin (err=%v)", sc.Err())
462 // CTRL-D exited scanner, so send it explicitly
464 time.Sleep(time.Millisecond * 100)
466 if paranoia--; paranoia <= 0 {
467 msg := "Abnormal loop detected on stdin"
468 log.Errorf("Abnormal loop detected on stdin")
469 gdb.SendSignal(syscall.SIGTERM)
470 exitChan <- exitResult{fmt.Errorf(msg), int(syscall.ELOOP)}
475 // Handling all Signals
476 sigs := make(chan os.Signal, 1)
483 if isIgnoredSignal(sig) {
487 if err := gdb.SendSignal(sig); err != nil {
488 log.Errorf("Error while sending signal %v : %s", sig, err.Error())
494 if code, err := gdb.Start(clientPty != ""); err != nil {
495 return cli.NewExitError(err.Error(), code)
500 case res := <-exitChan:
503 log.Infoln("Exit successfully")
505 if res.error != nil {
506 log.Infoln("Exit with ERROR: ", res.error.Error())
507 errStr = res.error.Error()
509 return cli.NewExitError(errStr, res.code)
517 func loadConfigEnvFile(confFile, gdbCmdFile string) (map[string]string, string, error) {
519 envMap := make(map[string]string)
521 // 1- if no confFile set, use setting from gdb command file is option
522 // --command/-x is set
523 if confFile == "" && gdbCmdFile != "" {
524 log.Infof("Try extract config from gdbCmdFile: %s", gdbCmdFile)
525 confFile, err = extractEnvFromCmdFile(gdbCmdFile)
527 defer os.Remove(confFile)
530 log.Infof("Extraction from gdbCmdFile failed: %v", err.Error())
533 // 2- search xds-gdb.env file in various locations
535 curDir, _ := os.Getwd()
536 if u, err := user.Current(); err == nil {
537 xdsEnvFile := "xds-gdb.env"
538 for _, d := range []string{
540 path.Join(curDir, ".."),
541 path.Join(curDir, "target"),
542 path.Join(u.HomeDir, ".config", "xds"),
544 cf := path.Join(d, xdsEnvFile)
545 log.Infof("Search config in %s", cf)
546 if common.Exists(cf) {
555 log.Infof("NO valid conf file found!")
556 return envMap, "", nil
559 if !common.Exists(confFile) {
560 return envMap, confFile, fmt.Errorf("Error no env config file not found")
562 if err = godotenv.Load(confFile); err != nil {
563 return envMap, confFile, fmt.Errorf("Error loading env config file " + confFile)
565 if envMap, err = godotenv.Read(confFile); err != nil {
566 return envMap, confFile, fmt.Errorf("Error reading env config file " + confFile)
569 return envMap, confFile, nil
573 extractEnvFromCmdFile: extract xds-gdb env variable from gdb command file
574 All commented lines (#) in gdb command file that start with ':XDS-ENV:' prefix
575 will be considered as XDS env commands. For example the 3 syntaxes below
577 # :XDS-ENV: XDS_PROJECT_ID=IW7B4EE-DBY4Z74_myProject
578 #:XDS-ENV:XDS_SDK_ID=poky-agl_aarch64_3.99.1+snapshot
579 # :XDS-ENV: export XDS_SERVER_URL=localhost:8800
581 func extractEnvFromCmdFile(cmdFile string) (string, error) {
582 if !common.Exists(cmdFile) {
585 cFd, err := os.Open(cmdFile)
587 return "", fmt.Errorf("Cannot open %s : %s", cmdFile, err.Error())
592 scanner := bufio.NewScanner(cFd)
594 lines = append(lines, scanner.Text())
596 if err = scanner.Err(); err != nil {
597 return "", fmt.Errorf("Cannot parse %s : %s", cmdFile, err.Error())
600 envFile, err := ioutil.TempFile("", "xds-gdb_env.ini")
602 return "", fmt.Errorf("Error while creating temporary env file: %s", err.Error())
604 envFileName := envFile.Name()
605 defer envFile.Close()
608 for _, ln := range lines {
609 ln = strings.TrimSpace(ln)
610 if strings.HasPrefix(ln, "#") && strings.Contains(ln, ":XDS-ENV:") {
611 env := strings.SplitAfterN(ln, ":XDS-ENV:", 2)
614 if _, err := envFile.WriteString(strings.TrimSpace(env[1]) + "\n"); err != nil {
615 return "", fmt.Errorf("Error write into temporary env file: %s", err.Error())
618 log.Warnf("Error while decoding line %s", ln)
630 return envFileName, nil