debug.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*
  2. * ECAL
  3. *
  4. * Copyright 2020 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the MIT
  7. * License, If a copy of the MIT License was not distributed with this
  8. * file, You can obtain one at https://opensource.org/licenses/MIT.
  9. */
  10. package tool
  11. import (
  12. "bufio"
  13. "bytes"
  14. "encoding/base64"
  15. "encoding/json"
  16. "flag"
  17. "fmt"
  18. "net"
  19. "strings"
  20. "time"
  21. "devt.de/krotik/common/errorutil"
  22. "devt.de/krotik/common/stringutil"
  23. "devt.de/krotik/ecal/interpreter"
  24. "devt.de/krotik/ecal/util"
  25. )
  26. /*
  27. CLIDebugInterpreter is a commandline interpreter with debug capabilities for ECAL.
  28. */
  29. type CLIDebugInterpreter struct {
  30. *CLIInterpreter
  31. // Parameter these can either be set programmatically or via CLI args
  32. DebugServerAddr *string // Debug server address
  33. RunDebugServer *bool // Run a debug server
  34. EchoDebugServer *bool // Echo all input and output of the debug server
  35. Interactive *bool // Flag if the interpreter should open a console in the current tty.
  36. BreakOnStart *bool // Flag if the debugger should stop the execution on start
  37. BreakOnError *bool // Flag if the debugger should stop when encountering an error
  38. }
  39. /*
  40. NewCLIDebugInterpreter wraps an existing CLIInterpreter object and adds capabilities.
  41. */
  42. func NewCLIDebugInterpreter(i *CLIInterpreter) *CLIDebugInterpreter {
  43. return &CLIDebugInterpreter{i, nil, nil, nil, nil, nil, nil}
  44. }
  45. /*
  46. ParseArgs parses the command line arguments.
  47. */
  48. func (i *CLIDebugInterpreter) ParseArgs() bool {
  49. if i.Interactive != nil {
  50. return false
  51. }
  52. i.DebugServerAddr = flag.String("serveraddr", "localhost:33274", "Debug server address") // Think BERTA
  53. i.RunDebugServer = flag.Bool("server", false, "Run a debug server")
  54. i.EchoDebugServer = flag.Bool("echo", false, "Echo all i/o of the debug server")
  55. i.Interactive = flag.Bool("interactive", true, "Run interactive console")
  56. i.BreakOnStart = flag.Bool("breakonstart", false, "Stop the execution on start")
  57. i.BreakOnError = flag.Bool("breakonerror", false, "Stop the execution when encountering an error")
  58. return i.CLIInterpreter.ParseArgs()
  59. }
  60. /*
  61. Interpret starts the ECAL code interpreter with debug capabilities.
  62. */
  63. func (i *CLIDebugInterpreter) Interpret() error {
  64. if i.ParseArgs() {
  65. return nil
  66. }
  67. err := i.CreateRuntimeProvider("debug console")
  68. if err == nil {
  69. // Set custom messages
  70. i.CLIInterpreter.CustomWelcomeMessage = "Running in debug mode - "
  71. if *i.RunDebugServer {
  72. i.CLIInterpreter.CustomWelcomeMessage += fmt.Sprintf("with debug server on %v - ", *i.DebugServerAddr)
  73. }
  74. i.CLIInterpreter.CustomWelcomeMessage += "prefix debug commands with ##"
  75. i.CustomHelpString = " @dbg [glob] - List all available debug commands.\n"
  76. // Set debug object on the runtime provider
  77. i.RuntimeProvider.Debugger = interpreter.NewECALDebugger(i.GlobalVS)
  78. i.RuntimeProvider.Debugger.BreakOnStart(*i.BreakOnStart)
  79. i.RuntimeProvider.Debugger.BreakOnError(*i.BreakOnError)
  80. // Set this object as a custom handler to deal with input.
  81. i.CustomHandler = i
  82. if *i.RunDebugServer {
  83. // Start the debug server
  84. debugServer := &debugTelnetServer{*i.DebugServerAddr, "ECALDebugServer: ",
  85. nil, true, *i.EchoDebugServer, i, i.RuntimeProvider.Logger}
  86. go debugServer.Run()
  87. time.Sleep(500 * time.Millisecond) // Too lazy to do proper signalling
  88. defer func() {
  89. if debugServer.listener != nil {
  90. debugServer.listen = false
  91. debugServer.listener.Close() // Attempt to cleanup
  92. }
  93. }()
  94. }
  95. err = i.CLIInterpreter.Interpret(*i.Interactive)
  96. }
  97. return err
  98. }
  99. /*
  100. LoadInitialFile clears the global scope and reloads the initial file.
  101. */
  102. func (i *CLIDebugInterpreter) LoadInitialFile(tid uint64) error {
  103. i.RuntimeProvider.Debugger.StopThreads(500 * time.Millisecond)
  104. i.RuntimeProvider.Debugger.BreakOnStart(*i.BreakOnStart)
  105. i.RuntimeProvider.Debugger.BreakOnError(*i.BreakOnError)
  106. return nil
  107. }
  108. /*
  109. CanHandle checks if a given string can be handled by this handler.
  110. */
  111. func (i *CLIDebugInterpreter) CanHandle(s string) bool {
  112. return strings.HasPrefix(s, "##") || strings.HasPrefix(s, "@dbg")
  113. }
  114. /*
  115. Handle handles a given input string.
  116. */
  117. func (i *CLIDebugInterpreter) Handle(ot OutputTerminal, line string) {
  118. if strings.HasPrefix(line, "@dbg") {
  119. args := strings.Fields(line)[1:]
  120. tabData := []string{"Debug command", "Description"}
  121. for name, f := range interpreter.DebugCommandsMap {
  122. ds := f.DocString()
  123. if len(args) > 0 && !matchesFulltextSearch(ot, fmt.Sprintf("%v %v", name, ds), args[0]) {
  124. continue
  125. }
  126. tabData = fillTableRow(tabData, name, ds)
  127. }
  128. if len(tabData) > 2 {
  129. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  130. stringutil.SingleDoubleLineTable))
  131. }
  132. ot.WriteString(fmt.Sprintln(fmt.Sprintln()))
  133. } else {
  134. res, err := i.RuntimeProvider.Debugger.HandleInput(strings.TrimSpace(line[2:]))
  135. if err == nil {
  136. var outBytes []byte
  137. outBytes, err = json.MarshalIndent(res, "", " ")
  138. if err == nil {
  139. ot.WriteString(fmt.Sprintln(fmt.Sprintln(string(outBytes))))
  140. }
  141. }
  142. if err != nil {
  143. var outBytes []byte
  144. outBytes, err = json.MarshalIndent(map[string]interface{}{
  145. "DebuggerError": err.Error(),
  146. }, "", " ")
  147. errorutil.AssertOk(err)
  148. ot.WriteString(fmt.Sprintln(fmt.Sprintln(string(outBytes))))
  149. }
  150. }
  151. }
  152. /*
  153. debugTelnetServer is a simple telnet server to send and receive debug data.
  154. */
  155. type debugTelnetServer struct {
  156. address string
  157. logPrefix string
  158. listener *net.TCPListener
  159. listen bool
  160. echo bool
  161. interpreter *CLIDebugInterpreter
  162. logger util.Logger
  163. }
  164. /*
  165. Run runs the debug server.
  166. */
  167. func (s *debugTelnetServer) Run() {
  168. tcpaddr, err := net.ResolveTCPAddr("tcp", s.address)
  169. if err == nil {
  170. if s.listener, err = net.ListenTCP("tcp", tcpaddr); err == nil {
  171. s.logger.LogInfo(s.logPrefix,
  172. "Running Debug Server on ", tcpaddr.String())
  173. for s.listen {
  174. var conn net.Conn
  175. if conn, err = s.listener.Accept(); err == nil {
  176. go s.HandleConnection(conn)
  177. } else if s.listen {
  178. s.logger.LogError(s.logPrefix, err)
  179. err = nil
  180. }
  181. }
  182. }
  183. }
  184. if s.listen && err != nil {
  185. s.logger.LogError(s.logPrefix, "Could not start debug server - ", err)
  186. }
  187. }
  188. /*
  189. HandleConnection handles an incoming connection.
  190. */
  191. func (s *debugTelnetServer) HandleConnection(conn net.Conn) {
  192. tid := s.interpreter.RuntimeProvider.NewThreadID()
  193. inputReader := bufio.NewReader(conn)
  194. outputTerminal := OutputTerminal(&bufioWriterShim{fmt.Sprint(conn.RemoteAddr()), bufio.NewWriter(conn), s.echo})
  195. line := ""
  196. s.logger.LogDebug(s.logPrefix, "Connect ", conn.RemoteAddr())
  197. if s.echo {
  198. fmt.Println(fmt.Sprintf("%v : Connected", conn.RemoteAddr()))
  199. }
  200. for {
  201. var outBytes []byte
  202. var err error
  203. if line, err = inputReader.ReadString('\n'); err == nil {
  204. line = strings.TrimSpace(line)
  205. if s.echo {
  206. fmt.Println(fmt.Sprintf("%v > %v", conn.RemoteAddr(), line))
  207. }
  208. if line == "exit" || line == "q" || line == "quit" || line == "bye" || line == "\x04" {
  209. break
  210. }
  211. isHelpTable := strings.HasPrefix(line, "@")
  212. if !s.interpreter.CanHandle(line) || isHelpTable {
  213. buffer := bytes.NewBuffer(nil)
  214. s.interpreter.HandleInput(&bufioWriterShim{"tmpbuffer", bufio.NewWriter(buffer), false}, line, tid)
  215. if isHelpTable {
  216. // Special case we have tables which should be transformed
  217. r := strings.NewReplacer("═", "*", "│", "*", "╪", "*", "╒", "*",
  218. "╕", "*", "╘", "*", "╛", "*", "╤", "*", "╞", "*", "╡", "*", "╧", "*")
  219. outBytes = []byte(r.Replace(buffer.String()))
  220. } else {
  221. outBytes = buffer.Bytes()
  222. }
  223. outBytes, err = json.MarshalIndent(map[string]interface{}{
  224. "EncodedOutput": base64.StdEncoding.EncodeToString(outBytes),
  225. }, "", " ")
  226. errorutil.AssertOk(err)
  227. outputTerminal.WriteString(fmt.Sprintln(fmt.Sprintln(string(outBytes))))
  228. } else {
  229. s.interpreter.HandleInput(outputTerminal, line, tid)
  230. }
  231. }
  232. if err != nil {
  233. if s.echo {
  234. fmt.Println(fmt.Sprintf("%v : Disconnected", conn.RemoteAddr()))
  235. }
  236. s.logger.LogDebug(s.logPrefix, "Disconnect ", conn.RemoteAddr(), " - ", err)
  237. break
  238. }
  239. }
  240. conn.Close()
  241. }
  242. /*
  243. bufioWriterShim is a shim to allow a bufio.Writer to be used as an OutputTerminal.
  244. */
  245. type bufioWriterShim struct {
  246. id string
  247. writer *bufio.Writer
  248. echo bool
  249. }
  250. /*
  251. WriteString write a string to the writer.
  252. */
  253. func (shim *bufioWriterShim) WriteString(s string) {
  254. if shim.echo {
  255. fmt.Println(fmt.Sprintf("%v < %v", shim.id, s))
  256. }
  257. shim.writer.WriteString(s)
  258. shim.writer.Flush()
  259. }