Пример #1
0
        static void Main(string[] args)
        {
            var p = new Program();



            var loader = new AssemblySystem();


            var module = loader.LoadFrom(loader.GetAnyCpuPath(loader.BaseDirectory), "RegFreeComNativeConsumer.dll");

            //call dll entry point if needed -
            //var main = module.GetDelegate<DEF.DllMain>();//enty point is not declared as export
            //bool result = main(module.Handle, FDW_REASONS.DLL_PROCESS_ATTACH, IntPtr.Zero);
            //if (!result) throw new Exception("Failed to init dll");

            // push managed COM service into native method
            _service = new RegFreeSimpleObject();
            _service.FloatProperty = 42;
            _pointer = Marshal.GetIUnknownForObject(_service);
            var initialize = module.GetDelegate <Initialize>();
            int error      = initialize(_pointer);

            if (error != 0)
            {
                throw new Exception();
            }

            EnsureGC();
            _service.RaiseEnsureGCIsNotObstacle();

            // return string from C

            IntPtr strPtr = IntPtr.Zero;

            module.GetDelegate <GetStringResult>()(out strPtr);
            var str = Marshal.PtrToStringUni(strPtr);

            Marshal.FreeBSTR(strPtr);
            Console.WriteLine(str);

            // return array of COM services which return pointers
            var com            = loader.LoadFrom(loader.GetAnyCpuPath(loader.BaseDirectory), "RegFreeComNativeImplementer");
            var servicesGetter = com.GetDelegate <GetComInterface>();

            object[] services;
            servicesGetter(out services);
            var    srv = (RegFreeComNativeInterfacesLib.IMyService)services[0];
            IntPtr otherHandle;

            srv.GetSomeHanlde(out otherHandle);
            var srvRepeat = (RegFreeComNativeInterfacesLib.IMyService)Marshal.GetObjectForIUnknown(otherHandle);

            // pointer to itself was used to simplify testing
            Assert.AreEqual(services[0], srvRepeat);

            Console.ReadKey();
        }
Пример #2
0
 public void LoadFrom_32BitsLoads64BitsDll()
 {
     Assert.AreEqual(4, IntPtr.Size);
     var loader = new AssemblySystem();
     var dll64 = Path.Combine(loader.BaseDirectory, loader.x64Directory, "RegFreeComResources.dll");
     loader.LoadFrom(dll64);
 }
Пример #3
0
        public void TestLoadeAndDisposeNativeDll()
        {
            var loader = new AssemblySystem();
            var anyCpu = loader.GetAnyCpuPath(loader.BaseDirectory);
            var module = loader.LoadFrom(anyCpu, "RegFreeComNativeConsumer.dll");

            module.Dispose();
        }
Пример #4
0
        public void LoadFrom_32BitsLoads64BitsDll()
        {
            Assert.AreEqual(4, IntPtr.Size);
            var loader = new AssemblySystem();
            var dll64  = Path.Combine(loader.BaseDirectory, loader.x64Directory, "RegFreeComResources.dll");

            loader.LoadFrom(dll64);
        }
Пример #5
0
        private static IAssembly LoadDll()
        {
            var loader = new AssemblySystem();
            var anyCpu = loader.GetAnyCpuPath(loader.BaseDirectory);

            loader.AddSearchPath(anyCpu);
            var module = loader.LoadFrom(anyCpu, "NativeLibrary.dll");

            return(module);
        }
Пример #6
0
        public void TestDllDependenciesLoading()
        {
            var loader = new AssemblySystem();

            // C# loads C++ from Win32 or x64 subfolder
            var anyCpu = loader.GetAnyCpuPath(loader.BaseDirectory);

            loader.AddSearchPath(anyCpu);
            var module = loader.LoadFrom(anyCpu, "NativeLibraryConsumer.dll");
            var fn     = module.GetDelegate <fnNativeLibraryConsumer>();

            object[] retval;

            Assert.IsTrue(42 == fn(out retval));
            loader.Dispose();
        }
Пример #7
0
    public static unsafe void ServerThread1()
    {
//        SECURITY_DESCRIPTOR sd = new SECURITY_DESCRIPTOR();
        IntPtr sd = Marshal.AllocHGlobal(sizeof(SECURITY_DESCRIPTOR));

        OBJECT_ATTRIBUTES ObjAttr  = new OBJECT_ATTRIBUTES();             // Object attributes for the name
        UNICODE_STRING    PortName = new UNICODE_STRING();
        int    Status;
        IntPtr LpcPortHandle;
        IntPtr RequestBuffer = Marshal.AllocHGlobal(sizeof(G.PORT_MESSAGE) + Constants.MAX_LPC_DATA);
        bool   WeHaveToStop  = false;
        int    nError;
        TRANSFERRED_MESSAGE tm = TRANSFERRED_MESSAGE.Create();

        //
        // Initialize security descriptor that will be set to
        // "Everyone has the full access"
        //


        if (!InitializeSecurityDescriptor_Ptr(out sd, SECURITY_DESCRIPTOR_REVISION))
        {
            nError = Marshal.GetLastWin32Error();
            if (nError != Constants.S_OK)
            {
                throw new Win32Exception(nError);
            }
        }

        //
        // Set the empty DACL to the security descriptor
        //

        if (!SetSecurityDescriptorDacl_Ptr(ref sd, true, IntPtr.Zero, false))
        {
            nError = Marshal.GetLastWin32Error();
            if (nError != Constants.S_OK)
            {
                throw new Win32Exception(nError);
            }
        }

        uint securityDescriptorSize = 0;

        ConvertStringSecurityDescriptorToSecurityDescriptor("S:(ML;;NW;;;LW)", 1, ref sd, ref securityDescriptorSize);

        //
        // Initialize attributes for the port and create it
        //

        //RtlInitUnicodeString(ref PortName, LpcPortName);
        PortName.Length        = (ushort)(LpcPortName.Length * 2);
        PortName.MaximumLength = (ushort)(PortName.Length + 2);
        PortName.buffer        = Marshal.StringToHGlobalUni(LpcPortName);

        NRegFreeCom.AssemblySystem a = new AssemblySystem();
        //var qwe = LoadLibrary(@"I:\src\NLocalIpc\build\Debug\rpcrtex.dll");
        // var aaaaa = NRegFreeCom.Interop.NativeMethods.GetProcAddress(qwe, "secddd");
        var aa  = a.LoadFrom(@"I:\src\NLocalIpc\build\Debug\rpcrtex.dll");
        var aaa = aa.GetDelegate <secddd>();

        sd = aaa();

        OBJECT_ATTRIBUTES.InitializeObjectAttributes_Ptr(ref ObjAttr, ref PortName, 0, IntPtr.Zero, sd);

        Console.WriteLine("Server: Creating LPC port \"{0}\" (NtCreatePort) ...\n", LpcPortName);
        var msg = (uint)(sizeof(PORT_MESSAGE) + G.Constants.MAX_LPC_DATA);

        Status = G.NativeMethods.NtCreatePort(out LpcPortHandle,
                                              ref ObjAttr,
                                              100,
                                              msg,
                                              0);
        Console.WriteLine("Server: NtCreatePort result {0:x8}", Status);


        AlpcErrorHandler.Check(Status);

        //
        // Process all incoming LPC messages
        //
        uint qwe = 0;

        while (WeHaveToStop == false)
        {
            //PTRANSFERRED_MESSAGE
            IntPtr LpcMessage   = IntPtr.Zero;
            IntPtr ServerHandle = IntPtr.Zero;

            //
            // Create the data buffer for the request
            //

            LpcMessage = RequestBuffer;
            Console.WriteLine("Server: ------------- Begin loop ----------------------\n {0}", Status);

            //
            // Listen to the port. This call is blocking, and cannot be interrupted,
            // even if the handle is closed. The only way how to stop the block is to send
            // an LPC request which will be recognized by server thread as "Stop" command
            //
            AlpcErrorHandler.Check(Status);

            Console.WriteLine("Server: Listening to LPC port (NtListenPort) ... {0} \n", LpcPortName);


            Status = G.NativeMethods.NtListenPort(LpcPortHandle,
                                                  ref tm.Header);
            Console.WriteLine("Server: NtListenPort result {0:x8}\n", Status);

            //
            // Accept the port connection
            //

            AlpcErrorHandler.Check(Status);

            Console.WriteLine("Server: Accepting LPC connection (NtAcceptConnectPort) ...{0:}\n", LpcPortName);
            IntPtr             NULL = IntPtr.Zero;
            G.PORT_VIEW        pv   = new G.PORT_VIEW();
            G.REMOTE_PORT_VIEW cv   = new G.REMOTE_PORT_VIEW();

            AlpcPortHandle sh;
            Status = G.NativeMethods.NtAcceptConnectPort_Ptr(out ServerHandle,
                                                             IntPtr.Zero,
                                                             ref tm.Header,
                                                             1,
                                                             NULL,
                                                             NULL);
            Console.WriteLine("Server: NtAcceptConnectPort result {0:x8}\n", Status);



            //
            // Complete the connection
            //

            AlpcErrorHandler.Check(Status);

            Console.WriteLine("Server: Completing LPC connection (NtCompleteConnectPort) ...{0:}\n", LpcPortName);

            Status = G.NativeMethods.NtCompleteConnectPort(ServerHandle);
            Console.WriteLine("Server: NtCompleteConnectPort result {0:x8}\n", Status);



            //
            // Now accept the data request coming from the port.
            //

            AlpcErrorHandler.Check(Status);
            // lpcMsg = (TRANSFERRED_MESSAGE)Marshal.PtrToStructure(LpcMessage, typeof(TRANSFERRED_MESSAGE));
            //  mh = lpcMsg.Header;
            Console.WriteLine("Server: Receiving LPC data (NtReplyWaitReceivePort) ...{0:}\n", LpcPortName);


            IntPtr asd = Marshal.AllocHGlobal(sizeof(TRANSFERRED_MESSAGE));
            Marshal.StructureToPtr(tm, asd, false);

            Status = G.NativeMethods.NtReplyWaitReceivePort_NoMarshal(ServerHandle,
                                                                      ref NULL,
                                                                      IntPtr.Zero,
                                                                      asd);
            Console.WriteLine("Server: NtReplyWaitReceivePort result {0:x8}\n", Status);
            var wqe = Marshal.PtrToStructure(asd, typeof(TRANSFERRED_MESSAGE));
            //  var qwe = Marshal.PtrToStringUni(tm.MessageText);
            //
            // Get the data sent by the client
            //

            AlpcErrorHandler.Check(Status);



            // If a request has been received, answer to it.
            switch (tm.Command)
            {
            case LPC_COMMAND_REQUEST_NOREPLY:

                Console.WriteLine("Server: Received request {0}\n", tm.MessageText);

                break;         // Nothing more to do

            case LPC_COMMAND_REQUEST_REPLY:
                //_tprintf(_T("Server: Received request \"%s\"\n"), LpcMessage->MessageText);
                //_tprintf(_T("Server: Sending reply (NtReplyPort) ...\n"), LpcPortName);
                Status = G.NativeMethods.NtReplyPort(LpcPortHandle, ref tm.Header);
                //_tprintf(_T("Server: NtReplyPort result 0x%08lX\n"), Status);
                break;

            case LPC_COMMAND_STOP:         // Stop the work
                //_tprintf(_T("Server: Stopping ...\n"));
                WeHaveToStop = false;
                break;
            }


            //
            // Close the server connection handle
            //

            if (ServerHandle != NULL)
            {
                // _tprintf(_T("Server: Closing the request handle (NtClose) ...\n"), LpcPortName);
                Status = NAlpc.NativeMethods.NtClose(ServerHandle);
                //_tprintf(_T("Server: NtClose result 0x%08lX\n"), Status);
            }

            //_tprintf(_T("Server: ------------- End loop ----------------------\n"), Status);
        }



        return;
    }
Пример #8
0
 private static IAssembly LoadDll()
 {
     var loader = new AssemblySystem();
     var anyCpu = loader.GetAnyCpuPath(loader.BaseDirectory);
     loader.AddSearchPath(anyCpu);
     var module = loader.LoadFrom(anyCpu, "NativeLibrary.dll");
     return module;
 }
Пример #9
0
 public void TestLoadeAndDisposeNativeDll()
 {
     var loader = new AssemblySystem();
     var anyCpu = loader.GetAnyCpuPath(loader.BaseDirectory);
     var module = loader.LoadFrom(anyCpu, "RegFreeComNativeConsumer.dll");
     module.Dispose();
 }
Пример #10
0
        public void TestDllDependenciesLoading()
        {
            var loader = new AssemblySystem();

            // C# loads C++ from Win32 or x64 subfolder
            var anyCpu = loader.GetAnyCpuPath(loader.BaseDirectory);
            loader.AddSearchPath(anyCpu);
            var module = loader.LoadFrom(anyCpu, "NativeLibraryConsumer.dll");
            var fn = module.GetDelegate<fnNativeLibraryConsumer>();
            object[] retval;

            Assert.IsTrue(42 == fn(out retval));
            loader.Dispose();
        }