| 1 | using System.ComponentModel; |
| 2 | using System.Diagnostics; |
| 3 | using System.Runtime.InteropServices; |
| 4 | |
| 5 | namespace Cage.GuestClipboard; |
| 6 | |
| 7 | |
| 8 | |
| 9 | internal sealed class GuestProcessJob : IDisposable |
| 10 | { |
| 11 | private IntPtr handle; |
| 12 | internal GuestProcessJob(Process process) |
| 13 | { |
| 14 | handle=CreateJobObject(IntPtr.Zero,null); |
| 15 | if(handle==IntPtr.Zero)throw new Win32Exception(); |
| 16 | try |
| 17 | { |
| 18 | var limits=new Limits();limits.Basic.Flags=0x2000; |
| 19 | if(!SetInformationJobObject(handle,9,ref limits,(uint)Marshal.SizeOf<Limits>())||!AssignProcessToJobObject(handle,process.Handle))throw new Win32Exception(); |
| 20 | } |
| 21 | catch{Dispose();throw;} |
| 22 | } |
| 23 | public void Dispose(){var job=Interlocked.Exchange(ref handle,IntPtr.Zero);if(job!=IntPtr.Zero)CloseHandle(job);} |
| 24 | [StructLayout(LayoutKind.Sequential)]private struct Basic{internal long ProcessTime,JobTime;internal uint Flags;internal nuint MinWorking,MaxWorking;internal uint Active;internal nuint Affinity;internal uint Priority,Scheduling;} |
| 25 | [StructLayout(LayoutKind.Sequential)]private struct IO{internal ulong ReadOperations,WriteOperations,OtherOperations,ReadBytes,WriteBytes,OtherBytes;} |
| 26 | [StructLayout(LayoutKind.Sequential)]private struct Limits{internal Basic Basic;internal IO IO;internal nuint ProcessMemory,JobMemory,PeakProcessMemory,PeakJobMemory;} |
| 27 | [DllImport("kernel32.dll",CharSet=CharSet.Unicode,EntryPoint="CreateJobObjectW",SetLastError=true)]private static extern IntPtr CreateJobObject(IntPtr attributes,string? name); |
| 28 | [DllImport("kernel32.dll",SetLastError=true)]private static extern bool SetInformationJobObject(IntPtr job,int type,ref Limits limits,uint size); |
| 29 | [DllImport("kernel32.dll",SetLastError=true)]private static extern bool AssignProcessToJobObject(IntPtr job,IntPtr process); |
| 30 | [DllImport("kernel32.dll")]private static extern bool CloseHandle(IntPtr handle); |
| 31 | } |