Parameter can not read by hook handler function

May 3, 2013 at 8:07 PM
Edited May 3, 2013 at 8:08 PM
Hi,

I recently tried to hook WMI function using tweak stated in here and here .
Somehow I managed to hook IWbemClassObject::Get with following signature:
        [Guid("dc12a681-737f-11cf-884d-00aa004b2e24"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public interface IWbemClassObject
        {
            int Get(
                    IntPtr wszName,
                    UInt32 lFlags,
                    IntPtr pVal,
                    IntPtr pType,
                    IntPtr plFlavor
                    );
and hook handler is like this:
        [UnmanagedFunctionPointer(CallingConvention.StdCall,
            CharSet = CharSet.Unicode,
            SetLastError = true)]
        unsafe delegate int DGet(
                         IntPtr wszName,
                         UInt32 lFlags,
                         IntPtr pVal,
                         IntPtr pType,
                         IntPtr plFlavor);

        static int Get_Hooked(
                          IntPtr pwszName,
                          UInt32 lFlags,
                          IntPtr pVal,
                          IntPtr pType,
                          IntPtr plFlavor
                         )
        {
            string str;
          
                try
                {
                    str = Marshal.PtrToStringBSTR((IntPtr)pwszName);

                }
                catch (Exception ExtInfo)
                {
                    Console.WriteLine(ExtInfo.ToString());
                }

                Console.WriteLine("pwszNameBSTR : " + str);
 
            DGet genuineGet = (DGet)Marshal.GetDelegateForFunctionPointer(GetHook.OldProc, typeof(DGet));
            MessageBox.Show("Halt");
                
                href = genuineGet(pwszName,
                                lFlags,
                                 pVal,
                                 pType,
                                plFlavor); //Call original function
                
            return href;
        }
Problem 1)
Marshal.PtrToStringBSTR((IntPtr)pwszName) throws exception while later called original function works normally as if main program and original function knows what is set in parameters and only hook handler don't know.
How can I touch the content of parameters?
Problem 2)
when I tried to make the code work, always it fails at calling original function
until I insert "MessageBox.Show("Halt");" Line right after initializing delegate.
is there any way to get rid of this quick fix?

thanks in advance,