diff --git a/.github/workflows/windows-image-lock-experiment.yml b/.github/workflows/windows-image-lock-experiment.yml
index d82e4a4d..8d8f16e1 100644
--- a/.github/workflows/windows-image-lock-experiment.yml
+++ b/.github/workflows/windows-image-lock-experiment.yml
@@ -16,10 +16,20 @@ jobs:
with:
dotnet-version: '10.0.x'
- name: Publish Native AOT experiment peer
- run: dotnet publish tests/ReportWorker/ReportWorker.csproj -c Release -f net10.0 -r win-x64 -p:PublishAot=true -p:TargetFrameworks=net10.0 -o native-peer
- - name: Test held image with native peer
+ run: dotnet publish tests/ReportWorker/ReportWorker.csproj -c Release -f net10.0 -r win-x64 -p:PublishAot=true -p:TargetFrameworks=net10.0 -p:DefineConstants=WINDOWS_SNAPSHOT_LAUNCH_EXPERIMENT -o native-peer
+ - name: Inspect static native dependencies
+ shell: pwsh
+ run: |
+ $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
+ $vs = & $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
+ if (-not $vs) { throw 'Visual C++ tools were not found' }
+ $tools = Get-ChildItem (Join-Path $vs 'VC\Tools\MSVC') -Directory | Sort-Object Name -Descending | Select-Object -First 1
+ $dumpbin = Join-Path $tools.FullName 'bin\Hostx64\x64\dumpbin.exe'
+ & $dumpbin /dependents (Join-Path $PWD 'native-peer\ReportWorker.exe')
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ - name: Test sharing and restricted inheritance with native peer
shell: pwsh
run: |
$env:GU_WINDOWS_NATIVE_LOCK_PEER = Join-Path $PWD 'native-peer\ReportWorker.exe'
- dotnet test tests/CoreTest/CoreTest.csproj -c Release --filter "FullyQualifiedName~WindowsImageLockExperimentTests" --logger "console;verbosity=detailed"
+ dotnet test tests/CoreTest/CoreTest.csproj -c Release -p:DefineConstants=WINDOWS_SNAPSHOT_LAUNCH_EXPERIMENT --filter "FullyQualifiedName~WindowsImageLockExperimentTests|FullyQualifiedName~WindowsRestrictedInheritanceExperimentTests|FullyQualifiedName~WindowsDllSearchExperimentTests|FullyQualifiedName~WindowsJobLifetimeExperimentTests|FullyQualifiedName~WindowsAtomicSnapshotExperimentTests|FullyQualifiedName~WindowsImageSnapshotLeaseTests" --logger "console;verbosity=detailed"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
diff --git a/src/GeneralUpdate.Core/Security/WindowsImageSnapshotLease.cs b/src/GeneralUpdate.Core/Security/WindowsImageSnapshotLease.cs
new file mode 100644
index 00000000..69112815
--- /dev/null
+++ b/src/GeneralUpdate.Core/Security/WindowsImageSnapshotLease.cs
@@ -0,0 +1,451 @@
+// This snapshot is part of the unfinished launch experiment, not a production API.
+#if NET8_0_OR_GREATER && WINDOWS_SNAPSHOT_LAUNCH_EXPERIMENT
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.IO;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Security.AccessControl;
+using System.Security.Cryptography;
+using System.Security.Principal;
+using System.Threading;
+using Microsoft.Win32.SafeHandles;
+
+namespace GeneralUpdate.Core.Security;
+
+/// A host-authorized file to copy into a Windows execution snapshot.
+public sealed class WindowsSnapshotFile
+{
+ public WindowsSnapshotFile(string sourcePath, byte[] sha256)
+ {
+ SourcePath = sourcePath ?? throw new ArgumentNullException(nameof(sourcePath));
+ if (sha256 == null || sha256.Length != 32) throw new ArgumentException("A SHA256 digest is required.", nameof(sha256));
+ Sha256 = (byte[])sha256.Clone();
+ }
+
+ public string SourcePath { get; }
+ internal byte[] Sha256 { get; }
+}
+
+///
+/// Keeps a private, hash-verified Windows file snapshot and its ancestor handles open.
+/// This object does not launch or authenticate a process.
+///
+public sealed class WindowsImageSnapshotLease : IDisposable
+{
+ private readonly List _handles;
+ private readonly SafeFileHandle _parent;
+ private readonly SafeFileHandle _directory;
+ private readonly string _directoryName;
+ private readonly List<(string Name, SafeFileHandle Handle)> _files;
+ private int _disposed;
+
+ private WindowsImageSnapshotLease(string directory, string image, List handles,
+ SafeFileHandle parent, SafeFileHandle directoryHandle, string directoryName,
+ List<(string Name, SafeFileHandle Handle)> files)
+ {
+ DirectoryPath = directory;
+ ImagePath = image;
+ _handles = handles;
+ _parent = parent;
+ _directory = directoryHandle;
+ _directoryName = directoryName;
+ _files = files;
+ }
+
+ public string DirectoryPath { get; }
+ public string ImagePath { get; }
+
+ ///
+ /// Creates a new protected snapshot. The feature is disabled unless explicitly enabled.
+ /// The caller must separately establish a controlled launch and a trusted peer contract.
+ /// Cleanup uses relative handles and verifies object identities before deletion.
+ ///
+ public static WindowsImageSnapshotLease Create(bool enabled, string snapshotParent,
+ WindowsSnapshotFile image, IReadOnlyList dependencies,
+ CancellationToken cancellationToken = default)
+ {
+ if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("Windows is required.");
+ if (!enabled) throw new InvalidOperationException("Windows image snapshots are disabled.");
+ if (snapshotParent == null) throw new ArgumentNullException(nameof(snapshotParent));
+ if (image == null) throw new ArgumentNullException(nameof(image));
+ if (dependencies == null) throw new ArgumentNullException(nameof(dependencies));
+ return CreateWindows(snapshotParent, image, dependencies, cancellationToken);
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static WindowsImageSnapshotLease CreateWindows(string snapshotParent, WindowsSnapshotFile image,
+ IReadOnlyList dependencies, CancellationToken cancellationToken)
+ {
+ var user = WindowsIdentity.GetCurrent().User
+ ?? throw new InvalidOperationException("The current user has no SID.");
+ var parentPath = ValidatePath(snapshotParent);
+ var files = new List { image };
+ files.AddRange(dependencies);
+ var names = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (var file in files)
+ {
+ if (file == null) throw new ArgumentException("A dependency is null.", nameof(dependencies));
+ var source = ValidatePath(file.SourcePath);
+ var name = Path.GetFileName(source);
+ if (!names.Add(name)) throw new ArgumentException("Snapshot file names must be distinct.", nameof(dependencies));
+ if (ReferenceEquals(file, image))
+ {
+ if (!name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException("The image must be an executable.", nameof(image));
+ }
+ else if (!name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException("Dependencies must be DLL files.", nameof(dependencies));
+ }
+
+ var leases = new List();
+ var heldFiles = new List<(string Name, SafeFileHandle Handle)>();
+ try
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var parent = LockAncestors(parentPath, user, leases);
+ var directorySecurity = new DirectorySecurity();
+ directorySecurity.SetOwner(user);
+ directorySecurity.SetAccessRuleProtection(true, false);
+ directorySecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl,
+ InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
+ PropagationFlags.None, AccessControlType.Allow));
+ var directoryName = "gu-snapshot-" + Guid.NewGuid().ToString("N");
+ var snapshot = CreateRelative(parent, directoryName, directorySecurity, directory: true, write: true);
+ leases.Add(snapshot);
+ ValidateHandle(snapshot, user, directory: true, ancestor: false, privateSnapshot: true);
+ var directoryPath = Path.Combine(parentPath, directoryName);
+
+ foreach (var file in files)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ CopyVerifiedFile(file, snapshot, user, leases, heldFiles, cancellationToken);
+ }
+ var heldDirectory = NtOpenRelative(parent, directoryName, null, directory: true, write: false, create: false, share: 3);
+ try
+ {
+ if (!GetFileInformationByHandle(snapshot, out var created) ||
+ !GetFileInformationByHandle(heldDirectory, out var held))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ if (created.VolumeSerialNumber != held.VolumeSerialNumber ||
+ created.FileIndexHigh != held.FileIndexHigh || created.FileIndexLow != held.FileIndexLow)
+ throw new InvalidDataException("The snapshot directory changed during creation.");
+ ValidateHandle(heldDirectory, user, directory: true, ancestor: false, privateSnapshot: true);
+ leases.Add(heldDirectory);
+ }
+ catch
+ {
+ heldDirectory.Dispose();
+ throw;
+ }
+ snapshot.Dispose();
+ return new WindowsImageSnapshotLease(directoryPath, Path.Combine(directoryPath, Path.GetFileName(image.SourcePath)),
+ leases, parent, heldDirectory, directoryName, heldFiles);
+ }
+ catch
+ {
+ for (var i = leases.Count - 1; i >= 0; i--) leases[i].Dispose();
+ throw;
+ }
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static void CopyVerifiedFile(WindowsSnapshotFile file, SafeFileHandle snapshot, SecurityIdentifier user,
+ List leases, List<(string Name, SafeFileHandle Handle)> heldFiles, CancellationToken cancellationToken)
+ {
+ var path = ValidatePath(file.SourcePath);
+ var sourceLeases = new List();
+ try
+ {
+ LockAncestors(Path.GetDirectoryName(path)!, user, sourceLeases);
+ using var source = OpenPath(path, directory: false, root: false);
+ ValidateHandle(source, user, directory: false, ancestor: false);
+ var security = new FileSecurity();
+ security.SetOwner(user);
+ security.SetAccessRuleProtection(true, false);
+ security.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow));
+ var name = Path.GetFileName(path);
+ using (var destination = CreateRelative(snapshot, name, security, directory: false, write: true))
+ using (var stream = new FileStream(destination, FileAccess.ReadWrite))
+ using (var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256))
+ {
+ var buffer = new byte[81920];
+ long offset = 0;
+ int count;
+ while ((count = RandomAccess.Read(source, buffer, offset)) != 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ hash.AppendData(buffer, 0, count);
+ stream.Write(buffer, 0, count);
+ offset += count;
+ }
+ if (!CryptographicOperations.FixedTimeEquals(hash.GetHashAndReset(), file.Sha256))
+ throw new InvalidDataException("A source file does not match its authorized SHA256.");
+ stream.Flush();
+ stream.Position = 0;
+ if (!CryptographicOperations.FixedTimeEquals(SHA256.HashData(stream), file.Sha256))
+ throw new InvalidDataException("A snapshot file does not match its authorized SHA256.");
+ }
+ var held = OpenRelative(snapshot, name, directory: false);
+ try
+ {
+ ValidateHandle(held, user, directory: false, ancestor: false, privateSnapshot: true);
+ using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
+ var buffer = new byte[81920];
+ long offset = 0;
+ int count;
+ while ((count = RandomAccess.Read(held, buffer, offset)) != 0)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ hash.AppendData(buffer, 0, count);
+ offset += count;
+ }
+ if (!CryptographicOperations.FixedTimeEquals(hash.GetHashAndReset(), file.Sha256))
+ throw new InvalidDataException("The held snapshot file does not match its authorized SHA256.");
+ leases.Add(held);
+ heldFiles.Add((name, held));
+ }
+ catch
+ {
+ held.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ for (var i = sourceLeases.Count - 1; i >= 0; i--) sourceLeases[i].Dispose();
+ }
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static string ValidatePath(string path)
+ {
+ if (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path))
+ throw new ArgumentException("An absolute local path is required.", nameof(path));
+ var full = Path.GetFullPath(path);
+ var root = Path.GetPathRoot(full);
+ if (root == null || root.Length != 3 || root[1] != ':' || !string.Equals(path.TrimEnd('\\'), full.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException("A canonical local drive path is required.", nameof(path));
+ var drive = new DriveInfo(root);
+ if (drive.DriveType != DriveType.Fixed || !string.Equals(drive.DriveFormat, "NTFS", StringComparison.OrdinalIgnoreCase))
+ throw new PlatformNotSupportedException("A local fixed NTFS volume is required.");
+ foreach (var component in full.Substring(root.Length).Split('\\'))
+ if (component.Length == 0 || component.IndexOf(':') >= 0 || component.EndsWith(".", StringComparison.Ordinal) || component.EndsWith(" ", StringComparison.Ordinal))
+ throw new ArgumentException("The path contains an unsupported component.", nameof(path));
+ return full;
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static SafeFileHandle LockAncestors(string path, SecurityIdentifier user, List leases)
+ {
+ var root = Path.GetPathRoot(path)!;
+ var current = root;
+ var handle = OpenPath(current, directory: true, root: true);
+ leases.Add(handle);
+ ValidateHandle(handle, user, directory: true, ancestor: true);
+ foreach (var component in path.Substring(root.Length).Split('\\'))
+ {
+ if (component.Length == 0) continue;
+ current = Path.Combine(current, component);
+ handle = OpenPath(current, directory: true, root: false);
+ leases.Add(handle);
+ ValidateHandle(handle, user, directory: true, ancestor: true);
+ }
+ return handle;
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static SafeFileHandle OpenPath(string path, bool directory, bool root)
+ {
+ var handle = CreateFile(path, 0x80000000, root ? 7u : directory ? 3u : 1u, IntPtr.Zero, 3,
+ 0x00200000 | (directory ? 0x02000000u : 0u), IntPtr.Zero);
+ if (!handle.IsInvalid) return handle;
+ var error = Marshal.GetLastWin32Error();
+ handle.Dispose();
+ throw new Win32Exception(error, "Unable to acquire a protected file handle.");
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static void ValidateHandle(SafeFileHandle handle, SecurityIdentifier user, bool directory, bool ancestor,
+ bool privateSnapshot = false)
+ {
+ if (!GetFileInformationByHandle(handle, out var information)) throw new Win32Exception(Marshal.GetLastWin32Error());
+ if ((information.FileAttributes & 0x400) != 0 || ((information.FileAttributes & 0x10) != 0) != directory)
+ throw new InvalidDataException("A path component is a reparse point or has an unexpected type.");
+ var error = GetSecurityInfo(handle, 1, 0x1 | 0x4, out _, out _, out _, out _, out var descriptor);
+ if (error != 0) throw new Win32Exception((int)error, "Unable to read an object security descriptor.");
+ try
+ {
+ var bytes = new byte[GetSecurityDescriptorLength(descriptor)];
+ Marshal.Copy(descriptor, bytes, 0, bytes.Length);
+ var security = new RawSecurityDescriptor(bytes, 0);
+ if (security.Owner == null || !IsTrusted(security.Owner, user) ||
+ (security.ControlFlags & ControlFlags.DiscretionaryAclPresent) == 0 || security.DiscretionaryAcl == null)
+ throw new InvalidDataException("The object owner or DACL is not trusted.");
+ if (privateSnapshot && (!security.Owner.Equals(user) ||
+ (security.ControlFlags & ControlFlags.DiscretionaryAclProtected) == 0))
+ throw new InvalidDataException("The snapshot owner or DACL protection is invalid.");
+ const uint namespaceRights = 0x000d0040 | 0x50000000;
+ const uint fileWriteRights = namespaceRights | 0x00000116;
+ foreach (GenericAce ace in security.DiscretionaryAcl)
+ {
+ if ((ace.AceFlags & AceFlags.InheritOnly) != 0) continue;
+ if (ace is not CommonAce common || common.IsCallback)
+ throw new InvalidDataException("The object has an unsupported access rule.");
+ if (common.AceQualifier == AceQualifier.AccessDenied) continue;
+ if (common.AceQualifier != AceQualifier.AccessAllowed)
+ throw new InvalidDataException("The object has an unsupported access rule.");
+ if (privateSnapshot && !common.SecurityIdentifier.Equals(user))
+ throw new InvalidDataException("A snapshot access rule grants another principal access.");
+ if (!IsTrusted(common.SecurityIdentifier, user) &&
+ (unchecked((uint)common.AccessMask) & (ancestor ? namespaceRights : fileWriteRights)) != 0)
+ throw new InvalidDataException("An untrusted principal can modify the object or namespace.");
+ }
+ }
+ finally
+ {
+ LocalFree(descriptor);
+ }
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static bool IsTrusted(SecurityIdentifier sid, SecurityIdentifier user) =>
+ sid.Equals(user) || sid.IsWellKnown(WellKnownSidType.LocalSystemSid) ||
+ sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid) ||
+ sid.Value == "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
+
+ [SupportedOSPlatform("windows")]
+ private static SafeFileHandle CreateRelative(SafeFileHandle parent, string name, ObjectSecurity security, bool directory, bool write) =>
+ NtOpenRelative(parent, name, security.GetSecurityDescriptorBinaryForm(), directory, write, create: true);
+
+ [SupportedOSPlatform("windows")]
+ private static SafeFileHandle OpenRelative(SafeFileHandle parent, string name, bool directory) =>
+ NtOpenRelative(parent, name, null, directory, write: false, create: false);
+
+ private static SafeFileHandle NtOpenRelative(SafeFileHandle parent, string name, byte[]? security,
+ bool directory, bool write, bool create, uint share = 1, bool delete = false)
+ {
+ var nameBuffer = Marshal.StringToHGlobalUni(name);
+ var namePointer = Marshal.AllocHGlobal(Marshal.SizeOf());
+ var descriptor = security == null ? IntPtr.Zero : Marshal.AllocHGlobal(security.Length);
+ try
+ {
+ if (security != null) Marshal.Copy(security, 0, descriptor, security.Length);
+ var unicode = new UnicodeString
+ {
+ Length = checked((ushort)(name.Length * 2)),
+ MaximumLength = checked((ushort)((name.Length + 1) * 2)),
+ Buffer = nameBuffer
+ };
+ Marshal.StructureToPtr(unicode, namePointer, false);
+ var attributes = new ObjectAttributes
+ {
+ Length = Marshal.SizeOf(),
+ RootDirectory = parent.DangerousGetHandle(),
+ ObjectName = namePointer,
+ Attributes = 0x40,
+ SecurityDescriptor = descriptor
+ };
+ var access = delete ? 0x00110080u : directory ? (write ? 0x00120083u : 0x00120081u) : write ? 0xc0100000u : 0x80100000u;
+ var options = 0x00200020u | (directory ? 1u : 0x40u);
+ var status = NtCreateFile(out var handle, access, ref attributes, out _, IntPtr.Zero, 0x80, share,
+ create ? 2u : 1u, options, IntPtr.Zero, 0);
+ if (status == 0 && !handle.IsInvalid) return handle;
+ handle.Dispose();
+ var error = (int)RtlNtStatusToDosError(status);
+ throw new Win32Exception(error, $"Unable to create or open a snapshot object (NTSTATUS 0x{status:x8}, Win32 {error}).");
+ }
+ finally
+ {
+ if (descriptor != IntPtr.Zero) Marshal.FreeHGlobal(descriptor);
+ Marshal.FreeHGlobal(namePointer);
+ Marshal.FreeHGlobal(nameBuffer);
+ }
+ }
+
+ public void Dispose()
+ {
+ if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
+ try
+ {
+ foreach (var file in _files)
+ DeleteVerified(_directory, file.Name, file.Handle, directory: false);
+ DeleteVerified(_parent, _directoryName, _directory, directory: true);
+ }
+ finally
+ {
+ for (var i = _handles.Count - 1; i >= 0; i--) _handles[i].Dispose();
+ }
+ }
+
+ private static void DeleteVerified(SafeFileHandle parent, string name, SafeFileHandle original, bool directory)
+ {
+ using var retained = NtOpenRelative(parent, name, null, directory, write: false, create: false, share: 7);
+ RequireSameObject(original, retained);
+ original.Dispose();
+ using var deleteHandle = NtOpenRelative(parent, name, null, directory, write: false, create: false, share: 3, delete: true);
+ RequireSameObject(retained, deleteHandle);
+ var disposition = new FileDispositionInformation { DeleteFile = true };
+ var status = NtSetInformationFile(deleteHandle, out _, ref disposition, 1, 13);
+ if (status != 0)
+ {
+ var error = (int)RtlNtStatusToDosError(status);
+ throw new Win32Exception(error, $"Unable to delete the snapshot object (NTSTATUS 0x{status:x8}, Win32 {error}).");
+ }
+ }
+
+ private static void RequireSameObject(SafeFileHandle first, SafeFileHandle second)
+ {
+ if (!GetFileInformationByHandle(first, out var a) || !GetFileInformationByHandle(second, out var b))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ if (a.VolumeSerialNumber != b.VolumeSerialNumber || a.FileIndexHigh != b.FileIndexHigh || a.FileIndexLow != b.FileIndexLow)
+ throw new InvalidDataException("A snapshot object changed during cleanup.");
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct UnicodeString { public ushort Length, MaximumLength; public IntPtr Buffer; }
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ObjectAttributes
+ {
+ public int Length;
+ public IntPtr RootDirectory, ObjectName;
+ public uint Attributes;
+ public IntPtr SecurityDescriptor, SecurityQualityOfService;
+ }
+ [StructLayout(LayoutKind.Sequential)]
+ private struct IoStatusBlock { public IntPtr Status, Information; }
+ [StructLayout(LayoutKind.Sequential)]
+ private struct FileDispositionInformation { [MarshalAs(UnmanagedType.U1)] public bool DeleteFile; }
+ [StructLayout(LayoutKind.Sequential)]
+ private struct FileInformation
+ {
+ public uint FileAttributes;
+ public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime, LastAccessTime, LastWriteTime;
+ public uint VolumeSerialNumber, FileSizeHigh, FileSizeLow, NumberOfLinks, FileIndexHigh, FileIndexLow;
+ }
+
+ [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateFile(string path, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool GetFileInformationByHandle(SafeFileHandle handle, out FileInformation information);
+ [DllImport("advapi32.dll")]
+ private static extern uint GetSecurityInfo(SafeFileHandle handle, int type, uint information, out IntPtr owner,
+ out IntPtr group, out IntPtr dacl, out IntPtr sacl, out IntPtr descriptor);
+ [DllImport("advapi32.dll")]
+ private static extern uint GetSecurityDescriptorLength(IntPtr descriptor);
+ [DllImport("kernel32.dll")]
+ private static extern IntPtr LocalFree(IntPtr pointer);
+ [DllImport("ntdll.dll")]
+ private static extern int NtCreateFile(out SafeFileHandle handle, uint access, ref ObjectAttributes attributes,
+ out IoStatusBlock status, IntPtr allocationSize, uint fileAttributes, uint share, uint disposition,
+ uint options, IntPtr extendedAttributes, uint extendedAttributesLength);
+ [DllImport("ntdll.dll")]
+ private static extern int NtSetInformationFile(SafeFileHandle handle, out IoStatusBlock status,
+ ref FileDispositionInformation information, uint length, int informationClass);
+ [DllImport("ntdll.dll")]
+ private static extern uint RtlNtStatusToDosError(int status);
+}
+#endif
diff --git a/src/GeneralUpdate.Core/Security/WindowsNativeLaunchLease.cs b/src/GeneralUpdate.Core/Security/WindowsNativeLaunchLease.cs
new file mode 100644
index 00000000..813c010e
--- /dev/null
+++ b/src/GeneralUpdate.Core/Security/WindowsNativeLaunchLease.cs
@@ -0,0 +1,354 @@
+// The experiment does not yet verify the Windows system dependency closure.
+#if NET8_0_OR_GREATER && WINDOWS_SNAPSHOT_LAUNCH_EXPERIMENT
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Microsoft.Win32.SafeHandles;
+
+namespace GeneralUpdate.Core.Security;
+
+///
+/// Owns a snapshot, a process handle and a kill-on-close job. This is not peer
+/// authentication and does not provide a communication channel.
+///
+public sealed class WindowsNativeLaunchLease : IAsyncDisposable
+{
+ private static readonly HashSet Active = new();
+ private readonly SafeFileHandle _job;
+ private readonly SafeFileHandle _process;
+ private readonly WindowsImageSnapshotLease _snapshot;
+ private readonly SemaphoreSlim _disposeLock = new(1, 1);
+ private bool _disposed;
+
+ private WindowsNativeLaunchLease(SafeFileHandle job, SafeFileHandle process, WindowsImageSnapshotLease snapshot)
+ {
+ _job = job;
+ _process = process;
+ _snapshot = snapshot;
+ }
+
+ public string SnapshotDirectory => _snapshot.DirectoryPath;
+
+ ///
+ /// Returns an independently owned handle to this exact process, limited to
+ /// query and synchronization. The caller must dispose the returned handle.
+ ///
+ public SafeProcessHandle DuplicateProcessHandle()
+ {
+ _disposeLock.Wait();
+ try
+ {
+ if (_disposed) throw new ObjectDisposedException(nameof(WindowsNativeLaunchLease));
+ var current = GetCurrentProcess();
+ if (!DuplicateHandle(current, _process, current, out var duplicate, 0x00101000, false, 0))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ return duplicate;
+ }
+ finally { _disposeLock.Release(); }
+ }
+
+ ///
+ /// Starts a host-authorized, cooperative Windows Native AOT peer. The hash identifies
+ /// the peer and its trusted entry-point contract; this method does not inspect its code.
+ /// The peer must limit DLL loading to its authorized snapshot and Windows system
+ /// directories before handling sensitive input. Do not pass secrets in arguments.
+ /// No handles are inherited. The working directory and executable directory are the
+ /// snapshot, not the application installation directory.
+ ///
+ public static WindowsNativeLaunchLease Start(bool enabled, string snapshotParent,
+ WindowsSnapshotFile image, System.Collections.Generic.IReadOnlyList dependencies,
+ System.Collections.Generic.IReadOnlyList arguments, CancellationToken cancellationToken = default)
+ {
+ if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("Windows is required.");
+ if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041))
+ throw new PlatformNotSupportedException("Windows 10 version 2004 or later is required.");
+ if (arguments == null) throw new ArgumentNullException(nameof(arguments));
+ return StartWindows(enabled, snapshotParent, image, dependencies, arguments, cancellationToken);
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static WindowsNativeLaunchLease StartWindows(bool enabled, string snapshotParent,
+ WindowsSnapshotFile image, System.Collections.Generic.IReadOnlyList dependencies,
+ System.Collections.Generic.IReadOnlyList arguments, CancellationToken cancellationToken)
+ {
+ foreach (var argument in arguments)
+ if (argument == null || argument.IndexOf('\0') >= 0)
+ throw new ArgumentException("Arguments must not contain null values or NUL characters.", nameof(arguments));
+ cancellationToken.ThrowIfCancellationRequested();
+ var snapshot = WindowsImageSnapshotLease.Create(enabled, snapshotParent, image, dependencies, cancellationToken);
+ SafeFileHandle? job = null;
+ try
+ {
+ job = CreateJobObject(IntPtr.Zero, null);
+ if (job.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
+ var limits = new ExtendedLimitInformation
+ {
+ BasicLimitInformation = new BasicLimitInformation { LimitFlags = 0x2000 }
+ };
+ if (!SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf()))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ var size = IntPtr.Zero;
+ InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size);
+ if (size == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error());
+ var list = Marshal.AllocHGlobal(size);
+ var jobPointer = Marshal.AllocHGlobal(IntPtr.Size);
+ var initialized = false;
+ try
+ {
+ if (!InitializeProcThreadAttributeList(list, 1, 0, ref size))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ initialized = true;
+ Marshal.WriteIntPtr(jobPointer, job.DangerousGetHandle());
+ if (!UpdateProcThreadAttribute(list, 0, new IntPtr(0x0002000d), jobPointer,
+ new IntPtr(IntPtr.Size), IntPtr.Zero, IntPtr.Zero))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ var windows = new StringBuilder(32768);
+ var length = GetWindowsDirectory(windows, (uint)windows.Capacity);
+ if (length == 0 || length >= windows.Capacity) throw new Win32Exception(Marshal.GetLastWin32Error());
+ var system = Environment.SystemDirectory;
+ if (string.IsNullOrEmpty(system) || !Path.IsPathFullyQualified(system))
+ throw new InvalidOperationException("The Windows system directory is unavailable.");
+ var environment = "PATH=" + system + "\0SystemRoot=" + windows + "\0WINDIR=" + windows + "\0\0";
+ var environmentPointer = Marshal.StringToHGlobalUni(environment);
+ try
+ {
+ var command = new StringBuilder(Quote(snapshot.ImagePath));
+ foreach (var argument in arguments) command.Append(' ').Append(Quote(argument));
+ var startup = new StartupInfoEx
+ {
+ StartupInfo = new StartupInfo { Size = Marshal.SizeOf() },
+ AttributeList = list
+ };
+ cancellationToken.ThrowIfCancellationRequested();
+ if (!CreateProcess(snapshot.ImagePath, command, IntPtr.Zero, IntPtr.Zero, false,
+ 0x00080000 | 0x08000000 | 0x00000004 | 0x00000400, environmentPointer,
+ snapshot.DirectoryPath, ref startup, out var process))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ var resumed = false;
+ WindowsNativeLaunchLease? result = null;
+ using var thread = new SafeFileHandle(process.Thread, true);
+ var processHandle = new SafeFileHandle(process.Process, true);
+ try
+ {
+ if (!IsProcessInJob(processHandle, job, out var assigned))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ if (!assigned) throw new InvalidOperationException("The created process is not in the job.");
+ cancellationToken.ThrowIfCancellationRequested();
+ result = new WindowsNativeLaunchLease(job, processHandle, snapshot);
+ lock (Active) Active.Add(result);
+ if (ResumeThread(thread) == uint.MaxValue)
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ resumed = true;
+ job = null;
+ return result;
+ }
+ finally
+ {
+ if (!resumed)
+ {
+ if (result != null)
+ lock (Active) Active.Remove(result);
+ if (!TerminateProcess(processHandle, 1))
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to terminate the suspended process.");
+ if (WaitForSingleObject(processHandle, uint.MaxValue) != 0)
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to wait for the suspended process.");
+ processHandle.Dispose();
+ }
+ }
+ }
+ finally { Marshal.FreeHGlobal(environmentPointer); }
+ }
+ finally
+ {
+ if (initialized) DeleteProcThreadAttributeList(list);
+ Marshal.FreeHGlobal(jobPointer);
+ Marshal.FreeHGlobal(list);
+ }
+ }
+ catch
+ {
+ job?.Dispose();
+ snapshot.Dispose();
+ throw;
+ }
+ }
+
+ private static string Quote(string value)
+ {
+ var result = new StringBuilder("\"");
+ var slashes = 0;
+ foreach (var c in value)
+ {
+ if (c == '\\') { slashes++; continue; }
+ if (c == '"') result.Append('\\', slashes * 2 + 1);
+ else result.Append('\\', slashes);
+ result.Append(c);
+ slashes = 0;
+ }
+ result.Append('\\', slashes * 2).Append('"');
+ return result.ToString();
+ }
+
+ /// Waits for the owned process. Cancellation stops the job and releases the lease.
+ public async Task WaitForExitAsync(CancellationToken cancellationToken = default)
+ {
+ try
+ {
+ while (true)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ await _disposeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ if (_disposed) throw new ObjectDisposedException(nameof(WindowsNativeLaunchLease));
+ var wait = WaitForSingleObject(_process, 0);
+ if (wait == 0)
+ {
+ if (!GetExitCodeProcess(_process, out var code)) throw new Win32Exception(Marshal.GetLastWin32Error());
+ return code;
+ }
+ if (wait != 258) throw new Win32Exception(Marshal.GetLastWin32Error());
+ }
+ finally { _disposeLock.Release(); }
+ await Task.Delay(100, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ await DisposeAsync().ConfigureAwait(false);
+ throw;
+ }
+ }
+
+ /// Closes the job, waits for the process to exit, and releases snapshot handles.
+ public async ValueTask DisposeAsync()
+ {
+ await _disposeLock.WaitAsync().ConfigureAwait(false);
+ try
+ {
+ if (_disposed) return;
+ if (!TerminateJobObject(_job, 1))
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to terminate the owned job.");
+ var result = await Task.Run(() =>
+ {
+ var wait = WaitForSingleObject(_process, uint.MaxValue);
+ return (Wait: wait, Error: wait == 0 ? 0 : Marshal.GetLastWin32Error());
+ }).ConfigureAwait(false);
+ if (result.Wait != 0) throw new Win32Exception(result.Error, "Unable to wait for the terminated process.");
+ while (true)
+ {
+ if (!QueryInformationJobObject(_job, 1, out var accounting,
+ (uint)Marshal.SizeOf(), IntPtr.Zero))
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to inspect the owned job.");
+ if (accounting.ActiveProcesses == 0) break;
+ await Task.Delay(50).ConfigureAwait(false);
+ }
+ _job.Dispose();
+ _process.Dispose();
+ try { _snapshot.Dispose(); }
+ finally
+ {
+ _disposed = true;
+ lock (Active) Active.Remove(this);
+ }
+ }
+ finally { _disposeLock.Release(); }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct BasicLimitInformation
+ {
+ public long PerProcessUserTimeLimit, PerJobUserTimeLimit;
+ public uint LimitFlags;
+ public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize;
+ public uint ActiveProcessLimit;
+ public UIntPtr Affinity;
+ public uint PriorityClass, SchedulingClass;
+ }
+ [StructLayout(LayoutKind.Sequential)]
+ private struct IoCounters
+ {
+ public ulong ReadOperationCount, WriteOperationCount, OtherOperationCount;
+ public ulong ReadTransferCount, WriteTransferCount, OtherTransferCount;
+ }
+ [StructLayout(LayoutKind.Sequential)]
+ private struct BasicAccountingInformation
+ {
+ public long TotalUserTime, TotalKernelTime, ThisPeriodTotalUserTime, ThisPeriodTotalKernelTime;
+ public uint TotalPageFaultCount, TotalProcesses, ActiveProcesses, TotalTerminatedProcesses;
+ }
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ExtendedLimitInformation
+ {
+ public BasicLimitInformation BasicLimitInformation;
+ public IoCounters IoInfo;
+ public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed;
+ }
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct StartupInfo
+ {
+ public int Size;
+ public string? Reserved, Desktop, Title;
+ public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;
+ public short ShowWindow, Reserved2;
+ public IntPtr ReservedPointer, StandardInput, StandardOutput, StandardError;
+ }
+ [StructLayout(LayoutKind.Sequential)]
+ private struct StartupInfoEx { public StartupInfo StartupInfo; public IntPtr AttributeList; }
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ProcessInformation { public IntPtr Process, Thread; public int ProcessId, ThreadId; }
+
+ [DllImport("kernel32.dll", EntryPoint = "CreateJobObjectW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateJobObject(IntPtr attributes, string? name);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool SetInformationJobObject(SafeFileHandle job, int informationClass, ref ExtendedLimitInformation information, uint length);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool TerminateJobObject(SafeFileHandle job, uint exitCode);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool QueryInformationJobObject(SafeFileHandle job, int informationClass,
+ out BasicAccountingInformation information, uint length, IntPtr returnLength);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool InitializeProcThreadAttributeList(IntPtr list, int count, int flags, ref IntPtr size);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool UpdateProcThreadAttribute(IntPtr list, int flags, IntPtr attribute, IntPtr value, IntPtr size, IntPtr previousValue, IntPtr returnSize);
+ [DllImport("kernel32.dll")]
+ private static extern void DeleteProcThreadAttributeList(IntPtr list);
+ [DllImport("kernel32.dll", EntryPoint = "GetWindowsDirectoryW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern uint GetWindowsDirectory(StringBuilder buffer, uint size);
+ [DllImport("kernel32.dll", EntryPoint = "CreateProcessW", CharSet = CharSet.Unicode, SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool CreateProcess(string application, StringBuilder command, IntPtr processAttributes,
+ IntPtr threadAttributes, [MarshalAs(UnmanagedType.Bool)] bool inheritHandles, uint flags, IntPtr environment,
+ string currentDirectory, ref StartupInfoEx startup, out ProcessInformation process);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool IsProcessInJob(SafeFileHandle process, SafeFileHandle job, [MarshalAs(UnmanagedType.Bool)] out bool result);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern uint ResumeThread(SafeFileHandle thread);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool TerminateProcess(SafeFileHandle process, uint exitCode);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern uint WaitForSingleObject(SafeFileHandle handle, uint milliseconds);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool GetExitCodeProcess(SafeFileHandle process, out uint exitCode);
+ [DllImport("kernel32.dll")]
+ private static extern IntPtr GetCurrentProcess();
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool DuplicateHandle(IntPtr sourceProcess, SafeFileHandle source, IntPtr targetProcess,
+ out SafeProcessHandle target, uint access, [MarshalAs(UnmanagedType.Bool)] bool inherit, uint options);
+}
+#endif
diff --git a/tests/CoreTest/Ipc/WindowsAtomicSnapshotExperimentTests.cs b/tests/CoreTest/Ipc/WindowsAtomicSnapshotExperimentTests.cs
new file mode 100644
index 00000000..d22fb34a
--- /dev/null
+++ b/tests/CoreTest/Ipc/WindowsAtomicSnapshotExperimentTests.cs
@@ -0,0 +1,126 @@
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Security.AccessControl;
+using System.Security.Principal;
+using Microsoft.Win32.SafeHandles;
+
+namespace CoreTest.Ipc;
+
+/// Exercises atomic private-directory creation, not a protected updater launcher.
+public sealed class WindowsAtomicSnapshotExperimentTests
+{
+ [Fact]
+ public void AtomicCreateReturnsLockedPrivateObjectAndRejectsExistingName()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ RunExperiment();
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static void RunExperiment()
+ {
+ var root = Path.Combine(Path.GetTempPath(), "gu-atomic-directory-" + Guid.NewGuid().ToString("N"));
+ var identity = WindowsIdentity.GetCurrent().User
+ ?? throw new InvalidOperationException("The current user has no SID.");
+ var security = new DirectorySecurity();
+ security.SetOwner(identity);
+ security.SetAccessRuleProtection(true, false);
+ security.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl,
+ InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
+ PropagationFlags.None, AccessControlType.Allow));
+ new DirectoryInfo(root).Create(security);
+ try
+ {
+ using var parent = CreateFile(root, 0x80000000, 1, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero);
+ if (parent.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
+ using var snapshot = CreateDirectoryRelative(parent, "snapshot", security, out var result, out var information);
+ Assert.Equal(0, result);
+ Assert.Equal(2, information.ToInt64());
+ Assert.False(snapshot.IsInvalid);
+ var path = Path.Combine(root, "snapshot");
+ var actual = new DirectoryInfo(path).GetAccessControl();
+ Assert.True(actual.AreAccessRulesProtected);
+ Assert.Equal(identity, actual.GetOwner(typeof(SecurityIdentifier)));
+ Assert.All(actual.GetAccessRules(true, true, typeof(SecurityIdentifier)).Cast(),
+ rule => Assert.Equal(identity, rule.IdentityReference));
+ Assert.Throws(() => Directory.Move(path, path + ".moved"));
+ using var collision = CreateDirectoryRelative(parent, "snapshot", security, out var collisionResult, out _);
+ Assert.Equal(unchecked((int)0xc0000035), collisionResult);
+ }
+ finally
+ {
+ if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
+ }
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static SafeFileHandle CreateDirectoryRelative(SafeFileHandle parent, string name, DirectorySecurity security,
+ out int result, out IntPtr information)
+ {
+ var nameBuffer = Marshal.StringToHGlobalUni(name);
+ var namePointer = Marshal.AllocHGlobal(Marshal.SizeOf());
+ var descriptorBytes = security.GetSecurityDescriptorBinaryForm();
+ var descriptor = Marshal.AllocHGlobal(descriptorBytes.Length);
+ try
+ {
+ Marshal.Copy(descriptorBytes, 0, descriptor, descriptorBytes.Length);
+ var unicode = new UnicodeString
+ {
+ Length = checked((ushort)(name.Length * 2)),
+ MaximumLength = checked((ushort)((name.Length + 1) * 2)),
+ Buffer = nameBuffer
+ };
+ Marshal.StructureToPtr(unicode, namePointer, false);
+ var attributes = new ObjectAttributes
+ {
+ Length = Marshal.SizeOf(),
+ RootDirectory = parent.DangerousGetHandle(),
+ ObjectName = namePointer,
+ Attributes = 0x40,
+ SecurityDescriptor = descriptor
+ };
+ result = NtCreateFile(out var handle, 0x00120081, ref attributes, out var status,
+ IntPtr.Zero, 0x80, 1, 2, 0x00200021, IntPtr.Zero, 0);
+ information = status.Information;
+ return handle;
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(descriptor);
+ Marshal.FreeHGlobal(namePointer);
+ Marshal.FreeHGlobal(nameBuffer);
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct UnicodeString
+ {
+ public ushort Length, MaximumLength;
+ public IntPtr Buffer;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ObjectAttributes
+ {
+ public int Length;
+ public IntPtr RootDirectory, ObjectName;
+ public uint Attributes;
+ public IntPtr SecurityDescriptor, SecurityQualityOfService;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct IoStatusBlock
+ {
+ public IntPtr Status, Information;
+ }
+
+ [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateFile(string path, uint access, uint share, IntPtr security,
+ uint creation, uint flags, IntPtr template);
+
+ [DllImport("ntdll.dll")]
+ private static extern int NtCreateFile(out SafeFileHandle handle, uint access, ref ObjectAttributes attributes,
+ out IoStatusBlock status, IntPtr allocationSize, uint fileAttributes, uint share, uint disposition,
+ uint options, IntPtr extendedAttributes, uint extendedAttributesLength);
+}
diff --git a/tests/CoreTest/Ipc/WindowsDllSearchExperimentTests.cs b/tests/CoreTest/Ipc/WindowsDllSearchExperimentTests.cs
new file mode 100644
index 00000000..b3c11ce7
--- /dev/null
+++ b/tests/CoreTest/Ipc/WindowsDllSearchExperimentTests.cs
@@ -0,0 +1,131 @@
+using System.Diagnostics;
+using System.Runtime.Versioning;
+
+namespace CoreTest.Ipc;
+
+/// Demonstrates loader search behavior, not a protected updater launcher.
+public sealed class WindowsDllSearchExperimentTests
+{
+ [Fact]
+ public async Task SanitizedPathDoesNotRestrictExplicitDllPaths()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ await RunExperiment();
+ }
+
+ [Fact]
+ public async Task NativeAotSqliteUsesAdjacentDependencyAndFailsWhenItIsMissing()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ var executable = Environment.GetEnvironmentVariable("GU_WINDOWS_NATIVE_LOCK_PEER");
+ if (executable == null) return;
+ await RunSqliteExperiment(executable);
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static async Task RunSqliteExperiment(string executable)
+ {
+ var root = Path.Combine(Path.GetTempPath(), "gu-sqlite-search-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(root);
+ try
+ {
+ var adjacent = await RunSqlitePeer(executable, root);
+ Assert.True(adjacent.ExitCode == 0, adjacent.Error);
+ Assert.Equal(Path.Combine(Path.GetDirectoryName(executable)!, "e_sqlite3.dll"),
+ adjacent.Output.Trim(), ignoreCase: true);
+
+ var isolated = Path.Combine(root, "peer.exe");
+ File.Copy(executable, isolated);
+ var missing = await RunSqlitePeer(isolated, root);
+ Assert.NotEqual(0, missing.ExitCode);
+ Assert.Contains("e_sqlite3", missing.Error + missing.Output, StringComparison.OrdinalIgnoreCase);
+ }
+ finally
+ {
+ Directory.Delete(root, recursive: true);
+ }
+ }
+
+ private static async Task<(int ExitCode, string Output, string Error)> RunSqlitePeer(string executable, string directory)
+ {
+ var start = new ProcessStartInfo(executable)
+ {
+ UseShellExecute = false,
+ WorkingDirectory = directory,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ CreateNoWindow = true
+ };
+ start.Environment["PATH"] = Environment.SystemDirectory;
+ start.ArgumentList.Add("--sqlite-module-probe");
+ using var peer = Process.Start(start) ?? throw new InvalidOperationException("SQLite probe did not start.");
+ var output = peer.StandardOutput.ReadToEndAsync();
+ var error = peer.StandardError.ReadToEndAsync();
+ try
+ {
+ await peer.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30));
+ return (peer.ExitCode, await output, await error);
+ }
+ finally
+ {
+ if (!peer.HasExited) peer.Kill(entireProcessTree: true);
+ await peer.WaitForExitAsync();
+ }
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static async Task RunExperiment()
+ {
+ var root = Path.Combine(Path.GetTempPath(), "gu-dll-search-" + Guid.NewGuid().ToString("N"));
+ var injection = Path.Combine(root, "injection");
+ var workingDirectory = Path.Combine(root, "working");
+ Directory.CreateDirectory(injection);
+ Directory.CreateDirectory(workingDirectory);
+ try
+ {
+ var source = Path.Combine(AppContext.BaseDirectory, "runtimes", "win-x64", "native", "e_sqlite3.dll");
+ var name = "gu_probe_" + Guid.NewGuid().ToString("N") + ".dll";
+ var candidate = Path.Combine(injection, name);
+ File.Copy(source, candidate);
+ var executable = Environment.GetEnvironmentVariable("GU_WINDOWS_NATIVE_LOCK_PEER")
+ ?? Path.Combine(AppContext.BaseDirectory, "ReportWorker.exe");
+
+ Assert.Equal("loaded", await RunPeer(executable, workingDirectory, injection, name));
+ Assert.Equal("error:126", await RunPeer(executable, workingDirectory, Environment.SystemDirectory, name));
+ Assert.Equal("loaded", await RunPeer(executable, workingDirectory, Environment.SystemDirectory, candidate));
+ }
+ finally
+ {
+ Directory.Delete(root, recursive: true);
+ }
+ }
+
+ private static async Task RunPeer(string executable, string workingDirectory, string path, string dll)
+ {
+ var start = new ProcessStartInfo(executable)
+ {
+ UseShellExecute = false,
+ WorkingDirectory = workingDirectory,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ CreateNoWindow = true
+ };
+ start.Environment["PATH"] = path;
+ start.ArgumentList.Add("--dll-search-probe");
+ start.ArgumentList.Add(dll);
+ using var peer = Process.Start(start) ?? throw new InvalidOperationException("DLL search probe did not start.");
+ var output = peer.StandardOutput.ReadToEndAsync();
+ var error = peer.StandardError.ReadToEndAsync();
+ try
+ {
+ await peer.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30));
+ Assert.True(peer.ExitCode == 0, await error);
+ return (await output).Trim();
+ }
+ finally
+ {
+ if (!peer.HasExited) peer.Kill(entireProcessTree: true);
+ await peer.WaitForExitAsync();
+ }
+ }
+}
diff --git a/tests/CoreTest/Ipc/WindowsImageLockExperimentTests.cs b/tests/CoreTest/Ipc/WindowsImageLockExperimentTests.cs
index 946ab56a..bd3202c5 100644
--- a/tests/CoreTest/Ipc/WindowsImageLockExperimentTests.cs
+++ b/tests/CoreTest/Ipc/WindowsImageLockExperimentTests.cs
@@ -26,6 +26,226 @@ public async Task HeldImageAndPrivateDirectoryRejectConcurrentDeployment()
await RunWindowsExperiment();
}
+ [Fact]
+ public async Task DirectorySharingDoesNotFreezeAclOrContents()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ await RunDirectorySharingCounterexample();
+ }
+
+ [Theory]
+ [InlineData(2u)]
+ [InlineData(65536u)]
+ public async Task PreviouslyOpenedWriteOrDeleteHandlePreventsImageLease(uint access)
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ await RunExistingHandleExperiment(access);
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static async Task RunExistingHandleExperiment(uint access)
+ {
+ var root = Path.Combine(Path.GetTempPath(), "gu-existing-handle-" + Guid.NewGuid().ToString("N"));
+ var identity = WindowsIdentity.GetCurrent().User
+ ?? throw new InvalidOperationException("The current user has no SID.");
+ var security = new DirectorySecurity();
+ security.SetOwner(identity);
+ security.SetAccessRuleProtection(true, false);
+ security.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl,
+ InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
+ PropagationFlags.None, AccessControlType.Allow));
+ new DirectoryInfo(root).Create(security);
+
+ try
+ {
+ var file = Path.Combine(root, "image.bin");
+ File.WriteAllText(file, "probe");
+ var script = """
+ $ErrorActionPreference = 'Stop'
+ Add-Type @'
+ using System;
+ using System.Runtime.InteropServices;
+ using Microsoft.Win32.SafeHandles;
+ public static class ExistingHandleProbe {
+ [DllImport("kernel32.dll", EntryPoint="CreateFileW", CharSet=CharSet.Unicode, SetLastError=true)]
+ public static extern SafeFileHandle Open(string path, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
+ }
+ '@
+ $handle = [ExistingHandleProbe]::Open($args[0], [uint32]$args[1], 7, [IntPtr]::Zero, 3, 0x80, [IntPtr]::Zero)
+ if ($handle.IsInvalid) { throw "Open failed: $([Runtime.InteropServices.Marshal]::GetLastWin32Error())" }
+ try {
+ [Console]::WriteLine('ready')
+ [Console]::Out.Flush()
+ if ([Console]::ReadLine() -ne 'close') { throw 'Unexpected input' }
+ } finally { $handle.Dispose() }
+ """;
+ var encoded = Convert.ToBase64String(Encoding.Unicode.GetBytes(
+ "& { " + script + " } '" + file.Replace("'", "''") + "' '" + access + "'"));
+ var start = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"))
+ {
+ UseShellExecute = false,
+ RedirectStandardInput = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ CreateNoWindow = true
+ };
+ start.ArgumentList.Add("-NoProfile");
+ start.ArgumentList.Add("-NonInteractive");
+ start.ArgumentList.Add("-EncodedCommand");
+ start.ArgumentList.Add(encoded);
+ using var worker = Process.Start(start) ?? throw new InvalidOperationException("Sharing probe did not start.");
+ var errors = worker.StandardError.ReadToEndAsync();
+ try
+ {
+ Assert.Equal("ready", await worker.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(30)));
+ var exception = Assert.Throws(() => OpenLocked(file, directory: false));
+ Assert.Equal(32, exception.NativeErrorCode);
+ await worker.StandardInput.WriteLineAsync("close");
+ await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30));
+ Assert.True(worker.ExitCode == 0, await errors);
+ using var lease = OpenLocked(file, directory: false);
+ }
+ finally
+ {
+ if (!worker.HasExited) worker.Kill(entireProcessTree: true);
+ await worker.WaitForExitAsync();
+ }
+ }
+ finally
+ {
+ if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
+ }
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static async Task RunDirectorySharingCounterexample()
+ {
+ var root = Path.Combine(Path.GetTempPath(), "gu-directory-sharing-" + Guid.NewGuid().ToString("N"));
+ var identity = WindowsIdentity.GetCurrent().User
+ ?? throw new InvalidOperationException("The current user has no SID.");
+ var security = new DirectorySecurity();
+ security.SetOwner(identity);
+ security.SetAccessRuleProtection(true, false);
+ security.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl,
+ InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
+ PropagationFlags.None, AccessControlType.Allow));
+ new DirectoryInfo(root).Create(security);
+
+ try
+ {
+ var directory = Path.Combine(root, "image");
+ new DirectoryInfo(directory).Create(security);
+ var snapshot = Path.Combine(directory, "snapshot");
+ new DirectoryInfo(snapshot).Create(security);
+ var inheritedControl = Path.Combine(directory, "inherited");
+ Directory.CreateDirectory(inheritedControl);
+ var snapshotFile = Path.Combine(snapshot, "image.bin");
+ File.WriteAllText(snapshotFile, "probe");
+ var fileSecurity = new FileSecurity();
+ fileSecurity.SetOwner(identity);
+ fileSecurity.SetAccessRuleProtection(true, false);
+ fileSecurity.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl, AccessControlType.Allow));
+ new FileInfo(snapshotFile).SetAccessControl(fileSecurity);
+ var before = new DirectoryInfo(directory).GetAccessControl().GetSecurityDescriptorSddlForm(
+ AccessControlSections.Access);
+ var snapshotBefore = new DirectoryInfo(snapshot).GetAccessControl().GetSecurityDescriptorSddlForm(
+ AccessControlSections.Access);
+ var fileBefore = new FileInfo(snapshotFile).GetAccessControl().GetSecurityDescriptorSddlForm(
+ AccessControlSections.Access);
+ var script = """
+ $ErrorActionPreference = 'Stop'
+ Add-Type @'
+ using System;
+ using System.Runtime.InteropServices;
+ using Microsoft.Win32.SafeHandles;
+ public static class DirectorySharingProbe {
+ [DllImport("kernel32.dll", EntryPoint="CreateFileW", CharSet=CharSet.Unicode, SetLastError=true)]
+ public static extern SafeFileHandle Open(string path, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
+ [DllImport("advapi32.dll", EntryPoint="ConvertStringSecurityDescriptorToSecurityDescriptorW", CharSet=CharSet.Unicode, SetLastError=true)]
+ public static extern bool Convert(string sddl, uint revision, out IntPtr descriptor, out uint size);
+ [DllImport("advapi32.dll", SetLastError=true)]
+ public static extern bool GetSecurityDescriptorDacl(IntPtr descriptor, out bool present, out IntPtr dacl, out bool defaulted);
+ [DllImport("advapi32.dll")]
+ public static extern uint SetSecurityInfo(SafeFileHandle handle, int type, uint information, IntPtr owner, IntPtr group, IntPtr dacl, IntPtr sacl);
+ [DllImport("kernel32.dll")]
+ public static extern IntPtr LocalFree(IntPtr pointer);
+ }
+ '@
+ $handle = [DirectorySharingProbe]::Open($args[0], 393216, 7, [IntPtr]::Zero, 3, 0x02000000, [IntPtr]::Zero)
+ if ($handle.IsInvalid) { throw "WRITE_DAC open failed: $([Runtime.InteropServices.Marshal]::GetLastWin32Error())" }
+ $descriptor = [IntPtr]::Zero
+ $size = [uint32]0
+ try {
+ $sddl = 'D:P(A;OICI;FA;;;' + $args[1] + ')(A;OICI;FR;;;BU)'
+ if (-not [DirectorySharingProbe]::Convert($sddl, 1, [ref]$descriptor, [ref]$size)) {
+ throw "Security descriptor conversion failed: $([Runtime.InteropServices.Marshal]::GetLastWin32Error())"
+ }
+ $present = $false
+ $defaulted = $false
+ $dacl = [IntPtr]::Zero
+ if (-not [DirectorySharingProbe]::GetSecurityDescriptorDacl($descriptor, [ref]$present, [ref]$dacl, [ref]$defaulted)) {
+ throw "GetSecurityDescriptorDacl failed: $([Runtime.InteropServices.Marshal]::GetLastWin32Error())"
+ }
+ [Console]::WriteLine('ready')
+ [Console]::Out.Flush()
+ if ([Console]::ReadLine() -ne 'continue') { throw 'Unexpected input' }
+ $status = [DirectorySharingProbe]::SetSecurityInfo($handle, 1, 4, [IntPtr]::Zero, [IntPtr]::Zero, $dacl, [IntPtr]::Zero)
+ if ($status -ne 0) { throw "SetSecurityInfo failed: $status" }
+ [IO.File]::WriteAllText([IO.Path]::Combine($args[0], 'created.txt'), 'probe')
+ [Console]::WriteLine('changed-and-created')
+ } finally {
+ if ($descriptor -ne [IntPtr]::Zero) { [void][DirectorySharingProbe]::LocalFree($descriptor) }
+ $handle.Dispose()
+ }
+ """;
+ var encoded = Convert.ToBase64String(Encoding.Unicode.GetBytes(
+ "& { " + script + " } '" + directory.Replace("'", "''") + "' '" + identity.Value + "'"));
+ var start = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe"))
+ {
+ UseShellExecute = false,
+ RedirectStandardInput = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ CreateNoWindow = true
+ };
+ start.ArgumentList.Add("-NoProfile");
+ start.ArgumentList.Add("-NonInteractive");
+ start.ArgumentList.Add("-EncodedCommand");
+ start.ArgumentList.Add(encoded);
+ using var worker = Process.Start(start) ?? throw new InvalidOperationException("Sharing probe did not start.");
+ var errors = worker.StandardError.ReadToEndAsync();
+ try
+ {
+ Assert.Equal("ready", await worker.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(30)));
+ using var lease = OpenLocked(directory, directory: true);
+ await worker.StandardInput.WriteLineAsync("continue");
+ Assert.Equal("changed-and-created", await worker.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(30)));
+ await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30));
+ Assert.True(worker.ExitCode == 0, await errors);
+ var after = new DirectoryInfo(directory).GetAccessControl().GetSecurityDescriptorSddlForm(
+ AccessControlSections.Access);
+ Assert.NotEqual(before, after);
+ Assert.True(File.Exists(Path.Combine(directory, "created.txt")));
+ Assert.Equal(snapshotBefore, new DirectoryInfo(snapshot).GetAccessControl().GetSecurityDescriptorSddlForm(
+ AccessControlSections.Access));
+ Assert.Equal(fileBefore, new FileInfo(snapshotFile).GetAccessControl().GetSecurityDescriptorSddlForm(
+ AccessControlSections.Access));
+ Assert.Contains(new DirectoryInfo(inheritedControl).GetAccessControl()
+ .GetAccessRules(true, true, typeof(SecurityIdentifier)).Cast(),
+ rule => rule.IdentityReference.Equals(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null)));
+ }
+ finally
+ {
+ if (!worker.HasExited) worker.Kill(entireProcessTree: true);
+ await worker.WaitForExitAsync();
+ }
+ }
+ finally
+ {
+ if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
+ }
+ }
+
[SupportedOSPlatform("windows")]
private async Task RunWindowsExperiment()
{
diff --git a/tests/CoreTest/Ipc/WindowsImageSnapshotLeaseTests.cs b/tests/CoreTest/Ipc/WindowsImageSnapshotLeaseTests.cs
new file mode 100644
index 00000000..f42c735d
--- /dev/null
+++ b/tests/CoreTest/Ipc/WindowsImageSnapshotLeaseTests.cs
@@ -0,0 +1,334 @@
+#if WINDOWS_SNAPSHOT_LAUNCH_EXPERIMENT
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Security.AccessControl;
+using System.Security.Cryptography;
+using System.Security.Principal;
+using GeneralUpdate.Core.Security;
+using Microsoft.Win32.SafeHandles;
+
+namespace CoreTest.Ipc;
+
+public sealed class WindowsImageSnapshotLeaseTests
+{
+ [Fact]
+ public void DisabledProfileIsRejected()
+ {
+ var image = new WindowsSnapshotFile("unused.exe", new byte[32]);
+ if (OperatingSystem.IsWindows())
+ Assert.Throws(() => WindowsImageSnapshotLease.Create(false, "unused", image, Array.Empty()));
+ else
+ Assert.Throws(() => WindowsImageSnapshotLease.Create(false, "unused", image, Array.Empty()));
+ }
+
+ [Fact]
+ public void VerifiedSnapshotHoldsImageAndDirectory()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ using var fixture = new Fixture();
+ using var lease = fixture.Create();
+ Assert.Equal(File.ReadAllBytes(fixture.Image), File.ReadAllBytes(lease.ImagePath));
+ Assert.Equal(File.ReadAllBytes(fixture.Dependency), File.ReadAllBytes(Path.Combine(lease.DirectoryPath, "native.dll")));
+ var security = new DirectoryInfo(lease.DirectoryPath).GetAccessControl();
+ Assert.True(security.AreAccessRulesProtected);
+ Assert.Equal(WindowsIdentity.GetCurrent().User, security.GetOwner(typeof(SecurityIdentifier)));
+ var write = Assert.Throws(() => File.WriteAllText(lease.ImagePath, "changed"));
+ Assert.Equal(32, write.HResult & 0xffff);
+ var move = Assert.Throws(() => Directory.Move(lease.DirectoryPath, lease.DirectoryPath + ".moved"));
+ Assert.Equal(32, move.HResult & 0xffff);
+ }
+
+ [Fact]
+ public void DisposalDeletesTheHeldSnapshot()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ using var fixture = new Fixture();
+ var lease = fixture.Create();
+ var path = lease.DirectoryPath;
+ lease.Dispose();
+ Assert.False(Directory.Exists(path));
+ lease.Dispose();
+ }
+
+ [Fact]
+ public void DeploymentCanReplaceSourceWhileSnapshotRemainsFixed()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ using var fixture = new Fixture();
+ using var lease = fixture.Create();
+ var replacement = fixture.Image + ".new";
+ File.WriteAllText(replacement, "new deployment");
+ File.Move(replacement, fixture.Image, overwrite: true);
+ Assert.Equal("new deployment", File.ReadAllText(fixture.Image));
+ Assert.Equal("image bytes", File.ReadAllText(lease.ImagePath));
+ }
+
+ [Fact]
+ public void UnexpectedChildIsNotRecursivelyDeleted()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ using var fixture = new Fixture();
+ var lease = fixture.Create();
+ var path = Path.Combine(lease.DirectoryPath, "unexpected.txt");
+ File.WriteAllText(path, "preserve");
+ var failure = Assert.Throws(() => lease.Dispose());
+ Assert.Equal(145, failure.NativeErrorCode);
+ Assert.Equal("preserve", File.ReadAllText(path));
+ }
+
+ [Fact]
+ public void HashMismatchAndExistingWriteHandleAreRejected()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ using var fixture = new Fixture();
+ var bad = new WindowsSnapshotFile(fixture.Image, new byte[32]);
+ Assert.Throws(() => WindowsImageSnapshotLease.Create(true, fixture.Staging, bad, Array.Empty()));
+ var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image)));
+ using var existing = new FileStream(fixture.Image, FileMode.Open, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete);
+ var failure = Assert.Throws(() =>
+ WindowsImageSnapshotLease.Create(true, fixture.Staging, image, Array.Empty()));
+ Assert.Equal(32, failure.NativeErrorCode);
+ }
+
+ [Fact]
+ public void UntrustedWriteRuleIsRejected()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ using var fixture = new Fixture();
+ var security = new FileInfo(fixture.Image).GetAccessControl();
+ security.AddAccessRule(new FileSystemAccessRule(
+ new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
+ FileSystemRights.WriteData, AccessControlType.Allow));
+ new FileInfo(fixture.Image).SetAccessControl(security);
+ Assert.Throws(() => fixture.Create());
+ }
+
+ [Fact]
+ public void ExistingDeleteHandleAndAncestorJunctionAreRejected()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ using var fixture = new Fixture();
+ var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image)));
+ using (var handle = CreateFile(fixture.Image, 0x00010000, 7, IntPtr.Zero, 3, 0x80, IntPtr.Zero))
+ {
+ if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
+ var failure = Assert.Throws(() =>
+ WindowsImageSnapshotLease.Create(true, fixture.Staging, image, Array.Empty()));
+ Assert.Equal(32, failure.NativeErrorCode);
+ }
+ var junction = Path.Combine(fixture.Root, "junction");
+ var start = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "cmd.exe"))
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true
+ };
+ foreach (var argument in new[] { "/c", "mklink", "/J", junction, fixture.Root })
+ start.ArgumentList.Add(argument);
+ using var command = Process.Start(start) ?? throw new InvalidOperationException("Could not start mklink.");
+ var output = command.StandardOutput.ReadToEnd();
+ var error = command.StandardError.ReadToEnd();
+ command.WaitForExit();
+ Assert.True(command.ExitCode == 0, output + error);
+ try
+ {
+ var throughJunction = new WindowsSnapshotFile(Path.Combine(junction, "image.exe"),
+ SHA256.HashData(File.ReadAllBytes(fixture.Image)));
+ Assert.Throws(() =>
+ WindowsImageSnapshotLease.Create(true, fixture.Staging, throughJunction, Array.Empty()));
+ }
+ finally { Directory.Delete(junction); }
+ }
+
+ [Fact]
+ public async Task LaunchUsesTheSnapshotAndCancellationEndsTheJob()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ using var fixture = new Fixture();
+ var native = Environment.GetEnvironmentVariable("GU_WINDOWS_NATIVE_LOCK_PEER");
+ var dependencies = Array.Empty();
+ string[] arguments;
+ var marker = Path.Combine(fixture.Root, "child marker.txt");
+ if (native != null)
+ {
+ File.Copy(native, fixture.Image, overwrite: true);
+ var sqlite = Path.Combine(fixture.Root, "e_sqlite3.dll");
+ File.Copy(Path.Combine(Path.GetDirectoryName(native)!, "e_sqlite3.dll"), sqlite);
+ dependencies = new[] { new WindowsSnapshotFile(sqlite, SHA256.HashData(File.ReadAllBytes(sqlite))) };
+ arguments = new[] { "--snapshot-probe", marker, "wait" };
+ }
+ else
+ {
+ File.Copy(Path.Combine(Environment.SystemDirectory, "cmd.exe"), fixture.Image, overwrite: true);
+ arguments = new[] { "/c", "ping", "-n", "120", "127.0.0.1" };
+ }
+ var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image)));
+ var lease = WindowsNativeLaunchLease.Start(true, fixture.Staging, image, dependencies, arguments);
+ await using (lease)
+ {
+ using var process = lease.DuplicateProcessHandle();
+ Assert.False(TerminateProcess(process, 123));
+ Assert.Equal(5, Marshal.GetLastWin32Error());
+ if (native != null)
+ {
+ for (var i = 0; i < 200 && !File.Exists(marker + ".ready") && !File.Exists(marker + ".error"); i++) await Task.Delay(50);
+ Assert.True(File.Exists(marker + ".ready"), File.Exists(marker + ".error") ? File.ReadAllText(marker + ".error") : "Native AOT peer did not load SQLite and create the marker.");
+ Assert.Equal(Path.Combine(lease.SnapshotDirectory, "e_sqlite3.dll"), File.ReadAllLines(marker)[0], ignoreCase: true);
+ }
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
+ await Assert.ThrowsAnyAsync(() => lease.WaitForExitAsync(timeout.Token));
+ }
+ }
+
+ [Fact]
+ public async Task InvalidImageHashNeverStartsAndNormalExitIsReported()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ using var fixture = new Fixture();
+ File.Copy(Path.Combine(Environment.SystemDirectory, "cmd.exe"), fixture.Image, overwrite: true);
+ var marker = Path.Combine(fixture.Root, "unexpected.txt");
+ var bad = new WindowsSnapshotFile(fixture.Image, new byte[32]);
+ Assert.Throws(() => WindowsNativeLaunchLease.Start(true, fixture.Staging, bad,
+ Array.Empty(), new[] { "/c", "echo", "bad", ">", marker }));
+ Assert.False(File.Exists(marker));
+ var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image)));
+ await using var lease = WindowsNativeLaunchLease.Start(true, fixture.Staging, image,
+ Array.Empty(), new[] { "/c", "exit 1" });
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
+ Assert.Equal(1u, await lease.WaitForExitAsync(timeout.Token));
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task SnapshotJobStopsChildOnOwnerExit(bool killOwner)
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ var native = Environment.GetEnvironmentVariable("GU_WINDOWS_NATIVE_LOCK_PEER")
+ ?? throw new InvalidOperationException("The Native AOT experiment peer is required.");
+ using var fixture = new Fixture();
+ File.Copy(native, fixture.Image, overwrite: true);
+ var sqlite = Path.Combine(fixture.Root, "e_sqlite3.dll");
+ File.Copy(Path.Combine(Path.GetDirectoryName(native)!, "e_sqlite3.dll"), sqlite);
+ var marker = Path.Combine(fixture.Root, "child.txt");
+ var start = new ProcessStartInfo(native)
+ {
+ UseShellExecute = false, RedirectStandardInput = true, RedirectStandardError = true, CreateNoWindow = true
+ };
+ foreach (var argument in new[] { "--snapshot-owner-probe", fixture.Staging, fixture.Image, sqlite, marker })
+ start.ArgumentList.Add(argument);
+ using var owner = Process.Start(start) ?? throw new InvalidOperationException("Could not start the owner.");
+ var errors = owner.StandardError.ReadToEndAsync();
+ Process? child = null;
+ try
+ {
+ for (var i = 0; i < 600 && !File.Exists(marker + ".ready") && !File.Exists(marker + ".error") && !owner.HasExited; i++) await Task.Delay(50);
+ Assert.True(File.Exists(marker + ".ready"), File.Exists(marker + ".error") ? File.ReadAllText(marker + ".error") :
+ owner.HasExited ? await errors : "Child did not start.");
+ var lines = File.ReadAllLines(marker);
+ child = Process.GetProcessById(int.Parse(lines[1]));
+ Assert.False(child.HasExited);
+ if (killOwner) owner.Kill();
+ else await owner.StandardInput.WriteLineAsync("release");
+ await owner.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30));
+ if (!killOwner) Assert.True(owner.ExitCode == 0, await errors);
+ await child.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30));
+ }
+ finally
+ {
+ if (!owner.HasExited) owner.Kill();
+ await owner.WaitForExitAsync();
+ if (child != null)
+ {
+ if (!child.HasExited) child.Kill();
+ await child.WaitForExitAsync();
+ child.Dispose();
+ }
+ }
+ }
+
+ [Fact]
+ public async Task SnapshotLaunchInheritsNoUnlistedHandles()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ var native = Environment.GetEnvironmentVariable("GU_WINDOWS_NATIVE_LOCK_PEER")
+ ?? throw new InvalidOperationException("The Native AOT experiment peer is required.");
+ using var fixture = new Fixture();
+ File.Copy(native, fixture.Image, overwrite: true);
+ var marker = Path.Combine(fixture.Root, "inherited.txt");
+ var attributes = new SecurityAttributes { Length = Marshal.SizeOf(), InheritHandle = true };
+ using var first = CreateInheritableFile(fixture.Dependency, 0x80000000, 7, ref attributes, 3, 0x80, IntPtr.Zero);
+ using var second = CreateInheritableFile(fixture.Dependency, 0x80000000, 7, ref attributes, 3, 0x80, IntPtr.Zero);
+ if (first.IsInvalid || second.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
+ var image = new WindowsSnapshotFile(fixture.Image, SHA256.HashData(File.ReadAllBytes(fixture.Image)));
+ await using var lease = WindowsNativeLaunchLease.Start(true, fixture.Staging, image,
+ Array.Empty(), new[] { "--handle-list-probe",
+ first.DangerousGetHandle().ToInt64().ToString(),
+ second.DangerousGetHandle().ToInt64().ToString(), marker });
+ using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
+ Assert.Equal(0u, await lease.WaitForExitAsync(timeout.Token));
+ var lines = File.ReadAllLines(marker);
+ Assert.Equal(2, lines.Length);
+ Assert.DoesNotContain(lines, path => path.EndsWith(fixture.Dependency, StringComparison.OrdinalIgnoreCase));
+ }
+
+ [SupportedOSPlatform("windows")]
+ private sealed class Fixture : IDisposable
+ {
+ private readonly string _root = Path.Combine(Path.GetTempPath(), "gu-snapshot-test-" + Guid.NewGuid().ToString("N"));
+ public string Root => _root;
+ public string Staging { get; }
+ public string Image { get; }
+ public string Dependency { get; }
+
+ public Fixture()
+ {
+ var user = WindowsIdentity.GetCurrent().User ?? throw new InvalidOperationException();
+ var security = new DirectorySecurity();
+ security.SetOwner(user);
+ security.SetAccessRuleProtection(true, false);
+ security.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl,
+ InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
+ PropagationFlags.None, AccessControlType.Allow));
+ new DirectoryInfo(_root).Create(security);
+ Staging = Path.Combine(_root, "staging");
+ new DirectoryInfo(Staging).Create(security);
+ Image = Path.Combine(_root, "image.exe");
+ Dependency = Path.Combine(_root, "native.dll");
+ File.WriteAllText(Image, "image bytes");
+ File.WriteAllText(Dependency, "dependency bytes");
+ }
+ #endif
+
+ public WindowsImageSnapshotLease Create() => WindowsImageSnapshotLease.Create(true, Staging,
+ new WindowsSnapshotFile(Image, SHA256.HashData(File.ReadAllBytes(Image))),
+ new[] { new WindowsSnapshotFile(Dependency, SHA256.HashData(File.ReadAllBytes(Dependency))) });
+
+ public void Dispose()
+ {
+ if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true);
+ }
+
+ }
+
+ [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateFile(string path, uint access, uint share, IntPtr security,
+ uint creation, uint flags, IntPtr template);
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct SecurityAttributes
+ {
+ public int Length;
+ public IntPtr SecurityDescriptor;
+ [MarshalAs(UnmanagedType.Bool)] public bool InheritHandle;
+ }
+ [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateInheritableFile(string path, uint access, uint share, ref SecurityAttributes security,
+ uint creation, uint flags, IntPtr template);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool TerminateProcess(SafeProcessHandle process, uint exitCode);
+}
diff --git a/tests/CoreTest/Ipc/WindowsJobLifetimeExperimentTests.cs b/tests/CoreTest/Ipc/WindowsJobLifetimeExperimentTests.cs
new file mode 100644
index 00000000..b9c9d649
--- /dev/null
+++ b/tests/CoreTest/Ipc/WindowsJobLifetimeExperimentTests.cs
@@ -0,0 +1,113 @@
+using System.Diagnostics;
+
+namespace CoreTest.Ipc;
+
+/// Exercises job lifetime behavior, not a protected updater launcher.
+public sealed class WindowsJobLifetimeExperimentTests
+{
+ [Fact]
+ public async Task InvalidJobIsRejectedBeforeChildRuns()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ var executable = Environment.GetEnvironmentVariable("GU_WINDOWS_NATIVE_LOCK_PEER")
+ ?? Path.Combine(AppContext.BaseDirectory, "ReportWorker.exe");
+ var root = Path.Combine(Path.GetTempPath(), "gu-invalid-job-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(root);
+ try
+ {
+ var marker = Path.Combine(root, "started.txt");
+ var start = new ProcessStartInfo(executable)
+ {
+ UseShellExecute = false,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ CreateNoWindow = true
+ };
+ start.ArgumentList.Add("--job-invalid-probe");
+ start.ArgumentList.Add(executable);
+ start.ArgumentList.Add(marker);
+ using var owner = Process.Start(start) ?? throw new InvalidOperationException("Job owner did not start.");
+ var output = owner.StandardOutput.ReadToEndAsync();
+ var errors = owner.StandardError.ReadToEndAsync();
+ try
+ {
+ await owner.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30));
+ Assert.True(owner.ExitCode == 0, await errors);
+ Assert.StartsWith("rejected:", await output);
+ Assert.False(File.Exists(marker));
+ }
+ finally
+ {
+ if (!owner.HasExited) owner.Kill();
+ await owner.WaitForExitAsync();
+ }
+ }
+ finally
+ {
+ Directory.Delete(root, recursive: true);
+ }
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task JobListStopsChildWhenOwnerExits(bool killOwner)
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ var executable = Environment.GetEnvironmentVariable("GU_WINDOWS_NATIVE_LOCK_PEER")
+ ?? Path.Combine(AppContext.BaseDirectory, "ReportWorker.exe");
+ var root = Path.Combine(Path.GetTempPath(), "gu-job-lifetime-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(root);
+ try
+ {
+ var marker = Path.Combine(root, "started.txt");
+ var start = new ProcessStartInfo(executable)
+ {
+ UseShellExecute = false,
+ RedirectStandardInput = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ CreateNoWindow = true
+ };
+ start.ArgumentList.Add("--job-owner-probe");
+ start.ArgumentList.Add(executable);
+ start.ArgumentList.Add(marker);
+ using var owner = Process.Start(start) ?? throw new InvalidOperationException("Job owner did not start.");
+ var errors = owner.StandardError.ReadToEndAsync();
+ Process? child = null;
+ try
+ {
+ var line = await owner.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(30));
+ if (!int.TryParse(line, out var childId))
+ throw new InvalidOperationException($"Job owner did not report a child: {line}; {await errors}");
+ child = Process.GetProcessById(childId);
+ var deadline = DateTime.UtcNow.AddSeconds(30);
+ while (!File.Exists(marker) && !child.HasExited && DateTime.UtcNow < deadline)
+ await Task.Delay(50);
+ Assert.True(File.Exists(marker), "The child did not run.");
+ Assert.False(child.HasExited);
+ if (killOwner) owner.Kill();
+ else await owner.StandardInput.WriteLineAsync("release");
+ await owner.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30));
+ if (!killOwner) Assert.True(owner.ExitCode == 0, await errors);
+ await child.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30));
+ Assert.True(child.HasExited);
+ }
+ finally
+ {
+ if (!owner.HasExited) owner.Kill();
+ await owner.WaitForExitAsync();
+ if (child != null)
+ {
+ if (!child.HasExited) child.Kill();
+ await child.WaitForExitAsync();
+ child.Dispose();
+ }
+ }
+ }
+ finally
+ {
+ Directory.Delete(root, recursive: true);
+ }
+ }
+}
diff --git a/tests/CoreTest/Ipc/WindowsRestrictedInheritanceExperimentTests.cs b/tests/CoreTest/Ipc/WindowsRestrictedInheritanceExperimentTests.cs
new file mode 100644
index 00000000..2d622592
--- /dev/null
+++ b/tests/CoreTest/Ipc/WindowsRestrictedInheritanceExperimentTests.cs
@@ -0,0 +1,196 @@
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Text;
+using Microsoft.Win32.SafeHandles;
+
+namespace CoreTest.Ipc;
+
+/// Experiments with handle inheritance, not a protected updater launcher.
+public sealed class WindowsRestrictedInheritanceExperimentTests
+{
+ [Fact]
+ public void ExplicitHandleListExcludesOtherInheritableHandles()
+ {
+ if (!OperatingSystem.IsWindows()) return;
+ RunExperiment();
+ }
+
+ [SupportedOSPlatform("windows")]
+ private static void RunExperiment()
+ {
+ var root = Path.Combine(Path.GetTempPath(), "gu-handle-list-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(root);
+ try
+ {
+ var allowedPath = Path.Combine(root, "allowed.txt");
+ var rejectedPath = Path.Combine(root, "rejected.txt");
+ var resultPath = Path.Combine(root, "result.txt");
+ File.WriteAllText(allowedPath, "allowed");
+ File.WriteAllText(rejectedPath, "rejected");
+ var security = new SecurityAttributes { Length = Marshal.SizeOf(), InheritHandle = true };
+ using var allowed = CreateFile(allowedPath, 0x80000000, 7, ref security, 3, 0x80, IntPtr.Zero);
+ if (allowed.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
+ using var rejected = CreateFile(rejectedPath, 0x80000000, 7, ref security, 3, 0x80, IntPtr.Zero);
+ if (rejected.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
+
+ var script = """
+ $ErrorActionPreference = 'Stop'
+ Add-Type @'
+ using System;
+ using System.Runtime.InteropServices;
+ using System.Text;
+ public static class InheritedHandleProbe {
+ [DllImport("kernel32.dll", EntryPoint="GetFinalPathNameByHandleW", CharSet=CharSet.Unicode, SetLastError=true)]
+ public static extern uint GetPath(IntPtr handle, StringBuilder path, uint size, uint flags);
+ }
+ '@
+ function Get-HandlePath($value) {
+ $path = New-Object Text.StringBuilder 32768
+ $length = [InheritedHandleProbe]::GetPath([IntPtr][long]$value, $path, 32768, 0)
+ if ($length -eq 0) { return '' }
+ return $path.ToString()
+ }
+ $allowed = Get-HandlePath $args[0]
+ $rejected = Get-HandlePath $args[1]
+ [IO.File]::WriteAllLines($args[2], @($allowed, $rejected))
+ """;
+ var encoded = Convert.ToBase64String(Encoding.Unicode.GetBytes(
+ "& { " + script + " } '" + allowed.DangerousGetHandle().ToInt64() + "' '" +
+ rejected.DangerousGetHandle().ToInt64() + "' '" + resultPath.Replace("'", "''") + "'"));
+ var nativePeer = Environment.GetEnvironmentVariable("GU_WINDOWS_NATIVE_LOCK_PEER");
+ var executable = nativePeer ?? Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe");
+ var arguments = nativePeer == null
+ ? "-NoProfile -NonInteractive -EncodedCommand " + encoded
+ : "--handle-list-probe " + allowed.DangerousGetHandle().ToInt64() + " " +
+ rejected.DangerousGetHandle().ToInt64() + " \"" + resultPath + "\"";
+ var commandLine = new StringBuilder("\"" + executable + "\" " + arguments);
+
+ var size = IntPtr.Zero;
+ InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size);
+ if (size == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error());
+ var list = Marshal.AllocHGlobal(size);
+ var handles = Marshal.AllocHGlobal(IntPtr.Size);
+ var initialized = false;
+ try
+ {
+ if (!InitializeProcThreadAttributeList(list, 1, 0, ref size))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ initialized = true;
+ Marshal.WriteIntPtr(handles, allowed.DangerousGetHandle());
+ if (!UpdateProcThreadAttribute(list, 0, new IntPtr(0x00020002), handles,
+ new IntPtr(IntPtr.Size), IntPtr.Zero, IntPtr.Zero))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ var startup = new StartupInfoEx
+ {
+ StartupInfo = new StartupInfo { Size = Marshal.SizeOf() },
+ AttributeList = list
+ };
+ if (!CreateProcess(executable, commandLine, IntPtr.Zero, IntPtr.Zero, true,
+ 0x00080000 | 0x08000000, IntPtr.Zero, root, ref startup, out var process))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ try
+ {
+ var wait = WaitForSingleObject(process.Process, 30000);
+ if (wait != 0)
+ {
+ TerminateProcess(process.Process, 1);
+ throw new InvalidOperationException($"Worker did not exit: wait result {wait}.");
+ }
+ if (!GetExitCodeProcess(process.Process, out var exitCode))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ Assert.Equal(0u, exitCode);
+ }
+ finally
+ {
+ CloseHandle(process.Thread);
+ CloseHandle(process.Process);
+ }
+ }
+ finally
+ {
+ if (initialized) DeleteProcThreadAttributeList(list);
+ Marshal.FreeHGlobal(handles);
+ Marshal.FreeHGlobal(list);
+ }
+
+ var lines = File.ReadAllLines(resultPath);
+ Assert.Equal(2, lines.Length);
+ Assert.EndsWith(allowedPath, lines[0], StringComparison.OrdinalIgnoreCase);
+ Assert.False(lines[1].EndsWith(rejectedPath, StringComparison.OrdinalIgnoreCase));
+ }
+ finally
+ {
+ Directory.Delete(root, recursive: true);
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct SecurityAttributes
+ {
+ public int Length;
+ public IntPtr SecurityDescriptor;
+ [MarshalAs(UnmanagedType.Bool)] public bool InheritHandle;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct StartupInfo
+ {
+ public int Size;
+ public string? Reserved, Desktop, Title;
+ public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;
+ public short ShowWindow, Reserved2;
+ public IntPtr ReservedPointer, StandardInput, StandardOutput, StandardError;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct StartupInfoEx
+ {
+ public StartupInfo StartupInfo;
+ public IntPtr AttributeList;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ProcessInformation
+ {
+ public IntPtr Process, Thread;
+ public int ProcessId, ThreadId;
+ }
+
+ [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateFile(string path, uint access, uint share, ref SecurityAttributes security,
+ uint creation, uint flags, IntPtr template);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool InitializeProcThreadAttributeList(IntPtr list, int count, int flags, ref IntPtr size);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool UpdateProcThreadAttribute(IntPtr list, int flags, IntPtr attribute, IntPtr value,
+ IntPtr size, IntPtr previousValue, IntPtr returnSize);
+
+ [DllImport("kernel32.dll")]
+ private static extern void DeleteProcThreadAttributeList(IntPtr list);
+
+ [DllImport("kernel32.dll", EntryPoint = "CreateProcessW", CharSet = CharSet.Unicode, SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool CreateProcess(string application, StringBuilder commandLine, IntPtr processAttributes,
+ IntPtr threadAttributes, [MarshalAs(UnmanagedType.Bool)] bool inheritHandles, uint flags, IntPtr environment,
+ string currentDirectory, ref StartupInfoEx startup, out ProcessInformation process);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool GetExitCodeProcess(IntPtr process, out uint exitCode);
+
+ [DllImport("kernel32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool TerminateProcess(IntPtr process, uint exitCode);
+
+ [DllImport("kernel32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool CloseHandle(IntPtr handle);
+}
diff --git a/tests/ReportWorker/Program.cs b/tests/ReportWorker/Program.cs
index 26fd0243..8b0b58fd 100644
--- a/tests/ReportWorker/Program.cs
+++ b/tests/ReportWorker/Program.cs
@@ -1,6 +1,13 @@
using System.Net;
+using System.Runtime.InteropServices;
+using System.Text;
using System.Text.Json;
using GeneralUpdate.Core.Download.Reporting;
+using Microsoft.Data.Sqlite;
+#if WINDOWS_SNAPSHOT_LAUNCH_EXPERIMENT
+using GeneralUpdate.Core.Security;
+using System.Security.Cryptography;
+#endif
namespace ReportWorker;
@@ -10,6 +17,93 @@ internal static class Program
{
private static async Task Main(string[] args)
{
+#if WINDOWS_SNAPSHOT_LAUNCH_EXPERIMENT
+ if (args.Length == 5 && args[0] == "--snapshot-owner-probe")
+ {
+ if (!OperatingSystem.IsWindows()) return 3;
+ var image = new WindowsSnapshotFile(args[2], SHA256.HashData(File.ReadAllBytes(args[2])));
+ var dll = new WindowsSnapshotFile(args[3], SHA256.HashData(File.ReadAllBytes(args[3])));
+ await using var lease = WindowsNativeLaunchLease.Start(true, args[1], image, new[] { dll },
+ new[] { "--snapshot-probe", args[4], "wait" });
+ await Console.In.ReadLineAsync();
+ return 0;
+ }
+#endif
+ if (args.Length == 3 && args[0] == "--snapshot-probe")
+ {
+ try
+ {
+ if (!OperatingSystem.IsWindows()) return 3;
+ if (!SetDefaultDllDirectories(0x00000200 | 0x00000800))
+ throw new InvalidOperationException($"SetDefaultDllDirectories failed: {Marshal.GetLastWin32Error()}");
+ using var connection = new SqliteConnection("Data Source=:memory:");
+ connection.Open();
+ var module = GetModuleHandle("e_sqlite3.dll");
+ if (module == IntPtr.Zero) throw new InvalidOperationException("SQLite native module not found.");
+ var path = new StringBuilder(32768);
+ if (GetModuleFileName(module, path, (uint)path.Capacity) == 0)
+ throw new InvalidOperationException($"GetModuleFileName failed: {Marshal.GetLastWin32Error()}");
+ File.WriteAllLines(args[1], new[] { path.ToString(), Environment.ProcessId.ToString() });
+ File.WriteAllText(args[1] + ".ready", "ready");
+ if (args[2] == "wait") await Task.Delay(Timeout.InfiniteTimeSpan);
+ return 0;
+ }
+ catch (Exception ex)
+ {
+ File.WriteAllText(args[1] + ".error", ex.ToString());
+ return 91;
+ }
+ }
+ if (args.Length == 3 && args[0] == "--job-owner-probe")
+ {
+ if (!OperatingSystem.IsWindows()) return 3;
+ return await WindowsJobProbe.RunAsync(args[1], args[2]);
+ }
+ if (args.Length == 3 && args[0] == "--job-invalid-probe")
+ {
+ if (!OperatingSystem.IsWindows()) return 3;
+ return await WindowsJobProbe.RunAsync(args[1], args[2], invalidJob: true);
+ }
+ if (args.Length == 2 && args[0] == "--job-child-probe")
+ {
+ File.WriteAllText(args[1], "ready");
+ await Task.Delay(Timeout.InfiniteTimeSpan);
+ return 0;
+ }
+ if (args.Length == 1 && args[0] == "--sqlite-module-probe")
+ {
+ if (!OperatingSystem.IsWindows()) return 3;
+ if (!SetDefaultDllDirectories(0x00000200 | 0x00000800))
+ throw new InvalidOperationException($"SetDefaultDllDirectories failed: {Marshal.GetLastWin32Error()}");
+ using var connection = new SqliteConnection("Data Source=:memory:");
+ connection.Open();
+ var module = GetModuleHandle("e_sqlite3.dll");
+ if (module == IntPtr.Zero) throw new InvalidOperationException("SQLite native module not found.");
+ var path = new StringBuilder(32768);
+ if (GetModuleFileName(module, path, (uint)path.Capacity) == 0)
+ throw new InvalidOperationException($"GetModuleFileName failed: {Marshal.GetLastWin32Error()}");
+ Console.WriteLine(path.ToString());
+ return 0;
+ }
+ if (args.Length == 2 && args[0] == "--dll-search-probe")
+ {
+ if (!OperatingSystem.IsWindows()) return 3;
+ var module = LoadLibrary(args[1]);
+ if (module == IntPtr.Zero)
+ {
+ Console.WriteLine($"error:{Marshal.GetLastWin32Error()}");
+ return 0;
+ }
+ FreeLibrary(module);
+ Console.WriteLine("loaded");
+ return 0;
+ }
+ if (args.Length == 4 && args[0] == "--handle-list-probe")
+ {
+ if (!OperatingSystem.IsWindows()) return 3;
+ File.WriteAllLines(args[3], new[] { HandlePath(args[1]), HandlePath(args[2]) });
+ return 0;
+ }
if (args.Length == 1 && args[0] == "--image-lock-peer")
{
Console.WriteLine("ready");
@@ -31,6 +125,33 @@ private static async Task Main(string[] args)
return 0;
}
+ private static string HandlePath(string value)
+ {
+ var path = new StringBuilder(32768);
+ var length = GetFinalPathNameByHandle(new IntPtr(long.Parse(value)), path, (uint)path.Capacity, 0);
+ return length == 0 ? "" : path.ToString();
+ }
+
+ [DllImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern uint GetFinalPathNameByHandle(IntPtr handle, StringBuilder path, uint size, uint flags);
+
+ [DllImport("kernel32.dll", EntryPoint = "LoadLibraryW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern IntPtr LoadLibrary(string path);
+
+ [DllImport("kernel32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool FreeLibrary(IntPtr module);
+
+ [DllImport("kernel32.dll", EntryPoint = "GetModuleHandleW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern IntPtr GetModuleHandle(string name);
+
+ [DllImport("kernel32.dll", EntryPoint = "GetModuleFileNameW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern uint GetModuleFileName(IntPtr module, StringBuilder path, uint size);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool SetDefaultDllDirectories(uint flags);
+
private sealed class Handler(string mode) : HttpMessageHandler
{
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token)
diff --git a/tests/ReportWorker/WindowsJobProbe.cs b/tests/ReportWorker/WindowsJobProbe.cs
new file mode 100644
index 00000000..dfc8eb77
--- /dev/null
+++ b/tests/ReportWorker/WindowsJobProbe.cs
@@ -0,0 +1,175 @@
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Text;
+using Microsoft.Win32.SafeHandles;
+
+namespace ReportWorker;
+
+internal static class WindowsJobProbe
+{
+ internal static async Task RunAsync(string executable, string marker, bool invalidJob = false)
+ {
+ using var job = CreateJobObject(IntPtr.Zero, null);
+ if (job.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
+ var limits = new ExtendedLimitInformation
+ {
+ BasicLimitInformation = new BasicLimitInformation { LimitFlags = 0x00002000 }
+ };
+ if (!SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf()))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+
+ var size = IntPtr.Zero;
+ InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size);
+ if (size == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error());
+ var list = Marshal.AllocHGlobal(size);
+ var handles = Marshal.AllocHGlobal(IntPtr.Size);
+ var initialized = false;
+ try
+ {
+ if (!InitializeProcThreadAttributeList(list, 1, 0, ref size))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ initialized = true;
+ Marshal.WriteIntPtr(handles, invalidJob ? IntPtr.Zero : job.DangerousGetHandle());
+ if (!UpdateProcThreadAttribute(list, 0, new IntPtr(0x0002000d), handles,
+ new IntPtr(IntPtr.Size), IntPtr.Zero, IntPtr.Zero))
+ {
+ var error = Marshal.GetLastWin32Error();
+ if (!invalidJob) throw new Win32Exception(error);
+ Console.WriteLine($"rejected:{error}");
+ return 0;
+ }
+ var startup = new StartupInfoEx
+ {
+ StartupInfo = new StartupInfo { Size = Marshal.SizeOf() },
+ AttributeList = list
+ };
+ var command = new StringBuilder("\"" + executable + "\" --job-child-probe \"" + marker + "\"");
+ if (!CreateProcess(executable, command, IntPtr.Zero, IntPtr.Zero, false,
+ 0x00080000 | 0x08000000 | 0x00000004, IntPtr.Zero, null, ref startup, out var process))
+ {
+ var error = Marshal.GetLastWin32Error();
+ if (!invalidJob) throw new Win32Exception(error);
+ Console.WriteLine($"rejected:{error}");
+ return 0;
+ }
+ var resumed = false;
+ try
+ {
+ if (invalidJob) throw new InvalidOperationException("An invalid job unexpectedly allowed process creation.");
+ if (!IsProcessInJob(process.Process, job, out var assigned))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ if (!assigned) throw new InvalidOperationException("The child is not in the job.");
+ if (ResumeThread(process.Thread) == uint.MaxValue)
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+ resumed = true;
+ Console.WriteLine(process.ProcessId);
+ await Console.Out.FlushAsync();
+ await Console.In.ReadLineAsync();
+ return 0;
+ }
+ finally
+ {
+ if (!resumed) TerminateProcess(process.Process, 1);
+ CloseHandle(process.Thread);
+ CloseHandle(process.Process);
+ }
+ }
+ finally
+ {
+ if (initialized) DeleteProcThreadAttributeList(list);
+ Marshal.FreeHGlobal(handles);
+ Marshal.FreeHGlobal(list);
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct BasicLimitInformation
+ {
+ public long PerProcessUserTimeLimit, PerJobUserTimeLimit;
+ public uint LimitFlags;
+ public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize;
+ public uint ActiveProcessLimit;
+ public UIntPtr Affinity;
+ public uint PriorityClass, SchedulingClass;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct IoCounters
+ {
+ public ulong ReadOperationCount, WriteOperationCount, OtherOperationCount;
+ public ulong ReadTransferCount, WriteTransferCount, OtherTransferCount;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ExtendedLimitInformation
+ {
+ public BasicLimitInformation BasicLimitInformation;
+ public IoCounters IoInfo;
+ public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct StartupInfo
+ {
+ public int Size;
+ public string? Reserved, Desktop, Title;
+ public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;
+ public short ShowWindow, Reserved2;
+ public IntPtr ReservedPointer, StandardInput, StandardOutput, StandardError;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct StartupInfoEx
+ {
+ public StartupInfo StartupInfo;
+ public IntPtr AttributeList;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct ProcessInformation
+ {
+ public IntPtr Process, Thread;
+ public int ProcessId, ThreadId;
+ }
+
+ [DllImport("kernel32.dll", EntryPoint = "CreateJobObjectW", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateJobObject(IntPtr attributes, string? name);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool SetInformationJobObject(SafeFileHandle job, int informationClass,
+ ref ExtendedLimitInformation information, uint length);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool InitializeProcThreadAttributeList(IntPtr list, int count, int flags, ref IntPtr size);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool UpdateProcThreadAttribute(IntPtr list, int flags, IntPtr attribute, IntPtr value,
+ IntPtr size, IntPtr previousValue, IntPtr returnSize);
+
+ [DllImport("kernel32.dll")]
+ private static extern void DeleteProcThreadAttributeList(IntPtr list);
+
+ [DllImport("kernel32.dll", EntryPoint = "CreateProcessW", CharSet = CharSet.Unicode, SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool CreateProcess(string application, StringBuilder command, IntPtr processAttributes,
+ IntPtr threadAttributes, [MarshalAs(UnmanagedType.Bool)] bool inheritHandles, uint flags, IntPtr environment,
+ string? currentDirectory, ref StartupInfoEx startup, out ProcessInformation process);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool IsProcessInJob(IntPtr process, SafeFileHandle job, [MarshalAs(UnmanagedType.Bool)] out bool result);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern uint ResumeThread(IntPtr thread);
+
+ [DllImport("kernel32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool CloseHandle(IntPtr handle);
+
+ [DllImport("kernel32.dll")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool TerminateProcess(IntPtr process, uint exitCode);
+}