Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
760 lines (699 loc) · 38.4 KB
/
Copy pathProgram.cs
File metadata and controls
760 lines (699 loc) · 38.4 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
// S2 Step 11 — OwnSharp.WeakTargetProbe. See the .csproj for the two-mode contract.
using System.ComponentModel;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
using System.Text;
using System.Text.Json;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
internal static class Program
{
private static int Main(string[] args)
{
try
{
if (args.Length >= 1 && args[0] == "bind") return BindMode.Run(args);
if (args.Length >= 1 && args[0] == "probe") return ProbeMode.Run(args);
Console.Error.WriteLine("weak-target-probe: usage: (bind|probe) ...");
return 2;
}
catch (Exception e)
{
Console.Error.WriteLine($"weak-target-probe: internal error ({e.GetType().Name}: {e.Message})");
return 2;
}
}
// --- deterministic canonical JSON (sorted keys, compact, trailing LF) for a restricted
// value domain (bool / non-negative long / printable-ASCII string / array / object) so the
// bytes byte-match Python json.dumps(sort_keys=True, separators=(",",":"), ensure_ascii=False).
internal static void WriteCanonical(string path, object value)
{
var sb = new StringBuilder();
Emit(sb, value);
sb.Append('\n');
File.WriteAllBytes(path, Encoding.UTF8.GetBytes(sb.ToString()));
}
private static void Emit(StringBuilder sb, object? v)
{
switch (v)
{
case null: sb.Append("null"); break;
case bool b: sb.Append(b ? "true" : "false"); break;
case int i: sb.Append(i.ToString(System.Globalization.CultureInfo.InvariantCulture)); break;
case long l: sb.Append(l.ToString(System.Globalization.CultureInfo.InvariantCulture)); break;
case string s: EmitString(sb, s); break;
case IReadOnlyList<object> arr:
sb.Append('[');
for (var k = 0; k < arr.Count; k++) { if (k > 0) sb.Append(','); Emit(sb, arr[k]); }
sb.Append(']');
break;
case IReadOnlyDictionary<string, object> obj:
sb.Append('{');
var keys = obj.Keys.ToList();
keys.Sort(StringComparer.Ordinal);
for (var k = 0; k < keys.Count; k++)
{
if (k > 0) sb.Append(',');
EmitString(sb, keys[k]);
sb.Append(':');
Emit(sb, obj[keys[k]]);
}
sb.Append('}');
break;
default: throw new InvalidOperationException($"non-canonical value type {v.GetType()}");
}
}
private static void EmitString(StringBuilder sb, string s)
{
sb.Append('"');
foreach (var ch in s)
{
if (ch == '"' || ch == '\\') { sb.Append('\\').Append(ch); }
else if (ch < 0x20) throw new InvalidOperationException("control char in canonical string");
else sb.Append(ch);
}
sb.Append('"');
}
// The single canonical signature form used by BOTH bind (Roslyn) and probe (reflection).
internal static string Sig(string returnFull, string declFull, string method, IEnumerable<string> paramFull)
=> $"{returnFull} {declFull}.{method}({string.Join(", ", paramFull)})";
}
// --- BIND MODE (G1, G2) ------------------------------------------------------------------
internal static class BindMode
{
public static int Run(string[] args)
{
var a = Args.Parse(args, 1);
var preText = SourceText.From(File.ReadAllText(a["preimage"]), Encoding.UTF8);
var postText = SourceText.From(File.ReadAllText(a["postimage"]), Encoding.UTF8);
var target = a["target"];
var selectedType = a["selected-class"];
var sourceFile = a["source-file"];
var slotsDir = a["slots-dir"];
using var bp = JsonDocument.Parse(File.ReadAllBytes(a["bind-params"]));
var parse = new CSharpParseOptions(LanguageVersion.CSharp12, DocumentationMode.None);
var preTree = CSharpSyntaxTree.ParseText(preText, parse, sourceFile);
var postTree = CSharpSyntaxTree.ParseText(postText, parse, sourceFile);
var (refs, slotByPath) = References.Build(slotsDir);
// only the POSTIMAGE is compiled (semantic model); the preimage is used syntactically
// (span location + identity + the frozen replacement text), so its class type does not
// clash with the postimage's.
var comp = CSharpCompilation.Create("weaktargetbind",
new[] { postTree }, refs,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, deterministic: true));
var postModel = comp.GetSemanticModel(postTree);
var preRoot = preTree.GetRoot();
var postRoot = postTree.GetRoot();
// 1-3: locate every converted preimage AddAssignment at its hash-bound span; revalidate
// identity; reproduce the frozen Step 8 replacement text; record (start, len, replacement).
var edits = new List<Edit>();
foreach (var cand in bp.RootElement.GetProperty("converted").EnumerateArray())
{
var fid = cand.GetProperty("finding_id").GetString()!;
var span = new TextSpan(cand.GetProperty("acquire_span").GetProperty("start").GetInt32(),
cand.GetProperty("acquire_span").GetProperty("length").GetInt32());
var node = preRoot.FindNode(span, getInnermostNodeForTie: true);
if (node is not AssignmentExpressionSyntax asg || asg.Span != span
|| !asg.IsKind(SyntaxKind.AddAssignmentExpression))
return Refuse("CALLSITE_BINDING", $"{fid}: preimage span is not an event += acquire");
var replacement = ReplacementText(asg, target, cand, out var err);
if (replacement is null) return Refuse("CALLSITE_BINDING", $"{fid}: {err}");
if ((cand.GetProperty("file").GetString() ?? "") != sourceFile)
return Refuse("CALLSITE_BINDING", $"{fid}: candidate file is not the target file");
edits.Add(new Edit(fid, span.Start, span.Length, replacement,
cand.GetProperty("source").GetString()!,
cand.GetProperty("normalized_handler").GetString()!));
}
if (edits.Count == 0) return Refuse("CALLSITE_BINDING", "no converted candidates to bind");
// 4: ordered non-overlapping edits, cumulative length deltas -> each derived postimage span.
edits.Sort((x, y) => x.PreStart.CompareTo(y.PreStart));
for (var i = 1; i < edits.Count; i++)
if (edits[i].PreStart < edits[i - 1].PreStart + edits[i - 1].PreLen)
return Refuse("CALLSITE_BINDING", "overlapping converted acquire spans");
// every converted finding id appears exactly once.
var convertedFids = new HashSet<string>(StringComparer.Ordinal);
foreach (var e in edits)
if (!convertedFids.Add(e.Fid))
return Refuse("CALLSITE_BINDING", $"{e.Fid}: converted finding id appears more than once");
long delta = 0;
var callsites = new List<IReadOnlyDictionary<string, object>>();
IMethodSymbol? firstSym = null;
int derivedOrdinal = -1;
string? asmName = null, mvid = null, token = null, sig = null;
foreach (var e in edits)
{
var postStart = (int)(e.PreStart + delta);
var postSpan = new TextSpan(postStart, e.Replacement.Length);
delta += e.Replacement.Length - e.PreLen;
// 5-6: exactly one invocation node exactly filling the derived postimage span.
var pnode = postRoot.FindNode(postSpan, getInnermostNodeForTie: true);
if (pnode is not InvocationExpressionSyntax inv || inv.Span != postSpan)
return Refuse("CALLSITE_BINDING", $"{e.Fid}: no invocation at the derived postimage span");
if (inv.Expression.ToString() != target)
return Refuse("CALLSITE_BINDING", $"{e.Fid}: invocation target is not plan.target_api.subscribe");
var argList = inv.ArgumentList.Arguments;
if (argList.Count != 2
|| argList[0].Expression.ToString() != e.Source
|| Rewrite.NormalizeHandler(argList[1].Expression).ToString() != e.NormalizedHandler)
return Refuse("CALLSITE_BINDING", $"{e.Fid}: invocation arguments do not match the candidate");
// the invocation must sit in the accepted source tree/file and inside the selected class.
if (inv.SyntaxTree != postTree || inv.SyntaxTree.FilePath != sourceFile)
return Refuse("CALLSITE_BINDING", $"{e.Fid}: invocation is not in the accepted source file");
var enclosingType = postModel.GetEnclosingSymbol(inv.SpanStart)?.ContainingType;
if (enclosingType is null || FQ(enclosingType) != selectedType)
return Refuse("CALLSITE_BINDING", $"{e.Fid}: invocation is not inside the selected class");
// 7: a converted callsite may pass ONLY on a cleanly bound Symbol that is an
// IMethodSymbol. Symbol == null is ALWAYS a refusal — CandidateSymbols are inspected only
// to choose the category: exactly one candidate wrapper slot of the wrong frozen shape is
// WRAPPER_BINDING; anything else (ambiguous / multiple / otherwise unresolved) is
// CALLSITE_BINDING. A candidate method is never promoted to the bound symbol.
var si = postModel.GetSymbolInfo(inv);
if (si.Symbol is not IMethodSymbol sym)
return RefuseUnbound(e.Fid, si, comp, slotByPath, target);
if (SymbolEqualityComparer.Default.Equals(sym.ContainingAssembly, comp.Assembly))
return Refuse("CALLSITE_BINDING", $"{e.Fid}: target is source-defined, not a reference wrapper");
if (firstSym is null)
{
firstSym = sym;
var mref = comp.GetMetadataReference(sym.ContainingAssembly) as PortableExecutableReference;
var path = mref?.FilePath ?? "";
if (!slotByPath.TryGetValue(path, out var slot))
return Refuse("WRAPPER_BINDING", $"{e.Fid}: resolved assembly is not a materialized slot");
// TARGET_BINDING: resolve plan.target_api.subscribe (SimpleType.Method) inside the
// selected wrapper assembly and enforce the exact required shape (exactly one public
// type, exactly one public static non-generic void(INPC, PCEH) method, no other
// overload, no ref/optional/params/modopt) — any mismatch is WRAPPER_BINDING.
var terr = TargetBinding.Validate(sym.ContainingAssembly, target);
if (terr is not null) return Refuse("WRAPPER_BINDING", $"{e.Fid}: {terr}");
// even a CLEANLY BOUND wrapper may target an incompatible runtime family (e.g. a
// .NET Framework mscorlib wrapper whose types retarget onto the net8 refs) — the
// positive runtime-family predicate refuses it before probing (L1).
if (RuntimeIncompatible(comp, sym.ContainingAssembly))
return Refuse("WRAPPER_RUNTIME_UNSUPPORTED",
$"{e.Fid}: the wrapper targets a runtime family/version incompatible with the probe runtime");
derivedOrdinal = slot.Ordinal;
asmName = sym.ContainingAssembly.Name;
mvid = ReadMvid(path);
token = "0x" + sym.MetadataToken.ToString("x8");
sig = Program.Sig(FQ(sym.ReturnType), FQ(sym.ContainingType), sym.Name,
sym.Parameters.Select(p => FQ(p.Type)));
}
else if (!SymbolEqualityComparer.Default.Equals(sym, firstSym))
{
return Refuse("CALLSITE_BINDING", $"{e.Fid}: converted callsites resolve to different methods");
}
callsites.Add(new Dictionary<string, object>
{
["finding_id"] = e.Fid,
["preimage_span"] = new List<object> { (long)e.PreStart, (long)e.PreLen },
["postimage_span"] = new List<object> { (long)postSpan.Start, (long)postSpan.Length },
["assembly_simple_name"] = asmName!,
["module_mvid"] = mvid!,
["metadata_token"] = token!,
["resolved_signature"] = sig!,
});
}
callsites.Sort((x, y) => string.CompareOrdinal((string)x["finding_id"], (string)y["finding_id"]));
// the emitted callsites are a total bijection onto the converted findings with distinct
// postimage spans (defence in depth; the Python parent re-checks the canonical bytes).
var emitted = callsites.Select(c => (string)c["finding_id"]).ToList();
if (emitted.Count != edits.Count || !convertedFids.SetEquals(emitted)
|| new HashSet<string>(emitted, StringComparer.Ordinal).Count != emitted.Count)
return Refuse("CALLSITE_BINDING", "callsites are not a bijection onto the converted findings");
var spanKeys = callsites.Select(c =>
{
var s = (List<object>)c["postimage_span"];
return $"{s[0]}:{s[1]}";
}).ToList();
if (new HashSet<string>(spanKeys, StringComparer.Ordinal).Count != spanKeys.Count)
return Refuse("CALLSITE_BINDING", "two callsites share a derived postimage span");
var outObj = new Dictionary<string, object>
{
["version"] = 1L,
["operation"] = "weak-target-bind",
["converted_callsites"] = (long)edits.Count,
["derived_wrapper_ordinal"] = (long)derivedOrdinal,
["resolved_wrapper"] = new Dictionary<string, object>
{
["assembly_simple_name"] = asmName!,
["module_mvid"] = mvid!,
["metadata_token"] = token!,
["resolved_signature"] = sig!,
},
["callsite_binding"] = new Dictionary<string, object>
{
["all_callsites_same_symbol"] = true,
["target_is_source_defined"] = false,
},
["callsites"] = callsites.Cast<object>().ToList(),
};
Program.WriteCanonical(a["out"], outObj);
return 0;
}
private static string? ReplacementText(AssignmentExpressionSyntax asg, string target,
JsonElement cand, out string err)
{
err = "";
ExpressionSyntax receiver;
string eventName;
if (asg.Left is MemberAccessExpressionSyntax lhs
&& lhs.IsKind(SyntaxKind.SimpleMemberAccessExpression)
&& lhs.Name is IdentifierNameSyntax ev)
{ receiver = lhs.Expression; eventName = ev.Identifier.Text; }
else if (asg.Left is IdentifierNameSyntax bare)
{ receiver = Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ThisExpression(); eventName = bare.Identifier.Text; }
else { err = "LHS is not an event member access"; return null; }
if (eventName != cand.GetProperty("event").GetString()) { err = "event name mismatch"; return null; }
var eventFull = asg.Left.ToString();
var dot = eventFull.LastIndexOf('.');
var srcDisplay = dot >= 0 ? eventFull[..dot] : "this";
if (srcDisplay != cand.GetProperty("source").GetString()) { err = "receiver mismatch"; return null; }
if (asg.Right.ToString() != cand.GetProperty("handler").GetString()) { err = "handler mismatch"; return null; }
var handler = Rewrite.NormalizeHandler(asg.Right);
if (Rewrite.NormWs(handler.ToString()) != cand.GetProperty("normalized_handler").GetString())
{ err = "normalized handler mismatch"; return null; }
var comma = Microsoft.CodeAnalysis.CSharp.SyntaxFactory
.Token(SyntaxKind.CommaToken)
.WithTrailingTrivia(Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Space);
return Microsoft.CodeAnalysis.CSharp.SyntaxFactory.InvocationExpression(
Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseExpression(target),
Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ArgumentList(
Microsoft.CodeAnalysis.CSharp.SyntaxFactory.SeparatedList(
new[]
{
Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Argument(receiver.WithoutTrivia()),
Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Argument(handler.WithoutTrivia()),
},
new[] { comma }))).ToString();
}
// fully-qualified metadata type name (no `global::`, no C# keyword aliasing), matching the
// reflection FullName the probe uses, so bind and probe signatures are byte-identical (G3).
private static readonly SymbolDisplayFormat FQFmt = SymbolDisplayFormat.FullyQualifiedFormat
.WithMiscellaneousOptions(SymbolDisplayFormat.FullyQualifiedFormat.MiscellaneousOptions
& ~SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private static string FQ(ITypeSymbol t) => t.ToDisplayString(FQFmt).Replace("global::", "");
private static string ReadMvid(string dllPath)
{
using var fs = File.OpenRead(dllPath);
using var pe = new PEReader(fs);
var mr = pe.GetMetadataReader();
return mr.GetGuid(mr.GetModuleDefinition().Mvid).ToString("D");
}
// Symbol == null: choose the refusal category WITHOUT ever promoting a candidate to the bound
// symbol. With exactly one candidate wrapper slot: a wrong frozen shape is WRAPPER_BINDING;
// WRAPPER_RUNTIME_UNSUPPORTED is returned ONLY when a POSITIVE predicate establishes the wrapper
// targets a core framework NEWER than the selected probe runtime (metadata/runtime
// incompatibility) — never inferred from "one candidate + correct textual shape". Every other
// unresolved callsite (argument conversion failure, method-group ambiguity, multiple / ambiguous
// assemblies, source-compilation failure) is CALLSITE_BINDING.
private static int RefuseUnbound(string fid, SymbolInfo si, CSharpCompilation comp,
Dictionary<string, References.Slot> slotByPath, string target)
{
var asms = new List<IAssemblySymbol>();
foreach (var m in si.CandidateSymbols.OfType<IMethodSymbol>())
{
if (SymbolEqualityComparer.Default.Equals(m.ContainingAssembly, comp.Assembly)) continue;
if (!asms.Any(x => SymbolEqualityComparer.Default.Equals(x, m.ContainingAssembly)))
asms.Add(m.ContainingAssembly);
}
if (asms.Count == 1)
{
var path = (comp.GetMetadataReference(asms[0]) as PortableExecutableReference)?.FilePath ?? "";
if (slotByPath.ContainsKey(path))
{
if (TargetBinding.Validate(asms[0], target) is not null)
return Refuse("WRAPPER_BINDING", $"{fid}: the wrapper target has the wrong frozen shape");
if (RuntimeIncompatible(comp, asms[0]))
return Refuse("WRAPPER_RUNTIME_UNSUPPORTED",
$"{fid}: the wrapper targets a core framework newer than the selected probe runtime");
}
}
return Refuse("CALLSITE_BINDING", $"{fid}: the invocation does not bind to a single wrapper symbol");
}
// The POSITIVE runtime-compatibility predicate (K3 / L1): a deterministic metadata comparison,
// never an inference from a failed overload. It positively establishes BOTH an incompatible
// runtime FAMILY (a .NET-Framework `mscorlib` wrapper under a CoreCLR probe, or a CoreCLR
// `System.Private.CoreLib` wrapper under a non-CoreCLR probe) AND a newer SAME-family runtime
// contract (a core contract at a version strictly newer than the selected runtime supplies), plus
// a TargetFrameworkAttribute that positively declares an incompatible family. A netstandard
// reference is NEVER a reason to reject (netstandard is a compatibility contract, not a family).
private static readonly HashSet<string> SameFamilyContract = new(StringComparer.OrdinalIgnoreCase)
{ "System.Runtime", "System.Private.CoreLib" };
private static bool RuntimeIncompatible(CSharpCompilation comp, IAssemblySymbol wrapperAsm)
{
var coreAsm = comp.GetSpecialType(SpecialType.System_Object).ContainingAssembly;
var runtimeVersion = coreAsm.Identity.Version;
var runtimeIsCoreClr = string.Equals(coreAsm.Name, "System.Private.CoreLib",
StringComparison.OrdinalIgnoreCase);
foreach (var mod in wrapperAsm.Modules)
foreach (var r in mod.ReferencedAssemblies)
{
if (string.Equals(r.Name, "mscorlib", StringComparison.OrdinalIgnoreCase)
&& runtimeIsCoreClr)
return true; // .NET Framework wrapper under a CoreCLR probe
if (string.Equals(r.Name, "System.Private.CoreLib", StringComparison.OrdinalIgnoreCase)
&& !runtimeIsCoreClr)
return true; // CoreCLR wrapper under a non-CoreCLR probe
if (SameFamilyContract.Contains(r.Name) && r.Version > runtimeVersion)
return true; // a same-family core contract strictly newer than the runtime
}
foreach (var attr in wrapperAsm.GetAttributes())
if (attr.AttributeClass?.ToDisplayString()
== "System.Runtime.Versioning.TargetFrameworkAttribute"
&& attr.ConstructorArguments.Length > 0
&& attr.ConstructorArguments[0].Value is string moniker
&& MonikerFamilyIncompatible(moniker, runtimeIsCoreClr))
return true;
return false;
}
private static bool MonikerFamilyIncompatible(string moniker, bool runtimeIsCoreClr)
{
var isFramework = moniker.StartsWith(".NETFramework", StringComparison.OrdinalIgnoreCase);
var isCoreApp = moniker.StartsWith(".NETCoreApp", StringComparison.OrdinalIgnoreCase);
return (runtimeIsCoreClr && isFramework) || (!runtimeIsCoreClr && isCoreApp);
}
private static int Refuse(string category, string message)
{
Console.Error.WriteLine($"{category}: {message}");
return category switch
{
"CALLSITE_BINDING" => 11,
"WRAPPER_BINDING" => 12,
"TOOLCHAIN_BINDING" => 13,
"WRAPPER_RUNTIME_UNSUPPORTED" => 14,
_ => 2,
};
}
private readonly record struct Edit(string Fid, int PreStart, int PreLen, string Replacement,
string Source, string NormalizedHandler);
}
// The frozen Step 8 handler peel + whitespace normalization (copied grammar; the rewriter stays frozen).
internal static class Rewrite
{
public static ExpressionSyntax NormalizeHandler(ExpressionSyntax e)
{
while (e is BaseObjectCreationExpressionSyntax { ArgumentList.Arguments: { Count: 1 } args })
e = args[0].Expression;
return e;
}
public static string NormWs(string s) => string.Join(" ", s.Split((char[]?)null,
StringSplitOptions.RemoveEmptyEntries));
}
internal static class References
{
public static (List<MetadataReference>, Dictionary<string, Slot>) Build(string slotsDir)
{
var refs = new List<MetadataReference>();
var byPath = new Dictionary<string, Slot>(StringComparer.OrdinalIgnoreCase);
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// framework references = the SELECTED runtime the probe is pinned to (TPA), first.
var tpa = ((AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") as string) ?? "")
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries);
foreach (var p in tpa) { seen.Add(Path.GetFileNameWithoutExtension(p)); refs.Add(MetadataReference.CreateFromFile(p)); }
// reference slots in exact ordinal order; first simple-name wins (framework wins over a slot).
if (Directory.Exists(slotsDir))
foreach (var slot in Directory.GetDirectories(slotsDir).OrderBy(d => d, StringComparer.Ordinal))
{
var dll = Directory.GetFiles(slot, "*.dll").Single();
var name = Path.GetFileNameWithoutExtension(dll);
var ordinal = int.Parse(Path.GetFileName(slot));
var full = Path.GetFullPath(dll);
byPath[full] = new Slot(ordinal, full, name);
if (seen.Add(name)) refs.Add(MetadataReference.CreateFromFile(full));
}
return (refs, byPath);
}
public readonly record struct Slot(int Ordinal, string Path, string SimpleName);
}
// TARGET_BINDING (WRAPPER_BINDING on any mismatch): the plan.target_api.subscribe method, resolved
// by name ONLY inside the selected wrapper assembly, must have the exact accepted shape. This is
// independent of whether the postimage callsite's arguments bind, so a wrong-signature or overloaded
// wrapper is refused here rather than surfacing as an unresolved callsite or a runtime load failure.
internal static class TargetBinding
{
private static readonly SymbolDisplayFormat FQFmt = SymbolDisplayFormat.FullyQualifiedFormat
.WithMiscellaneousOptions(SymbolDisplayFormat.FullyQualifiedFormat.MiscellaneousOptions
& ~SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private static string FQ(ITypeSymbol t) => t.ToDisplayString(FQFmt).Replace("global::", "");
public static string? Validate(IAssemblySymbol asm, string target)
{
var dot = target.LastIndexOf('.');
if (dot <= 0) return "target_api.subscribe is not SimpleType.Method";
var typeName = target[..dot];
var methodName = target[(dot + 1)..];
var types = new List<INamedTypeSymbol>();
Collect(asm.GlobalNamespace, types);
var matches = types.Where(t => t.DeclaredAccessibility == Accessibility.Public
&& (t.Name == typeName || FQ(t) == typeName)).ToList();
if (matches.Count != 1) return $"expected exactly one public type '{typeName}'";
var declType = matches[0];
if (declType.IsGenericType) return "the wrapper type is generic";
var overloads = declType.GetMembers(methodName).OfType<IMethodSymbol>()
.Where(m => m.IsStatic && m.DeclaredAccessibility == Accessibility.Public).ToList();
if (overloads.Count != 1) return $"expected exactly one public static '{methodName}'";
var m = overloads[0];
if (m.IsGenericMethod) return "the wrapper method is generic";
if (m.ReturnType.SpecialType != SpecialType.System_Void) return "return type is not System.Void";
if (m.Parameters.Length != 2) return "parameter count is not 2";
if (FQ(m.Parameters[0].Type) != "System.ComponentModel.INotifyPropertyChanged"
|| FQ(m.Parameters[1].Type) != "System.ComponentModel.PropertyChangedEventHandler")
return "parameters are not (INotifyPropertyChanged, PropertyChangedEventHandler)";
foreach (var p in m.Parameters)
if (p.RefKind != RefKind.None || p.IsOptional || p.IsParams
|| p.CustomModifiers.Any() || p.RefCustomModifiers.Any())
return "a parameter uses ref/optional/params/custom-modifier shape";
return null;
}
private static void Collect(INamespaceSymbol ns, List<INamedTypeSymbol> acc)
{
acc.AddRange(ns.GetTypeMembers());
foreach (var child in ns.GetNamespaceMembers()) Collect(child, acc);
}
}
internal static class Args
{
public static Dictionary<string, string> Parse(string[] args, int start)
{
var d = new Dictionary<string, string>();
for (var i = start; i < args.Length; i++)
if (args[i].StartsWith("--") && i + 1 < args.Length) { d[args[i][2..]] = args[i + 1]; i++; }
return d;
}
}
// --- PROBE MODE (G3, G4, F4) -------------------------------------------------------------
internal static class ProbeMode
{
private const int CollectionRounds = 5;
private const int AllocPerRound = 4194304;
public static int Run(string[] args)
{
var a = Args.Parse(args, 1);
var ordinal = int.Parse(a["wrapper-ordinal"]);
var attempt = int.Parse(a["attempt"]);
var target = a["target"];
var slotsDir = a["slots-dir"];
var runtimeDir = a["runtime-dir"];
var outPath = a["out"];
var slot = Path.Combine(slotsDir, ordinal.ToString("D6"));
var rootPath = Path.GetFullPath(Directory.GetFiles(slot, "*.dll").Single());
var slotSha = Sha256(rootPath);
var dot = target.LastIndexOf('.');
var typeName = target[..dot];
var methodName = target[(dot + 1)..];
// the closed load context: the wrapper root loads only from its exact derived slot; its
// non-framework dependencies resolve ONLY from the ordered materialized slots (first
// filename wins); framework assemblies resolve ONLY from the selected probe runtime; a
// non-framework dependency absent from the slots is a controlled loader failure. The probe
// deployment / default context can NEVER satisfy a wrapper dependency.
var framework = FrameworkNames(runtimeDir);
var alc = new WrapperLoadContext(slotsDir, framework);
MethodInfo method;
Action<INotifyPropertyChanged, PropertyChangedEventHandler> invoke;
string asmName, mvid, token, sig;
try
{
// G4 preflight: load-by-path, resolve type + exact method, build delegate, prepare.
var root = alc.LoadFromAssemblyPath(rootPath);
var type = root.GetTypes().Single(t => t.IsPublic && !t.IsGenericType && t.Name == typeName);
var cands = type.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Where(m => m.Name == methodName).ToList();
method = cands.Single(m => !m.IsGenericMethod && m.ReturnType == typeof(void)
&& Params(m).SequenceEqual(new[] { typeof(INotifyPropertyChanged), typeof(PropertyChangedEventHandler) }));
invoke = (Action<INotifyPropertyChanged, PropertyChangedEventHandler>)
method.CreateDelegate(typeof(Action<INotifyPropertyChanged, PropertyChangedEventHandler>));
RuntimeHelpers.PrepareMethod(method.MethodHandle);
asmName = root.GetName().Name!;
mvid = method.Module.ModuleVersionId.ToString("D");
token = "0x" + method.MetadataToken.ToString("x8");
sig = Program.Sig("System.Void", FullName(type), method.Name, Params(method).Select(FullName));
}
catch (Exception e) when (IsLoaderFailure(e))
{
var obj = new Dictionary<string, object>
{
["version"] = 1L, ["operation"] = "weak-target-probe", ["attempt"] = (long)attempt,
["runtime_unsupported"] = true,
["reason"] = Inner(e).GetType().Name,
};
Program.WriteCanonical(outPath, obj);
return 10; // WRAPPER_RUNTIME_UNSUPPORTED
}
var strongSource = new ProbeSource();
var strongRef = RunStrong(strongSource, out var strongDelivered);
var weakRef = RunCollectable();
var targetSource = new ProbeSource();
var wref = RunTarget(targetSource, invoke, out var delivered, out var threwSub, out var threwFirst);
for (var r = 0; r < CollectionRounds; r++) CollectRound(strongSource, targetSource);
GC.KeepAlive(strongSource);
GC.KeepAlive(targetSource);
var strongRetained = strongRef.TryGetTarget(out _);
var weakCollected = !weakRef.TryGetTarget(out _);
var subscriberCollected = !wref.TryGetTarget(out _);
bool threwPost = false;
try { targetSource.Raise(); } catch { threwPost = true; }
GC.KeepAlive(targetSource);
var result = new Dictionary<string, object>
{
["version"] = 1L,
["operation"] = "weak-target-probe",
["attempt"] = (long)attempt,
["strong_delivered_once"] = strongDelivered == 1,
["strong_retained"] = strongRetained,
["weak_control_collected"] = weakCollected,
["delivered_count"] = (long)delivered,
["threw_on_subscribe"] = threwSub,
["threw_on_first_raise"] = threwFirst,
["subscriber_collected"] = subscriberCollected,
["threw_on_post_collection_raise"] = threwPost,
["resolved_wrapper"] = new Dictionary<string, object>
{
["ordinal"] = (long)ordinal,
["slot_sha256"] = "sha256:" + slotSha,
["assembly_simple_name"] = asmName,
["module_mvid"] = mvid,
["metadata_token"] = token,
["resolved_signature"] = sig,
},
};
Program.WriteCanonical(outPath, result);
return 0;
}
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private static WeakReference<ProbeSubscriber> RunTarget(ProbeSource source,
Action<INotifyPropertyChanged, PropertyChangedEventHandler> invoke,
out int delivered, out bool threwSub, out bool threwFirst)
{
threwSub = false; threwFirst = false; delivered = 0;
var sub = new ProbeSubscriber();
var handler = new PropertyChangedEventHandler(sub.OnChanged);
try { invoke(source, handler); } catch { threwSub = true; }
if (!threwSub) { try { source.Raise(); } catch { threwFirst = true; } }
delivered = sub.Count;
return new WeakReference<ProbeSubscriber>(sub, trackResurrection: false);
}
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private static WeakReference<ProbeSubscriber> RunStrong(ProbeSource source, out int delivered)
{
var sub = new ProbeSubscriber();
source.PropertyChanged += sub.OnChanged;
source.Raise();
delivered = sub.Count;
return new WeakReference<ProbeSubscriber>(sub, trackResurrection: false);
}
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private static WeakReference<ProbeSubscriber> RunCollectable()
=> new(new ProbeSubscriber(), trackResurrection: false);
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private static void CollectRound(ProbeSource keepA, ProbeSource keepB)
{
var pressure = new byte[AllocPerRound];
for (var i = 0; i < pressure.Length; i += 4096) pressure[i] = 1;
pressure = null!;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);
GC.KeepAlive(keepA);
GC.KeepAlive(keepB);
}
private static Type[] Params(MethodInfo m) => m.GetParameters().Select(p => p.ParameterType).ToArray();
private static string FullName(Type t) => t.FullName ?? t.Name;
private static bool IsLoaderFailure(Exception e)
{
var x = Inner(e);
return x is BadImageFormatException or FileNotFoundException or FileLoadException
or TypeLoadException or MissingMethodException or MissingMemberException
or ReflectionTypeLoadException or InvalidOperationException;
}
private static Exception Inner(Exception e)
=> e is TargetInvocationException { InnerException: { } inner } ? inner : e;
private static string Sha256(string path)
{
using var s = File.OpenRead(path);
using var h = System.Security.Cryptography.SHA256.Create();
return Convert.ToHexString(h.ComputeHash(s)).ToLowerInvariant();
}
// the framework assembly set = the simple names physically present in the SELECTED probe
// runtime directory. Only these may resolve from the default context; everything else must
// come from a materialized slot.
private static HashSet<string> FrameworkNames(string runtimeDir)
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (Directory.Exists(runtimeDir))
foreach (var dll in Directory.GetFiles(runtimeDir, "*.dll"))
set.Add(Path.GetFileNameWithoutExtension(dll));
return set;
}
}
internal sealed class ProbeSource : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public void Raise() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Probe"));
}
internal sealed class ProbeSubscriber
{
public int Count;
public void OnChanged(object? sender, PropertyChangedEventArgs e) => Count++;
}
internal sealed class WrapperLoadContext : AssemblyLoadContext
{
private readonly string _slotsDir;
private readonly HashSet<string> _framework;
public WrapperLoadContext(string slotsDir, HashSet<string> framework)
: base("weak-target", isCollectible: false)
{
_slotsDir = slotsDir;
_framework = framework;
}
protected override Assembly? Load(AssemblyName name)
{
var simple = name.Name ?? "";
// framework assemblies resolve ONLY from the selected probe runtime (the default context,
// which the probe pinned via --fx-version). Returning null delegates to that runtime.
if (_framework.Contains(simple)) return null;
// a non-framework dependency resolves ONLY from the ordered materialized slots (first
// filename wins) — never the probe deployment, the default context, the working directory,
// the user profile, or an arbitrary PATH entry.
var dll = ResolveSlot(simple);
if (dll != null) return LoadFromAssemblyPath(dll);
// absent from the slots -> a controlled loader failure -> WRAPPER_RUNTIME_UNSUPPORTED.
throw new FileNotFoundException(
$"the wrapper dependency '{simple}' is not in the materialized reference closure");
}
private string? ResolveSlot(string simple)
{
if (!Directory.Exists(_slotsDir)) return null;
foreach (var slot in Directory.GetDirectories(_slotsDir).OrderBy(d => d, StringComparer.Ordinal))
{
var dll = Directory.GetFiles(slot, "*.dll").SingleOrDefault();
if (dll != null && string.Equals(Path.GetFileNameWithoutExtension(dll), simple,
StringComparison.OrdinalIgnoreCase))
return Path.GetFullPath(dll);
}
return null;
}
}