Debian Codegraph @

lib/ansible/module_utils/csharp/Ansible._Async.cs

raw
1 using Microsoft.Win32.SafeHandles;
2 using System;
3 using System.IO;
4 using System.Runtime.InteropServices;
5 using System.Security;
6 using System.Text;
7 using System.Threading;
8 using System.Threading.Tasks;
9
10 // Used by async_wrapper.ps1, not for general use.
11 //AllowUnsafe
12
13 namespace Ansible._Async
14 {
15 internal class NativeHelpers
16 {
17 public const int CREATE_SUSPENDED = 0x00000004;
18 public const int CREATE_NEW_CONSOLE = 0x00000010;
19 public const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
20 public const int EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
21 public const int CREATE_BREAKAWAY_FROM_JOB = 0x01000000;
22
23 public const int DUPLICATE_CLOSE_SOURCE = 0x00000001;
24 public const int DUPLICATE_SAME_ACCESS = 0x00000002;
25
26 public const int JobObjectBasicLimitInformation = 2;
27
28 public const int JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800;
29
30 public const int PROCESS_DUP_HANDLE = 0x00000040;
31 public const int PROCESS_CREATE_PROCESS = 0x00000080;
32
33 public const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000;
34 public const int PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x00020002;
35
36 public const int STARTF_USESHOWWINDOW = 0x00000001;
37 public const int STARTF_USESTDHANDLES = 0x00000100;
38
39 public const short SW_HIDE = 0;
40
41 [StructLayout(LayoutKind.Sequential)]
42 public struct JOBOBJECT_BASIC_LIMIT_INFORMATION
43 {
44 public long PerProcessUserTimeLimit;
45 public long PerJobUserTimeLimit;
46 public int LimitFlags;
47 public IntPtr MinimumWorkingSetSize;
48 public IntPtr MaximumWorkingSetSize;
49 public int ActiveProcessLimit;
50 public UIntPtr Affinity;
51 public int PriorityClass;
52 public int SchedulingClass;
53 }
54
55 [StructLayout(LayoutKind.Sequential)]
56 public struct SECURITY_ATTRIBUTES
57 {
58 public int nLength;
59 public IntPtr lpSecurityDescriptor;
60 public int bInheritHandle;
61 }
62
63 [StructLayout(LayoutKind.Sequential)]
64 public struct STARTUPINFO
65 {
66 public int cb;
67 public IntPtr lpReserved;
68 public IntPtr lpDesktop;
69 public IntPtr lpTitle;
70 public int dwX;
71 public int dwY;
72 public int dwXSize;
73 public int dwYSize;
74 public int dwXCountChars;
75 public int dwYCountChars;
76 public int dwFillAttribute;
77 public int dwFlags;
78 public short wShowWindow;
79 public short cbReserved2;
80 public IntPtr lpReserved2;
81 public IntPtr hStdInput;
82 public IntPtr hStdOutput;
83 public IntPtr hStdError;
84 }
85
86 [StructLayout(LayoutKind.Sequential)]
87 public struct STARTUPINFOEX
88 {
89 public STARTUPINFO startupInfo;
90 public IntPtr lpAttributeList;
91 }
92
93 [StructLayout(LayoutKind.Sequential)]
94 public struct PROCESS_INFORMATION
95 {
96 public IntPtr hProcess;
97 public IntPtr hThread;
98 public int dwProcessId;
99 public int dwThreadId;
100 }
101 }
102
103 internal class NativeMethods
104 {
105 [DllImport("kernel32.dll", SetLastError = true)]
106 public static extern IntPtr CreateEventW(
107 ref NativeHelpers.SECURITY_ATTRIBUTES lpEventAttributes,
108 bool bManualReset,
109 bool bInitialState,
110 IntPtr lpName);
111
112 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
113 public static extern bool CreateProcessW(
114 [MarshalAs(UnmanagedType.LPWStr)] string lpApplicationName,
115 StringBuilder lpCommandLine,
116 IntPtr lpProcessAttributes,
117 IntPtr lpThreadAttributes,
118 bool bInheritHandles,
119 int dwCreationFlags,
120 IntPtr lpEnvironment,
121 IntPtr lpCurrentDirectory,
122 ref NativeHelpers.STARTUPINFOEX lpStartupInfo,
123 out NativeHelpers.PROCESS_INFORMATION lpProcessInformation);
124
125 [DllImport("kernel32.dll")]
126 public static extern void DeleteProcThreadAttributeList(
127 IntPtr lpAttributeList);
128
129 [DllImport("kernel32.dll", SetLastError = true)]
130 public static extern bool DuplicateHandle(
131 IntPtr hSourceProcessHandle,
132 IntPtr hSourceHandle,
133 IntPtr hTargetProcessHandle,
134 out IntPtr lpTargetHandle,
135 int dwDesiredAccess,
136 bool bInheritHandle,
137 int dwOptions);
138
139 [DllImport("kernel32.dll")]
140 public static extern IntPtr GetCurrentProcess();
141
142 [DllImport("kernel32.dll", SetLastError = true)]
143 public static extern bool GetExitCodeProcess(
144 IntPtr hProcess,
145 out int lpExitCode);
146
147 [DllImport("kernel32.dll", SetLastError = true)]
148 public static extern bool InitializeProcThreadAttributeList(
149 IntPtr lpAttributeList,
150 int dwAttributeCount,
151 int dwFlags,
152 ref IntPtr lpSize);
153
154 [DllImport("kernel32.dll", SetLastError = true)]
155 public static extern bool IsProcessInJob(
156 IntPtr ProcessHandle,
157 IntPtr JobHandle,
158 out bool Result);
159
160 [DllImport("kernel32.dll", SetLastError = true)]
161 public static extern IntPtr OpenProcess(
162 Int32 dwDesiredAccess,
163 bool bInheritHandle,
164 Int32 dwProcessId);
165
166 [DllImport("kernel32.dll", SetLastError = true)]
167 public static extern bool QueryInformationJobObject(
168 IntPtr hJob,
169 int JobObjectInformationClass,
170 ref NativeHelpers.JOBOBJECT_BASIC_LIMIT_INFORMATION lpJobObjectInformation,
171 int cbJobObjectInformationLength,
172 IntPtr lpReturnLength);
173
174 [DllImport("kernel32.dll", SetLastError = true)]
175 public static extern int ResumeThread(
176 IntPtr hThread);
177
178 [DllImport("kernel32.dll", SetLastError = true)]
179 public static unsafe extern bool UpdateProcThreadAttribute(
180 SafeProcThreadAttrList lpAttributeList,
181 int dwFlags,
182 UIntPtr Attribute,
183 void* lpValue,
184 UIntPtr cbSize,
185 IntPtr lpPreviousValue,
186 IntPtr lpReturnSize);
187 }
188
189 public class ProcessInformation : IDisposable
190 {
191 public SafeWaitHandle Process { get; private set; }
192 public SafeWaitHandle Thread { get; private set; }
193 public int ProcessId { get; private set; }
194 public int ThreadId { get; private set; }
195 public Task<string> StdoutReader { get; private set; }
196 public Task<string> StderrReader { get; private set; }
197
198 public ProcessInformation(
199 SafeWaitHandle process,
200 SafeWaitHandle thread,
201 int processId,
202 int threadId,
203 Task<string> stdoutReader,
204 Task<string> stderrReader)
205 {
206 Process = process;
207 Thread = thread;
208 ProcessId = processId;
209 ThreadId = threadId;
210 StdoutReader = stdoutReader;
211 StderrReader = stderrReader;
212 }
213
214 public void Dispose()
215 {
216 Process.Dispose();
217 Thread.Dispose();
218 GC.SuppressFinalize(this);
219 }
220 ~ProcessInformation() { Dispose(); }
221 }
222
223 public class Win32Exception : System.ComponentModel.Win32Exception
224 {
225 private string _msg;
226
227 public Win32Exception(string message) : this(Marshal.GetLastWin32Error(), message) { }
228 public Win32Exception(int errorCode, string message) : base(errorCode)
229 {
230 _msg = String.Format("{0} ({1}, Win32ErrorCode {2} - 0x{2:X8})", message, base.Message, errorCode);
231 }
232
233 public override string Message { get { return _msg; } }
234 public static explicit operator Win32Exception(string message) { return new Win32Exception(message); }
235 }
236
237 public class ManagedWaitHandle : WaitHandle
238 {
239 public ManagedWaitHandle(SafeWaitHandle handle)
240 {
241 SafeWaitHandle = handle;
242 }
243 }
244
245 internal sealed class SafeProcThreadAttrList : SafeHandle
246 {
247 public SafeProcThreadAttrList(IntPtr handle) : base(handle, true) { }
248
249 public override bool IsInvalid { get { return handle == IntPtr.Zero; } }
250
251 protected override bool ReleaseHandle()
252 {
253 NativeMethods.DeleteProcThreadAttributeList(handle);
254 Marshal.FreeHGlobal(handle);
255 return true;
256 }
257 }
258
259 public class AsyncUtil
260 {
261 public static bool CanCreateBreakawayProcess()
262 {
263 bool isInJob;
264 if (!NativeMethods.IsProcessInJob(NativeMethods.GetCurrentProcess(), IntPtr.Zero, out isInJob))
265 {
266 throw new Win32Exception("IsProcessInJob() failed");
267 }
268
269 if (!isInJob)
270 {
271 return true;
272 }
273
274 NativeHelpers.JOBOBJECT_BASIC_LIMIT_INFORMATION jobInfo = new NativeHelpers.JOBOBJECT_BASIC_LIMIT_INFORMATION();
275 bool jobRes = NativeMethods.QueryInformationJobObject(
276 IntPtr.Zero,
277 NativeHelpers.JobObjectBasicLimitInformation,
278 ref jobInfo,
279 Marshal.SizeOf<NativeHelpers.JOBOBJECT_BASIC_LIMIT_INFORMATION>(),
280 IntPtr.Zero);
281 if (!jobRes)
282 {
283 throw new Win32Exception("QueryInformationJobObject() failed");
284 }
285
286 return (jobInfo.LimitFlags & NativeHelpers.JOB_OBJECT_LIMIT_BREAKAWAY_OK) != 0;
287 }
288
289 public static ProcessInformation CreateAsyncProcess(
290 string applicationName,
291 string commandLine,
292 SafeHandle stdin,
293 SafeHandle stdout,
294 SafeHandle stderr,
295 SafeHandle mutexHandle,
296 SafeHandle parentProcess,
297 StreamReader stdoutReader,
298 StreamReader stderrReader)
299 {
300 StringBuilder commandLineBuffer = new StringBuilder(commandLine);
301 int creationFlags = NativeHelpers.CREATE_NEW_CONSOLE |
302 NativeHelpers.CREATE_SUSPENDED |
303 NativeHelpers.CREATE_UNICODE_ENVIRONMENT |
304 NativeHelpers.EXTENDED_STARTUPINFO_PRESENT;
305 if (parentProcess == null)
306 {
307 creationFlags |= NativeHelpers.CREATE_BREAKAWAY_FROM_JOB;
308 }
309
310 NativeHelpers.STARTUPINFOEX si = new NativeHelpers.STARTUPINFOEX();
311 si.startupInfo.cb = Marshal.SizeOf(typeof(NativeHelpers.STARTUPINFOEX));
312 si.startupInfo.dwFlags = NativeHelpers.STARTF_USESHOWWINDOW | NativeHelpers.STARTF_USESTDHANDLES;
313 si.startupInfo.wShowWindow = NativeHelpers.SW_HIDE;
314 si.startupInfo.hStdInput = stdin.DangerousGetHandle();
315 si.startupInfo.hStdOutput = stdout.DangerousGetHandle();
316 si.startupInfo.hStdError = stderr.DangerousGetHandle();
317
318 int attrCount = 1;
319 IntPtr rawParentProcessHandle = IntPtr.Zero;
320 if (parentProcess != null)
321 {
322 attrCount++;
323 rawParentProcessHandle = parentProcess.DangerousGetHandle();
324 }
325
326 using (SafeProcThreadAttrList attrList = CreateProcThreadAttribute(attrCount))
327 {
328 si.lpAttributeList = attrList.DangerousGetHandle();
329
330 IntPtr[] handlesToInherit = new IntPtr[4]
331 {
332 stdin.DangerousGetHandle(),
333 stdout.DangerousGetHandle(),
334 stderr.DangerousGetHandle(),
335 mutexHandle.DangerousGetHandle()
336 };
337 unsafe
338 {
339 fixed (IntPtr* handlesToInheritPtr = &handlesToInherit[0])
340 {
341 UpdateProcThreadAttribute(
342 attrList,
343 NativeHelpers.PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
344 handlesToInheritPtr,
345 IntPtr.Size * 4);
346
347 if (rawParentProcessHandle != IntPtr.Zero)
348 {
349 UpdateProcThreadAttribute(
350 attrList,
351 NativeHelpers.PROC_THREAD_ATTRIBUTE_PARENT_PROCESS,
352 &rawParentProcessHandle,
353 IntPtr.Size);
354 }
355
356 NativeHelpers.PROCESS_INFORMATION pi = new NativeHelpers.PROCESS_INFORMATION();
357 bool res = NativeMethods.CreateProcessW(
358 applicationName,
359 commandLineBuffer,
360 IntPtr.Zero,
361 IntPtr.Zero,
362 true,
363 (int)creationFlags,
364 IntPtr.Zero,
365 IntPtr.Zero,
366 ref si,
367 out pi);
368 if (!res)
369 {
370 throw new Win32Exception("CreateProcessW() failed");
371 }
372
373 return new ProcessInformation(
374 new SafeWaitHandle(pi.hProcess, true),
375 new SafeWaitHandle(pi.hThread, true),
376 pi.dwProcessId,
377 pi.dwThreadId,
378 Task.Run(() => stdoutReader.ReadToEnd()),
379 Task.Run(() => stderrReader.ReadToEnd()));
380 }
381 }
382 }
383 }
384
385 public static SafeWaitHandle CreateInheritableEvent()
386 {
387 NativeHelpers.SECURITY_ATTRIBUTES sa = new NativeHelpers.SECURITY_ATTRIBUTES();
388 sa.nLength = Marshal.SizeOf(sa);
389 sa.bInheritHandle = 1;
390
391 IntPtr hEvent = NativeMethods.CreateEventW(ref sa, true, false, IntPtr.Zero);
392 if (hEvent == IntPtr.Zero)
393 {
394 throw new Win32Exception("CreateEventW() failed");
395 }
396 return new SafeWaitHandle(hEvent, true);
397 }
398
399 public static SafeHandle DuplicateHandleToProcess(
400 SafeHandle handle,
401 SafeHandle targetProcess)
402 {
403 IntPtr targetHandle;
404 bool res = NativeMethods.DuplicateHandle(
405 NativeMethods.GetCurrentProcess(),
406 handle.DangerousGetHandle(),
407 targetProcess.DangerousGetHandle(),
408 out targetHandle,
409 0,
410 true,
411 NativeHelpers.DUPLICATE_SAME_ACCESS);
412 if (!res)
413 {
414 throw new Win32Exception("DuplicateHandle() failed");
415 }
416
417 // This will not dispose the handle, it is assumed
418 // the caller will close it manually with CloseHandleInProcess.
419 return new SafeWaitHandle(targetHandle, false);
420 }
421
422 public static void CloseHandleInProcess(
423 SafeHandle handle,
424 SafeHandle targetProcess)
425 {
426 IntPtr _ = IntPtr.Zero;
427 bool res = NativeMethods.DuplicateHandle(
428 targetProcess.DangerousGetHandle(),
429 handle.DangerousGetHandle(),
430 IntPtr.Zero,
431 out _,
432 0,
433 false,
434 NativeHelpers.DUPLICATE_CLOSE_SOURCE);
435 if (!res)
436 {
437 throw new Win32Exception("DuplicateHandle() failed to close handle");
438 }
439 }
440
441 public static int GetProcessExitCode(SafeHandle process)
442 {
443 int exitCode;
444 bool res = NativeMethods.GetExitCodeProcess(process.DangerousGetHandle(), out exitCode);
445 if (!res)
446 {
447 throw new Win32Exception("GetExitCodeProcess() failed");
448 }
449 return exitCode;
450 }
451
452 public static SafeHandle OpenProcessAsParent(int processId)
453 {
454 IntPtr hProcess = NativeMethods.OpenProcess(
455 NativeHelpers.PROCESS_DUP_HANDLE | NativeHelpers.PROCESS_CREATE_PROCESS,
456 false,
457 processId);
458 if (hProcess == IntPtr.Zero)
459 {
460 throw new Win32Exception("OpenProcess() failed");
461 }
462 return new SafeWaitHandle(hProcess, true);
463 }
464
465 public static void ResumeThread(SafeHandle thread)
466 {
467 int res = NativeMethods.ResumeThread(thread.DangerousGetHandle());
468 if (res == -1)
469 {
470 throw new Win32Exception("ResumeThread() failed");
471 }
472 }
473
474 private static SafeProcThreadAttrList CreateProcThreadAttribute(int count)
475 {
476 IntPtr attrSize = IntPtr.Zero;
477 NativeMethods.InitializeProcThreadAttributeList(IntPtr.Zero, count, 0, ref attrSize);
478
479 IntPtr attributeList = Marshal.AllocHGlobal((int)attrSize);
480 try
481 {
482 if (!NativeMethods.InitializeProcThreadAttributeList(attributeList, count, 0, ref attrSize))
483 {
484 throw new Win32Exception("InitializeProcThreadAttributeList() failed");
485 }
486
487 return new SafeProcThreadAttrList(attributeList);
488 }
489 catch
490 {
491 Marshal.FreeHGlobal(attributeList);
492 throw;
493 }
494 }
495
496 private static unsafe void UpdateProcThreadAttribute(
497 SafeProcThreadAttrList attributeList,
498 int attribute,
499 void* value,
500 int size)
501 {
502 bool res = NativeMethods.UpdateProcThreadAttribute(
503 attributeList,
504 0,
505 (UIntPtr)attribute,
506 value,
507 (UIntPtr)size,
508 IntPtr.Zero,
509 IntPtr.Zero);
510 if (!res)
511 {
512 string msg = string.Format("UpdateProcThreadAttribute() failed to set attribute 0x{0:X8}", attribute);
513 throw new Win32Exception(msg);
514 }
515 }
516 }
517 }