Пример #1
0
        static void Main(string[] args)
        {
            var         lol         = new AssemblyCreator("testAssembly");
            EnumCreator enumCreator = lol.CreateEnum("lol");

            enumCreator.AddEntry("lol", 1);
            enumCreator.Compile();
            TypeCreator             typeCreator      = lol.CreateClass("lol2");
            GenericParameterCreator genericParameter = typeCreator.SetGenericParameter("bon")[0];

            typeCreator.AddConstructor(MethodAttributes.Public, new List <Metadata>()
            {
                genericParameter
            });
            typeCreator.AddField("lol", genericParameter, FieldAttributes.Public);
            MethodCreator methodCreator = typeCreator.AddMethod("hey", MethodAttributes.Public, CallingConventions.HasThis);

            methodCreator.SetParameters(genericParameter);
            methodCreator.SetReturnType(genericParameter);
            methodCreator.ConfigureParameter(1, ParameterAttributes.None, "salut");
            typeCreator.AddProperty("salut", genericParameter, PropertyAttributes.HasDefault);
            Type   type1 = typeCreator.Compile();
            object test  = Activator.CreateInstance(type1.MakeGenericType(typeof(int)), Enum.ToObject(enumCreator, 1));

            return;
        }
Пример #2
0
        public async Task DoInitializeAsync()
        {
            await Task.Yield();

            try
            {
                await TaskScheduler.Default;
                var outputLogFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyTestAsm.log");
                File.Delete(outputLogFile);
                //// we can call the method normally, from the current 32 bit devenv process and see the result
                MyClassThatRunsIn32and64bit.MyMainMethod(outputLogFile, "Executing normally", 32, true);
                var result = File.ReadAllText(outputLogFile);
                _logger.LogMessage(result);
                File.Delete(outputLogFile);

                // or we can call it via reflection (from the current 32 bit devenv process):
                //*
                var meth = typeof(MyClassThatRunsIn32and64bit)
                           .GetMethod(nameof(MyClassThatRunsIn32and64bit.MyMainMethod), BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic);
                meth.Invoke(null, new object[] { // null for static method
                    outputLogFile, "Executing from 32 bit via reflection", 32, true
                });
                result = File.ReadAllText(outputLogFile);
                _logger.LogMessage(result);
                File.Delete(outputLogFile);

                // Or we can generate a 64 bit exe and run it
                var vsRoot = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
                var addDir = Path.Combine(vsRoot, "PublicAssemblies") + ";" + Path.Combine(vsRoot, "PrivateAssemblies");

                // now we create an assembly, load it in a 64 bit process which will invoke the same method using reflection
                var asm64BitFile = Path.ChangeExtension(Path.GetTempFileName(), ".exe");

                var type = new AssemblyCreator().CreateAssembly
                           (
                    asm64BitFile,
                    PortableExecutableKinds.PE32Plus,
                    ImageFileMachine.AMD64,
                    AdditionalAssemblyPaths: addDir, // Microsoft.VisualStudio.Shell.Interop
                    logOutput: false                 // for diagnostics
                           );
                var args = $@"""{Assembly.GetExecutingAssembly().Location
                    }"" {nameof(MyClassThatRunsIn32and64bit)} {
                        nameof(MyClassThatRunsIn32and64bit.MyMainMethod)} ""{outputLogFile}"" ""Executing from 64 bit Asm"" ""64"" true";
                var p64  = Process.Start(
                    asm64BitFile,
                    args);
                p64.WaitForExit(30 * 1000);
                File.Delete(asm64BitFile);
                result = File.ReadAllText(outputLogFile);
                _logger.LogMessage(result);
            }
            catch (Exception ex)
            {
                _logger.LogMessage($"Exception {ex}");
            }
        }
Пример #3
0
        public void TestInvokePWViaCreatedAssembly()
        {
            var dumpFile = Path.ChangeExtension(_tempOutputFile, ".dmp");
            var addDirs  = Path.Combine(Path.GetDirectoryName(_targ32bitPWDll), "PrivateAssemblies");
            var type     = new AssemblyCreator().CreateAssembly(
                _tempExeName,
                PortableExecutableKinds.PE32Plus,
                ImageFileMachine.AMD64,
                @"c:\dummy;" + addDirs, // test that multiple folders work too
                logOutput: true
                );

            Assert.IsTrue(File.Exists(_tempExeName), "generated asm not found");

            var procToDump = Process.GetProcessesByName("Microsoft.ServiceHub.Controller")[0];

            var targDllToRun = _targ32bitPWDll;
            var p64          = Process.Start(
                _tempExeName,
                $@"""{targDllToRun}"" MemoryDumpHelper CollectDump {procToDump.Id} ""{dumpFile}"" true");

            if (p64.WaitForExit(10 * 1000))
            {
                Assert.IsTrue(File.Exists(_tempOutputFile), $"Log file not found {dumpFile}");
                Assert.IsTrue(new FileInfo(_tempOutputFile).LastWriteTime > DateTime.Now - TimeSpan.FromSeconds(1), $"new Log file not found {_tempOutputFile}");
                var result = File.ReadAllText(_tempOutputFile);
                TestContext.WriteLine(result);
                Assert.IsTrue(File.Exists(dumpFile), $"Dump file not found {dumpFile}");
                var finfo = new FileInfo(dumpFile);
                Assert.IsTrue(finfo.LastWriteTime > DateTime.Now - TimeSpan.FromSeconds(1));
                Assert.IsTrue(finfo.Length > 100 * 1000 * 1000, $"Dump should be big {finfo.Length}");
                TestContext.WriteLine($"Got results dump file len = {finfo.Length:n0} {dumpFile}");
                File.Delete(dumpFile);
            }
            else
            {
                Assert.Fail($"Process took too long {_tempExeName}");
            }
        }
Пример #4
0
        private (TaskFunction TaskFunction, Exception Exception) GetTaskFunction(bool isStatic, ExerciseSubmissionViewModel viewModel)
        {
            try
            {
                var creator   = new AssemblyCreator(viewModel.Content, new[] { typeof(ILogger) });
                var assembler = creator.CreateAssembly();
                var type      = assembler.GetType(viewModel.TypeName);
                if (type == null)
                {
                    throw new NotSupportedException($"Type {viewModel.TypeName} not found.");
                }

                var method = type.GetMethod(viewModel.MethodName);
                if (method == null)
                {
                    throw new NotSupportedException($"Method {viewModel.MethodName} not found.");
                }

                TaskFunction taskFunction;
                if (isStatic)
                {
                    taskFunction = (parameters) => method.Invoke(null, parameters);
                }
                else
                {
                    var instance = Activator.CreateInstance(type);
                    taskFunction = (parameters) => method.Invoke(instance, parameters);
                }


                return(taskFunction, null);
            }
            catch (Exception exception)
            {
                return(null, exception);
            }
        }
Пример #5
0
        public void TestInvokeViaCreatedAssembly()
        {
            var type = new AssemblyCreator().CreateAssembly(
                _tempExeName,
                PortableExecutableKinds.PE32Plus,
                ImageFileMachine.AMD64,
                additionalAssemblyPaths: Path.Combine(Path.GetDirectoryName(_targ32bitPWDll), "PrivateAssemblies"),
                logOutput: true
                );

            Assert.IsTrue(File.Exists(_tempExeName), "generated asm not found");

            var procToDump = Process.GetProcessesByName("Microsoft.ServiceHub.Controller")[0];

            var targDllToRun = _targ32bitPWDll;

            targDllToRun = typeof(AssemblyCreator).Assembly.Location;
            var parm1 = procToDump.Id;
            var parm2 = _tempOutputFile;
            var parm3 = true;
            var p64   = Process.Start(
                _tempExeName,
                $@"""{targDllToRun}"" TargetStaticClass MyStaticMethodWith3Param {parm1} ""{parm2}"" {parm3}");

            if (p64.WaitForExit(10 * 1000))
            {
                Assert.IsTrue(File.Exists(_tempOutputFile), $"Output file not found {_tempOutputFile}");
                var finfo = new FileInfo(_tempOutputFile);
                Assert.IsTrue(finfo.LastWriteTime > DateTime.Now - TimeSpan.FromSeconds(1));
                var result = File.ReadAllText(_tempOutputFile);
                TestContext.WriteLine(result);
                Assert.IsTrue(result.Contains("InMyTestAsm!!!"), "Test content expected");
                Assert.IsTrue(result.Contains("Asm ResolveEvents events subscribed"), "Test content expected");
                Assert.IsTrue(result.Contains("Here I am in TargetStaticClass MyStaticMethodWith3Param"), "Test content expected");
                Assert.IsTrue(result.Contains($"StaticParm1 = {parm1}"), "Test content expected");
                Assert.IsTrue(result.Contains($"StaticParm2 = {parm2}"), "Test content expected");
                Assert.IsTrue(result.Contains($"StaticParm3 = {parm3}"), "Test content expected");
                Assert.IsTrue(IntPtr.Size == 4, "We're in a 32 bit process");
                Assert.IsTrue(result.Contains("IntPtr.Size == 8"), "we executed code in a 64 bit process");
                Assert.IsTrue(result.Contains("back from call"), "Test content expected");

                Assert.IsTrue(result.Contains("Asm ResolveEvents events Unsubscribed"), "Test content expected");
            }
            else
            {
                Assert.Fail($"Process took too long {_tempExeName}");
            }

            File.AppendAllText(_tempOutputFile, $"\r\nNow test non-static\r\n");

            p64 = Process.Start(
                _tempExeName,
                $@"""{targDllToRun}"" TargetClass MyMethodWith3Param {parm1} ""{parm2}"" {parm3}");
            if (p64.WaitForExit(10 * 1000))
            {
                Assert.IsTrue(File.Exists(_tempOutputFile), $"Output file not found {_tempOutputFile}");
                var finfo = new FileInfo(_tempOutputFile);
                Assert.IsTrue(finfo.LastWriteTime > DateTime.Now - TimeSpan.FromSeconds(1));
                var result = File.ReadAllText(_tempOutputFile);
                TestContext.WriteLine(result);
                Assert.IsTrue(result.Contains("isNotStatic"), "Test content expected");
                Assert.IsTrue(result.Contains($"parm1 = {parm1}"), "Test content expected");
                Assert.IsTrue(result.Contains($"parm2 = {parm2}"), "Test content expected");
                Assert.IsTrue(result.Contains($"parm3 = {parm3}"), "Test content expected");
            }
            else
            {
                Assert.Fail($"Process took too long {_tempExeName}");
            }
        }