forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonoProxy.cs
More file actions
1957 lines (1774 loc) · 92.8 KB
/
Copy pathMonoProxy.cs
File metadata and controls
1957 lines (1774 loc) · 92.8 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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using BrowserDebugProxy;
using static System.Formats.Asn1.AsnWriter;
using System.Reflection;
using System.Collections.Concurrent;
namespace Microsoft.WebAssembly.Diagnostics
{
internal class MonoProxy : DevToolsProxy
{
internal List<string> UrlSymbolServerList { get; private set; }
internal string CachePathSymbolServer { get; private set; }
private readonly HashSet<SessionId> sessions = new HashSet<SessionId>();
private static readonly string[] s_executionContextIndependentCDPCommandNames = { "DotnetDebugger.setDebuggerProperty", "DotnetDebugger.runTests" };
internal ConcurrentExecutionContextDictionary Contexts = new ();
public static HttpClient HttpClient => new HttpClient();
// index of the runtime in a same JS page/process
public int RuntimeId { get; private init; }
public bool JustMyCode { get; private set; }
private PauseOnExceptionsKind _defaultPauseOnExceptions { get; set; }
public MonoProxy(ILogger logger, int runtimeId = 0, string loggerId = "", ProxyOptions options = null) : base(options, logger, loggerId)
{
UrlSymbolServerList = new List<string>();
RuntimeId = runtimeId;
_defaultPauseOnExceptions = PauseOnExceptionsKind.Unset;
JustMyCode = options?.JustMyCode ?? false;
}
internal virtual Task<Result> SendMonoCommand(SessionId id, MonoCommands cmd, CancellationToken token) => SendCommand(id, "Runtime.evaluate", JObject.FromObject(cmd), token);
internal void SendLog(SessionId sessionId, string message, CancellationToken token, string type = "warning")
{
if (!Contexts.TryGetCurrentExecutionContextValue(sessionId, out ExecutionContext context))
return;
/*var o = JObject.FromObject(new
{
entry = JObject.FromObject(new
{
source = "recommendation",
level = "warning",
text = message
})
});
SendEvent(id, "Log.enabled", null, token);
SendEvent(id, "Log.entryAdded", o, token);*/
var o = JObject.FromObject(new
{
type,
args = new JArray(JObject.FromObject(new
{
type = "string",
value = message,
})),
executionContextId = context.Id
});
SendEvent(sessionId, "Runtime.consoleAPICalled", o, token);
}
protected override async Task<bool> AcceptEvent(SessionId sessionId, JObject parms, CancellationToken token)
{
var method = parms["method"].Value<string>();
var args = parms["params"] as JObject;
switch (method)
{
case "Runtime.consoleAPICalled":
{
// Don't process events from sessions we aren't tracking
if (!Contexts.ContainsKey(sessionId))
return false;
string type = args["type"]?.ToString();
if (type == "debug")
{
JToken a = args["args"];
if (a is null)
break;
int aCount = a.Count();
if (aCount > 1 && a[0]?["value"]?.ToString() == MonoConstants.EVENT_RAISED)
{
if (a.Type != JTokenType.Array)
{
logger.LogDebug($"Invalid event raised args, expected an array: {a.Type}");
}
else
{
if (aCount > 2 &&
JObjectTryParse(a?[2]?["value"]?.Value<string>(), out JObject raiseArgs) &&
JObjectTryParse(a?[1]?["value"]?.Value<string>(), out JObject eventArgs))
{
await OnJSEventRaised(sessionId, eventArgs, token);
if (raiseArgs?["trace"]?.Value<bool>() == true) {
// Let the message show up on the console
return false;
}
}
}
// Don't log this message in the console
return true;
}
}
break;
}
case "Runtime.executionContextCreated":
{
await SendEvent(sessionId, method, args, token);
JToken ctx = args?["context"];
var aux_data = ctx?["auxData"] as JObject;
int id = ctx["id"].Value<int>();
if (aux_data != null)
{
bool? is_default = aux_data["isDefault"]?.Value<bool>();
if (is_default == true)
{
await OnDefaultContext(sessionId, new ExecutionContext(new MonoSDBHelper(this, logger, sessionId), id, aux_data, _defaultPauseOnExceptions), token);
}
}
return true;
}
case "Runtime.executionContextDestroyed":
{
Contexts.DestroyContext(sessionId, args["executionContextId"].Value<int>());
return false;
}
case "Runtime.executionContextsCleared":
{
Contexts.ClearContexts(sessionId);
return false;
}
case "Debugger.scriptParsed":
{
if (args["url"]?.ToString()?.Contains("/_framework/") == true) //is from dotnet runtime framework
{
if (Contexts.TryGetCurrentExecutionContextValue(sessionId, out ExecutionContext context))
context.FrameworkScriptList.Add(args["scriptId"].Value<int>());
}
return false;
}
case "Debugger.paused":
{
return await OnDebuggerPaused(sessionId, args, token);
}
case "Debugger.breakpointResolved":
{
break;
}
case "Target.attachedToTarget":
{
var targetType = args["targetInfo"]["type"]?.ToString();
if (targetType == "page")
await AttachToTarget(new SessionId(args["sessionId"]?.ToString()), token);
else if (targetType == "worker")
Contexts.CreateWorkerExecutionContext(new SessionId(args["sessionId"]?.ToString()), new SessionId(parms["sessionId"]?.ToString()), logger);
break;
}
case "Target.targetDestroyed":
{
await SendMonoCommand(sessionId, MonoCommands.DetachDebugger(RuntimeId), token);
break;
}
}
return false;
}
protected async Task<bool> OnDebuggerPaused(SessionId sessionId, JObject args, CancellationToken token)
{
if (args?["callFrames"]?.Value<JArray>()?.Count == 0) //new browser version can send pause of type "instrumentation" with an empty callstack
return false;
if (args["asyncStackTraceId"] != null)
{
if (!Contexts.TryGetCurrentExecutionContextValue(sessionId, out ExecutionContext context))
return false;
if (context.CopyDataFromParentContext())
{
var store = await LoadStore(sessionId, true, token);
foreach (var source in store.AllSources())
{
await OnSourceFileAdded(sessionId, source, context, token, false);
}
}
}
//TODO figure out how to stich out more frames and, in particular what happens when real wasm is on the stack
string top_func = args?["callFrames"]?[0]?["functionName"]?.Value<string>();
switch (top_func) {
// keep function names un-mangled via src\mono\browser\runtime\rollup.config.js
case "mono_wasm_set_entrypoint_breakpoint":
case "_mono_wasm_set_entrypoint_breakpoint":
{
await OnSetEntrypointBreakpoint(sessionId, args, token);
return true;
}
case "mono_wasm_runtime_ready":
case "_mono_wasm_runtime_ready":
{
await RuntimeReady(sessionId, token);
await SendResume(sessionId, token);
if (!JustMyCode)
await ReloadSymbolsFromSymbolServer(sessionId, Contexts.GetCurrentContext(sessionId), token);
return true;
}
case "mono_wasm_fire_debugger_agent_message_with_data_to_pause":
case "_mono_wasm_fire_debugger_agent_message_with_data_to_pause":
try
{
return await OnReceiveDebuggerAgentEvent(sessionId, args, await GetLastDebuggerAgentBuffer(sessionId, args, token), token);
}
catch (Exception) //if the page is refreshed maybe it stops here.
{
await SendResume(sessionId, token);
return true;
}
case "mono_wasm_fire_debugger_agent_message_with_data":
case "_mono_wasm_fire_debugger_agent_message_with_data":
{
//the only reason that we would get pause in this method is because the user is stepping out
//and as we don't want to pause in a debugger related function we continue stepping out
await SendCommand(sessionId, "Debugger.stepOut", new JObject(), token);
return true;
}
default:
{
if (JustMyCode)
{
if (!Contexts.TryGetCurrentExecutionContextValue(sessionId, out ExecutionContext context) || !context.IsRuntimeReady)
return false;
//avoid pausing when justMyCode is enabled and it's a wasm function
if (args?["callFrames"]?[0]?["scopeChain"]?[0]?["type"]?.Value<string>()?.Equals("wasm-expression-stack") == true)
{
await SendCommand(sessionId, "Debugger.stepOut", new JObject(), token);
return true;
}
//avoid pausing when justMyCode is enabled and it's a framework function
var scriptId = args?["callFrames"]?[0]?["location"]?["scriptId"]?.Value<int>();
if (!context.IsSkippingHiddenMethod && !context.IsSteppingThroughMethod && scriptId is not null && context.FrameworkScriptList.Contains(scriptId.Value))
{
await SendCommand(sessionId, "Debugger.stepOut", new JObject(), token);
return true;
}
}
break;
}
}
return false;
}
protected virtual async Task SendResume(SessionId id, CancellationToken token)
{
await SendCommand(id, "Debugger.resume", new JObject(), token);
}
protected async Task<bool> IsRuntimeAlreadyReadyAlready(SessionId sessionId, CancellationToken token)
{
if (Contexts.TryGetCurrentExecutionContextValue(sessionId, out ExecutionContext context) && context.IsRuntimeReady)
return true;
Result res = await SendMonoCommand(sessionId, MonoCommands.IsRuntimeReady(RuntimeId), token);
if (!res.IsOk || res.Value?["result"]?["value"]?.Type != JTokenType.Boolean) //if runtime is not ready this may be the response
return false;
return res.Value?["result"]?["value"]?.Value<bool>() ?? false;
}
private static PauseOnExceptionsKind GetPauseOnExceptionsStatusFromString(string state)
{
PauseOnExceptionsKind pauseOnException;
if (Enum.TryParse(state, true, out pauseOnException))
return pauseOnException;
return PauseOnExceptionsKind.Unset;
}
protected override async Task<bool> AcceptCommand(MessageId id, JObject parms, CancellationToken token)
{
var method = parms["method"].Value<string>();
var args = parms["params"] as JObject;
// Inspector doesn't use the Target domain or sessions
// so we try to init immediately
if (id == SessionId.Null)
await AttachToTarget(id, token);
if (!Contexts.TryGetCurrentExecutionContextValue(id, out ExecutionContext context) && !s_executionContextIndependentCDPCommandNames.Contains(method))
{
if (method == "Debugger.setPauseOnExceptions")
{
string state = args["state"].Value<string>();
var pauseOnException = GetPauseOnExceptionsStatusFromString(state);
if (pauseOnException != PauseOnExceptionsKind.Unset)
_defaultPauseOnExceptions = pauseOnException;
}
return method.StartsWith("DotnetDebugger.", StringComparison.OrdinalIgnoreCase);
}
switch (method)
{
case "Target.attachToTarget":
{
Result resp = await SendCommand(id, method, args, token);
await AttachToTarget(new SessionId(resp.Value["sessionId"]?.ToString()), token);
break;
}
case "Debugger.enable":
{
Result resp = await SendCommand(id, method, args, token);
if (!resp.IsOk)
{
SendResponse(id, resp, token);
return true;
}
context.DebugId = resp.Value["DebugId"]?.ToString();
if (await IsRuntimeAlreadyReadyAlready(id, token))
await RuntimeReady(id, token);
SendResponse(id, resp, token);
return true;
}
case "Debugger.getScriptSource":
{
string script = args?["scriptId"]?.Value<string>();
return await OnGetScriptSource(id, script, token);
}
case "Runtime.compileScript":
{
string exp = args?["expression"]?.Value<string>();
if (exp.StartsWith("//dotnet:", StringComparison.Ordinal))
{
OnCompileDotnetScript(id, token);
return true;
}
break;
}
case "Debugger.getPossibleBreakpoints":
{
Result resp = await SendCommand(id, method, args, token);
if (resp.IsOk && resp.Value["locations"].HasValues)
{
SendResponse(id, resp, token);
return true;
}
var start = SourceLocation.Parse(args?["start"] as JObject);
//FIXME support variant where restrictToFunction=true and end is omitted
var end = SourceLocation.Parse(args?["end"] as JObject);
if (start != null && end != null && await GetPossibleBreakpoints(id, start, end, token))
return true;
SendResponse(id, resp, token);
return true;
}
case "Debugger.setBreakpoint":
{
break;
}
case "Debugger.setBreakpointByUrl":
{
Result resp = await SendCommand(id, method, args, token);
if (!resp.IsOk)
{
SendResponse(id, resp, token);
return true;
}
try
{
string bpid = resp.Value["breakpointId"]?.ToString();
IEnumerable<object> locations = resp.Value["locations"]?.Values<object>();
var request = BreakpointRequest.Parse(bpid, args);
// is the store done loading?
bool loaded = context.Source.Task.IsCompleted;
if (!loaded)
{
// Send and empty response immediately if not
// and register the breakpoint for resolution
context.BreakpointRequests[bpid] = request;
SendResponse(id, resp, token);
}
if (await IsRuntimeAlreadyReadyAlready(id, token))
{
DebugStore store = await RuntimeReady(id, token);
Log("verbose", $"BP req {args}");
await SetBreakpoint(id, store, request, !loaded, false, token);
}
if (loaded)
{
// we were already loaded so we should send a response
// with the locations included and register the request
context.BreakpointRequests[bpid] = request;
var result = Result.OkFromObject(request.AsSetBreakpointByUrlResponse(locations));
SendResponse(id, result, token);
}
}
catch (Exception e)
{
logger.LogDebug($"Debugger.setBreakpointByUrl - {args} - failed with exception: {e}");
SendResponse(id, Result.Err($"Debugger.setBreakpointByUrl - {args} - failed with exception: {e}"), token);
}
return true;
}
case "Debugger.removeBreakpoint":
{
await RemoveBreakpoint(id, args, false, token);
break;
}
case "Debugger.resume":
{
await OnResume(id, token);
break;
}
case "Debugger.stepInto":
{
return await Step(id, StepKind.Into, token);
}
case "Debugger.setVariableValue":
{
if (!DotnetObjectId.TryParse(args?["callFrameId"], out DotnetObjectId objectId))
return false;
switch (objectId.Scheme)
{
case "scope":
return await OnSetVariableValue(id,
objectId.Value,
args?["variableName"]?.Value<string>(),
args?["newValue"],
token);
default:
return false;
}
}
case "Debugger.stepOut":
{
return await Step(id, StepKind.Out, token);
}
case "Debugger.stepOver":
{
return await Step(id, StepKind.Over, token);
}
case "Runtime.evaluate":
{
if (context.CallStack != null)
{
Frame scope = context.CallStack.First<Frame>();
return await OnEvaluateOnCallFrame(id,
scope.Id,
args?["expression"]?.Value<string>(), token);
}
break;
}
case "Debugger.evaluateOnCallFrame":
{
if (!DotnetObjectId.TryParse(args?["callFrameId"], out DotnetObjectId objectId))
return false;
switch (objectId.Scheme)
{
case "scope":
return await OnEvaluateOnCallFrame(id,
objectId.Value,
args?["expression"]?.Value<string>(), token);
default:
return false;
}
}
case "Runtime.getProperties":
{
if (!DotnetObjectId.TryParse(args?["objectId"], out DotnetObjectId objectId))
break;
var valueOrError = await RuntimeGetObjectMembers(id, objectId, args, token, true);
if (valueOrError.IsError)
{
logger.LogDebug($"Runtime.getProperties: {valueOrError.Error}");
SendResponse(id, valueOrError.Error.Value, token);
return true;
}
if (valueOrError.Value.JObject == null)
{
SendResponse(id, Result.Err($"Failed to get properties for '{objectId}'"), token);
return true;
}
SendResponse(id, Result.OkFromObject(valueOrError.Value.JObject), token);
return true;
}
case "Runtime.releaseObject":
{
if (!(DotnetObjectId.TryParse(args["objectId"], out DotnetObjectId objectId) && objectId.Scheme == "cfo_res"))
break;
await SendMonoCommand(id, MonoCommands.ReleaseObject(RuntimeId, objectId), token);
SendResponse(id, Result.OkFromObject(new { }), token);
return true;
}
case "Debugger.setPauseOnExceptions":
{
string state = args["state"].Value<string>();
var pauseOnException = GetPauseOnExceptionsStatusFromString(state);
if (pauseOnException != PauseOnExceptionsKind.Unset)
context.PauseOnExceptions = pauseOnException;
if (context.IsRuntimeReady)
await context.SdbAgent.EnableExceptions(context.PauseOnExceptions, token);
// Pass this on to JS too
return false;
}
case "Runtime.callFunctionOn":
{
try {
return await CallOnFunction(id, args, token);
}
catch (Exception ex) {
logger.LogDebug($"Runtime.callFunctionOn failed for {id} with args {args}: {ex}");
SendResponse(id,
Result.Exception(new ArgumentException(
$"Runtime.callFunctionOn not supported with ({args["objectId"]}).")),
token);
return true;
}
}
// Protocol extensions
case "DotnetDebugger.setDebuggerProperty":
{
foreach (KeyValuePair<string, JToken> property in args)
{
switch (property.Key)
{
case "JustMyCodeStepping":
await SetJustMyCode(id, (bool)property.Value, context, token);
break;
default:
logger.LogDebug($"DotnetDebugger.setDebuggerProperty failed for {property.Key} with value {property.Value}");
break;
}
}
return true;
}
case "DotnetDebugger.setNextIP":
{
var loc = SourceLocation.Parse(args?["location"] as JObject);
if (loc == null)
return false;
bool ret = await OnSetNextIP(id, loc, token);
if (ret)
SendResponse(id, Result.OkFromObject(new { }), token);
else
SendResponse(id, Result.Err("Set next instruction pointer failed."), token);
return true;
}
case "DotnetDebugger.applyUpdates":
{
if (await ApplyUpdates(id, args, token))
SendResponse(id, Result.OkFromObject(new { }), token);
else
SendResponse(id, Result.Err("ApplyUpdate failed."), token);
return true;
}
case "DotnetDebugger.setSymbolOptions":
{
SendResponse(id, Result.OkFromObject(new { }), token);
CachePathSymbolServer = args["symbolOptions"]?["cachePath"]?.Value<string>();
var urls = args["symbolOptions"]?["searchPaths"]?.Value<JArray>();
if (urls == null)
return true;
UrlSymbolServerList.Clear();
UrlSymbolServerList.AddRange(urls.Values<string>());
if (!JustMyCode)
{
if (!await IsRuntimeAlreadyReadyAlready(id, token))
return true;
return await ReloadSymbolsFromSymbolServer(id, context, token);
}
return true;
}
case "DotnetDebugger.getMethodLocation":
{
SendResponse(id, await GetMethodLocation(id, args, token), token);
return true;
}
case "DotnetDebugger.setEvaluationOptions":
{
//receive the available options from DAP to variables, stack and evaluate commands.
try {
if (args["options"]?["noFuncEval"]?.Value<bool>() == true)
context.AutoEvaluateProperties = false;
else
context.AutoEvaluateProperties = true;
SendResponse(id, Result.OkFromObject(new { }), token);
}
catch (Exception ex)
{
logger.LogDebug($"DotnetDebugger.setEvaluationOptions failed for {id} with args {args}: {ex}");
SendResponse(id,
Result.Exception(new ArgumentException(
$"DotnetDebugger.setEvaluationOptions got incorrect argument ({args})")),
token);
}
return true;
}
case "DotnetDebugger.runTests":
{
SendResponse(id, Result.OkFromObject(new { }), token);
while (!await IsRuntimeAlreadyReadyAlready(id, token)) //retry on debugger-tests until the runtime is ready
await Task.Delay(1000, token);
await RuntimeReady(id, token);
return true;
}
}
// for Dotnetdebugger.* messages, treat them as handled, thus not passing them on to the browser
return method.StartsWith("DotnetDebugger.", StringComparison.OrdinalIgnoreCase);
}
private async Task<bool> ReloadSymbolsFromSymbolServer(SessionId id, ExecutionContext context, CancellationToken token)
{
DebugStore store = await LoadStore(id, true, token);
store.UpdateSymbolStore(UrlSymbolServerList, CachePathSymbolServer);
await store.ReloadAllPDBsFromSymbolServersAndSendSources(this, id, context, token);
return true;
}
private async Task<bool> ApplyUpdates(MessageId id, JObject args, CancellationToken token)
{
var context = Contexts.GetCurrentContext(id);
string moduleGUID = args["moduleGUID"]?.Value<string>();
string dmeta = args["dmeta"]?.Value<string>();
string dil = args["dil"]?.Value<string>();
string dpdb = args["dpdb"]?.Value<string>();
var moduleId = await context.SdbAgent.GetModuleId(moduleGUID, token);
var applyUpdates = await context.SdbAgent.ApplyUpdates(moduleId, dmeta, dil, dpdb, token);
return applyUpdates;
}
private async Task SetJustMyCode(MessageId id, bool isEnabled, ExecutionContext context, CancellationToken token)
{
if (JustMyCode != isEnabled && isEnabled == false)
{
JustMyCode = isEnabled;
if (await IsRuntimeAlreadyReadyAlready(id, token))
await ReloadSymbolsFromSymbolServer(id, context, token);
}
JustMyCode = isEnabled;
SendResponse(id, Result.OkFromObject(new { justMyCodeEnabled = JustMyCode }), token);
}
internal async Task<Result> GetMethodLocation(MessageId id, JObject args, CancellationToken token)
{
DebugStore store = await RuntimeReady(id, token);
string aname = args["assemblyName"]?.Value<string>();
string typeName = args["typeName"]?.Value<string>();
string methodName = args["methodName"]?.Value<string>();
if (aname == null || typeName == null || methodName == null)
{
return Result.Err("Invalid protocol message '" + args + "'.");
}
// GetAssemblyByName seems to work on file names
AssemblyInfo assembly = store.GetAssemblyByName(aname);
assembly ??= store.GetAssemblyByName(aname + ".dll");
if (assembly == null)
{
return Result.Err($"Assembly '{aname}' not found," +
$"needed to get method location of '{typeName}:{methodName}'");
}
TypeInfo type = assembly.GetTypeByName(typeName);
if (type == null)
{
return Result.Err($"Type '{typeName}' not found.");
}
MethodInfo methodInfo = type.Methods.FirstOrDefault(m => m.Name == methodName);
if (methodInfo?.Source is null)
{
// Maybe this is an async method, in which case the debug info is attached
// to the async method implementation, in class named:
// `{type_name}.<method_name>::MoveNext`
methodInfo = assembly.TypesByName.Values.SingleOrDefault(t => t.FullName.StartsWith($"{typeName}.<{methodName}>"))?
.Methods.FirstOrDefault(mi => mi.Name == "MoveNext");
}
if (methodInfo == null)
{
return Result.Err($"Method '{typeName}:{methodName}' not found.");
}
string src_url = methodInfo.Assembly.Sources.Single(sf => sf.SourceId == methodInfo.SourceId).Url.ToString();
return Result.OkFromObject(new
{
result = new { line = methodInfo.StartLocation.Line, column = methodInfo.StartLocation.Column, url = src_url }
});
}
private async Task<bool> CallOnFunction(MessageId id, JObject args, CancellationToken token)
{
var context = Contexts.GetCurrentContext(id);
if (!DotnetObjectId.TryParse(args["objectId"], out DotnetObjectId objectId)) {
return false;
}
switch (objectId.Scheme)
{
case "method":
args["details"] = await context.SdbAgent.GetMethodProxy(objectId.ValueAsJson, token);
break;
case "object":
args["details"] = await context.SdbAgent.GetObjectProxy(objectId.Value, token);
break;
case "valuetype":
var valueType = context.SdbAgent.GetValueTypeClass(objectId.Value);
if (valueType == null)
throw new Exception($"Internal Error: No valuetype found for {objectId}.");
args["details"] = await valueType.GetProxy(context.SdbAgent, token);
break;
case "pointer":
args["details"] = await context.SdbAgent.GetPointerContent(objectId.Value, token);
break;
case "array":
args["details"] = await context.SdbAgent.GetArrayValuesProxy(objectId.Value, token);
break;
case "cfo_res":
Result cfo_res = await SendMonoCommand(id, MonoCommands.CallFunctionOn(RuntimeId, args), token);
cfo_res = Result.OkFromObject(new { result = cfo_res.Value?["result"]?["value"]});
SendResponse(id, cfo_res, token);
return true;
case "scope":
{
SendResponse(id,
Result.Exception(new ArgumentException(
$"Runtime.callFunctionOn not supported with scope ({objectId}).")),
token);
return true;
}
default:
return false;
}
Result res = await SendMonoCommand(id, MonoCommands.CallFunctionOn(RuntimeId, args), token);
if (!res.IsOk)
{
SendResponse(id, res, token);
return true;
}
if (res.Value?["result"]?["value"]?["type"] == null) //it means that is not a buffer returned from the debugger-agent
{
byte[] newBytes = Convert.FromBase64String(res.Value?["result"]?["value"]?["value"]?.Value<string>());
var retDebuggerCmdReader = new MonoBinaryReader(newBytes);
retDebuggerCmdReader.ReadByte(); //number of objects returned.
var obj = await context.SdbAgent.ValueCreator.ReadAsVariableValue(retDebuggerCmdReader, "ret", token);
/*JTokenType? res_value_type = res.Value?["result"]?["value"]?.Type;*/
res = Result.OkFromObject(new { result = obj["value"]});
SendResponse(id, res, token);
return true;
}
res = Result.OkFromObject(new { result = res.Value?["result"]?["value"]});
SendResponse(id, res, token);
return true;
}
private async Task<bool> OnSetVariableValue(MessageId id, int scopeId, string varName, JToken varValue, CancellationToken token)
{
ExecutionContext context = Contexts.GetCurrentContext(id);
Frame scope = context.CallStack.FirstOrDefault(s => s.Id == scopeId);
if (scope == null)
return false;
var varIds = scope.Method.Info.GetLiveVarsAt(scope.Location.IlLocation.Offset);
if (varIds == null)
return false;
var varToSetValue = varIds.FirstOrDefault(v => v.Name == varName);
if (varToSetValue == null)
return false;
var res = await context.SdbAgent.SetVariableValue(context.ThreadId, scopeId, varToSetValue.Index, varValue["value"].Value<string>(), token);
if (res)
SendResponse(id, Result.Ok(new JObject()), token);
else
SendResponse(id, Result.Err($"Unable to set '{varValue["value"].Value<string>()}' to variable '{varName}'"), token);
return true;
}
internal async Task<ValueOrError<GetMembersResult>> RuntimeGetObjectMembers(SessionId id, DotnetObjectId objectId, JToken args, CancellationToken token, bool sortByAccessLevel = false)
{
var context = Contexts.GetCurrentContext(id);
GetObjectCommandOptions getObjectOptions = GetObjectCommandOptions.WithProperties;
if (args != null)
{
if (args["accessorPropertiesOnly"]?.Value<bool>() == true)
getObjectOptions |= GetObjectCommandOptions.AccessorPropertiesOnly;
if (args["ownProperties"]?.Value<bool>() == true)
getObjectOptions |= GetObjectCommandOptions.OwnProperties;
if (args["forDebuggerDisplayAttribute"]?.Value<bool>() == true)
getObjectOptions |= GetObjectCommandOptions.ForDebuggerDisplayAttribute;
}
if (context.AutoEvaluateProperties)
getObjectOptions |= GetObjectCommandOptions.AutoExpandable;
if (JustMyCode)
getObjectOptions |= GetObjectCommandOptions.JustMyCode;
try
{
switch (objectId.Scheme)
{
// ToDo: fix Exception types here
case "scope":
GetMembersResult resScope = await GetScopeProperties(id, objectId.Value, token);
resScope.CleanUp();
return ValueOrError<GetMembersResult>.WithValue(resScope);
case "valuetype":
var resValue = await MemberObjectsExplorer.GetValueTypeMemberValues(
context.SdbAgent, objectId.Value, getObjectOptions, token, sortByAccessLevel, includeStatic: true);
resValue?.CleanUp();
return resValue switch
{
null => ValueOrError<GetMembersResult>.WithError($"Could not get properties for {objectId}"),
_ => ValueOrError<GetMembersResult>.WithValue(resValue)
};
case "array":
var resArr = await context.SdbAgent.GetArrayValues(objectId.Value, token);
return ValueOrError<GetMembersResult>.WithValue(GetMembersResult.FromValues(resArr));
case "method":
var resMethod = await context.SdbAgent.InvokeMethod(objectId, token);
return ValueOrError<GetMembersResult>.WithValue(GetMembersResult.FromValues(new JArray(resMethod)));
case "object":
var resObj = await MemberObjectsExplorer.GetObjectMemberValues(
context.SdbAgent, objectId.Value, getObjectOptions, token, sortByAccessLevel, includeStatic: true);
resObj.CleanUp();
return ValueOrError<GetMembersResult>.WithValue(resObj);
case "pointer":
var resPointer = new JArray { await context.SdbAgent.GetPointerContent(objectId.Value, token) };
return ValueOrError<GetMembersResult>.WithValue(GetMembersResult.FromValues(resPointer));
case "cfo_res":
Result res = await SendMonoCommand(id, MonoCommands.GetDetails(RuntimeId, objectId.Value, args), token);
string value_json_str = res.Value["result"]?["value"]?["__value_as_json_string__"]?.Value<string>();
if (res.IsOk && value_json_str == null)
return ValueOrError<GetMembersResult>.WithError(
$"Internal error: Could not find expected __value_as_json_string__ field in the result: {res}");
return value_json_str != null
? ValueOrError<GetMembersResult>.WithValue(GetMembersResult.FromValues(JArray.Parse(value_json_str)))
: ValueOrError<GetMembersResult>.WithError(res);
case "evaluationResult":
JArray evaluationRes = (JArray)context.SdbAgent.GetEvaluationResultProperties(objectId.ToString());
return ValueOrError<GetMembersResult>.WithValue(GetMembersResult.FromValues(evaluationRes));
default:
return ValueOrError<GetMembersResult>.WithError($"RuntimeGetProperties: unknown object id scheme: {objectId.Scheme}");
}
}
catch (Exception ex)
{
return ValueOrError<GetMembersResult>.WithError($"RuntimeGetProperties: Failed to get properties for {objectId}: {ex}");
}
}
protected async Task<bool> EvaluateCondition(SessionId sessionId, ExecutionContext context, Frame mono_frame, Breakpoint bp, CancellationToken token)
{
if (string.IsNullOrEmpty(bp?.Condition) || mono_frame == null)
return true;
string condition = bp.Condition;
if (bp.ConditionAlreadyEvaluatedWithError)
return false;
try {
var resolver = new MemberReferenceResolver(this, context, sessionId, mono_frame.Id, logger);
JObject retValue = await resolver.Resolve(condition, token);
retValue ??= await ExpressionEvaluator.CompileAndRunTheExpression(condition, resolver, logger, token);
if (retValue?["value"]?.Type == JTokenType.Boolean ||
retValue?["value"]?.Type == JTokenType.Integer ||
retValue?["value"]?.Type == JTokenType.Float) {
if (retValue?["value"]?.Value<bool>() == true)
return true;
}
else if (retValue?["value"] != null && // null object, missing value
retValue?["value"]?.Type != JTokenType.Null)
{
return true;
}
}
catch (ReturnAsErrorException raee)
{
logger.LogDebug($"Unable to evaluate breakpoint condition '{condition}': {raee}");
SendLog(sessionId, $"Unable to evaluate breakpoint condition '{condition}': {raee.Message}", token, type: "error");
bp.ConditionAlreadyEvaluatedWithError = true;
}
catch (Exception e)
{
Log("info", $"Unable to evaluate breakpoint condition '{condition}': {e}");
bp.ConditionAlreadyEvaluatedWithError = true;
}
return false;
}
private async Task<bool> ProcessEnC(SessionId sessionId, ExecutionContext context, MonoBinaryReader retDebuggerCmdReader, CancellationToken token)
{
int moduleId = retDebuggerCmdReader.ReadInt32();
int meta_size = retDebuggerCmdReader.ReadInt32();
byte[] meta_buf = retDebuggerCmdReader.ReadBytes(meta_size);
int pdb_size = retDebuggerCmdReader.ReadInt32();
byte[] pdb_buf = retDebuggerCmdReader.ReadBytes(pdb_size);
var assemblyName = await context.SdbAgent.GetAssemblyNameFromModule(moduleId, token);
DebugStore store = await LoadStore(sessionId, true, token);
AssemblyInfo asm = store.GetAssemblyByName(assemblyName);
var methods = DebugStore.EnC(context.SdbAgent, asm, meta_buf, pdb_buf);
foreach (var method in methods)
{
await ResetBreakpoint(sessionId, store, method, token);
}
var files = methods.Distinct(new MethodInfo.SourceComparer());
foreach (var file in files)
{
JObject scriptSource = JObject.FromObject(file.Source.ToScriptSource(context.Id, context.AuxData));
Log("debug", $"sending after update {file.Source.Url} {context.Id} {sessionId.sessionId}");
await SendEvent(sessionId, "Debugger.scriptParsed", scriptSource, token);
}
return true;
}
private async Task<bool> SendBreakpointsOfMethodUpdated(SessionId sessionId, ExecutionContext context, MonoBinaryReader retDebuggerCmdReader, CancellationToken token)
{
var methodId = retDebuggerCmdReader.ReadInt32();
var method = await context.SdbAgent.GetMethodInfo(methodId, token);
if (method == null || method.Info.Source is null)
{
return true;
}
foreach (var req in context.BreakpointRequests.Values)
{
if (req.TryResolve(method.Info.Source))
{
await SetBreakpoint(sessionId, context.store, req, true, true, token);
}
}
return true;
}
protected virtual async Task<bool> ShouldSkipMethod(SessionId sessionId, ExecutionContext context, EventKind event_kind, int frameNumber, int totalFrames, MethodInfoWithDebugInformation method, CancellationToken token)
{
var shouldReturn = await SkipMethod(
isSkippable: context.IsSkippingHiddenMethod,
shouldBeSkipped: event_kind != EventKind.UserBreak,
StepKind.Over);
context.IsSkippingHiddenMethod = false;
if (shouldReturn)
return true;
shouldReturn = await SkipMethod(
isSkippable: context.IsSteppingThroughMethod,
shouldBeSkipped: event_kind != EventKind.UserBreak && event_kind != EventKind.Breakpoint,
StepKind.Over);
context.IsSteppingThroughMethod = false;
if (shouldReturn)
return true;
if (frameNumber != 0)
return false;
if (method?.Info?.DebuggerAttrInfo?.DoAttributesAffectCallStack(JustMyCode) == true)
{
if (method.Info.DebuggerAttrInfo.ShouldStepOut(event_kind))
{
if (event_kind == EventKind.Step)
context.IsSkippingHiddenMethod = true;
if (await SkipMethod(isSkippable: true, shouldBeSkipped: true, StepKind.Out))
return true;