495a644541c5a6c96cc4e1640af2ffdca9666719
[src/xds/xds-gdb.git] / main.go
1 // xds-gdb: a wrapper on gdb tool for X(cross) Development System.
2 package main
3
4 import (
5         "bufio"
6         "fmt"
7         "io/ioutil"
8         "os"
9         "os/signal"
10         "os/user"
11         "syscall"
12         "time"
13
14         "strings"
15
16         "path"
17
18         "github.com/Sirupsen/logrus"
19         "github.com/codegangsta/cli"
20         common "github.com/iotbzh/xds-common/golib"
21         "github.com/joho/godotenv"
22 )
23
24 var appAuthors = []cli.Author{
25         cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
26 }
27
28 // AppName name of this application
29 var AppName = "xds-gdb"
30
31 // AppVersion Version of this application
32 // (set by Makefile)
33 var AppVersion = "?.?.?"
34
35 // AppSubVersion is the git tag id added to version string
36 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
37 // (set by Makefile)
38 var AppSubVersion = "unknown-dev"
39
40 // Create logger
41 var log = logrus.New()
42 var logFileInitial = "/tmp/xds-gdb.log"
43
44 // Application details
45 const (
46         appCopyright    = "Apache-2.0"
47         defaultLogLevel = "warning"
48 )
49
50 // Exit events
51 type exitResult struct {
52         error error
53         code  int
54 }
55
56 // EnvVar - Environment variables used by application
57 type EnvVar struct {
58         Name        string
59         Usage       string
60         Destination *string
61 }
62
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)
68
69         os.Exit(int(code))
70 }
71
72 // main
73 func main() {
74         var uri, prjID, rPath, logLevel, logFile, sdkid, confFile, gdbNative string
75         var listProject bool
76         var err error
77
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)
82         if err != nil {
83                 msgErr := fmt.Sprintf("Cannot create log file %s", logFileInitial)
84                 exitError(syscall.EPERM, msgErr)
85         }
86         log.Formatter = &logrus.TextFormatter{}
87         log.Out = fdL
88         log.Level = logrus.DebugLevel
89
90         uri = "localhost:8000"
91         logLevel = defaultLogLevel
92
93         // Create a new App instance
94         app := cli.NewApp()
95         app.Name = AppName
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
104
105         app.Flags = []cli.Flag{
106                 cli.BoolFlag{
107                         Name:        "list, ls",
108                         Usage:       "list existing xds projects",
109                         Destination: &listProject,
110                 },
111         }
112
113         appEnvVars := []EnvVar{
114                 EnvVar{
115                         Name:        "XDS_CONFIG",
116                         Usage:       "env config file to source on startup",
117                         Destination: &confFile,
118                 },
119                 EnvVar{
120                         Name:        "XDS_LOGLEVEL",
121                         Usage:       "logging level (supported levels: panic, fatal, error, warn, info, debug)",
122                         Destination: &logLevel,
123                 },
124                 EnvVar{
125                         Name:        "XDS_LOGFILE",
126                         Usage:       "logging file",
127                         Destination: &logFile,
128                 },
129                 EnvVar{
130                         Name:        "XDS_NATIVE_GDB",
131                         Usage:       "use native gdb instead of remote XDS server",
132                         Destination: &gdbNative,
133                 },
134                 EnvVar{
135                         Name:        "XDS_PROJECT_ID",
136                         Usage:       "project ID you want to build (mandatory variable)",
137                         Destination: &prjID,
138                 },
139                 EnvVar{
140                         Name:        "XDS_RPATH",
141                         Usage:       "relative path into project",
142                         Destination: &rPath,
143                 },
144                 EnvVar{
145                         Name:        "XDS_SDK_ID",
146                         Usage:       "Cross Sdk ID to use to build project",
147                         Destination: &sdkid,
148                 },
149                 EnvVar{
150                         Name:        "XDS_SERVER_URL",
151                         Usage:       "remote XDS server url",
152                         Destination: &uri,
153                 },
154         }
155
156         // Process gdb arguments
157         log.Debugf("xds-gdb started with args: %v", os.Args)
158         args := make([]string, len(os.Args))
159         args[0] = os.Args[0]
160         gdbArgs := make([]string, len(os.Args))
161
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
166                 switch a {
167                 case "--help", "-h", "--version", "-v":
168                         args[1] = a
169                         goto endloop
170                 case "--":
171                         // Detect skip option (IOW '--') to split arguments
172                         copy(args, os.Args[0:idx+1])
173                         copy(gdbArgs, os.Args[idx+2:])
174                         goto endloop
175                 }
176         }
177 endloop:
178
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
182         clientPty := ""
183         gdbCmdFile := ""
184         for idx, a := range gdbArgs {
185                 switch {
186                 case strings.HasPrefix(a, "--tty="):
187                         clientPty = a[len("--tty="):]
188                         gdbArgs[idx] = ""
189
190                 case a == "--tty":
191                 case strings.HasPrefix(a, "-tty"):
192                         clientPty = gdbArgs[idx+1]
193                         gdbArgs[idx] = ""
194                         gdbArgs[idx+1] = ""
195
196                 case strings.HasPrefix(a, "--command="):
197                         gdbCmdFile = a[len("--command="):]
198
199                 case a == "--command":
200                 case strings.HasPrefix(a, "-x"):
201                         gdbCmdFile = gdbArgs[idx+1]
202                 }
203         }
204
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
209         // Only rise an error when args is not set (IOW when --help or --version is not set)
210         if len(args) == 1 {
211                 if err != nil {
212                         exitError(syscall.ENOENT, err.Error())
213                 }
214         }
215
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
222                 }
223         }
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"
241
242         // only one action
243         app.Action = func(ctx *cli.Context) error {
244                 var err error
245                 curDir, _ := os.Getwd()
246
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))
251                 }
252                 log.Infof("Switch log level to %s", logLevel)
253
254                 if logFile != logFileInitial {
255                         log.Infof("Switch logging to log file %s", logFile)
256
257                         fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
258                         if err != nil {
259                                 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
260                                 return cli.NewExitError(msgErr, int(syscall.EPERM))
261                         }
262                         defer fdL.Close()
263                         log.Out = fdL
264                 }
265
266                 // Build env variables
267                 env := []string{}
268                 for k, v := range envMap {
269                         env = append(env, k+"="+v)
270                 }
271
272                 // Create cross or native gdb interface
273                 var gdb IGDB
274                 if gdbNative != "" {
275                         gdb = NewGdbNative(log, gdbArgs, env)
276                 } else {
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)
283                 }
284
285                 // Log useful info
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())
290
291                 // Properly report invalid init file error
292                 gdbCommandFileError := ""
293                 for i, a := range gdbArgs {
294                         if a == "-x" {
295                                 gdbCommandFileError = gdbArgs[i+1] + ": No such file or directory."
296                                 break
297                         } else if strings.HasPrefix(a, "--command=") {
298                                 gdbCommandFileError = strings.TrimLeft(a, "--command=") + ": No such file or directory."
299                                 break
300                         }
301                 }
302                 log.Infof("Add detection of error: <%s>", gdbCommandFileError)
303
304                 // Init gdb subprocess management
305                 if code, err := gdb.Init(); err != nil {
306                         return cli.NewExitError(err.Error(), code)
307                 }
308
309                 exitChan := make(chan exitResult, 1)
310
311                 gdb.OnError(func(err error) {
312                         fmt.Println("ERROR: ", err.Error())
313                 })
314
315                 gdb.OnDisconnect(func(err error) {
316                         fmt.Println("Disconnection: ", err.Error())
317                         exitChan <- exitResult{err, int(syscall.ESHUTDOWN)}
318                 })
319
320                 gdb.Read(func(timestamp, stdout, stderr string) {
321                         if stdout != "" {
322                                 fmt.Printf("%s", stdout)
323                                 log.Debugf("Recv OUT: <%s>", stdout)
324                         }
325                         if stderr != "" {
326                                 fmt.Fprintf(os.Stderr, "%s", stderr)
327                                 log.Debugf("Recv ERR: <%s>", stderr)
328                         }
329
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())
336                                 }
337                                 exitChan <- exitResult{err, int(syscall.ENOENT)}
338                         }
339                 })
340
341                 gdb.OnExit(func(code int, err error) {
342                         exitChan <- exitResult{err, code}
343                 })
344
345                 // Handle client tty / pts
346                 if clientPty != "" {
347                         log.Infoln("Client tty detected: %v\n", clientPty)
348
349                         cpFd, err := os.OpenFile(clientPty, os.O_RDWR, 0)
350                         if err != nil {
351                                 return cli.NewExitError(err.Error(), int(syscall.EPERM))
352                         }
353                         defer cpFd.Close()
354
355                         // client tty stdin
356                         /* XXX TODO - implement stdin to send data to debugged program
357                         go func() {
358                                 reader := bufio.NewReader(cpFd)
359                                 sc := bufio.NewScanner(reader)
360                                 for sc.Scan() {
361                                         data := sc.Text()
362                                         iosk.Emit(apiv1.ExecInferiorInEvent, data+"\n")
363                                         log.Debugf("Inferior IN: <%v>", data)
364                                 }
365                                 if sc.Err() != nil {
366                                         log.Warnf("Inferior Stdin scanner exit, close stdin (err=%v)", sc.Err())
367                                 }
368                         }()
369                         */
370
371                         // client tty stdout
372                         gdb.InferiorRead(func(timestamp, stdout, stderr string) {
373                                 if stdout != "" {
374                                         fmt.Fprintf(cpFd, "%s", stdout)
375                                         log.Debugf("Inferior OUT: <%s>", stdout)
376                                 }
377                                 if stderr != "" {
378                                         fmt.Fprintf(cpFd, "%s", stderr)
379                                         log.Debugf("Inferior ERR: <%s>", stderr)
380                                 }
381                         })
382                 }
383
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])
393                                         } else {
394                                                 return cli.NewExitError(
395                                                         fmt.Errorf("Invalid definition in XDS_OVERWRITE_COMMANDS (%s)", def),
396                                                         int(syscall.EINVAL))
397                                         }
398                                 }
399                         }
400                 } else {
401                         overwriteMap["-exec-run"] = "-exec-continue"
402                         overwriteMap["-file-exec-and-symbols"] = "-file-exec-file"
403                 }
404                 log.Debugf("overwriteMap = %v", overwriteMap)
405
406                 // Send stdin though WS
407                 go func() {
408                         paranoia := 600
409                         reader := bufio.NewReader(os.Stdin)
410
411                         for {
412                                 sc := bufio.NewScanner(reader)
413                                 for sc.Scan() {
414                                         command := sc.Text()
415
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)
421                                                 }
422                                         }
423                                         gdb.Write(command + "\n")
424                                         log.Debugf("Send: <%v>", command)
425                                 }
426                                 log.Infof("Stdin scanner exit, close stdin (err=%v)", sc.Err())
427
428                                 // CTRL-D exited scanner, so send it explicitly
429                                 gdb.Write("\x04")
430                                 time.Sleep(time.Millisecond * 100)
431
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)}
437                                 }
438                         }
439                 }()
440
441                 // Handling all Signals
442                 sigs := make(chan os.Signal, 1)
443                 signal.Notify(sigs)
444
445                 go func() {
446                         for {
447                                 sig := <-sigs
448                                 if err := gdb.SendSignal(sig); err != nil {
449                                         log.Errorf("Error while sending signal: %s", err.Error())
450                                 }
451                         }
452                 }()
453
454                 // Start gdb
455                 if code, err := gdb.Start(clientPty != ""); err != nil {
456                         return cli.NewExitError(err.Error(), code)
457                 }
458
459                 // Wait exit
460                 select {
461                 case res := <-exitChan:
462                         errStr := ""
463                         if res.code == 0 {
464                                 log.Infoln("Exit successfully")
465                         }
466                         if res.error != nil {
467                                 log.Infoln("Exit with ERROR: ", res.error.Error())
468                                 errStr = res.error.Error()
469                         }
470                         return cli.NewExitError(errStr, res.code)
471                 }
472         }
473
474         app.Run(args)
475 }
476
477 // loadConfigEnvFile
478 func loadConfigEnvFile(confFile, gdbCmdFile string) (map[string]string, string, error) {
479         var err error
480         envMap := make(map[string]string)
481
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)
487                 if confFile != "" {
488                         defer os.Remove(confFile)
489                 }
490                 if err != nil {
491                         return envMap, confFile, fmt.Errorf(err.Error())
492                 }
493         }
494         // 2- search xds-gdb.env file in various locations
495         if confFile == "" {
496                 curDir, _ := os.Getwd()
497                 if u, err := user.Current(); err == nil {
498                         xdsEnvFile := "xds-gdb.env"
499                         for _, d := range []string{
500                                 path.Join(curDir),
501                                 path.Join(curDir, "..", ".."),
502                                 path.Join(curDir, "../../target"),
503                                 path.Join(u.HomeDir, ".xds"),
504                         } {
505                                 confFile = path.Join(d, xdsEnvFile)
506                                 log.Infof("Search config in %s", confFile)
507                                 if common.Exists(confFile) {
508                                         break
509                                 }
510                         }
511                 }
512         }
513
514         if confFile == "" {
515                 log.Infof("NO valid conf file found!")
516                 return envMap, "", nil
517         }
518
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")
522         }
523         if err = godotenv.Load(confFile); err != nil {
524                 return envMap, confFile, fmt.Errorf("Error loading env config file " + confFile)
525         }
526         if envMap, err = godotenv.Read(confFile); err != nil {
527                 return envMap, confFile, fmt.Errorf("Error reading env config file " + confFile)
528         }
529         return envMap, confFile, nil
530 }
531
532 /*
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
536   are supported:
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
540 */
541 func extractEnvFromCmdFile(cmdFile string) (string, error) {
542         if !common.Exists(cmdFile) {
543                 return "", nil
544         }
545         cFd, err := os.Open(cmdFile)
546         if err != nil {
547                 return "", fmt.Errorf("Cannot open %s : %s", cmdFile, err.Error())
548         }
549         defer cFd.Close()
550
551         var lines []string
552         scanner := bufio.NewScanner(cFd)
553         for scanner.Scan() {
554                 lines = append(lines, scanner.Text())
555         }
556         if err = scanner.Err(); err != nil {
557                 return "", fmt.Errorf("Cannot parse %s : %s", cmdFile, err.Error())
558         }
559
560         envFile, err := ioutil.TempFile("", "xds-gdb_env.ini")
561         if err != nil {
562                 return "", fmt.Errorf("Error while creating temporary env file: %s", err.Error())
563         }
564         envFileName := envFile.Name()
565         defer envFile.Close()
566
567         envFound := false
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)
572                         if len(env) == 2 {
573                                 envFound = true
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())
576                                 }
577                         } else {
578                                 log.Warnf("Error while decoding line %s", ln)
579                         }
580                 }
581         }
582
583         if !envFound {
584                 ff := envFileName
585                 defer os.Remove(ff)
586                 envFileName = ""
587
588         }
589
590         return envFileName, nil
591 }