debug.go 8.6 KB

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