ecalDebugClient.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. /**
  2. * Debug client implementation for the ECAL debugger.
  3. */
  4. import * as net from "net";
  5. import { EventEmitter } from "events";
  6. import PromiseSocket from "promise-socket";
  7. import { LogOutputStream, DebugStatus, ThreadInspection } from "./types";
  8. interface BacklogCommand {
  9. cmd: string;
  10. args?: string[];
  11. }
  12. /**
  13. * Debug client for ECAL debug server.
  14. */
  15. export class ECALDebugClient extends EventEmitter {
  16. private socket: PromiseSocket<net.Socket>;
  17. private socketLock: any;
  18. private connected: boolean = false;
  19. private backlog: BacklogCommand[] = [];
  20. private threadInspection: Record<number, ThreadInspection> = {};
  21. /**
  22. * Create a new debug client.
  23. */
  24. public constructor(protected out: LogOutputStream) {
  25. super();
  26. this.socket = new PromiseSocket(new net.Socket());
  27. const AsyncLock = require("async-lock");
  28. this.socketLock = new AsyncLock();
  29. }
  30. public async conect(host: string, port: number) {
  31. try {
  32. this.out.log(`Connecting to: ${host}:${port}`);
  33. await this.socket.connect({ port, host });
  34. // this.socket.setTimeout(2000);
  35. this.connected = true;
  36. this.pollEvents(); // Start emitting events
  37. } catch (e) {
  38. this.out.error(`Could not connect to debug server: ${e}`);
  39. }
  40. }
  41. public async status(): Promise<DebugStatus | null> {
  42. try {
  43. return (await this.sendCommand("status")) as DebugStatus;
  44. } catch (e) {
  45. this.out.error(`Could not query for status: ${e}`);
  46. return null;
  47. }
  48. }
  49. public async inspect(tid: number): Promise<ThreadInspection | null> {
  50. try {
  51. return (await this.sendCommand("inspect", [
  52. String(tid),
  53. ])) as ThreadInspection;
  54. } catch (e) {
  55. this.out.error(`Could not inspect thread ${tid}: ${e}`);
  56. return null;
  57. }
  58. }
  59. public async setBreakpoint(breakpoint: string) {
  60. try {
  61. (await this.sendCommand(`break ${breakpoint}`)) as DebugStatus;
  62. } catch (e) {
  63. this.out.error(`Could not set breakpoint ${breakpoint}: ${e}`);
  64. }
  65. }
  66. public async clearBreakpoints(source: string) {
  67. try {
  68. (await this.sendCommand("rmbreak", [source])) as DebugStatus;
  69. } catch (e) {
  70. this.out.error(`Could not remove breakpoints for ${source}: ${e}`);
  71. }
  72. }
  73. public async shutdown() {
  74. this.connected = false;
  75. await this.socket.destroy();
  76. }
  77. /**
  78. * PollEvents is the polling loop for debug events.
  79. */
  80. private async pollEvents() {
  81. let nextLoop = 1000;
  82. try {
  83. const status = await this.status();
  84. this.emit("status", status);
  85. for (const [tidString, thread] of Object.entries(status?.threads || [])) {
  86. const tid = parseInt(tidString);
  87. if (thread.threadRunning === false && !this.threadInspection[tid]) {
  88. console.log("#### Thread was stopped!!");
  89. // A thread was stopped inspect it
  90. let inspection: ThreadInspection = {
  91. callstack: [],
  92. threadRunning: false,
  93. };
  94. try {
  95. inspection = (await this.sendCommand("describe", [
  96. String(tid),
  97. ])) as ThreadInspection;
  98. } catch (e) {
  99. this.out.error(`Could not get description for ${tid}: ${e}`);
  100. }
  101. this.threadInspection[tid] = inspection;
  102. this.emit("pauseOnBreakpoint", { tid, inspection });
  103. }
  104. }
  105. } catch (e) {
  106. this.out.error(`Error during event loop: ${e}`);
  107. nextLoop = 5000;
  108. }
  109. if (this.connected) {
  110. setTimeout(this.pollEvents.bind(this), nextLoop);
  111. } else {
  112. this.out.log("Stop emitting events" + nextLoop);
  113. }
  114. }
  115. public async sendCommand(cmd: string, args?: string[]): Promise<any> {
  116. // Create or process the backlog depending on the connection status
  117. if (!this.connected) {
  118. this.backlog.push({
  119. cmd,
  120. args,
  121. });
  122. return null;
  123. } else if (this.backlog.length > 0) {
  124. const backlog = this.backlog;
  125. this.backlog = [];
  126. for (const item of backlog) {
  127. await this.sendCommand(item.cmd, item.args);
  128. }
  129. }
  130. return await this.sendCommandString(
  131. `##${cmd} ${args ? args.join(" ") : ""}\r\n`
  132. );
  133. }
  134. public async sendCommandString(cmdString: string): Promise<any> {
  135. // Socket needs to be locked. Reading and writing to the socket is seen
  136. // by the interpreter as async (i/o bound) code. Separate calls to
  137. // sendCommand will be executed in different event loops. Without the lock
  138. // the different sendCommand calls would mix their responses.
  139. return await this.socketLock.acquire("socket", async () => {
  140. await this.socket.write(cmdString, "utf8");
  141. let text = "";
  142. while (!text.endsWith("\n\n")) {
  143. text += await this.socket.read(1);
  144. }
  145. let res: any = {};
  146. try {
  147. res = JSON.parse(text);
  148. } catch (e) {
  149. throw new Error(`Could not parse response: ${text} - error:${e}`);
  150. }
  151. if (res?.DebuggerError) {
  152. throw new Error(
  153. `Unexpected internal error for command "${cmdString}": ${res.DebuggerError}`
  154. );
  155. }
  156. if (res?.EncodedOutput !== undefined) {
  157. res = Buffer.from(res.EncodedOutput, "base64").toString("utf8");
  158. }
  159. return res;
  160. });
  161. }
  162. }