public static void CustomName()
    {
        try
        {
            Console.WriteLine("CustomName()");

            // ALC should be a concrete class
            AssemblyLoadContext alc = new AssemblyLoadContext("CustomName");
            Assert(PropertyAllContainsContext(alc));

            Console.WriteLine(alc.Name);
            Assert(alc.Name == "CustomName");

            Console.WriteLine(alc.GetType().ToString());
            Assert(alc.GetType().ToString() == "System.Runtime.Loader.AssemblyLoadContext");

            Console.WriteLine(alc.ToString());
            Assert(alc.ToString().Contains("\"CustomName"));
            Assert(alc.ToString().Contains("\" System.Runtime.Loader.AssemblyLoadContext"));
            Assert(alc.ToString().Contains(" #"));
        }
        catch (Exception e)
        {
            Assert(false, e.ToString());
        }
    }
    public static void AssemblyLoadByteArrayName()
    {
#if ReadAllBytes // System.IO.File.ReadAllBytes is not found when ReferenceSystemPrivateCoreLib is true
        try
        {
            Console.WriteLine("AssemblyLoadByteArrayName()");

            String              path      = typeof(Program).Assembly.Location;
            Byte []             byteArray = System.IO.File.ReadAllBytes(path);
            Assembly            a         = Assembly.Load(byteArray);
            AssemblyLoadContext alc       = AssemblyLoadContext.GetLoadContext(a);
            Assert(PropertyAllContainsContext(alc));
            Assert(AssembliesContainAssembly(alc, a));

            Console.WriteLine(alc.Name);
            Assert(alc.Name == "Assembly.Load(byte[], ...)");

            Console.WriteLine(alc.GetType().ToString());
            Assert(alc.GetType().ToString() == "System.Runtime.Loader.IndividualAssemblyLoadContext");

            Console.WriteLine(alc.ToString());
            Assert(alc.ToString().Contains("\"Default"));
            Assert(alc.ToString().Contains("\" System.Runtime.Loader.IndividualAssemblyLoadContext"));
            Assert(alc.ToString().Contains(" #"));
        }
        catch (Exception e)
        {
            Assert(false, e.ToString());
        }
#endif
    }
    public static void CustomWOName()
    {
        try
        {
            Console.WriteLine("CustomWOName()");

            // ALC should be a concrete class
            AssemblyLoadContext alc = new My.CustomAssemblyLoadContext();
            Assert(PropertyAllContainsContext(alc));

            Console.WriteLine(alc.Name);
            Assert(alc.Name == null);

            Console.WriteLine(alc.GetType().ToString());
            Assert(alc.GetType().ToString() == "My.CustomAssemblyLoadContext");

            Console.WriteLine(alc.ToString());
            Assert(alc.ToString().Contains("\"\" "));
            Assert(alc.ToString().Contains("\" My.CustomAssemblyLoadContext"));
            Assert(alc.ToString().Contains(" #"));
        }
        catch (Exception e)
        {
            Assert(false, e.ToString());
        }
    }
    public static void DefaultName()
    {
        try
        {
            Console.WriteLine("DefaultName()");

            AssemblyLoadContext alc = AssemblyLoadContext.Default;
            Assert(alc == AssemblyLoadContext.GetLoadContext(typeof(Program).Assembly));
            Assert(PropertyAllContainsContext(alc));
            Assert(AssembliesContainAssembly(alc, typeof(Program).Assembly));

            Console.WriteLine(alc.Name);
            Assert(alc.Name == "Default");

            Console.WriteLine(alc.GetType().ToString());
            Assert(alc.GetType().ToString() == "System.Runtime.Loader.DefaultAssemblyLoadContext");

            Console.WriteLine(alc.ToString());
            Assert(alc.ToString().Contains("\"Default"));
            Assert(alc.ToString().Contains("\" System.Runtime.Loader.DefaultAssemblyLoadContext"));
            Assert(alc.ToString().Contains(" #"));
        }
        catch (Exception e)
        {
            Assert(false, e.ToString());
        }
    }
    public static void AssemblyLoadFileName()
    {
        try
        {
            Console.WriteLine("AssemblyLoadFileName()");

            String   path = typeof(Program).Assembly.Location;
            Assembly a    = Assembly.LoadFile(path);

            Assert(a != typeof(Program).Assembly);

            AssemblyLoadContext alc = AssemblyLoadContext.GetLoadContext(a);
            Assert(PropertyAllContainsContext(alc));
            Assert(AssembliesContainAssembly(alc, a));
            Assert(alc != AssemblyLoadContext.Default);


            Console.WriteLine(alc.Name);
            Assert(alc.Name == String.Format("Assembly.LoadFile({0})", path));

            Console.WriteLine(alc.GetType().ToString());
            Assert(alc.GetType().ToString() == "System.Runtime.Loader.IndividualAssemblyLoadContext");

            Console.WriteLine(alc.ToString());
            Assert(alc.ToString().Contains("\"" + String.Format("Assembly.LoadFile({0})", path)));
            Assert(alc.ToString().Contains("\" System.Runtime.Loader.IndividualAssemblyLoadContext"));
            Assert(alc.ToString().Contains(" #"));
        }
        catch (Exception e)
        {
            Assert(false, e.ToString());
        }
    }
示例#6
0
    static int TestExecuteInAppDomain(string assemblyPath, string typeName, string methodName, string argument, int expectedHResult, int expectedResult)
    {
        bool passed = true;

        try
        {
            int result  = 0;
            int hresult = NativeMethods.CallExecuteInDefaultAppDomain(assemblyPath, typeName, methodName, argument, ref result);

            if (hresult != expectedHResult)
            {
                Console.WriteLine($"Bad HRESULT: expected {expectedHResult:X} actual {hresult:X}");
                passed = false;
            }
            else if (result != expectedResult)
            {
                Console.WriteLine($"Bad result: expected {expectedResult} actual {result}");
                passed = false;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"Unexpected exception: {e}");
            passed = false;
        }
        return(passed ? 0 : 1);
    }
 public static void Assert(bool value, string message = "none")
 {
     if (!value)
     {
         Console.WriteLine("FAIL! " + message);
         passed = false;
     }
 }
示例#8
0
    private static int NoInline_NoGCTransition(int expected)
    {
        Console.WriteLine($"{nameof(NoInline_NoGCTransition)} ({expected}) ...");
        int n;

        SuppressGCTransitionNative.NextUInt_NoInline_NoGCTransition(&n);
        Assert.AreEqual(expected, n);
        return(n + 1);
    }
示例#9
0
 public bool IsInstanceOfInterface(RuntimeTypeHandle interfaceType, out Exception castError)
 {
     Console.WriteLine(String.Format("IsInstanceOfInterface has been called for type {0}", Type.GetTypeFromHandle(interfaceType)));
     if (_interface2impl == null)
     {
         castError = new CastableException();
         return(false);
     }
     castError = null;
     return(_interface2impl.ContainsKey(Type.GetTypeFromHandle(interfaceType)));
 }
 public static void NegativeTest_NonBlittable()
 {
     // Try invoking method directly
     try
     {
         Func <bool, int> invoker = CallbackMethodNonBlitabble;
         invoker(true);
     }
     catch (Exception)
     {
         Console.WriteLine(":bla");
     }
 }
示例#11
0
    private static int CallAsFunctionPointer(int expected)
    {
        Console.WriteLine($"{nameof(CallAsFunctionPointer)} ({expected}) ...");

        IntPtr fptr = SuppressGCTransitionNative.GetNextUIntFunctionPointer();

        int    n      = 0;
        int *  pn     = &n;
        object boxedN = Pointer.Box(pn, typeof(int *));

        MethodInfo callNextUInt = typeof(FunctionPointer).GetMethod("Call_NextUInt");

        callNextUInt.Invoke(null, new object[] { fptr, boxedN });
        Assert.AreEqual(expected, n);
        return(n + 1);
    }
示例#12
0
 static bool EXPECT(TestResult actualValue, TestResult expectedValue = TestResult.Success)
 {
     if (actualValue == expectedValue)
     {
         if (Verbose)
         {
             Console.WriteLine(String.Format("{0} : {1} : [OK]", CurrentTest, actualValue));
         }
         return(true);
     }
     else
     {
         Console.WriteLine(String.Format(" {0} : {1} : [FAIL]", CurrentTest, actualValue));
         return(false);
     }
 }
示例#13
0
    private static int Mixed_TightLoop(int expected)
    {
        Console.WriteLine($"{nameof(Mixed_TightLoop)} ({expected}) ...");
        int n     = 0;
        int count = 0x100;

        for (int i = 0; i < count; ++i)
        {
            SuppressGCTransitionNative.NextUInt_Inline_NoGCTransition(&n);
        }

        // Use the non-optimized version at the end so a GC poll is not
        // inserted here as well.
        SuppressGCTransitionNative.NextUInt_NoInline_GCTransition(&n);
        Assert.AreEqual(expected + count, n);
        return(n + 1);
    }
    public static void NegativeTest_ViaCalli()
    {
        Console.WriteLine($"{nameof(NativeCallableAttribute)} function via calli instruction. The CLR _will_ crash.");

        /*
         * void TestNativeCallableViaCalli()
         * {
         *      .locals init (native int V_0)
         *      IL_0000:  nop
         *      IL_0001:  ldftn      void CallbackViaCalli(int32)
         *      IL_0007:  stloc.0
         *
         *      IL_0008:  ldc.i4     1234
         *      IL_000d:  ldloc.0
         *      IL_000e:  calli      void(int32)
         *
         *      IL_0013:  nop
         *      IL_0014:  ret
         * }
         */
        DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallableViaCalli", null, null, typeof(Program).Module);
        ILGenerator   il = testNativeCallable.GetILGenerator();

        il.DeclareLocal(typeof(IntPtr));
        il.Emit(OpCodes.Nop);

        // Get native function pointer of the callback
        il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(CallbackViaCalli)));
        il.Emit(OpCodes.Stloc_0);

        il.Emit(OpCodes.Ldc_I4, 1234);
        il.Emit(OpCodes.Ldloc_0);
        il.EmitCalli(OpCodes.Calli, CallingConventions.Standard, null, new Type[] { typeof(int) }, null);

        il.Emit(OpCodes.Nop);
        il.Emit(OpCodes.Ret);

        NativeMethodInvoker testNativeMethod = (NativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(NativeMethodInvoker));

        // It is not possible to catch the resulting ExecutionEngineException exception.
        // To observe the crashing behavior set a breakpoint in the ReversePInvokeBadTransition() function
        // located in src/vm/dllimportcallback.cpp.
        testNativeMethod();
    }
    public static void NativeCallableViaUnmanagedCalli()
    {
        Console.WriteLine($"{nameof(NativeCallableAttribute)} function via calli instruction with unmanaged calling convention.");

        /*
         * void TestNativeCallableViaCalli()
         * {
         *      .locals init (native int V_0)
         *      IL_0000:  nop
         *      IL_0001:  ldftn      int CallbackViaUnmanagedCalli(int32)
         *      IL_0007:  stloc.0
         *
         *      IL_0008:  ldc.i4     1234
         *      IL_000d:  ldloc.0
         *      IL_000e:  calli      int32 stdcall(int32)
         *
         *      IL_0014:  ret
         * }
         */
        DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallableViaUnmanagedCalli", typeof(int), null, typeof(Program).Module);
        ILGenerator   il = testNativeCallable.GetILGenerator();

        il.DeclareLocal(typeof(IntPtr));
        il.Emit(OpCodes.Nop);

        // Get native function pointer of the callback
        il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(CallbackViaUnmanagedCalli)));
        il.Emit(OpCodes.Stloc_0);

        int n = 1234;

        il.Emit(OpCodes.Ldc_I4, n);
        il.Emit(OpCodes.Ldloc_0);
        il.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, typeof(int), new Type[] { typeof(int) });

        il.Emit(OpCodes.Ret);

        IntNativeMethodInvoker testNativeMethod = (IntNativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(IntNativeMethodInvoker));

        int expected = DoubleImpl(n);

        Assert.AreEqual(expected, testNativeMethod());
    }
示例#16
0
    public static void SetResolve()
    {
        Console.WriteLine("Setting PInvoke Resolver");

        DllImportResolver resolver =
            (string libraryName, Assembly asm, DllImportSearchPath? dllImportSearchPath) =>
        {
            if (dllImportSearchPath != DllImportSearchPath.System32)
            {
                Console.WriteLine($"Unexpected dllImportSearchPath: {dllImportSearchPath.ToString()}");
                throw new ArgumentException();
            }

            return(NativeLibrary.Load("ResolveLib", asm, null));
        };

        NativeLibrary.SetDllImportResolver(
            Assembly.GetExecutingAssembly(),
            resolver);
    }
示例#17
0
 public static int Main()
 {
     try
     {
         int n = 1;
         n = Inline_NoGCTransition(n);
         n = Inline_GCTransition(n);
         n = NoInline_NoGCTransition(n);
         n = NoInline_GCTransition(n);
         n = Mixed(n);
         n = Mixed_TightLoop(n);
         n = CallAsFunctionPointer(n);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
         return(101);
     }
     return(100);
 }
    public static void TestNativeCallableValid()
    {
        Console.WriteLine($"{nameof(NativeCallableAttribute)} function");

        /*
         * void TestNativeCallable()
         * {
         *      .locals init ([0] native int ptr)
         *      IL_0000:  nop
         *      IL_0001:  ldftn      int32 ManagedDoubleCallback(int32)
         *      IL_0007:  stloc.0
         *
         *      IL_0008:  ldloc.0
         *      IL_0009:  ldc.i4     <n> local
         *      IL_000e:  call       bool NativeMethods::CallManagedProc(native int, int)
         *
         *      IL_0013:  ret
         *   }
         */
        DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallable", typeof(int), null, typeof(Program).Module);
        ILGenerator   il = testNativeCallable.GetILGenerator();

        il.DeclareLocal(typeof(IntPtr));
        il.Emit(OpCodes.Nop);

        // Get native function pointer of the callback
        il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(ManagedDoubleCallback)));
        il.Emit(OpCodes.Stloc_0);
        il.Emit(OpCodes.Ldloc_0);

        int n = 12345;

        il.Emit(OpCodes.Ldc_I4, n);
        il.Emit(OpCodes.Call, typeof(NativeMethods).GetMethod("CallManagedProc"));
        il.Emit(OpCodes.Ret);
        var testNativeMethod = (IntNativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(IntNativeMethodInvoker));

        int expected = DoubleImpl(n);

        Assert.AreEqual(expected, testNativeMethod());
    }
    public static int Main(string[] args)
    {
        try
        {
            TestNativeCallableValid();
            NegativeTest_ViaDelegate();
            NegativeTest_NonBlittable();
            NegativeTest_GenericArguments();

            if (args.Length != 0 && args[0].Equals("calli"))
            {
                NegativeTest_ViaCalli();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"Test Failure: {e}");
            return(101);
        }

        return(100);
    }
    public static void NegativeTest_ViaDelegate()
    {
        Console.WriteLine($"{nameof(NativeCallableAttribute)} function as delegate");

        // Try invoking method directly
        try
        {
            CallAsDelegate();
            Assert.Fail($"Invalid to call {nameof(ManagedDoubleCallback)} as delegate");
        }
        catch (NotSupportedException)
        {
        }

        // Local function to delay exception thrown during JIT
        void CallAsDelegate()
        {
            Func <int, int> invoker = ManagedDoubleCallback;

            invoker(0);
        }
    }
    public static int Main()
    {
        foreach (AssemblyLoadContext alc in AssemblyLoadContext.All)
        {
            Console.WriteLine(alc.ToString());
            foreach (Assembly a in alc.Assemblies)
            {
                Console.WriteLine(a.ToString());
            }
        }

        DefaultName();
        AssemblyLoadFileName();
        AssemblyLoadByteArrayName();
        CustomWOName();
        CustomName();

        foreach (AssemblyLoadContext alc in AssemblyLoadContext.All)
        {
            Console.WriteLine(alc.ToString());
            foreach (Assembly a in alc.Assemblies)
            {
                Console.WriteLine(a.ToString());
            }
        }

        if (passed)
        {
            Console.WriteLine("Test PASSED!");
            return(100);
        }
        else
        {
            Console.WriteLine("Test FAILED!");
            return(-1);
        }
    }
    public static void NegativeTest_NonBlittable()
    {
        Console.WriteLine($"{nameof(NativeCallableAttribute)} function with non-blittable arguments");

        /*
         * void TestNativeCallableNonBlittable()
         * {
         *      .locals init ([0] native int ptr)
         *      IL_0000:  nop
         *      IL_0001:  ldftn      int32 CallbackMethodNonBlittable(bool)
         *      IL_0007:  stloc.0
         *      IL_0008:  ret
         *   }
         */
        DynamicMethod testNativeCallable = new DynamicMethod("TestNativeCallableNonBlittable", null, null, typeof(Program).Module);
        ILGenerator   il = testNativeCallable.GetILGenerator();

        il.DeclareLocal(typeof(IntPtr));
        il.Emit(OpCodes.Nop);

        // Get native function pointer of the callback
        il.Emit(OpCodes.Ldftn, typeof(Program).GetMethod(nameof(CallbackMethodNonBlittable)));
        il.Emit(OpCodes.Stloc_0);

        il.Emit(OpCodes.Ret);
        var testNativeMethod = (NativeMethodInvoker)testNativeCallable.CreateDelegate(typeof(NativeMethodInvoker));

        // Try invoking method
        try
        {
            testNativeMethod();
            Assert.Fail($"Function {nameof(CallbackMethodNonBlittable)} has non-blittable types");
        }
        catch (NotSupportedException)
        {
        }
    }
示例#23
0
    public static int Main()
    {
        new Thread(Collector).Start();

        for (int i = 0; i < s_LoopCounter; i++)
        {
            try
            {
                NativeSum(10, 10);
                s_WrongPInvokesExecuted++;
            }
            catch (DllNotFoundException) { s_CatchCalled++; }

            try { DoCall(); }
            catch (DllNotFoundException) { s_CatchCalled++; }

            try { DoCallTryFinally(); }
            catch (DllNotFoundException) { s_CatchCalled++; }

            try { DoCallTryCatch(true); }
            catch (ArgumentException) { s_OtherExceptionCatchCalled++; }

            try { DoCallTryRethrowInCatch(); }
            catch (DllNotFoundException) { s_CatchCalled++; }

            try { DoCallTryRethrowDifferentExceptionInCatch(); }
            catch (InvalidOperationException) { s_OtherExceptionCatchCalled++; }

            ManualRaiseException();
        }

        SetResolve();

        for (int i = 0; i < s_LoopCounter; i++)
        {
            var a = NativeSum(10, 10);
            var b = NativeSum(10, 10);
            s_PInvokesExecuted += (a == b && a == 20)? 2 : 0;

            try { DoCallTryCatch(false); }
            catch (ArgumentException) { s_OtherExceptionCatchCalled++; }

            ManualRaiseException();
        }

        s_RunGC = false;

        if (s_FinallyCalled == s_LoopCounter &&
            s_CatchCalled == (s_LoopCounter * 7) &&
            s_OtherExceptionCatchCalled == (s_LoopCounter * 3) &&
            s_WrongPInvokesExecuted == 0 &&
            s_PInvokesExecuted == (s_LoopCounter * 3) &&
            s_SEHExceptionCatchCalled == (s_LoopCounter * 2))
        {
            Console.WriteLine("PASS");
            return(100);
        }

        Console.WriteLine("s_FinallyCalled = " + s_FinallyCalled);
        Console.WriteLine("s_CatchCalled = " + s_CatchCalled);
        Console.WriteLine("s_OtherExceptionCatchCalled = " + s_OtherExceptionCatchCalled);
        Console.WriteLine("s_SEHExceptionCatchCalled = " + s_SEHExceptionCatchCalled);
        Console.WriteLine("s_WrongPInvokesExecuted = " + s_WrongPInvokesExecuted);
        Console.WriteLine("s_PInvokesExecuted = " + s_PInvokesExecuted);
        return(-1);
    }
示例#24
0
 public T ReturnArg(T t)
 {
     Console.WriteLine(String.Format("Generic ReturnArg has been called. My type is {0}", GetType()));
     return(t);
 }
示例#25
0
    public static int Main()
    {
        bool success = true;

        Assembly assembly   = System.Reflection.Assembly.GetExecutingAssembly();
        string   testBinDir = Path.GetDirectoryName(assembly.Location);
        string   libName;
        IntPtr   handle;

        try
        {
            // -----------------------------------------------
            //         Simple LoadLibrary() API Tests
            // -----------------------------------------------

            // Calls on correct full-path to native lib
            libName  = Path.Combine(testBinDir, GetNativeLibraryName());
            success &= EXPECT(LoadLibrarySimple(libName));
            success &= EXPECT(TryLoadLibrarySimple(libName));

            // Calls on non-existant file
            libName  = Path.Combine(testBinDir, "notfound");
            success &= EXPECT(LoadLibrarySimple(libName), TestResult.DllNotFound);
            success &= EXPECT(TryLoadLibrarySimple(libName), TestResult.ReturnFailure);

            // Calls on an invalid file
            libName  = Path.Combine(testBinDir, "NativeLibrary.cpp");
            success &= EXPECT(LoadLibrarySimple(libName),
                              (TestLibrary.Utilities.IsWindows) ? TestResult.BadImage : TestResult.DllNotFound);
            success &= EXPECT(TryLoadLibrarySimple(libName), TestResult.ReturnFailure);

            // Calls on null input
            libName  = null;
            success &= EXPECT(LoadLibrarySimple(libName), TestResult.ArgumentNull);
            success &= EXPECT(TryLoadLibrarySimple(libName), TestResult.ArgumentNull);

            // -----------------------------------------------
            //         Advanced LoadLibrary() API Tests
            // -----------------------------------------------

            // Advanced LoadLibrary() API Tests
            // Calls on correct full-path to native lib
            libName  = Path.Combine(testBinDir, GetNativeLibraryName());
            success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null));
            success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null));

            // Calls on non-existant file
            libName  = Path.Combine(testBinDir, "notfound");
            success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null), TestResult.DllNotFound);
            success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null), TestResult.ReturnFailure);

            // Calls on an invalid file
            libName = Path.Combine(testBinDir, "NativeLibrary.cpp");
            // The VM can only distinguish BadImageFormatException from DllNotFoundException on Windows.
            success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null),
                              (TestLibrary.Utilities.IsWindows) ? TestResult.BadImage : TestResult.DllNotFound);
            success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null), TestResult.ReturnFailure);

            // Calls on just Native Library name
            libName  = GetNativeLibraryPlainName();
            success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null));
            success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null));

            // Calls on Native Library name with correct prefix-suffix
            libName  = GetNativeLibraryName();
            success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null));
            success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null));

            // Calls on full path without prefix-siffix
            libName = Path.Combine(testBinDir, GetNativeLibraryPlainName());
            // DllImport doesn't add a prefix if the name is preceeded by a path specification.
            // Windows only needs a suffix, but Linux and Mac need both prefix and suffix
            success &= EXPECT(LoadLibraryAdvanced(libName, assembly, null),
                              (TestLibrary.Utilities.IsWindows) ? TestResult.Success : TestResult.DllNotFound);
            success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, null),
                              (TestLibrary.Utilities.IsWindows) ? TestResult.Success : TestResult.ReturnFailure);

            if (TestLibrary.Utilities.IsWindows)
            {
                libName = GetWin32LibName();

                // Calls on a valid library from System32 directory
                success &= EXPECT(LoadLibraryAdvanced(libName, assembly, DllImportSearchPath.System32));
                success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, DllImportSearchPath.System32));

                // Calls on a valid library from application directory
                success &= EXPECT(LoadLibraryAdvanced(libName, assembly, DllImportSearchPath.ApplicationDirectory), TestResult.DllNotFound);
                success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, DllImportSearchPath.ApplicationDirectory), TestResult.ReturnFailure);
            }

            // Calls with null libName input
            success &= EXPECT(LoadLibraryAdvanced(null, assembly, null), TestResult.ArgumentNull);
            success &= EXPECT(TryLoadLibraryAdvanced(null, assembly, null), TestResult.ArgumentNull);

            // Calls with null assembly
            libName  = GetNativeLibraryPlainName();
            success &= EXPECT(LoadLibraryAdvanced(libName, null, null), TestResult.ArgumentNull);
            success &= EXPECT(TryLoadLibraryAdvanced(libName, null, null), TestResult.ArgumentNull);

            // Ensure that a lib is not picked up from current directory when
            // a different full-path is specified.
            libName  = Path.Combine(testBinDir, Path.Combine("lib", GetNativeLibraryPlainName()));
            success &= EXPECT(LoadLibraryAdvanced(libName, assembly, DllImportSearchPath.AssemblyDirectory), TestResult.DllNotFound);
            success &= EXPECT(TryLoadLibraryAdvanced(libName, assembly, DllImportSearchPath.AssemblyDirectory), TestResult.ReturnFailure);

            // -----------------------------------------------
            //         FreeLibrary Tests
            // -----------------------------------------------

            libName = Path.Combine(testBinDir, GetNativeLibraryName());
            handle  = NativeLibrary.Load(libName);

            // Valid Free
            success &= EXPECT(FreeLibrary(handle));

            // Double Free
            success &= EXPECT(FreeLibrary(handle), TestResult.InvalidOperation);

            // Null Free
            success &= EXPECT(FreeLibrary(IntPtr.Zero));

            // -----------------------------------------------
            //         GetLibraryExport Tests
            // -----------------------------------------------
            libName = Path.Combine(testBinDir, GetNativeLibraryName());
            handle  = NativeLibrary.Load(libName);

            // Valid Call (with some hard-coded name mangling)
            success &= EXPECT(GetLibraryExport(handle, TestLibrary.Utilities.IsX86 ? "_NativeSum@8" : "NativeSum"));
            success &= EXPECT(TryGetLibraryExport(handle, TestLibrary.Utilities.IsX86 ? "_NativeSum@8" : "NativeSum"));

            // Call with null handle
            success &= EXPECT(GetLibraryExport(IntPtr.Zero, "NativeSum"), TestResult.ArgumentNull);
            success &= EXPECT(TryGetLibraryExport(IntPtr.Zero, "NativeSum"), TestResult.ArgumentNull);

            // Call with null string
            success &= EXPECT(GetLibraryExport(handle, null), TestResult.ArgumentNull);
            success &= EXPECT(TryGetLibraryExport(handle, null), TestResult.ArgumentNull);

            // Call with wrong string
            success &= EXPECT(GetLibraryExport(handle, "NonNativeSum"), TestResult.EntryPointNotFound);
            success &= EXPECT(TryGetLibraryExport(handle, "NonNativeSum"), TestResult.ReturnFailure);

            NativeLibrary.Free(handle);
        }
        catch (Exception e)
        {
            // Catch any exceptions in NativeLibrary calls directly within this function.
            // These calls are used to setup the environment for tests that follow, and are not expected to fail.
            // If they do fail (ex: incorrect build environment) fail with an error code, rather than segmentation fault.
            Console.WriteLine(String.Format("Unhandled exception {0}", e));
            success = false;
        }

        return((success) ? 100 : -100);
    }
示例#26
0
 public IRetThis ReturnThis()
 {
     Console.WriteLine("RetThis has been called.");
     return(this);
 }
示例#27
0
 public Type GetMyType()
 {
     Console.WriteLine(String.Format("GetMyType has been called. My type is {0}", GetType()));
     return(GetType());
 }
示例#28
0
 public RuntimeTypeHandle GetImplType(RuntimeTypeHandle interfaceType)
 {
     Console.WriteLine(String.Format("GetImplType has been called for type {0}", Type.GetTypeFromHandle(interfaceType)));
     return(_interface2impl[Type.GetTypeFromHandle(interfaceType)].TypeHandle);
 }
示例#29
0
 public int InnocentMethod()
 {
     Console.WriteLine(String.Format("InnocentMethod has been called. My type is {0}", GetType()));
     return(3);
 }
示例#30
0
    public static int Main()
    {
        // Events on the Default Load Context

        try
        {
            AssemblyLoadContext.Default.ResolvingUnmanagedDll += HandlerFail;
            NativeSum(10, 10);
        }
        catch (DllNotFoundException e)
        {
            if (HandlerTracker != 0)
            {
                Console.WriteLine("Event Handlers not called as expected");
                return(101);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"Unexpected exception: {e.Message}");
            return(102);
        }

        try
        {
            AssemblyLoadContext.Default.ResolvingUnmanagedDll += HandlerPass;

            if (NativeSum(10, 10) != 20)
            {
                Console.WriteLine("Unexpected ReturnValue from NativeSum()");
                return(103);
            }
            if (HandlerTracker != 0)
            {
                Console.WriteLine("Event Handlers not called as expected");
                return(104);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"Unexpected exception: {e.Message}");
            return(105);
        }

        // Events on a Custom Load Context

        try
        {
            string currentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string testAsmDir = Path.Combine(currentDir, "..", "TestAsm", "TestAsm");

            ALC alc = new ALC();
            alc.ResolvingUnmanagedDll += HandlerPass;

            var assembly = alc.LoadFromAssemblyPath(Path.Combine(testAsmDir, "TestAsm.dll"));
            var type     = assembly.GetType("TestAsm");
            var method   = type.GetMethod("Sum");
            int value    = (int)method.Invoke(null, new object[] { 10, 10 });

            if (value != 20)
            {
                Console.WriteLine("Unexpected ReturnValue from TestAsm.Sum()");
                return(106);
            }
            if (HandlerTracker != 1)
            {
                Console.WriteLine("Event Handlers not called as expected");
                return(107);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"Unexpected exception: {e.Message}");
            return(108);
        }

        return(100);
    }