-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathmi2.ts
More file actions
824 lines (759 loc) · 25.4 KB
/
mi2.ts
File metadata and controls
824 lines (759 loc) · 25.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
import { Breakpoint, IBackend, Thread, Stack, SSHArguments, Variable, VariableObject, MIError } from "../backend";
import * as ChildProcess from "child_process";
import { EventEmitter } from "events";
import { parseMI, MINode } from '../mi_parse';
import * as linuxTerm from '../linux/console';
import * as net from "net";
import * as fs from "fs";
import { posix } from "path";
import * as nativePath from "path";
const path = posix;
import { Client } from "ssh2";
export function escape(str: string) {
return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
}
const nonOutput = /^(?:\d*|undefined)[\*\+\=]|[\~\@\&\^]/;
const gdbMatch = /(?:\d*|undefined)\(gdb\)/;
const numRegex = /\d+/;
function couldBeOutput(line: string) {
if (nonOutput.exec(line))
return false;
return true;
}
const trace = false;
export class MI2 extends EventEmitter implements IBackend {
constructor(public application: string, public preargs: string[], public extraargs: string[], procEnv: any, public extraCommands: string[] = []) {
super();
if (procEnv) {
const env = {};
// Duplicate process.env so we don't override it
for (const key in process.env)
if (process.env.hasOwnProperty(key))
env[key] = process.env[key];
// Overwrite with user specified variables
for (const key in procEnv) {
if (procEnv.hasOwnProperty(key)) {
if (procEnv === null)
delete env[key];
else
env[key] = procEnv[key];
}
}
this.procEnv = env;
}
}
load(cwd: string, target: string, procArgs: string, separateConsole: string): Thenable<any> {
if (!nativePath.isAbsolute(target))
target = nativePath.join(cwd, target);
return new Promise((resolve, reject) => {
this.isSSH = false;
const args = this.preargs.concat(this.extraargs || []);
this.process = ChildProcess.spawn(this.application, args, { cwd: cwd, env: this.procEnv });
this.process.stdout.on("data", this.stdout.bind(this));
this.process.stderr.on("data", this.stderr.bind(this));
this.process.on("exit", (() => { this.emit("quit"); }).bind(this));
this.process.on("error", ((err) => { this.emit("launcherror", err); }).bind(this));
const promises = this.initCommands(target, cwd);
if (procArgs && procArgs.length)
promises.push(this.sendCommand("exec-arguments " + procArgs));
if (process.platform == "win32") {
if (separateConsole !== undefined)
promises.push(this.sendCommand("gdb-set new-console on"));
Promise.all(promises).then(() => {
this.emit("debug-ready");
resolve();
}, reject);
} else {
if (separateConsole !== undefined) {
linuxTerm.spawnTerminalEmulator(separateConsole).then(tty => {
promises.push(this.sendCommand("inferior-tty-set " + tty));
Promise.all(promises).then(() => {
this.emit("debug-ready");
resolve();
}, reject);
});
} else {
Promise.all(promises).then(() => {
this.emit("debug-ready");
resolve();
}, reject);
}
}
});
}
ssh(args: SSHArguments, cwd: string, target: string, procArgs: string, separateConsole: string, attach: boolean): Thenable<any> {
return new Promise((resolve, reject) => {
this.isSSH = true;
this.sshReady = false;
this.sshConn = new Client();
if (separateConsole !== undefined)
this.log("stderr", "WARNING: Output to terminal emulators are not supported over SSH");
if (args.forwardX11) {
this.sshConn.on("x11", (info, accept, reject) => {
const xserversock = new net.Socket();
xserversock.on("error", (err) => {
this.log("stderr", "Could not connect to local X11 server! Did you enable it in your display manager?\n" + err);
});
xserversock.on("connect", () => {
const xclientsock = accept();
xclientsock.pipe(xserversock).pipe(xclientsock);
});
xserversock.connect(args.x11port, args.x11host);
});
}
const connectionArgs: any = {
host: args.host,
port: args.port,
username: args.user
};
if (args.useAgent) {
connectionArgs.agent = process.env.SSH_AUTH_SOCK;
} else if (args.keyfile) {
if (require("fs").existsSync(args.keyfile))
connectionArgs.privateKey = require("fs").readFileSync(args.keyfile);
else {
this.log("stderr", "SSH key file does not exist!");
this.emit("quit");
reject();
return;
}
} else {
connectionArgs.password = args.password;
}
this.sshConn.on("ready", () => {
this.log("stdout", "Running " + this.application + " over ssh...");
const execArgs: any = {};
if (args.forwardX11) {
execArgs.x11 = {
single: false,
screen: args.remotex11screen
};
}
let sshCMD = this.application + " " + this.preargs.join(" ");
if (args.bootstrap) sshCMD = args.bootstrap + " && " + sshCMD;
if (attach)
sshCMD += " -p " + target;
this.sshConn.exec(sshCMD, execArgs, (err, stream) => {
if (err) {
this.log("stderr", "Could not run " + this.application + " over ssh!");
this.log("stderr", err.toString());
this.emit("quit");
reject();
return;
}
this.sshReady = true;
this.stream = stream;
stream.on("data", this.stdout.bind(this));
stream.stderr.on("data", this.stderr.bind(this));
stream.on("exit", (() => {
this.emit("quit");
this.sshConn.end();
}).bind(this));
const promises = this.initCommands(target, cwd, true, attach);
promises.push(this.sendCommand("environment-cd \"" + escape(cwd) + "\""));
if (procArgs && procArgs.length && !attach)
promises.push(this.sendCommand("exec-arguments " + procArgs));
Promise.all(promises).then(() => {
this.emit("debug-ready");
resolve();
}, reject);
});
}).on("error", (err) => {
this.log("stderr", "Could not run " + this.application + " over ssh!");
this.log("stderr", err.toString());
this.emit("quit");
reject();
}).connect(connectionArgs);
});
}
protected initCommands(target: string, cwd: string, ssh: boolean = false, attach: boolean = false) {
if (ssh) {
if (!path.isAbsolute(target))
target = path.join(cwd, target);
} else {
if (!nativePath.isAbsolute(target))
target = nativePath.join(cwd, target);
}
const cmds = [
this.sendCommand("gdb-set target-async on", true),
this.sendCommand("environment-directory \"" + escape(cwd) + "\"", true)
];
if (!attach)
cmds.push(this.sendCommand("file-exec-and-symbols \"" + escape(target) + "\""));
if (this.prettyPrint)
cmds.push(this.sendCommand("enable-pretty-printing"));
if (this.multiProcess) {
cmds.push(
this.sendCommand("gdb-set follow-fork-mode parent"),
this.sendCommand("gdb-set detach-on-fork off"),
this.sendCommand("gdb-set non-stop on"),
this.sendCommand("gdb-set schedule-multiple on"),
this.sendCommand("interpreter-exec console \"handle SIGSYS nostop noprint\"")
);
}
for (let cmd of this.extraCommands) {
cmds.push(this.sendCommand(cmd));
return cmds;
}
attach(cwd: string, executable: string, target: string): Thenable<any> {
return new Promise((resolve, reject) => {
let args = [];
if (executable && !nativePath.isAbsolute(executable))
executable = nativePath.join(cwd, executable);
if (!executable)
executable = "-p";
let isExtendedRemote = false;
if (target.startsWith("extended-remote")) {
isExtendedRemote = true;
args = this.preargs;
} else
args = args.concat([executable, target], this.preargs);
this.process = ChildProcess.spawn(this.application, args, { cwd: cwd, env: this.procEnv });
this.process.stdout.on("data", this.stdout.bind(this));
this.process.stderr.on("data", this.stderr.bind(this));
this.process.on("exit", (() => { this.emit("quit"); }).bind(this));
this.process.on("error", ((err) => { this.emit("launcherror", err); }).bind(this));
const commands = [
this.sendCommand("gdb-set target-async on"),
this.sendCommand("environment-directory \"" + escape(cwd) + "\"")
];
if (isExtendedRemote) {
commands.push(this.sendCommand("target-select " + target));
commands.push(this.sendCommand("file-symbol-file \"" + escape(executable) + "\""));
}
Promise.all(commands).then(() => {
this.emit("debug-ready");
resolve();
}, reject);
});
}
connect(cwd: string, executable: string, target: string): Thenable<any> {
return new Promise((resolve, reject) => {
let args = [];
if (executable && !nativePath.isAbsolute(executable))
executable = nativePath.join(cwd, executable);
if (executable)
args = args.concat([executable], this.preargs);
else
args = this.preargs;
this.process = ChildProcess.spawn(this.application, args, { cwd: cwd, env: this.procEnv });
this.process.stdout.on("data", this.stdout.bind(this));
this.process.stderr.on("data", this.stderr.bind(this));
this.process.on("exit", (() => { this.emit("quit"); }).bind(this));
this.process.on("error", ((err) => { this.emit("launcherror", err); }).bind(this));
Promise.all([
this.sendCommand("gdb-set target-async on"),
this.sendCommand("environment-directory \"" + escape(cwd) + "\""),
this.sendCommand("target-select remote " + target)
]).then(() => {
this.emit("debug-ready");
resolve();
}, reject);
});
}
stdout(data) {
if (trace)
this.log("stderr", "stdout: " + data);
if (typeof data == "string")
this.buffer += data;
else
this.buffer += data.toString("utf8");
const end = this.buffer.lastIndexOf('\n');
if (end != -1) {
this.onOutput(this.buffer.substr(0, end));
this.buffer = this.buffer.substr(end + 1);
}
if (this.buffer.length) {
if (this.onOutputPartial(this.buffer)) {
this.buffer = "";
}
}
}
stderr(data) {
if (typeof data == "string")
this.errbuf += data;
else
this.errbuf += data.toString("utf8");
const end = this.errbuf.lastIndexOf('\n');
if (end != -1) {
this.onOutputStderr(this.errbuf.substr(0, end));
this.errbuf = this.errbuf.substr(end + 1);
}
if (this.errbuf.length) {
this.logNoNewLine("stderr", this.errbuf);
this.errbuf = "";
}
}
onOutputStderr(lines) {
lines = <string[]> lines.split('\n');
lines.forEach(line => {
this.log("stderr", line);
});
}
onOutputPartial(line) {
if (couldBeOutput(line)) {
this.logNoNewLine("stdout", line);
return true;
}
return false;
}
onOutput(lines) {
lines = <string[]> lines.split('\n');
lines.forEach(line => {
if (couldBeOutput(line)) {
if (!gdbMatch.exec(line))
this.log("stdout", line);
} else {
const parsed = parseMI(line);
if (this.debugOutput)
this.log("log", "GDB -> App: " + JSON.stringify(parsed));
let handled = false;
if (parsed.token !== undefined) {
if (this.handlers[parsed.token]) {
this.handlers[parsed.token](parsed);
delete this.handlers[parsed.token];
handled = true;
}
}
if (!handled && parsed.resultRecords && parsed.resultRecords.resultClass == "error") {
this.log("stderr", parsed.result("msg") || line);
}
if (parsed.outOfBandRecord) {
parsed.outOfBandRecord.forEach(record => {
if (record.isStream) {
this.log(record.type, record.content);
} else {
if (record.type == "exec") {
this.emit("exec-async-output", parsed);
if (record.asyncClass == "running")
this.emit("running", parsed);
else if (record.asyncClass == "stopped") {
const reason = parsed.record("reason");
if (trace)
this.log("stderr", "stop: " + reason);
if (reason == "breakpoint-hit")
this.emit("breakpoint", parsed);
else if (reason == "end-stepping-range")
this.emit("step-end", parsed);
else if (reason == "function-finished")
this.emit("step-out-end", parsed);
else if (reason == "signal-received")
this.emit("signal-stop", parsed);
else if (reason == "exited-normally")
this.emit("exited-normally", parsed);
else if (reason == "exited") { // exit with error code != 0
this.log("stderr", "Inferior exited with code " + parsed.record("exit-code"));
this.emit("exited-normally", parsed);
} else {
this.log("console", "Not implemented stop reason (assuming exception): " + reason);
this.emit("stopped", parsed);
}
} else
this.log("log", JSON.stringify(parsed));
} else if (record.type == "notify") {
if (record.asyncClass == "thread-created") {
this.emit("thread-created", parsed);
} else if (record.asyncClass == "thread-exited") {
this.emit("thread-exited", parsed);
} else if (record.asyncClass == "thread-group-started") {
this.emit("thread-group-started", parsed);
} else if (record.asyncClass == "thread-group-exited") {
this.emit("thread-group-exited", parsed);
}
}
}
});
handled = true;
}
if (parsed.token == undefined && parsed.resultRecords == undefined && parsed.outOfBandRecord.length == 0)
handled = true;
if (!handled)
this.log("log", "Unhandled: " + JSON.stringify(parsed));
}
});
}
start(): Thenable<boolean> {
return new Promise((resolve, reject) => {
this.once("ui-break-done", () => {
this.log("console", "Running executable");
this.sendCommand("exec-run").then((info) => {
if (info.resultRecords.resultClass == "running")
resolve();
else
reject();
}, reject);
});
});
}
stop() {
if (this.isSSH) {
const proc = this.stream;
const to = setTimeout(() => {
proc.signal("KILL");
}, 1000);
this.stream.on("exit", function (code) {
clearTimeout(to);
});
this.sendRaw("-gdb-exit");
} else {
const proc = this.process;
const to = setTimeout(() => {
process.kill(-proc.pid);
}, 1000);
this.process.on("exit", function (code) {
clearTimeout(to);
});
this.sendRaw("-gdb-exit");
}
}
detach() {
const proc = this.process;
const to = setTimeout(() => {
process.kill(-proc.pid);
}, 1000);
this.process.on("exit", function (code) {
clearTimeout(to);
});
this.sendRaw("-target-detach");
}
interrupt(all: boolean = true): Thenable<boolean> {
if (trace)
this.log("stderr", "interrupt");
return new Promise((resolve, reject) => {
this.sendCommand("exec-interrupt" + (all ? " --all" : "")).then((info) => {
resolve(info.resultRecords.resultClass == "done");
}, reject);
});
}
continue(reverse: boolean = false, all: boolean = true): Thenable<boolean> {
if (trace)
this.log("stderr", "continue");
return new Promise((resolve, reject) => {
this.sendCommand("exec-continue" + (reverse ? " --reverse" : "") + (all ? " --all" : "")).then((info) => {
resolve(info.resultRecords.resultClass == "running");
}, reject);
});
}
next(reverse: boolean = false): Thenable<boolean> {
if (trace)
this.log("stderr", "next");
return new Promise((resolve, reject) => {
this.sendCommand("exec-next" + (reverse ? " --reverse" : "")).then((info) => {
resolve(info.resultRecords.resultClass == "running");
}, reject);
});
}
step(reverse: boolean = false): Thenable<boolean> {
if (trace)
this.log("stderr", "step");
return new Promise((resolve, reject) => {
this.sendCommand("exec-step" + (reverse ? " --reverse" : "")).then((info) => {
resolve(info.resultRecords.resultClass == "running");
}, reject);
});
}
stepOut(reverse: boolean = false): Thenable<boolean> {
if (trace)
this.log("stderr", "stepOut");
return new Promise((resolve, reject) => {
this.sendCommand("exec-finish" + (reverse ? " --reverse" : "")).then((info) => {
resolve(info.resultRecords.resultClass == "running");
}, reject);
});
}
goto(filename: string, line: number): Thenable<Boolean> {
if (trace)
this.log("stderr", "goto");
return new Promise((resolve, reject) => {
const target: string = '"' + (filename ? escape(filename) + ":" : "") + line + '"';
this.sendCommand("break-insert -t " + target).then(() => {
this.sendCommand("exec-jump " + target).then((info) => {
resolve(info.resultRecords.resultClass == "running");
}, reject);
}, reject);
});
}
changeVariable(name: string, rawValue: string): Thenable<any> {
if (trace)
this.log("stderr", "changeVariable");
return this.sendCommand("gdb-set var " + name + "=" + rawValue);
}
loadBreakPoints(breakpoints: Breakpoint[]): Thenable<[boolean, Breakpoint][]> {
if (trace)
this.log("stderr", "loadBreakPoints");
const promisses = [];
breakpoints.forEach(breakpoint => {
promisses.push(this.addBreakPoint(breakpoint));
});
return Promise.all(promisses);
}
setBreakPointCondition(bkptNum, condition): Thenable<any> {
if (trace)
this.log("stderr", "setBreakPointCondition");
return this.sendCommand("break-condition " + bkptNum + " " + condition);
}
addBreakPoint(breakpoint: Breakpoint): Thenable<[boolean, Breakpoint]> {
if (trace)
this.log("stderr", "addBreakPoint");
return new Promise((resolve, reject) => {
if (this.breakpoints.has(breakpoint))
return resolve([false, undefined]);
let location = "";
if (breakpoint.countCondition) {
if (breakpoint.countCondition[0] == ">")
location += "-i " + numRegex.exec(breakpoint.countCondition.substr(1))[0] + " ";
else {
const match = numRegex.exec(breakpoint.countCondition)[0];
if (match.length != breakpoint.countCondition.length) {
this.log("stderr", "Unsupported break count expression: '" + breakpoint.countCondition + "'. Only supports 'X' for breaking once after X times or '>X' for ignoring the first X breaks");
location += "-t ";
} else if (parseInt(match) != 0)
location += "-t -i " + parseInt(match) + " ";
}
}
if (breakpoint.raw)
location += '"' + escape(breakpoint.raw) + '"';
else
location += '"' + escape(breakpoint.file) + ":" + breakpoint.line + '"';
this.sendCommand("break-insert -f " + location).then((result) => {
if (result.resultRecords.resultClass == "done") {
const bkptNum = parseInt(result.result("bkpt.number"));
const newBrk = {
file: result.result("bkpt.file"),
line: parseInt(result.result("bkpt.line")),
condition: breakpoint.condition
};
if (breakpoint.condition) {
this.setBreakPointCondition(bkptNum, breakpoint.condition).then((result) => {
if (result.resultRecords.resultClass == "done") {
this.breakpoints.set(newBrk, bkptNum);
resolve([true, newBrk]);
} else {
resolve([false, undefined]);
}
}, reject);
} else {
this.breakpoints.set(newBrk, bkptNum);
resolve([true, newBrk]);
}
} else {
reject(result);
}
}, reject);
});
}
removeBreakPoint(breakpoint: Breakpoint): Thenable<boolean> {
if (trace)
this.log("stderr", "removeBreakPoint");
return new Promise((resolve, reject) => {
if (!this.breakpoints.has(breakpoint))
return resolve(false);
this.sendCommand("break-delete " + this.breakpoints.get(breakpoint)).then((result) => {
if (result.resultRecords.resultClass == "done") {
this.breakpoints.delete(breakpoint);
resolve(true);
} else resolve(false);
});
});
}
clearBreakPoints(): Thenable<any> {
if (trace)
this.log("stderr", "clearBreakPoints");
return new Promise((resolve, reject) => {
this.sendCommand("break-delete").then((result) => {
if (result.resultRecords.resultClass == "done") {
this.breakpoints.clear();
resolve(true);
} else resolve(false);
}, () => {
resolve(false);
});
});
}
async getThreads(): Promise<Thread[]> {
if (trace) this.log("stderr", "getThreads");
const command = "thread-info";
const result = await this.sendCommand(command);
const threads = result.result("threads");
const ret: Thread[] = [];
return threads.map(element => {
const ret: Thread = {
id: parseInt(MINode.valueOf(element, "id")),
targetId: MINode.valueOf(element, "target-id")
};
ret.name = MINode.valueOf(element, "details")
|| undefined;
return ret;
});
}
async getStack(maxLevels: number, thread: number): Promise<Stack[]> {
if (trace) this.log("stderr", "getStack");
let command = "stack-list-frames";
if (thread != 0) {
command += ` --thread ${thread}`;
}
if (maxLevels) {
command += " 0 " + maxLevels;
}
const result = await this.sendCommand(command);
const stack = result.result("stack");
const ret: Stack[] = [];
return stack.map(element => {
const level = MINode.valueOf(element, "@frame.level");
const addr = MINode.valueOf(element, "@frame.addr");
const func = MINode.valueOf(element, "@frame.func");
const filename = MINode.valueOf(element, "@frame.file");
let file: string = MINode.valueOf(element, "@frame.fullname");
if (file) {
if (this.isSSH)
file = posix.normalize(file);
else
file = nativePath.normalize(file);
}
let line = 0;
const lnstr = MINode.valueOf(element, "@frame.line");
if (lnstr)
line = parseInt(lnstr);
const from = parseInt(MINode.valueOf(element, "@frame.from"));
return {
address: addr,
fileName: filename,
file: file,
function: func || from,
level: level,
line: line
};
});
}
async getStackVariables(thread: number, frame: number): Promise<Variable[]> {
if (trace)
this.log("stderr", "getStackVariables");
const result = await this.sendCommand(`stack-list-variables --thread ${thread} --frame ${frame} --simple-values`);
const variables = result.result("variables");
const ret: Variable[] = [];
for (const element of variables) {
const key = MINode.valueOf(element, "name");
const value = MINode.valueOf(element, "value");
const type = MINode.valueOf(element, "type");
ret.push({
name: key,
valueStr: value,
type: type,
raw: element
});
}
return ret;
}
examineMemory(from: number, length: number): Thenable<any> {
if (trace)
this.log("stderr", "examineMemory");
return new Promise((resolve, reject) => {
this.sendCommand("data-read-memory-bytes 0x" + from.toString(16) + " " + length).then((result) => {
resolve(result.result("memory[0].contents"));
}, reject);
});
}
async evalExpression(name: string, thread: number, frame: number): Promise<MINode> {
if (trace)
this.log("stderr", "evalExpression");
let command = "data-evaluate-expression ";
if (thread != 0) {
command += `--thread ${thread} --frame ${frame} `;
}
command += name;
return await this.sendCommand(command);
}
async varCreate(expression: string, name: string = "-"): Promise<VariableObject> {
if (trace)
this.log("stderr", "varCreate");
const res = await this.sendCommand(`var-create ${name} @ "${expression}"`);
return new VariableObject(res.result(""));
}
async varEvalExpression(name: string): Promise<MINode> {
if (trace)
this.log("stderr", "varEvalExpression");
return this.sendCommand(`var-evaluate-expression ${name}`);
}
async varListChildren(name: string): Promise<VariableObject[]> {
if (trace)
this.log("stderr", "varListChildren");
//TODO: add `from` and `to` arguments
const res = await this.sendCommand(`var-list-children --all-values ${name}`);
const children = res.result("children") || [];
const omg: VariableObject[] = children.map(child => new VariableObject(child[1]));
return omg;
}
async varUpdate(name: string = "*"): Promise<MINode> {
if (trace)
this.log("stderr", "varUpdate");
return this.sendCommand(`var-update --all-values ${name}`);
}
async varAssign(name: string, rawValue: string): Promise<MINode> {
if (trace)
this.log("stderr", "varAssign");
return this.sendCommand(`var-assign ${name} ${rawValue}`);
}
logNoNewLine(type: string, msg: string) {
this.emit("msg", type, msg);
}
log(type: string, msg: string) {
this.emit("msg", type, msg[msg.length - 1] == '\n' ? msg : (msg + "\n"));
}
sendUserInput(command: string, threadId: number = 0, frameLevel: number = 0): Thenable<any> {
if (command.startsWith("-")) {
return this.sendCommand(command.substr(1));
} else {
return this.sendCliCommand(command, threadId, frameLevel);
}
}
sendRaw(raw: string) {
if (this.printCalls)
this.log("log", raw);
if (this.isSSH)
this.stream.write(raw + "\n");
else
this.process.stdin.write(raw + "\n");
}
async sendCliCommand(command: string, threadId: number = 0, frameLevel: number = 0) {
let miCommand = "interpreter-exec ";
if (threadId != 0) {
miCommand += `--thread ${threadId} --frame ${frameLevel} `;
}
miCommand += `console "${command.replace(/[\\"']/g, '\\$&')}"`;
await this.sendCommand(miCommand);
}
sendCommand(command: string, suppressFailure: boolean = false): Thenable<MINode> {
const sel = this.currentToken++;
return new Promise((resolve, reject) => {
this.handlers[sel] = (node: MINode) => {
if (node && node.resultRecords && node.resultRecords.resultClass === "error") {
if (suppressFailure) {
this.log("stderr", `WARNING: Error executing command '${command}'`);
resolve(node);
} else
reject(new MIError(node.result("msg") || "Internal error", command));
} else
resolve(node);
};
this.sendRaw(sel + "-" + command);
});
}
isReady(): boolean {
return this.isSSH ? this.sshReady : !!this.process;
}
prettyPrint: boolean = true;
multiProcess: boolean = false;
printCalls: boolean;
debugOutput: boolean;
public procEnv: any;
protected isSSH: boolean;
protected sshReady: boolean;
protected currentToken: number = 1;
protected handlers: { [index: number]: (info: MINode) => any } = {};
protected breakpoints: Map<Breakpoint, Number> = new Map();
protected buffer: string;
protected errbuf: string;
protected process: ChildProcess.ChildProcess;
protected stream;
protected sshConn;
}