Example #1
0
        private ProcessThreadTimes GetThreadTimes() {
            ProcessThreadTimes threadTimes = new ProcessThreadTimes();

            SafeThreadHandle threadHandle = null;
            try {
                threadHandle = OpenThreadHandle(NativeMethods.THREAD_QUERY_INFORMATION);

                if (!NativeMethods.GetThreadTimes(threadHandle, 
                    out threadTimes.create, 
                    out threadTimes.exit, 
                    out threadTimes.kernel, 
                    out threadTimes.user)) {
                    throw new Win32Exception();
                }
            }
            finally {
                CloseThreadHandle(threadHandle);
            }

            return threadTimes;
        }
        // This method figures out which values are supposed to go into which structures so that PDH can do the 
        // calculation for us.  This was ported from Window's cutils.c
        private static void FillInValues(CounterSample oldSample, CounterSample newSample, NativeMethods.PDH_RAW_COUNTER oldPdhValue, NativeMethods.PDH_RAW_COUNTER newPdhValue) {
            int newCounterType = (int) newSample.CounterType;

            switch (newCounterType) {
                case NativeMethods.PERF_COUNTER_COUNTER:
                case NativeMethods.PERF_COUNTER_QUEUELEN_TYPE:
                case NativeMethods.PERF_SAMPLE_COUNTER:
                case NativeMethods.PERF_OBJ_TIME_TIMER:
                case NativeMethods.PERF_COUNTER_OBJ_TIME_QUEUELEN_TYPE:
                    newPdhValue.FirstValue  = newSample.RawValue;
                    newPdhValue.SecondValue = newSample.TimeStamp;

                    oldPdhValue.FirstValue  = oldSample.RawValue;
                    oldPdhValue.SecondValue = oldSample.TimeStamp;
                    break;
                
                case NativeMethods.PERF_COUNTER_100NS_QUEUELEN_TYPE:
                    newPdhValue.FirstValue  = newSample.RawValue;
                    newPdhValue.SecondValue = newSample.TimeStamp100nSec;

                    oldPdhValue.FirstValue  = oldSample.RawValue;
                    oldPdhValue.SecondValue = oldSample.TimeStamp100nSec;
                    break;
                
                case NativeMethods.PERF_COUNTER_TIMER:
                case NativeMethods.PERF_COUNTER_TIMER_INV:
                case NativeMethods.PERF_COUNTER_BULK_COUNT:
                case NativeMethods.PERF_COUNTER_LARGE_QUEUELEN_TYPE:
                case NativeMethods.PERF_COUNTER_MULTI_TIMER:
                case NativeMethods.PERF_COUNTER_MULTI_TIMER_INV:
                    newPdhValue.FirstValue  = newSample.RawValue;
                    newPdhValue.SecondValue = newSample.TimeStamp;

                    oldPdhValue.FirstValue  = oldSample.RawValue;
                    oldPdhValue.SecondValue = oldSample.TimeStamp;
                    if (newCounterType == NativeMethods.PERF_COUNTER_MULTI_TIMER || newCounterType == NativeMethods.PERF_COUNTER_MULTI_TIMER_INV) {
                        //  this is to make PDH work like PERFMON for
                        //  this counter type
                        newPdhValue.FirstValue *= (uint) newSample.CounterFrequency;
                        if (oldSample.CounterFrequency != 0) {
                            oldPdhValue.FirstValue *= (uint) oldSample.CounterFrequency;
                        }
                    }

                    if ((newCounterType & NativeMethods.PERF_MULTI_COUNTER) == NativeMethods.PERF_MULTI_COUNTER) {
                            newPdhValue.MultiCount = (int) newSample.BaseValue;
                            oldPdhValue.MultiCount = (int) oldSample.BaseValue;
                    }
                    
                        
                    break;
                //
                //  These counters do not use any time reference
                //
                case NativeMethods.PERF_COUNTER_RAWCOUNT:
                case NativeMethods.PERF_COUNTER_RAWCOUNT_HEX:
                case NativeMethods.PERF_COUNTER_DELTA:
                case NativeMethods.PERF_COUNTER_LARGE_RAWCOUNT:
                case NativeMethods.PERF_COUNTER_LARGE_RAWCOUNT_HEX:
                case NativeMethods.PERF_COUNTER_LARGE_DELTA:
                    newPdhValue.FirstValue  = newSample.RawValue;
                    newPdhValue.SecondValue = 0;

                    oldPdhValue.FirstValue  = oldSample.RawValue;
                    oldPdhValue.SecondValue = 0;
                    break;
                //
                //  These counters use the 100 Ns time base in thier calculation
                //
                case NativeMethods.PERF_100NSEC_TIMER:
                case NativeMethods.PERF_100NSEC_TIMER_INV:
                case NativeMethods.PERF_100NSEC_MULTI_TIMER:
                case NativeMethods.PERF_100NSEC_MULTI_TIMER_INV:
                    newPdhValue.FirstValue  = newSample.RawValue;
                    newPdhValue.SecondValue = newSample.TimeStamp100nSec;

                    oldPdhValue.FirstValue  = oldSample.RawValue;
                    oldPdhValue.SecondValue = oldSample.TimeStamp100nSec;
                    if ((newCounterType & NativeMethods.PERF_MULTI_COUNTER) == NativeMethods.PERF_MULTI_COUNTER) {
                        newPdhValue.MultiCount = (int) newSample.BaseValue;
                        oldPdhValue.MultiCount = (int) oldSample.BaseValue;
                    }
                    break;
                //
                //  These counters use two data points
                //
                case NativeMethods.PERF_SAMPLE_FRACTION:
                case NativeMethods.PERF_RAW_FRACTION:
                case NativeMethods.PERF_LARGE_RAW_FRACTION:
                case NativeMethods.PERF_PRECISION_SYSTEM_TIMER:
                case NativeMethods.PERF_PRECISION_100NS_TIMER:
                case NativeMethods.PERF_PRECISION_OBJECT_TIMER:
                case NativeMethods.PERF_AVERAGE_TIMER:
                case NativeMethods.PERF_AVERAGE_BULK:
                    newPdhValue.FirstValue = newSample.RawValue;
                    newPdhValue.SecondValue = newSample.BaseValue;

                    oldPdhValue.FirstValue = oldSample.RawValue;
                    oldPdhValue.SecondValue = oldSample.BaseValue;
                    break;
                
                default:
                    // an unidentified counter was returned so
                    newPdhValue.FirstValue  = 0;
                    newPdhValue.SecondValue = 0;

                    oldPdhValue.FirstValue  = 0;
                    oldPdhValue.SecondValue = 0;
                    break;
            }
        }
 static ProcessInfo GetProcessInfo(NativeMethods.PERF_OBJECT_TYPE type, IntPtr instancePtr, NativeMethods.PERF_COUNTER_DEFINITION[] counters) {
     ProcessInfo processInfo = new ProcessInfo();
     for (int i = 0; i < counters.Length; i++) {
         NativeMethods.PERF_COUNTER_DEFINITION counter = counters[i];
         long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset));
         switch ((ValueId)counter.CounterNameTitlePtr) {
             case ValueId.ProcessId:
                 processInfo.processId = (int)value;
                 break;
             case ValueId.HandleCount:
                 processInfo.handleCount = (int)value;
                 break;
             case ValueId.PoolPagedBytes:
                 processInfo.poolPagedBytes = value;
                 break;
             case ValueId.PoolNonpagedBytes:
                 processInfo.poolNonpagedBytes = value;
                 break;
             case ValueId.VirtualBytes:
                 processInfo.virtualBytes = value;
                 break;
             case ValueId.VirtualBytesPeak:
                 processInfo.virtualBytesPeak = value;
                 break;
             case ValueId.WorkingSetPeak:
                 processInfo.workingSetPeak = value;
                 break;
             case ValueId.WorkingSet:
                 processInfo.workingSet = value;
                 break;
             case ValueId.PageFileBytesPeak:
                 processInfo.pageFileBytesPeak = value;
                 break;
             case ValueId.PageFileBytes:
                 processInfo.pageFileBytes = value;
                 break;
             case ValueId.PrivateBytes:
                 processInfo.privateBytes = value;
                 break;
             case ValueId.BasePriority:
                 processInfo.basePriority = (int)value;
                 break;
         }
     }
     return processInfo;
 }
        static ThreadInfo GetThreadInfo(NativeMethods.PERF_OBJECT_TYPE type, IntPtr instancePtr, NativeMethods.PERF_COUNTER_DEFINITION[] counters) {
            ThreadInfo threadInfo = new ThreadInfo();
            for (int i = 0; i < counters.Length; i++) {
                NativeMethods.PERF_COUNTER_DEFINITION counter = counters[i];
                long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset));
                switch ((ValueId)counter.CounterNameTitlePtr) {
                    case ValueId.ProcessId:
                        threadInfo.processId = (int)value;
                        break;
                    case ValueId.ThreadId:
                        threadInfo.threadId = (int)value;
                        break;
                    case ValueId.BasePriority:
                        threadInfo.basePriority = (int)value;
                        break;
                    case ValueId.CurrentPriority:
                        threadInfo.currentPriority = (int)value;
                        break;
                    case ValueId.StartAddress:
                        threadInfo.startAddress = (IntPtr)value;
                        break;
                    case ValueId.ThreadState:
                        threadInfo.threadState = (ThreadState)value;
                        break;
                    case ValueId.ThreadWaitReason:
                        threadInfo.threadWaitReason = GetThreadWaitReason((int)value);
                        break;
                }
            }

            return threadInfo;
        }
Example #5
0
        private void StartRaisingEvents()
        {
            //Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed.
            if (this.disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            try {
                new EnvironmentPermission(PermissionState.Unrestricted).Assert();
                if (Environment.OSVersion.Platform != PlatformID.Win32NT)
                {
                    throw new PlatformNotSupportedException(SR.GetString(SR.WinNTRequired));
                }
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }

            // If we're called when "Initializing" is true, set enabled to true
            if (IsSuspended())
            {
                enabled = true;
                return;
            }

            if (!readGranted)
            {
                string fullPath;
                // Consider asserting path discovery permission here.
                fullPath = System.IO.Path.GetFullPath(directory);

                FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, fullPath);
                permission.Demand();
                readGranted = true;
            }


            // If we're attached, don't do anything.
            if (!IsHandleInvalid)
            {
                return;
            }

            // Create handle to directory being monitored
            directoryHandle = NativeMethods.CreateFile(directory,                               // Directory name
                                                       UnsafeNativeMethods.FILE_LIST_DIRECTORY, // access (read-write) mode
                                                       UnsafeNativeMethods.FILE_SHARE_READ |
                                                       UnsafeNativeMethods.FILE_SHARE_DELETE |
                                                       UnsafeNativeMethods.FILE_SHARE_WRITE,     // share mode
                                                       null,                                     // security descriptor
                                                       UnsafeNativeMethods.OPEN_EXISTING,        // how to create
                                                       UnsafeNativeMethods.FILE_FLAG_BACKUP_SEMANTICS |
                                                       UnsafeNativeMethods.FILE_FLAG_OVERLAPPED, // file attributes
                                                       new SafeFileHandle(IntPtr.Zero, false)    // file with attributes to copy
                                                       );

            if (IsHandleInvalid)
            {
                throw new FileNotFoundException(SR.GetString(SR.FSW_IOError, directory));
            }

            stopListening = false;
            // Start ignoring all events that were initiated before this.
            Interlocked.Increment(ref currentSession);

            // Attach handle to thread pool

            //SECREVIEW: At this point at least FileIOPermission has already been demanded.
            SecurityPermission secPermission = new SecurityPermission(PermissionState.Unrestricted);

            secPermission.Assert();
            try {
                ThreadPool.BindHandle(directoryHandle);
            }
            finally {
                SecurityPermission.RevertAssert();
            }
            enabled = true;

            // Setup IO completion port
            Monitor(null);
        }
        internal CounterDefinitionSample(NativeMethods.PERF_COUNTER_DEFINITION perfCounter, CategorySample categorySample, int instanceNumber) {
            this.NameIndex = perfCounter.CounterNameTitleIndex;
            this.CounterType = perfCounter.CounterType;
            this.offset = perfCounter.CounterOffset;
            this.size = perfCounter.CounterSize;
            if (instanceNumber == -1) {
                this.instanceValues = new long[1];
            }
            else
                this.instanceValues = new long[instanceNumber];

            this.categorySample = categorySample;
        }
 internal CategoryEntry(NativeMethods.PERF_OBJECT_TYPE perfObject) {
     this.NameIndex = perfObject.ObjectNameTitleIndex;
     this.HelpIndex = perfObject.ObjectHelpTitleIndex;
     this.CounterIndexes = new int[perfObject.NumCounters];
     this.HelpIndexes = new int[perfObject.NumCounters];
 }
Example #8
0
        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[(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,                    // IntPtr 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), // IntPtr 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 {
                    bool signaled;
                    ProcessWaitHandle pwh = null;
                    try {
                        pwh      = new ProcessWaitHandle(procSH);
                        signaled = pwh.WaitOne(ProcessTimeOut, false);
                    } finally {
                        if (pwh != null)
                        {
                            pwh.Close();
                        }
                    }

                    // Check for timeout
                    if (!signaled)
                    {
                        throw new ExternalException(SR.GetString(SR.ExecTimeout, cmd), NativeMethods.WAIT_TIMEOUT);
                    }

                    // 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
            {
                int err = Marshal.GetLastWin32Error();
                if (err == NativeMethods.ERROR_NOT_ENOUGH_MEMORY)
                {
                    throw new OutOfMemoryException();
                }

                Win32Exception    win32Exception = new Win32Exception(err);
                ExternalException ex             = new ExternalException(SR.GetString(SR.ExecCantExec, cmd), win32Exception);
                throw ex;
            }

            return(retValue);
        }