-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConsoleProcess.cs
More file actions
631 lines (539 loc) · 21.6 KB
/
ConsoleProcess.cs
File metadata and controls
631 lines (539 loc) · 21.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
using System;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
namespace ShellRunner
{
/*
* This file contains the ConsoleProcess and related classes.
*/
/// <summary>
/// ConsoleProcess. Controller class for console applications.
/// </summary>
class ConsoleProcess
{
#region "Windows 32 API"
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
/*
* Problem: this structure is used differently from its documentation.
* ExitStatus, UniqueProcessID and InheritedFromUniqueProcessID all contain real values,
* but are documented as pointers (IntPtr).
*
* Therefore, we have to declare two versions of the structures
* and two versions of the NTDLL entry point, one for each structure.
*
* This works, but is utterly unelegant!
*/
// 32-bit version of PROCESS_BASIC_INFORMATION.
// All pointers are Int32 (or IntPtr)
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_BASIC_INFORMATION_32
{
public Int32 ExitStatus; // PVOID
public IntPtr PebBaseAddress; // PPEB
public Int32 AffinityMask; // PVOID
public Int32 BasePriority; // PVOID
public UInt32 UniqueProcessId; // ULONG_PTR
public UInt32 InheritedFromUniqueProcessId; // PVOID
}
// 64-bit version of PROCESS_BASIC_INFORMATION.
// All pointers are Int64 (or IntPtr)
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_BASIC_INFORMATION_64
{
public Int64 ExitStatus; // PVOID
public IntPtr PebBaseAddress; // PPEB
public Int64 AffinityMask; // PVOID
public Int64 BasePriority; // PVOID
public UInt64 UniqueProcessId; // ULONG_PTR
public UInt64 InheritedFromUniqueProcessId; // PVOID
}
[StructLayout(LayoutKind.Sequential)]
private struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
private struct SECURITY_ATTRIBUTES
{
public int length;
public IntPtr lpSecurityDescriptor;
public uint bInheritHandle;
}
[DllImport("kernel32.dll")]
static extern uint CreateProcess(
string lpApplicationName,
string lpCommandLine,
/* ref SECURITY_ATTRIBUTES */ IntPtr lpProcessAttributes,
/* ref SECURITY_ATTRIBUTES */ IntPtr lpThreadAttributes,
uint bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation
);
[DllImport("kernel32.dll")]
static extern uint FreeConsole();
[DllImport("kernel32.dll")]
static extern uint AttachConsole(uint dwProcessID);
[DllImport("kernel32.dll")]
static extern uint ResumeThread(IntPtr hThread);
[DllImport("kernel32.dll")]
static extern uint CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, ref SECURITY_ATTRIBUTES sattr, uint size);
[DllImport("kernel32.dll")]
static extern uint SetHandleInformation(IntPtr hHandle, uint mask, uint flags);
[DllImport("kernel32.dll")]
static extern uint CloseHandle(IntPtr hHandle);
[DllImport("kernel32.dll")]
static extern uint ReadFile(IntPtr handle, byte[] buffer, uint bufsize, out uint dwRead, IntPtr OverlappedRead);
[DllImport("kernel32.dll")]
static extern uint WriteFile(IntPtr handle, byte[] buffer, uint bufsize, out uint dwWritten, IntPtr OverlappedRead);
[DllImport("kernel32.dll")]
static extern uint WaitForMultipleObjects(uint count, ref IntPtr handles, short waitAll, uint dwMilliSeconds);
[DllImport("kernel32.dll")]
static extern uint GetExitCodeProcess(IntPtr hProcess, out int exitCode);
[DllImport("kernel32.dll")]
static extern uint TerminateProcess(IntPtr hProcess, int exitCode);
[DllImport("kernel32.dll")]
static extern uint TerminateThread(IntPtr hThread, int exitCode);
// 32-bit version of NtQueryInformationProcess
[DllImport("ntdll.dll", EntryPoint = "NtQueryInformationProcess")]
static extern int NtQueryInformationProcess32(IntPtr hProcess, int processInformationClass /* 0 */,
ref PROCESS_BASIC_INFORMATION_32 processBasicInformation, int processInformationLength, out uint returnLength);
// 64-bit version of NtQueryInformationProcess
[DllImport("ntdll.dll", EntryPoint = "NtQueryInformationProcess")]
static extern int NtQueryInformationProcess64(IntPtr hProcess, int processInformationClass /* 0 */,
ref PROCESS_BASIC_INFORMATION_64 processBasicInformation, int processInformationLength, out uint returnLength);
#endregion
// The name of the command to execute
private string commandFileName;
// The default timeout (infinite) in milliseconds
private uint timeout = 0xFFFFFFFF;
// The results of reading standard output and standard error
// Available during execution as well as afterwards
private StringBuilder standardOutput;
private StringBuilder standardError;
// The currently running process
// private Process runningProcess;
private PROCESS_INFORMATION processInformation = new PROCESS_INFORMATION();
// Handles to pipes
private IntPtr hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr, hChildStdErrorRd, hChildStdErrorWr;
private string currentOutputLine;
private string currentErrorLine;
// Read buffer size
private const int BUFSIZE = 1;
/// <summary>
/// Delegate for the OnOutputReceived and OnErrorReceived events
/// </summary>
public delegate void OutputReceivedHandler(object sender, string output);
/// <summary>
/// Raised when output is available on standard output
/// </summary>
public event OutputReceivedHandler OnOutputReceived;
private void RaiseOnOutputReceived(string output)
{
if (this.OnOutputReceived != null)
this.OnOutputReceived(this, output);
}
/// <summary>
/// Raised when output is available on standard error
/// </summary>
public event OutputReceivedHandler OnErrorReceived;
private void RaiseOnErrorReceived(string output)
{
if (this.OnErrorReceived != null)
this.OnErrorReceived(this, output);
}
/// <summary>
/// Property CommandFileName (string). The file name of the console executable.
/// Must include a path if not in PATH.
/// </summary>
public string CommandFileName
{
get
{
return this.commandFileName;
}
set
{
this.commandFileName = value;
}
}
/// <summary>
/// Property Timeout (int). Get/Set the timeout in ms
/// </summary>
public uint Timeout
{
get
{
return this.timeout;
}
set
{
this.timeout = value;
}
}
/// <summary>
/// Execute a console command in a hidden window with a timeout and standard input feed
/// <param name="commandline">The command line to ecexute</param>
/// <param name="timeoutMilliSeconds">A timeout in milliseconds.</param>
/// <param name="standardInput">The string to feed to standard input of the process</param>
/// <param name="currentDir">The current directory for the process</param>
/// <returns>The exit code of the process</returns>
/// </summary>
public int ExecuteCommand(string commandline, uint timeoutMilliSeconds, string standardInput, string currentDir)
{
if (this.processInformation.hProcess != IntPtr.Zero)
throw new ApplicationException("Cannot execute a command when another command is still executing");
try
{
// Create security attributes to be able to set pipes to NO INHERIT
SECURITY_ATTRIBUTES saAttr = new SECURITY_ATTRIBUTES();
saAttr.length = Marshal.SizeOf(saAttr);
saAttr.bInheritHandle = 1; // true
saAttr.lpSecurityDescriptor = IntPtr.Zero;
// Create a pipe for the child process's STDIN.
if (CreatePipe(out this.hChildStdinRd, out this.hChildStdinWr, ref saAttr, 0) == 0)
throw new ApplicationException("Could not redirect stdin");
// Ensure the write handle to the pipe for STDIN is not inherited.
SetHandleInformation(this.hChildStdinWr, 1 /* HANDLE_FLAG_INHERIT */, 0);
// Create a pipe for the child process's STDOUT.
if (CreatePipe(out this.hChildStdoutRd, out this.hChildStdoutWr, ref saAttr, 0) == 0)
throw new ApplicationException("Could not redirect stdout");
// Ensure the read handle to the pipe for STDOUT is not inherited.
SetHandleInformation(hChildStdoutRd, 1 /* HANDLE_FLAG_INHERIT */, 0);
// Create a pipe for the child process's STDERR.
if (CreatePipe(out this.hChildStdErrorRd, out this.hChildStdErrorWr, ref saAttr, 0) == 0)
throw new ApplicationException("Could not redirect stderr");
// Ensure the write handle to the pipe for STDIN is not inherited.
SetHandleInformation(this.hChildStdErrorRd, 1 /* HANDLE_FLAG_INHERIT */, 0);
// Now create the child process in a suspended state
// with handles redirected to pipes
STARTUPINFO si = new STARTUPINFO();
si.cb = (uint)Marshal.SizeOf(si);
si.hStdInput = this.hChildStdinRd;
si.hStdOutput = this.hChildStdoutWr;
si.hStdError = this.hChildStdErrorWr;
si.dwFlags |= 0x100; /* STARTF_USESTDHANDLES; */
si.wShowWindow = 0;
this.processInformation = new PROCESS_INFORMATION();
string effectiveCommandLine = "\"" + CommandFileName + "\"";
if (!string.IsNullOrEmpty(commandline))
effectiveCommandLine += " " + commandline;
if (CreateProcess(
CommandFileName,
effectiveCommandLine,
IntPtr.Zero, /* process attributes */
IntPtr.Zero, /* thread attributes */
1 /* true */, /* inherit handles */
4 /* suspended*/ | 0x08000000 /* CREATE_NO_WINDOW */,
IntPtr.Zero, /* environment */
currentDir, /* current dir */
ref si, /* Startup-info */
out this.processInformation)
== 0)
throw new ApplicationException("Could not create process");
// Close the write end of the pipes before reading from the
// read end of the pipes.
if (CloseHandle(hChildStdoutWr) == 0)
throw new ApplicationException("Could not close stdout");
if (CloseHandle(hChildStdErrorWr) == 0)
throw new ApplicationException("Could not close stderr");
this.standardOutput = new StringBuilder();
this.standardError = new StringBuilder();
this.currentOutputLine = "";
this.currentErrorLine = "";
// Start a new thread to write to standard input if necessary
Thread standardInputWriter = null;
if (standardInput != null)
{
// Print to standard input:
standardInputWriter = new Thread(new ParameterizedThreadStart(WriteStandardInput));
standardInputWriter.Start(standardInput);
}
// Start two new threads to read standard output and standard error on the process
// Create the 'standard output reader' thread
Thread standardOutputReader = new Thread(new ThreadStart(ReadStandardOutput));
standardOutputReader.Start();
// Create the 'standard error reader' thread
Thread standardErrorReader = new Thread(new ThreadStart(ReadStandardError));
standardErrorReader.Start();
// Resume the thread, i.e. start the process
ResumeThread(this.processInformation.hThread);
// Wait for the process to end
switch (WaitForMultipleObjects(1,
ref this.processInformation.hProcess,
1 /* true */,
timeoutMilliSeconds)
)
{
case 0:
// The process ended normally, or it was Terminate()d
break;
case 0x102: // There was a timeout
TerminateThread(this.processInformation.hThread, -1);
TerminateProcess(this.processInformation.hProcess, -1);
break;
default:
// This is unexpected!
break;
}
// Wait for the two threads to rejoin:
standardOutputReader.Join();
standardErrorReader.Join();
// Kill the standard input writer at the end of the process
if (standardInputWriter != null)
{
standardInputWriter.Abort();
}
// Return exit code of the process
int exitCode;
if (GetExitCodeProcess(this.processInformation.hProcess, out exitCode) == 0)
throw new ApplicationException("Could not retrieve exit code");
return exitCode;
}
finally
{
// Clean up when exception happens
if (this.processInformation.hProcess != IntPtr.Zero)
CloseHandle(this.processInformation.hProcess);
if (this.processInformation.hThread != IntPtr.Zero)
CloseHandle(this.processInformation.hThread);
// Reset the running process
this.processInformation = new PROCESS_INFORMATION();
}
}
/// <summary>
/// Execute a console command in a hidden window with a timeout and standard input feed
/// <param name="commandline">The command line to ecexute</param>
/// <param name="timeoutMilliSeconds">A timeout in milliseconds.</param>
/// <param name="standardInput">The string to feed to standard input of the process</param>
/// <returns>The exit code of the process</returns>
/// </summary>
public int ExecuteCommand(string commandline, uint timeoutMilliSeconds, string standardInput)
{
return ExecuteCommand(commandline, timeoutMilliSeconds, standardInput, null);
}
/// <summary>
/// Execute a console command in a hidden window
/// </summary>
/// <param name="commandline">The command line to ecexute</param>
/// <param name="timeoutMilliSeconds">A timeout in milliseconds.</param>
/// <returns>The exit code of the process</returns>
public int ExecuteCommand(string commandline, uint timeoutMilliSeconds)
{
return ExecuteCommand(commandline, timeoutMilliSeconds, null);
}
/// <summary>
/// Execute a console command with a default timeout
/// </summary>
/// <param name="commandline"></param>
/// <returns></returns>
public int ExecuteCommand(string commandline)
{
return ExecuteCommand(commandline, this.timeout);
}
/// <summary>
/// Force the command to end with an exit code
/// </summary>
/// <param name="exitCode"></param>
public void Terminate(int exitCode)
{
if (this.processInformation.hProcess == IntPtr.Zero)
throw new ApplicationException("Process is not running");
// Terminate the process TREE here
TerminateProcessTree(this.processInformation.hProcess, this.processInformation.dwProcessId, exitCode);
}
/// <summary>
/// Terminate a process tree
/// </summary>
/// <param name="hProcess">The handle of the process</param>
/// <param name="processID">The ID of the process. Passed as UInt64 to make sure it works in both 32- and 64-bit environments</param>
/// <param name="exitCode">The exit code of the process</param>
public void TerminateProcessTree(IntPtr hProcess, UInt64 processID, int exitCode)
{
Process[] processes = Process.GetProcesses();
// Retrieve all processes on the system
foreach (Process p in processes)
{
try
{
// Get some basic information about the process
if (IntPtr.Size == 4)
{
// 32-bit
PROCESS_BASIC_INFORMATION_32 pbi = new PROCESS_BASIC_INFORMATION_32();
uint bytesWritten;
NtQueryInformationProcess32(p.Handle,
0, ref pbi, Marshal.SizeOf(pbi),
out bytesWritten); // == 0 is OK
// Is it a child process of the process we're trying to terminate?
if (pbi.InheritedFromUniqueProcessId == processID)
// The terminate the child process and its child processes
TerminateProcessTree(p.Handle, pbi.UniqueProcessId, exitCode);
}
else
{
// 64-bit
PROCESS_BASIC_INFORMATION_64 pbi = new PROCESS_BASIC_INFORMATION_64();
uint bytesWritten;
NtQueryInformationProcess64(p.Handle,
0, ref pbi, Marshal.SizeOf(pbi),
out bytesWritten); // == 0 is OK
// Is it a child process of the process we're trying to terminate?
if (pbi.InheritedFromUniqueProcessId == processID)
// The terminate the child process and its child processes
TerminateProcessTree(p.Handle, pbi.UniqueProcessId, exitCode);
}
}
catch (Exception /* ex */)
{
// Ignore, most likely 'Access Denied'
}
}
// Finally, termine the process itself:
TerminateProcess(hProcess, exitCode);
}
/// <summary>
/// Property StandardOutput (string).
/// Returns the result of the command execution
/// </summary>
public string StandardOutput
{
get
{
lock (this)
{
return this.standardOutput.ToString();
}
}
}
/// <summary>
/// Property StandardError (string).
/// Returns the error result of the command execution
/// </summary>
public string StandardError
{
get
{
lock (this)
{
return this.standardError.ToString();
}
}
}
/// <summary>
/// Write a string to standard input of the process.
/// This method is called on its own thread
/// </summary>
/// <param name="input">The string to write to standard input</param>
private void WriteStandardInput(object input)
{
string standardInput = (string)input;
byte[] buf = Encoding.Default.GetBytes(standardInput);
uint dwWritten;
WriteFile(hChildStdinWr, buf, (uint)buf.Length, out dwWritten, IntPtr.Zero);
CloseHandle(hChildStdinWr);
}
/// <summary>
/// Read standard output of the process.
/// This method is called on its own thread
/// </summary>
private void ReadStandardOutput()
{
uint dwRead;
byte[] chBuf = new byte[BUFSIZE];
for (; ; )
{
if (ReadFile(hChildStdoutRd, chBuf, BUFSIZE, out dwRead, IntPtr.Zero) == 0)
break;
if (dwRead != 0)
{
string output = Encoding.Default.GetString(chBuf, 0, (int)dwRead);
this.currentOutputLine += output;
lock (this)
{
int p;
while ((p = this.currentOutputLine.IndexOf("\r\n")) >= 0)
{
string line = this.currentOutputLine.Substring(0, p);
if (line.Length > 0)
this.RaiseOnOutputReceived(line);
if (p + 2 >= this.currentOutputLine.Length)
{
this.currentOutputLine = "";
break;
}
else
this.currentOutputLine = this.currentOutputLine.Substring(p + 2);
}
}
this.standardOutput.Append(output);
}
}
}
/// <summary>
/// Read standard error output of the process.
/// This method is called on its own thread
/// </summary>
private void ReadStandardError()
{
uint dwRead;
byte[] chBuf = new byte[BUFSIZE];
for (; ; )
{
if (ReadFile(hChildStdErrorRd, chBuf, BUFSIZE, out dwRead, IntPtr.Zero) == 0)
break;
if (dwRead != 0)
{
string error = System.Text.Encoding.Default.GetString(chBuf, 0, (int)dwRead);
this.currentErrorLine += error;
lock (this)
{
int p;
while ((p = this.currentErrorLine.IndexOf("\r\n")) >= 0)
{
string line = this.currentErrorLine.Substring(0, p);
if (line.Length > 0)
this.RaiseOnErrorReceived(line);
if (p + 2 >= this.currentErrorLine.Length)
{
this.currentErrorLine = "";
break;
}
else
this.currentErrorLine = this.currentErrorLine.Substring(p + 2);
}
}
this.standardError.Append(error);
}
}
}
}
}