/
MonoProxy.cs
1780 lines (1589 loc) · 81.8 KB
/
MonoProxy.cs
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;
namespace Microsoft.WebAssembly.Diagnostics
{
internal class MonoProxy : DevToolsProxy
{
private IList<string> urlSymbolServerList;
private HashSet<SessionId> sessions = new HashSet<SessionId>();
protected Dictionary<SessionId, ExecutionContext> contexts = new Dictionary<SessionId, ExecutionContext>();
private const string sPauseOnUncaught = "pause_on_uncaught";
private const string sPauseOnCaught = "pause_on_caught";
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; }
protected readonly ProxyOptions _options;
public MonoProxy(ILogger logger, IList<string> urlSymbolServerList, int runtimeId = 0, string loggerId = "", ProxyOptions options = null) : base(logger, loggerId)
{
this.urlSymbolServerList = urlSymbolServerList ?? new List<string>();
RuntimeId = runtimeId;
_options = options;
}
internal ExecutionContext GetContext(SessionId sessionId)
{
if (contexts.TryGetValue(sessionId, out ExecutionContext context))
return context;
throw new ArgumentException($"Invalid Session: \"{sessionId}\"", nameof(sessionId));
}
private bool UpdateContext(SessionId sessionId, ExecutionContext executionContext, out ExecutionContext previousExecutionContext)
{
bool previous = contexts.TryGetValue(sessionId, out previousExecutionContext);
contexts[sessionId] = executionContext;
return previous;
}
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.TryGetValue(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":
{
string type = args["type"]?.ToString();
if (type == "debug")
{
JToken a = args["args"];
if (a is null)
break;
int aCount = a.Count();
if (aCount >= 2 &&
a[0]?["value"]?.ToString() == MonoConstants.RUNTIME_IS_READY &&
a[1]?["value"]?.ToString() == MonoConstants.RUNTIME_IS_READY_ID)
{
if (aCount > 2)
{
try
{
// The optional 3rd argument is the stringified assembly
// list so that we don't have to make more round trips
ExecutionContext context = GetContext(sessionId);
string loaded = a[2]?["value"]?.ToString();
if (loaded != null)
context.LoadedFiles = JToken.Parse(loaded).ToObject<string[]>();
}
catch (InvalidCastException ice)
{
Log("verbose", ice.ToString());
}
}
await RuntimeReady(sessionId, token);
}
else 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), token);
}
}
return true;
}
case "Runtime.exceptionThrown":
{
// Don't process events from sessions we aren't tracking
if (!contexts.TryGetValue(sessionId, out ExecutionContext context))
return false;
if (!context.IsRuntimeReady)
{
string exceptionError = args?["exceptionDetails"]?["exception"]?["value"]?.Value<string>();
if (exceptionError == sPauseOnUncaught || exceptionError == sPauseOnCaught)
return true;
}
break;
}
case "Debugger.paused":
{
// Don't process events from sessions we aren't tracking
if (!contexts.TryGetValue(sessionId, out ExecutionContext context))
return false;
if (!context.IsRuntimeReady)
{
string reason = args?["reason"]?.Value<string>();
if (reason == "exception")
{
string exceptionError = args?["data"]?["value"]?.Value<string>();
if (exceptionError == sPauseOnUncaught)
{
await SendResume(sessionId, token);
if (context.PauseOnExceptions == PauseOnExceptionsKind.Unset)
context.PauseOnExceptions = PauseOnExceptionsKind.Uncaught;
return true;
}
if (exceptionError == sPauseOnCaught)
{
await SendResume(sessionId, token);
context.PauseOnExceptions = PauseOnExceptionsKind.All;
return true;
}
}
}
//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\wasm\runtime\rollup.config.js
case "mono_wasm_runtime_ready":
case "_mono_wasm_runtime_ready":
{
await RuntimeReady(sessionId, token);
await SendResume(sessionId, token);
return true;
}
case "mono_wasm_fire_debugger_agent_message":
case "_mono_wasm_fire_debugger_agent_message":
{
try {
return await OnReceiveDebuggerAgentEvent(sessionId, args, token);
}
catch (Exception) //if the page is refreshed maybe it stops here.
{
await SendResume(sessionId, token);
return true;
}
}
}
break;
}
case "Debugger.breakpointResolved":
{
break;
}
case "Debugger.scriptParsed":
{
string url = args?["url"]?.Value<string>() ?? "";
switch (url)
{
case var _ when url == "":
case var _ when url.StartsWith("wasm://", StringComparison.Ordinal):
case var _ when url.EndsWith(".wasm", StringComparison.Ordinal):
{
logger.LogTrace($"ignoring wasm: Debugger.scriptParsed {url}");
return true;
}
}
logger.LogTrace($"proxying Debugger.scriptParsed ({sessionId.sessionId}) {url} {args}");
break;
}
case "Target.attachedToTarget":
{
if (args["targetInfo"]["type"]?.ToString() == "page")
await AttachToTarget(new SessionId(args["sessionId"]?.ToString()), token);
break;
}
case "Target.targetDestroyed":
{
await SendMonoCommand(sessionId, MonoCommands.DetachDebugger(RuntimeId), token);
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.TryGetValue(sessionId, out ExecutionContext context) && context.IsRuntimeReady)
return true;
Result res = await SendMonoCommand(sessionId, MonoCommands.IsRuntimeReady(RuntimeId), token);
return res.Value?["result"]?["value"]?.Value<bool>() ?? false;
}
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.TryGetValue(id, out ExecutionContext context))
return false;
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);
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;
}
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);
}
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>();
context.PauseOnExceptions = state switch
{
"all" => PauseOnExceptionsKind.All,
"uncaught" => PauseOnExceptionsKind.Uncaught,
"none" => PauseOnExceptionsKind.None,
_ => PauseOnExceptionsKind.Unset
};
if (context.IsRuntimeReady)
await context.SdbAgent.EnableExceptions(context.PauseOnExceptions, token);
// Pass this on to JS too
return false;
}
// Protocol extensions
case "DotnetDebugger.setNextIP":
{
var loc = SourceLocation.Parse(args?["location"] as JObject);
if (loc == null)
return false;
var ret = await OnSetNextIP(id, loc, token);
if (ret == true)
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.addSymbolServerUrl":
{
string url = args["url"]?.Value<string>();
if (!string.IsNullOrEmpty(url) && !urlSymbolServerList.Contains(url))
urlSymbolServerList.Add(url);
return true;
}
case "DotnetDebugger.getMethodLocation":
{
SendResponse(id, await GetMethodLocation(id, args, token), token);
return true;
}
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;
}
}
case "DotnetDebugger.justMyCode":
{
try
{
SetJustMyCode(id, args, token);
}
catch (Exception ex)
{
logger.LogDebug($"DotnetDebugger.justMyCode failed for {id} with args {args}: {ex}");
SendResponse(id,
Result.Exception(new ArgumentException(
$"DotnetDebugger.justMyCode got incorrect argument ({args})")),
token);
}
return true;
}
}
return false;
}
private async Task<bool> ApplyUpdates(MessageId id, JObject args, CancellationToken token)
{
var context = GetContext(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 void SetJustMyCode(MessageId id, JObject args, CancellationToken token)
{
var isEnabled = args["enabled"]?.Value<bool>();
if (isEnabled == null)
throw new ArgumentException();
JustMyCode = isEnabled.Value;
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);
if (assembly == null)
assembly = store.GetAssemblyByName(aname + ".exe");
if (assembly == null)
assembly = store.GetAssemblyByName(aname + ".dll");
if (assembly == null)
{
return Result.Err("Assembly '" + aname + "' not found.");
}
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 == 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;
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 = GetContext(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 = GetContext(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 = GetContext(id);
GetObjectCommandOptions getObjectOptions = GetObjectCommandOptions.WithProperties;
if (args != null)
{
if (args["accessorPropertiesOnly"] != null && args["accessorPropertiesOnly"].Value<bool>())
{
getObjectOptions |= GetObjectCommandOptions.AccessorPropertiesOnly;
}
if (args["ownProperties"] != null && args["ownProperties"].Value<bool>())
{
getObjectOptions |= GetObjectCommandOptions.OwnProperties;
}
}
try
{
switch (objectId.Scheme)
{
case "scope":
Result resScope = await GetScopeProperties(id, objectId.Value, token);
return resScope.IsOk
? ValueOrError<GetMembersResult>.WithValue(
new GetMembersResult((JArray)resScope.Value?["result"], sortByAccessLevel: false))
: ValueOrError<GetMembersResult>.WithError(resScope);
case "valuetype":
var resValue = await MemberObjectsExplorer.GetValueTypeMemberValues(
context.SdbAgent, objectId.Value, getObjectOptions, token, sortByAccessLevel, includeStatic: false);
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);
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);
if (retValue == null)
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, token);
AssemblyInfo asm = store.GetAssemblyByName(assemblyName);
var methods = DebugStore.EnC(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)
{
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 j, 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 (j == 0 && 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;
}
if (!method.Info.DebuggerAttrInfo.HasStepperBoundary)
{
if (event_kind == EventKind.Step ||
(JustMyCode && (event_kind == EventKind.Breakpoint || event_kind == EventKind.UserBreak)))
{
if (context.IsResumedAfterBp)
context.IsResumedAfterBp = false;
else if (event_kind != EventKind.UserBreak)
context.IsSteppingThroughMethod = true;
if (await SkipMethod(isSkippable: true, shouldBeSkipped: true, StepKind.Out))
return true;
}
if (event_kind == EventKind.Breakpoint)
context.IsResumedAfterBp = true;
}
}
return false;
async Task<bool> SkipMethod(bool isSkippable, bool shouldBeSkipped, StepKind stepKind)
{
if (isSkippable && shouldBeSkipped)
{
await context.SdbAgent.Step(context.ThreadId, stepKind, token);
await SendResume(sessionId, token);
return true;
}
return false;
}
}
protected virtual async Task<bool> SendCallStack(SessionId sessionId, ExecutionContext context, string reason, int thread_id, Breakpoint bp, JObject data, JObject args, EventKind event_kind, CancellationToken token)
{
var orig_callframes = args?["callFrames"]?.Values<JObject>();
var callFrames = new List<object>();
var frames = new List<Frame>();
using var commandParamsWriter = new MonoBinaryWriter();
commandParamsWriter.Write(thread_id);
commandParamsWriter.Write(0);
commandParamsWriter.Write(-1);
using var retDebuggerCmdReader = await context.SdbAgent.SendDebuggerAgentCommand(CmdThread.GetFrameInfo, commandParamsWriter, token);
var frame_count = retDebuggerCmdReader.ReadInt32();
//Console.WriteLine("frame_count - " + frame_count);
for (int j = 0; j < frame_count; j++) {
var frame_id = retDebuggerCmdReader.ReadInt32();
var methodId = retDebuggerCmdReader.ReadInt32();
var il_pos = retDebuggerCmdReader.ReadInt32();
var flags = retDebuggerCmdReader.ReadByte();
DebugStore store = await LoadStore(sessionId, token);
var method = await context.SdbAgent.GetMethodInfo(methodId, token);
if (await ShouldSkipMethod(sessionId, context, event_kind, j, method, token))
return true;
SourceLocation location = method?.Info.GetLocationByIl(il_pos);
// When hitting a breakpoint on the "IncrementCount" method in the standard
// Blazor project template, one of the stack frames is inside mscorlib.dll
// and we get location==null for it. It will trigger a NullReferenceException
// if we don't skip over that stack frame.
if (location == null)
{
continue;
}
// logger.LogTrace($"frame il offset: {il_pos} method token: {method.Info.Token} assembly name: {method.Info.Assembly.Name}");
// logger.LogTrace($"\tmethod {method.Name} location: {location}");
frames.Add(new Frame(method, location, frame_id));
callFrames.Add(new
{
functionName = method.Name,
callFrameId = $"dotnet:scope:{frame_id}",