debug.go 8.1 KB

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