-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathluaDebug.ts
More file actions
682 lines (565 loc) · 26.2 KB
/
Copy pathluaDebug.ts
File metadata and controls
682 lines (565 loc) · 26.2 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
import {
Logger, logger,
LoggingDebugSession,
InitializedEvent, TerminatedEvent, StoppedEvent, BreakpointEvent, OutputEvent,
Thread, StackFrame, Scope, Source, Handles, Breakpoint
} from 'vscode-debugadapter';
import { DebugProtocol } from 'vscode-debugprotocol';
import { basename, join, dirname } from 'path';
import { LuaRuntime, LuaBreakpoint, VariableTypes, StartFrameInfo, cleanUpPath, excludeRootPath } from './luaRuntime';
import { Subject } from 'await-notify';
import * as sm from 'source-map';
import * as fs from 'fs-extra';
/**
* This interface describes the lua debug specific launch attributes
* (which are not part of the Debug Adapter Protocol).
* The schema for these attributes lives in the package.json of the lua-debug extension.
* The interface should always match this schema.
*/
interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments {
/** Absolute path to the working directory of the program being debugged. */
cwd: string;
/** An absolute path to the "program" to debug. */
program: string;
/** Automatically stop target after launch. If not specified, target does not stop. */
stopOnEntry?: boolean;
/** enable logging the Debug Adapter Protocol */
trace?: boolean;
/** An absolute path to the lua "executable" to launch. */
luaExecutable: string;
/** An absolute path to the lua debugger (set in config) */
luaDebuggerFilePath: string;
}
export class LuaDebugSession extends LoggingDebugSession {
// we don't support multiple threads, so we can use a hardcoded ID for the default thread
private static THREAD_ID = 1;
// a Mock runtime (or debugger)
private _runtime: LuaRuntime;
private _variableHandles = new Handles<string>();
private _configurationDone = new Subject();
private _dumpInProgress: Subject;
private _sourceMapCache = new Map<string, sm.BasicSourceMapConsumer>();
private _sourceMapFilePathCache = new Map<string, string>();
private _mapFiles: true | Map<string, any | boolean>;
private _listOfMapFiles: Array<string>;
/**
* Creates a new debug adapter that is used for one debug session.
* We configure the default implementation of a debug adapter here.
*/
public constructor() {
super("lua-debug.txt");
// this debugger uses zero-based lines and columns
this.setDebuggerLinesStartAt1(true);
this.setDebuggerColumnsStartAt1(false);
this._runtime = new LuaRuntime();
// setup event handlers
this._runtime.on('stopOnEntry', () => {
this.sendEvent(new StoppedEvent('entry', LuaDebugSession.THREAD_ID));
});
this._runtime.on('stopOnStep', () => {
this.sendEvent(new StoppedEvent('step', LuaDebugSession.THREAD_ID));
});
this._runtime.on('stopOnBreakpoint', () => {
this.sendEvent(new StoppedEvent('breakpoint', LuaDebugSession.THREAD_ID));
});
this._runtime.on('stopOnException', (msg?) => {
const event = new StoppedEvent('exception', LuaDebugSession.THREAD_ID, msg);
//(<DebugProtocol.StoppedEvent>event).body.description = msg;
this.sendEvent(event);
});
this._runtime.on('breakpointValidated', (bp: LuaBreakpoint) => {
this.sendEvent(new BreakpointEvent('changed', <DebugProtocol.Breakpoint>{ verified: bp.verified, id: bp.id }));
});
this._runtime.on('outputData', (text) => {
const e: DebugProtocol.OutputEvent = new OutputEvent(text);
this.sendEvent(e);
});
this._runtime.on('errorData', (text) => {
const e: DebugProtocol.OutputEvent = new OutputEvent(text, 'error');
this.sendEvent(e);
});
this._runtime.on('logData', (text) => {
const e: DebugProtocol.OutputEvent = new OutputEvent(text, 'log');
this.sendEvent(e);
});
this._runtime.on('output', (text, filePath, line, column) => {
const e: DebugProtocol.OutputEvent = new OutputEvent(`${text}\n`);
e.body.source = this.createSource(filePath);
e.body.line = this.convertDebuggerLineToClient(line);
e.body.column = this.convertDebuggerColumnToClient(column);
this.sendEvent(e);
});
this._runtime.on('end', () => {
this.sendEvent(new TerminatedEvent());
});
}
/**
* The 'initialize' request is the first request called by the frontend
* to interrogate the features the debug adapter provides.
*/
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
// build and return the capabilities of this debug adapter:
response.body = response.body || {};
// the adapter implements the configurationDoneRequest.
response.body.supportsConfigurationDoneRequest = true;
// make VS Code to use 'evaluate' when hovering over source
response.body.supportsEvaluateForHovers = true;
// make VS Code to show a 'step back' button
response.body.supportsStepBack = false;
//
////response.body.supportsDelayedStackTraceLoading = true;
response.body.supportsExceptionOptions = false;
response.body.supportsExceptionInfoRequest = true;
response.body.exceptionBreakpointFilters = [];
response.body.supportTerminateDebuggee = true;
this.sendResponse(response);
// since this debug adapter can accept configuration requests like 'setBreakpoint' at any time,
// we request them early by sending an 'initializeRequest' to the frontend.
// The frontend will end the configuration sequence by calling 'configurationDone' request.
this.sendEvent(new InitializedEvent());
}
/**
* Called at the end of the configuration sequence.
* Indicates that all breakpoints etc. have been sent to the DA and that the 'launch' can start.
*/
protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void {
super.configurationDoneRequest(response, args);
// notify the launchRequest that configuration has finished
this._configurationDone.notify();
}
protected async launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments) {
// make sure to 'Stop' the buffered logging if 'trace' is not set
logger.setup(args.trace ? Logger.LogLevel.Verbose : Logger.LogLevel.Stop, false);
// set current folder
if (args.cwd) {
process.chdir(args.cwd);
}
if (!args.noDebug) {
// load source maps and prepare breakpoints
await this.loadMapSourceAndSetBreakpoints();
// start the program in the runtime
await this._runtime.start(args.program, !!args.stopOnEntry, args.luaExecutable, args.luaDebuggerFilePath);
} else {
await this._runtime.startNoDebug(args.program, args.luaExecutable);
}
// wait until configuration has finished (and configurationDoneRequest has been called)
await this._configurationDone.wait(1000);
this.sendResponse(response);
}
private async loadMapSourceAndSetBreakpoints() {
const cwd = process.cwd();
if (this._mapFiles === undefined) {
this._listOfMapFiles = [];
await this.readAllMapFile(cwd, this._listOfMapFiles);
}
// check all map files
const rootFolder = cleanUpPath(cwd);
const breakpointsMap = this._runtime.breakPoints;
for (const mapFile of this._listOfMapFiles) {
const sourceMapConsumer = await this.loadMapFileIfExists(mapFile);
if (sourceMapConsumer) {
const luaFilePath = cleanUpPath(this.getFilePathFromSourceMapConsumer(sourceMapConsumer));
if (!luaFilePath) {
continue;
}
for (const source of sourceMapConsumer.sources) {
const sourcePath = cleanUpPath(source);
const bps = breakpointsMap.get(sourcePath);
if (bps) {
let luaFilePathWithoutRoot = excludeRootPath(luaFilePath, rootFolder);
const sourceFileSubPath = excludeRootPath(source, sourceMapConsumer.sourceRoot);
let sourceSubPath = dirname(sourceFileSubPath);
if (sourceSubPath === '.') {
luaFilePathWithoutRoot = basename(luaFilePathWithoutRoot);
// to lower folder names
} else {
const positionOfSubPath = luaFilePathWithoutRoot.indexOf(sourceSubPath);
if (positionOfSubPath > -1) {
luaFilePathWithoutRoot = luaFilePathWithoutRoot.substring(positionOfSubPath);
}
}
luaFilePathWithoutRoot = luaFilePathWithoutRoot;
const mappedLines = this.convertLinesFromSourceMapConsumer(bps.map(bp => bp.line), sourceMapConsumer, source);
for (const mappedLine of mappedLines) {
this._runtime.setBreakPoint(luaFilePathWithoutRoot, mappedLine);
}
}
}
}
}
}
protected async setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments) {
const subPath = args.source.origin || <string>args.source.path;
const clientLines = args.lines || [];
const originLines = this.convertLinesFromMap(clientLines, args.source.origin, args.source.path);
// clear all breakpoints for this file
this._runtime.clearBreakpoints(subPath);
// set and verify breakpoint locations
const actualBreakpoints = new Array<DebugProtocol.Breakpoint>();
for (let index = 0; index < originLines.length; index++) {
const element = originLines[index];
const fileLine = clientLines[index];
let { verified, line, id } = await this._runtime.setBreakPoint(subPath, this.convertClientLineToDebugger(element));
line = fileLine;
const bp = <DebugProtocol.Breakpoint>new Breakpoint(verified, this.convertDebuggerLineToClient(line));
bp.id = id;
actualBreakpoints.push(bp);
}
// send back the actual breakpoint positions
response.body = {
breakpoints: actualBreakpoints
};
this.sendResponse(response);
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
// runtime supports now threads so just return a default thread.
response.body = {
threads: [
new Thread(LuaDebugSession.THREAD_ID, "main")
]
};
this.sendResponse(response);
}
protected async stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments) {
const startFrame = typeof args.startFrame === 'number' ? args.startFrame : 0;
const maxLevels = typeof args.levels === 'number' ? args.levels : 1000;
const endFrame = startFrame + maxLevels;
const stk = await this.getStackTrace(startFrame + 1, endFrame + 1);
response.body = {
stackFrames: stk.frames
.map(f => this.convertFrameFromMap(f))
.map(f => new StackFrame(f.index, f.name, this.createSource(f.file, f.origin), this.convertDebuggerLineToClient(f.line))),
totalFrames: stk.count
};
this.sendResponse(response);
}
protected async getStackTrace(startFrame, endFrame) {
const stk = await this._runtime.stack(startFrame, endFrame);
// creating cache of map files
for (const frame of stk.frames) {
await this.loadMapFileIfExists(frame.file);
}
return stk;
}
private async loadMapFileIfExists(execFile: string): Promise<sm.BasicSourceMapConsumer | undefined> {
if (execFile && execFile in this._sourceMapCache) {
return this._sourceMapCache[execFile];
}
const mapFile = execFile.endsWith('.map') ? execFile : execFile + ".map";
let filePath = this.getFilePathOfMapFile(mapFile);
if (!filePath) {
const canBeRootFolder = (mapFile.length > 1 && mapFile.charAt(1) === ':') || (mapFile.length > 0 && mapFile.charAt(0) === '/');
if (canBeRootFolder) {
const exists = await new Promise((resolve, reject) => fs.exists(mapFile, (exists) => resolve(exists)));
if (exists) {
filePath = mapFile;
}
}
}
if (filePath) {
const json = await fs.readJson(filePath);
this._sourceMapFilePathCache[execFile] = filePath;
const mapConsumer = await new sm.SourceMapConsumer(json);
this._sourceMapCache[execFile] = mapConsumer;
return mapConsumer;
} else {
console.error(`Could not load file ${mapFile}, current folder: ${process.cwd()}`);
}
return undefined;
}
protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void {
const frameReference = args.frameId;
const scopes = new Array<Scope>();
scopes.push(new Scope("Locals", this._variableHandles.create("::local:" + frameReference), false));
scopes.push(new Scope("Globals", this._variableHandles.create("::global:" + frameReference), true));
scopes.push(new Scope("Environment", this._variableHandles.create("::environment:" + frameReference), true));
response.body = {
scopes: scopes
};
this.sendResponse(response);
}
protected async variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments) {
if (this._dumpInProgress) {
await this._dumpInProgress.wait(3000);
response.success = false;
response.message = "Can't retrieve, the debugger is busy";
this.sendResponse(response);
return;
}
const dumpInProgress = this._dumpInProgress = new Subject();
const id = this._variableHandles.get(args.variablesReference);
let frameId = -1;
let variableName;
let variableType = VariableTypes.Local;
if (id.startsWith("::local:")) {
variableType = VariableTypes.Local;
frameId = parseInt(id.substr("::local:".length));
} else if (id.startsWith("::global:")) {
variableType = VariableTypes.Global;
frameId = parseInt(id.substr("::global:".length));
} else if (id.startsWith("::environment:")) {
variableType = VariableTypes.Environment;
frameId = parseInt(id.substr("::environment:".length));
} else {
variableType = VariableTypes.SingleVariable;
variableName = id;
}
try {
if (frameId >= 0) {
await this._runtime.setFrameId(frameId);
}
const cb = (variables) => {
dumpInProgress.notify();
this._dumpInProgress = null;
if (variables instanceof Error) {
response.success = false;
response.message = "Can't retrieve variable: " + variables.message;
} else {
if (variables) {
response.body = {
variables: variables
};
}
}
this.sendResponse(response);
};
await this._runtime.dumpVariables(cb, variableType, variableName, this._variableHandles);
}
catch (e) {
response.success = false;
response.message = "Can't retrieve '" + (variableName || "") + "'";
dumpInProgress.notify();
this._dumpInProgress = null;
}
}
protected async continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments) {
this.sendResponse(response);
await this._runtime.continue();
}
protected async nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments) {
this.sendResponse(response);
await this._runtime.stepOver();
}
protected async stepInRequest(response: DebugProtocol.StepInResponse, args: DebugProtocol.StepInArguments) {
this.sendResponse(response);
await this._runtime.stepIn();
}
protected async stepOutRequest(response: DebugProtocol.StepOutResponse, args: DebugProtocol.StepOutArguments) {
this.sendResponse(response);
await this._runtime.stepOut();
}
protected async pauseRequest(response: DebugProtocol.StepOutResponse, args: DebugProtocol.StepOutArguments) {
this.sendResponse(response);
//await this._runtime.pause();
await this._runtime.ctrlc();
}
protected exceptionInfoRequest(response: DebugProtocol.ExceptionInfoResponse, args: DebugProtocol.ExceptionInfoArguments) {
response.body = {
exceptionId: "undefined",
description: this._runtime.getError(),
////breakMode: 'userUnhandled',
breakMode: 'never',
details: {
////message: this._runtime.getError(),
stackTrace: this._runtime.getErrorStack()
}
};
this.sendResponse(response);
}
protected async evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments) {
if (this._dumpInProgress) {
await this._dumpInProgress.wait(3000);
response.success = false;
response.message = "Can't retrieve, the debugger is busy";
this.sendResponse(response);
return;
}
const dumpInProgress = this._dumpInProgress = new Subject();
let variableName = args.expression;
let variableType = VariableTypes.SingleVariable;
try {
const cb = async (variables) => {
dumpInProgress.notify();
this._dumpInProgress = null;
if (variables instanceof Error) {
response.success = false;
response.message = "Can't retrieve variable: " + variables.message;
} else {
if (variables) {
response.body = {
result: variables[0].value,
variablesReference: variables[0].variablesReference
};
} else if (args.context === 'repl') {
// run statement
await this._runtime.runStatement(variableName);
response.body = {
result: "done.",
variablesReference: 0
};
}
}
this.sendResponse(response);
};
await this._runtime.dumpVariables(cb, variableType, variableName, this._variableHandles, true);
}
catch (e) {
response.success = false;
response.message = "Can't retrieve " + (variableName || "") + ": " + e.message;
dumpInProgress.notify();
this._dumpInProgress = null;
}
}
//---- helpers
private async readAllMapFile(cwd: string, allMapFilePathes?: Array<string>) {
const files = await this.readAllMapFileInDirectory(cwd, allMapFilePathes);
if (files !== false) {
this._mapFiles = files;
}
}
private async readAllMapFileInDirectory(filePath: string, allMapFilePathes?: Array<string>) {
const stat = await fs.stat(filePath);
if (stat.isDirectory()) {
const allFiles = await fs.readdir(filePath);
const files = new Map<string, any | boolean>();
for (const file of allFiles) {
const value = await this.readAllMapFileInDirectory(join(filePath, file), allMapFilePathes);
if (value !== false) {
files[file] = value;
}
}
return files;
}
if (stat.isFile() && filePath.endsWith('.map')) {
if (allMapFilePathes) {
allMapFilePathes.push(filePath);
}
return true;
}
return false;
}
private getFilePathOfMapFile(fileMapName: string): string | undefined {
if (!this._mapFiles) {
return undefined;
}
return this.getFilePathOfMapFileInternal(fileMapName, <Map<string, any>>this._mapFiles, '', false);
}
private getFilePathOfMapFileInternal(fileMapName: string, mapFiles: Map<string, any>, path: string, matching: boolean): string | undefined {
// case when xxx\yyy
let index = fileMapName.indexOf('/');
if (index === -1) {
index = fileMapName.indexOf('\\');
}
if (index !== -1) {
// sub path
const dirPath = fileMapName.substr(0, index);
const restPath = fileMapName.substr(index + 1);
const value = mapFiles[dirPath];
if (value !== undefined && value !== true) {
const subPath = this.getFilePathOfMapFileInternal(restPath, <Map<string, any>>value, dirPath.toLowerCase(), true);
if (subPath && subPath.endsWith('.map')) {
return join(path, subPath);
}
}
}
// other case when subfolder is not defined
for (const item in mapFiles) {
if (item === fileMapName) {
return join(path, item);
}
if (!matching) {
const value = mapFiles[item];
if (value !== true) {
const subPath = this.getFilePathOfMapFileInternal(fileMapName, <Map<string, any>>value, item, matching);
if (subPath && subPath.endsWith('.map')) {
return join(path, subPath);
}
}
}
}
}
private createSource(filePath: string, origin?: string): Source {
// default response
return new Source(basename(filePath), this.convertDebuggerPathToClient(filePath), undefined, origin, 'lua-file-adapter-data');
}
private convertFrameFromMap(frame: StartFrameInfo) {
const originalPosition = this.getOriginalPositionFor(frame.file, frame.line || 1, frame.column || 0);
if (originalPosition) {
frame.origin = frame.file;
frame.file = originalPosition.source;
if (frame.line > 0) {
frame.line = originalPosition.line;
frame.column = originalPosition.column;
} else {
frame.line = 1;
frame.column = 0;
}
}
return frame;
}
private getFilePathFromSourceMapConsumer(consumer: sm.BasicSourceMapConsumer) {
let fullPath = '';
if (!consumer.file) {
return fullPath;
}
const mapFile = consumer.file + ".map";
// find path by
for (const fileSubPath in this._sourceMapFilePathCache) {
if (fileSubPath.endsWith(mapFile)) {
fullPath = this._sourceMapFilePathCache[fileSubPath];
break;
}
}
return this.replaceFileName(fullPath, consumer.file);
}
private replaceFileName(path: string, newFileName: string) {
let subPathIndex = path.lastIndexOf('\\');
if (subPathIndex === -1) {
subPathIndex = path.lastIndexOf('/');
}
if (subPathIndex === -1) {
return newFileName;
}
return path.substr(0, subPathIndex + 1) + newFileName;
}
private convertLinesFromMap(lines: number[], origin?: string, sourceFilePath?: string): number[] {
if (!origin) {
return lines;
}
const consumer = this._sourceMapCache[origin];
if (!consumer) {
return lines;
}
return this.convertLinesFromSourceMapConsumer(lines, consumer, sourceFilePath || '');
}
private convertLinesFromSourceMapConsumer(lines: number[], consumer: sm.BasicSourceMapConsumer, sourceFilePath: string) {
if (sourceFilePath) {
sourceFilePath = cleanUpPath(sourceFilePath);
sourceFilePath = excludeRootPath(sourceFilePath, consumer.sourceRoot);
}
const originLines = new Array<number>();
for (const line of lines) {
const originPosition = consumer.generatedPositionFor({
source: sourceFilePath || '',
line: line,
column: 0
});
if (originPosition && originPosition.line) {
originLines.push(originPosition.line);
} else {
originLines.push(line);
}
}
return originLines;
}
private getOriginalPositionFor(filePath: string, line: number, column: number): any {
// check if filename is map file
const consumer = this._sourceMapCache[filePath];
if (!consumer) {
return undefined;
}
// TODO: do not forget to call destroy
////consumer.destroy();
return consumer.originalPositionFor({ line, column });
}
}