debug.go 8.9 KB

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