Ejemplo n.º 1
0
        private unsafe bool GetDataFromController(int etwSessionId,
                UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart)
        {
            data = null;
            dataStart = 0;
            if (filterData == null)
            {
#if !ES_BUILD_PCL && !FEATURE_PAL
                string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
                if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
                    regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey;
                else
                    regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey;

                string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture);

                // we need to assert this permission for partial trust scenarios
                (new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert();
                data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[];
                if (data != null)
                {
                    // We only used the persisted data from the registry for updates.   
                    command = ControllerCommand.Update;
                    return true;
                }
#endif
            }
            else
            {
                if (filterData->Ptr != 0 && 0 < filterData->Size && filterData->Size <= 1024)
                {
                    data = new byte[filterData->Size];
                    Marshal.Copy((IntPtr)filterData->Ptr, data, 0, data.Length);
                }
                command = (ControllerCommand)filterData->Type;
                return true;
            }

            command = ControllerCommand.Update;
            return false;
        }
Ejemplo n.º 2
0
        internal unsafe int SetInformation(
            UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass,
            void* data,
            int dataSize)
        {
            int status = UnsafeNativeMethods.ManifestEtw.ERROR_NOT_SUPPORTED;

            if (!m_setInformationMissing)
            {
                try
                {
                    status = UnsafeNativeMethods.ManifestEtw.EventSetInformation(
                        m_regHandle,
                        eventInfoClass,
                        data,
                        dataSize);
                }
                catch (TypeLoadException)
                {
                    m_setInformationMissing = true;
                }
            }

            return status;
        }
Ejemplo n.º 3
0
 private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback)
 {
     m_providerId = providerId;
     m_etwCallback = enableCallback;
     return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
 }
Ejemplo n.º 4
0
        private void Create(PipeDirection direction, UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs, int bufferSize) {
            Debug.Assert(direction != PipeDirection.InOut, "Anonymous pipe direction shouldn't be InOut");
            Debug.Assert(bufferSize >= 0, "bufferSize is negative");

            bool bSuccess;
            SafePipeHandle serverHandle;
            SafePipeHandle newServerHandle;

            // Create the two pipe handles that make up the anonymous pipe.
            if (direction == PipeDirection.In) {
                bSuccess = UnsafeNativeMethods.CreatePipe(out serverHandle, out m_clientHandle, secAttrs, bufferSize);
            }
            else {
                bSuccess = UnsafeNativeMethods.CreatePipe(out m_clientHandle, out serverHandle, secAttrs, bufferSize);
            }

            if (!bSuccess) {
                __Error.WinIOError(Marshal.GetLastWin32Error(), String.Empty);
            }

            // Duplicate the server handle to make it not inheritable.  Note: We need to do this so that the child 
            // process doesn't end up getting another copy of the server handle.  If it were to get a copy, the
            // OS wouldn't be able to inform the child that the server has closed its handle because it will see
            // that there is still one server handle that is open.  
            bSuccess = UnsafeNativeMethods.DuplicateHandle(UnsafeNativeMethods.GetCurrentProcess(), serverHandle, UnsafeNativeMethods.GetCurrentProcess(),
                    out newServerHandle, 0, false, UnsafeNativeMethods.DUPLICATE_SAME_ACCESS);

            if (!bSuccess) {
                __Error.WinIOError(Marshal.GetLastWin32Error(), String.Empty);
            }

            // Close the inheritable server handle.
            serverHandle.Dispose();

            InitializeHandle(newServerHandle, false, false);

            State = PipeState.Connected;
        }
Ejemplo n.º 5
0
        private void Create(String fullPipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                PipeAccessRights rights, UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs) {
            Debug.Assert(fullPipeName != null && fullPipeName.Length != 0, "fullPipeName is null or empty");
            Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
            Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
            Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
            Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            int openMode = ((int)direction) |
                           (maxNumberOfServerInstances == 1 ? UnsafeNativeMethods.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) |
                           (int)options |
                           (int)rights;

            // We automatically set the ReadMode to match the TransmissionMode.
            int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1;

            // Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254).
            if (maxNumberOfServerInstances == MaxAllowedServerInstances) {
                maxNumberOfServerInstances = 255;
            }

            SafePipeHandle handle = UnsafeNativeMethods.CreateNamedPipe(fullPipeName, openMode, pipeModes,
                    maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, secAttrs);

            if (handle.IsInvalid) {
                __Error.WinIOError(Marshal.GetLastWin32Error(), String.Empty);
            }

            InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
        }
Ejemplo n.º 6
0
    internal void _Init(String path, int fAccess, FileShare share, UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs, FileIOPermissionAccess secAccess, 
                        FileMode mode, int flagsAndAttributes, bool seekToEnd)
    {
        String filePath = Path.GetFullPath(path);
        _fileName = filePath;

        new FileIOPermission(secAccess, new String[] { filePath }).Demand();

        // Don't pop up a dialog for reading from an emtpy floppy drive
        int oldMode = UnsafeNativeMethods.SetErrorMode(UnsafeNativeMethods.SEM_FAILCRITICALERRORS);
        try {
            _handle = UnsafeNativeMethods.SafeCreateFile(filePath, fAccess, share, secAttrs, mode, flagsAndAttributes, UnsafeNativeMethods.NULL);
            int errorCode = Marshal.GetLastWin32Error();

            if (_handle.IsInvalid) {
                // Return a meaningful exception, using the RELATIVE path to
                // the file to avoid returning extra information to the caller
                // unless they have path discovery permission, in which case
                // the full path is fine & useful.

                // We need to give an exception, and preferably it would include
                // the fully qualified path name.  Do security check here.  If
                // we fail, give back the msgPath, which should not reveal much.
                // While this logic is largely duplicated in 
                // __Error.WinIOError, we need this for 
                // IsolatedStorageLogFileStream.
                bool canGiveFullPath = false;

                try {
                    new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { _fileName }).Demand();
                    canGiveFullPath = true;
                }
                catch(SecurityException) {}

                if (canGiveFullPath)
                    __Error.WinIOError(errorCode, _fileName);
                else
                    __Error.WinIOError(errorCode, Path.GetFileName(_fileName));
            }
        }
        finally {
            UnsafeNativeMethods.SetErrorMode(oldMode);
        }
        Debug.Assert(UnsafeNativeMethods.GetFileType(_handle) == UnsafeNativeMethods.FILE_TYPE_DISK, "did someone accidentally removed the device type check from SafeCreateFile P/Invoke wrapper?"); 

        pos = 0;

        // For Append mode...
        if (seekToEnd) {
            SeekCore(0, SeekOrigin.End);
        }
    }
Ejemplo n.º 7
0
        unsafe void EtwEnableCallBack(
                        ref System.Guid sourceId,
                        int controlCode,
                        byte setLevel,
                        long anyKeyword,
                        long allKeyword,
                        UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData,
                        void* callbackContext
                        )
        {
            // This is an optional callback API. We will therefore ignore any failures that happen as a 
            // result of turning on this provider as to not crash the app.
            // EventSource has code to validate whether initialization it expected to occur actually occurred
            try
            {
                ControllerCommand command = ControllerCommand.Update;
                IDictionary<string, string> args = null;
                bool skipFinalOnControllerCommand = false;

                if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_ENABLE_PROVIDER)
                {
                    m_enabled = true;
                    m_level = setLevel;
                    m_anyKeywordMask = anyKeyword;
                    m_allKeywordMask = allKeyword;

                    // ES_SESSION_INFO is a marker for additional places we #ifdeffed out to remove
                    // references to EnumerateTraceGuidsEx.  This symbol is actually not used because
                    // today we use FEATURE_ACTIVITYSAMPLING to determine if this code is there or not.
                    // However we put it in the #if so that we don't lose the fact that this feature
                    // switch is at least partially independent of FEATURE_ACTIVITYSAMPLING
#if ES_SESSION_INFO || FEATURE_ACTIVITYSAMPLING
                    List<Tuple<SessionInfo, bool>> sessionsChanged = GetSessions();
                    foreach (var session in sessionsChanged)
                    {
                        int sessionChanged = session.Item1.sessionIdBit;
                        int etwSessionId = session.Item1.etwSessionId;
                        bool bEnabling = session.Item2;

                        skipFinalOnControllerCommand = true;
                        args = null;                                // reinitialize args for every session...

                        // if we get more than one session changed we have no way
                        // of knowing which one "filterData" belongs to
                        if (sessionsChanged.Count > 1)
                            filterData = null;

                        // read filter data only when a session is being *added*
                        byte[] data;
                        int keyIndex;
                        if (bEnabling &&
                            GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex))
                        {
                            args = new Dictionary<string, string>(4);
                            while (keyIndex < data.Length)
                            {
                                int keyEnd = FindNull(data, keyIndex);
                                int valueIdx = keyEnd + 1;
                                int valueEnd = FindNull(data, valueIdx);
                                if (valueEnd < data.Length)
                                {
                                    string key = System.Text.Encoding.UTF8.GetString(data, keyIndex, keyEnd - keyIndex);
                                    string value = System.Text.Encoding.UTF8.GetString(data, valueIdx, valueEnd - valueIdx);
                                    args[key] = value;
                                }
                                keyIndex = valueEnd + 1;
                            }
                        }

                        // execute OnControllerCommand once for every session that has changed.
                        OnControllerCommand(command, args, (bEnabling ? sessionChanged : -sessionChanged), etwSessionId);
                    }
#endif
                }
                else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_DISABLE_PROVIDER)
                {
                    m_enabled = false;
                    m_level = 0;
                    m_anyKeywordMask = 0;
                    m_allKeywordMask = 0;
#if ES_SESSION_INFO || FEATURE_ACTIVITYSAMPLING
                    m_liveSessions = null;
#endif
                }
                else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_CAPTURE_STATE)
                {
                    command = ControllerCommand.SendManifest;
                }
                else
                    return;     // per spec you ignore commands you don't recognize.  

                if (!skipFinalOnControllerCommand)
                    OnControllerCommand(command, args, 0, 0);
            }
            catch (Exception)
            {
                // We want to ignore any failures that happen as a result of turning on this provider as to
                // not crash the app.
            }
        }
Ejemplo n.º 8
0
        private unsafe long GetTypeInfoVersion(UnsafeNativeMethods.ITypeInfo pTypeInfo) {


            IntPtr pTypeAttr = IntPtr.Zero;
            int hr = pTypeInfo.GetTypeAttr(ref pTypeAttr);
            if (!NativeMethods.Succeeded(hr)) {
                return 0;
            }

            System.Runtime.InteropServices.ComTypes.TYPEATTR pTAStruct;
            try {
                try {
                    // just access directly...no marshalling needed!
                    //
                    pTAStruct = *(System.Runtime.InteropServices.ComTypes.TYPEATTR*)pTypeAttr;
                }
                catch {

                    return 0;
                }

                long result = 0;

                // we pull two things out of the struct: the 
                // number of functions and variables, and the version.
                // since they are next to each other, we just pull the memory directly.
                //
                // the cFuncs and cVars are both shorts, so we read them as one block of ints.
                //
                //
                int* pResult = (int*)&result;
                byte* pbStruct = (byte*)&pTAStruct;

                // in the low byte, pull the number of props.
                //
                *pResult = *(int*)(pbStruct + CountMemberOffset);

                // move up to the high word of the long.
                //                
                pResult++;

                // now pull out the version info.
                //
                *pResult = *(int*)(pbStruct + VersionOffset);

                // return that composite long.
                //
                return result;
            }
            finally {
               pTypeInfo.ReleaseTypeAttr(pTypeAttr);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        ///  This is the public method that will be called to actually show
        ///  a common dialog.  Since CommonDialog is abstract, this function
        ///  performs initialization tasks for all common dialogs and then
        ///  calls RunDialog.
        /// </summary>
        /// <Remarks>
        ///     Callers must have UIPermission(UIPermissionWindow.AllWindows) to call this API.
        /// </Remarks>
        public virtual Nullable <bool> ShowDialog()
        {
            CheckPermissionsToShowDialog();

            // Don't allow file dialogs to be shown if not in interactive mode
            // (for example, if we're running as a service)
            if (!Environment.UserInteractive)
            {
                throw new InvalidOperationException(SR.Get(SRID.CantShowModalOnNonInteractive));
            }

            // Call GetActiveWindow to retrieve the window handle to the active window
            // attached to the calling thread's message queue.  We'll set the owner of
            // the common dialog to this handle.
            IntPtr hwndOwner = UnsafeNativeMethods.GetActiveWindow();

            if (hwndOwner == IntPtr.Zero)
            {
                // No active window, so we'll use the parking window as the owner,
                // if its available.
                if (Application.Current != null)
                {
                    hwndOwner = Application.Current.ParkingHwnd;
                }
            }

            HwndWrapper tempParentHwnd = null;

            try
            {
                // No active window and application wasn't available or didn't have
                // a ParkingHwnd, we create a hidden parent window for the dialog to
                // prevent breaking UIAutomation.
                if (hwndOwner == IntPtr.Zero)
                {
                    tempParentHwnd = new HwndWrapper(0, 0, 0, 0, 0, 0, 0, "", IntPtr.Zero, null);
                    hwndOwner      = tempParentHwnd.Handle;
                }

                // Store the handle of the owner window inside our class so we can use it
                // to center the dialog later.
                _hwndOwnerWindow = hwndOwner;

                // Signal that this thread is going to go modal.
                try
                {
                    ComponentDispatcher.CriticalPushModal();

                    return(RunDialog(hwndOwner));
                }
                finally
                {
                    ComponentDispatcher.CriticalPopModal();
                }
            }
            finally
            {
                if (tempParentHwnd != null)
                {
                    tempParentHwnd.Dispose();
                }
            }
        }
 protected override bool ReleaseHandle()
 {
     return(UnsafeNativeMethods.FreeLibrary(base.handle));
 }