debug.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. // Log output
  42. LogOut io.Writer
  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}
  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. debugServer := &debugTelnetServer{*i.DebugServerAddr, "ECALDebugServer: ",
  90. nil, true, *i.EchoDebugServer, i, i.RuntimeProvider.Logger}
  91. wg := &sync.WaitGroup{}
  92. wg.Add(1)
  93. go debugServer.Run(wg)
  94. wg.Wait()
  95. defer func() {
  96. if debugServer.listener != nil {
  97. debugServer.listen = false
  98. debugServer.listener.Close() // Attempt to cleanup
  99. }
  100. }()
  101. }
  102. err = i.CLIInterpreter.Interpret(*i.Interactive)
  103. }
  104. return err
  105. }
  106. /*
  107. LoadInitialFile clears the global scope and reloads the initial file.
  108. */
  109. func (i *CLIDebugInterpreter) LoadInitialFile(tid uint64) error {
  110. i.RuntimeProvider.Debugger.StopThreads(500 * time.Millisecond)
  111. i.RuntimeProvider.Debugger.BreakOnStart(*i.BreakOnStart)
  112. i.RuntimeProvider.Debugger.BreakOnError(*i.BreakOnError)
  113. return nil
  114. }
  115. /*
  116. CanHandle checks if a given string can be handled by this handler.
  117. */
  118. func (i *CLIDebugInterpreter) CanHandle(s string) bool {
  119. return strings.HasPrefix(s, "##") || strings.HasPrefix(s, "@dbg")
  120. }
  121. /*
  122. Handle handles a given input string.
  123. */
  124. func (i *CLIDebugInterpreter) Handle(ot OutputTerminal, line string) {
  125. if strings.HasPrefix(line, "@dbg") {
  126. args := strings.Fields(line)[1:]
  127. tabData := []string{"Debug command", "Description"}
  128. for name, f := range interpreter.DebugCommandsMap {
  129. ds := f.DocString()
  130. if len(args) > 0 && !matchesFulltextSearch(ot, fmt.Sprintf("%v %v", name, ds), args[0]) {
  131. continue
  132. }
  133. tabData = fillTableRow(tabData, name, ds)
  134. }
  135. if len(tabData) > 2 {
  136. ot.WriteString(stringutil.PrintGraphicStringTable(tabData, 2, 1,
  137. stringutil.SingleDoubleLineTable))
  138. }
  139. ot.WriteString(fmt.Sprintln(fmt.Sprintln()))
  140. } else {
  141. res, err := i.RuntimeProvider.Debugger.HandleInput(strings.TrimSpace(line[2:]))
  142. if err == nil {
  143. var outBytes []byte
  144. outBytes, err = json.MarshalIndent(res, "", " ")
  145. if err == nil {
  146. ot.WriteString(fmt.Sprintln(fmt.Sprintln(string(outBytes))))
  147. }
  148. }
  149. if err != nil {
  150. var outBytes []byte
  151. outBytes, err = json.MarshalIndent(map[string]interface{}{
  152. "DebuggerError": err.Error(),
  153. }, "", " ")
  154. errorutil.AssertOk(err)
  155. ot.WriteString(fmt.Sprintln(fmt.Sprintln(string(outBytes))))
  156. }
  157. }
  158. }
  159. /*
  160. debugTelnetServer is a simple telnet server to send and receive debug data.
  161. */
  162. type debugTelnetServer struct {
  163. address string
  164. logPrefix string
  165. listener *net.TCPListener
  166. listen bool
  167. echo bool
  168. interpreter *CLIDebugInterpreter
  169. logger util.Logger
  170. }
  171. /*
  172. Run runs the debug server.
  173. */
  174. func (s *debugTelnetServer) Run(wg *sync.WaitGroup) {
  175. tcpaddr, err := net.ResolveTCPAddr("tcp", s.address)
  176. if err == nil {
  177. s.listener, err = net.ListenTCP("tcp", tcpaddr)
  178. if err == nil {
  179. wg.Done()
  180. s.logger.LogInfo(s.logPrefix,
  181. "Running Debug Server on ", tcpaddr.String())
  182. for s.listen {
  183. var conn net.Conn
  184. if conn, err = s.listener.Accept(); err == nil {
  185. go s.HandleConnection(conn)
  186. } else if s.listen {
  187. s.logger.LogError(s.logPrefix, err)
  188. err = nil
  189. }
  190. }
  191. }
  192. }
  193. if s.listen && err != nil {
  194. s.logger.LogError(s.logPrefix, "Could not start debug server - ", err)
  195. wg.Done()
  196. }
  197. }
  198. /*
  199. HandleConnection handles an incoming connection.
  200. */
  201. func (s *debugTelnetServer) HandleConnection(conn net.Conn) {
  202. tid := s.interpreter.RuntimeProvider.NewThreadID()
  203. inputReader := bufio.NewReader(conn)
  204. outputTerminal := OutputTerminal(&bufioWriterShim{fmt.Sprint(conn.RemoteAddr()),
  205. bufio.NewWriter(conn), s.echo, s.interpreter.LogOut})
  206. line := ""
  207. s.logger.LogDebug(s.logPrefix, "Connect ", conn.RemoteAddr())
  208. if s.echo {
  209. fmt.Fprintln(s.interpreter.LogOut, fmt.Sprintf("%v : Connected", conn.RemoteAddr()))
  210. }
  211. for {
  212. var outBytes []byte
  213. var err error
  214. if line, err = inputReader.ReadString('\n'); err == nil {
  215. line = strings.TrimSpace(line)
  216. if s.echo {
  217. fmt.Fprintln(s.interpreter.LogOut, fmt.Sprintf("%v > %v", conn.RemoteAddr(), line))
  218. }
  219. if line == "exit" || line == "q" || line == "quit" || line == "bye" || line == "\x04" {
  220. break
  221. }
  222. isHelpTable := strings.HasPrefix(line, "@")
  223. if !s.interpreter.CanHandle(line) || isHelpTable {
  224. buffer := bytes.NewBuffer(nil)
  225. s.interpreter.HandleInput(&bufioWriterShim{"tmpbuffer",
  226. bufio.NewWriter(buffer), false, s.interpreter.LogOut}, line, tid)
  227. if isHelpTable {
  228. // Special case we have tables which should be transformed
  229. r := strings.NewReplacer("═", "*", "│", "*", "╪", "*", "╒", "*",
  230. "╕", "*", "╘", "*", "╛", "*", "╤", "*", "╞", "*", "╡", "*", "╧", "*")
  231. outBytes = []byte(r.Replace(buffer.String()))
  232. } else {
  233. outBytes = buffer.Bytes()
  234. }
  235. outBytes, err = json.MarshalIndent(map[string]interface{}{
  236. "EncodedOutput": base64.StdEncoding.EncodeToString(outBytes),
  237. }, "", " ")
  238. errorutil.AssertOk(err)
  239. outputTerminal.WriteString(fmt.Sprintln(fmt.Sprintln(string(outBytes))))
  240. } else {
  241. s.interpreter.HandleInput(outputTerminal, line, tid)
  242. }
  243. }
  244. if err != nil {
  245. if s.echo {
  246. fmt.Fprintln(s.interpreter.LogOut, fmt.Sprintf("%v : Disconnected", conn.RemoteAddr()))
  247. }
  248. s.logger.LogDebug(s.logPrefix, "Disconnect ", conn.RemoteAddr(), " - ", err)
  249. break
  250. }
  251. }
  252. conn.Close()
  253. }
  254. /*
  255. bufioWriterShim is a shim to allow a bufio.Writer to be used as an OutputTerminal.
  256. */
  257. type bufioWriterShim struct {
  258. id string
  259. writer *bufio.Writer
  260. echo bool
  261. logOut io.Writer
  262. }
  263. /*
  264. WriteString write a string to the writer.
  265. */
  266. func (shim *bufioWriterShim) WriteString(s string) {
  267. if shim.echo {
  268. fmt.Fprintln(shim.logOut, fmt.Sprintf("%v < %v", shim.id, s))
  269. }
  270. shim.writer.WriteString(s)
  271. shim.writer.Flush()
  272. }