XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFESystem

【Rust】XFE系统,基于Rust和汇编

公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/XFESystem

Bound UART writes and show physical boot progress diagnostics

a18be56
XFE工作室室长 <mail@xfegzs.com>
提交于

代码差异

11 个文件 +994 -1
Modified Source/XFESystem.Kernel/Kernel.cs +33 -0
@@ -48,6 +48,19 @@ public sealed class Kernel : Cosmos.Kernel.System.Kernel
48 48
49 49 protected override void BeforeRun()
50 50 {
51 NativeBootProgress.Begin();
52 try { InitializeDesktop(); }
53 catch (Exception error) when (error is not OutOfMemoryException and not StackOverflowException)
54 {
55 NativeBootProgress.Failed(error.Message);
56 WriteDiagnostic("[FAILFAST] Desktop startup failed: " + error.Message + "\n");
57 while (true) Power.Halt();
58 }
59 }
60
61 private void InitializeDesktop()
62 {
63 NativeBootProgress.Stage("B10", "Preparing input and packaged resources");
51 64 desktopInput.Trace = WriteDiagnostic;
52 65 desktopInput.NavigationDispatched = () =>
53 66 {
@@ -64,27 +77,33 @@ public sealed class Kernel : Cosmos.Kernel.System.Kernel
64 77 int documentTextResources = XFESystem.Documents.WebsiteAssets.PrewarmTextResources();
65 78 int browserTextResources = PackagedBrowserResources.PrewarmTextResources();
66 79 WriteDiagnostic("XFE_PACKAGED_TEXT_PREWARM|Documents|" + documentTextResources + "|Browser|" + browserTextResources + "|Immutable|1\n");
80 NativeBootProgress.Stage("B20", "Checking managed runtime");
67 81 if (!RuntimeVarianceRegression.Run())
68 82 throw new InvalidOperationException("The managed generic variance runtime regression failed.");
69 83 WriteDiagnostic("XFE_RUNTIME_VARIANCE_OK\n");
70 84 WriteDiagnostic("XFE_GC_DEEP_BEGIN\n");
85 NativeBootProgress.Stage("B21", "Checking garbage collector");
71 86 bool deepGc = NativeGcRegression.Run();
72 87 WriteDiagnostic("XFE_GC_DEEP_RESULT|" + deepGc + "|Frames|"+NativeGcRegression.FramesVerified+"|Collections|"+NativeGcRegression.CollectionsRequested+"|FailureDepth|"+NativeGcRegression.FailureDepth+"\n");
73 88 if (!deepGc) throw new InvalidOperationException("The native deep-stack GC root regression failed.");
74 89 WriteDiagnostic("XFE_EH_DEEP_RETHROW_BEGIN\n");
90 NativeBootProgress.Stage("B22", "Checking exception handling");
75 91 if (!NativeEhRegression.Run())
76 92 throw new InvalidOperationException("The native deep catch/rethrow recovery regression failed.");
77 93 WriteDiagnostic("XFE_EH_DEEP_RETHROW_OK|Frames|" + NativeEhRegression.FramesCaught + "|Post|" + NativeEhRegression.PostCatchFrames + "\n");
78 94 WriteDiagnostic("XFE_THREAD_EH_GC_BEGIN\n");
95 NativeBootProgress.Stage("B30", "Checking timer, scheduler and thread runtime");
79 96 bool threadRuntimeReady = NativeThreadRegression.Run();
80 97 WriteDiagnostic("XFE_THREAD_EH_GC_RESULT|" + threadRuntimeReady + "|Steps|" + NativeThreadRegression.Steps + "|Collections|" + NativeThreadRegression.Collections + "|SingleCpu|1|GcStopTheWorld|1\n");
81 98 WriteDiagnostic("XFE_THREAD_PREEMPTION|Checks|" + NativeThreadRegression.PreemptionChecks + "|FirstId|" + NativeThreadRegression.FirstThreadId + "|SecondId|" + NativeThreadRegression.SecondThreadId + "|FirstFailure|" + NativeThreadRegression.FirstFailure + "|SecondFailure|" + NativeThreadRegression.SecondFailure + "\n");
82 99 WriteDiagnostic("XFE_THREAD_TLS|Checks|" + NativeThreadRegression.ThreadStaticChecks + "|FirstManagedId|" + NativeThreadRegression.FirstManagedThreadId + "|SecondManagedId|" + NativeThreadRegression.SecondManagedThreadId + "|OrdinaryThreadsOnly|1\n");
83 100 if (!threadRuntimeReady)
84 101 {
102 NativeBootProgress.Failed("Thread, timer or preemption contract failed.");
85 103 WriteDiagnostic("[FAILFAST] Native thread EH/GC/preemption contract failed; background work and desktop startup remain disabled.\n");
86 104 while (true) Power.Halt();
87 105 }
106 NativeBootProgress.Stage("B40", "Checking weak references and frozen memory");
88 107 bool weakRuntimeReady = NativeWeakLifetimeRegression.Run(NativeRuntimeMemoryDiagnostics.DependentHandleCount);
89 108 WriteDiagnostic("XFE_WEAK_LIFETIME_RESULT|" + weakRuntimeReady + "|Checks|" + NativeWeakLifetimeRegression.ChecksPassed +
90 109 "|Weak|" + (NativeWeakLifetimeRegression.WeakTargetCleared ? 1 : 0) +
@@ -97,6 +116,7 @@ public sealed class Kernel : Cosmos.Kernel.System.Kernel
97 116 "|Failure|" + NativeWeakLifetimeRegression.Failure + "\n");
98 117 if (!weakRuntimeReady)
99 118 {
119 NativeBootProgress.Failed("Weak reference lifetime contract failed.");
100 120 WriteDiagnostic("[FAILFAST] Native weak/dependent handle contract failed; browser and desktop remain disabled.\n");
101 121 while (true) Power.Halt();
102 122 }
@@ -107,6 +127,7 @@ public sealed class Kernel : Cosmos.Kernel.System.Kernel
107 127 "|Failure|" + NativeFrozenRangeRegression.Failure + "\n");
108 128 if (!frozenRuntimeReady)
109 129 {
130 NativeBootProgress.Failed("Frozen memory range contract failed.");
110 131 WriteDiagnostic("[FAILFAST] Native frozen-object range contract failed; browser and desktop remain disabled.\n");
111 132 while (true) Power.Halt();
112 133 }
@@ -118,9 +139,11 @@ public sealed class Kernel : Cosmos.Kernel.System.Kernel
118 139 "|Failure|" + NativeWeakCollectionsRegression.Failure + "\n");
119 140 if (!weakCollectionsReady)
120 141 {
142 NativeBootProgress.Failed("Owned weak collection contract failed.");
121 143 WriteDiagnostic("[FAILFAST] Native owned weak collection contract failed; browser and desktop remain disabled.\n");
122 144 while (true) Power.Halt();
123 145 }
146 NativeBootProgress.Stage("B50", "Checking JavaScript engine lifetime");
124 147 var weakJavaScriptWarmup = BrowserWeakCollectionsRegression.Run();
125 148 if (!weakJavaScriptWarmup.Passed || !weakJavaScriptWarmup.EngineCachesExercised ||
126 149 !weakJavaScriptWarmup.ConstructorFailureReleased || !weakJavaScriptWarmup.ConstructorExceptionPreserved)
@@ -139,9 +162,11 @@ public sealed class Kernel : Cosmos.Kernel.System.Kernel
139 162 "|Actual|" + weakJavaScript.Actual + "\n");
140 163 if (!weakJavaScriptReady)
141 164 {
165 NativeBootProgress.Failed("JavaScript weak collection contract failed.");
142 166 WriteDiagnostic("[FAILFAST] Native JavaScript weak collection contract failed; browser and desktop remain disabled.\n");
143 167 while (true) Power.Halt();
144 168 }
169 NativeBootProgress.Stage("B60", "Preparing memory workspace and console programs");
145 170 RunConsoleDemo();
146 171 workspace = new MemoryWorkspace();
147 172 workspace.WriteText(SystemPaths.Combine(SystemPaths.Documents, "Readme.md"),
@@ -157,8 +182,10 @@ public sealed class Kernel : Cosmos.Kernel.System.Kernel
157 182 workspace.WriteBytes(ManagedDemoPath, bytes);
158 183 }
159 184 RunManagedApplicationCore(ManagedDemoPath, verifyDemonstration: true);
185 NativeBootProgress.Stage("B70", "Checking network (offline startup is supported)");
160 186 InitializeNetwork();
161 187 WriteDiagnostic("XFE_BROWSER_CONSTRUCT_BEGIN\n");
188 NativeBootProgress.Stage("B80", "Preparing browser and document renderer");
162 189 var browser = new BrowserService(new NativeWebTransport()) { Trace = WriteDiagnostic };
163 190 WriteDiagnostic("XFE_BROWSER_CONSTRUCT_OK\nXFE_BROWSER_NAVIGATE_BEGIN\n");
164 191 var constrainedJavaScript = new JavaScriptRuntime(new BrowserLimits { MaximumStatements = 50 });
@@ -179,6 +206,7 @@ public sealed class Kernel : Cosmos.Kernel.System.Kernel
179 206 if (!markdown.Contains("Markdown", StringComparison.Ordinal))
180 207 throw new InvalidOperationException("The guest Markdown preview test failed.");
181 208 WriteDiagnostic("XFE_CSHARP_JAVASCRIPT_DOM_OK\nXFE_CSHARP_MARKDOWN_OK\n");
209 NativeBootProgress.Stage("B90", "Creating desktop display surface");
182 210 var canvas = new CanvasAdapter();
183 211 display = canvas;
184 212 editorWorker = new NativeManagedWorkScheduler(WriteDiagnostic, canvas.ScalePercent / 100);
@@ -198,7 +226,12 @@ public sealed class Kernel : Cosmos.Kernel.System.Kernel
198 226 desktop.Pointer(canvas.ToLayout(MouseManager.X), canvas.ToLayout(MouseManager.Y), false);
199 227 while (NativePointerCapture.TryRead(out _)) { }
200 228 desktop.PointerReportsLost(canvas.ToLayout(MouseManager.X),canvas.ToLayout(MouseManager.Y),MouseManager.LeftButton,MonotonicMilliseconds());
229 NativeBootProgress.Stage("B99", "Presenting desktop");
230 NativeBootProgress.DesktopOwnsDisplay();
201 231 desktop.Render();
232 WriteDiagnostic("XFE_BOOT_SCREEN|Stages|" + NativeBootProgress.StageCount + "|DisabledBeforeDesktop|" + (NativeBootProgress.IsVisible ? 0 : 1) + "\n");
233 WriteDiagnostic("XFE_SERIAL_BOUNDED|PollLimit|4096|Absent|" + NativeBootProgress.SerialAbsentCount() +
234 "|Timeout|" + NativeBootProgress.SerialTimeoutCount() + "|Dropped|" + NativeBootProgress.SerialDroppedCount() + "\n");
202 235 WriteDiagnostic("XFE_RENDER_BACKEND|Rasterization|CPU|GpuAcceleration|0|CudaAcceleration|0|Reason|No initialized native GPU or CUDA command backend\n");
203 236 WriteDiagnostic("XFE_MONITOR_TIMING|" + monitor.Timing.AdvertisedRefreshMilliHz + "|TargetMilliHz|" + refreshTarget +
204 237 "|DriverConfirmedHz|" + canvas.DriverRefreshHz + "|VSync|0|Origin|" + monitor.Origin + "|" + monitor.Timing.Source + "\n");
Added Source/XFESystem.Kernel/NativeBootProgress.cs +67 -0
@@ -0,0 +1,67 @@
1 using System.Runtime.InteropServices;
2
3 namespace XFESystem.Kernel;
4
5 /// <summary>Small, allocation-free firmware-framebuffer diagnostics until desktop ownership.</summary>
6 internal static class NativeBootProgress
7 {
8 private static bool visible;
9 private static string stage = "B00";
10 internal static int StageCount { get; private set; }
11 internal static bool IsVisible => visible;
12
13 [DllImport("*", EntryPoint = "XfeBootConsoleSetEnabled")]
14 [SuppressGCTransition]
15 private static extern void SetEnabled(int enabled);
16
17 [DllImport("*", EntryPoint = "XfeBootConsoleWriteChar")]
18 [SuppressGCTransition]
19 private static extern void WriteChar(int character);
20
21 [DllImport("*", EntryPoint = "XfeRuntimeSerialAbsentCount")]
22 [SuppressGCTransition]
23 internal static extern ulong SerialAbsentCount();
24 [DllImport("*", EntryPoint = "XfeRuntimeSerialTimeoutCount")]
25 [SuppressGCTransition]
26 internal static extern ulong SerialTimeoutCount();
27 [DllImport("*", EntryPoint = "XfeRuntimeSerialDroppedCount")]
28 [SuppressGCTransition]
29 internal static extern ulong SerialDroppedCount();
30
31 internal static void Begin()
32 {
33 SetEnabled(1);
34 visible = true;
35 StageCount = 0;
36 Write("\nXFESystem startup diagnostics\n");
37 Stage("B00", "Managed kernel entered");
38 }
39
40 internal static void Stage(string code, string description)
41 {
42 stage = code;
43 StageCount++;
44 Write("[XFE "); Write(code); Write("] "); Write(description); Write("\n");
45 }
46
47 internal static void Failed(string reason)
48 {
49 if (!visible) { SetEnabled(1); visible = true; }
50 Write("\n[XFE BOOT FAILED] Stage "); Write(stage); Write("\n");
51 Write(reason); Write("\nPlease photograph this screen. No disk install was performed.\n");
52 }
53
54 internal static void DesktopOwnsDisplay()
55 {
56 // Disable the early mirror before the first desktop presentation so
57 // runtime logging can never paint over a completed desktop frame.
58 SetEnabled(0);
59 visible = false;
60 }
61
62 private static void Write(string text)
63 {
64 if (!visible) return;
65 foreach (char character in text) WriteChar(character);
66 }
67 }
Added Tools/CSharpBoot/TestNoSerialBoot.py +325 -0
@@ -0,0 +1,325 @@
1 """Read-only image boot proof with no emulated serial controller.
2
3 This test proves that two framebuffer captures reach the already verified idle
4 desktop. It does not claim guest serial markers, physical hardware support,
5 complete editor stability, or GPU/CUDA acceleration.
6 """
7 import argparse
8 import hashlib
9 import json
10 import pathlib
11 import re
12 import shutil
13 import socket
14 import subprocess
15 import time
16
17 from PIL import Image, ImageChops, ImageStat
18 from ReadImage import inspect_image
19
20
21 ROOT = pathlib.Path(__file__).resolve().parents[2]
22 GIB = 1024 ** 3
23
24
25 def require(condition, message):
26 if not condition:
27 raise ValueError(message)
28
29
30 def sha256(path):
31 digest = hashlib.sha256()
32 with pathlib.Path(path).open('rb') as stream:
33 for block in iter(lambda: stream.read(1024 * 1024), b''):
34 digest.update(block)
35 return digest.hexdigest()
36
37
38 def absolute_file(value, name):
39 path = pathlib.Path(value)
40 require(path.is_absolute(), name + ' must be an absolute file path')
41 path = path.resolve(strict=True)
42 require(path.is_file(), name + ' must identify a file')
43 return path
44
45
46 def close_rgb_fraction(reference, actual):
47 if reference.size != actual.size:
48 return 0.0
49 difference = ImageChops.difference(reference, actual)
50 red, green, blue = difference.split()
51 maximum = ImageChops.lighter(ImageChops.lighter(red, green), blue)
52 histogram = maximum.histogram()
53 return sum(histogram[:4]) / (reference.width * reference.height)
54
55
56 def regions_for(width, height, scale):
57 # Match the current DesktopSession's five launcher bounds and 48px taskbar.
58 work_height = height // scale - 48
59 if work_height >= 554:
60 top, bottom = 84, 84 + 4 * 94 + 74
61 else:
62 icon_height = max(40, min(74, (work_height - 80) // 5))
63 gap = max(4, min(12, (work_height - 32 - icon_height * 5) // 4))
64 top, bottom = 16, 16 + 4 * (icon_height + gap) + icon_height
65 return {
66 'DesktopEntries': (22 * scale, top * scale, 122 * scale, min(height - 48 * scale, bottom * scale)),
67 'Taskbar': (0, height - 48 * scale, width, height),
68 }
69
70
71 def verify_reference(reference, regions):
72 for name, box in regions.items():
73 require(box[2] > box[0] and box[3] > box[1], 'Invalid ' + name + ' comparison region')
74 with reference.crop(box) as crop:
75 ranges = [high - low for low, high in crop.getextrema()]
76 require(max(ranges) >= 32 and max(ImageStat.Stat(crop).stddev) >= 4,
77 name + ' reference lacks visible interface detail; a black/background frame cannot qualify')
78
79
80 def converted_arguments(original, source_image, variables, port, acceleration):
81 require(isinstance(original, list) and original and all(isinstance(value, str) for value in original),
82 'Verified boot receipt has no QEMU argument list')
83 executable = absolute_file(original[0], 'QEMU executable')
84 require(executable == (ROOT / '.tools/qemu/qemu-system-x86_64.exe').resolve(),
85 'Only this project QEMU executable may run')
86 result = [str(executable)]
87 counts = {'-serial': 0, '-qmp': 0, '-display': 0, '-accel': 0, 'Image': 0, 'Vars': 0, 'Code': 0}
88 cursor = 1
89 while cursor < len(original):
90 option = original[cursor]
91 if option in ('-serial', '-qmp', '-display', '-accel', '-drive'):
92 require(cursor + 1 < len(original), 'Incomplete QEMU option: ' + option)
93 value = original[cursor + 1]
94 cursor += 2
95 if option == '-drive':
96 fields = dict(piece.split('=', 1) for piece in value.split(',') if '=' in piece)
97 path = pathlib.Path(fields.get('file', '')).resolve()
98 if path == source_image:
99 counts['Image'] += 1
100 require(fields.get('format') == 'raw' and fields.get('snapshot') == 'on',
101 'The verified source image must already use raw snapshot mode')
102 # snapshot=on opens the source read-only and gives the IDE
103 # frontend a temporary writable overlay. readonly=on here
104 # would make that frontend read-only and QEMU rejects it.
105 require('readonly' not in fields, 'Unexpected frontend read-only override')
106 value = ','.join(key + '=' + item for key, item in fields.items())
107 elif fields.get('if') == 'pflash' and fields.get('readonly') == 'on':
108 counts['Code'] += 1
109 require(path.is_file(), 'Verified firmware code is unavailable')
110 elif fields.get('if') == 'pflash':
111 counts['Vars'] += 1
112 fields['file'] = str(variables)
113 value = ','.join(key + '=' + item for key, item in fields.items())
114 else:
115 raise ValueError('Unexpected writable/extra drive in verified QEMU recipe')
116 else:
117 counts[option] += 1
118 value = {'-serial': 'none', '-qmp': f'tcp:127.0.0.1:{port},server=on,wait=off',
119 '-display': 'none', '-accel': acceleration}[option]
120 result.extend((option, value))
121 else:
122 require(option not in ('-chardev', '-readconfig', '-writeconfig', '-S', '-incoming'),
123 'Unexpected diagnostic/device override in verified recipe')
124 if option == '-device':
125 require(cursor + 1 < len(original) and not re.search(r'serial|uart', original[cursor + 1], re.I),
126 'An explicit serial/UART device cannot qualify')
127 result.append(option)
128 cursor += 1
129 require(all(value == 1 for value in counts.values()), 'Expected exactly one image, firmware pair, serial/display/accel/QMP option')
130 return result
131
132
133 class Qmp:
134 def __init__(self, connection):
135 self.connection = connection
136 self.stream = connection.makefile('rwb')
137 greeting = self.stream.readline()
138 require(greeting and 'QMP' in json.loads(greeting), 'Invalid QMP greeting')
139 self.call('qmp_capabilities')
140
141 def call(self, command, arguments=None):
142 self.stream.write((json.dumps({'execute': command, 'arguments': arguments or {}}) + '\n').encode())
143 self.stream.flush()
144 while True:
145 line = self.stream.readline()
146 require(bool(line), 'QMP connection closed')
147 message = json.loads(line)
148 if 'error' in message:
149 raise RuntimeError(str(message['error']))
150 if 'return' in message:
151 return message['return']
152
153 def close(self):
154 self.stream.close()
155 self.connection.close()
156
157
158 def main():
159 parser = argparse.ArgumentParser(description=__doc__)
160 parser.add_argument('--verified-boot-result', required=True)
161 parser.add_argument('--reference-screenshot', required=True)
162 parser.add_argument('--accel', choices=('whpx', 'tcg'), required=True)
163 options = parser.parse_args()
164 receipt_path = absolute_file(options.verified_boot_result, 'Verified boot receipt')
165 screenshot_path = absolute_file(options.reference_screenshot, 'Reference screenshot')
166 receipt = json.loads(receipt_path.read_text(encoding='utf-8-sig'))
167 require(receipt.get('Kind') == 'BareMetalNativeAotBootProof' and receipt.get('Passed') is True and
168 receipt.get('ImageUnchanged') is True and receipt.get('QemuExitCode') == 0 and receipt.get('Booted') is True,
169 'A passing, cleanly closed native boot receipt is required')
170 image = absolute_file(receipt['ImagePath'], 'Verified source image')
171 source_hash = sha256(image)
172 require(source_hash == receipt['ImageSha256'], 'Source image differs from the verified boot receipt')
173 inspection, payloads = inspect_image(image)
174 require(inspection['ImageSha256'] == source_hash and
175 hashlib.sha256(payloads['System/Kernel.elf']).hexdigest() == receipt['KernelSha256'],
176 'Embedded kernel does not match the verified boot receipt')
177 del payloads
178 snapshot = absolute_file(receipt['SourceSnapshotPath'], 'Verified source snapshot')
179 require(sha256(snapshot) == receipt['SourceSnapshotSha256'], 'Source snapshot differs from the verified boot receipt')
180 require(pathlib.Path(receipt['DefaultAppearance']['Screenshot']).resolve() == screenshot_path and
181 receipt['DefaultAppearance'].get('Passed') is True,
182 'The reference must be the passing idle Desktop screenshot from this same boot receipt')
183 with Image.open(screenshot_path) as source:
184 reference = source.convert('RGB')
185 require(reference.size == (receipt['NativeWidth'], receipt['NativeHeight']), 'Reference/native resolution mismatch')
186 scale_percent = receipt['ScalePercent']
187 require(scale_percent in (100, 200), 'The comparison supports the actual 100/200 percent startup profiles')
188 regions = regions_for(reference.width, reference.height, scale_percent // 100)
189 verify_reference(reference, regions)
190 require(shutil.disk_usage(ROOT).free >= 10 * GIB, 'At least 10 GiB free space is required; no test artifacts were created')
191 out = ROOT / 'build/CSharpBoot' / f'NoSerial-{time.time_ns()}'
192 out.mkdir(parents=True, exist_ok=False)
193 variables = out / 'FirmwareVars.fd'
194 shutil.copyfile(ROOT / '.tools/firmware/edk2-i386-vars.fd', variables)
195 with socket.socket() as probe:
196 probe.bind(('127.0.0.1', 0))
197 port = probe.getsockname()[1]
198 arguments = converted_arguments(receipt['QemuArgs'], image, variables, port, options.accel)
199 result = {
200 'Kind': 'NativeNoSerialFramebufferBootProof', 'Passed': False,
201 'VerifiedBootResult': str(receipt_path), 'VerifiedBootResultSha256': sha256(receipt_path),
202 'ImagePath': str(image), 'ImageSha256': source_hash, 'KernelSha256': receipt['KernelSha256'],
203 'ImageCopied': False, 'SourceDriveReadOnly': False, 'SourceDriveSnapshot': True,
204 'SourceSnapshotSha256': receipt['SourceSnapshotSha256'], 'ReferenceScreenshot': str(screenshot_path),
205 'ReferenceScreenshotSha256': sha256(screenshot_path), 'QemuArgs': arguments, 'Acceleration': options.accel,
206 'TestHarnessSha256': sha256(__file__), 'SerialArgument': 'none', 'SerialControllersAbsent': False,
207 'GuestSerialMarkersObserved': False, 'CompleteStabilityAcceptance': False, 'PhysicalHardwareAcceptance': False,
208 'CudaExecutionVerified': False, 'GpuRasterizationVerified': False,
209 'PixelTolerancePerRgbChannel': 3, 'FullFrameRequiredMatchingFraction': 0.99,
210 'StrictRegionsRequiredMatchingFraction': 1.0, 'StrictRegions': regions,
211 'RequiredConsecutiveMatches': 2, 'TimeoutSeconds': 90, 'Samples': [],
212 }
213 process, qmp = None, None
214 consecutive = 0
215 kept_frames = []
216 started = time.monotonic()
217 try:
218 with (out / 'QemuStdout.log').open('xb') as stdout, (out / 'QemuStderr.log').open('xb') as stderr:
219 process = subprocess.Popen(arguments, cwd=ROOT, stdout=stdout, stderr=stderr)
220 result['OwnedProcessId'] = process.pid
221 deadline = started + 90
222 while time.monotonic() < deadline:
223 if process.poll() is not None:
224 raise RuntimeError('QEMU exited before framebuffer readiness: ' + str(process.returncode))
225 try:
226 qmp = Qmp(socket.create_connection(('127.0.0.1', port), timeout=2))
227 break
228 except ConnectionRefusedError:
229 time.sleep(0.1)
230 require(qmp is not None, 'QMP startup timeout')
231 tree = qmp.call('human-monitor-command', {'command-line': 'info qtree'})
232 require(isinstance(tree, str) and 'bus: main-system-bus' in tree and 'dev:' in tree,
233 'QMP did not return a complete device tree')
234 (out / 'Qtree.txt').write_text(tree, encoding='utf-8')
235 require(not re.search(r'\bdev:\s*(?:isa-serial|serial-mm)\b', tree, re.I),
236 'A serial controller exists despite -serial none')
237 result['SerialControllersAbsent'] = True
238 block_nodes = qmp.call('query-named-block-nodes')
239 require(isinstance(block_nodes, list), 'QMP did not return block node details')
240 source_nodes = [node for node in block_nodes if node.get('drv') == 'raw' and
241 isinstance(node.get('image'), dict) and
242 pathlib.Path(node['image'].get('filename', '')).resolve() == image]
243 require(source_nodes and all(node.get('ro') is True for node in source_nodes),
244 'The exact source image is not attached as a read-only raw backing node')
245 result['SourceDriveReadOnly'] = True
246 result['SourceBlockNodes'] = source_nodes
247 last_capture = started - 1
248 while time.monotonic() < deadline:
249 if process.poll() is not None:
250 raise RuntimeError('QEMU exited before two matching desktop frames')
251 remaining = 1 - (time.monotonic() - last_capture)
252 if remaining > 0:
253 time.sleep(min(remaining, max(0, deadline - time.monotonic())))
254 if time.monotonic() >= deadline:
255 break
256 require(shutil.disk_usage(out).free >= 10 * GIB, 'Free space fell below 10 GiB; no additional screenshot was created')
257 last_capture = time.monotonic()
258 index = len(result['Samples'])
259 ppm, png = out / f'Frame-{index:03}.ppm', out / f'Frame-{index:03}.png'
260 qmp.call('screendump', {'filename': str(ppm)})
261 try:
262 with Image.open(ppm) as frame:
263 actual = frame.convert('RGB')
264 actual.save(png)
265 finally:
266 if ppm.exists():
267 ppm.unlink()
268 fractions = {'FullFrame': close_rgb_fraction(reference, actual)}
269 if actual.size == reference.size:
270 for name, box in regions.items():
271 with reference.crop(box) as expected_region, actual.crop(box) as actual_region:
272 fractions[name] = close_rgb_fraction(expected_region, actual_region)
273 else:
274 fractions.update({name: 0.0 for name in regions})
275 actual.close()
276 matched = fractions['FullFrame'] >= 0.99 and all(fractions[name] == 1.0 for name in regions)
277 consecutive = consecutive + 1 if matched else 0
278 result['Samples'].append({'ElapsedSeconds': round(last_capture - started, 3), 'Screenshot': str(png),
279 'MatchingPixelFractions': fractions, 'Matched': matched,
280 'ConsecutiveMatches': consecutive})
281 kept_frames.append(png)
282 if len(kept_frames) > 2:
283 kept_frames.pop(0).unlink()
284 if consecutive >= 2:
285 result['FramebufferReady'] = True
286 result['DesktopReadyElapsedSeconds'] = round(time.monotonic() - started, 3)
287 break
288 require(consecutive >= 2, 'No serial hardware: desktop framebuffer did not match twice within 90 seconds')
289 except Exception as error:
290 result['Failure'] = type(error).__name__ + ': ' + str(error)
291 finally:
292 if process is not None:
293 if qmp is not None and process.poll() is None:
294 try:
295 qmp.call('quit')
296 result['QmpQuitSent'] = True
297 except Exception as error:
298 result['QmpQuitError'] = str(error)
299 try:
300 process.wait(timeout=10)
301 except subprocess.TimeoutExpired:
302 process.kill()
303 process.wait(timeout=10)
304 result['OwnedProcessKilledAfterTimeout'] = True
305 result['QemuExitCode'] = process.returncode
306 result['OwnedProcessExited'] = process.poll() is not None
307 if qmp is not None:
308 qmp.close()
309 result['ImageSha256After'] = sha256(image)
310 result['ImageUnchanged'] = result['ImageSha256After'] == source_hash
311 result['Passed'] = bool(result.get('FramebufferReady') and result['SerialControllersAbsent'] and result['SourceDriveReadOnly'] and
312 result.get('QmpQuitSent') and result.get('QemuExitCode') == 0 and result['ImageUnchanged'])
313 result['ElapsedSeconds'] = round(time.monotonic() - started, 3)
314 result['RetainedScreenshots'] = [str(path) for path in kept_frames]
315 for sample in result['Samples']:
316 sample['ScreenshotRetained'] = pathlib.Path(sample['Screenshot']).exists()
317 (out / 'Result.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
318 reference.close()
319 print(json.dumps({'Passed': result['Passed'], 'Result': str(out / 'Result.json'),
320 'Failure': result.get('Failure')}, ensure_ascii=False))
321 return 0 if result['Passed'] else 1
322
323
324 if __name__ == '__main__':
325 raise SystemExit(main())
Added Tools/GcRuntimePatch/EarlyBootConsoleRuntimePatch.cs +121 -0
@@ -0,0 +1,121 @@
1 using Mono.Cecil;
2 using Mono.Cecil.Cil;
3
4 /// <summary>
5 /// Explicit, allocation-free access to the existing firmware framebuffer writer.
6 /// The kernel keeps its serial trace separate and disables this writer once its
7 /// first desktop frame owns the framebuffer. No firmware services are invoked.
8 /// </summary>
9 internal static class EarlyBootConsoleRuntimePatch
10 {
11 public const string SetEnabledName = "XfeBootConsoleSetEnabledV1";
12 public const string WriteCharName = "XfeBootConsoleWriteCharV1";
13 public const string SetEnabledExport = "XfeBootConsoleSetEnabled";
14 public const string WriteCharExport = "XfeBootConsoleWriteChar";
15
16 public static bool Apply(AssemblyDefinition assembly)
17 {
18 var module = assembly.MainModule;
19 var console = module.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.IO.EarlyGop");
20 var enabled = console.Fields.Single(field => field.Name == "Enabled");
21 var putChar = console.Methods.Single(method => method.Name == "PutChar" && method.Parameters.Count == 1);
22 if (!console.IsAbstract || !console.IsSealed || !enabled.IsStatic || !enabled.IsPublic || enabled.IsInitOnly ||
23 enabled.FieldType.MetadataType != MetadataType.Boolean || !putChar.IsPublic || !putChar.IsStatic ||
24 putChar.ReturnType.MetadataType != MetadataType.Void || putChar.Parameters[0].ParameterType.MetadataType != MetadataType.Char ||
25 !putChar.HasBody || !putChar.Body.Instructions.Any(instruction => instruction.OpCode == OpCodes.Ldsfld &&
26 instruction.Operand is FieldReference field && field.FullName == enabled.FullName))
27 throw new InvalidOperationException("The pinned early framebuffer console contract changed.");
28
29 var existing = console.Methods.Where(method => method.Name is SetEnabledName or WriteCharName).ToArray();
30 if (existing.Length != 0)
31 {
32 if (existing.Length != 2) throw new InvalidOperationException("Incomplete early framebuffer console exports.");
33 Verify();
34 return true;
35 }
36 foreach (var type in module.Types)
37 if (type.Methods.Any(method => method.CustomAttributes.Any(attribute => attribute.AttributeType.FullName ==
38 "System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute" && attribute.Fields.Any(field =>
39 field.Name == "EntryPoint" && field.Argument.Value is string entry && entry is SetEnabledExport or WriteCharExport))))
40 throw new InvalidOperationException("An early framebuffer console export name is already in use.");
41
42 var setter = Export(SetEnabledName, SetEnabledExport);
43 var si = setter.Body.GetILProcessor();
44 si.Append(si.Create(OpCodes.Ldarg_0));
45 si.Append(si.Create(OpCodes.Ldc_I4_0));
46 si.Append(si.Create(OpCodes.Cgt_Un));
47 si.Append(si.Create(OpCodes.Stsfld, enabled));
48 si.Append(si.Create(OpCodes.Ret));
49 setter.Body.MaxStackSize = 2;
50
51 var writer = Export(WriteCharName, WriteCharExport);
52 var wi = writer.Body.GetILProcessor();
53 var pass = wi.Create(OpCodes.Ldarg_0);
54 var replace = wi.Create(OpCodes.Ldc_I4, (int)'?');
55 var convert = wi.Create(OpCodes.Conv_U2);
56 wi.Append(wi.Create(OpCodes.Ldarg_0));
57 wi.Append(wi.Create(OpCodes.Ldc_I4, (int)'\n'));
58 wi.Append(wi.Create(OpCodes.Beq, pass));
59 wi.Append(wi.Create(OpCodes.Ldarg_0));
60 wi.Append(wi.Create(OpCodes.Ldc_I4, (int)'\r'));
61 wi.Append(wi.Create(OpCodes.Beq, pass));
62 wi.Append(wi.Create(OpCodes.Ldarg_0));
63 wi.Append(wi.Create(OpCodes.Ldc_I4, 0x20));
64 wi.Append(wi.Create(OpCodes.Blt_Un, replace));
65 wi.Append(wi.Create(OpCodes.Ldarg_0));
66 wi.Append(wi.Create(OpCodes.Ldc_I4, 0x7e));
67 wi.Append(wi.Create(OpCodes.Bgt_Un, replace));
68 wi.Append(pass);
69 wi.Append(wi.Create(OpCodes.Br, convert));
70 wi.Append(replace);
71 wi.Append(convert);
72 wi.Append(wi.Create(OpCodes.Call, putChar));
73 wi.Append(wi.Create(OpCodes.Ret));
74 writer.Body.MaxStackSize = 2;
75 Verify();
76 return false;
77
78 MethodDefinition Export(string name, string entryPoint)
79 {
80 var method = new MethodDefinition(name, MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig,
81 module.TypeSystem.Void);
82 method.Parameters.Add(new("value", ParameterAttributes.None, module.TypeSystem.Int32));
83 var attribute = new CustomAttribute(module.ImportReference(typeof(System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute)
84 .GetConstructor(Type.EmptyTypes)!));
85 attribute.Fields.Add(new("EntryPoint", new CustomAttributeArgument(module.TypeSystem.String, entryPoint)));
86 method.CustomAttributes.Add(attribute);
87 console.Methods.Add(method);
88 return method;
89 }
90
91 void Verify()
92 {
93 var setter = console.Methods.Single(method => method.Name == SetEnabledName);
94 var writer = console.Methods.Single(method => method.Name == WriteCharName);
95 foreach (var (method, entryPoint) in new[] { (setter, SetEnabledExport), (writer, WriteCharExport) })
96 if (!method.IsStatic || !method.IsAssembly || method.ReturnType.MetadataType != MetadataType.Void ||
97 method.Parameters.Count != 1 || method.Parameters[0].ParameterType.MetadataType != MetadataType.Int32 ||
98 !method.HasBody || method.Body.InitLocals || method.Body.Variables.Count != 0 || method.Body.ExceptionHandlers.Count != 0 ||
99 method.CustomAttributes.Count != 1 || method.CustomAttributes[0].AttributeType.FullName !=
100 "System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute" || method.CustomAttributes[0].Fields.Count != 1 ||
101 method.CustomAttributes[0].Fields[0].Name != "EntryPoint" || !Equals(method.CustomAttributes[0].Fields[0].Argument.Value, entryPoint))
102 throw new InvalidOperationException("An early framebuffer console export contract changed.");
103 var set = setter.Body.Instructions;
104 if (set.Count != 5 || set[0].OpCode != OpCodes.Ldarg_0 || set[1].OpCode != OpCodes.Ldc_I4_0 ||
105 set[2].OpCode != OpCodes.Cgt_Un || set[3].OpCode != OpCodes.Stsfld ||
106 set[3].Operand is not FieldReference field || field.FullName != enabled.FullName || set[4].OpCode != OpCodes.Ret)
107 throw new InvalidOperationException("The early framebuffer console setter is not its expected leaf.");
108 var write = writer.Body.Instructions;
109 var expected = new[] { OpCodes.Ldarg_0, OpCodes.Ldc_I4, OpCodes.Beq, OpCodes.Ldarg_0, OpCodes.Ldc_I4, OpCodes.Beq,
110 OpCodes.Ldarg_0, OpCodes.Ldc_I4, OpCodes.Blt_Un, OpCodes.Ldarg_0, OpCodes.Ldc_I4, OpCodes.Bgt_Un,
111 OpCodes.Ldarg_0, OpCodes.Br, OpCodes.Ldc_I4, OpCodes.Conv_U2, OpCodes.Call, OpCodes.Ret };
112 if (write.Count != expected.Length || write.Where((instruction, index) => instruction.OpCode != expected[index]).Any() ||
113 !Equals(write[1].Operand, (int)'\n') || !Equals(write[4].Operand, (int)'\r') || !Equals(write[7].Operand, 0x20) ||
114 !Equals(write[10].Operand, 0x7e) || !Equals(write[14].Operand, (int)'?') ||
115 !ReferenceEquals(write[2].Operand, write[12]) || !ReferenceEquals(write[5].Operand, write[12]) ||
116 !ReferenceEquals(write[8].Operand, write[14]) || !ReferenceEquals(write[11].Operand, write[14]) ||
117 !ReferenceEquals(write[13].Operand, write[15]) || write[16].Operand is not MethodReference call || call.FullName != putChar.FullName)
118 throw new InvalidOperationException("The early framebuffer console character export is not its bounded ASCII leaf.");
119 }
120 }
121 }
Modified Tools/GcRuntimePatch/Program.cs +11 -1
@@ -115,6 +115,8 @@ bool funcletEhAlreadyPatched = FuncletEhRuntimePatch.Apply(runtime);
115 115 bool threadEhAlreadyPatched = ThreadEhRuntimePatch.Apply(runtime);
116 116 bool frozenRangeAlreadyPatched = FrozenRangeRuntimePatch.Apply(runtime);
117 117 bool gcMemoryAlreadyPatched = GcMemoryRuntimePatch.Apply(runtime);
118 bool serialAlreadyPatched = SerialRuntimePatch.Apply(runtime);
119 bool earlyBootConsoleAlreadyPatched = EarlyBootConsoleRuntimePatch.Apply(runtime);
118 120 // A stale receipt may accompany the official file after the Cosmos patcher restores it.
119 121 // Trust that exact pinned file independently; retain stable provenance on repeat invocations.
120 122 // Unknown files still undergo both shape checks before rejection, and cannot be partially written.
@@ -128,7 +130,7 @@ if (alreadyPatched && !ehAlreadyPatched)
128 130 previous.RootElement.GetProperty("BeforeSha256").GetString() != pinnedOriginalSha256)
129 131 throw new InvalidOperationException("The previous GC patch is not a verified pinned-origin private copy.");
130 132 }
131 if (!alreadyPatched || !ehAlreadyPatched || !allocationAlreadyPatched || !threadEhAlreadyPatched || !funcletEhAlreadyPatched || !threadStackAlreadyPatched || !gcMemoryAlreadyPatched || !frozenRangeAlreadyPatched)
133 if (!alreadyPatched || !ehAlreadyPatched || !allocationAlreadyPatched || !threadEhAlreadyPatched || !funcletEhAlreadyPatched || !threadStackAlreadyPatched || !gcMemoryAlreadyPatched || !frozenRangeAlreadyPatched || !serialAlreadyPatched || !earlyBootConsoleAlreadyPatched)
132 134 {
133 135 var temporary = runtimePath + ".XfeGc.tmp";
134 136 runtime.Write(temporary);
@@ -165,10 +167,18 @@ var receipt = new
165 167 , DependentHandleCountReadOnlyExport = true
166 168 , FrozenUpdateAcceptsAbsoluteEndAddresses = true, FrozenUpdateNormalizesByteCounts = true,
167 169 FrozenUpdateValidatesUnsignedRange = true, FrozenRangeAlreadyPatched = frozenRangeAlreadyPatched
170 , SerialFinitePolling = true, SerialPollLimit = SerialRuntimePatch.PollLimit,
171 SerialAlreadyPatched = serialAlreadyPatched, SerialMissingStatus = "0xFF",
172 SerialFailureDisablesOutputForThisBoot = true, SerialNewHardwareProbeWrites = false,
173 SerialInitializationPreserved = true, SerialCounterExports = 4,
174 EarlyBootConsoleAlreadyPatched = earlyBootConsoleAlreadyPatched,
175 EarlyBootConsoleLeafExports = 2, EarlyBootConsoleChangesSystemStart = false,
176 PhysicalBootAcceptancePassed = false
168 177 };
169 178 File.WriteAllText(receiptPath + ".tmp", JsonSerializer.Serialize(receipt, new JsonSerializerOptions { WriteIndented = true }));
170 179 File.Move(receiptPath + ".tmp", receiptPath, true);
171 180 Console.WriteLine("XFE precise GC tail fallback ready; native regression still required.");
172 181 Console.WriteLine("XFE active EH catch tracking limit 4096 ready; native deep-rethrow regression still required.");
173 182 Console.WriteLine("XFE allocation failure guards ready; out of memory halts the entire guest without allocation or recovery.");
183 Console.WriteLine("XFE bounded serial output ready; absence or stuck UART disables diagnostics, never waits forever.");
174 184 static string Hash(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
Added Tools/GcRuntimePatch/SerialRuntimePatch.cs +141 -0
@@ -0,0 +1,141 @@
1 using Mono.Cecil;
2 using Mono.Cecil.Cil;
3
4 /// <summary>Serial diagnostics must never prevent a machine without COM1 from booting.</summary>
5 internal static class SerialRuntimePatch
6 {
7 public const string HelperName = "XfeBoundedComWriteV1";
8 // An iteration bound deliberately works before any clock, scheduler or IRQ exists.
9 // A failed UART is disabled for this boot, so later diagnostics do not repeat it.
10 public const int PollLimit = 4096;
11 private const string Prefix = "XfeSerialV1_";
12 private static readonly string[] CounterNames = ["Absent", "Timeout", "Dropped", "Written"];
13
14 public static bool Apply(AssemblyDefinition assembly)
15 {
16 if (assembly.Name.Name != "Cosmos.Kernel.Core" || assembly.Name.Version != new Version(3, 0, 94, 0))
17 throw new InvalidOperationException("Bounded serial output supports only pinned Cosmos.Kernel.Core 3.0.94.");
18 var module = assembly.MainModule;
19 var serial = module.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.IO.Serial");
20 var write = serial.Methods.Single(method => method.Name == "ComWrite" && method.IsStatic && method.HasBody &&
21 method.ReturnType.MetadataType == MetadataType.Void && method.Parameters.Count == 1 && method.Parameters[0].ParameterType.MetadataType == MetadataType.Byte);
22 var uart = module.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.CosmosFeatures").Methods.Single(method => method.Name == "get_UARTEnabled");
23 var io = module.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.Native").NestedTypes.Single(type => type.Name == "IO");
24 var read = io.Methods.Single(method => method.Name == "Read8");
25 var output = io.Methods.Single(method => method.Name == "Write8");
26 var existing = serial.Methods.SingleOrDefault(method => method.Name == HelperName);
27 if (existing is not null)
28 {
29 Verify(serial, write, uart, read, output);
30 return true;
31 }
32 if (serial.Fields.Any(field => field.Name.StartsWith(Prefix, StringComparison.Ordinal)) ||
33 serial.Methods.Any(method => method.Name.StartsWith("XfeSerial", StringComparison.Ordinal)))
34 throw new InvalidOperationException("Incomplete or unknown bounded serial patch exists.");
35 // Exact pinned x64 body, including branch destinations, constants and native calls.
36 if (!OriginalReleaseShape(write, uart, read, output))
37 throw new InvalidOperationException("Pinned x64 ComWrite IL changed; refusing to patch an unknown UART implementation.");
38 var disabled = new FieldDefinition(Prefix + "Disabled", FieldAttributes.Private | FieldAttributes.Static, module.TypeSystem.Boolean);
39 serial.Fields.Add(disabled);
40 var counters = CounterNames.ToDictionary(name => name, name => new FieldDefinition(Prefix + name, FieldAttributes.Private | FieldAttributes.Static, module.TypeSystem.UInt64));
41 foreach (var counter in counters.Values) serial.Fields.Add(counter);
42 var helper = new MethodDefinition(HelperName, MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig, module.TypeSystem.Void);
43 helper.Parameters.Add(new("value", ParameterAttributes.None, module.TypeSystem.Byte)); serial.Methods.Add(helper);
44 EmitHelper(helper, disabled, counters, read, output);
45 EmitWrapper(write, uart, helper);
46 foreach (var name in CounterNames)
47 {
48 var getter = new MethodDefinition("XfeSerial" + name + "CountV1", MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig, module.TypeSystem.UInt64);
49 var attribute = new CustomAttribute(module.ImportReference(typeof(System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute).GetConstructor(Type.EmptyTypes)!));
50 attribute.Fields.Add(new("EntryPoint", new CustomAttributeArgument(module.TypeSystem.String, "XfeRuntimeSerial" + name + "Count")));
51 getter.CustomAttributes.Add(attribute); serial.Methods.Add(getter);
52 var il = getter.Body.GetILProcessor(); il.Append(il.Create(OpCodes.Ldsfld, counters[name])); il.Append(il.Create(OpCodes.Ret)); getter.Body.MaxStackSize = 1;
53 }
54 Verify(serial, write, uart, read, output);
55 return false;
56 }
57
58 private static bool OriginalReleaseShape(MethodDefinition write, MethodReference uart, MethodReference read, MethodReference output)
59 {
60 var i = write.Body.Instructions;
61 return write.Body.CodeSize == 34 && write.Body.Variables.Count == 0 && write.Body.ExceptionHandlers.Count == 0 && i.Count == 11 &&
62 Calls(i[0], uart) && i[1].OpCode == OpCodes.Brfalse_S && ReferenceEquals(i[1].Operand, i[10]) &&
63 i[2].OpCode == OpCodes.Ldc_I4 && Equals(i[2].Operand, 0x3fd) && Calls(i[3], read) &&
64 i[4].OpCode == OpCodes.Ldc_I4_S && Equals(i[4].Operand, (sbyte)0x20) && i[5].OpCode == OpCodes.And &&
65 i[6].OpCode == OpCodes.Brfalse_S && ReferenceEquals(i[6].Operand, i[2]) &&
66 i[7].OpCode == OpCodes.Ldc_I4 && Equals(i[7].Operand, 0x3f8) && i[8].OpCode == OpCodes.Ldarg_0 &&
67 Calls(i[9], output) && i[10].OpCode == OpCodes.Ret;
68 }
69
70 private static void EmitWrapper(MethodDefinition write, MethodReference uart, MethodReference helper)
71 {
72 write.Body = new MethodBody(write); var il = write.Body.GetILProcessor(); var end = il.Create(OpCodes.Ret);
73 il.Append(il.Create(OpCodes.Call, uart)); il.Append(il.Create(OpCodes.Brfalse, end));
74 il.Append(il.Create(OpCodes.Ldarg_0)); il.Append(il.Create(OpCodes.Call, helper)); il.Append(end); write.Body.MaxStackSize = 1;
75 }
76
77 private static void EmitHelper(MethodDefinition helper, FieldReference disabled, IReadOnlyDictionary<string, FieldDefinition> counters, MethodReference read, MethodReference output)
78 {
79 helper.Body = new MethodBody(helper) { InitLocals = true, MaxStackSize = 3 };
80 var count = new VariableDefinition(helper.Module.TypeSystem.Int32); var status = new VariableDefinition(helper.Module.TypeSystem.Byte);
81 helper.Body.Variables.Add(count); helper.Body.Variables.Add(status);
82 var il = helper.Body.GetILProcessor();
83 var dropped = il.Create(OpCodes.Ldsfld, counters["Dropped"]); var absent = il.Create(OpCodes.Ldsfld, counters["Absent"]);
84 var timeout = il.Create(OpCodes.Ldsfld, counters["Timeout"]); var disable = il.Create(OpCodes.Ldc_I4_1);
85 var next = il.Create(OpCodes.Ldloc, count); var poll = il.Create(OpCodes.Ldc_I4, 0x3fd);
86 il.Append(il.Create(OpCodes.Ldsfld, disabled)); il.Append(il.Create(OpCodes.Brtrue, dropped));
87 il.Append(il.Create(OpCodes.Ldc_I4_0)); il.Append(il.Create(OpCodes.Stloc, count));
88 il.Append(poll); il.Append(il.Create(OpCodes.Call, read)); il.Append(il.Create(OpCodes.Stloc, status));
89 il.Append(il.Create(OpCodes.Ldloc, status)); il.Append(il.Create(OpCodes.Ldc_I4, 0xff)); il.Append(il.Create(OpCodes.Beq, absent));
90 il.Append(il.Create(OpCodes.Ldloc, status)); il.Append(il.Create(OpCodes.Ldc_I4, 0x20)); il.Append(il.Create(OpCodes.And)); il.Append(il.Create(OpCodes.Brfalse, next));
91 il.Append(il.Create(OpCodes.Ldc_I4, 0x3f8)); il.Append(il.Create(OpCodes.Ldarg_0)); il.Append(il.Create(OpCodes.Call, output));
92 Increment("Written"); il.Append(il.Create(OpCodes.Ret));
93 il.Append(next); il.Append(il.Create(OpCodes.Ldc_I4_1)); il.Append(il.Create(OpCodes.Add)); il.Append(il.Create(OpCodes.Stloc, count));
94 il.Append(il.Create(OpCodes.Ldloc, count)); il.Append(il.Create(OpCodes.Ldc_I4, PollLimit)); il.Append(il.Create(OpCodes.Blt, poll));
95 il.Append(timeout); IncrementTail("Timeout"); il.Append(il.Create(OpCodes.Br, disable));
96 il.Append(absent); IncrementTail("Absent");
97 il.Append(disable); il.Append(il.Create(OpCodes.Stsfld, disabled));
98 il.Append(dropped); IncrementTail("Dropped"); il.Append(il.Create(OpCodes.Ret));
99 void Increment(string name) { il.Append(il.Create(OpCodes.Ldsfld, counters[name])); IncrementTail(name); }
100 void IncrementTail(string name) { il.Append(il.Create(OpCodes.Ldc_I4_1)); il.Append(il.Create(OpCodes.Conv_U8)); il.Append(il.Create(OpCodes.Add)); il.Append(il.Create(OpCodes.Stsfld, counters[name])); }
101 }
102
103 private static void Verify(TypeDefinition serial, MethodDefinition write, MethodReference uart, MethodReference read, MethodReference output)
104 {
105 var helper = serial.Methods.Single(method => method.Name == HelperName);
106 var disabled = serial.Fields.Single(field => field.Name == Prefix + "Disabled");
107 var counters = CounterNames.ToDictionary(name => name, name => serial.Fields.Single(field => field.Name == Prefix + name));
108 if (!disabled.IsPrivate || !disabled.IsStatic || disabled.FieldType.MetadataType != MetadataType.Boolean ||
109 counters.Values.Any(field => !field.IsPrivate || !field.IsStatic || field.FieldType.MetadataType != MetadataType.UInt64) ||
110 helper.ReturnType.MetadataType != MetadataType.Void || helper.Parameters.Count != 1 || helper.Parameters[0].ParameterType.MetadataType != MetadataType.Byte)
111 throw new InvalidOperationException("Unexpected bounded serial state or signature.");
112 var expected = new MethodDefinition("Expected", MethodAttributes.Static, serial.Module.TypeSystem.Void);
113 expected.Parameters.Add(new("value", ParameterAttributes.None, serial.Module.TypeSystem.Byte)); serial.Methods.Add(expected);
114 try
115 {
116 EmitHelper(expected, disabled, counters, read, output);
117 if (Canonical(helper) != Canonical(expected)) throw new InvalidOperationException("Bounded serial helper differs from its fixed polling contract.");
118 EmitWrapper(expected, uart, helper);
119 if (Canonical(write) != Canonical(expected)) throw new InvalidOperationException("Bounded serial wrapper changed its feature gate.");
120 }
121 finally { serial.Methods.Remove(expected); }
122 foreach (string name in CounterNames)
123 {
124 var getter = serial.Methods.Single(method => method.Name == "XfeSerial" + name + "CountV1");
125 if (getter.Body.Instructions.Count != 2 || getter.Body.Instructions[0].OpCode != OpCodes.Ldsfld ||
126 getter.Body.Instructions[0].Operand is not FieldReference field || field.FullName != counters[name].FullName ||
127 getter.Body.Instructions[1].OpCode != OpCodes.Ret || !getter.CustomAttributes.Any(attribute => attribute.AttributeType.Name == "UnmanagedCallersOnlyAttribute" &&
128 attribute.Fields.Any(argument => argument.Name == "EntryPoint" && Equals(argument.Argument.Value, "XfeRuntimeSerial" + name + "Count"))))
129 throw new InvalidOperationException("Serial diagnostic counter is not a read-only leaf export.");
130 }
131 }
132
133 private static bool Calls(Instruction i, MethodReference method) => i.OpCode == OpCodes.Call && i.Operand is MethodReference call && call.FullName == method.FullName;
134 private static string Canonical(MethodDefinition method) =>
135 string.Join(";", method.Body.Variables.Select(variable => variable.VariableType.FullName)) + "|" + method.Body.InitLocals + "|" + method.Body.ExceptionHandlers.Count + "|" +
136 string.Join("\n", method.Body.Instructions.Select(instruction => instruction.OpCode.Code + ":" + (instruction.Operand switch
137 {
138 Instruction branch => "#" + method.Body.Instructions.IndexOf(branch), VariableDefinition local => "$" + local.Index,
139 MemberReference member => member.FullName, null => "", var operand => operand.ToString()
140 })));
141 }
Added Tools/GcRuntimePatch/Tests/EarlyBootConsoleRuntimePatchChecks.cs +123 -0
@@ -0,0 +1,123 @@
1 using Mono.Cecil;
2 using Mono.Cecil.Cil;
3
4 internal static class EarlyBootConsoleRuntimePatchChecks
5 {
6 public static void Run(Action<string, bool> check)
7 {
8 using var assembly = Fixture();
9 var console = assembly.MainModule.Types.Single(type => type.Name == "EarlyGop");
10 var originalPutChar = console.Methods.Single(method => method.Name == "PutChar");
11 var originalBody = originalPutChar.Body.Instructions.ToArray();
12 check("EarlyConsoleFirstApplyAddsExports", !EarlyBootConsoleRuntimePatch.Apply(assembly));
13 check("EarlyConsoleSecondApplyVerifiesWithoutDuplicates", EarlyBootConsoleRuntimePatch.Apply(assembly) && console.Methods.Count == 3);
14 check("EarlyConsoleOriginalWriterUnchanged", originalBody.SequenceEqual(originalPutChar.Body.Instructions));
15 var writer = console.Methods.Single(method => method.Name == EarlyBootConsoleRuntimePatch.WriteCharName);
16 int[] inputs = [int.MinValue, -65526, -1, 0, 9, 10, 13, 31, 32, 65, 126, 127, 255, 65546, int.MaxValue];
17 check("EarlyConsoleAsciiAndLineBreaksOnly", inputs.All(value => Simulate(writer, value) ==
18 (value is '\n' or '\r' or >= 0x20 and <= 0x7e ? value : '?')));
19 check("EarlyConsoleExportsAvoidAllocationAndExceptions", console.Methods.Where(method => method.Name != "PutChar").All(method =>
20 method.Body.Variables.Count == 0 && method.Body.ExceptionHandlers.Count == 0 &&
21 method.Body.Instructions.All(instruction => instruction.OpCode.Code is not (Code.Newobj or Code.Newarr or Code.Throw or Code.Callvirt))));
22
23 using (var serialized = new MemoryStream())
24 {
25 assembly.Write(serialized);
26 serialized.Position = 0;
27 using var reloaded = AssemblyDefinition.ReadAssembly(serialized);
28 check("EarlyConsoleRoundtripIdempotence", EarlyBootConsoleRuntimePatch.Apply(reloaded));
29 }
30 using (var partial = Fixture())
31 {
32 EarlyBootConsoleRuntimePatch.Apply(partial);
33 var type = partial.MainModule.Types.Single(type => type.Name == "EarlyGop");
34 type.Methods.Remove(type.Methods.Single(method => method.Name == EarlyBootConsoleRuntimePatch.WriteCharName));
35 check("EarlyConsolePartialPatchRejected", Rejects(() => EarlyBootConsoleRuntimePatch.Apply(partial)));
36 }
37 using (var altered = Fixture())
38 {
39 EarlyBootConsoleRuntimePatch.Apply(altered);
40 var type = altered.MainModule.Types.Single(type => type.Name == "EarlyGop");
41 type.Methods.Single(method => method.Name == EarlyBootConsoleRuntimePatch.WriteCharName).Body.Instructions[10].Operand = 255;
42 check("EarlyConsoleAlteredRangeRejected", Rejects(() => EarlyBootConsoleRuntimePatch.Apply(altered)));
43 }
44 using (var altered = Fixture())
45 {
46 var type = altered.MainModule.Types.Single(type => type.Name == "EarlyGop");
47 type.Fields.Single().FieldType = altered.MainModule.TypeSystem.Int32;
48 check("EarlyConsoleChangedFieldContractRejected", Rejects(() => EarlyBootConsoleRuntimePatch.Apply(altered)));
49 }
50 using (var altered = Fixture())
51 {
52 var type = altered.MainModule.Types.Single(type => type.Name == "EarlyGop");
53 type.Methods.Single().Parameters[0].ParameterType = altered.MainModule.TypeSystem.Int32;
54 check("EarlyConsoleChangedWriterContractRejected", Rejects(() => EarlyBootConsoleRuntimePatch.Apply(altered)));
55 }
56 using (var altered = Fixture())
57 {
58 EarlyBootConsoleRuntimePatch.Apply(altered);
59 var type = altered.MainModule.Types.Single(type => type.Name == "EarlyGop");
60 var method = type.Methods.Single(method => method.Name == EarlyBootConsoleRuntimePatch.WriteCharName);
61 method.Body.Instructions[2].Operand = method.Body.Instructions[^1];
62 check("EarlyConsoleAlteredBranchRejected", Rejects(() => EarlyBootConsoleRuntimePatch.Apply(altered)));
63 }
64 }
65
66 private static AssemblyDefinition Fixture()
67 {
68 var assembly = AssemblyDefinition.CreateAssembly(new AssemblyNameDefinition("EarlyConsoleFixture", new Version(1, 0)),
69 "EarlyConsoleFixture", ModuleKind.Dll);
70 var module = assembly.MainModule;
71 var type = new TypeDefinition("Cosmos.Kernel.Core.IO", "EarlyGop", TypeAttributes.NotPublic | TypeAttributes.Abstract | TypeAttributes.Sealed,
72 module.TypeSystem.Object);
73 module.Types.Add(type);
74 var enabled = new FieldDefinition("Enabled", FieldAttributes.Public | FieldAttributes.Static, module.TypeSystem.Boolean);
75 type.Fields.Add(enabled);
76 var putChar = new MethodDefinition("PutChar", MethodAttributes.Public | MethodAttributes.Static, module.TypeSystem.Void);
77 putChar.Parameters.Add(new("character", ParameterAttributes.None, module.TypeSystem.Char));
78 type.Methods.Add(putChar);
79 var il = putChar.Body.GetILProcessor();
80 il.Append(il.Create(OpCodes.Ldsfld, enabled)); il.Append(il.Create(OpCodes.Pop)); il.Append(il.Create(OpCodes.Ret));
81 return assembly;
82 }
83
84 // Interpret the small integer/branch prefix rather than execute a hardware
85 // framebuffer writer on the host. The output is the argument to PutChar.
86 private static int Simulate(MethodDefinition method, int value)
87 {
88 var stack = new Stack<int>();
89 var instructions = method.Body.Instructions;
90 for (int index = 0, budget = 50; budget-- > 0; index++)
91 {
92 var instruction = instructions[index];
93 switch (instruction.OpCode.Code)
94 {
95 case Code.Ldarg_0: stack.Push(value); break;
96 case Code.Ldc_I4: stack.Push((int)instruction.Operand); break;
97 case Code.Beq:
98 case Code.Blt_Un:
99 case Code.Bgt_Un:
100 int right = stack.Pop(), left = stack.Pop();
101 bool taken = instruction.OpCode.Code switch
102 {
103 Code.Beq => left == right,
104 Code.Blt_Un => unchecked((uint)left) < unchecked((uint)right),
105 _ => unchecked((uint)left) > unchecked((uint)right)
106 };
107 if (taken) index = instructions.IndexOf((Instruction)instruction.Operand) - 1;
108 break;
109 case Code.Br: index = instructions.IndexOf((Instruction)instruction.Operand) - 1; break;
110 case Code.Conv_U2: stack.Push(unchecked((ushort)stack.Pop())); break;
111 case Code.Call: return stack.Pop();
112 default: throw new InvalidOperationException("Unexpected early console simulation instruction.");
113 }
114 }
115 throw new InvalidOperationException("The early console simulation exceeded its bounded instruction budget.");
116 }
117
118 private static bool Rejects(Action action)
119 {
120 try { action(); return false; }
121 catch (InvalidOperationException) { return true; }
122 }
123 }
Modified Tools/GcRuntimePatch/Tests/GcRuntimePatch.Check.csproj +2 -0
@@ -10,5 +10,7 @@
10 10 <ItemGroup>
11 11 <PackageReference Include="Mono.Cecil" Version="0.11.6" />
12 12 <Compile Include="../Fixture/NativeGcRegression.cs" Link="NativeGcRegression.cs" />
13 <Compile Include="../EarlyBootConsoleRuntimePatch.cs" Link="EarlyBootConsoleRuntimePatch.cs" />
14 <Compile Include="../SerialRuntimePatch.cs" Link="SerialRuntimePatch.cs" />
13 15 </ItemGroup>
14 16 </Project>
Modified Tools/GcRuntimePatch/Tests/Program.cs +2 -0
@@ -9,6 +9,7 @@ if (args.Length != 3) throw new ArgumentException("GcRuntimePatch.Check <patcher
9 9 string patcher = Path.GetFullPath(args[0]), original = Path.GetFullPath(args[1]), fixture = Path.GetFullPath(args[2]);
10 10 Directory.CreateDirectory(fixture);
11 11 var checks = new List<object>();
12 EarlyBootConsoleRuntimePatchChecks.Run(Check);
12 13 string originalHash = Hash(original);
13 14 string kernelRoot = Path.Combine(fixture, "KernelCopy");
14 15 Directory.CreateDirectory(kernelRoot);
@@ -23,6 +24,7 @@ string patchedHash = Hash(privatePath);
23 24 using (var before = AssemblyDefinition.ReadAssembly(original))
24 25 using (var after = AssemblyDefinition.ReadAssembly(privatePath))
25 26 {
27 SerialRuntimePatchChecks.Run(before, after, Check);
26 28 var originalGc = Gc(before); var patchedGc = Gc(after);
27 29 var target = patchedGc.Methods.Single(m => m.Name == "PreciseScanFrameChain");
28 30 var helper = patchedGc.Methods.Single(m => m.Name == "XfeScanPreciseTailFallbackV1");
Added Tools/GcRuntimePatch/Tests/SerialRuntimePatchChecks.cs +142 -0
@@ -0,0 +1,142 @@
1 using System.Reflection;
2 using System.Runtime.Loader;
3 using Mono.Cecil;
4 using Mono.Cecil.Cil;
5
6 internal static class SerialRuntimePatchChecks
7 {
8 public static void Run(AssemblyDefinition before, AssemblyDefinition after, Action<string, bool> check)
9 {
10 var serial = after.MainModule.Types.Single(type => type.FullName == "Cosmos.Kernel.Core.IO.Serial");
11 var original = before.MainModule.Types.Single(type => type.FullName == serial.FullName);
12 var helper = serial.Methods.Single(method => method.Name == SerialRuntimePatch.HelperName);
13 check("SerialInitializationAndOtherWritersUnchanged", original.Methods.Where(method => method.Name != "ComWrite").All(method =>
14 Il(method) == Il(serial.Methods.Single(candidate => candidate.FullName == method.FullName))));
15 check("SerialFixedBudgetWithoutClockAllocationOrIrqChanges", helper.Body.Instructions.Any(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 4096)) &&
16 helper.Body.ExceptionHandlers.Count == 0 && helper.Body.Instructions.All(instruction => instruction.OpCode.Code is not (Code.Newobj or Code.Newarr or Code.Throw or Code.Callvirt)) &&
17 helper.Body.Instructions.Where(instruction => instruction.Operand is MethodReference).All(instruction => instruction.Operand is MethodReference call &&
18 call.DeclaringType.FullName == "Cosmos.Kernel.Core.Native/IO" && call.Name is "Read8" or "Write8"));
19 check("SerialReadOnlyCounterExports", new[] { "Absent", "Timeout", "Dropped", "Written" }.All(name =>
20 {
21 var getter = serial.Methods.Single(method => method.Name == "XfeSerial" + name + "CountV1");
22 return getter.Body.Instructions.Count == 2 && getter.Body.Instructions[0].OpCode == OpCodes.Ldsfld && getter.Body.Instructions[1].OpCode == OpCodes.Ret;
23 }));
24
25 // Execute copies of the actual patched IL with only its two privileged
26 // I/O calls redirected to fake ports. No hardware instructions execute.
27 using var clone = CreateExecutableFixture(serial);
28 using var bytes = new MemoryStream(); clone.Write(bytes); bytes.Position = 0;
29 var context = new AssemblyLoadContext("BoundedSerialFixture", isCollectible: true);
30 try
31 {
32 var type = context.LoadFromStream(bytes).GetType("Fixture.Serial", throwOnError: true)!;
33 var write = type.GetMethod("ComWrite")!;
34 void Reset(bool enabled, params byte[] statuses)
35 {
36 SerialIoFixture.Reset(enabled, statuses);
37 foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Static))
38 field.SetValue(null, field.FieldType == typeof(bool) ? false : 0UL);
39 }
40 void Write(byte value) => write.Invoke(null, [value]);
41 ulong Counter(string name) => (ulong)type.GetField("XfeSerialV1_" + name)!.GetValue(null)!;
42
43 Reset(false, 0); Write(65);
44 check("SerialFeatureDisabledDoesNoPortIo", SerialIoFixture.Reads == 0 && SerialIoFixture.Writes == 0 && Counter("Dropped") == 0);
45 Reset(true, 0x20); Write(65);
46 check("SerialReadyWritesOriginalByteToCom1", SerialIoFixture.Reads == 1 && SerialIoFixture.Writes == 1 && SerialIoFixture.LastValue == 65 && Counter("Written") == 1);
47 Reset(true, 0, 0, 0x20); Write(0xff);
48 check("SerialTransientBusyThenReadyPreservesByte", SerialIoFixture.Reads == 3 && SerialIoFixture.Writes == 1 && SerialIoFixture.LastValue == 0xff && Counter("Timeout") == 0);
49 Reset(true, Enumerable.Repeat((byte)0, 4095).Append((byte)0x20).ToArray()); Write(42);
50 check("SerialLastPermittedPollMayWrite", SerialIoFixture.Reads == 4096 && SerialIoFixture.Writes == 1 && Counter("Timeout") == 0);
51 Reset(true, 0); Write(65);
52 check("SerialStuckZeroReturnsAtExactBudget", SerialIoFixture.Reads == 4096 && SerialIoFixture.Writes == 0 && Counter("Timeout") == 1 && Counter("Dropped") == 1);
53 Write(66);
54 check("SerialStuckOutputStaysDisabledWithoutRepeatingWait", SerialIoFixture.Reads == 4096 && SerialIoFixture.Writes == 0 && Counter("Timeout") == 1 && Counter("Dropped") == 2);
55 Reset(true, 0x10); Write(1);
56 check("SerialStuckNonzeroBusyAlsoReturns", SerialIoFixture.Reads == 4096 && SerialIoFixture.Writes == 0 && Counter("Timeout") == 1);
57 Reset(true, 0xff); Write(65);
58 check("SerialMissingUartReturnsAfterOneRead", SerialIoFixture.Reads == 1 && SerialIoFixture.Writes == 0 && Counter("Absent") == 1 && Counter("Dropped") == 1);
59 Write(66);
60 check("SerialMissingUartStaysDisabled", SerialIoFixture.Reads == 1 && SerialIoFixture.Writes == 0 && Counter("Absent") == 1 && Counter("Dropped") == 2);
61 Reset(true, 0x21); Write(10); Write(13);
62 check("SerialReadyWithOtherStatusBitsAndLineEndings", SerialIoFixture.Reads == 2 && SerialIoFixture.Writes == 2 && SerialIoFixture.LastValue == 13 && Counter("Written") == 2);
63 check("SerialFixturesUseOnlyExistingCom1Ports", SerialIoFixture.InvalidPortAccesses == 0);
64 }
65 finally { context.Unload(); }
66
67 check("SerialRepeatedApplyVerifiesWithoutMutation", SerialRuntimePatch.Apply(after));
68 var budget = helper.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 4096));
69 budget.Operand = 4097;
70 check("SerialModifiedPollingBudgetRejected", Rejects(() => SerialRuntimePatch.Apply(after)));
71 budget.Operand = 4096;
72 using var alteredOriginal = AssemblyDefinition.ReadAssembly(new MemoryStream(ToBytes(before)));
73 var changed = alteredOriginal.MainModule.Types.Single(type => type.FullName == serial.FullName).Methods.Single(method => method.Name == "ComWrite");
74 changed.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Ldc_I4 && Equals(instruction.Operand, 0x3fd)).Operand = 0x2fd;
75 check("SerialUnknownOriginalPortShapeRejected", Rejects(() => SerialRuntimePatch.Apply(alteredOriginal)));
76 }
77
78 private static AssemblyDefinition CreateExecutableFixture(TypeDefinition source)
79 {
80 var fixture = AssemblyDefinition.CreateAssembly(new AssemblyNameDefinition("SerialFixture_" + Guid.NewGuid().ToString("N"), new Version(1, 0)), "SerialFixture", ModuleKind.Dll);
81 var module = fixture.MainModule;
82 var type = new TypeDefinition("Fixture", "Serial", Mono.Cecil.TypeAttributes.Public | Mono.Cecil.TypeAttributes.Abstract | Mono.Cecil.TypeAttributes.Sealed, module.TypeSystem.Object);
83 module.Types.Add(type);
84 var fields = source.Fields.Where(field => field.Name.StartsWith("XfeSerialV1_", StringComparison.Ordinal)).ToDictionary(field => field.Name,
85 field => new FieldDefinition(field.Name, Mono.Cecil.FieldAttributes.Public | Mono.Cecil.FieldAttributes.Static, module.ImportReference(field.FieldType)));
86 foreach (var field in fields.Values) type.Fields.Add(field);
87 var sources = source.Methods.Where(method => method.Name is "ComWrite" or SerialRuntimePatch.HelperName).ToArray();
88 var methods = sources.ToDictionary(method => method.Name, method => new MethodDefinition(method.Name,
89 Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.Static, module.ImportReference(method.ReturnType)));
90 foreach (var method in methods.Values) { method.Parameters.Add(new("value", Mono.Cecil.ParameterAttributes.None, module.TypeSystem.Byte)); type.Methods.Add(method); }
91 foreach (var method in sources)
92 {
93 var copy = methods[method.Name]; copy.Body.InitLocals = method.Body.InitLocals; copy.Body.MaxStackSize = method.Body.MaxStackSize;
94 var locals = method.Body.Variables.ToDictionary(local => local, local => new VariableDefinition(module.ImportReference(local.VariableType)));
95 foreach (var local in locals.Values) copy.Body.Variables.Add(local);
96 var instructions = method.Body.Instructions.ToDictionary(instruction => instruction, instruction => Instruction.Create(OpCodes.Nop));
97 foreach (var instruction in method.Body.Instructions)
98 {
99 var target = instructions[instruction]; target.OpCode = instruction.OpCode;
100 target.Operand = instruction.Operand switch
101 {
102 Instruction branch => instructions[branch], VariableDefinition local => locals[local],
103 FieldReference field => fields[field.Name],
104 MethodReference call when methods.TryGetValue(call.Name, out var own) => own,
105 MethodReference call when call.Name == "get_UARTEnabled" => module.ImportReference(typeof(SerialIoFixture).GetProperty(nameof(SerialIoFixture.UartEnabled))!.GetMethod!),
106 MethodReference call when call.Name == "Read8" => module.ImportReference(typeof(SerialIoFixture).GetMethod(nameof(SerialIoFixture.Read8))!),
107 MethodReference call when call.Name == "Write8" => module.ImportReference(typeof(SerialIoFixture).GetMethod(nameof(SerialIoFixture.Write8))!),
108 MethodReference call => throw new InvalidOperationException("Unexpected serial fixture call: " + call.FullName),
109 var operand => operand
110 };
111 copy.Body.Instructions.Add(target);
112 }
113 }
114 return fixture;
115 }
116 private static byte[] ToBytes(AssemblyDefinition assembly) { using var stream = new MemoryStream(); assembly.Write(stream); return stream.ToArray(); }
117 private static string Il(MethodDefinition method) => !method.HasBody ? "" : string.Join("\n", method.Body.Instructions.Select(instruction => instruction.ToString()));
118 private static bool Rejects(Action action) { try { action(); return false; } catch (InvalidOperationException) { return true; } }
119 }
120
121 public static class SerialIoFixture
122 {
123 private static byte[] statuses = [0];
124 public static bool UartEnabled { get; private set; }
125 public static int Reads { get; private set; }
126 public static int Writes { get; private set; }
127 public static int InvalidPortAccesses { get; private set; }
128 public static byte LastValue { get; private set; }
129 public static void Reset(bool enabled, byte[] values)
130 {
131 UartEnabled = enabled; statuses = values; Reads = Writes = InvalidPortAccesses = 0; LastValue = 0;
132 }
133 public static byte Read8(ushort port)
134 {
135 if (port != 0x3fd) InvalidPortAccesses++;
136 byte value = statuses[Math.Min(Reads, statuses.Length - 1)]; Reads++; return value;
137 }
138 public static void Write8(ushort port, byte value)
139 {
140 if (port != 0x3f8) InvalidPortAccesses++; Writes++; LastValue = value;
141 }
142 }
Added docs/CSharpPhysicalBootDiagnostics.md +27 -0
@@ -0,0 +1,27 @@
1 # C# 实体启动诊断
2
3 实体机若停在 `[Kernel] KernelConsole initialized: … chars`,这句话本身不是错误信息。固定运行时在这之后关闭早期画面输出,然后调用 XFESystem 的 `BeforeRun`。旧镜像随后发生的自检失败只能从串口观察,不能用这一行断定具体根因。
4
5 诊断版在进入 `BeforeRun` 后重新启用已有 framebuffer 的早期文字输出,显示下列阶段;普通启动异常和自检失败也会显示最近阶段和原因。首个桌面画面呈现前关闭早期文字通路,避免后续日志覆盖桌面。该通路不调用已经退出的 UEFI 服务,也不写入磁盘。
6
7 | 阶段 | 操作 |
8 | --- | --- |
9 | B00 | 已进入 XFESystem 托管内核 |
10 | B10 | 输入与内置资源 |
11 | B20 | 托管泛型运行时 |
12 | B21 | 垃圾回收与深层栈根 |
13 | B22 | 异常处理 |
14 | B30 | 定时器、调度与线程 |
15 | B40 | 弱引用与冻结内存 |
16 | B50 | JavaScript 引擎生命周期 |
17 | B60 | 内存文件与控制台程序 |
18 | B70 | 网络;无可用网络仍可继续 |
19 | B80 | 浏览器与文档渲染 |
20 | B90 | 桌面显示表面 |
21 | B99 | 即将呈现桌面 |
22
23 如果仍无法启动,记录最后一个阶段码及 `XFE BOOT FAILED` 后的文字。仍只有原来的 `chars` 行、没有 B00 时,问题发生在新诊断入口之前,或写入的不是这份诊断镜像。硬件异常、失效的中断和运行时 failfast 可能只能留下阶段码;诊断提示不是崩溃恢复机制。
24
25 串口补丁修复固定 x64 `Serial.ComWrite` 的无限轮询:单字节最多检查 4096 次发送状态;全 1 状态或超限后禁用本次启动的串口发送。原有串口初始化和就绪时的端口写入保留,不新增硬件复位或端口探测。丢弃串口日志不应阻止启动,屏幕诊断走独立通路。这是已确认的代码缺陷修复,尚不能据此声称已定位本次实体启动失败。
26
27 验证分别覆盖补丁的实际生成 IL、正常串口 QEMU 启动,以及 QEMU 不创建 UART 设备时的桌面画面。QEMU 通过不等于该华硕实体机、USB 输入或 RTX 显示驱动已验收。