-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathandroidConnection.ts
803 lines (671 loc) · 27.1 KB
/
androidConnection.ts
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
import * as http from 'http';
import {EventEmitter} from 'events';
import {Services} from '../../services/debugAdapterServices';
import * as Net from 'net';
import { INSDebugConnection } from './INSDebugConnection';
interface IMessageWithId {
id: number;
method: string;
params?: string[];
}
class Callbacks {
private lastId: number = 1;
private callbacks: any = {};
public wrap(callback: any): number {
var callbackId = this.lastId++;
this.callbacks[callbackId] = callback || function() { };
return callbackId;
}
public processResponse(callbackId: any, args: any) {
var callback = this.callbacks[callbackId];
if (callback) {
callback.apply(null, args);
}
delete this.callbacks[callbackId];
}
public removeResponseCallbackEntry(callbackId: any) {
delete this.callbacks[callbackId];
}
}
class ResReqNetSocket extends EventEmitter {
private _pendingRequests = new Map<number, any>();
private connected = false;
private debugBuffer: any = '';
private msg: any = false;
private conn: Net.Socket;
private offset: number;
private contentLengthMatch: any;
private lastError: string;
private callbacks: Callbacks;
private isRunning: boolean;
private isMessageFlushLoopStarted = false;
private hasNewDataMessage = false;
public attach(port: number, url: string, timeout: number = 10000) {
var that = this;
this.callbacks = new Callbacks();
return new Promise<void>((resolve, reject) => {
that.conn = Net.createConnection(port, url),
that.conn.setEncoding('utf8');
setTimeout(() => {
reject('Connection timed out')
}, timeout);
that.conn.on('error', reject);
that.conn.on('connect', function() {
// Replace the promise-rejecting handler
that.conn.removeListener('error', reject);
that.conn.on('error', e => {
console.error('socket error: ' + e.toString());
if ((<any>e).code == 'ECONNREFUSED') {
(<any>e).helpString = 'Is node running with --debug port ' + port + '?';
} else if ((<any>e).code == 'ECONNRESET') {
(<any>e).helpString = 'Check there is no other debugger client attached to port ' + port + '.';
}
that.lastError = e.toString();
if ((<any>e).helpString) {
that.lastError += '. ' + (<any>e).helpString;
}
that.emit('error', e);
});
that.conn.on('data', function(data) {
that.debugBuffer += data;
that.parse(function() {
that.connected = true;
that.emit('connect');
resolve();
});
});
that.conn.on('end', function() {
that.close();
});
that.conn.on('close', function() {
if (!that.connected)
{
reject("Can't connect. Check the application is running on the device");
that.emit('close', that.lastError || 'Debugged process exited.');
return;
}
that.connected = false;
that.emit('close', that.lastError || 'Debugged process exited.');
});
});
});
}
private makeMessage() {
return {
headersDone: false,
headers: null,
contentLength: 0
};
}
private parse(connectedCallback: () => any) {
var b, obj;
var that = this;
if (this.msg && this.msg.headersDone) {
//parse body
if (Buffer.byteLength(this.debugBuffer) >= this.msg.contentLength) {
b = new Buffer(this.debugBuffer);
this.msg.body = b.toString('utf8', 0, this.msg.contentLength);
this.debugBuffer = b.toString('utf8', this.msg.contentLength, b.length);
if (this.msg.body.length > 0) {
obj = JSON.parse(this.msg.body);
Services.logger().log('From target(' + (obj.type ? obj.type : '') + '): ' + this.msg.body);
if (typeof obj.running === 'boolean') {
this.isRunning = obj.running;
}
if (obj.type === 'response' && obj.request_seq > 0) {
this.callbacks.processResponse(obj.request_seq, [obj]);
}
else if (obj.type === 'event') {
if (obj.event === "afterCompile") {
if (!that.connected && connectedCallback) {
connectedCallback();
}
}
this.emit(obj.event, obj);
}
}
this.msg = false;
this.parse(connectedCallback);
}
return;
}
if (!this.msg) {
this.msg = this.makeMessage();
}
this.offset = this.debugBuffer.indexOf('\r\n\r\n');
if (this.offset > 0) {
this.msg.headersDone = true;
this.msg.headers = this.debugBuffer.substr(0, this.offset + 4);
this.contentLengthMatch = /Content-Length: (\d+)/.exec(this.msg.headers);
if (this.contentLengthMatch[1]) {
this.msg.contentLength = parseInt(this.contentLengthMatch[1], 10);
}
else {
console.warn('no Content-Length');
}
this.debugBuffer = this.debugBuffer.slice(this.offset + 4);
this.parse(connectedCallback);
}
}
public send(data) {
if (this.connected) {
Services.logger().log('To target: ' + data);
this.conn.write('Content-Length: ' + data.length + '\r\n\r\n' + data);
this.hasNewDataMessage = true;
if (!this.isMessageFlushLoopStarted) {
this.isMessageFlushLoopStarted = true;
setInterval(() => {
if (this.hasNewDataMessage) {
let msg = 'FLUSH BUFFERS';
this.conn.write('Content-Length: ' + msg.length + '\r\n\r\n' + msg);
this.hasNewDataMessage = false;
}
}, 200);
}
}
}
public request(command, params, callback) {
var msg = {
seq: 0,
type: 'request',
command: command
};
if (typeof callback == 'function') {
msg.seq = this.callbacks.wrap(callback);
}
if (params) {
Object.keys(params).forEach(function(key) {
msg[key] = params[key];
});
}
this.send(JSON.stringify(msg));
}
public close() {
if (this.conn) {
this.conn.end();
}
}
}
export class AndroidConnection implements INSDebugConnection {
private _nextId = 1;
//private _socket: ResReqWebSocket;
//private _socket: ResReqHttpSocket;
private _socket: ResReqNetSocket;
constructor() {
//this._socket = new ResReqWebSocket();
let that = this;
this._socket = new ResReqNetSocket();
this._socket.on("afterCompile", function(params) {
let scriptData = <WebKitProtocol.Debugger.Script>{
scriptId: String(params.body.script.id),
url: params.body.script.name,
startLine: params.body.script.lineOffset,
startColumn: params.body.script.columnOffset
};
that._socket.emit("Debugger.scriptParsed", scriptData);
});
this._socket.on("break", function(params) {
that.handleBreakEvent(params);
});
this._socket.on("exception", function(params) {
that.handleBreakEvent(params);
});
this._socket.on("messageAdded", function(params) {
that._socket.emit("Console.messageAdded", params.body);
});
}
private handleBreakEvent(params: any): Promise<any> {
let that = this;
return this.fetchCallFrames().then(callFrames => {
let scriptData = <WebKitProtocol.Debugger.PausedParams>{
reason: "other",
hitBreakpoints: params ? (params.breakpoints || []) : [],
callFrames: callFrames
};
that._socket.emit("Debugger.paused", scriptData);
});
}
private v8ScopeTypeToString(v8ScopeType: number): string {
switch (v8ScopeType) {
case 0:
return 'global';
case 1:
return 'local';
case 2:
return 'with';
case 3:
return 'closure';
case 4:
return 'catch';
default:
return 'unknown';
}
}
private v8ResultToInspectorResult(result: any): any {
if (['object', 'function', 'regexp', 'error'].indexOf(result.type) > -1) {
return this.v8RefToInspectorObject(result);
}
if (result.type == 'null') {
// workaround for the problem with front-end's setVariableValue
// implementation not preserving null type
result.value = null;
}
return {
type: result.type,
value: result.value,
description: String(result.value)
};
}
private inspectorUrlToV8Name(url: string): string {
let path = url.replace(/^file:\/\//, '');
if (/^\/[a-zA-Z]:\//.test(path))
return path.substring(1).replace(/\//g, '\\'); // Windows disk path
if (/^\//.test(path))
return path; // UNIX-style
if (/^file:\/\//.test(url))
return '\\\\' + path.replace(/\//g, '\\'); // Windows UNC path
return url;
};
private v8LocationToInspectorLocation(v8loc: any): any {
return {
scriptId: v8loc.script_id.toString(),
lineNumber: v8loc.line,
columnNumber: v8loc.column
};
};
private v8RefToInspectorObject(ref: any): any {
var desc = '',
type = ref.type,
size,
name,
objectId;
switch (type) {
case 'object':
name = /#<(\w+)>/.exec(ref.text);
if (name && name.length > 1) {
desc = name[1];
if (desc === 'Array' || desc === 'Buffer') {
size = ref.properties.filter(function(p) { return /^\d+$/.test(p.name); }).length;
desc += '[' + size + ']';
}
} else if (ref.className === 'Date') {
desc = new Date(ref.value).toString();
type = 'date';
} else {
desc = ref.className || 'Object';
}
break;
case 'function':
desc = ref.text || 'function()';
break;
case 'error':
type = 'object';
desc = ref.text || 'Error';
break;
default:
desc = ref.text || '';
break;
}
if (desc.length > 100) {
desc = desc.substring(0, 100) + '\u2026';
}
objectId = ref.handle;
if (objectId === undefined)
objectId = ref.ref;
return {
type: type,
objectId: String(objectId),
className: ref.className,
description: desc
};
}
private v8ErrorToInspectorError(message: any) {
var nameMatch = /^([^:]+):/.exec(message);
return {
type: 'object',
objectId: 'ERROR',
className: nameMatch ? nameMatch[1] : 'Error',
description: message
};
};
private fetchCallFrames(): Promise<WebKitProtocol.Debugger.CallFrame[]> {
let that = this;
return this.request("backtrace",
{
inlineRefs: true,
fromFrame: 0,
toFrame: 50
})
.then(response => {
var debuggerFrames = <Array<any>>response.frames || [];
let frames = debuggerFrames.map(function(frame) {
var scopeChain = frame.scopes.map(function(scope) {
return {
object: {
type: 'object',
objectId: 'scope:' + frame.index + ':' + scope.index,
className: 'Object',
description: 'Object'
},
type: that.v8ScopeTypeToString(scope.type)
};
});
return {
callFrameId: frame.index.toString(),
functionName: frame.func.inferredName || frame.func.name,
location: {
scriptId: String(frame.func.scriptId),
lineNumber: frame.line,
columnNumber: frame.column
},
scopeChain: scopeChain,
this: that.v8RefToInspectorObject(frame.receiver)
}
});
return frames;
});
}
public on(eventName: string, handler: (msg: any) => void): void {
this._socket.on(eventName, handler);
}
public attach(port: number, url?: string): Promise<void> {
Services.logger().log('Attempting to attach on port ' + port);
return this._attach(port, url);
//.then(() => this.sendMessage('Console.enable'))
}
private _attach(port: number, url?: string): Promise<void> {
return this._socket.attach(port, url);
}
public close(): void {
this._socket.close();
}
public debugger_setBreakpointByUrl(url: string, lineNumber: number, columnNumber: number, condition: string, ignoreCount: number): Promise<WebKitProtocol.Debugger.SetBreakpointByUrlResponse> {
let that = this;
var requestParams = {
type: 'script',
target: that.inspectorUrlToV8Name(url),
line: lineNumber,
column: columnNumber,
condition: condition,
ignoreCount: ignoreCount
};
return this.request("setbreakpoint", requestParams)
.then(response => {
return <WebKitProtocol.Debugger.SetBreakpointByUrlResponse>
{
result: {
breakpointId: response.breakpoint.toString(),
locations: response.actual_locations.map(that.v8LocationToInspectorLocation),
},
}
});
}
public debugger_removeBreakpoint(breakpointId: string): Promise<WebKitProtocol.Response> {
//throw new Error("Not implemented");
//return this.sendMessage('Debugger.removeBreakpoint', <WebKitProtocol.Debugger.RemoveBreakpointParams>{ breakpointId });
//ok
return this.request("clearbreakpoint", {
breakpoint: breakpointId
})
.then(response => {
return <WebKitProtocol.Response>{};
});
}
public debugger_stepOver(): Promise<WebKitProtocol.Response> {
//throw new Error("Not implemented");
//return this.sendMessage('Debugger.stepOver');
//locations: response.actual_locations.map(that.v8LocationToInspectorLocation)
return this.sendContinue('next').then(reponse => {
return <WebKitProtocol.Response>{};
});
//ok
}
private sendContinue(stepAction: string): Promise<any> {
let that = this;
let args = stepAction ? { stepaction: stepAction } : undefined;
return this.request("continue", args).then(response => {
that._socket.emit("'Debugger.resumed");
return response;
})
}
public debugger_stepIn(): Promise<WebKitProtocol.Response> {
//return this.sendMessage('Debugger.stepInto');
//throw new Error("Not implemented");
//ok
return this.sendContinue('in').then(reponse => {
return <WebKitProtocol.Response>{};
});
}
public debugger_stepOut(): Promise<WebKitProtocol.Response> {
//return this.sendMessage('Debugger.stepOut');
//throw new Error("Not implemented");
//ok
return this.sendContinue('out').then(reponse => {
return <WebKitProtocol.Response>{};
});
}
public debugger_resume(): Promise<WebKitProtocol.Response> {
//return this.sendMessage('Debugger.resume');
//throw new Error("Not implemented");
//ok
return this.sendContinue(null).then(reponse => {
return <WebKitProtocol.Response>{};
});
}
public debugger_pause(): Promise<WebKitProtocol.Response> {
//return this.sendMessage('Debugger.pause');
//throw new Error("Not implemented");
//ok
let that = this;
return this.request("suspend", {})
.then(reponse => that.handleBreakEvent(null));
// .then(reponse => {
// return <WebKitProtocol.Response>{};
// });
}
public debugger_evaluateOnCallFrame(callFrameId: string, expression: string, objectGroup = 'dummyObjectGroup', returnByValue?: boolean): Promise<WebKitProtocol.Debugger.EvaluateOnCallFrameResponse> {
//return this.sendMessage('Debugger.evaluateOnCallFrame', <WebKitProtocol.Debugger.EvaluateOnCallFrameParams>{ callFrameId, expression, objectGroup, returnByValue });
//throw new Error("Not implemented");
var requestParams = {
expression: expression,
frame: callFrameId
};
let messageId = this._nextId++;
let that = this;
return this.request("evaluate", requestParams).then(response => {
return <WebKitProtocol.Debugger.EvaluateOnCallFrameResponse>{
result: {
result : that.v8ResultToInspectorResult(response),
wasThrown : false
}
}
});
}
public debugger_setPauseOnExceptions(state: string): Promise<WebKitProtocol.Response> {
//return this.sendMessage('Debugger.setPauseOnExceptions', <WebKitProtocol.Debugger.SetPauseOnExceptionsParams>{ state });
var requestParams = {
type: state !== 'none' ? state : "uncaught",
enabled: state !== 'none'
};
let messageId = this._nextId++;
return this.request("setexceptionbreak", requestParams).then(response => {
return new Promise((resolve, reject) => {
if (response.error) {
reject(response.error);
return;
}
resolve(<WebKitProtocol.Response>{ id: messageId });
});
});
}
public debugger_getScriptSource(scriptId: WebKitProtocol.Debugger.ScriptId): Promise<WebKitProtocol.Debugger.GetScriptSourceResponse> {
//return this.sendMessage('Debugger.getScriptSource', //<WebKitProtocol.Debugger.GetScriptSourceParams>{ scriptId });
var requestParams = {
includeSource: true,
types: 4,
ids: [Number(scriptId)]
};
let messageId = this._nextId++;
return this.request("scripts", requestParams).then(response => {
return new Promise((resolve, reject) => {
if (response.error) {
reject(response.error);
return;
}
let source = undefined;
if (Array.isArray(response))
{
source = response[0].source;
}
else if (response.result)
{
source = response.result[0].source;
}
else if (response.source) {
source = response.source;
}
let result = <WebKitProtocol.Debugger.GetScriptSourceResponse>{
id: messageId,
result: {
scriptSource: source
}
}
resolve(result);
});
});
}
private request(command, args): Promise<any> {
return new Promise((resolve, reject) => {
this._socket.request(command, { arguments: args }, response => {
if (!response.success) {
reject(new Error(response.message));
return;
}
if (response.refs) {
let refsLookup = {};
response.refs.forEach(function(r) { refsLookup[r.handle] = r; });
//TODO: response.body may be undefined in that case set it to {} here
response.body.refsLookup = refsLookup;
}
resolve(response.body);
});
});
}
////getProperties Functions. Implementation in RuntimeAgent.js
public runtime_getProperties(objectId: string, ownProperties: boolean, accessorPropertiesOnly: boolean): Promise<WebKitProtocol.Runtime.GetPropertiesResponse> {
//return this.sendMessage('Runtime.getProperties', <WebKitProtocol.Runtime.GetPropertiesParams>{ objectId, ownProperties, accessorPropertiesOnly });
//throw new Error("Not implemented");
return this.isScopeId(objectId).then(response => {
if (response) {
return this.getPropertiesOfScopeId(objectId);
}
else {
if (!ownProperties || accessorPropertiesOnly) {
// Temporary fix for missing getInternalProperties() implementation
// See the comment in RuntimeAgent.js->getProperties and GH issue #213 (node-inspector repo)
return { result: [] };
}
return this.getPropertiesOfObjectId(objectId);
}
}).then(response => {
let properties = response.result;
let result = [];
for (var i = 0; properties && i < properties.length; ++i) {
let property = properties[i];
//convert the result to <WebKitProtocol.Runtime.PropertyDescriptor>
result.push({
name: property.name,
writeable: property.writable,
enumerable: property.enumerable,
value: property.value
});
}
return <WebKitProtocol.Runtime.GetPropertiesResponse>{
result: {
result: result
}
};
});
}
private isScopeId(objectId: string): Promise<boolean> {
let SCOPE_ID_MATCHER = /^scope:(\d+):(\d+)$/;
return Promise.resolve(SCOPE_ID_MATCHER.test(objectId))
}
private getPropertiesOfScopeId(scopeId: string): Promise<any> {
let SCOPE_ID_MATCHER = /^scope:(\d+):(\d+)$/;
let scopeIdMatch = SCOPE_ID_MATCHER.exec(scopeId);
if (!scopeIdMatch) {
return Promise.reject(new Error('Invalid scope id "' + scopeId + '"'));
}
let that = this;
return this.request("scope",
{
number: Number(scopeIdMatch[2]),
frameNumber: Number(scopeIdMatch[1])
})
.then(response => {
return response.object.ref;
}).then(response => {
return that.getPropertiesOfObjectId(response);
});
};
private getPropertiesOfObjectId(objectId: string): Promise<any> {
let handle = parseInt(objectId, 10);
let request = { handles: [handle], includeSource: false };
let that = this;
return this.request("lookup", request)
.then(response => {
let obj;
let proto;
let props;
obj = response[handle];
proto = obj.proto;
props = obj.properties;
if (props) {
props = props.map(function(p) {
var ref = response.refsLookup[p.ref];
return {
name: String(p.name),
writable: (p.attributes & 1) != 1,
enumerable: (p.attributes & 2) != 2,
value: that.v8ResultToInspectorResult(ref)
};
});
}
if (proto)
props.push({
name: '__proto__',
value: that.v8RefToInspectorObject(response.refsLookup[proto.ref])
});
return { result: props };
});
}
////getProperties Functions END
public runtime_evaluate(expression: string, objectGroup = 'dummyObjectGroup', contextId?: number, returnByValue = false): Promise<WebKitProtocol.Runtime.EvaluateResponse> {
//return this.sendMessage('Runtime.evaluate', <WebKitProtocol.Runtime.EvaluateParams>{ expression, objectGroup, contextId, returnByValue });
throw new Error("Not implemented");
}
// private sendMessage(method: any, params?: any): Promise<WebKitProtocol.Response> {
// return this._socket.sendMessage({
// id: this._nextId++,
// method,
// params
// });
// }
}
/**
* Helper function to GET the contents of a url
*/
function getUrl(url: string): Promise<string> {
return new Promise((resolve, reject) => {
http.get(url, response => {
let jsonResponse = '';
response.on('data', chunk => jsonResponse += chunk);
response.on('end', () => {
resolve(jsonResponse);
});
}).on('error', e => {
reject('Cannot connect to the target: ' + e.message);
});
});
}