mscorlib(4.0.0.0) API with additions
Executor.cs
1 using Microsoft.Win32;
2 using Microsoft.Win32.SafeHandles;
3 using System.Collections;
6 using System.Diagnostics;
7 using System.IO;
12 using System.Text;
13 
15 {
17  [PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
18  public static class Executor
19  {
20  private const int ProcessTimeOut = 600000;
21 
22  internal static string GetRuntimeInstallDirectory()
23  {
25  }
26 
27  private static FileStream CreateInheritedFile(string file)
28  {
29  return new FileStream(file, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
30  }
31 
35  public static void ExecWait(string cmd, TempFileCollection tempFiles)
36  {
37  string outputName = null;
38  string errorName = null;
39  ExecWaitWithCapture(cmd, tempFiles, ref outputName, ref errorName);
40  }
41 
48  public static int ExecWaitWithCapture(string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName)
49  {
50  return ExecWaitWithCapture(null, cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null);
51  }
52 
60  public static int ExecWaitWithCapture(string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName)
61  {
62  return ExecWaitWithCapture(null, cmd, currentDir, tempFiles, ref outputName, ref errorName, null);
63  }
64 
72  public static int ExecWaitWithCapture(IntPtr userToken, string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName)
73  {
74  return ExecWaitWithCapture(new SafeUserTokenHandle(userToken, ownsHandle: false), cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null);
75  }
76 
85  public static int ExecWaitWithCapture(IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName)
86  {
87  return ExecWaitWithCapture(new SafeUserTokenHandle(userToken, ownsHandle: false), cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null);
88  }
89 
90  internal static int ExecWaitWithCapture(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine)
91  {
92  int num = 0;
93  try
94  {
95  WindowsImpersonationContext impersonation = RevertImpersonation();
96  try
97  {
98  return ExecWaitWithCaptureUnimpersonated(userToken, cmd, currentDir, tempFiles, ref outputName, ref errorName, trueCmdLine);
99  }
100  finally
101  {
102  ReImpersonate(impersonation);
103  }
104  }
105  catch
106  {
107  throw;
108  }
109  }
110 
111  private unsafe static int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine)
112  {
113  IntSecurity.UnmanagedCode.Demand();
114  int num = 0;
115  if (outputName == null || outputName.Length == 0)
116  {
117  outputName = tempFiles.AddExtension("out");
118  }
119  if (errorName == null || errorName.Length == 0)
120  {
121  errorName = tempFiles.AddExtension("err");
122  }
123  FileStream fileStream = CreateInheritedFile(outputName);
124  FileStream fileStream2 = CreateInheritedFile(errorName);
125  bool flag = false;
126  Microsoft.Win32.SafeNativeMethods.PROCESS_INFORMATION pROCESS_INFORMATION = new Microsoft.Win32.SafeNativeMethods.PROCESS_INFORMATION();
127  SafeProcessHandle safeProcessHandle = new SafeProcessHandle();
128  Microsoft.Win32.SafeHandles.SafeThreadHandle safeThreadHandle = new Microsoft.Win32.SafeHandles.SafeThreadHandle();
129  SafeUserTokenHandle hNewToken = null;
130  try
131  {
132  StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.UTF8);
133  streamWriter.Write(currentDir);
134  streamWriter.Write("> ");
135  streamWriter.WriteLine((trueCmdLine != null) ? trueCmdLine : cmd);
136  streamWriter.WriteLine();
137  streamWriter.WriteLine();
138  streamWriter.Flush();
139  Microsoft.Win32.NativeMethods.STARTUPINFO sTARTUPINFO = new Microsoft.Win32.NativeMethods.STARTUPINFO();
140  sTARTUPINFO.cb = Marshal.SizeOf((object)sTARTUPINFO);
141  sTARTUPINFO.dwFlags = 257;
142  sTARTUPINFO.wShowWindow = 0;
143  sTARTUPINFO.hStdOutput = fileStream.SafeFileHandle;
144  sTARTUPINFO.hStdError = fileStream2.SafeFileHandle;
145  sTARTUPINFO.hStdInput = new SafeFileHandle(Microsoft.Win32.UnsafeNativeMethods.GetStdHandle(-10), ownsHandle: false);
146  StringDictionary stringDictionary = new StringDictionary();
147  foreach (DictionaryEntry environmentVariable in Environment.GetEnvironmentVariables())
148  {
149  stringDictionary[(string)environmentVariable.Key] = (string)environmentVariable.Value;
150  }
151  stringDictionary["_ClrRestrictSecAttributes"] = "1";
152  byte[] array = EnvironmentBlock.ToByteArray(stringDictionary, unicode: false);
153  try
154  {
155  byte[] array2 = array;
156  fixed (byte* value = array2)
157  {
158  IntPtr intPtr = new IntPtr(value);
159  if (userToken == null || userToken.IsInvalid)
160  {
162  try
163  {
164  }
165  finally
166  {
167  flag = Microsoft.Win32.NativeMethods.CreateProcess(null, new StringBuilder(cmd), null, null, bInheritHandles: true, 0, intPtr, currentDir, sTARTUPINFO, pROCESS_INFORMATION);
168  if (pROCESS_INFORMATION.hProcess != (IntPtr)0 && pROCESS_INFORMATION.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
169  {
170  safeProcessHandle.InitialSetHandle(pROCESS_INFORMATION.hProcess);
171  }
172  if (pROCESS_INFORMATION.hThread != (IntPtr)0 && pROCESS_INFORMATION.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
173  {
174  safeThreadHandle.InitialSetHandle(pROCESS_INFORMATION.hThread);
175  }
176  }
177  }
178  else
179  {
180  flag = SafeUserTokenHandle.DuplicateTokenEx(userToken, 983551, null, 2, 1, out hNewToken);
181  if (flag)
182  {
184  try
185  {
186  }
187  finally
188  {
189  flag = Microsoft.Win32.NativeMethods.CreateProcessAsUser(hNewToken, null, cmd, null, null, bInheritHandles: true, 0, new HandleRef(null, intPtr), currentDir, sTARTUPINFO, pROCESS_INFORMATION);
190  if (pROCESS_INFORMATION.hProcess != (IntPtr)0 && pROCESS_INFORMATION.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
191  {
192  safeProcessHandle.InitialSetHandle(pROCESS_INFORMATION.hProcess);
193  }
194  if (pROCESS_INFORMATION.hThread != (IntPtr)0 && pROCESS_INFORMATION.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)
195  {
196  safeThreadHandle.InitialSetHandle(pROCESS_INFORMATION.hThread);
197  }
198  }
199  }
200  }
201  }
202  }
203  finally
204  {
205  }
206  }
207  finally
208  {
209  if (!flag && hNewToken != null && !hNewToken.IsInvalid)
210  {
211  hNewToken.Close();
212  hNewToken = null;
213  }
214  fileStream.Close();
215  fileStream2.Close();
216  }
217  if (flag)
218  {
219  try
220  {
221  ProcessWaitHandle processWaitHandle = null;
222  bool flag2;
223  try
224  {
225  processWaitHandle = new ProcessWaitHandle(safeProcessHandle);
226  flag2 = processWaitHandle.WaitOne(600000, exitContext: false);
227  }
228  finally
229  {
230  processWaitHandle?.Close();
231  }
232  if (!flag2)
233  {
234  throw new ExternalException(SR.GetString("ExecTimeout", cmd), 258);
235  }
236  int exitCode = 259;
237  if (!Microsoft.Win32.NativeMethods.GetExitCodeProcess(safeProcessHandle, out exitCode))
238  {
239  throw new ExternalException(SR.GetString("ExecCantGetRetCode", cmd), Marshal.GetLastWin32Error());
240  }
241  return exitCode;
242  }
243  finally
244  {
245  safeProcessHandle.Close();
246  safeThreadHandle.Close();
247  if (hNewToken != null && !hNewToken.IsInvalid)
248  {
249  hNewToken.Close();
250  }
251  }
252  }
253  int lastWin32Error = Marshal.GetLastWin32Error();
254  if (lastWin32Error == 8)
255  {
256  throw new OutOfMemoryException();
257  }
258  Win32Exception inner = new Win32Exception(lastWin32Error);
259  ExternalException ex = new ExternalException(SR.GetString("ExecCantExec", cmd), inner);
260  throw ex;
261  }
262 
263  [PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
264  [SecurityPermission(SecurityAction.Assert, ControlPrincipal = true, UnmanagedCode = true)]
265  internal static WindowsImpersonationContext RevertImpersonation()
266  {
267  return WindowsIdentity.Impersonate(new IntPtr(0));
268  }
269 
270  internal static void ReImpersonate(WindowsImpersonationContext impersonation)
271  {
272  impersonation.Undo();
273  }
274  }
275 }
Represents a character encoding.To browse the .NET Framework source code for this type,...
Definition: Encoding.cs:15
Describes a set of security permissions applied to code. This class cannot be inherited.
Provides command execution functions for invoking compilers. This class cannot be inherited.
Definition: Executor.cs:18
static int ExecWaitWithCapture(IntPtr userToken, string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName)
Executes the specified command using the specified user token and temporary files,...
Definition: Executor.cs:72
virtual WindowsImpersonationContext Impersonate()
Impersonates the user represented by the T:System.Security.Principal.WindowsIdentity object.
FileMode
Specifies how the operating system should open a file.
Definition: FileMode.cs:8
Implements a hash table with the key and the value strongly typed to be strings rather than objects.
Definition: __Canon.cs:3
static int SizeOf(object structure)
Returns the unmanaged size of an object in bytes.
Definition: Marshal.cs:159
static int ExecWaitWithCapture(string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName)
Executes the specified command using the specified current directory and temporary files,...
Definition: Executor.cs:60
Wraps a managed object holding a handle to a resource that is passed to unmanaged code using platform...
Definition: HandleRef.cs:5
Provides a collection of static methods that return information about the common language runtime env...
static string GetRuntimeDirectory()
Returns the directory where the common language runtime is installed.
void Undo()
Reverts the user context to the Windows user represented by this object.
SecurityAction
Specifies the security actions that can be performed using declarative security.
Implements a T:System.IO.TextWriter for writing characters to a stream in a particular encoding....
Definition: StreamWriter.cs:15
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
virtual void Close()
Closes the current stream and releases any resources (such as sockets and file handles) associated wi...
Definition: Stream.cs:855
Throws an exception for a Win32 error code.
Provides a T:System.IO.Stream for a file, supporting both synchronous and asynchronous read and write...
Definition: FileStream.cs:15
A platform-specific type that is used to represent a pointer or a handle.
Definition: IntPtr.cs:14
static void PrepareConstrainedRegions()
Designates a body of code as a constrained execution region (CER).
Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks,...
Definition: Marshal.cs:15
Represents a mutable string of characters. This class cannot be inherited.To browse the ....
override void Write(char value)
Writes a character to the stream.
static int ExecWaitWithCapture(string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName)
Executes the specified command using the specified temporary files and waits for the call to return,...
Definition: Executor.cs:48
The base exception type for all COM interop exceptions and structured exception handling (SEH) except...
virtual SafeFileHandle SafeFileHandle
Gets a T:Microsoft.Win32.SafeHandles.SafeFileHandle object that represents the operating system file ...
Definition: FileStream.cs:249
FileAccess
Defines constants for read, write, or read/write access to a file.
Definition: FileAccess.cs:9
object Value
Gets or sets the value in the key/value pair.
static void ExecWait(string cmd, TempFileCollection tempFiles)
Executes the command using the specified temporary files and waits for the call to return.
Definition: Executor.cs:35
virtual void WriteLine()
Writes a line terminator to the text string or stream.
Definition: TextWriter.cs:778
static Encoding UTF8
Gets an encoding for the UTF-8 format.
Definition: Encoding.cs:1023
static int ExecWaitWithCapture(IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName)
Executes the specified command using the specified user token, current directory, and temporary files...
Definition: Executor.cs:85
object Key
Gets or sets the key in the key/value pair.
static int GetLastWin32Error()
Returns the error code returned by the last unmanaged function that was called using platform invoke ...
static string CurrentDirectory
Gets or sets the fully qualified path of the current working directory.
Definition: Environment.cs:356
Defines a dictionary key/value pair that can be set or retrieved.
override void Flush()
Clears all buffers for the current writer and causes any buffered data to be written to the underlyin...
Represents a collection of temporary files.
Represents the Windows user prior to an impersonation operation.
FileShare
Contains constants for controlling the kind of access other T:System.IO.FileStream objects can have t...
Definition: FileShare.cs:9
Provides a set of static methods and properties that provide support for compilers....