Code:
/ Dotnetfx_Win7_3.5.1 / Dotnetfx_Win7_3.5.1 / 3.5.1 / DEVDIV / depot / DevDiv / releases / whidbey / NetFXspW7 / ndp / fx / src / CompMod / System / CodeDOM / Compiler / Executor.cs / 1 / Executor.cs
//------------------------------------------------------------------------------ //// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------------- namespace System.CodeDom.Compiler { using System.Diagnostics; using System; using System.ComponentModel; using System.Text; using System.Threading; using System.IO; using System.Collections; using System.Collections.Specialized; using System.Reflection; using System.Runtime.InteropServices; using System.CodeDom; using System.Security; using System.Security.Permissions; using System.Security.Principal; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////// [PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")] [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")] public sealed class Executor { // How long (in milliseconds) do we wait for the program to terminate private const int ProcessTimeOut = 600000; private Executor() { } ////// Provides command execution functions for the CodeDom compiler. /// ////// internal static string GetRuntimeInstallDirectory() { return RuntimeEnvironment.GetRuntimeDirectory(); } private static FileStream CreateInheritedFile(string file) { return new FileStream(file, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable); } ////// Gets the runtime install directory. /// ////// public static void ExecWait(string cmd, TempFileCollection tempFiles) { string outputName = null; string errorName = null; ExecWaitWithCapture(null, cmd, tempFiles, ref outputName, ref errorName); } ////// public static int ExecWaitWithCapture(string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName) { return ExecWaitWithCapture(null, cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null); } ///[To be supplied.] ////// public static int ExecWaitWithCapture(string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) { return ExecWaitWithCapture(null, cmd, currentDir, tempFiles, ref outputName, ref errorName, null); } ///[To be supplied.] ////// public static int ExecWaitWithCapture(IntPtr userToken, string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName) { return ExecWaitWithCapture(new SafeUserTokenHandle(userToken, false), cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null); } ///[To be supplied.] ////// public static int ExecWaitWithCapture(IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) { return ExecWaitWithCapture(new SafeUserTokenHandle(userToken, false), cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null); } ///[To be supplied.] ////// internal static int ExecWaitWithCapture(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) { int retValue = 0; // Undo any current impersonation, call ExecWaitWithCaptureUnimpersonated, and reimpersonate #if !FEATURE_PAL // the extra try-catch is here to mitigate exception filter injection attacks. try { WindowsImpersonationContext impersonation = RevertImpersonation(); try { #endif // Execute the process retValue = ExecWaitWithCaptureUnimpersonated(userToken, cmd, currentDir, tempFiles, ref outputName, ref errorName, trueCmdLine); #if !FEATURE_PAL } finally { ReImpersonate(impersonation); } } catch { throw; } #endif return retValue; } private static unsafe int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) { IntSecurity.UnmanagedCode.Demand(); FileStream output; FileStream error; int retValue = 0; if (outputName == null || outputName.Length == 0) outputName = tempFiles.AddExtension("out"); if (errorName == null || errorName.Length == 0) errorName = tempFiles.AddExtension("err"); // Create the files output = CreateInheritedFile(outputName); error = CreateInheritedFile(errorName); bool success = false; SafeNativeMethods.PROCESS_INFORMATION pi = new SafeNativeMethods.PROCESS_INFORMATION(); SafeProcessHandle procSH = new SafeProcessHandle(); SafeThreadHandle threadSH = new SafeThreadHandle(); SafeUserTokenHandle primaryToken = null; try { // Output the command line... StreamWriter sw = new StreamWriter(output, Encoding.UTF8); sw.Write(currentDir); sw.Write("> "); // 'true' command line is used in case the command line points to // a response file sw.WriteLine(trueCmdLine != null ? trueCmdLine : cmd); sw.WriteLine(); sw.WriteLine(); sw.Flush(); NativeMethods.STARTUPINFO si = new NativeMethods.STARTUPINFO(); si.cb = Marshal.SizeOf(si); #if FEATURE_PAL si.dwFlags = NativeMethods.STARTF_USESTDHANDLES; #else //!FEATURE_PAL si.dwFlags = NativeMethods.STARTF_USESTDHANDLES | NativeMethods.STARTF_USESHOWWINDOW; si.wShowWindow = NativeMethods.SW_HIDE; #endif //!FEATURE_PAL si.hStdOutput = output.SafeFileHandle; si.hStdError = error.SafeFileHandle; si.hStdInput = new SafeFileHandle(UnsafeNativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE), false); // // Prepare the environment // #if PLATFORM_UNIX StringDictionary environment = new CaseSensitiveStringDictionary(); #else StringDictionary environment = new StringDictionary (); #endif // PLATFORM_UNIX // Add the current environment foreach ( DictionaryEntry entry in Environment.GetEnvironmentVariables () ) environment.Add ( (string) entry.Key, (string) entry.Value ); // Add the flag to indicate restricted security in the process environment["_ClrRestrictSecAttributes"] = "1"; #if DEBUG environment["OANOCACHE"] = "1"; #endif // set up the environment block parameter byte[] environmentBytes = EnvironmentBlock.ToByteArray(environment, false); fixed (byte* environmentBytesPtr = environmentBytes) { IntPtr environmentPtr = new IntPtr((void*)environmentBytesPtr); if (userToken == null || userToken.IsInvalid) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { success = NativeMethods.CreateProcess( null, // String lpApplicationName, new StringBuilder(cmd), // String lpCommandLine, null, // SECURITY_ATTRIBUTES lpProcessAttributes, null, // SECURITY_ATTRIBUTES lpThreadAttributes, true, // bool bInheritHandles, 0, // int dwCreationFlags, environmentPtr, // int lpEnvironment, currentDir, // String lpCurrentDirectory, si, // STARTUPINFO lpStartupInfo, pi); // PROCESS_INFORMATION lpProcessInformation); if ( pi.hProcess!= (IntPtr)0 && pi.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) procSH.InitialSetHandle(pi.hProcess); if ( pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) threadSH.InitialSetHandle(pi.hThread); } } else { #if FEATURE_PAL throw new NotSupportedException(); #else success = SafeUserTokenHandle.DuplicateTokenEx( userToken, NativeMethods.TOKEN_ALL_ACCESS, null, NativeMethods.IMPERSONATION_LEVEL_SecurityImpersonation, NativeMethods.TOKEN_TYPE_TokenPrimary, out primaryToken ); if (success) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { success = NativeMethods.CreateProcessAsUser( primaryToken, // int token, null, // String lpApplicationName, cmd, // String lpCommandLine, null, // SECURITY_ATTRIBUTES lpProcessAttributes, null, // SECURITY_ATTRIBUTES lpThreadAttributes, true, // bool bInheritHandles, 0, // int dwCreationFlags, new HandleRef(null, environmentPtr), // int lpEnvironment, currentDir, // String lpCurrentDirectory, si, // STARTUPINFO lpStartupInfo, pi); // PROCESS_INFORMATION lpProcessInformation); if ( pi.hProcess!= (IntPtr)0 && pi.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) procSH.InitialSetHandle(pi.hProcess); if ( pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) threadSH.InitialSetHandle(pi.hThread); } } #endif // !FEATURE_PAL } } } finally { // Close the file handles if (!success && (primaryToken != null && !primaryToken.IsInvalid)) { primaryToken.Close(); primaryToken = null; } output.Close(); error.Close(); } if (success) { try { int ret = NativeMethods.WaitForSingleObject(procSH, ProcessTimeOut); // Check for timeout if (ret == NativeMethods.WAIT_TIMEOUT) { throw new ExternalException(SR.GetString(SR.ExecTimeout, cmd), NativeMethods.WAIT_TIMEOUT); } if (ret != NativeMethods.WAIT_OBJECT_0) { throw new ExternalException(SR.GetString(SR.ExecBadreturn, cmd), Marshal.GetLastWin32Error()); } // Check the process's exit code int status = NativeMethods.STILL_ACTIVE; if (!NativeMethods.GetExitCodeProcess(procSH, out status)) { throw new ExternalException(SR.GetString(SR.ExecCantGetRetCode, cmd), Marshal.GetLastWin32Error()); } retValue = status; } finally { procSH.Close(); threadSH.Close(); if (primaryToken != null && !primaryToken.IsInvalid) primaryToken.Close(); } } else { throw new ExternalException(SR.GetString(SR.ExecCantExec, cmd), Marshal.GetLastWin32Error()); } return retValue; } #if !FEATURE_PAL internal static WindowsImpersonationContext RevertImpersonation() { new SecurityPermission(SecurityPermissionFlag.ControlPrincipal).Assert(); return WindowsIdentity.Impersonate(new IntPtr(0)); } #endif // !FEATURE_PAL #if !FEATURE_PAL internal static void ReImpersonate(WindowsImpersonationContext impersonation){ impersonation.Undo(); } #endif // !FEATURE_PAL } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. //------------------------------------------------------------------------------ //[To be supplied.] ///// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------------------- namespace System.CodeDom.Compiler { using System.Diagnostics; using System; using System.ComponentModel; using System.Text; using System.Threading; using System.IO; using System.Collections; using System.Collections.Specialized; using System.Reflection; using System.Runtime.InteropServices; using System.CodeDom; using System.Security; using System.Security.Permissions; using System.Security.Principal; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; ////// [PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")] [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")] public sealed class Executor { // How long (in milliseconds) do we wait for the program to terminate private const int ProcessTimeOut = 600000; private Executor() { } ////// Provides command execution functions for the CodeDom compiler. /// ////// internal static string GetRuntimeInstallDirectory() { return RuntimeEnvironment.GetRuntimeDirectory(); } private static FileStream CreateInheritedFile(string file) { return new FileStream(file, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable); } ////// Gets the runtime install directory. /// ////// public static void ExecWait(string cmd, TempFileCollection tempFiles) { string outputName = null; string errorName = null; ExecWaitWithCapture(null, cmd, tempFiles, ref outputName, ref errorName); } ////// public static int ExecWaitWithCapture(string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName) { return ExecWaitWithCapture(null, cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null); } ///[To be supplied.] ////// public static int ExecWaitWithCapture(string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) { return ExecWaitWithCapture(null, cmd, currentDir, tempFiles, ref outputName, ref errorName, null); } ///[To be supplied.] ////// public static int ExecWaitWithCapture(IntPtr userToken, string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName) { return ExecWaitWithCapture(new SafeUserTokenHandle(userToken, false), cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null); } ///[To be supplied.] ////// public static int ExecWaitWithCapture(IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) { return ExecWaitWithCapture(new SafeUserTokenHandle(userToken, false), cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null); } ///[To be supplied.] ////// internal static int ExecWaitWithCapture(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) { int retValue = 0; // Undo any current impersonation, call ExecWaitWithCaptureUnimpersonated, and reimpersonate #if !FEATURE_PAL // the extra try-catch is here to mitigate exception filter injection attacks. try { WindowsImpersonationContext impersonation = RevertImpersonation(); try { #endif // Execute the process retValue = ExecWaitWithCaptureUnimpersonated(userToken, cmd, currentDir, tempFiles, ref outputName, ref errorName, trueCmdLine); #if !FEATURE_PAL } finally { ReImpersonate(impersonation); } } catch { throw; } #endif return retValue; } private static unsafe int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) { IntSecurity.UnmanagedCode.Demand(); FileStream output; FileStream error; int retValue = 0; if (outputName == null || outputName.Length == 0) outputName = tempFiles.AddExtension("out"); if (errorName == null || errorName.Length == 0) errorName = tempFiles.AddExtension("err"); // Create the files output = CreateInheritedFile(outputName); error = CreateInheritedFile(errorName); bool success = false; SafeNativeMethods.PROCESS_INFORMATION pi = new SafeNativeMethods.PROCESS_INFORMATION(); SafeProcessHandle procSH = new SafeProcessHandle(); SafeThreadHandle threadSH = new SafeThreadHandle(); SafeUserTokenHandle primaryToken = null; try { // Output the command line... StreamWriter sw = new StreamWriter(output, Encoding.UTF8); sw.Write(currentDir); sw.Write("> "); // 'true' command line is used in case the command line points to // a response file sw.WriteLine(trueCmdLine != null ? trueCmdLine : cmd); sw.WriteLine(); sw.WriteLine(); sw.Flush(); NativeMethods.STARTUPINFO si = new NativeMethods.STARTUPINFO(); si.cb = Marshal.SizeOf(si); #if FEATURE_PAL si.dwFlags = NativeMethods.STARTF_USESTDHANDLES; #else //!FEATURE_PAL si.dwFlags = NativeMethods.STARTF_USESTDHANDLES | NativeMethods.STARTF_USESHOWWINDOW; si.wShowWindow = NativeMethods.SW_HIDE; #endif //!FEATURE_PAL si.hStdOutput = output.SafeFileHandle; si.hStdError = error.SafeFileHandle; si.hStdInput = new SafeFileHandle(UnsafeNativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE), false); // // Prepare the environment // #if PLATFORM_UNIX StringDictionary environment = new CaseSensitiveStringDictionary(); #else StringDictionary environment = new StringDictionary (); #endif // PLATFORM_UNIX // Add the current environment foreach ( DictionaryEntry entry in Environment.GetEnvironmentVariables () ) environment.Add ( (string) entry.Key, (string) entry.Value ); // Add the flag to indicate restricted security in the process environment["_ClrRestrictSecAttributes"] = "1"; #if DEBUG environment["OANOCACHE"] = "1"; #endif // set up the environment block parameter byte[] environmentBytes = EnvironmentBlock.ToByteArray(environment, false); fixed (byte* environmentBytesPtr = environmentBytes) { IntPtr environmentPtr = new IntPtr((void*)environmentBytesPtr); if (userToken == null || userToken.IsInvalid) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { success = NativeMethods.CreateProcess( null, // String lpApplicationName, new StringBuilder(cmd), // String lpCommandLine, null, // SECURITY_ATTRIBUTES lpProcessAttributes, null, // SECURITY_ATTRIBUTES lpThreadAttributes, true, // bool bInheritHandles, 0, // int dwCreationFlags, environmentPtr, // int lpEnvironment, currentDir, // String lpCurrentDirectory, si, // STARTUPINFO lpStartupInfo, pi); // PROCESS_INFORMATION lpProcessInformation); if ( pi.hProcess!= (IntPtr)0 && pi.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) procSH.InitialSetHandle(pi.hProcess); if ( pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) threadSH.InitialSetHandle(pi.hThread); } } else { #if FEATURE_PAL throw new NotSupportedException(); #else success = SafeUserTokenHandle.DuplicateTokenEx( userToken, NativeMethods.TOKEN_ALL_ACCESS, null, NativeMethods.IMPERSONATION_LEVEL_SecurityImpersonation, NativeMethods.TOKEN_TYPE_TokenPrimary, out primaryToken ); if (success) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { success = NativeMethods.CreateProcessAsUser( primaryToken, // int token, null, // String lpApplicationName, cmd, // String lpCommandLine, null, // SECURITY_ATTRIBUTES lpProcessAttributes, null, // SECURITY_ATTRIBUTES lpThreadAttributes, true, // bool bInheritHandles, 0, // int dwCreationFlags, new HandleRef(null, environmentPtr), // int lpEnvironment, currentDir, // String lpCurrentDirectory, si, // STARTUPINFO lpStartupInfo, pi); // PROCESS_INFORMATION lpProcessInformation); if ( pi.hProcess!= (IntPtr)0 && pi.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) procSH.InitialSetHandle(pi.hProcess); if ( pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) threadSH.InitialSetHandle(pi.hThread); } } #endif // !FEATURE_PAL } } } finally { // Close the file handles if (!success && (primaryToken != null && !primaryToken.IsInvalid)) { primaryToken.Close(); primaryToken = null; } output.Close(); error.Close(); } if (success) { try { int ret = NativeMethods.WaitForSingleObject(procSH, ProcessTimeOut); // Check for timeout if (ret == NativeMethods.WAIT_TIMEOUT) { throw new ExternalException(SR.GetString(SR.ExecTimeout, cmd), NativeMethods.WAIT_TIMEOUT); } if (ret != NativeMethods.WAIT_OBJECT_0) { throw new ExternalException(SR.GetString(SR.ExecBadreturn, cmd), Marshal.GetLastWin32Error()); } // Check the process's exit code int status = NativeMethods.STILL_ACTIVE; if (!NativeMethods.GetExitCodeProcess(procSH, out status)) { throw new ExternalException(SR.GetString(SR.ExecCantGetRetCode, cmd), Marshal.GetLastWin32Error()); } retValue = status; } finally { procSH.Close(); threadSH.Close(); if (primaryToken != null && !primaryToken.IsInvalid) primaryToken.Close(); } } else { throw new ExternalException(SR.GetString(SR.ExecCantExec, cmd), Marshal.GetLastWin32Error()); } return retValue; } #if !FEATURE_PAL internal static WindowsImpersonationContext RevertImpersonation() { new SecurityPermission(SecurityPermissionFlag.ControlPrincipal).Assert(); return WindowsIdentity.Impersonate(new IntPtr(0)); } #endif // !FEATURE_PAL #if !FEATURE_PAL internal static void ReImpersonate(WindowsImpersonationContext impersonation){ impersonation.Undo(); } #endif // !FEATURE_PAL } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007.[To be supplied.] ///
Link Menu
This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- PlaceHolder.cs
- Win32KeyboardDevice.cs
- _AutoWebProxyScriptHelper.cs
- basecomparevalidator.cs
- ComponentResourceManager.cs
- RefreshInfo.cs
- WindowsAuthenticationModule.cs
- CharAnimationUsingKeyFrames.cs
- indexingfiltermarshaler.cs
- DataStorage.cs
- OutgoingWebRequestContext.cs
- RectangleConverter.cs
- GeneralTransform3D.cs
- DbRetry.cs
- MasterPageBuildProvider.cs
- AnimationException.cs
- DeploymentSectionCache.cs
- ViewDesigner.cs
- ComponentChangingEvent.cs
- RootCodeDomSerializer.cs
- Parser.cs
- HttpConfigurationContext.cs
- ZipIOModeEnforcingStream.cs
- WindowsHyperlink.cs
- WebPartDeleteVerb.cs
- StringValidatorAttribute.cs
- IndexedGlyphRun.cs
- RSAOAEPKeyExchangeFormatter.cs
- COMException.cs
- DrawingAttributeSerializer.cs
- DuplicateWaitObjectException.cs
- BookmarkScopeManager.cs
- LowerCaseStringConverter.cs
- FunctionDescription.cs
- IRCollection.cs
- ConstructorNeedsTagAttribute.cs
- DataGridViewCellStateChangedEventArgs.cs
- ParseNumbers.cs
- SortedList.cs
- DataConnectionHelper.cs
- RSAPKCS1SignatureFormatter.cs
- UIElement.cs
- UndirectedGraph.cs
- ServiceTimeoutsElement.cs
- ResolveCriteria11.cs
- CompilationLock.cs
- ProxyElement.cs
- Matrix3D.cs
- SoapCodeExporter.cs
- Exceptions.cs
- XmlException.cs
- LineServicesRun.cs
- HostingEnvironmentException.cs
- MailDefinition.cs
- Win32SafeHandles.cs
- SqlGenerator.cs
- RadioButtonAutomationPeer.cs
- BamlLocalizerErrorNotifyEventArgs.cs
- RoleProviderPrincipal.cs
- MailMessageEventArgs.cs
- Journaling.cs
- ServiceOperationUIEditor.cs
- CombinedGeometry.cs
- BevelBitmapEffect.cs
- InternalBufferOverflowException.cs
- _ScatterGatherBuffers.cs
- DoWhile.cs
- ConfigXmlText.cs
- ApplicationHost.cs
- StrokeCollection2.cs
- AppDomainFactory.cs
- DecimalAnimation.cs
- Inline.cs
- InternalResources.cs
- XmlByteStreamReader.cs
- WSSecurityTokenSerializer.cs
- BaseValidatorDesigner.cs
- TargetControlTypeAttribute.cs
- _ShellExpression.cs
- MsmqQueue.cs
- CommandCollectionEditor.cs
- Membership.cs
- LinkDescriptor.cs
- DynamicResourceExtensionConverter.cs
- MsmqHostedTransportConfiguration.cs
- SqlRemoveConstantOrderBy.cs
- SerializationEventsCache.cs
- QuerySelectOp.cs
- CalloutQueueItem.cs
- Size3D.cs
- ConvertEvent.cs
- Missing.cs
- transactioncontext.cs
- ReferenceAssemblyAttribute.cs
- MimeObjectFactory.cs
- AppSecurityManager.cs
- EdmMember.cs
- Sql8ExpressionRewriter.cs
- Inflater.cs
- ListViewItemCollectionEditor.cs