Skip to content

Commit 87d05e9

Browse files
committed
test(P1-GATE.04): preserve original handle transfer and failure cleanup prototype
1 parent e8d1b07 commit 87d05e9

8 files changed

Lines changed: 919 additions & 0 deletions

File tree

‎docs/evidence/p1/original-handle-lease-v1.json‎

Lines changed: 486 additions & 0 deletions
Large diffs are not rendered by default.

‎docs/roadmap/P2-HANDOFF.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1341,3 +1341,5 @@ Round54 hand-MIR structure component is ✅ Complete: tiny1/full2 match230 canon
13411341
Round54 independent native growth input component is ✅ Complete: held/transient2/2 pass with actual creator receipts and explicit event done barrier; native birth/full-command/parent/Job proofs and owned handles are audited. [Input proof](../evidence/p1/controlled-growth-input-v1.json) preserves the old missing-receipt trial. Cross-birth raw accounting differs from separate stable production Inspect. Production reconciliation and dual-budget acceptance remain open; no legacy8 retry or core commit occurred. P1 six gates, P2 8/101 and P3 0/38+0/4 remain unchanged.
13421342

13431343
Round56 P1-GATE.02 inventory component is ✅ Complete: strict local build and11 fixed checks pass (four original reports/112 ordered ID+source hashes, proposal28 and six new mutations). Prior baseline/eight mutations are retained without rerun. [Exact inventory proof](../evidence/p1/strict-cleanup-inventory-v1.json) preserves the unapproved proposal and unchanged28/168/56/callable7+2 denominators. This is inventory validation only; generated cleanup semantics and all six P1 gates stay open.
1344+
1345+
Round56 original-handle lease component is ✅ Complete: strict build and real Windows A1/A2/A3 pass, including both forced-exception and cancellation cleanup. [Native ownership proof](../evidence/p1/original-handle-lease-v1.json) binds same observer handle transfer, receiver close, borrowed-handle survival and duplicate-transfer rejection; prior analyzer and path-precondition failures remain. Production acquisition, lifetime ancestry, growth reconciliation and legacy8/dual3 acceptance remain open; active20/cumulative1024 are unchanged.

‎docs/roadmap/P2-HANDOFF_zh.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1111,3 +1111,5 @@ root 负责共享注册容量、调用方集成、CI/门禁聚合、双语状
11111111
第54轮独立原生growth输入组件 ✅ 已完成:held/transient2/2通过,具备真实creator回执与明确event done屏障,已审查native birth/full-command/parent/Job及自有句柄。[输入证明](../evidence/p1/controlled-growth-input-v1.json)保留旧缺回执试验。跨birth原始计数与另一次稳定production Inspect不同。生产reconciliation和双预算验收仍开放;没有重试旧8或提交core。P1六门禁、P2 8/101、P3 0/38+0/4均不变。
11121112

11131113
Round56 P1-GATE.02库存组件 ✅ 已完成:本地严格构建及11项固定检查通过(四份原报告/112条有序ID与源码哈希、28项提案及六项新变异)。历史基线/八项变异保留且未重跑。[精确库存证据](../evidence/p1/strict-cleanup-inventory-v1.json)保留未批准提案及原28/168/56/callable7+2分母。这仅验证库存;生成清理语义与P1六门禁仍开放。
1114+
1115+
Round56原句柄lease组件 ✅ 已完成:严格构建及真实Windows A1/A2/A3通过,包含强制异常与取消回收两个子项。[原生所有权证据](../evidence/p1/original-handle-lease-v1.json)绑定同一观察进程原句柄转移、接收方关闭、借用句柄存活及重复转移拒绝;历史分析器与路径前置条件失败保留。生产acquisition、生命周期祖先链、增长协调器及legacy8/dual3验收仍开放;active20/cumulative1024不变。

‎eng/prototypes/OriginalHandleLeaseV1/Core/Launcher.cs‎

Lines changed: 85 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
#nullable enable
2+
using System;
3+
using System.Collections.Generic;
4+
using System.Diagnostics;
5+
using System.IO;
6+
using System.Linq;
7+
using System.Runtime.InteropServices;
8+
using System.Text;
9+
using System.Threading;
10+
using System.Security.Cryptography;
11+
using Microsoft.Win32.SafeHandles;
12+
13+
namespace RustSharp.ProcessContainment;
14+
internal sealed class NativeProcessTerminatingException:IOException {
15+
internal NativeProcessTerminatingException():base("NT command query STATUS_PROCESS_IS_TERMINATING (0xC000010A)"){}
16+
}
17+
public sealed class KernelHandle : SafeHandleZeroOrMinusOneIsInvalid {
18+
public KernelHandle():base(true){}
19+
internal KernelHandle(IntPtr value):base(true){SetHandle(value);}
20+
public bool? CloseSucceeded {get;private set;}
21+
public int? CloseLastError {get;private set;}
22+
protected override bool ReleaseHandle(){int native=Win32.CloseHandle(handle);CloseLastError=Marshal.GetLastPInvokeError();bool result=native!=0;CloseSucceeded=result;return result;}
23+
}
24+
public sealed record ProcessIdentity(uint Pid,long CreationFileTime,uint ParentPid,string CommandLine);
25+
public sealed record ParentChain(IReadOnlyList<ProcessIdentity> Nodes,bool Complete,string StopReason);
26+
public sealed record TerminalWaitResult(bool Terminal,bool BirthVerified,uint? ExitCode,int Checks,long ElapsedMilliseconds);
27+
internal static partial class Win32 {
28+
internal static TerminalWaitResult WaitOwnedTerminal(KernelHandle handle,ProcessIdentity expected,int milliseconds,CancellationToken cancellation)
29+
{
30+
Need(milliseconds is >0 and <=3000,"Owned terminal wait1..3000ms");var watch=Stopwatch.StartNew();int checks=0;
31+
// At most120 native waits, at most caller milliseconds, cancellation every25ms.
32+
for(int index=0;index<120&&watch.ElapsedMilliseconds<milliseconds;index++)
33+
{
34+
cancellation.ThrowIfCancellationRequested();Check(GetProcessTimes(handle,out long birth,out _,out _,out _),"owned terminal wait birth");Need(birth==expected.CreationFileTime,"Owned terminal same-handle creation mismatch");
35+
uint interval=checked((uint)Math.Max(1,Math.Min(25,milliseconds-watch.ElapsedMilliseconds)));uint state=WaitForSingleObject(handle,interval);checks++;Need(state is 0 or 258,"Owned terminal native wait error");
36+
if(state==0){Check(GetProcessTimes(handle,out long after,out _,out _,out _),"owned terminal final birth");Need(after==expected.CreationFileTime,"Owned terminal final creation mismatch");Check(GetExitCodeProcess(handle,out uint code),"owned terminal actual exit");return new(true,true,code,checks,watch.ElapsedMilliseconds);}
37+
}
38+
return new(false,true,null,checks,watch.ElapsedMilliseconds);
39+
}
40+
[StructLayout(LayoutKind.Sequential)] internal struct Startup {
41+
public uint Size;public IntPtr Reserved,Desktop,Title;public uint X,Y,XSize,YSize,XChars,YChars,Fill,Flags;public ushort Show,ReservedSize;public IntPtr ReservedBytes,Input,Output,Error;
42+
}
43+
[StructLayout(LayoutKind.Sequential)] internal struct Created {public IntPtr Process,Thread;public uint Pid,Tid;}
44+
// PBI offset40's inherited PID and NT class60 are Windows-specific internals.
45+
// Known v2 runtime verified them; any unsupported status blocks instead of guessing.
46+
[StructLayout(LayoutKind.Sequential)] internal struct Basic {public IntPtr Reserved,Peb,Reserved2,Reserved3,Pid,Parent;}
47+
[StructLayout(LayoutKind.Sequential)] internal struct BasicLimit {public long ProcessTime,JobTime;public uint Flags;public UIntPtr MinWs,MaxWs;public uint Active;public UIntPtr Affinity;public uint Priority,Scheduling;}
48+
[StructLayout(LayoutKind.Sequential)] internal struct Io {public ulong A,B,C,D,E,F;}
49+
[StructLayout(LayoutKind.Sequential)] internal struct JobLimit {public BasicLimit Basic;public Io Io;public UIntPtr A,B,C,D;}
50+
// BOOL is an explicit 32-bit int. UTF-16 W API; command is caller-owned mutable HGlobal.
51+
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,ExactSpelling=true,SetLastError=true)] internal static extern int CreateProcessW(string application,IntPtr command,IntPtr processAttributes,IntPtr threadAttributes,int inheritHandles,uint flags,IntPtr environment,string directory,ref Startup startup,out Created created);
52+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern KernelHandle CreateJobObjectW(IntPtr attributes,IntPtr name);
53+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern int SetInformationJobObject(KernelHandle job,int kind,ref JobLimit information,uint bytes);
54+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern int AssignProcessToJobObject(KernelHandle job,KernelHandle process);
55+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern int IsProcessInJob(KernelHandle process,KernelHandle job,out int member);
56+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern int TerminateJobObject(KernelHandle job,uint code);
57+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern int TerminateProcess(KernelHandle process,uint code);
58+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern uint ResumeThread(KernelHandle thread);
59+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern uint WaitForSingleObject(KernelHandle process,uint milliseconds);
60+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern int GetExitCodeProcess(KernelHandle process,out uint code);
61+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern int GetProcessTimes(KernelHandle process,out long creation,out long exit,out long kernel,out long user);
62+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern KernelHandle OpenProcess(uint access,int inherit,uint pid);
63+
[DllImport("kernel32.dll",ExactSpelling=true,SetLastError=true)] internal static extern int CloseHandle(IntPtr handle);
64+
[DllImport("ntdll.dll",EntryPoint="NtQueryInformationProcess",ExactSpelling=true)] internal static extern int QueryBasic(KernelHandle process,uint kind,ref Basic information,uint bytes,out uint returned);
65+
[DllImport("ntdll.dll",EntryPoint="NtQueryInformationProcess",ExactSpelling=true)] internal static extern int QueryCommand(KernelHandle process,uint kind,IntPtr information,uint bytes,out uint returned);
66+
internal static void Check(int result,string operation){int error=Marshal.GetLastPInvokeError();if(result==0)throw new System.ComponentModel.Win32Exception(error,operation);}
67+
internal static void CheckHandle(KernelHandle handle,string operation){int error=Marshal.GetLastPInvokeError();if(handle.IsInvalid)throw new System.ComponentModel.Win32Exception(error,operation);}
68+
internal static void Need(bool condition,string message){if(!condition)throw new InvalidDataException(message);}
69+
internal static void Layout<T>(int size,params (string Field,int Offset)[] fields){Need(Marshal.SizeOf<T>()==size,typeof(T).Name+" size");foreach(var f in fields)Need(Marshal.OffsetOf<T>(f.Field).ToInt32()==f.Offset,typeof(T).Name+"."+f.Field+" offset");}
70+
internal static void Audit(){
71+
Need(OperatingSystem.IsWindows()&&IntPtr.Size==8,"Windows x64 only");Layout<Startup>(104,("Flags",60),("ReservedBytes",72),("Input",80));Layout<Created>(24,("Pid",16));Layout<Basic>(48,("Pid",32),("Parent",40));Layout<BasicLimit>(64,("MinWs",24),("Affinity",48));Layout<Io>(48);Layout<JobLimit>(144,("Io",64),("A",112));
72+
}
73+
[DllImport("kernel32.dll",CharSet=CharSet.Unicode,ExactSpelling=true,SetLastError=true)] internal static extern int QueryFullProcessImageNameW(KernelHandle process,uint flags,[Out] char[] image,ref uint size);
74+
internal static string Command(KernelHandle process){
75+
const int size=65536;IntPtr buffer=Marshal.AllocHGlobal(size);
76+
try{int status=QueryCommand(process,60,buffer,size,out uint returned);if(unchecked((uint)status)==0xC000010Au)throw new NativeProcessTerminatingException();Need(status==0&&returned>=16&&returned<=size,"NT command query status=0x"+status.ToString("X8",System.Globalization.CultureInfo.InvariantCulture));
77+
int length=(ushort)Marshal.ReadInt16(buffer);IntPtr text=Marshal.ReadIntPtr(buffer,8);long lower=buffer.ToInt64(),pointer=text.ToInt64();Need(length%2==0&&pointer>=lower&&pointer<=lower+size-length,"UNICODE_STRING pointer/length bounds");return Marshal.PtrToStringUni(text,length/2)??throw new InvalidDataException("Missing OS command");
78+
}finally{Marshal.FreeHGlobal(buffer);}
79+
}
80+
internal static ProcessIdentity Identity(KernelHandle process,uint expected){
81+
Check(GetProcessTimes(process,out long creation,out _,out _,out _),"GetProcessTimes");var basic=new Basic();int status=QueryBasic(process,0,ref basic,48,out uint returned);Need(status==0&&returned==48&&basic.Pid.ToInt64()==expected,"NT PID/parent identity status=0x"+status.ToString("X8",System.Globalization.CultureInfo.InvariantCulture));
82+
string command=Command(process);Check(GetProcessTimes(process,out long after,out _,out _,out _),"identity creation recheck");Need(after==creation,"Exact native FILETIME changed");return new(expected,creation,checked((uint)basic.Parent.ToInt64()),command);
83+
}
84+
}
85+
public static class ProcessAudit {
86+
private static readonly System.Buffers.SearchValues<char> InvalidArgumentChars=System.Buffers.SearchValues.Create("\0\r\n");
87+
public static string VerifyRoot(string root,CancellationToken token){Win32.Need(Path.IsPathFullyQualified(root),"Absolute exclusive root required");string exact=Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);var clock=Stopwatch.StartNew();DirectoryInfo? node=new(exact);for(int depth=0;node!=null&&depth<64&&clock.Elapsed.TotalSeconds<5;depth++){token.ThrowIfCancellationRequested();Win32.Need(node.Exists&&(node.Attributes&FileAttributes.ReparsePoint)==0,"Existing non-reparse root ancestry required");node=node.Parent;}Win32.Need(node==null,"Root ancestry64-node/5-second bound");return exact;}
88+
public static string ImagePath(ProcessIdentity expected){using var process=Win32.OpenProcess(0x101400,0,expected.Pid);Win32.CheckHandle(process,"Retained native image query");Win32.Need(Win32.Identity(process,expected.Pid)==expected,"Exact identity before image query");var image=new char[32768];uint size=32768;Win32.Check(Win32.QueryFullProcessImageNameW(process,0,image,ref size),"QueryFullProcessImageNameW");Win32.Need(size>0&&size<32768&&Path.IsPathFullyQualified(new string(image,0,checked((int)size)))&&Win32.Identity(process,expected.Pid)==expected,"Absolute native image with exact identity recheck");return Path.GetFullPath(new string(image,0,checked((int)size)));}
89+
public static ProcessIdentity Read(uint pid){using var handle=Win32.OpenProcess(0x101400,0,pid);Win32.CheckHandle(handle,"OpenProcess exact query/synchronize target");return Win32.Identity(handle,pid);}
90+
public static BoundaryChain ToBoundary(uint first,ProcessIdentity host,CancellationToken cancellation){
91+
var watch=Stopwatch.StartNew();var rows=new List<ProcessIdentity>();var seen=new HashSet<uint>();uint current=first;
92+
try{for(int index=0;index<16&&watch.Elapsed.TotalSeconds<5;index++){cancellation.ThrowIfCancellationRequested();Win32.Need(current!=0&&seen.Add(current),"Host absent or ancestry cycle");var row=Read(current);rows.Add(row);if(current==host.Pid){Win32.Need(row==host&&Read(current)==host,"Live host exact PID/FILETIME/command/parent double check");return new(rows,true,false,"Reviewed host boundary reached; upstream system ancestry remains separately incomplete");}current=row.ParentPid;}
93+
return new(rows,false,false,"16-node / 5-second boundary before reviewed host");
94+
}catch(Exception e){return new(rows,false,false,e.GetType().Name+": "+e.Message);}
95+
}
96+
public static ParentChain Capture(uint first,CancellationToken cancellation){
97+
var watch=Stopwatch.StartNew();var rows=new List<ProcessIdentity>();var seen=new HashSet<uint>();uint current=first;
98+
try{
99+
// Manually reviewed comparisons: <=16 process nodes and <=5 seconds; no retry.
100+
for(int index=0;index<16&&watch.Elapsed.TotalSeconds<5;index++){
101+
cancellation.ThrowIfCancellationRequested();if(current==0)return new(rows,true,"parent PID zero");Win32.Need(seen.Add(current),"Parent chain cycle");
102+
using var handle=Win32.OpenProcess(0x1400,0,current);Win32.CheckHandle(handle,"OpenProcess query-only ancestor");var row=Win32.Identity(handle,current);rows.Add(row);current=row.ParentPid;
103+
}
104+
return new(rows,current==0,current==0?"parent PID zero":"16-node / 5-second boundary");
105+
}catch(Exception e){return new(rows,false,e.GetType().Name+": "+e.Message);}
106+
}
107+
public static string Quote(string value){
108+
Win32.Need(value.Length<=32767&&value.AsSpan().IndexOfAny(InvalidArgumentChars)<0,"Bounded literal Windows argument");bool quoting=value.Length==0;foreach(char item in value){if(char.IsWhiteSpace(item)||item=='"'){quoting=true;break;}}if(!quoting)return value;var b=new StringBuilder("\"");int slashes=0;
109+
foreach(char c in value){if(c=='\\'){slashes++;continue;}if(c=='"')b.Append('\\',slashes*2+1).Append(c);else b.Append('\\',slashes).Append(c);slashes=0;}return b.Append('\\',slashes*2).Append('"').ToString();
110+
}
111+
public static void ValidateLayouts()=>Win32.Audit();
112+
}
113+
public sealed record BoundaryChain(IReadOnlyList<ProcessIdentity> Nodes,bool BoundaryVerified,bool SystemAncestorsComplete,string StopReason);
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<TargetFramework>net10.0</TargetFramework><OutputType>Exe</OutputType><AssemblyName>LeaseFixture</AssemblyName>
4+
<Nullable>enable</Nullable><ImplicitUsings>disable</ImplicitUsings><EnableDefaultCompileItems>false</EnableDefaultCompileItems>
5+
<UseSharedCompilation>false</UseSharedCompilation><TreatWarningsAsErrors>true</TreatWarningsAsErrors>
6+
</PropertyGroup>
7+
<ItemGroup><Compile Include="Program.cs"/><Compile Include="OriginalHandleLease.cs"/><Compile Include="Core/Native.cs"/><Compile Include="Core/Launcher.cs"/></ItemGroup>
8+
</Project>

0 commit comments

Comments
 (0)