Пример #1
0
 public object MarshalNativeToManaged(IntPtr pNativeData)
 {
     //Console.WriteLine ("ToManaged: " + pNativeData);
     native_to_managed_count ++;
     native_to_managed_result = param + Marshal.ReadInt32 (new IntPtr (pNativeData.ToInt64 () + 4));
     return native_to_managed_result;
 }
    public void Add(Vector3 in_Pos, Vector3 in_Forward, Vector3 in_Top, uint in_ChannelMask)
    {
        if (m_Count >= m_MaxCount)
            throw new IndexOutOfRangeException("Out of range access in AkChannelEmitterArray");

        //Marshal doesn't do floats.  So copy the bytes themselves.  Grrr.
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Forward.x), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Forward.y), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Forward.z), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Top.x), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Top.y), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Top.z), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Pos.x), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Pos.y), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Pos.z), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, (int)in_ChannelMask);
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(uint));

        m_Count++;
    }
Пример #3
0
    public void CleanUpNativeData(IntPtr pNativeData)
    {
        Console.WriteLine("CleanUpNativeData called");
        if (pNativeData != IntPtr.Zero) {
            IntPtr realPtr = new IntPtr (pNativeData.ToInt64 () - Marshal.SizeOf (typeof (int)));

            Marshal.FreeHGlobal (realPtr);
        }
    }
Пример #4
0
 public override void CleanUpNativeData(IntPtr native_data)
 {
     Marshal.FreeHGlobal(native_data);
     #if MARSHAL_DEBUG
     // Useful for debugging things from a console application to see whether
     // allocating and freeing match.  We cannot use Log.Info here, since that
     // would recursively call the marshaler and end in overflowing hilarity.
     Console.WriteLine("freeh " + Convert.ToString(native_data.ToInt64(), 16));
     #endif
 }
Пример #5
0
    public void Add(uint in_EnvID, float in_fValue)
    {
        if (m_Count >= m_MaxCount)
            Resize(m_Count * 2);

        Marshal.WriteInt32(m_Current, (int)in_EnvID);
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(uint));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_fValue), 0));  //Marshal doesn't do floats.  So copy the bytes themselves.  Grrr.
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        m_Count++;
    }
Пример #6
0
        // ReSharper disable once TooManyArguments
        private void DebugMessage(string scope, IntPtr?socket, string message, params object[] args)
        {
            var lastError = NativeSocket.WSAGetLastError();

            try
            {
                var space = Math.Max(20 - scope.Length, 0);

                message = string.Format(
                    "{0:s} - #{4:D8} [`{1}`] {2}{3}",
                    DateTime.UtcNow,
                    scope,
                    new string(' ', space),
                    args?.Length > 0 ? string.Format(message, args) : message,
                    socket?.ToInt64() ?? 0
                    );

#if DEBUG
                try
                {
                    Debug.WriteLine(message);
                    Console.WriteLine(message);
                }
                catch
                {
                    // ignored
                }
#endif

                try
                {
                    if (string.IsNullOrWhiteSpace(LogPath))
                    {
                        return;
                    }

                    File.AppendAllText(LogPath, message + Environment.NewLine);
                }
                catch
                {
                    // ignored
                }
            }
            catch
            {
                // ignored
            }

            NativeSocket.WSASetLastError(lastError);
        }
Пример #7
0
    IEnumerator LoadFile()
    {
        ms_www = new WWW(m_bankPath);

        yield return ms_www;

        uint in_uInMemoryBankSize = 0;

        // Allocate an aligned buffer
        try
        {
            ms_pinnedArray = GCHandle.Alloc(ms_www.bytes, GCHandleType.Pinned);
            ms_pInMemoryBankPtr = ms_pinnedArray.AddrOfPinnedObject();
            in_uInMemoryBankSize = (uint)ms_www.bytes.Length;

            // Array inside the WWW object is not aligned. Allocate a new array for which we can guarantee the alignment.
            if( (ms_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0 )
            {
                byte[] alignedBytes = new byte[ms_www.bytes.Length + AK_BANK_PLATFORM_DATA_ALIGNMENT];
                GCHandle new_pinnedArray = GCHandle.Alloc(alignedBytes, GCHandleType.Pinned);
                IntPtr new_pInMemoryBankPtr = new_pinnedArray.AddrOfPinnedObject();
                int alignedOffset = 0;

                // New array is not aligned, so we will need to use an offset inside it to align our data.
                if( (new_pInMemoryBankPtr.ToInt64() & AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) != 0 )
                {
                    Int64 alignedPtr = (new_pInMemoryBankPtr.ToInt64() + AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK) & ~AK_BANK_PLATFORM_DATA_ALIGNMENT_MASK;
                    alignedOffset = (int)(alignedPtr - new_pInMemoryBankPtr.ToInt64());
                    new_pInMemoryBankPtr = new IntPtr(alignedPtr);
                }

                // Copy the bank's bytes in our new array, at the correct aligned offset.
                Array.Copy (ms_www.bytes, 0, alignedBytes, alignedOffset, ms_www.bytes.Length);

                ms_pInMemoryBankPtr = new_pInMemoryBankPtr;
                ms_pinnedArray.Free();
                ms_pinnedArray = new_pinnedArray;
            }
        }
        catch
        {
            yield break;
        }

        AKRESULT result = AkSoundEngine.LoadBank(ms_pInMemoryBankPtr, in_uInMemoryBankSize, out ms_bankID);
        if( result != AKRESULT.AK_Success )
        {
            Debug.LogError ("AkMemBankLoader: bank loading failed with result " + result.ToString ());
        }
    }
Пример #8
0
        static IntPtr OnHookedWindowMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == Win32Interop.WM_SYSCOMMAND && wParam.ToInt64() == (long)Win32Interop.SC_CONTEXTHELP)
            {
                var rootVisual = HwndSource.FromHwnd(hwnd).RootVisual;
                var focusedElement = FocusManager.GetFocusedElement(rootVisual);
                if (focusedElement == null)
                {
                    focusedElement = rootVisual as IInputElement;
                }
                ApplicationCommands.Help.Execute(null, focusedElement);
                handled = true;
            }

            // According to MSDN, zero should be returned after handling WM_SYSCOMMAND.
            // If this message is unhandled, it's still safe to return zero
            // because WPF framework (HwndSource) will return zero anyway if the
            // message is unhandled.
            return IntPtr.Zero;
        }       
Пример #9
0
    public void Add(Vector3 in_Pos, Vector3 in_Forward)
    {
        if (m_Count >= m_MaxCount)
            throw new IndexOutOfRangeException("Out of range access in AkPositionArray");

        //Marshal doesn't do floats.  So copy the bytes themselves.  Grrr.
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Pos.X), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Pos.Y), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Pos.Z), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Forward.X), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Forward.Y), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));
        Marshal.WriteInt32(m_Current, BitConverter.ToInt32(BitConverter.GetBytes(in_Forward.Z), 0));
        m_Current = (IntPtr)(m_Current.ToInt64() + sizeof(float));

        m_Count++;
    }
Пример #10
0
    /// <summary>
    /// for positive testing 
    /// </summary>
    /// <returns></returns>
    public bool PosTest1(string id, long i)
    {
        bool retVal = true;
        try
        {
            System.IntPtr ip = new IntPtr(i);
            if (ip.ToInt64() != i)
            {
                TestLibrary.TestFramework.LogError(id,
                    String.Format("IntPtr value expect {0}", i));
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError(id, "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Пример #11
0
        internal IntPtr FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            IntPtr result = IntPtr.Zero ;

            // It is possible to be re-entered during disposal.  Just return.
            if(null == _source || null == _source.Value)
            {
                return result;
            }
            /*
            NativeMethods.POINT ptCursor = new NativeMethods.POINT();
            int messagePos = 0;
            try
            {
                messagePos = SafeNativeMethods.GetMessagePos();
            }
            catch(System.ComponentModel.Win32Exception)
            {
                System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: GetMessagePos failed!");
            }

            ptCursor.x = NativeMethods.SignedLOWORD(messagePos);
            ptCursor.y = NativeMethods.SignedHIWORD(messagePos);
            Console.WriteLine("HwndMouseInputProvider.FilterMessage: hwnd: {0} msg: {1} wParam: {2} lParam: {3} MessagePos: ({4},{5})", hwnd, msg, wParam, lParam, ptCursor.x, ptCursor.y);
            */
            _msgTime = 0;
            try
            {
                _msgTime = SafeNativeMethods.GetMessageTime();
            }
            catch(System.ComponentModel.Win32Exception)
            {
                System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: GetMessageTime failed!");
            }

            // 
            if(msg == WindowMessage.WM_MOUSEQUERY)
            {
                if(!_isDwmProcess)
                {
                    _isDwmProcess = true;
                }

                unsafe
                {
                    // Currently only sending WM_MOUSEMOVE through until we rip out the prototype bits.
                    UnsafeNativeMethods.MOUSEQUERY* pmq = (UnsafeNativeMethods.MOUSEQUERY*)lParam;
                    if((WindowMessage)pmq->uMsg == WindowMessage.WM_MOUSEMOVE)
                    {
                        msg = (WindowMessage)pmq->uMsg;
                        wParam = pmq->wParam;
                        lParam = MakeLPARAM(pmq->ptX, pmq->ptY);
                    }
                }
            }

            switch(msg)
            {
                // Compatibility Note:
                //
                // WM_POINTERUP, WM_POINTERDOWN
                //
                // These messages were introduced in Win8 to unify the various
                // mechanisms for processing events from pointing devices,
                // including stylus, touch, mouse, etc.  WPF does not
                // currently support these messages; we still rely on the
                // classic WM_MOUSE messages.  For classic applications, this
                // is supported by default in Windows.  However, for immersive
                // applications, the default is to report mouse input through
                // these new WM_POINTER messages.  Blend - the only immersive
                // WPF application - must explicitly request the mouse input
                // be delivered through the traditional WM_MOUSE messages by
                // calling EnableMouseInPointer(false).  If WPF ever supports
                // the WM_POINTER messages, we need to be careful not to break
                // Blend.
                
                case WindowMessage.WM_NCDESTROY:
                {
                    //Console.WriteLine("WM_NCDESTROY");

                    // This is the normal clean-up path.  HwndSource destroys the
                    // HWND first, which should trigger this code, before it
                    // explicitly disposes us.  This allows us to call
                    // PossiblyDeactivate since our window is no longer on the
                    // screen.
                    Dispose();
                }
                break;

                case WindowMessage.WM_MOUSEMOVE:
                {
                    int x = NativeMethods.SignedLOWORD(lParam);
                    int y = NativeMethods.SignedHIWORD(lParam);

                    //Console.WriteLine("WM_MOUSEMOVE: " + x + "," + y);

                    // Abort the pending operation waiting to update the cursor, because we
                    // are going to update it as part of this mouse move processing.
                    if (_queryCursorOperation != null)
                    {
                        _queryCursorOperation.Abort();
                        _queryCursorOperation = null;
                    }

                    // MITIGATION_SETCURSOR
                    if (_haveCapture)
                    {
                        // When we have capture we don't receive WM_SETCURSOR
                        // prior to a mouse move.  So that we don't erroneously think
                        // we're in "Help Mode" we'll pretend we've received a set
                        // cursor message.
                        _setCursorState = SetCursorState.SetCursorReceived;
                    }
                    else
                    {
                        if (_setCursorState == SetCursorState.SetCursorNotReceived)
                        {
                            _setCursorState = SetCursorState.SetCursorDisabled;
                        }
                        else if(_setCursorState == SetCursorState.SetCursorReceived)
                        {
                            _setCursorState = SetCursorState.SetCursorNotReceived;
                        }
                    }

                    // 

                    handled = ReportInput(hwnd,
                                          InputMode.Foreground,
                                          _msgTime,
                                          RawMouseActions.AbsoluteMove,
                                          x,
                                          y,
                                          0);
                }
                break;

                case WindowMessage.WM_MOUSEWHEEL:
                {
                    int wheel = NativeMethods.SignedHIWORD(wParam);
                    int x = NativeMethods.SignedLOWORD(lParam);
                    int y = NativeMethods.SignedHIWORD(lParam);

                    // The WM_MOUSEWHEEL gives the coordinates relative to the desktop.
                    NativeMethods.POINT pt = new NativeMethods.POINT(x,y);
                    try
                    {
                        SafeNativeMethods.ScreenToClient(new HandleRef(this,hwnd), pt);

                        x = pt.x;
                        y = pt.y;

                        //Console.WriteLine("WM_MOUSEWHEEL: " + x + "," + y + "," + wheel);

                        // 

                        handled = ReportInput(hwnd,
                                              InputMode.Foreground,
                                              _msgTime,
                                              RawMouseActions.VerticalWheelRotate,
                                              x,
                                              y,
                                              wheel);
                    }
                    catch(System.ComponentModel.Win32Exception)
                    {
                        System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: ScreenToClient failed!");
                    }
                }
                break;

                case WindowMessage.WM_LBUTTONDBLCLK:
                case WindowMessage.WM_LBUTTONDOWN:
                {
                    int x = NativeMethods.SignedLOWORD(lParam);
                    int y = NativeMethods.SignedHIWORD(lParam);

                    //Console.WriteLine("WM_LBUTTONDOWN: " + x + "," + y);

                    // 

                    handled = ReportInput(hwnd,
                                          InputMode.Foreground,
                                          _msgTime,
                                          RawMouseActions.Button1Press,
                                          x,
                                          y,
                                          0);
                }
                break;

                case WindowMessage.WM_LBUTTONUP:
                {
                    int x = NativeMethods.SignedLOWORD(lParam);
                    int y = NativeMethods.SignedHIWORD(lParam);

                    //Console.WriteLine("WM_LBUTTONUP: " + x + "," + y);

                    // 

                    handled = ReportInput(hwnd,
                                          InputMode.Foreground,
                                          _msgTime,
                                          RawMouseActions.Button1Release,
                                          x,
                                          y,
                                          0);
                }
                break;

                case WindowMessage.WM_RBUTTONDBLCLK:
                case WindowMessage.WM_RBUTTONDOWN:
                {
                    int x = NativeMethods.SignedLOWORD(lParam);
                    int y = NativeMethods.SignedHIWORD(lParam);

                    // 

                    handled = ReportInput(hwnd,
                                          InputMode.Foreground,
                                          _msgTime,
                                          RawMouseActions.Button2Press,
                                          x,
                                          y,
                                          0);
                }
                break;

                case WindowMessage.WM_RBUTTONUP:
                {
                    int x = NativeMethods.SignedLOWORD(lParam);
                    int y = NativeMethods.SignedHIWORD(lParam);

                    // 

                    handled = ReportInput(hwnd,
                                          InputMode.Foreground,
                                          _msgTime,
                                          RawMouseActions.Button2Release,
                                          x,
                                          y,
                                          0);
                }
                break;

                case WindowMessage.WM_MBUTTONDBLCLK:
                case WindowMessage.WM_MBUTTONDOWN:
                {
                    int x = NativeMethods.SignedLOWORD(lParam);
                    int y = NativeMethods.SignedHIWORD(lParam);

                    // 

                    handled = ReportInput(hwnd,
                                          InputMode.Foreground,
                                          _msgTime,
                                          RawMouseActions.Button3Press,
                                          x,
                                          y,
                                          0);
                }
                break;

                case WindowMessage.WM_MBUTTONUP:
                {
                    int x = NativeMethods.SignedLOWORD(lParam);
                    int y = NativeMethods.SignedHIWORD(lParam);

                    // 

                    handled = ReportInput(hwnd,
                                          InputMode.Foreground,
                                          _msgTime,
                                          RawMouseActions.Button3Release,
                                          x,
                                          y,
                                          0);
                }
                break;

                case WindowMessage.WM_XBUTTONDBLCLK:
                case WindowMessage.WM_XBUTTONDOWN:
                {
                    int button = NativeMethods.SignedHIWORD(wParam);
                    int x = NativeMethods.SignedLOWORD(lParam);
                    int y = NativeMethods.SignedHIWORD(lParam);

                    RawMouseActions actions = 0;
                    if(button == 1)
                    {
                        actions = RawMouseActions.Button4Press;
                    }
                    else if(button == 2)
                    {
                        actions = RawMouseActions.Button5Press;
                    }

                    // 

                    handled = ReportInput(hwnd,
                                          InputMode.Foreground,
                                          _msgTime,
                                          actions,
                                          x,
                                          y,
                                          0);
                }
                break;

                case WindowMessage.WM_XBUTTONUP:
                {
                    int button = NativeMethods.SignedHIWORD(wParam);
                    int x = NativeMethods.SignedLOWORD(lParam);
                    int y = NativeMethods.SignedHIWORD(lParam);

                    RawMouseActions actions = 0;
                    if(button == 1)
                    {
                        actions = RawMouseActions.Button4Release;
                    }
                    else if(button == 2)
                    {
                        actions = RawMouseActions.Button5Release;
                    }

                    // 

                    handled = ReportInput(hwnd,
                                          InputMode.Foreground,
                                          _msgTime,
                                          actions,
                                          x,
                                          y,
                                          0);
                }
                break;

                case WindowMessage.WM_MOUSELEAVE:
                {
                    //Console.WriteLine("WM_MOUSELEAVE");

                    // When the mouse moves off the window, we receive a
                    // WM_MOUSELEAVE.   We'll start tracking again when the
                    // mouse moves back over us.
                    StopTracking(hwnd);

                    // It is possible that we have capture but we still receive
                    // a mouse leave event.  This can happen in the case of
                    // "soft capture".  In such cases, we defer the actual
                    // deactivation until the capture is lost.
                    //
                    // See the note on WM_CAPTURECHANGED for more details.
                    try
                    {
                        IntPtr hwndCapture = SafeNativeMethods.GetCapture();
                        IntPtr hwndCurrent = _source.Value.CriticalHandle;
                        if (hwndCapture != hwndCurrent)
                        {
                            PossiblyDeactivate(hwndCapture, false);
                        }
                    }
                    catch(System.ComponentModel.Win32Exception)
                    {
                        System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: GetCapture failed!");
                    }

            }
                break;

                case WindowMessage.WM_CAPTURECHANGED:
                {
                    //Console.WriteLine("WM_CAPTURECHANGED");

                    // Win32 has two concepts for capture:
                    //
                    // Hard Capture
                    // When a mouse button is pressed, Win32 finds the window
                    // underneath the mouse and assigns it as the MouseOwner.
                    // All mouse input is directed to this window until the
                    // mouse is button released.  The window does not even
                    // have to request capture.  Certain window types are
                    // excluded from this processing.
                    //
                    // Soft Capture
                    // This is accessed via the SetCapture API.  It assigns
                    // the window that should receive mouse input for the
                    // queue.  Win32 decides which queue the mouse input
                    // should go to without considering this type of capture.
                    // Once the input is in the queue, it is sent to the
                    // window with capture.  This means that the mouse
                    // messages will generally be sent to the specified window
                    // in the application, but other applications will work
                    // too.
                    //
                    // If another application calls SetCapture, the current
                    // application will receive a WM_CAPTURECHANGED.
                    //
                    // If the window took capture while Win32 was enforcing
                    // Hard Capture, and releases capture when the mouse
                    // button is released, then everything works as you
                    // probably expect.  But if the application retains
                    // capture after the mouse button is released, it is
                    // possible to receive a WM_MOUSELEAVE even though the
                    // window still has capture.

                    // Losing capture *after* a WM_MOUSELEAVE means we
                    // probably want to deactivate the mouse input stream.
                    // If someone else is taking capture, we may need
                    // to deactivate the mouse input stream too.

                    if(lParam != _source.Value.CriticalHandle) // Ignore odd messages that claim we are losing capture to ourselves.
                    {
                        // MITIGATION_SETCURSOR
                        _haveCapture = false;

                        if(_setCursorState == SetCursorState.SetCursorReceived)
                        {
                            _setCursorState = SetCursorState.SetCursorNotReceived;
                        }

                        if(!IsOurWindow(lParam) && _active)
                        {
                            ReportInput(hwnd,
                                        InputMode.Foreground,
                                        _msgTime,
                                        RawMouseActions.CancelCapture,
                                        0,
                                        0,
                                        0);
                        }

                        if(lParam != IntPtr.Zero || // someone else took capture
                           !_tracking)              // OR no one has capture and the mouse is not over us
                        {
                            PossiblyDeactivate(lParam, true);
                        }
                    }
                }
                break;

                case WindowMessage.WM_CANCELMODE:
                {
                    // MITIGATION: NESTED_MESSAGE_PUMPS_INTERFERE_WITH_INPUT
                    //
                    // When a nested message pump runs, it intercepts all messages
                    // before they are dispatched, and thus before they can be sent
                    // to the window with capture.
                    //
                    // This means that an element can take capture on MouseDown,
                    // expecting to receive either MouseUp or LostCapture.  But, in
                    // fact, neither event may be raised if a nested message pump
                    // runs.
                    //
                    // An example of this is displaying a dialog box in response to
                    // MouseDown.
                    //
                    // There isn't much we can do about the general case, but
                    // well-behaved message pumps (such as a dialog box) are
                    // supposed to send the WM_CANCELMODE message.  In response
                    // to this we release capture if we currently have it.
                    try
                    {
                        if(_source.Value.HasCapture )
                        {
                            SafeNativeMethods.ReleaseCapture();
                        }
                    }
                    catch(System.ComponentModel.Win32Exception)
                    {
                        System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: GetCapture failed!");
                    }
                }
                break;

                case WindowMessage.WM_SETCURSOR:
                {
                    if (_queryCursorOperation == null)
                    {
                        // It is possible that a WM_SETCURSOR is not followed by a WM_MOUSEMOVE, in which
                        // case we need a backup mechanism to query the cursor and update it. So we post to
                        // the queue to do this work. If a WM_MOUSEMOVE comes in earlier, then the operation
                        // is aborted, else it comes through and we update the cursor.
                        _queryCursorOperation = Dispatcher.BeginInvoke(DispatcherPriority.Input,
                            (DispatcherOperationCallback)delegate(object sender)
                            {
                                // Since this is an asynchronous operation and an arbitrary amount of time has elapsed
                                // since we received the WM_SETCURSOR, we need to be careful that the mouse hasn't
                                // been deactivated in the meanwhile. This is also another reason that we do not ReportInput,
                                // because the implicit assumption in doing that is to activate the MouseDevice. All we want
                                // to do is passively try to update the cursor.
                                if (_active)
                                {
                                    Mouse.UpdateCursor();
                                }

                                _queryCursorOperation = null;
                                return null;
                            },
                            null);
                    }

                    // MITIGATION_SETCURSOR
                    _setCursorState = SetCursorState.SetCursorReceived;

                    // Note: We get this message BEFORE we get WM_MOUSEMOVE.  This means that Avalon
                    //       still thinks the mouse is over the "old" element.  This is awkward, and we think
                    //       people will find it confusing to get a QueryCursor event before a MouseMove event.
                    //       Further, this means we would have to do a special hit-test, and route the
                    //       QueryCursor event differently than the other mouse events.
                    //
                    //       Another difference is that Win32 passes us a hit-test code, which was calculated
                    //       by an earlier WM_NCHITTEST message.  The problem with this is that it is a fixed
                    //       enum.  We don't have a similar concept in Avalon.
                    //
                    //       So instead, the MouseDevice will raise the QueryCursor event after every MouseMove
                    //       event.  We think this is a better ordering.  And the application can return whatever
                    //       cursor they want (not limited to a fixed enum of hit-test codes).
                    //
                    //       Of course, this is different than Win32.  One example of where this can cause a
                    //       problem is that sometimes Win32 will NOT send a WM_SETCURSOR message and just send
                    //       a WM_MOUSEMOVE.  This is for cases like when the mouse is captured, or when the
                    //       the "help mode" is active (clicking the little question mark in the title bar).
                    //       To accomodate this, we use the _setCursorState to prevent the user from changing
                    //       the cursor when we haven't received a WM_SETCURSOR message - which means that the
                    //       cursor is NOT supposed to change as it moves over new windows/elements/etc.  Note
                    //       that Avalon will raise the QueryCursor event, but the result is ignored.
                    //
                    // But:  We MUST mark this Win32 message as "handled" or windows will change the cursor to
                    //       the default cursor, which will cause annoying flicker if the app is trying to set
                    //       a custom one.  Of course, only do this for the client area.
                    //
                    int hittestCode = NativeMethods.SignedLOWORD((int) lParam);
                    if(hittestCode == NativeMethods.HTCLIENT)
                    {
                        handled = true;
                    }
                }
                break;
            }

            if (handled && EventTrace.IsEnabled(EventTrace.Keyword.KeywordInput | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info))
            {
                // Anything can (and does) happen in ReportInput.  We can be (and have been)
                // re-entered and Dispose()ed.  Then returning from ReportInput
                // needs to check for that.
                int dispatcherHashCode = 0;

                if( _source != null && !_source.Value.IsDisposed && _source.Value.CompositionTarget != null)
                    dispatcherHashCode = _source.Value.CompositionTarget.Dispatcher.GetHashCode();

                // The ETW manifest for this event declares the lParam and
                // wParam values to be integers.  This is not always true for
                // 64-bit systems, which sometimes pass pointers and handles
                // through this parameters.  However, we can't change the ETW
                // manifest in an in-place upgrade, so we are just going to
                // cast to an int.  Note that IntPtr defines the explicit int
                // cast operator to used a checked block, which will throw an
                // overflow exception if the IntPtr contains too big of a value.
                // So we do the cast ourselves and ignore the overflow.
                int wParamInt = (int) (long) wParam;;
                int lParamInt = (int) (long) lParam;
                
                EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientInputMessage, EventTrace.Keyword.KeywordInput | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info, dispatcherHashCode, hwnd.ToInt64(), msg, wParamInt, lParamInt);

            }

            return result;
        }
Пример #12
0
 void OnReadUnix(UVBuffer.Unix buffer, IntPtr bytesAvaliable)
 {
     long bytesRead = bytesAvaliable.ToInt64();
     if (bytesRead == 0)
     {
         return;
     }
     else if (bytesRead < 0)
     {
         var error = UVException.ErrorCodeToError((int)bytesRead);
         if (error == UVError.EOF)
         {
             OnEndOfStream();
             Dispose();
         }
         else
         {
             Dispose();
             throw new UVException((int)bytesRead);
         }
     }
     else
     {
         using (var owned = new OwnedNativeMemory((int)bytesRead, buffer.Buffer)) {
             OnReadCompleted(owned.Memory);
             //buffer.Dispose(); // TODO: owned memory frees the memory. this is bad; need to fix
         }
     }
 }
Пример #13
0
        public void SetServiceRecoveryOptions(HostSettings settings, ServiceRecoveryOptions options)
        {
            IntPtr scmHandle     = IntPtr.Zero;
            IntPtr serviceHandle = IntPtr.Zero;
            IntPtr lpsaActions   = IntPtr.Zero;
            IntPtr lpInfo        = IntPtr.Zero;
            IntPtr lpFlagInfo    = IntPtr.Zero;

            try
            {
                List <NativeMethods.SC_ACTION> actions = options.Actions.Select(x => x.GetAction()).ToList();
                if (actions.Count == 0)
                {
                    throw new TopshelfException("Must be at least one failure action configured");
                }

                scmHandle = NativeMethods.OpenSCManager(null, null, (int)NativeMethods.SCM_ACCESS.SC_MANAGER_ALL_ACCESS);
                if (scmHandle == IntPtr.Zero)
                {
                    throw new TopshelfException("Failed to open service control manager");
                }

                serviceHandle = NativeMethods.OpenService(scmHandle, settings.ServiceName,
                                                          (int)NativeMethods.SCM_ACCESS.SC_MANAGER_ALL_ACCESS);
                if (serviceHandle == IntPtr.Zero)
                {
                    throw new TopshelfException("Failed to open service: " + settings.ServiceName);
                }

                int actionSize = Marshal.SizeOf(typeof(NativeMethods.SC_ACTION));
                lpsaActions = Marshal.AllocHGlobal(actionSize * actions.Count + 1);
                if (lpsaActions == IntPtr.Zero)
                {
                    throw new TopshelfException("Unable to allocate memory for service recovery actions");
                }

                IntPtr nextAction = lpsaActions;
                for (int i = 0; i < actions.Count; i++)
                {
                    Marshal.StructureToPtr(actions[i], nextAction, false);
                    nextAction = (IntPtr)(nextAction.ToInt64() + actionSize);
                }

                var finalAction = new NativeMethods.SC_ACTION();
                finalAction.Type  = (int)NativeMethods.SC_ACTION_TYPE.None;
                finalAction.Delay = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;

                Marshal.StructureToPtr(finalAction, nextAction, false);

                string rebootMessage = options.Actions.Where(x => x.GetType() == typeof(RestartSystemRecoveryAction))
                                       .OfType <RestartSystemRecoveryAction>().Select(x => x.RestartMessage).
                                       FirstOrDefault() ?? "";

                string runProgramCommand = options.Actions.Where(x => x.GetType() == typeof(RunProgramRecoveryAction))
                                           .OfType <RunProgramRecoveryAction>().Select(x => x.Command).
                                           FirstOrDefault() ?? "";


                var failureActions = new NativeMethods.SERVICE_FAILURE_ACTIONS();
                failureActions.dwResetPeriod =
                    (int)TimeSpan.FromDays(options.ResetPeriod).TotalSeconds;
                failureActions.lpRebootMsg = rebootMessage;
                failureActions.lpCommand   = runProgramCommand;
                failureActions.cActions    = actions.Count + 1;
                failureActions.actions     = lpsaActions;

                lpInfo = Marshal.AllocHGlobal(Marshal.SizeOf(failureActions));
                if (lpInfo == IntPtr.Zero)
                {
                    throw new TopshelfException("Failed to allocate memory for failure actions");
                }

                Marshal.StructureToPtr(failureActions, lpInfo, false);

                if (!NativeMethods.ChangeServiceConfig2(serviceHandle,
                                                        NativeMethods.SERVICE_CONFIG_FAILURE_ACTIONS, lpInfo))
                {
                    throw new TopshelfException("Failed to change service recovery options");
                }

                if (false == options.RecoverOnCrashOnly)
                {
                    var flag = new NativeMethods.SERVICE_FAILURE_ACTIONS_FLAG();
                    flag.fFailureActionsOnNonCrashFailures = true;

                    lpFlagInfo = Marshal.AllocHGlobal(Marshal.SizeOf(flag));
                    if (lpFlagInfo == IntPtr.Zero)
                    {
                        throw new TopshelfException("Failed to allocate memory for failure flag");
                    }

                    Marshal.StructureToPtr(flag, lpFlagInfo, false);

                    try
                    {
                        NativeMethods.ChangeServiceConfig2(serviceHandle,
                                                           NativeMethods.SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, lpFlagInfo);
                    }
                    catch
                    {
                        // this fails on XP, but we don't care really as it's optional
                    }
                }
            }
            finally
            {
                if (lpFlagInfo != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(lpFlagInfo);
                }
                if (lpInfo != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(lpInfo);
                }
                if (lpsaActions != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(lpsaActions);
                }
                if (serviceHandle != IntPtr.Zero)
                {
                    NativeMethods.CloseServiceHandle(serviceHandle);
                }
                if (scmHandle != IntPtr.Zero)
                {
                    NativeMethods.CloseServiceHandle(scmHandle);
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Reads a number of samples.
        /// </summary>
        /// <param name="buffer">The buffer to write the data to.</param>
        /// <param name="requested">Number of requested number of samples.</param>
        /// <param name="offset">Offset to move the ring buffer read pointer before reading data.</param>
        /// <returns>Number of samples read.</returns>
        public int Read(IntPtr buffer, int requested, int offset)
        {
            int read;
            int readPointer;
            int writePointer;
            int space;

            lock (_syncObj)
            {
                readPointer  = _readPointer;
                writePointer = _writePointer;
                space        = _space;
            }

            offset = Math.Min(offset, _buffer.Length - space);

            readPointer += offset;
            if (readPointer > _buffer.Length)
            {
                readPointer -= _buffer.Length;
            }

            requested = Math.Min(requested, _buffer.Length - space - offset);

            if (writePointer > readPointer)
            {
                int count1 = Math.Min(requested, writePointer - readPointer);

                Marshal.Copy(_buffer, readPointer, buffer, count1);
                readPointer += count1;

                read = count1;
            }
            else
            {
                int count1 = Math.Min(requested, _buffer.Length - readPointer);

                if (count1 > 0)
                {
                    Marshal.Copy(_buffer, readPointer, buffer, count1);
                    readPointer += count1;
                    if (readPointer == _buffer.Length)
                    {
                        readPointer = 0;
                    }
                }

                int count2 = Math.Min(requested - count1, writePointer);
                if (count2 > 0)
                {
                    IntPtr ptr = new IntPtr((_is32Bit ? buffer.ToInt32() : buffer.ToInt64()) + (count1 * BassConstants.FloatBytes));
                    Marshal.Copy(_buffer, 0, ptr, count2);
                    readPointer = count2;
                }
                else
                {
                    count2 = 0;
                }
                read = count1 + count2;
            }

            readPointer = readPointer - offset;
            if (readPointer < 0)
            {
                readPointer += _buffer.Length;
            }

            lock (_syncObj)
            {
                _readPointer = readPointer;
                _space      += read;
            }
            return(read);
        }
Пример #15
0
        static byte[] _LightMaps = new byte[4 * MAX_LIGHTMAPS * BLOCK_WIDTH * BLOCK_HEIGHT]; // lightmaps

        /// <summary>
        /// GL_BuildLightmaps
        /// Builds the lightmap texture with all the surfaces from all brush models
        /// </summary>
        static void BuildLightMaps()
        {
            Array.Clear(_Allocated, 0, _Allocated.Length);
            //memset (allocated, 0, sizeof(allocated));

            _FrameCount = 1;            // no dlightcache

            if (_LightMapTextures == 0)
            {
                _LightMapTextures = Drawer.GenerateTextureNumberRange(MAX_LIGHTMAPS);
            }

            Drawer.LightMapFormat = PixelFormat.Luminance;// GL_LUMINANCE;

            // default differently on the Permedia
            if (Scr.IsPermedia)
            {
                Drawer.LightMapFormat = PixelFormat.Rgba;
            }

            if (Common.HasParam("-lm_1"))
            {
                Drawer.LightMapFormat = PixelFormat.Luminance;
            }

            if (Common.HasParam("-lm_a"))
            {
                Drawer.LightMapFormat = PixelFormat.Alpha;
            }

            //if (Common.HasParam("-lm_i"))
            //    Drawer.LightMapFormat = PixelFormat.Intensity;

            //if (Common.HasParam("-lm_2"))
            //    Drawer.LightMapFormat = PixelFormat.Rgba4;

            if (Common.HasParam("-lm_4"))
            {
                Drawer.LightMapFormat = PixelFormat.Rgba;
            }

            switch (Drawer.LightMapFormat)
            {
            case PixelFormat.Rgba:
                _LightMapBytes = 4;
                break;

            //case PixelFormat.Rgba4:
            //_LightMapBytes = 2;
            //break;

            case PixelFormat.Luminance:
            //case PixelFormat.Intensity:
            case PixelFormat.Alpha:
                _LightMapBytes = 1;
                break;
            }

            for (int j = 1; j < QDef.MAX_MODELS; j++)
            {
                model_t m = Client.cl.model_precache[j];
                if (m == null)
                {
                    break;
                }

                if (m.name != null && m.name.StartsWith("*"))
                {
                    continue;
                }

                _CurrentVertBase = m.vertexes;
                _CurrentModel    = m;
                for (int i = 0; i < m.numsurfaces; i++)
                {
                    CreateSurfaceLightmap(m.surfaces[i]);
                    if ((m.surfaces[i].flags & Surf.SURF_DRAWTURB) != 0)
                    {
                        continue;
                    }

                    if ((m.surfaces[i].flags & Surf.SURF_DRAWSKY) != 0)
                    {
                        continue;
                    }

                    BuildSurfaceDisplayList(m.surfaces[i]);
                }
            }

            if (_glTexSort.Value == 0)
            {
                Drawer.SelectTexture(MTexTarget.TEXTURE1_SGIS);
            }

            //
            // upload all lightmaps that were filled
            //
            GCHandle handle = GCHandle.Alloc(_LightMaps, GCHandleType.Pinned);

            try
            {
                IntPtr ptr    = handle.AddrOfPinnedObject();
                long   lmAddr = ptr.ToInt64();

                for (int i = 0; i < MAX_LIGHTMAPS; i++)
                {
                    if (_Allocated[i, 0] == 0)
                    {
                        break;          // no more used
                    }
                    _LightMapModified[i]     = false;
                    _LightMapRectChange[i].l = BLOCK_WIDTH;
                    _LightMapRectChange[i].t = BLOCK_HEIGHT;
                    _LightMapRectChange[i].w = 0;
                    _LightMapRectChange[i].h = 0;
                    Drawer.Bind(_LightMapTextures + i);
                    Drawer.SetTextureFilters(TextureMinFilter.Linear, TextureMagFilter.Linear);

                    long addr = lmAddr + i * BLOCK_WIDTH * BLOCK_HEIGHT * _LightMapBytes;
                    GL.TexImage2D(TextureTarget.Texture2D, 0, (PixelInternalFormat)_LightMapBytes,
                                  BLOCK_WIDTH, BLOCK_HEIGHT, 0, Drawer.LightMapFormat, PixelType.UnsignedByte, new IntPtr(addr));
                }
            }
            finally
            {
                handle.Free();
            }

            if (_glTexSort.Value == 0)
            {
                Drawer.SelectTexture(MTexTarget.TEXTURE0_SGIS);
            }
        }
Пример #16
0
 private static void AssertByrefPointsToStack(IntPtr ptr) {
     if (Marshal.ReadInt32(ptr) == _dummyMarker) {
         // Prevent recursion
         return;
     }
     int dummy = _dummyMarker;
     IntPtr ptrToLocal = ConvertInt32ByrefToPtr(ref dummy);
     Debug.Assert(ptrToLocal.ToInt64() < ptr.ToInt64());
     Debug.Assert((ptr.ToInt64() - ptrToLocal.ToInt64()) < (16 * 1024));
 }
Пример #17
0
 // we need a synchronized add and remove so that multiple threads
 // update the data store concurrently
 private static bool TryGetSessionTransportManager(IntPtr operationContext,
     out WSManClientSessionTransportManager sessnTransportManager,
     out long sessnTMId)
 {
     sessnTMId = operationContext.ToInt64();
     sessnTransportManager = null;
     lock (s_sessionTMHandles)
     {
         return s_sessionTMHandles.TryGetValue(sessnTMId, out sessnTransportManager);
     }
 }
Пример #18
0
        public static IntPtr GetExportAddress(IntPtr ModuleBase, string ExportName)
        {
            IntPtr FunctionPtr = IntPtr.Zero;

            try
            {
                Int32 PeHeader      = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C));
                Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14));
                Int64 OptHeader     = ModuleBase.ToInt64() + PeHeader + 0x18;
                Int16 Magic         = Marshal.ReadInt16((IntPtr)OptHeader);
                Int64 pExport       = 0;
                if (Magic == 0x010b)
                {
                    pExport = OptHeader + 0x60;
                }
                else
                {
                    pExport = OptHeader + 0x70;
                }
                Int32 ExportRVA         = Marshal.ReadInt32((IntPtr)pExport);
                Int32 OrdinalBase       = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10));
                Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14));
                Int32 NumberOfNames     = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18));
                Int32 FunctionsRVA      = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C));
                Int32 NamesRVA          = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20));
                Int32 OrdinalsRVA       = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24));
                for (int i = 0; i < NumberOfNames; i++)
                {
                    string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));
                    if (FunctionName.Equals(ExportName, StringComparison.OrdinalIgnoreCase))
                    {
                        Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;
                        Int32 FunctionRVA     = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));
                        FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);
                        break;
                    }
                }
            }
            catch
            {
                throw new InvalidOperationException("Failed to parse module exports.");
            }

            if (FunctionPtr == IntPtr.Zero)
            {
                throw new MissingMethodException(ExportName + ", export function not found.");
            }
            return(FunctionPtr);
        }
Пример #19
0
 /// <summary>
 /// Determines whether the specified memory pointer is aligned in memory.
 /// </summary>
 /// <param name="memoryPtr">The memory pointer.</param>
 /// <param name="align">The align.</param>
 /// <returns><c>true</c> if the specified memory pointer is aligned in memory; otherwise, <c>false</c>.</returns>
 public static bool IsMemoryAligned(IntPtr memoryPtr, int align = 16)
 {
     return((memoryPtr.ToInt64() & (align - 1)) == 0);
 }
Пример #20
0
        internal static LinkTargetInfo GetLinkTargetInfoInternal(SafeFileHandle safeHandle)
        {
            // Start with a large buffer to prevent a 2nd call.
            uint bytesReturned = NativeMethods.MaxPathUnicode;

            using (SafeGlobalMemoryBufferHandle safeBuffer = new SafeGlobalMemoryBufferHandle((int)bytesReturned))
            {
                do
                {
                    // Possible PInvoke signature bug: safeBuffer.Capacity and bytesReturned are always the same.
                    // Since a large buffer is used, we are not affected.

                    // DeviceIoControlMethod.Buffered = 0,
                    // DeviceIoControlFileDevice.FileSystem = 9
                    // FsctlGetReparsePoint = (DeviceIoControlFileDevice.FileSystem << 16) | (42 << 2) | DeviceIoControlMethod.Buffered | (0 << 14)

                    if (!NativeMethods.DeviceIoControl(safeHandle, ((9 << 16) | (42 << 2) | 0 | (0 << 14)), IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, out bytesReturned, IntPtr.Zero))
                    {
                        int lastError = Marshal.GetLastWin32Error();
                        switch ((uint)lastError)
                        {
                        case Win32Errors.ERROR_MORE_DATA:
                        case Win32Errors.ERROR_INSUFFICIENT_BUFFER:
                            if (safeBuffer.Capacity < bytesReturned)
                            {
                                safeBuffer.Close();
                                break;
                            }

                            // Throws IOException.
                            NativeError.ThrowException(lastError, true);
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                } while (true);



                // CA2001:AvoidCallingProblematicMethods

                IntPtr buffer     = IntPtr.Zero;
                bool   successRef = false;
                safeBuffer.DangerousAddRef(ref successRef);

                // MSDN: The DangerousGetHandle method poses a security risk because it can return a handle that is not valid.
                if (successRef)
                {
                    buffer = safeBuffer.DangerousGetHandle();
                }

                safeBuffer.DangerousRelease();

                if (buffer == IntPtr.Zero)
                {
                    NativeError.ThrowException(Resources.HandleDangerousRef);
                }

                // CA2001:AvoidCallingProblematicMethods


                Type   toMountPointReparseBuffer   = typeof(NativeMethods.MountPointReparseBuffer);
                Type   toReparseDataBufferHeader   = typeof(NativeMethods.ReparseDataBufferHeader);
                Type   toSymbolicLinkReparseBuffer = typeof(NativeMethods.SymbolicLinkReparseBuffer);
                IntPtr marshalReparseBuffer        = Marshal.OffsetOf(toReparseDataBufferHeader, "data");

                NativeMethods.ReparseDataBufferHeader header = Utils.MarshalPtrToStructure <NativeMethods.ReparseDataBufferHeader>(0, buffer);

                IntPtr dataPos;
                byte[] dataBuffer;

                switch (header.ReparseTag)
                {
                case ReparsePointTag.MountPoint:
                    NativeMethods.MountPointReparseBuffer mprb = Utils.MarshalPtrToStructure <NativeMethods.MountPointReparseBuffer>(0, new IntPtr(buffer.ToInt64() + marshalReparseBuffer.ToInt64()));

                    dataPos    = new IntPtr(marshalReparseBuffer.ToInt64() + Marshal.OffsetOf(toMountPointReparseBuffer, "data").ToInt64());
                    dataBuffer = new byte[bytesReturned - dataPos.ToInt64()];

                    Marshal.Copy(new IntPtr(buffer.ToInt64() + dataPos.ToInt64()), dataBuffer, 0, dataBuffer.Length);

                    return(new LinkTargetInfo(
                               Encoding.Unicode.GetString(dataBuffer, mprb.SubstituteNameOffset, mprb.SubstituteNameLength),
                               Encoding.Unicode.GetString(dataBuffer, mprb.PrintNameOffset, mprb.PrintNameLength)));


                case ReparsePointTag.SymLink:
                    NativeMethods.SymbolicLinkReparseBuffer slrb = Utils.MarshalPtrToStructure <NativeMethods.SymbolicLinkReparseBuffer>(0, new IntPtr(buffer.ToInt64() + marshalReparseBuffer.ToInt64()));

                    dataPos    = new IntPtr(marshalReparseBuffer.ToInt64() + Marshal.OffsetOf(toSymbolicLinkReparseBuffer, "data").ToInt64());
                    dataBuffer = new byte[bytesReturned - dataPos.ToInt64()];

                    Marshal.Copy(new IntPtr(buffer.ToInt64() + dataPos.ToInt64()), dataBuffer, 0, dataBuffer.Length);

                    return(new SymbolicLinkTargetInfo(
                               Encoding.Unicode.GetString(dataBuffer, slrb.SubstituteNameOffset, slrb.SubstituteNameLength),
                               Encoding.Unicode.GetString(dataBuffer, slrb.PrintNameOffset, slrb.PrintNameLength), slrb.Flags));


                default:
                    throw new UnrecognizedReparsePointException();
                }
            }
        }
Пример #21
0
        public Dictionary <string, object> GetProperties(LegacyJsonConverter.EventRecord eventRecord)
        {
            Dictionary <string, object> dictionary = new Dictionary <string, object>(traceEventInfo.TopLevelPropertyCount);

            if (hasProperties)
            {
                int    num1 = 0;
                IntPtr num2;
                for (int index = 0; index < traceEventInfo.TopLevelPropertyCount; ++index)
                {
                    EventPropertyInfo eventPropertyInfo = eventPropertyInfoArray[index];
                    string            stringUni         = Marshal.PtrToStringUni(new IntPtr(address.ToInt64() + eventPropertyInfo.NameOffset));
                    num2 = new IntPtr(eventRecord.UserData.ToInt64() + num1);
                    int    length;
                    object obj = null;
                    length = eventPropertyInfo.LengthPropertyIndex;
                    switch (eventPropertyInfo.NonStructTypeValue.InType)
                    {
                    case EventPropertyInfo.TdhInType.UnicodeString:
                        string stringUni2 = Marshal.PtrToStringUni(num2);
                        if (stringUni != null)
                        {
                            length = (stringUni2.Length + 1) * 2;
                            obj    = stringUni2;
                        }

                        break;

                    case EventPropertyInfo.TdhInType.Int32:
                        obj = Marshal.ReadInt32(num2);
                        break;

                    case EventPropertyInfo.TdhInType.UInt32:
                        obj = (uint)Marshal.ReadInt32(num2);
                        break;

                    case EventPropertyInfo.TdhInType.Int64:
                        obj = Marshal.ReadInt64(num2);
                        break;

                    case EventPropertyInfo.TdhInType.UInt64:
                        obj = (ulong)Marshal.ReadInt64(num2);
                        break;

                    case EventPropertyInfo.TdhInType.Pointer:
                        obj = Marshal.ReadIntPtr(num2);
                        break;

                    case EventPropertyInfo.TdhInType.FileTime:
                        obj = DateTime.FromFileTime(Marshal.ReadInt64(num2));
                        break;

                    case EventPropertyInfo.TdhInType.SystemTime:
                        obj = new DateTime(Marshal.ReadInt16(num2),
                                           Marshal.ReadInt16(num2, 2), Marshal.ReadInt16(num2, 6),
                                           Marshal.ReadInt16(num2, 8), Marshal.ReadInt16(num2, 10),
                                           Marshal.ReadInt16(num2, 12), Marshal.ReadInt16(num2, 14));
                        break;
                    }

                    num1 += length;
                    if (stringUni != null)
                    {
                        dictionary.Add(stringUni, obj);
                    }
                }
                if (num1 < eventRecord.UserDataLength)
                {
                    num2 = new IntPtr(eventRecord.UserData.ToInt64() + num1);
                    int    length   = eventRecord.UserDataLength - num1;
                    byte[] numArray = new byte[length];
                    for (int ofs = 0; ofs < length; ++ofs)
                    {
                        numArray[ofs] = Marshal.ReadByte(num2, ofs);
                    }
                    dictionary.Add("__ExtraPayload", numArray);
                }
            }
            else
            {
                string stringUni = Marshal.PtrToStringUni(eventRecord.UserData);
                dictionary.Add("EventData", stringUni);
            }
            return(dictionary);
        }
Пример #22
0
        /// <summary>
        /// Changes the page permissions for a specified combination of address and length via Windows API calls.
        /// </summary>
        /// <param name="memoryAddress">The memory address for which to change page permissions for.</param>
        /// <param name="length">The region size for which to change permissions for.</param>
        /// <param name="newPermissions">The new permissions to set.</param>
        /// <returns>The old page permissions.</returns>
        public static MemoryProtection ChangePermission(IntPtr memoryAddress, int length, MemoryProtection newPermissions)
        {
            var result = VirtualProtect(memoryAddress, (UIntPtr)length, newPermissions, out var oldPermissions);

            if (!result)
            {
                throw new MemoryPermissionException($"Unable to change permissions at 0x{memoryAddress.ToInt64():X} of length {length} and permission {newPermissions} (result={result})");
            }

            var last = Marshal.GetLastWin32Error();

            if (last > 0)
            {
                throw new MemoryPermissionException($"Unable to change permissions at 0x{memoryAddress.ToInt64():X} of length {length} and permission {newPermissions} (error={last})");
            }

            return(oldPermissions);
        }
Пример #23
0
        internal Redirection(MethodBase original, MethodBase replacement, bool start)
        {
            Original    = original;
            Replacement = replacement;

            // Note: I'm making local copies of the following fields to avoid accessing fields multiple times.
            RuntimeMethodHandle originalHandle    = original.MethodHandle;
            RuntimeMethodHandle replacementHandle = replacement.MethodHandle;

            // Fetch their respective start
            IntPtr originalStart    = Helpers.GetMethodStart(originalHandle);
            IntPtr replacementStart = Helpers.GetMethodStart(replacementHandle);

            // Edge case: calling this on the same method
            if (originalStart == replacementStart)
            {
                throw new InvalidOperationException("Cannot redirect a method to itself.");
            }

            // Edge case: methods are too close to one another
            int difference = (int)Math.Abs(originalStart.ToInt64() - replacementStart.ToInt64());
            int sizeOfPtr  = Marshal.SizeOf(typeof(IntPtr));

            if ((sizeOfPtr == sizeof(long) && difference < 13) || (sizeOfPtr == sizeof(int) && difference < 7))
            {
                throw new InvalidOperationException("Unable to redirect methods whose bodies are too close to one another.");
            }

            // Make sure they're jitted
            if (!Helpers.HasBeenCompiled(originalStart))
            {
                RuntimeHelpers.PrepareMethod(originalHandle);

                originalStart = Helpers.GetMethodStart(originalHandle);
            }

            if (!Helpers.HasBeenCompiled(replacementStart))
            {
                RuntimeHelpers.PrepareMethod(replacementHandle);

                replacementStart = Helpers.GetMethodStart(replacementHandle);
            }

            // Copy local value to field
            originalMethodStart = originalStart;

            // In some cases, the memory might need to be readable / writable:
            // Make the memory region rw right away just in case.
            Helpers.AllowRW(originalStart);

            // Save bytes to change to redirect method
            byte[] replBytes = replacementBytes = Helpers.GetJmpBytes(replacementStart);
            byte[] origBytes = originalBytes = new byte[replBytes.Length];

            Marshal.Copy(originalStart, origBytes, 0, origBytes.Length);

            if (start)
            {
                CopyToStart(replBytes, originalStart);
                isRedirecting = true;
            }

            // Save methods in static array to make sure they're not garbage collected
            PersistingMethods.Add(original);
            PersistingMethods.Add(replacement);
        }
Пример #24
0
		private static ServiceController [] GetServiceDependencies (string serviceName, string machineName)
		{
			IntPtr scHandle = IntPtr.Zero;
			IntPtr svcHandle = IntPtr.Zero;
			IntPtr buffer = IntPtr.Zero;

			try {
				scHandle = OpenServiceControlManager (machineName,
					SERVICE_MANAGER_RIGHTS.SC_MANAGER_CONNECT);

				svcHandle = OpenService (scHandle, serviceName, SERVICE_RIGHTS.SERVICE_QUERY_CONFIG);
				if (svcHandle == IntPtr.Zero)
					throw CreateCannotOpenServiceException (serviceName, machineName);

				uint bufferSize = 0;
				uint bytesNeeded = 0;

				ServiceController [] services;

				while (true) {
					if (!QueryServiceConfig (svcHandle, buffer, bufferSize, out bytesNeeded)) {
						int err = Marshal.GetLastWin32Error ();
						if (err == ERROR_INSUFFICIENT_BUFFER) {
							buffer = Marshal.AllocHGlobal ((int) bytesNeeded);
							bufferSize = bytesNeeded;
						} else {
							throw new Win32Exception (err);
						}
					} else {
						QUERY_SERVICE_CONFIG config = (QUERY_SERVICE_CONFIG) Marshal.PtrToStructure (
							buffer, typeof (QUERY_SERVICE_CONFIG));

						Hashtable depServices = new Hashtable ();
						IntPtr iPtr = config.lpDependencies;
						StringBuilder sb = new StringBuilder ();
						string currentChar = Marshal.PtrToStringUni (iPtr, 1);
						while (currentChar != "\0") {
							sb.Append (currentChar);
							iPtr = new IntPtr (iPtr.ToInt64 () + Marshal.SystemDefaultCharSize);
							currentChar = Marshal.PtrToStringUni (iPtr, 1);
							if (currentChar != "\0") {
								continue;
							}
							iPtr = new IntPtr (iPtr.ToInt64 () + Marshal.SystemDefaultCharSize);
							currentChar = Marshal.PtrToStringUni (iPtr, 1);
							string dependency = sb.ToString ();
							if (dependency [0] == SC_GROUP_IDENTIFIER) {
								ServiceController [] groupServices = GetServices (
									machineName, SERVICE_TYPE.SERVICE_WIN32,
									dependency.Substring (1));
								foreach (ServiceController sc in groupServices) {
									if (!depServices.Contains (sc.ServiceName))
										depServices.Add (sc.ServiceName, sc);
								}
							} else if (!depServices.Contains (dependency)) {
								depServices.Add (dependency, new ServiceController (dependency, machineName));
							}
							sb.Length = 0;
						}

						services = new ServiceController [depServices.Count];
						depServices.Values.CopyTo (services, 0);
						break;
					}
				}

				return services;
			} finally {
				if (scHandle != IntPtr.Zero)
					CloseServiceHandle (scHandle);
				if (svcHandle != IntPtr.Zero)
					CloseServiceHandle (svcHandle);
				if (buffer != IntPtr.Zero)
					Marshal.FreeHGlobal (buffer);
			}
		}
Пример #25
0
        public static AccessTokenGroups FromTokenHandle(AccessTokenHandle handle)
        {
            uint tokenInfLength = 0;
            bool success;

            IntPtr hToken = handle.GetHandle();

            success = Advapi32.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenGroups, IntPtr.Zero, tokenInfLength, out tokenInfLength);
            IntPtr tokenInfo = Marshal.AllocHGlobal(Convert.ToInt32(tokenInfLength));

            success = Advapi32.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenGroups, tokenInfo, tokenInfLength, out tokenInfLength);

            if (success)
            {
                var parsedGroups = new List <ATGroup>();

                TOKEN_GROUPS groups = (TOKEN_GROUPS)Marshal.PtrToStructure(tokenInfo, typeof(TOKEN_GROUPS));

                var sidAndAttrSize = Marshal.SizeOf(new SID_AND_ATTRIBUTES());

                for (int i = 0; i < groups.GroupCount; i++)
                {
                    var saa        = (SID_AND_ATTRIBUTES)Marshal.PtrToStructure(new IntPtr(tokenInfo.ToInt64() + i * sidAndAttrSize + IntPtr.Size), typeof(SID_AND_ATTRIBUTES));
                    var sid        = saa.Sid;
                    var attributes = saa.Attributes;

                    IntPtr strPtr;
                    var    sidString = "";
                    if (Advapi32.ConvertSidToStringSid(sid, out strPtr))
                    {
                        sidString = Marshal.PtrToStringAuto(strPtr);
                    }
                    else
                    {
                        Logger.GetInstance().Error($"Failed to convert SID to string. ConvertSidToStringSid failed with error: {Kernel32.GetLastError()}");
                        sidString = "UNKNOWN";
                    }

                    int    length   = Convert.ToInt32(Advapi32.GetLengthSid(sid));
                    byte[] sidBytes = new byte[length];
                    Marshal.Copy(sid, sidBytes, 0, length);
                    StringBuilder lpName    = new StringBuilder();
                    uint          cchname   = (uint)lpName.Capacity;
                    StringBuilder lpdomain  = new StringBuilder();
                    uint          cchdomain = (uint)lpdomain.Capacity;
                    SID_NAME_USE  peUse;

                    var name   = "";
                    var domain = "";
                    if (!Advapi32.LookupAccountSid(null, sidBytes, lpName, ref cchname, lpdomain, ref cchdomain, out peUse))
                    {
                        var err = Kernel32.GetLastError();
                        if (err == Constants.ERROR_INSUFFICIENT_BUFFER)
                        {
                            lpName.EnsureCapacity((int)cchname);
                            lpdomain.EnsureCapacity((int)cchdomain);


                            if (!Advapi32.LookupAccountSid(null, sidBytes, lpName, ref cchname, lpdomain, ref cchdomain, out peUse))
                            {
                                Logger.GetInstance().Error($"Failed to lookup name and domain from SID. LookupAccountSid failed with error: {err}");
                                name   = "UNKNOWN";
                                domain = "UNKNOWN";
                            }
                            else
                            {
                                name   = lpName.ToString();
                                domain = lpdomain.ToString();
                            }
                        }
                    }
                    else
                    {
                        name   = lpName.ToString();
                        domain = lpdomain.ToString();
                    }

                    parsedGroups.Add(new ATGroup(sidString, sid, attributes, name, domain, peUse));
                }

                Marshal.FreeHGlobal(tokenInfo);
                return(new AccessTokenGroups(parsedGroups));
            }
            else
            {
                Marshal.FreeHGlobal(tokenInfo);
                Logger.GetInstance().Error($"Failed to retreive session id information for access token. GetTokenInformation failed with error: {Kernel32.GetLastError()}");
                throw new TokenInformationException();
            }
        }
Пример #26
0
        private bool _obtainDeviceHandle()
        {
            try
            {
                // Used to capture how many bytes are returned by system calls
                UInt32 theBytesReturned = 0;

                // SetupAPI32.DLL Data Structures
                SP_DEVICE_INTERFACE_DETAIL_DATA theDevDetailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                SP_DEVINFO_DATA theDevInfoData = new SP_DEVINFO_DATA();
                theDevInfoData.cbSize = Marshal.SizeOf(theDevInfoData);
                IntPtr theDevInfo = SetupDiGetClassDevs(ref DeviceGuid, IntPtr.Zero, IntPtr.Zero, (int)(DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_DEVICEINTERFACE));
                SP_DEVICE_INTERFACE_DATA theInterfaceData = new SP_DEVICE_INTERFACE_DATA();
                theInterfaceData.cbSize = Marshal.SizeOf(theInterfaceData);

                // Check for a Garmin Device
                if (!SetupDiEnumDeviceInterfaces(theDevInfo, IntPtr.Zero, ref DeviceGuid, 0, ref theInterfaceData) && GetLastError() == ERROR_NO_MORE_ITEMS)
                {
                    gHandle = null;
                    return(false);
                }

                // Get the device's file path
                SetupDiGetDeviceInterfaceDetail(theDevInfo, ref theInterfaceData, IntPtr.Zero, 0, ref theBytesReturned, IntPtr.Zero);

                if (theBytesReturned <= 0)
                {
                    gHandle = null;
                    return(false);
                }

                IntPtr tmpBuffer = Marshal.AllocHGlobal((int)theBytesReturned);
                if (IntPtr.Size == 4)
                {
                    Marshal.WriteInt32(tmpBuffer, 4 + Marshal.SystemDefaultCharSize);
                }
                else
                {
                    Marshal.WriteInt32(tmpBuffer, 8);
                }

                theDevDetailData.cbSize = Marshal.SizeOf(theDevDetailData);
                SetupDiGetDeviceInterfaceDetail(theDevInfo, ref theInterfaceData, tmpBuffer, theBytesReturned, IntPtr.Zero, ref theDevInfoData);

                IntPtr pDevicePathName = new IntPtr(tmpBuffer.ToInt64() + 4);
                String devicePathName  = Marshal.PtrToStringAuto(pDevicePathName);

                // Create a handle to the device
                gHandle = CreateFile(devicePathName, ((UInt32)(GenericAccessRights.GenericRead | GenericAccessRights.GenericWrite)), 0, IntPtr.Zero, (UInt32)FileCreationDisposition.OpenExisting, (UInt32)FileAttributes.Normal, IntPtr.Zero);

                // Get the driver's asynchronous packet size
                if (tmpBuffer.Equals(IntPtr.Zero))
                {
                    Marshal.FreeHGlobal(tmpBuffer);
                }
                tmpBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(gUSBPacketSize));

                DeviceIoControl(gHandle, IOCTL_USB_PACKET_SIZE, IntPtr.Zero, 0, tmpBuffer, (UInt32)Marshal.SizeOf(gUSBPacketSize), ref theBytesReturned, IntPtr.Zero);

                switch (theBytesReturned)
                {
                case 2:
                    gUSBPacketSize = Marshal.ReadInt16(tmpBuffer);
                    break;

                case 4:
                    gUSBPacketSize = Marshal.ReadInt32(tmpBuffer);
                    break;

                case 8:
                    gUSBPacketSize = Marshal.ReadInt64(tmpBuffer);
                    break;
                }
                if (!tmpBuffer.Equals(IntPtr.Zero))
                {
                    Marshal.FreeHGlobal(tmpBuffer);
                }
            }
            catch
            {
                return(false);
            }

            return(true);
        }
 public virtual bool runTest()
   {
   Console.Error.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
   int iCountErrors = 0;
   int iCountTestcases = 0;
   String strLoc = "Loc_000oo";
   Int64 lValue;
   IntPtr ip1;
   try {
   strLoc = "Loc_743wg";
   lValue = 16;
   ip1 = new IntPtr(lValue);
   iCountTestcases++;
   if(ip1.ToInt64() != lValue){
   iCountErrors++;
   Console.WriteLine("Err_2975sf! Wrong value returned");
   }
   strLoc = "Loc_0084wf";
   lValue = 0;
   ip1 = new IntPtr(lValue);
   iCountTestcases++;
   if(ip1.ToInt64() != IntPtr.Zero.ToInt64()){
   iCountErrors++;
   Console.WriteLine("Err_974325sdg! Wrong value returned");
   }
   strLoc = "Loc_00s42f";
   lValue = -15;
   ip1 = new IntPtr(lValue);
   iCountTestcases++;
   if(ip1.ToInt64() != lValue){
   iCountErrors++;
   Console.WriteLine("Err_9374fzdg! Wrong value returned");
   }
   strLoc = "Loc_93476sdg";
   lValue = Int32.MaxValue;
   ip1 = new IntPtr(lValue);
   iCountTestcases++;
   if(ip1.ToInt64() != lValue){
   iCountErrors++;
   Console.WriteLine("Err_07536tsg! Wrong value returned");
   }
   lValue = Int32.MinValue;
   ip1 = new IntPtr(lValue);
   if(ip1.ToInt64() != lValue){
   iCountErrors++;
   Console.WriteLine("Err_9875wrsg! Wrong value returned");
   }
   strLoc = "Loc_8745sdg";
   lValue = Int64.MaxValue;
   iCountTestcases++;
   try{
   ip1 = new IntPtr(lValue);
   iCountErrors++;
   Console.WriteLine("Err_874325sdg! No oexception thrown. Is this a 64 bit machine? or has the functionality changed?");
   }catch(OverflowException){
   }catch(Exception ex){
   iCountErrors++;
   Console.WriteLine("Err_82375d! Wrong Exception returned, " + ex.GetType().Name);
   }
   lValue = Int64.MinValue;
   iCountTestcases++;
   try{
   ip1 = new IntPtr(lValue);
   iCountErrors++;
   Console.WriteLine("Err_9475sdg! No oexception thrown. Is this a 64 bit machine? or has the functionality changed?");
   }catch(OverflowException){
   }catch(Exception ex){
   iCountErrors++;
   Console.WriteLine("Err_297435sdg! Wrong Exception returned, " + ex.GetType().Name);
   }
   } catch (Exception exc_general ) {
   ++iCountErrors;
   Console.WriteLine(s_strTFAbbrev +" Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general=="+exc_general);
   }
   if ( iCountErrors == 0 )
     {
     Console.Error.WriteLine( "paSs.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
     return true;
     }
   else
     {
     Console.Error.WriteLine("FAiL!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
     return false;
     }
   }
Пример #28
0
        /// <summary>
        /// Rewrite IAT for manually mapped module.
        /// </summary>
        /// <author>Ruben Boonen (@FuzzySec)</author>
        /// <param name="PEINFO">Module meta data struct (PE.PE_META_DATA).</param>
        /// <param name="ModuleMemoryBase">Base address of the module in memory.</param>
        /// <returns>void</returns>
        public static void RewriteModuleIAT(Data.PE.PE_META_DATA PEINFO, IntPtr ModuleMemoryBase)
        {
            Data.PE.IMAGE_DATA_DIRECTORY idd = PEINFO.Is32Bit ? PEINFO.OptHeader32.ImportTable : PEINFO.OptHeader64.ImportTable;

            // Check if there is no import table
            if (idd.VirtualAddress == 0)
            {
                // Return so that the rest of the module mapping process may continue.
                return;
            }

            // Ptr for the base import directory
            IntPtr pImportTable = (IntPtr)((UInt64)ModuleMemoryBase + idd.VirtualAddress);

            // Get API Set mapping dictionary if on Win10+
            Data.Native.OSVERSIONINFOEX OSVersion = new Data.Native.OSVERSIONINFOEX();
            DynamicInvoke.Native.RtlGetVersion(ref OSVersion);
            Dictionary <string, string> ApiSetDict = new Dictionary <string, string>();

            if (OSVersion.MajorVersion >= 10)
            {
                ApiSetDict = DynamicInvoke.Generic.GetApiSetMapping();
            }

            // Loop IID's
            int counter = 0;

            Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR iid = new Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR();
            iid = (Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)Marshal.PtrToStructure(
                (IntPtr)((UInt64)pImportTable + (uint)(Marshal.SizeOf(iid) * counter)),
                typeof(Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)
                );
            while (iid.Name != 0)
            {
                // Get DLL
                string DllName = string.Empty;
                try
                {
                    DllName = Marshal.PtrToStringAnsi((IntPtr)((UInt64)ModuleMemoryBase + iid.Name));
                }
                catch { }

                // Loop imports
                if (DllName == string.Empty)
                {
                    throw new InvalidOperationException("Failed to read DLL name.");
                }
                else
                {
                    string LookupKey = DllName.Substring(0, DllName.Length - 6) + ".dll";
                    // API Set DLL? Ignore the patch number.
                    if (OSVersion.MajorVersion >= 10 && (DllName.StartsWith("api-") || DllName.StartsWith("ext-")) &&
                        ApiSetDict.ContainsKey(LookupKey) && ApiSetDict[LookupKey].Length > 0)
                    {
                        // Not all API set DLL's have a registered host mapping
                        DllName = ApiSetDict[LookupKey];
                    }

                    // Check and / or load DLL
                    IntPtr hModule = DynamicInvoke.Generic.GetLoadedModuleAddress(DllName);
                    if (hModule == IntPtr.Zero)
                    {
                        hModule = DynamicInvoke.Generic.LoadModuleFromDisk(DllName);
                        if (hModule == IntPtr.Zero)
                        {
                            throw new FileNotFoundException(DllName + ", unable to find the specified file.");
                        }
                    }

                    // Loop thunks
                    if (PEINFO.Is32Bit)
                    {
                        Data.PE.IMAGE_THUNK_DATA32 oft_itd = new Data.PE.IMAGE_THUNK_DATA32();
                        for (int i = 0; true; i++)
                        {
                            oft_itd = (Data.PE.IMAGE_THUNK_DATA32)Marshal.PtrToStructure((IntPtr)((UInt64)ModuleMemoryBase + iid.OriginalFirstThunk + (UInt32)(i * (sizeof(UInt32)))), typeof(Data.PE.IMAGE_THUNK_DATA32));
                            IntPtr ft_itd = (IntPtr)((UInt64)ModuleMemoryBase + iid.FirstThunk + (UInt64)(i * (sizeof(UInt32))));
                            if (oft_itd.AddressOfData == 0)
                            {
                                break;
                            }

                            if (oft_itd.AddressOfData < 0x80000000) // !IMAGE_ORDINAL_FLAG32
                            {
                                IntPtr pImpByName = (IntPtr)((UInt64)ModuleMemoryBase + oft_itd.AddressOfData + sizeof(UInt16));
                                IntPtr pFunc      = IntPtr.Zero;
                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, Marshal.PtrToStringAnsi(pImpByName));

                                // Write ProcAddress
                                Marshal.WriteInt32(ft_itd, pFunc.ToInt32());
                            }
                            else
                            {
                                ulong  fOrdinal = oft_itd.AddressOfData & 0xFFFF;
                                IntPtr pFunc    = IntPtr.Zero;
                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, (short)fOrdinal);

                                // Write ProcAddress
                                Marshal.WriteInt32(ft_itd, pFunc.ToInt32());
                            }
                        }
                    }
                    else
                    {
                        Data.PE.IMAGE_THUNK_DATA64 oft_itd = new Data.PE.IMAGE_THUNK_DATA64();
                        for (int i = 0; true; i++)
                        {
                            oft_itd = (Data.PE.IMAGE_THUNK_DATA64)Marshal.PtrToStructure((IntPtr)((UInt64)ModuleMemoryBase + iid.OriginalFirstThunk + (UInt64)(i * (sizeof(UInt64)))), typeof(Data.PE.IMAGE_THUNK_DATA64));
                            IntPtr ft_itd = (IntPtr)((UInt64)ModuleMemoryBase + iid.FirstThunk + (UInt64)(i * (sizeof(UInt64))));
                            if (oft_itd.AddressOfData == 0)
                            {
                                break;
                            }

                            if (oft_itd.AddressOfData < 0x8000000000000000) // !IMAGE_ORDINAL_FLAG64
                            {
                                IntPtr pImpByName = (IntPtr)((UInt64)ModuleMemoryBase + oft_itd.AddressOfData + sizeof(UInt16));
                                IntPtr pFunc      = IntPtr.Zero;
                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, Marshal.PtrToStringAnsi(pImpByName));

                                // Write pointer
                                Marshal.WriteInt64(ft_itd, pFunc.ToInt64());
                            }
                            else
                            {
                                ulong  fOrdinal = oft_itd.AddressOfData & 0xFFFF;
                                IntPtr pFunc    = IntPtr.Zero;
                                pFunc = DynamicInvoke.Generic.GetNativeExportAddress(hModule, (short)fOrdinal);

                                // Write pointer
                                Marshal.WriteInt64(ft_itd, pFunc.ToInt64());
                            }
                        }
                    }

                    // Go to the next IID
                    counter++;
                    iid = (Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)Marshal.PtrToStructure(
                        (IntPtr)((UInt64)pImportTable + (uint)(Marshal.SizeOf(iid) * counter)),
                        typeof(Data.Win32.Kernel32.IMAGE_IMPORT_DESCRIPTOR)
                        );
                }
            }
        }
Пример #29
0
			public int StreamGetHeaderImpl (IntPtr buf, int bufsz)  {
				int	bytesRead;

				start_buf = new byte[bufsz];

				try {
					bytesRead = stream.Read (start_buf, 0, bufsz);
				} catch (IOException) {
					return -1;
				}

				if (bytesRead > 0 && buf != IntPtr.Zero) {
					Marshal.Copy (start_buf, 0, (IntPtr) (buf.ToInt64()), bytesRead);
				}

				start_buf_pos = 0;
				start_buf_len = bytesRead;

				return bytesRead;
			}
Пример #30
0
        internal static void SendModData(ModBase @base, int message, int remoteClient, int ignoreClient, params object[] toSend)
        {
            if (Main.netMode == 0)
            {
                return;
            }

            int num = 256;

            if (Main.netMode == 2 && remoteClient >= 0)
            {
                num = remoteClient;
            }

            lock (NetMessage.buffer[num])
            {
                BinBuffer bb = new BinBuffer(new BinBufferByte(NetMessage.buffer[num].writeBuffer, false));
                bb.Pos = 4;                     //for size
                bb.WriteX((byte)100, (byte)Mods.mods.IndexOf(@base.mod), (byte)message);

                // write stuff here

                for (int i = 0; i < toSend.Length; i++)
                {
                    Type t = toSend[i].GetType();

                    #region primitives
                    if (t == typeof(byte))
                    {
                        bb.Write((byte)toSend[i]);
                    }
                    else if (t == typeof(sbyte))
                    {
                        bb.Write((sbyte)toSend[i]);
                    }

                    else if (t == typeof(ushort))
                    {
                        bb.Write((ushort)toSend[i]);
                    }
                    else if (t == typeof(short))
                    {
                        bb.Write((short)toSend[i]);
                    }

                    else if (t == typeof(int))
                    {
                        bb.Write((int)toSend[i]);
                    }
                    else if (t == typeof(uint))
                    {
                        bb.Write((uint)toSend[i]);
                    }

                    else if (t == typeof(long))
                    {
                        bb.Write((long)toSend[i]);
                    }
                    else if (t == typeof(ulong))
                    {
                        bb.Write((ulong)toSend[i]);
                    }

                    else if (t == typeof(float))
                    {
                        bb.Write((float)toSend[i]);
                    }
                    else if (t == typeof(double))
                    {
                        bb.Write((double)toSend[i]);
                    }
                    else if (t == typeof(decimal))
                    {
                        bb.Write((decimal)toSend[i]);
                    }

                    else if (t == typeof(DateTime))
                    {
                        bb.Write((DateTime)toSend[i]);
                    }
                    else if (t == typeof(TimeSpan))
                    {
                        bb.Write((TimeSpan)toSend[i]);
                    }

                    else if (t == typeof(BigInteger))
                    {
                        bb.Write((BigInteger)toSend[i]);
                    }
                    else if (t == typeof(Complex))
                    {
                        bb.Write((Complex)toSend[i]);
                    }

                    else if (t == typeof(MemoryStream))
                    {
                        bb.Write(((MemoryStream)toSend[i]).ToArray().Length);
                        bb.Write(((MemoryStream)toSend[i]).ToArray());
                    }
                    else if (t == typeof(BinBuffer))
                    {
                        bb.Write(((BinBuffer)toSend[i]).BytesLeft);
                        bb.Write(((BinBuffer)toSend[i]));
                    }
                    else if (t == typeof(BinBufferAbstract) || t.IsSubclassOf(typeof(BinBufferAbstract)))
                    {
                        bb.Write(((BinBufferAbstract)toSend[i]).BytesLeft());
                        bb.Write((new BinBuffer((BinBufferAbstract)toSend[i])));
                    }

                    else if (t == typeof(Vector2))
                    {
                        bb.Write((Vector2)toSend[i]);
                    }
                    else if (t == typeof(Color))
                    {
                        bb.Write((Color)toSend[i]);
                    }
                    else if (t == typeof(Item))
                    {
                        bb.Write((Item)toSend[i]);
                    }
                    #endregion

                    #region value type -> can read from memory
                    else if (t.IsValueType && (t.IsExplicitLayout || t.IsLayoutSequential) && !t.IsGenericType)
                    {
                        // this is probably lunacy
                        int size = Marshal.SizeOf(toSend[i]);

                        GCHandle argHandle = GCHandle.Alloc(toSend[i], GCHandleType.Pinned);
                        IntPtr   offset    = argHandle.AddrOfPinnedObject();

                        bb.Write(size);
                        for (IntPtr ptr = offset; ptr.ToInt64() < offset.ToInt64() + size; ptr += 1)
                        {
                            bb.Write(Marshal.ReadByte(ptr));
                        }

                        argHandle.Free();

                        //IntPtr ptr = IntPtr.Zero;
                        //Marshal.StructureToPtr(toSend[i], ptr, false);
                        //int size = Marshal.SizeOf(toSend[i]);

                        //bb.Write(size);

                        //for (IntPtr addr = ptr; addr.ToInt64() < ptr.ToInt64() + size; addr += 1) // read byte per byte
                        //    bb.Write(Marshal.ReadByte(addr));
                    }
                    #endregion

                    #region serilizable -> can use binaryformatter
                    else if (t.IsSerializable || t.GetInterface("System.Runtime.Serialization.ISerializable") != null)
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        MemoryStream    ms = new MemoryStream();
                        bf.Serialize(ms, toSend[i]);
                        bb.Write(ms.ToArray().Length);
                        bb.Write(ms.ToArray());
                        ms.Close();
                    }
                    #endregion
                    else
                    {
                        throw new ArgumentException("Object must be a primitive, struct, or serializable.", "toSend[" + i + "]");
                    }
                }

                #region send some other stuff
                int pos = bb.Pos;
                bb.Pos = 0;
                bb.Write(pos - 4);
                bb.Pos = pos;

                if (Main.netMode == 1)
                {
                    if (!Netplay.clientSock.tcpClient.Connected)
                    {
                        goto End;
                    }
                }

                try
                {
                    NetMessage.buffer[num].spamCount++;
                    Main.txMsg++;
                    Main.txData += pos;
                    Main.txMsgType[100]++;
                    Main.txDataType[100] += pos;
                    Netplay.clientSock.networkStream.BeginWrite(NetMessage.buffer[num].writeBuffer, 0, pos, new AsyncCallback(Netplay.clientSock.ClientWriteCallBack), Netplay.clientSock.networkStream);
                }
                catch
                {
                    goto End;
                }

                if (remoteClient == -1)
                {
                    for (int i = 0; i < 256; i++)
                    {
                        if (i != ignoreClient && NetMessage.buffer[i].broadcast && Netplay.serverSock[i].tcpClient.Connected)
                        {
                            try
                            {
                                NetMessage.buffer[i].spamCount++;
                                Main.txMsg++;
                                Main.txData += pos;
                                Main.txMsgType[100]++;
                                Main.txDataType[100] += pos;
                                Netplay.serverSock[i].networkStream.BeginWrite(NetMessage.buffer[num].writeBuffer, 0, pos, new AsyncCallback(Netplay.serverSock[i].ServerWriteCallBack), Netplay.serverSock[i].networkStream);
                            }
                            catch (Exception)
                            { }
                        }

                        else if (Netplay.serverSock[remoteClient].tcpClient.Connected)
                        {
                            try
                            {
                                NetMessage.buffer[remoteClient].spamCount++;
                                Main.txMsg++;
                                Main.txData += pos;
                                Main.txMsgType[100]++;
                                Main.txDataType[100] += pos;
                                Netplay.serverSock[remoteClient].networkStream.BeginWrite(NetMessage.buffer[num].writeBuffer, 0, pos, new AsyncCallback(Netplay.serverSock[remoteClient].ServerWriteCallBack), Netplay.serverSock[remoteClient].networkStream);
                            }
                            catch (Exception)
                            { }
                        }
                    }
                }

End:
                NetMessage.buffer[num].writeLocked = false;
                #endregion
            }
        }
Пример #31
0
 private IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
 {
     if (msg == (int) UnmanagedMethods.WindowsMessage.WM_DISPATCH_WORK_ITEM && wParam.ToInt64() == SignalW && lParam.ToInt64() == SignalL)
     {
         Signaled?.Invoke();
     }
     return UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam);
 }
Пример #32
0
        /// <summary>
        /// Read the list of items.
        /// </summary>
        /// <param name="itemIds">Items to read.</param>
        /// <param name="values">The values that were read.</param>
        /// <param name="pErrors">Individual error code for each item</param>
        /// <returns>Returns true if read succeeded for all items. Otherwise returns false.</returns>
        public bool Read(StringCollection itemIds, out object[] values, out int[] pErrors)
        {
            bool bResult = true;

            values  = new object[itemIds.Count];
            pErrors = new int[itemIds.Count];

            if (!m_connected)
            {
                throw new InvalidOperationException("Not connected to OPC-Server!");
            }

            int[] serverHandles;

            try
            {
                bResult = GetServerHandles(itemIds, out serverHandles, out pErrors);
            }
            catch (Exception e)
            {
                throw e;
            }

            // build in parameters to read
            int[]     serverHandlesToRead;
            ArrayList indexesToRead    = new ArrayList();
            ArrayList indexesNotToRead = new ArrayList();
            ArrayList handlesTmp       = new ArrayList();


            // check each handle
            for (int i = 0; i < itemIds.Count; i++)
            {
                if (pErrors[i] == 0)
                {
                    handlesTmp.Add(serverHandles[i]);
                    indexesToRead.Add(i);
                }
                else
                {
                    indexesNotToRead.Add(i);
                }
            }
            serverHandlesToRead = (int[])handlesTmp.ToArray(typeof(int));

            if (serverHandlesToRead.Length == 0)
            {
                return(false);
            }

            IntPtr pItemValues;
            IntPtr ppErrors;

            try
            {
                m_syncIO.Read(
                    OPCDATASOURCE.OPC_DS_DEVICE,    // DataSource is Device or Cache
                    serverHandlesToRead.Length,     // Number of items to read
                    serverHandlesToRead,            //
                    out pItemValues,                //
                    out ppErrors);                  //
            }
            catch (Exception e)
            {
                throw e;
            }

            if (pItemValues == IntPtr.Zero)
            {
                throw new Exception("Read failed. No Results.");
            }
            if (ppErrors == IntPtr.Zero)
            {
                throw new Exception("Read failed. No ErrorCodes returned.");
            }

            int[] errorsTmp = Helper.GetInt32s(ref ppErrors, serverHandlesToRead.Length, true);

            int    indexTmp = 0;
            IntPtr pos      = pItemValues;

            // Fill result of items that were read
            foreach (int index in indexesToRead)
            {
                // set error code
                pErrors[index] = errorsTmp[indexTmp];

                OPCITEMSTATE itemState = (OpcRcw.Da.OPCITEMSTATE)Marshal.PtrToStructure(pos, typeof(OPCITEMSTATE));
                Marshal.DestroyStructure(pos, typeof(OpcRcw.Da.OPCITEMSTATE));
                pos = (IntPtr)(pos.ToInt64() + Marshal.SizeOf(typeof(OPCITEMSTATE)));

                // set value
                values[index] = itemState.vDataValue;

                indexTmp++;
            }

            Marshal.FreeCoTaskMem(pItemValues);
            pItemValues = IntPtr.Zero;

            // Fill results of items that were not read.
            foreach (int index in indexesNotToRead)
            {
                // error code was alread set above - just initialize value element
                values[index] = null;
            }

            return(bResult);
        }
Пример #33
0
        public object Invoke(object[] ObjArray_Parameter, Type[] TypeArray_ParameterType, ModePass[] ModePassArray_Parameter, Type Type_Return)
        {
            if (hModule == IntPtr.Zero)
            {
                throw (new Exception(" 函数库模块的句柄为空 , 请确保已进行 LoadDll 操作 !"));
            }
            if (farProc == IntPtr.Zero)
            {
                throw (new Exception(" 函数指针为空 , 请确保已进行 LoadFun 操作 !"));
            }
            if (ObjArray_Parameter.Length != ModePassArray_Parameter.Length)
            {
                throw (new Exception(" 参数个数及其传递方式的个数不匹配 ."));
            }
            AssemblyName MyAssemblyName = new AssemblyName();

            MyAssemblyName.Name = "InvokeFun";
            AssemblyBuilder MyAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(MyAssemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder   MyModuleBuilder   = MyAssemblyBuilder.DefineDynamicModule("InvokeDll");
            MethodBuilder   MyMethodBuilder   = MyModuleBuilder.DefineGlobalMethod("MyFun", MethodAttributes.Public | MethodAttributes.Static, Type_Return, TypeArray_ParameterType);
            ILGenerator     IL = MyMethodBuilder.GetILGenerator();
            int             i;

            for (i = 0; i < ObjArray_Parameter.Length; i++)
            {
                switch (ModePassArray_Parameter[i])
                {
                case ModePass.ByValue:
                    IL.Emit(OpCodes.Ldarg, i);
                    break;

                case ModePass.ByRef:
                    IL.Emit(OpCodes.Ldarga, i);
                    break;

                default:
                    throw (new Exception(" 第 " + (i + 1).ToString() + " 个参数没有给定正确的传递方式 ."));
                }
            }

            if (IntPtr.Size == 4)
            {
                IL.Emit(OpCodes.Ldc_I4, farProc.ToInt32());
            }

            else if (IntPtr.Size == 8)
            {
                IL.Emit(OpCodes.Ldc_I8, farProc.ToInt64());
            }

            else
            {
                throw new PlatformNotSupportedException();
            }

            IL.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, Type_Return, TypeArray_ParameterType);

            IL.Emit(OpCodes.Ret); // 返回值

            MyModuleBuilder.CreateGlobalFunctions();

            MethodInfo MyMethodInfo = MyModuleBuilder.GetMethod("MyFun");

            return(MyMethodInfo.Invoke(null, ObjArray_Parameter));// 调用方法,并返回其值
        }
Пример #34
0
        /// <summary>
        /// For each item check if is has a handle already. If not add the item.
        /// </summary>
        /// <param name="itemIds"></param>
        /// <param name="handles"></param>
        /// <returns>true if all handles could be retreived. Otherwise false.</returns>
        internal bool GetServerHandles(StringCollection itemIds, out int[] handles, out int[] pErrors)
        {
            bool bResult = true;
            int  currentHandle;

            handles = new int[itemIds.Count];
            pErrors = new int[itemIds.Count];

            ArrayList indexesToAdd = new ArrayList();

            // collect data to AddItems
            for (int i = 0; i < itemIds.Count; i++)
            {
                // Item exists already
                if (m_mapServerHandles.TryGetValue(itemIds[i], out currentHandle))
                {
                    handles[i] = currentHandle;
                    pErrors[i] = 0;
                }
                // Need to add item
                else
                {
                    indexesToAdd.Add(i);
                }
            }

            if (indexesToAdd.Count > 0)
            {
                OPCITEMDEF[] itemsToAdd = new OPCITEMDEF[indexesToAdd.Count];

                for (int i = 0; i < indexesToAdd.Count; i++)
                {
                    //itemsToAdd[i] = new OPCITEMDEF();

                    itemsToAdd[i].szItemID            = itemIds[(int)indexesToAdd[i]];
                    itemsToAdd[i].szAccessPath        = "";
                    itemsToAdd[i].bActive             = 0;
                    itemsToAdd[i].vtRequestedDataType = 0;
                    itemsToAdd[i].hClient             = 0;
                    itemsToAdd[i].dwBlobSize          = 0;
                    itemsToAdd[i].pBlob = IntPtr.Zero;
                }

                IntPtr pAddResults;
                IntPtr ppErrors;

                m_itemManagement.AddItems(
                    indexesToAdd.Count,
                    itemsToAdd,
                    out pAddResults,
                    out ppErrors);

                if (pAddResults == IntPtr.Zero)
                {
                    throw new Exception("GetServerHandle failed. No Results.");
                }
                if (ppErrors == IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pAddResults);
                    throw new Exception("GetServerHandle failed. No ErrorCodes.");
                }

                IntPtr posResults = pAddResults;
                int[]  pErrorsTmp = Helper.GetInt32s(ref ppErrors, indexesToAdd.Count, true);

                for (int i = 0; i < indexesToAdd.Count; i++)
                {
                    int currentIndex = (int)indexesToAdd[i];
                    if (pErrorsTmp[i] != 0)
                    {
                        // caller to check pErrors
                        bResult = false;
                        pErrors[currentIndex] = pErrorsTmp[i];
                        continue;
                    }

                    OPCITEMRESULT itemResult = (OPCITEMRESULT)Marshal.PtrToStructure(posResults, typeof(OPCITEMRESULT));

                    m_mapServerHandles.Add(itemsToAdd[i].szItemID, itemResult.hServer);
                    handles[currentIndex] = itemResult.hServer;

                    Marshal.FreeCoTaskMem(itemResult.pBlob);
                    itemResult.pBlob = IntPtr.Zero;

                    Marshal.DestroyStructure(posResults, typeof(OpcRcw.Da.OPCITEMRESULT));

                    posResults = (IntPtr)(posResults.ToInt64() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
                }

                Marshal.FreeCoTaskMem(pAddResults);
                pAddResults = IntPtr.Zero;
            }

            return(bResult);
        }
Пример #35
0
 void OnReadWindows(UVBuffer.Windows buffer, IntPtr bytesAvaliable)
 {
     // TODO: all branches need to release buffer, I think
     long bytesRead = bytesAvaliable.ToInt64();
     if (bytesRead == 0)
     {
         buffer.Dispose();
         return;
     }
     else if (bytesRead < 0)
     {
         var error = UVException.ErrorCodeToError((int)bytesRead);
         if (error == UVError.EOF)
         {
             OnEndOfStream();
             Dispose();
             buffer.Dispose();
         }
         else if (error == UVError.ECONNRESET)
         {
             Debug.Assert(buffer.Buffer == IntPtr.Zero && buffer.Length == 0);
             // no need to dispose
             // TODO: what should we do here?
         }
         else
         {
             Dispose();
             buffer.Dispose();
             throw new UVException((int)bytesRead);
         }
     }
     else
     {
         using (var owned = new OwnedNativeMemory((int)bytesRead, buffer.Buffer)) {
             OnReadCompleted(owned.Memory);
             //buffer.Dispose(); // TODO: owned memory frees the memory. this is bad; need to fix
         }
     }
 }
Пример #36
0
 public static IEnumerable <_Disasm> Disassemble(byte[] data, IntPtr address, Architecture architecture)
 {
     return(BeaEngine.Disassemble(data, (UIntPtr)address.ToInt64(), architecture));
 }
Пример #37
0
 public static void setIntPtr(int e, IntPtr v)
 {
     setIntPtr(e, v.ToInt64());
 }
Пример #38
0
        /// <summary>
        /// Given a module base address, resolve the address of a function by manually walking the module export table.
        /// </summary>
        /// <author>Ruben Boonen (@FuzzySec)</author>
        /// <param name="ModuleBase">A pointer to the base address where the module is loaded in the current process.</param>
        /// <param name="FunctionHash">Hash of the exported procedure.</param>
        /// <param name="Key">64-bit integer to initialize the keyed hash object (e.g. 0xabc or 0x1122334455667788).</param>
        /// <returns>IntPtr for the desired function.</returns>
        public static IntPtr GetExportAddress(IntPtr ModuleBase, string FunctionHash, long Key)
        {
            IntPtr FunctionPtr = IntPtr.Zero;

            try
            {
                // Traverse the PE header in memory
                Int32 PeHeader      = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + 0x3C));
                Int16 OptHeaderSize = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + PeHeader + 0x14));
                Int64 OptHeader     = ModuleBase.ToInt64() + PeHeader + 0x18;
                Int16 Magic         = Marshal.ReadInt16((IntPtr)OptHeader);
                Int64 pExport       = 0;
                if (Magic == 0x010b)
                {
                    pExport = OptHeader + 0x60;
                }
                else
                {
                    pExport = OptHeader + 0x70;
                }

                // Read -> IMAGE_EXPORT_DIRECTORY
                Int32 ExportRVA         = Marshal.ReadInt32((IntPtr)pExport);
                Int32 OrdinalBase       = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x10));
                Int32 NumberOfFunctions = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x14));
                Int32 NumberOfNames     = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x18));
                Int32 FunctionsRVA      = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x1C));
                Int32 NamesRVA          = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x20));
                Int32 OrdinalsRVA       = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + ExportRVA + 0x24));

                // Loop the array of export name RVA's
                for (int i = 0; i < NumberOfNames; i++)
                {
                    string FunctionName = Marshal.PtrToStringAnsi((IntPtr)(ModuleBase.ToInt64() + Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + NamesRVA + i * 4))));
                    if (GetAPIHash(FunctionName, Key).Equals(FunctionHash, StringComparison.OrdinalIgnoreCase))
                    {
                        Int32 FunctionOrdinal = Marshal.ReadInt16((IntPtr)(ModuleBase.ToInt64() + OrdinalsRVA + i * 2)) + OrdinalBase;
                        Int32 FunctionRVA     = Marshal.ReadInt32((IntPtr)(ModuleBase.ToInt64() + FunctionsRVA + (4 * (FunctionOrdinal - OrdinalBase))));
                        FunctionPtr = (IntPtr)((Int64)ModuleBase + FunctionRVA);
                        break;
                    }
                }
            }
            catch
            {
                // Catch parser failure
                throw new InvalidOperationException("Failed to parse module exports.");
            }

            if (FunctionPtr == IntPtr.Zero)
            {
                // Export not found
                throw new MissingMethodException(FunctionHash + ", export hash not found.");
            }
            return(FunctionPtr);
        }
Пример #39
0
        /* private static void OnHotKey(string strKey, IntPtr lpUserData)
         * {
         *      if(string.IsNullOrEmpty(strKey)) return;
         *      if(strKey.IndexOf(@"<Release>", StrUtil.CaseIgnoreCmp) >= 0) return;
         *
         *      if(m_fRecvWnd != null)
         *      {
         *              MainForm mf = (m_fRecvWnd as MainForm);
         *              if(mf == null) { Debug.Assert(false); return; }
         *
         *              Keys k = EggAccStringToKeys(strKey);
         *              foreach(KeyValuePair<int, Keys> kvp in m_vRegKeys)
         *              {
         *                      if(kvp.Value == k) mf.HandleHotKey(kvp.Key);
         *              }
         *      }
         *      else { Debug.Assert(false); }
         * }
         *
         * private static Keys EggAccStringToKeys(string strKey)
         * {
         *      if(string.IsNullOrEmpty(strKey)) return Keys.None;
         *
         *      Keys k = Keys.None;
         *
         *      if(strKey.IndexOf(@"<Alt>", StrUtil.CaseIgnoreCmp) >= 0)
         *              k |= Keys.Alt;
         *      if((strKey.IndexOf(@"<Ctl>", StrUtil.CaseIgnoreCmp) >= 0) ||
         *              (strKey.IndexOf(@"<Ctrl>", StrUtil.CaseIgnoreCmp) >= 0) ||
         *              (strKey.IndexOf(@"<Control>", StrUtil.CaseIgnoreCmp) >= 0))
         *              k |= Keys.Control;
         *      if((strKey.IndexOf(@"<Shft>", StrUtil.CaseIgnoreCmp) >= 0) ||
         *              (strKey.IndexOf(@"<Shift>", StrUtil.CaseIgnoreCmp) >= 0))
         *              k |= Keys.Shift;
         *
         *      string strKeyCode = strKey;
         *      while(strKeyCode.IndexOf('<') >= 0)
         *      {
         *              int nStart = strKeyCode.IndexOf('<');
         *              int nEnd = strKeyCode.IndexOf('>');
         *              if((nStart < 0) || (nEnd < 0) || (nEnd <= nStart)) { Debug.Assert(false); break; }
         *
         *              strKeyCode = strKeyCode.Remove(nStart, nEnd - nStart + 1);
         *      }
         *      strKeyCode = strKeyCode.Trim();
         *
         *      try { k |= (Keys)Enum.Parse(typeof(Keys), strKeyCode, true); }
         *      catch(Exception) { Debug.Assert(false); }
         *
         *      return k;
         * }
         *
         * private static string EggAccKeysToString(Keys k)
         * {
         *      StringBuilder sb = new StringBuilder();
         *
         *      if((k & Keys.Shift) != Keys.None) sb.Append(@"<Shift>");
         *      if((k & Keys.Control) != Keys.None) sb.Append(@"<Control>");
         *      if((k & Keys.Alt) != Keys.None) sb.Append(@"<Alt>");
         *
         *      sb.Append((k & Keys.KeyCode).ToString());
         *      return sb.ToString();
         * } */

        internal static void CheckCtrlAltA(Form fParent)
        {
            try
            {
                if (!Program.Config.Integration.CheckHotKeys)
                {
                    return;
                }
                if (NativeLib.IsUnix())
                {
                    return;
                }

                // Check for a conflict only in the very specific case of
                // Ctrl+Alt+A; in all other cases we assume that the user
                // is aware of a possible conflict and intentionally wants
                // to override any system key combination
                if (Program.Config.Integration.HotKeyGlobalAutoType !=
                    (ulong)(Keys.Control | Keys.Alt | Keys.A))
                {
                    return;
                }

                // Check for a conflict only on Polish systems; other
                // languages typically don't use Ctrl+Alt+A frequently
                // and a conflict warning would just be confusing for
                // most users
                IntPtr hKL        = NativeMethods.GetKeyboardLayout(0);
                ushort uLangID    = (ushort)(hKL.ToInt64() & 0xFFFFL);
                ushort uPriLangID = NativeMethods.GetPrimaryLangID(uLangID);
                if (uPriLangID != NativeMethods.LANG_POLISH)
                {
                    return;
                }

                int vk = (int)Keys.A;

                // We actually check for RAlt (which maps to Ctrl+Alt)
                // instead of LCtrl+LAlt
                byte[] pbState = new byte[256];
                pbState[NativeMethods.VK_CONTROL]  = 0x80;
                pbState[NativeMethods.VK_LCONTROL] = 0x80;
                pbState[NativeMethods.VK_MENU]     = 0x80;
                pbState[NativeMethods.VK_RMENU]    = 0x80;
                pbState[NativeMethods.VK_NUMLOCK]  = 0x01;                // Toggled
                // pbState[vk] = 0x80;

                string strUni = NativeMethods.ToUnicode3(vk, pbState, IntPtr.Zero);
                if (string.IsNullOrEmpty(strUni))
                {
                    return;
                }
                if (strUni.EndsWith("a") || strUni.EndsWith("A"))
                {
                    return;
                }

                if (char.IsControl(strUni, 0))
                {
                    Debug.Assert(false); strUni = "?";
                }

                string str = KPRes.CtrlAltAConflict.Replace(@"{PARAM}", strUni) +
                             MessageService.NewParagraph + KPRes.CtrlAltAConflictHint;

                VistaTaskDialog dlg = new VistaTaskDialog();
                dlg.AddButton((int)DialogResult.Cancel, KPRes.Ok, null);
                dlg.CommandLinks    = false;
                dlg.Content         = str;
                dlg.DefaultButtonID = (int)DialogResult.Cancel;
                dlg.MainInstruction = KPRes.KeyboardKeyCtrl + "+" +
                                      KPRes.KeyboardKeyAlt + "+A - " + KPRes.Warning;
                dlg.SetIcon(VtdIcon.Warning);
                dlg.VerificationText = KPRes.DialogNoShowAgain;
                dlg.WindowTitle      = PwDefs.ShortProductName;

                if (dlg.ShowDialog(fParent))
                {
                    if (dlg.ResultVerificationChecked)
                    {
                        Program.Config.Integration.CheckHotKeys = false;
                    }
                }
                else
                {
                    MessageService.ShowWarning(str);
                }
            }
            catch (Exception) { Debug.Assert(false); }
        }
Пример #40
0
        //Name:     GetAll
        //Inputs:   none
        //Outputs:  string array
        //Errors:   This method may throw the following errors.
        //          Failed to enumerate device tree!
        //          Invalid handle!
        //Remarks:  This is code I cobbled together from a number of newsgroup threads
        //          as well as some C++ stuff I translated off of MSDN.  Seems to work.
        //          The idea is to come up with a list of devices, same as the device
        //          manager does.  Currently it uses the actual "system" names for the
        //          hardware.  It is also possible to use hardware IDs.  See the docs
        //          for SetupDiGetDeviceRegistryProperty in the MS SDK for more details.
        public List <DEVICE_INFO> GetAll()
        {
            List <DEVICE_INFO> HWList = new List <DEVICE_INFO>();

            try {
                Guid   myGUID   = System.Guid.Empty;
                IntPtr hDevInfo = Native.SetupDiGetClassDevs(ref myGUID, 0, IntPtr.Zero, Native.DIGCF_ALLCLASSES | Native.DIGCF_PRESENT);
                if (hDevInfo.ToInt64() == Native.INVALID_HANDLE_VALUE)
                {
                    throw new Exception("Invalid Handle");
                }
                Native.SP_DEVINFO_DATA DeviceInfoData;
                DeviceInfoData = new Native.SP_DEVINFO_DATA();

                //for 32-bit, IntPtr.Size = 4
                //for 64-bit, IntPtr.Size = 8
                if (IntPtr.Size == 4)
                {
                    DeviceInfoData.cbSize = 28;
                }
                else if (IntPtr.Size == 8)
                {
                    DeviceInfoData.cbSize = 32;
                }

                //is devices exist for class
                DeviceInfoData.devInst   = 0;
                DeviceInfoData.classGuid = System.Guid.Empty;
                DeviceInfoData.reserved  = 0;
                UInt32        i;
                StringBuilder DeviceName         = new StringBuilder("");
                StringBuilder DeviceFriendlyName = new StringBuilder("");
                StringBuilder DeviceHardwareId   = new StringBuilder("");
                DeviceName.Capacity = DeviceFriendlyName.Capacity = DeviceHardwareId.Capacity = Native.MAX_DEV_LEN;
                for (i = 0; Native.SetupDiEnumDeviceInfo(hDevInfo, i, DeviceInfoData); i++)
                {
                    DeviceName.Length = DeviceFriendlyName.Length = DeviceHardwareId.Length = 0;

                    if (!Native.SetupDiGetDeviceRegistryProperty(hDevInfo, DeviceInfoData, Native.SPDRP_DEVICEDESC, 0, DeviceName, Native.MAX_DEV_LEN, IntPtr.Zero))
                    {
                        continue;
                    }
                    Native.SetupDiGetDeviceRegistryProperty(hDevInfo, DeviceInfoData, Native.SPDRP_FRIENDLYNAME, 0, DeviceFriendlyName, Native.MAX_DEV_LEN, IntPtr.Zero);
                    Native.SetupDiGetDeviceRegistryProperty(hDevInfo, DeviceInfoData, Native.SPDRP_HARDWAREID, 0, DeviceHardwareId, Native.MAX_DEV_LEN, IntPtr.Zero);

                    UInt32       status, problem;
                    string       dstatustr    = "";
                    DeviceStatus deviceStatus = DeviceStatus.Unknown;
                    if (Native.CM_Get_DevNode_Status(out status, out problem, DeviceInfoData.devInst, 0) == Native.CR_SUCCESS)
                    {
                        deviceStatus = ((status & Native.DN_STARTED) > 0) ? DeviceStatus.Enabled : DeviceStatus.Disabled;
                    }

                    HWList.Add(new DEVICE_INFO {
                        name = DeviceName.ToString(), friendlyName = DeviceFriendlyName.ToString(), hardwareId = DeviceHardwareId.ToString(), status = deviceStatus, statusstr = dstatustr
                    });
                }
                Native.SetupDiDestroyDeviceInfoList(hDevInfo);
            }
            catch (Exception ex) {
                throw new Exception("Failed to enumerate device tree!", ex);
            }
            return(HWList);
        }
Пример #41
0
        public static MemoryPatch HookMethod(MethodInfo source, MethodInfo target)
        {
            if (!EqualSignatures(source, target))
            {
                throw new ArgumentException("The method signatures are not the same.", nameof(source));
            }

            RuntimeHelpers.PrepareMethod(source.MethodHandle);
            RuntimeHelpers.PrepareMethod(target.MethodHandle);
            IntPtr srcAddr = source.MethodHandle.GetFunctionPointer();
            IntPtr tgtAddr = target.MethodHandle.GetFunctionPointer();

            var arch = GetProcessorArchitecture();

            long offset;

            byte[] jumpInst;
            switch (arch)
            {
            case ProcessorArchitecture.Amd64:
                offset = tgtAddr.ToInt64() - srcAddr.ToInt64() - 5;
                if (offset >= Int32.MinValue && offset <= Int32.MaxValue)
                {
                    jumpInst = new byte[] {
                        0xE9,     // JMP rel32
                        (byte)(offset & 0xFF),
                        (byte)((offset >> 8) & 0xFF),
                        (byte)((offset >> 16) & 0xFF),
                        (byte)((offset >> 24) & 0xFF)
                    };
                }
                else
                {
                    offset   = tgtAddr.ToInt64();
                    jumpInst = new byte[] {
                        0x48, 0xB8,     // MOV moffs64,rax
                        (byte)(offset & 0xFF),
                        (byte)((offset >> 8) & 0xFF),
                        (byte)((offset >> 16) & 0xFF),
                        (byte)((offset >> 24) & 0xFF),
                        (byte)((offset >> 32) & 0xFF),
                        (byte)((offset >> 40) & 0xFF),
                        (byte)((offset >> 48) & 0xFF),
                        (byte)((offset >> 56) & 0xFF),
                        0xFF, 0xE0     // JMP rax
                    };
                }
                break;

            case ProcessorArchitecture.X86:
                offset   = tgtAddr.ToInt32() - srcAddr.ToInt32() - 5;
                jumpInst = new byte[] {
                    0xE9,     // JMP rel32
                    (byte)(offset & 0xFF),
                    (byte)((offset >> 8) & 0xFF),
                    (byte)((offset >> 16) & 0xFF),
                    (byte)((offset >> 24) & 0xFF)
                };
                break;

            default:
                throw new NotSupportedException(
                          $"Processor architecture {arch} is not supported.");
            }

            return(PatchMemory(srcAddr, jumpInst));
        }
Пример #42
0
 private IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
 {
     if (msg == (int)UnmanagedMethods.WindowsMessage.WM_DISPATCH_WORK_ITEM && wParam.ToInt64() == SignalW && lParam.ToInt64() == SignalL)
     {
         Signaled?.Invoke();
     }
     return(UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam));
 }
Пример #43
0
 // we need a synchronized add and remove so that multiple threads
 // update the data store concurrently
 private static bool TryGetCmdTransportManager(IntPtr operationContext,
     out WSManClientCommandTransportManager cmdTransportManager,
     out long cmdTMId)
 {
     cmdTMId = operationContext.ToInt64();
     cmdTransportManager = null;
     lock (s_cmdTMHandles)
     {
         return s_cmdTMHandles.TryGetValue(cmdTMId, out cmdTransportManager);
     }
 }
Пример #44
0
 public static IntPtr ArrayElementAsPtr(IntPtr arrayDataPtr, long index, long size) => new IntPtr(arrayDataPtr.ToInt64() + index * size);
Пример #45
0
 /// <summary>
 /// Returns a new <see cref="IntPtr" /> object instance based on the
 /// specified <see cref="IntPtr" /> object instance and an integer
 /// offset.
 /// </summary>
 /// <param name="pointer">
 /// The <see cref="IntPtr" /> object instance representing the base
 /// memory location.
 /// </param>
 /// <param name="offset">
 /// The integer offset from the base memory location that the new
 /// <see cref="IntPtr" /> object instance should point to.
 /// </param>
 /// <returns>
 /// The new <see cref="IntPtr" /> object instance.
 /// </returns>
 public static IntPtr IntPtrForOffset(
     IntPtr pointer,
     int offset
     )
 {
     return new IntPtr(pointer.ToInt64() + offset);
 }
Пример #46
0
 internal ProcessMemoryStream(NtProcess process, IntPtr base_address)
 {
     _process      = process;
     _base_address = base_address.ToInt64();
 }
    private static byte[] IntPtrToBytes(IntPtr p, long offset, long length) {
        // This method converts the given pointer and offset to a byte[] representation
        // of the C struct EcbFileAndOffset (32 and 64-bit specific):
        //
        // struct FileAndOffset
        // {
        //     ULONGLONG cbOffset;
        //     ULONGLONG cbLength;
        //     HANDLE hFile;
        // }
        //

        byte[] bytes = new byte[2 * sizeof(long) + IntPtr.Size];

        // Put the offset value first
        for (int i = 0; i < 8; i++)
            bytes[i] = (byte)((offset >> 8*i) & 0xFF );

        // Put the file value next
        for (int i = 0; i < 8; i++)
            bytes[8+i] = (byte)((length >> 8*i) & 0xFF );
        
        if (IntPtr.Size == 4) {
            int temp = p.ToInt32();
            for (int i = 0; i < 4; i++)
                bytes[16+i] = (byte)((temp >> 8*i) & 0xFF );
        }  else {
            long temp = p.ToInt64();
            for (int i = 0; i < 8; i++)
                bytes[16+i] = (byte)((temp >> 8*i) & 0xFF );
        }
        return bytes;
    }
Пример #48
0
 void OnReadUnix(UVBuffer.Unix buffer, IntPtr bytesAvaliable)
 {
     long bytesRead = bytesAvaliable.ToInt64();
     if (bytesRead == 0)
     {
         return;
     }
     else if (bytesRead < 0)
     {
         var error = UVException.ErrorCodeToError((int)bytesRead);
         if (error == UVError.EOF)
         {
             OnEndOfStream();
             Dispose();
         }
         else
         {
             Dispose();
             throw new UVException((int)bytesRead);
         }
     }
     else
     {
         var readSlice = new ByteSpan((byte*)buffer.Buffer, (int)bytesRead);
         OnReadCompleted(readSlice);
         buffer.Dispose();
     }
 }
Пример #49
0
 public HotKeyEventArgs(IntPtr hotKeyParam)
 {
     uint param = (uint)hotKeyParam.ToInt64();
     Key = (Keys)((param & 0xffff0000) >> 16);
     Modifiers = (KeyModifiers)(param & 0x0000ffff);
 }
        private int GetOffset(IntPtr pBuffer)
        {
            Contract.Assert(pBuffer != IntPtr.Zero, "'pBuffer' MUST NOT be IntPtr.Zero.");
            int offset = (int)(pBuffer.ToInt64() - m_StartAddress + m_InternalBuffer.Offset);

            Contract.Assert(offset >= 0, "'offset' MUST NOT be negative.");
            return offset;
        }
Пример #51
0
			public int StreamGetBytesImpl (IntPtr buf, int bufsz, bool peek) 
			{
				if (buf == IntPtr.Zero && peek) {
					return -1;
				}

				if (bufsz > managedBuf.Length)
					managedBuf = new byte[bufsz];
				int bytesRead = 0;
				long streamPosition = 0;

				if (bufsz > 0) {
					if (stream.CanSeek) {
						streamPosition = stream.Position;
					}
					if (start_buf_len > 0) {
						if (start_buf_len > bufsz) {
							Array.Copy(start_buf, start_buf_pos, managedBuf, 0, bufsz);
							start_buf_pos += bufsz;
							start_buf_len -= bufsz;
							bytesRead = bufsz;
							bufsz = 0;
						} else {
							// this is easy
							Array.Copy(start_buf, start_buf_pos, managedBuf, 0, start_buf_len);
							bufsz -= start_buf_len;
							bytesRead = start_buf_len;
							start_buf_len = 0;
						}
					}

					if (bufsz > 0) {
						try {
							bytesRead += stream.Read (managedBuf, bytesRead, bufsz);
						} catch (IOException) {
							return -1;
						}
					}
			
					if (bytesRead > 0 && buf != IntPtr.Zero) {
						Marshal.Copy (managedBuf, 0, (IntPtr) (buf.ToInt64()), bytesRead);
					}

					if (!stream.CanSeek && (bufsz == 10) && peek) {
						// Special 'hack' to support peeking of the type for gdi+ on non-seekable streams
					}
				
					if (peek) {
						if (stream.CanSeek) {
							// If we are peeking bytes, then go back to original position before peeking
							stream.Seek (streamPosition, SeekOrigin.Begin);
						} else {
							throw new NotSupportedException();
						}
					}
				}
				
				return bytesRead;
			}
Пример #52
0
 private static int IntPtrToInt32(IntPtr intPtr)
 {
     return(unchecked ((int)intPtr.ToInt64()));
 }
Пример #53
0
 void OnReadWindows(UVBuffer.Windows buffer, IntPtr bytesAvaliable)
 {
     // TODO: all branches need to release buffer, I think
     long bytesRead = bytesAvaliable.ToInt64();
     if (bytesRead == 0)
     {
         buffer.Dispose();
         return;
     }
     else if (bytesRead < 0)
     {
         var error = UVException.ErrorCodeToError((int)bytesRead);
         if (error == UVError.EOF)
         {
             OnEndOfStream();
             Dispose();
             buffer.Dispose();
         }
         else if(error == UVError.ECONNRESET)
         {
             Debug.Assert(buffer.Buffer == IntPtr.Zero && buffer.Length == 0);
             // no need to dispose
             // TODO: what should we do here?
         }
         else
         {
             Dispose();
             buffer.Dispose();
             throw new UVException((int)bytesRead);
         }
     }
     else
     {
         var readSlice = new ByteSpan((byte*)buffer.Buffer, (int)bytesRead);
         OnReadCompleted(readSlice);
         buffer.Dispose();
     }
 }
Пример #54
0
        public static unsafe bool IsDynamic(this RuntimeMethodHandle rtfh)
        {
            IntPtr rtfhValue = *(IntPtr *)&rtfh;

            return((rtfhValue.ToInt64() & 0x1) == 0x1);
        }
        private bool IsNativeBuffer(IntPtr pBuffer, uint bufferSize)
        {
            Contract.Assert(pBuffer != IntPtr.Zero, "'pBuffer' MUST NOT be NULL.");
            Contract.Assert(bufferSize <= GetMaxBufferSize(),
                "'bufferSize' MUST NOT be bigger than 'm_ReceiveBufferSize' and 'm_SendBufferSize'.");

            long nativeBufferStartAddress = pBuffer.ToInt64();
            long nativeBufferEndAddress = bufferSize + nativeBufferStartAddress;

            Contract.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(m_InternalBuffer.Array, m_InternalBuffer.Offset).ToInt64() == m_StartAddress,
                "'m_InternalBuffer.Array' MUST be pinned for the whole lifetime of a WebSocket.");

            if (nativeBufferStartAddress >= m_StartAddress &&
                nativeBufferStartAddress <= m_EndAddress &&
                nativeBufferEndAddress >= m_StartAddress &&
                nativeBufferEndAddress <= m_EndAddress)
            {
                return true;
            }

            return false;
        }
Пример #56
0
 /// <summary>
 /// Adds a 64-bits offset to a native pointer.
 /// </summary>
 /// <param name="pointer">Native pointer</param>
 /// <param name="offset">Offset to add</param>
 /// <returns>Native pointer with the added offset</returns>
 private IntPtr PtrAddr(IntPtr pointer, ulong offset)
 {
     return((IntPtr)(pointer.ToInt64() + (long)offset));
 }
Пример #57
0
			/// <summary>
			/// Reads a TWAIN value.
			/// </summary>
			/// <param name="baseAddress">The base address.</param>
			/// <param name="offset">The offset.</param>
			/// <param name="type">The TWAIN type.</param>
			/// <returns></returns>
			public static object ReadValue(IntPtr baseAddress, ref int offset, TwainType type)
			{
				object val = null;
				switch (type)
				{
					case TwainType.Int8:
						val = (sbyte)Marshal.ReadByte(baseAddress, offset);
						break;
					case TwainType.UInt8:
						val = Marshal.ReadByte(baseAddress, offset);
						break;
					case TwainType.Bool:
					case TwainType.UInt16:
						val = (ushort)Marshal.ReadInt16(baseAddress, offset);
						break;
					case TwainType.Int16:
						val = Marshal.ReadInt16(baseAddress, offset);
						break;
					case TwainType.UInt32:
						val = (uint)Marshal.ReadInt32(baseAddress, offset);
						break;
					case TwainType.Int32:
						val = Marshal.ReadInt32(baseAddress, offset);
						break;
					case TwainType.Fix32:
						Fix32 f32 = new Fix32();
						f32.Whole = Marshal.ReadInt16(baseAddress, offset);
						f32.Frac = (ushort)Marshal.ReadInt16(baseAddress, offset + 2);
						val = f32;
						break;
					case TwainType.Frame:
						Frame frame = new Frame();
						frame.Left = (Fix32)ReadValue(baseAddress, ref offset, TwainType.Fix32);
						frame.Top = (Fix32)ReadValue(baseAddress, ref offset, TwainType.Fix32);
						frame.Right = (Fix32)ReadValue(baseAddress, ref offset, TwainType.Fix32);
						frame.Bottom = (Fix32)ReadValue(baseAddress, ref offset, TwainType.Fix32);
						return frame; // no need to update offset again after reading fix32
					case TwainType.Str128:
					case TwainType.Str255:
					case TwainType.Str32:
					case TwainType.Str64:
						val = Marshal.PtrToStringAnsi(new IntPtr(baseAddress.ToInt64() + offset));
						break;
/*					case TwainType.Handle:
						val = Marshal.ReadIntPtr(baseAddress, offset);
						break;*/
				}
				offset += GetItemTypeSize(type);
				return val;
			}
Пример #58
0
        /// <summary>
        /// Reads a number of samples without moving the readpointer.
        /// </summary>
        /// <param name="buffer">The buffer to write the data to.</param>
        /// <param name="requested">Number of requested number of samples.</param>
        /// <param name="offset">Offset to move the ring buffer read pointer before reading data.</param>
        /// <returns>Number of bytes read.</returns>
        public int Peek(IntPtr buffer, int requested, int offset)
        {
            if (buffer == IntPtr.Zero)
            {
                return(0);
            }

            // Same code as method Read, only without the last update of _readPointer and _space
            int read;
            int readPointer;
            int writePointer;
            int space;

            lock (_syncObj)
            {
                readPointer  = _readPointer;
                writePointer = _writePointer;
                space        = _space;
            }

            offset = Math.Min(offset, _buffer.Length - space);

            readPointer += offset;
            if (readPointer > _buffer.Length)
            {
                readPointer -= _buffer.Length;
            }

            requested = Math.Min(requested, _buffer.Length - space - offset);

            if (writePointer > readPointer)
            {
                int count1 = Math.Min(requested, writePointer - readPointer);

                Marshal.Copy(_buffer, readPointer, buffer, count1);
                //readPointer += count1;

                read = count1;
            }
            else
            {
                int count1 = Math.Min(requested, _buffer.Length - readPointer);

                if (count1 > 0)
                {
                    Marshal.Copy(_buffer, readPointer, buffer, count1);
                    //readPointer += count1;
                    //if (readPointer == _buffer.Length)
                    //  readPointer = 0;
                }

                int count2 = Math.Min(requested - count1, writePointer);
                if (count2 > 0)
                {
                    IntPtr ptr = new IntPtr((_is32Bit ? buffer.ToInt32() : buffer.ToInt64()) + (count1 * BassConstants.FloatBytes));

                    Marshal.Copy(_buffer, 0, ptr, count2);
                    //readPointer = count2;
                }
                else
                {
                    count2 = 0;
                }
                read = count1 + count2;
            }
            return(read);
        }
Пример #59
0
    /// <summary>
    /// Creates the particle system in the physics simulation and creates any existing particle groups</summary>
    public void Initialise(IntPtr world,bool debug,int index)
    {
        if (Particles != null )Debug.Log(Particles.Length);
        Index = index;
        PartSysPtr = LPAPIParticleSystems.CreateParticleSystem(world,ParticleRadius,Damping,GravityScale,Index);
        //PartSysPtr = LPAPIParticleSystems.CreateParticleSystem2(world,ParticleRadius,Damping,GravityScale,Index,
        //SurfaceTensionNormalStrenght,SurfaceTensionPressureStrenght,ViscousStrenght);
        LPAPIParticleSystems.SetDestructionByAge(PartSysPtr,DestroyByAgeAllowed);

        if (ParticleAmountLimit > 0)
        {
            LPAPIParticleSystems.SetMaxParticleCount(PartSysPtr,ParticleAmountLimit);
        }

        LPAPIParticleSystems.SetParticleSystemIndex(PartSysPtr,Index);

        if (debug)Debug.Log("Particle System Created at: 0x" + PartSysPtr.ToInt64());

        foreach (LPParticleGroup _shape in GameObject.FindObjectsOfType<LPParticleGroup>())
        {
            if (Index == _shape.ParticleSystemImIn && _shape.SpawnOnPlay)
            {
                _shape.Initialise(this);
            }
        }
        if (debug)Debug.Log(LPAPIParticleSystems.GetNumberOfParticles(PartSysPtr)+ " Particles created");
        Drawers = GetComponentsInChildren<LPDrawParticleSystem>();
        for (int i = 0; i < Drawers.Length; i++)
        {
            Drawers[i].Initialise(this);
        }
    }
Пример #60
0
        public void EnumerateDevices()
        {
            lock (lockObject)
            {
                DeviceList.Clear();

                uint deviceCount = 0;
                int  dwSize      = Marshal.SizeOf(typeof(RawInputDeviceList));

                if (Win32.GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0)
                {
                    IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));
                    Win32.GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);

                    for (int i = 0; i < deviceCount; i++)
                    {
                        uint pcbSize = 0;

                        // On Window 8 64bit when compiling against .Net > 3.5 using .ToInt32 you will generate an arithmetic overflow. Leave as it is for 32bit/64bit applications
                        RawInputDeviceList rid = (RawInputDeviceList)Marshal.PtrToStructure(new IntPtr(pRawInputDeviceList.ToInt64() + (dwSize * i)), typeof(RawInputDeviceList));

                        Win32.GetRawInputDeviceInfo(rid.Device, RawInputDeviceInfo.RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

                        if (pcbSize <= 0)
                        {
                            continue;
                        }

                        IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                        Win32.GetRawInputDeviceInfo(rid.Device, RawInputDeviceInfo.RIDI_DEVICENAME, pData, ref pcbSize);
                        string deviceName = Marshal.PtrToStringAnsi(pData);

                        if (rid.Type == (uint)DeviceType.Keyboard && deviceName.Length > 0 && deviceName.Count(x => x == '#') >= 2)
                        {
                            try
                            {
                                string[] split = deviceName.Substring(4).Split('#');

                                string classCode    = split[0]; // ACPI (Class code)
                                string subClassCode = split[1]; // PNP0303 (SubClass code)
                                string protocolCode = split[2]; // 3&13c0b0c5&0 (Protocol code)

                                RegistryKey deviceKey = Registry.LocalMachine.OpenSubKey($@"System\CurrentControlSet\Enum\{classCode}\{subClassCode}\{protocolCode}");

                                string deviceDesc = deviceKey.GetValue("DeviceDesc").ToString();
                                deviceDesc = deviceDesc.Substring(deviceDesc.IndexOf(';') + 1);

                                KeyPressEvent deviceInfo = new KeyPressEvent
                                {
                                    DeviceName   = Marshal.PtrToStringAnsi(pData),
                                    DeviceHandle = rid.Device,
                                    Description  = deviceDesc,
                                };

                                if (!DeviceList.ContainsKey(rid.Device))
                                {
                                    DeviceList.Add(rid.Device, deviceInfo);
                                }
                            }
                            catch (Exception) { } // Ignore error and try next device.
                        }

                        Marshal.FreeHGlobal(pData);
                    }

                    Marshal.FreeHGlobal(pRawInputDeviceList);
                    return;
                }
            }

            throw new Win32Exception(Marshal.GetLastWin32Error());
        }