Ejemplo n.º 1
0
        static void ClassNotRegistered(bool builtInComDisabled)
        {
            Console.WriteLine($"Running {nameof(ClassNotRegistered)}...");

            Action action = () =>
            {
                var CLSID_NotRegistered = new Guid("328FF83E-3F6C-4BE9-A742-752562032925");     // Random GUID
                var cxt = new ComActivationContext()
                {
                    ClassId      = CLSID_NotRegistered,
                    InterfaceId  = typeof(IClassFactory).GUID,
                    AssemblyPath = @"C:\foo.dll"
                };
                ComActivator.GetClassFactoryForType(cxt);
            };

            if (!builtInComDisabled)
            {
                COMException e = Assert.Throws <COMException>(action, "Class should not be found");
                const int    CLASS_E_CLASSNOTAVAILABLE = unchecked ((int)0x80040111);
                Assert.AreEqual(CLASS_E_CLASSNOTAVAILABLE, e.HResult, "Unexpected HRESULT");
            }
            else
            {
                Assert.Throws <NotSupportedException>(action, "Built-in COM has been disabled via a feature switch");
            }
        }
Ejemplo n.º 2
0
        static int Main(string[] doNotUse)
        {
            try
            {
                bool builtInComDisabled = false;
                var  comConfig          = AppContext.GetData("System.Runtime.InteropServices.BuiltInComInterop.IsSupported");
                if (comConfig != null && !bool.Parse(comConfig.ToString()))
                {
                    builtInComDisabled = true;
                }
                Console.WriteLine($"Built-in COM Disabled?: {builtInComDisabled}");

                InvalidInterfaceRequest();
                ClassNotRegistered(builtInComDisabled);
                NonrootedAssemblyPath(builtInComDisabled);
                ValidateAssemblyIsolation(builtInComDisabled);
                if (!builtInComDisabled)
                {
                    // We don't test this scenario with builtInComDisabled since it is covered by ValidateAssemblyIsolation() above
                    ValidateUserDefinedRegistrationCallbacks();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Test Failure: {e}");
                return(101);
            }

            return(100);
        }
        static void Main(string[] args)
        {
            if (!CreatePipe(out SafeFileHandle readPipeHandle, out SafeFileHandle writePipeHandle, IntPtr.Zero, 0))
            {
                Console.WriteLine(string.Format("CreatePipe failed: {0:X8}", Marshal.GetLastWin32Error()));
                return;
            }
            FileStream fs = new FileStream(readPipeHandle, FileAccess.Read, 4096, false);

            byte[] buffer = new byte[1];
            CancellationTokenSource cts = new CancellationTokenSource();
            Task <int> asyncRead        = fs.ReadAsync(buffer, 0, 1, cts.Token);

            Thread.Sleep(1000);
            cts.Cancel();
            Task.WaitAny(asyncRead);
            Console.WriteLine($"Status: {asyncRead.Status}");
            Console.WriteLine($"Exception: {asyncRead.Exception}");
            try
            {
                Console.WriteLine($"bytes read: {asyncRead.Result}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"asyncRead.Result threw {e}");
            }
        }
Ejemplo n.º 4
0
        static int Main(string[] doNotUse)
        {
            try
            {
                InvalidInterfaceRequest();
                ClassNotRegistered();
            }
            catch (Exception e)
            {
                Console.WriteLine($"Test Failure: {e}");
                return(101);
            }

            return(100);
        }
Ejemplo n.º 5
0
        public static int Main()
        {
            try
            {
                Assert.Throws <PlatformNotSupportedException>(() => CustomMarshalersNative.Unsupported(typeof(object)));
                Assert.Throws <PlatformNotSupportedException>(() => CustomMarshalersNative.Unsupported((IReflect)typeof(object)));
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.ToString());
                return(101);
            }

            return(100);
        }
Ejemplo n.º 6
0
        static void InvalidInterfaceRequest()
        {
            Console.WriteLine($"Running {nameof(InvalidInterfaceRequest)}...");

            Assert.Throws <NotSupportedException>(
                () =>
            {
                var notIClassFactory = new Guid("ED53F949-63E4-43B5-A13D-5655478AADD5");
                var cxt = new ComActivationContext()
                {
                    InterfaceId = notIClassFactory
                };
                ComActivator.GetClassFactoryForType(cxt);
            });
        }
Ejemplo n.º 7
0
        static void NonrootedAssemblyPath()
        {
            Console.WriteLine($"Running {nameof(NonrootedAssemblyPath)}...");

            ArgumentException e = Assert.Throws <ArgumentException>(
                () =>
            {
                var cxt = new ComActivationContext()
                {
                    InterfaceId  = typeof(IClassFactory).GUID,
                    AssemblyPath = "foo.dll"
                };
                ComActivator.GetClassFactoryForType(cxt);
            },
                "Non-root assembly path should not be valid");
        }
Ejemplo n.º 8
0
        static int Main(string[] doNotUse)
        {
            try
            {
                InvalidInterfaceRequest();
                ClassNotRegistered();
                NonrootedAssemblyPath();
                ValidateAssemblyIsolation();
            }
            catch (Exception e)
            {
                Console.WriteLine($"Test Failure: {e}");
                return(101);
            }

            return(100);
        }
Ejemplo n.º 9
0
        static void ClassNotRegistered()
        {
            Console.WriteLine($"Running {nameof(ClassNotRegistered)}...");

            COMException e = Assert.Throws <COMException>(
                () =>
            {
                var CLSID_NotRegistered = new Guid("328FF83E-3F6C-4BE9-A742-752562032925");     // Random GUID
                var cxt = new ComActivationContext()
                {
                    ClassId      = CLSID_NotRegistered,
                    InterfaceId  = typeof(IClassFactory).GUID,
                    AssemblyPath = @"C:\foo.dll"
                };
                ComActivator.GetClassFactoryForType(cxt);
            },
                "Class should not be found");

            const int CLASS_E_CLASSNOTAVAILABLE = unchecked ((int)0x80040111);

            Assert.AreEqual(CLASS_E_CLASSNOTAVAILABLE, e.HResult, "Unexpected HRESULT");
        }
Ejemplo n.º 10
0
        static void NonrootedAssemblyPath(bool builtInComDisabled)
        {
            Console.WriteLine($"Running {nameof(NonrootedAssemblyPath)}...");

            Action action = () =>
            {
                var cxt = new ComActivationContext()
                {
                    InterfaceId  = typeof(IClassFactory).GUID,
                    AssemblyPath = "foo.dll"
                };
                ComActivator.GetClassFactoryForType(cxt);
            };

            if (!builtInComDisabled)
            {
                Assert.Throws <ArgumentException>(action, "Non-root assembly path should not be valid");
            }
            else
            {
                Assert.Throws <NotSupportedException>(action, "Built-in COM has been disabled via a feature switch");
            }
        }
Ejemplo n.º 11
0
        static void NonrootedAssemblyPath(bool builtInComDisabled)
        {
            Console.WriteLine($"Running {nameof(NonrootedAssemblyPath)}...");

            Action action = () =>
            {
                var cxt = new ComActivationContext()
                {
                    InterfaceId  = typeof(IClassFactory).GUID,
                    AssemblyPath = "foo.dll"
                };
                ComActivator.GetClassFactoryForType(cxt);
            };

            if (!builtInComDisabled)
            {
                Assert.Throws <ArgumentException>(action);
            }
            else
            {
                Assert.Throws <NotSupportedException>(action);
            }
        }
Ejemplo n.º 12
0
        unsafe static int Main(string[] args)
        {
            // Disable running on Windows 7 until IJW activation work is complete.
            if (Environment.OSVersion.Platform != PlatformID.Win32NT || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1))
            {
                return(100);
            }

            try
            {
                HostPolicyMock.Initialize(Environment.CurrentDirectory, null);

                Console.WriteLine("Verify that we can load an IJW assembly from native code.");
                string ijwModulePath   = Path.Combine(Environment.CurrentDirectory, "IjwNativeCallingManagedDll.dll");
                IntPtr ijwNativeHandle = NativeLibrary.Load(ijwModulePath);

                using (HostPolicyMock.Mock_corehost_resolve_component_dependencies(
                           0,
                           ijwModulePath,
                           string.Empty,
                           string.Empty))
                    fixed(char *path = ijwModulePath)
                    {
                        InMemoryAssemblyLoader.LoadInMemoryAssembly(ijwNativeHandle, (IntPtr)path);
                    }

                NativeEntryPointDelegate nativeEntryPoint = Marshal.GetDelegateForFunctionPointer <NativeEntryPointDelegate>(NativeLibrary.GetExport(ijwNativeHandle, "NativeEntryPoint"));

                Assert.AreEqual(100, nativeEntryPoint());

                Console.WriteLine("Test calls from managed to native to managed when an IJW assembly was first loaded via native.");

                Assembly   ijwAssemblyManaged = Assembly.Load("IjwNativeCallingManagedDll");
                Type       testType           = ijwAssemblyManaged.GetType("TestClass");
                object     testInstance       = Activator.CreateInstance(testType);
                MethodInfo testMethod         = testType.GetMethod("ManagedEntryPoint");

                Assert.AreEqual(100, (int)testMethod.Invoke(testInstance, null));

                MethodInfo changeReturnedValueMethod = testType.GetMethod("ChangeReturnedValue");
                MethodInfo getReturnValueMethod      = testType.GetMethod("GetReturnValue");

                int newValue = 42;
                changeReturnedValueMethod.Invoke(null, new object[] { newValue });

                Assert.AreEqual(newValue, (int)getReturnValueMethod.Invoke(null, null));

                // Native images are only loaded into memory once. As a result, the stubs in the vtfixup table
                // will always point to JIT stubs that exist in the first ALC that the module was loaded into.
                // As a result, if an IJW module is loaded into two different ALCs, or if the module is
                // first loaded via a native call and then loaded via the managed loader, the call stack can change ALCs when
                // jumping from managed->native->managed code within the IJW module.
                Assert.AreEqual(100, (int)testMethod.Invoke(testInstance, null));
                return(100);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());

                return(101);
            }
        }
Ejemplo n.º 13
0
        static void ValidateAssemblyIsolation()
        {
            Console.WriteLine($"Running {nameof(ValidateAssemblyIsolation)}...");

            string assemblySubPath = Path.Combine(Environment.CurrentDirectory, "Servers");
            string assemblyAPath   = Path.Combine(assemblySubPath, "AssemblyA.dll");
            string assemblyBPath   = Path.Combine(assemblySubPath, "AssemblyB.dll");
            string assemblyCPath   = Path.Combine(assemblySubPath, "AssemblyC.dll");
            string assemblyPaths   = $"{assemblyAPath}{Path.PathSeparator}{assemblyBPath}{Path.PathSeparator}{assemblyCPath}";

            HostPolicyMock.Initialize(Environment.CurrentDirectory, null);

            var  CLSID_NotUsed = Guid.Empty; // During this phase of activation the GUID is not used.
            Guid iid           = typeof(IGetTypeFromC).GUID;
            Type typeCFromAssemblyA;
            Type typeCFromAssemblyB;

            using (HostPolicyMock.Mock_corehost_resolve_component_dependencies(
                       0,
                       assemblyPaths,
                       string.Empty,
                       string.Empty))
            {
                var cxt = new ComActivationContext()
                {
                    ClassId      = CLSID_NotUsed,
                    InterfaceId  = typeof(IClassFactory).GUID,
                    AssemblyPath = assemblyAPath,
                    AssemblyName = "AssemblyA",
                    TypeName     = "ClassFromA"
                };

                var factory = (IClassFactory)ComActivator.GetClassFactoryForType(cxt);

                object svr;
                factory.CreateInstance(null, ref iid, out svr);
                typeCFromAssemblyA = (Type)((IGetTypeFromC)svr).GetTypeFromC();
            }

            using (HostPolicyMock.Mock_corehost_resolve_component_dependencies(
                       0,
                       assemblyPaths,
                       string.Empty,
                       string.Empty))
            {
                var cxt = new ComActivationContext()
                {
                    ClassId      = CLSID_NotUsed,
                    InterfaceId  = typeof(IClassFactory).GUID,
                    AssemblyPath = assemblyBPath,
                    AssemblyName = "AssemblyB",
                    TypeName     = "ClassFromB"
                };

                var factory = (IClassFactory)ComActivator.GetClassFactoryForType(cxt);

                object svr;
                factory.CreateInstance(null, ref iid, out svr);
                typeCFromAssemblyB = (Type)((IGetTypeFromC)svr).GetTypeFromC();
            }

            Assert.AreNotEqual(typeCFromAssemblyA, typeCFromAssemblyB, "Types should be from different AssemblyLoadContexts");
        }
Ejemplo n.º 14
0
        static void ValidateUserDefinedRegistrationCallbacks()
        {
            Console.WriteLine($"Running {nameof(ValidateUserDefinedRegistrationCallbacks)}...");

            string assemblySubPath = Path.Combine(Environment.CurrentDirectory, "Servers");
            string assemblyAPath   = Path.Combine(assemblySubPath, "AssemblyA.dll");
            string assemblyBPath   = Path.Combine(assemblySubPath, "AssemblyB.dll");
            string assemblyCPath   = Path.Combine(assemblySubPath, "AssemblyC.dll");
            string assemblyPaths   = $"{assemblyAPath}{Path.PathSeparator}{assemblyBPath}{Path.PathSeparator}{assemblyCPath}";

            HostPolicyMock.Initialize(Environment.CurrentDirectory, null);

            var  CLSID_NotUsed = Guid.Empty; // During this phase of activation the GUID is not used.
            Guid iid           = typeof(IValidateRegistrationCallbacks).GUID;

            using (HostPolicyMock.Mock_corehost_resolve_component_dependencies(
                       0,
                       assemblyPaths,
                       string.Empty,
                       string.Empty))
            {
                foreach (string typename in new[] { "ValidRegistrationTypeCallbacks", "ValidRegistrationStringCallbacks" })
                {
                    Console.WriteLine($"Validating {typename}...");

                    var cxt = new ComActivationContext()
                    {
                        ClassId      = CLSID_NotUsed,
                        InterfaceId  = typeof(IClassFactory).GUID,
                        AssemblyPath = assemblyAPath,
                        AssemblyName = "AssemblyA",
                        TypeName     = typename
                    };

                    var factory = (IClassFactory)ComActivator.GetClassFactoryForType(cxt);

                    object svr;
                    factory.CreateInstance(null, ref iid, out svr);

                    var inst = (IValidateRegistrationCallbacks)svr;
                    Assert.IsFalse(inst.DidRegister());
                    Assert.IsFalse(inst.DidUnregister());

                    cxt.InterfaceId = Guid.Empty;
                    ComActivator.ClassRegistrationScenarioForType(cxt, register: true);
                    ComActivator.ClassRegistrationScenarioForType(cxt, register: false);

                    Assert.IsTrue(inst.DidRegister());
                    Assert.IsTrue(inst.DidUnregister());
                }
            }

            using (HostPolicyMock.Mock_corehost_resolve_component_dependencies(
                       0,
                       assemblyPaths,
                       string.Empty,
                       string.Empty))
            {
                foreach (string typename in new[] { "NoRegistrationCallbacks", "InvalidArgRegistrationCallbacks", "InvalidInstanceRegistrationCallbacks", "MultipleRegistrationCallbacks" })
                {
                    Console.WriteLine($"Validating {typename}...");

                    var cxt = new ComActivationContext()
                    {
                        ClassId      = CLSID_NotUsed,
                        InterfaceId  = typeof(IClassFactory).GUID,
                        AssemblyPath = assemblyAPath,
                        AssemblyName = "AssemblyA",
                        TypeName     = typename
                    };

                    var factory = (IClassFactory)ComActivator.GetClassFactoryForType(cxt);

                    object svr;
                    factory.CreateInstance(null, ref iid, out svr);

                    var inst = (IValidateRegistrationCallbacks)svr;
                    cxt.InterfaceId = Guid.Empty;
                    bool exceptionThrown = false;
                    try
                    {
                        ComActivator.ClassRegistrationScenarioForType(cxt, register: true);
                    }
                    catch
                    {
                        exceptionThrown = true;
                    }

                    Assert.IsTrue(exceptionThrown || !inst.DidRegister());

                    exceptionThrown = false;
                    try
                    {
                        ComActivator.ClassRegistrationScenarioForType(cxt, register: false);
                    }
                    catch
                    {
                        exceptionThrown = true;
                    }

                    Assert.IsTrue(exceptionThrown || !inst.DidUnregister());
                }
            }
        }
Ejemplo n.º 15
0
        static void ValidateAssemblyIsolation(bool builtInComDisabled)
        {
            Console.WriteLine($"Running {nameof(ValidateAssemblyIsolation)}...");

            string assemblySubPath = Path.Combine(Environment.CurrentDirectory, "Servers");
            string assemblyAPath   = Path.Combine(assemblySubPath, "AssemblyA.dll");
            string assemblyBPath   = Path.Combine(assemblySubPath, "AssemblyB.dll");
            string assemblyCPath   = Path.Combine(assemblySubPath, "AssemblyC.dll");
            string assemblyPaths   = $"{assemblyAPath}{Path.PathSeparator}{assemblyBPath}{Path.PathSeparator}{assemblyCPath}";

            HostPolicyMock.Initialize(Environment.CurrentDirectory, null);

            var  CLSID_NotUsed = Guid.Empty; // During this phase of activation the GUID is not used.
            Guid iid           = typeof(IGetTypeFromC).GUID;
            Type typeCFromAssemblyA;
            Type typeCFromAssemblyB;

            using (HostPolicyMock.Mock_corehost_resolve_component_dependencies(
                       0,
                       assemblyPaths,
                       string.Empty,
                       string.Empty))
            {
                var cxt = new ComActivationContext()
                {
                    ClassId      = CLSID_NotUsed,
                    InterfaceId  = typeof(IClassFactory).GUID,
                    AssemblyPath = assemblyAPath,
                    AssemblyName = "AssemblyA",
                    TypeName     = "ClassFromA"
                };

                if (builtInComDisabled)
                {
                    Assert.Throws <NotSupportedException>(
                        () => ComActivator.GetClassFactoryForType(cxt), "Built-in COM has been disabled via a feature switch");
                    return;
                }

                var factory = (IClassFactory)ComActivator.GetClassFactoryForType(cxt);

                IntPtr svrRaw;
                factory.CreateInstance(null, ref iid, out svrRaw);
                var svr = (IGetTypeFromC)Marshal.GetObjectForIUnknown(svrRaw);
                Marshal.Release(svrRaw);
                typeCFromAssemblyA = (Type)svr.GetTypeFromC();
            }

            using (HostPolicyMock.Mock_corehost_resolve_component_dependencies(
                       0,
                       assemblyPaths,
                       string.Empty,
                       string.Empty))
            {
                var cxt = new ComActivationContext()
                {
                    ClassId      = CLSID_NotUsed,
                    InterfaceId  = typeof(IClassFactory).GUID,
                    AssemblyPath = assemblyBPath,
                    AssemblyName = "AssemblyB",
                    TypeName     = "ClassFromB"
                };

                var factory = (IClassFactory)ComActivator.GetClassFactoryForType(cxt);

                IntPtr svrRaw;
                factory.CreateInstance(null, ref iid, out svrRaw);
                var svr = (IGetTypeFromC)Marshal.GetObjectForIUnknown(svrRaw);
                Marshal.Release(svrRaw);
                typeCFromAssemblyB = (Type)svr.GetTypeFromC();
            }

            Assert.AreNotEqual(typeCFromAssemblyA, typeCFromAssemblyB, "Types should be from different AssemblyLoadContexts");
        }