forked from dart-lang/webdev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchrome_proxy_service.dart
1759 lines (1572 loc) · 51.2 KB
/
chrome_proxy_service.dart
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:dwds/data/debug_event.dart';
import 'package:dwds/data/register_event.dart';
import 'package:dwds/src/config/tool_configuration.dart';
import 'package:dwds/src/connections/app_connection.dart';
import 'package:dwds/src/debugging/debugger.dart';
import 'package:dwds/src/debugging/execution_context.dart';
import 'package:dwds/src/debugging/inspector.dart';
import 'package:dwds/src/debugging/instance.dart';
import 'package:dwds/src/debugging/location.dart';
import 'package:dwds/src/debugging/modules.dart';
import 'package:dwds/src/debugging/remote_debugger.dart';
import 'package:dwds/src/debugging/skip_list.dart';
import 'package:dwds/src/events.dart';
import 'package:dwds/src/readers/asset_reader.dart';
import 'package:dwds/src/services/batched_expression_evaluator.dart';
import 'package:dwds/src/services/debug_service.dart';
import 'package:dwds/src/services/expression_compiler.dart';
import 'package:dwds/src/services/expression_evaluator.dart';
import 'package:dwds/src/utilities/dart_uri.dart';
import 'package:dwds/src/utilities/shared.dart';
import 'package:logging/logging.dart' hide LogRecord;
import 'package:pub_semver/pub_semver.dart' as semver;
import 'package:vm_service/vm_service.dart' hide vmServiceVersion;
import 'package:vm_service_interface/vm_service_interface.dart';
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart';
/// A proxy from the chrome debug protocol to the dart vm service protocol.
class ChromeProxyService implements VmServiceInterface {
/// Cache of all existing StreamControllers.
///
/// These are all created through [onEvent].
final _streamControllers = <String, StreamController<Event>>{};
/// The root `VM` instance. There can only be one of these, but its isolates
/// are dynamic and roughly map to chrome tabs.
final VM _vm;
/// Signals when isolate is initialized.
Future<void> get isInitialized => _initializedCompleter.future;
Completer<void> _initializedCompleter = Completer<void>();
/// Signals when isolate starts.
Future<void> get isStarted => _startedCompleter.future;
Completer<void> _startedCompleter = Completer<void>();
/// Signals when expression compiler is ready to evaluate.
Future<void> get isCompilerInitialized => _compilerCompleter.future;
Completer<void> _compilerCompleter = Completer<void>();
/// The root at which we're serving.
final String root;
final RemoteDebugger remoteDebugger;
final ExecutionContext executionContext;
final AssetReader _assetReader;
final Locations _locations;
final SkipLists _skipLists;
final Modules _modules;
/// Provides debugger-related functionality.
Future<Debugger> get debuggerFuture => _debuggerCompleter.future;
final _debuggerCompleter = Completer<Debugger>();
/// Provides variable inspection functionality.
AppInspector get inspector {
if (_inspector == null) {
throw StateError('No running isolate (inspector is not set).');
}
return _inspector!;
}
AppInspector? _inspector;
/// Determines if there an isolate running currently.
///
/// [_inspector] is `null` iff the isolate is not running,
/// for example, before the first isolate starts or during
/// a hot restart.
bool get _isIsolateRunning => _inspector != null;
StreamSubscription<ConsoleAPIEvent>? _consoleSubscription;
/// The flags that can be set at runtime via [setFlag] and their respective
/// values.
final Map<String, bool> _currentVmServiceFlags = {
_pauseIsolatesOnStartFlag: false,
};
/// The value of the [_pauseIsolatesOnStartFlag].
///
/// This value can be updated at runtime via [setFlag].
bool get pauseIsolatesOnStart =>
_currentVmServiceFlags[_pauseIsolatesOnStartFlag] ?? false;
/// Whether or not the connected app has a pending restart.
bool get hasPendingRestart => _resumeAfterRestartEventsController.hasListener;
final _resumeAfterRestartEventsController =
StreamController<String>.broadcast();
/// A global stream of resume events.
///
/// The values in the stream are the isolates IDs for the resume event.
///
/// IMPORTANT: This should only be listened to during a hot-restart or page
/// refresh. The debugger ignores any resume events as long as there is a
/// subscriber to this stream.
Stream<String> get resumeAfterRestartEventsStream =>
_resumeAfterRestartEventsController.stream;
final _logger = Logger('ChromeProxyService');
final ExpressionCompiler? _compiler;
ExpressionEvaluator? _expressionEvaluator;
bool terminatingIsolates = false;
ChromeProxyService._(
this._vm,
this.root,
this._assetReader,
this.remoteDebugger,
this._modules,
this._locations,
this._skipLists,
this.executionContext,
this._compiler,
) {
final debugger = Debugger.create(
remoteDebugger,
_streamNotify,
_locations,
_skipLists,
root,
);
debugger.then(_debuggerCompleter.complete);
}
static Future<ChromeProxyService> create(
RemoteDebugger remoteDebugger,
String root,
AssetReader assetReader,
AppConnection appConnection,
ExecutionContext executionContext,
ExpressionCompiler? expressionCompiler,
) async {
final vm = VM(
name: 'ChromeDebugProxy',
operatingSystem: Platform.operatingSystem,
startTime: DateTime.now().millisecondsSinceEpoch,
version: Platform.version,
isolates: [],
isolateGroups: [],
systemIsolates: [],
systemIsolateGroups: [],
targetCPU: 'Web',
hostCPU: 'DWDS',
architectureBits: -1,
pid: -1,
);
final modules = Modules(root);
final locations = Locations(assetReader, modules, root);
final skipLists = SkipLists();
final service = ChromeProxyService._(
vm,
root,
assetReader,
remoteDebugger,
modules,
locations,
skipLists,
executionContext,
expressionCompiler,
);
safeUnawaited(service.createIsolate(appConnection));
return service;
}
/// Initializes metadata in [Locations], [Modules], and [ExpressionCompiler].
void _initializeEntrypoint(String entrypoint) {
_locations.initialize(entrypoint);
_modules.initialize(entrypoint);
_skipLists.initialize();
// We do not need to wait for compiler dependencies to be updated as the
// [ExpressionEvaluator] is robust to evaluation requests during updates.
safeUnawaited(_updateCompilerDependencies(entrypoint));
}
Future<void> _updateCompilerDependencies(String entrypoint) async {
final loadStrategy = globalToolConfiguration.loadStrategy;
final moduleFormat = loadStrategy.moduleFormat;
final canaryFeatures = loadStrategy.buildSettings.canaryFeatures;
final experiments = loadStrategy.buildSettings.experiments;
_logger.info('Initializing expression compiler for $entrypoint');
final compilerOptions = CompilerOptions(
moduleFormat: ModuleFormat.values.byName(moduleFormat),
canaryFeatures: canaryFeatures,
experiments: experiments,
);
final compiler = _compiler;
if (compiler != null) {
await compiler.initialize(compilerOptions);
final dependencies =
await loadStrategy.moduleInfoForEntrypoint(entrypoint);
await captureElapsedTime(
() async {
final result = await compiler.updateDependencies(dependencies);
// Expression evaluation is ready after dependencies are updated.
if (!_compilerCompleter.isCompleted) _compilerCompleter.complete();
return result;
},
(result) => DwdsEvent.compilerUpdateDependencies(entrypoint),
);
}
}
Future<void> _prewarmExpressionCompilerCache() async {
// Exit early if the expression evaluation is not enabled.
if (_compiler == null || _expressionEvaluator == null) {
return;
}
// Wait until the inspector is ready.
await isInitialized;
// Pre-warm the flutter framework module cache in the compiler.
//
// Flutter inspector relies on evaluations in widget_inspector
// library, which is a part of the flutter framework module, to
// produce widget trees, draw the layout explorer, show hover
// cards etc.
// Pre-warming the cache while DevTools is still loading helps
// Flutter Inspector start faster.
final libraryToCache = await inspector.flutterWidgetInspectorLibrary;
if (libraryToCache != null) {
final isolateId = inspector.isolateRef.id;
final libraryId = libraryToCache.id;
if (isolateId != null && libraryId != null) {
_logger.finest(
'Caching ${libraryToCache.uri} in expression compiler worker',
);
await evaluate(isolateId, libraryId, 'true');
}
}
}
/// Creates a new isolate.
///
/// Only one isolate at a time is supported, but they should be cleaned up
/// with [destroyIsolate] and recreated with this method there is a hot
/// restart or full page refresh.
Future<void> createIsolate(AppConnection appConnection) async {
// Inspector is null if the previous isolate is destroyed.
if (_isIsolateRunning) {
throw UnsupportedError(
'Cannot create multiple isolates for the same app',
);
}
// Waiting for the debugger to be ready before initializing the entrypoint.
//
// Note: moving `await debugger` after the `_initializeEntryPoint` call
// causes `getcwd` system calls to fail. Since that system call is used
// in first `Uri.base` call in the expression compiler service isolate,
// the expression compiler service will fail to start.
// Issue: https://github.com/dart-lang/webdev/issues/1282
final debugger = await debuggerFuture;
final entrypoint = appConnection.request.entrypointPath;
_initializeEntrypoint(entrypoint);
debugger.notifyPausedAtStart();
_inspector = await AppInspector.create(
appConnection,
remoteDebugger,
_assetReader,
_locations,
root,
debugger,
executionContext,
);
final compiler = _compiler;
_expressionEvaluator = compiler == null
? null
: BatchedExpressionEvaluator(
entrypoint,
inspector,
debugger,
_locations,
_modules,
compiler,
);
safeUnawaited(_prewarmExpressionCompilerCache());
safeUnawaited(
appConnection.onStart.then((_) {
debugger.resumeFromStart();
_startedCompleter.complete();
}),
);
safeUnawaited(appConnection.onDone.then((_) => destroyIsolate()));
final isolateRef = inspector.isolateRef;
final timestamp = DateTime.now().millisecondsSinceEpoch;
// Listen for `registerExtension` and `postEvent` calls.
_setUpChromeConsoleListeners(isolateRef);
_vm.isolates?.add(isolateRef);
_streamNotify(
'Isolate',
Event(
kind: EventKind.kIsolateStart,
timestamp: timestamp,
isolate: isolateRef,
),
);
_streamNotify(
'Isolate',
Event(
kind: EventKind.kIsolateRunnable,
timestamp: timestamp,
isolate: isolateRef,
),
);
// TODO: We shouldn't need to fire these events since they exist on the
// isolate, but devtools doesn't recognize extensions after a page refresh
// otherwise.
for (final extensionRpc in inspector.isolate.extensionRPCs ?? []) {
_streamNotify(
'Isolate',
Event(
kind: EventKind.kServiceExtensionAdded,
timestamp: timestamp,
isolate: isolateRef,
)..extensionRPC = extensionRpc,
);
}
// If the new isolate was created as part of a restart, send a
// kPausePostRequest event to notify client that the app is paused so that
// it can resume:
if (hasPendingRestart) {
_streamNotify(
'Debug',
Event(
kind: EventKind.kPausePostRequest,
timestamp: timestamp,
isolate: isolateRef,
),
);
}
// The service is considered initialized when the first isolate is created.
if (!_initializedCompleter.isCompleted) _initializedCompleter.complete();
}
/// Should be called when there is a hot restart or full page refresh.
///
/// Clears out the [_inspector] and all related cached information.
void destroyIsolate() {
_logger.fine('Destroying isolate');
if (!_isIsolateRunning) return;
final isolate = inspector.isolate;
final isolateRef = inspector.isolateRef;
_initializedCompleter = Completer<void>();
_startedCompleter = Completer<void>();
_compilerCompleter = Completer<void>();
_streamNotify(
'Isolate',
Event(
kind: EventKind.kIsolateExit,
timestamp: DateTime.now().millisecondsSinceEpoch,
isolate: isolateRef,
),
);
_vm.isolates?.removeWhere((ref) => ref.id == isolate.id);
_inspector = null;
_expressionEvaluator?.close();
_consoleSubscription?.cancel();
_consoleSubscription = null;
}
Future<void> disableBreakpoints() async {
if (!_isIsolateRunning) return;
final isolate = inspector.isolate;
for (final breakpoint in isolate.breakpoints?.toList() ?? []) {
await (await debuggerFuture).removeBreakpoint(breakpoint.id);
}
}
@override
Future<Breakpoint> addBreakpoint(
String isolateId,
String scriptId,
int line, {
int? column,
}) {
return wrapInErrorHandlerAsync(
'addBreakpoint',
() => _addBreakpoint(isolateId, scriptId, line),
);
}
Future<Breakpoint> _addBreakpoint(
String isolateId,
String scriptId,
int line, {
int? column,
}) async {
await isInitialized;
_checkIsolate('addBreakpoint', isolateId);
return (await debuggerFuture).addBreakpoint(scriptId, line, column: column);
}
@override
Future<Breakpoint> addBreakpointAtEntry(String isolateId, String functionId) {
return _rpcNotSupportedFuture('addBreakpointAtEntry');
}
@override
Future<Breakpoint> addBreakpointWithScriptUri(
String isolateId,
String scriptUri,
int line, {
int? column,
}) =>
wrapInErrorHandlerAsync(
'addBreakpointWithScriptUri',
() => _addBreakpointWithScriptUri(
isolateId,
scriptUri,
line,
column: column,
),
);
Future<Breakpoint> _addBreakpointWithScriptUri(
String isolateId,
String scriptUri,
int line, {
int? column,
}) async {
await isInitialized;
_checkIsolate('addBreakpointWithScriptUri', isolateId);
if (Uri.parse(scriptUri).scheme == 'dart') {
// TODO(annagrin): Support setting breakpoints in dart SDK locations.
// Issue: https://github.com/dart-lang/webdev/issues/1584
throw RPCError(
'addBreakpoint',
102,
'The VM is unable to add a breakpoint '
'at the specified line or function: $scriptUri:$line:$column: '
'breakpoints in dart SDK locations are not supported yet.');
}
final dartUri = DartUri(scriptUri, root);
final scriptRef = await inspector.scriptRefFor(dartUri.serverPath);
final scriptId = scriptRef?.id;
if (scriptId == null) {
throw RPCError(
'addBreakpoint',
102,
'The VM is unable to add a breakpoint '
'at the specified line or function: $scriptUri:$line:$column: '
'cannot find script ID for ${dartUri.serverPath}');
}
return (await debuggerFuture).addBreakpoint(scriptId, line, column: column);
}
@override
Future<Response> callServiceExtension(
String method, {
String? isolateId,
Map? args,
}) =>
wrapInErrorHandlerAsync(
'callServiceExtension',
() => _callServiceExtension(
method,
isolateId: isolateId,
args: args,
),
);
Future<Response> _callServiceExtension(
String method, {
String? isolateId,
Map? args,
}) async {
await isInitialized;
isolateId ??= _inspector?.isolate.id;
_checkIsolate('callServiceExtension', isolateId);
args ??= <String, String>{};
final stringArgs = args.map(
(k, v) => MapEntry(
k is String ? k : jsonEncode(k),
v is String ? v : jsonEncode(v),
),
);
final expression = '''
${globalToolConfiguration.loadStrategy.loadModuleSnippet}("dart_sdk").developer.invokeExtension(
"$method", JSON.stringify(${jsonEncode(stringArgs)}));
''';
final result = await inspector.jsEvaluate(expression, awaitPromise: true);
final decodedResponse =
jsonDecode(result.value as String) as Map<String, dynamic>;
if (decodedResponse.containsKey('code') &&
decodedResponse.containsKey('message') &&
decodedResponse.containsKey('data')) {
// ignore: only_throw_errors
throw RPCError(
method,
decodedResponse['code'] as int,
// ignore: avoid-unnecessary-type-casts
decodedResponse['message'] as String,
decodedResponse['data'] as Map,
);
} else {
return Response()..json = decodedResponse;
}
}
@override
Future<Success> clearVMTimeline() {
return _rpcNotSupportedFuture('clearVMTimeline');
}
Future<Response> _getEvaluationResult(
String isolateId,
Future<RemoteObject> Function() evaluation,
String expression,
) async {
try {
final result = await evaluation();
if (!_isIsolateRunning || isolateId != inspector.isolate.id) {
_logger.fine('Cannot get evaluation result for isolate $isolateId: '
' isolate exited.');
return ErrorRef(
kind: 'error',
message: 'Isolate exited',
id: createId(),
);
}
// Handle compilation errors, internal errors,
// and reference errors from JavaScript evaluation in chrome.
if (_hasEvaluationError(result.type)) {
if (_hasReportableEvaluationError(result.type)) {
_logger.warning('Failed to evaluate expression \'$expression\': '
'${result.type}: ${result.value}.');
_logger.info('Please follow instructions at '
'https://github.com/dart-lang/webdev/issues/956 '
'to file a bug.');
}
return ErrorRef(
kind: 'error',
message: '${result.type}: ${result.value}',
id: createId(),
);
}
return await _instanceRef(result);
} on RPCError catch (_) {
rethrow;
} catch (e, s) {
// Handle errors that throw exceptions, such as invalid JavaScript
// generated by the expression evaluator.
_logger.warning('Failed to evaluate expression \'$expression\'. ');
_logger.info('Please follow instructions at '
'https://github.com/dart-lang/webdev/issues/956 '
'to file a bug.');
_logger.info('$e:$s');
return ErrorRef(kind: 'error', message: '<unknown>', id: createId());
}
}
bool _hasEvaluationError(String type) => type.contains('Error');
// Decides if the error is serious enough to be shown to the user
// to encourage bug reporting.
bool _hasReportableEvaluationError(String type) {
if (!_hasEvaluationError(type)) return false;
if (type == EvaluationErrorKind.compilation ||
type == EvaluationErrorKind.asyncFrame) {
return false;
}
return true;
}
@override
Future<Response> evaluate(
String isolateId,
String targetId,
String expression, {
Map<String, String>? scope,
// TODO(798) - respect disableBreakpoints.
bool? disableBreakpoints,
/// Note that `idZoneId` arguments will be ignored. This parameter is only
/// here to make this method is a valid override of
/// [VmServiceInterface.evaluate].
String? idZoneId,
}) =>
wrapInErrorHandlerAsync(
'evaluate',
() => _evaluate(
isolateId,
targetId,
expression,
scope: scope,
),
);
Future<Response> _evaluate(
String isolateId,
String targetId,
String expression, {
Map<String, String>? scope,
}) {
// TODO(798) - respect disableBreakpoints.
return captureElapsedTime(
() async {
await isInitialized;
final evaluator = _expressionEvaluator;
if (evaluator != null) {
await isCompilerInitialized;
_checkIsolate('evaluate', isolateId);
late Obj object;
try {
object = await inspector.getObject(targetId);
} catch (_) {
return ErrorRef(
kind: 'error',
message: 'Evaluate is called on an unsupported target:'
'$targetId',
id: createId(),
);
}
final library =
object is Library ? object : inspector.isolate.rootLib;
if (object is Instance) {
// Evaluate is called on a target - convert this to a dart
// expression and scope by adding a target variable to the
// expression and the scope, for example:
//
// Library: 'package:hello_world/main.dart'
// Expression: 'hashCode' => 'x.hashCode'
// Scope: {} => { 'x' : targetId }
final target = _newVariableForScope(scope);
expression = '$target.$expression';
scope = (scope ?? {})..addAll({target: targetId});
}
return await _getEvaluationResult(
isolateId,
() => evaluator.evaluateExpression(
isolateId,
library?.uri,
expression,
scope,
),
expression,
);
}
throw RPCError(
'evaluate',
RPCErrorKind.kInvalidRequest.code,
'Expression evaluation is not supported for this configuration.',
);
},
(result) => DwdsEvent.evaluate(expression, result),
);
}
String _newVariableForScope(Map<String, String>? scope) {
// Find a new variable not in scope.
var candidate = 'x';
while (scope?.containsKey(candidate) ?? false) {
candidate += '\$1';
}
return candidate;
}
@override
Future<Response> evaluateInFrame(
String isolateId,
int frameIndex,
String expression, {
Map<String, String>? scope,
// TODO(798) - respect disableBreakpoints.
bool? disableBreakpoints,
/// Note that `idZoneId` arguments will be ignored. This parameter is only
/// here to make this method is a valid override of
/// [VmServiceInterface.evaluateInFrame].
String? idZoneId,
}) =>
wrapInErrorHandlerAsync(
'evaluateInFrame',
() => _evaluateInFrame(
isolateId,
frameIndex,
expression,
scope: scope,
),
);
Future<Response> _evaluateInFrame(
String isolateId,
int frameIndex,
String expression, {
Map<String, String>? scope,
}) {
// TODO(798) - respect disableBreakpoints.
return captureElapsedTime(
() async {
await isInitialized;
final evaluator = _expressionEvaluator;
if (evaluator != null) {
await isCompilerInitialized;
_checkIsolate('evaluateInFrame', isolateId);
return await _getEvaluationResult(
isolateId,
() => evaluator.evaluateExpressionInFrame(
isolateId,
frameIndex,
expression,
scope,
),
expression,
);
}
throw RPCError(
'evaluateInFrame',
RPCErrorKind.kInvalidRequest.code,
'Expression evaluation is not supported for this configuration.',
);
},
(result) => DwdsEvent.evaluateInFrame(expression, result),
);
}
@override
Future<AllocationProfile> getAllocationProfile(
String isolateId, {
bool? gc,
bool? reset,
}) {
return _rpcNotSupportedFuture('getAllocationProfile');
}
@override
Future<ClassList> getClassList(String isolateId) {
// See dart-lang/webdev/issues/971.
return _rpcNotSupportedFuture('getClassList');
}
@override
Future<FlagList> getFlagList() {
return wrapInErrorHandlerAsync(
'getFlagList',
_getFlagList,
);
}
Future<FlagList> _getFlagList() {
final flags = _currentVmServiceFlags.entries.map<Flag>(
(entry) => Flag(
name: entry.key,
valueAsString: '${entry.value}',
),
);
return Future.value(FlagList(flags: flags.toList()));
}
@override
Future<InstanceSet> getInstances(
String isolateId,
String classId,
int limit, {
bool? includeImplementers,
bool? includeSubclasses,
String? idZoneId,
}) {
return _rpcNotSupportedFuture('getInstances');
}
@override
Future<Isolate> getIsolate(String isolateId) => wrapInErrorHandlerAsync(
'getIsolate',
() => _getIsolate(isolateId),
);
Future<Isolate> _getIsolate(String isolateId) {
return captureElapsedTime(
() async {
await isInitialized;
_checkIsolate('getIsolate', isolateId);
return inspector.isolate;
},
(result) => DwdsEvent.getIsolate(),
);
}
@override
Future<MemoryUsage> getMemoryUsage(String isolateId) =>
wrapInErrorHandlerAsync(
'getMemoryUsage',
() => _getMemoryUsage(isolateId),
);
Future<MemoryUsage> _getMemoryUsage(String isolateId) async {
await isInitialized;
_checkIsolate('getMemoryUsage', isolateId);
return inspector.getMemoryUsage();
}
@override
Future<Obj> getObject(
String isolateId,
String objectId, {
int? offset,
int? count,
/// Note that `idZoneId` arguments will be ignored. This parameter is only
/// here to make this method is a valid override of
/// [VmServiceInterface.getObject].
String? idZoneId,
}) =>
wrapInErrorHandlerAsync(
'getObject',
() => _getObject(
isolateId,
objectId,
offset: offset,
count: count,
),
);
Future<Obj> _getObject(
String isolateId,
String objectId, {
int? offset,
int? count,
}) async {
await isInitialized;
_checkIsolate('getObject', isolateId);
return inspector.getObject(objectId, offset: offset, count: count);
}
@override
Future<ScriptList> getScripts(String isolateId) => wrapInErrorHandlerAsync(
'getScripts',
() => _getScripts(isolateId),
);
Future<ScriptList> _getScripts(String isolateId) {
return captureElapsedTime(
() async {
await isInitialized;
_checkIsolate('getScripts', isolateId);
return inspector.getScripts();
},
(result) => DwdsEvent.getScripts(),
);
}
@override
Future<SourceReport> getSourceReport(
String isolateId,
List<String> reports, {
String? scriptId,
int? tokenPos,
int? endTokenPos,
bool? forceCompile,
bool? reportLines,
List<String>? libraryFilters,
// Note: Ignore the optional librariesAlreadyCompiled parameter. It is here
// to match the VM service interface.
List<String>? librariesAlreadyCompiled,
}) =>
wrapInErrorHandlerAsync(
'getSourceReport',
() => _getSourceReport(
isolateId,
reports,
scriptId: scriptId,
tokenPos: tokenPos,
endTokenPos: endTokenPos,
forceCompile: forceCompile,
reportLines: reportLines,
libraryFilters: libraryFilters,
),
);
Future<SourceReport> _getSourceReport(
String isolateId,
List<String> reports, {
String? scriptId,
int? tokenPos,
int? endTokenPos,
bool? forceCompile,
bool? reportLines,
List<String>? libraryFilters,
}) {
return captureElapsedTime(
() async {
await isInitialized;
_checkIsolate('getSourceReport', isolateId);
return await inspector.getSourceReport(
reports,
scriptId: scriptId,
tokenPos: tokenPos,
endTokenPos: endTokenPos,
forceCompile: forceCompile,
reportLines: reportLines,
libraryFilters: libraryFilters,
);
},
(result) => DwdsEvent.getSourceReport(),
);
}
/// Returns the current stack.
///
/// Throws RPCError the corresponding isolate is not paused.
///
/// The returned stack will contain up to [limit] frames if provided.
@override
Future<Stack> getStack(
String isolateId, {
int? limit,
/// Note that `idZoneId` arguments will be ignored. This parameter is only
/// here to make this method is a valid override of
/// [VmServiceInterface.getStack].
String? idZoneId,
}) =>
wrapInErrorHandlerAsync(
'getStack',
() => _getStack(isolateId, limit: limit),
);
Future<Stack> _getStack(String isolateId, {int? limit}) async {
await isInitialized;
await isStarted;
_checkIsolate('getStack', isolateId);
return (await debuggerFuture).getStack(limit: limit);
}
@override
Future<VM> getVM() => wrapInErrorHandlerAsync('getVM', _getVM);
Future<VM> _getVM() {
return captureElapsedTime(
() async {
await isInitialized;
return _vm;
},
(result) => DwdsEvent.getVM(),
);
}
@override
Future<Timeline> getVMTimeline({
int? timeOriginMicros,
int? timeExtentMicros,
}) {
return _rpcNotSupportedFuture('getVMTimeline');
}