public void Invoke_NullDomain()
 {
     Assert.Throws(typeof(ArgumentNullException), () =>
     {
         RemoteFunc.Invoke(null, () => { return(1); });
     });
 }
예제 #2
0
        public void Decompile(CompilationStreamPair streams, TextWriter codeWriter)
        {
            Argument.NotNull(nameof(streams), streams);
            Argument.NotNull(nameof(codeWriter), codeWriter);

            var currentSetup = AppDomain.CurrentDomain.SetupInformation;

            using (var dataTarget = DataTarget.AttachToProcess(CurrentProcess.Id, UInt32.MaxValue, AttachFlag.Passive))
                using (var context = AppDomainContext.Create(new AppDomainSetup {
                    ApplicationBase = currentSetup.ApplicationBase,
                    PrivateBinPath = currentSetup.PrivateBinPath
                })) {
                    context.LoadAssembly(LoadMethod.LoadFrom, Assembly.GetExecutingAssembly().GetAssemblyFile().FullName);
                    var results = RemoteFunc.Invoke(context.Domain, streams.AssemblyStream, Remote.GetCompiledMethods);

                    var currentMethodAddressRef = new Reference <ulong>();
                    var runtime    = dataTarget.ClrVersions.Single().CreateRuntime();
                    var translator = new IntelTranslator {
                        SymbolResolver = (Instruction instruction, long addr, ref long offset) =>
                                         ResolveSymbol(runtime, instruction, addr, currentMethodAddressRef.Value)
                    };

                    WriteJitInfo(runtime.ClrInfo, codeWriter);

                    var architecture = MapArchitecture(runtime.ClrInfo.DacInfo.TargetArchitecture);
                    foreach (var result in results)
                    {
                        DisassembleAndWrite(result, runtime, architecture, translator, currentMethodAddressRef, codeWriter);
                        codeWriter.WriteLine();
                    }
                }
        }
        public void Invoke_Serializable_FourArg()
        {
            using (var context = AppDomainContext.Create())
            {
                var actual = RemoteFunc.Invoke(
                    context.Domain,
                    10,
                    (short)11,
                    new Double?(12.0),
                    new Composite()
                {
                    Value = 13
                },
                    (value1, value2, value3, value4) =>
                {
                    return(new Test()
                    {
                        Value1 = value1, Value2 = value2, Value3 = value3, Value4 = value4
                    });
                });

                Assert.IsNotNull(actual);
                Assert.AreEqual(10, actual.Value1);
                Assert.AreEqual(11, actual.Value2);
                Assert.AreEqual(12, actual.Value3);

                Assert.IsNotNull(actual.Value4);
                Assert.AreEqual(13, actual.Value4.Value);
            }
        }
 public void Invoke_NullFunction()
 {
     using (var context = AppDomainContext.Create())
     {
         var actual = RemoteFunc.Invoke <int>(context.Domain, null);
     }
 }
예제 #5
0
        public string FindAttribute(string assemblyPath)
        {
            using (var context = AppDomainContext.Create(new AppDomainSetup
            {
                ApplicationBase = Path.GetDirectoryName(typeof(AttributeFinder).Assembly.Location),
                PrivateBinPath = Path.GetDirectoryName(assemblyPath),
            }))
            {
                context.LoadAssemblyWithReferences(LoadMethod.LoadFile, assemblyPath);
                return(RemoteFunc.Invoke(context.Domain, new AttributeFinderRequest {
                    AssemblyPath = assemblyPath, AttributeType = typeof(XafCacheWarmupAttribute)
                }, (args) =>
                {
                    WriteLine($"Try to find {nameof(XafCacheWarmupAttribute)} in {args.AssemblyPath}");
                    var assembly = AppDomain.CurrentDomain.GetAssemblies().First(b => b.Location == args.AssemblyPath);

                    var attribute = assembly.GetCustomAttributes(false).OfType <XafCacheWarmupAttribute>().FirstOrDefault();
                    if (attribute != null)
                    {
                        WriteLine($"Found {nameof(XafCacheWarmupAttribute)} with '{attribute.XafApplicationType.FullName}'");
                        return attribute.XafApplicationType.FullName;
                    }
                    return null;
                }));
            }
        }
예제 #6
0
        public TestResult Execute(IDictionary <string, object> variables, bool verbose, Action <ExecuteTraceInfo> onExecution)
        {
            using (var context = AppDomainContext.Create(new AppDomainSetup()
            {
                ConfigurationFile = this._appConfigFile
            }))
            {
                context.RemoteResolver.AddProbePath(this._binPath);
                List <string> traces = new List <string>();
                TestResult    result = null;
                try
                {
                    result = RemoteFunc.Invoke(context.Domain, variables, verbose, this.InternalExecute);
                }
                finally
                {
                    result?.Traces.ToList().ForEach(trace =>
                    {
                        try
                        {
                            onExecution(JsonConvert.DeserializeObject <ExecuteTraceInfo>(trace));
                        }
                        catch (JsonSerializationException e)
                        {
                            TraceLogger.Warning($"[Exception:{e} While deserializing trace.");
                        }
                    });
                }

                return(result);
            }
        }
예제 #7
0
 private TestCaseDeserializer CreateTestCaseDeserializer()
 {
     return(RemoteFunc.Invoke(
                _appDomain,
                _testCaseDeserializerArgs,
                args => new TestCaseDeserializer(args.AssemblyName, args.SourceInformationProvider, args.DiagnosticMessageSink)
                ));
 }
 public void Invoke_EmptyFunction()
 {
     using (var context = AppDomainContext.Create())
     {
         var actual = RemoteFunc.Invoke(context.Domain, () => { return(1); });
         Assert.AreEqual(1, actual);
     }
 }
 public void Invoke_InstanceTwoTypes_NullFunction()
 {
     Assert.Throws(typeof(ArgumentNullException), () =>
      {
          var action = new RemoteFunc<int, int>();
          action.Invoke(1, null);
      });
 }
 public void Invoke_InstanceFiveTypes_NullFunction()
 {
     Assert.Throws(typeof(ArgumentNullException), () =>
     {
         var action = new RemoteFunc <int, int, int, int, int>();
         action.Invoke(1, 2, 3, 4, null);
     });
 }
 public void Invoke_NullFunction()
 {
     Assert.Throws(typeof(ArgumentNullException), () =>
     {
         using (var context = AppDomainContext.Create())
         {
             var actual = RemoteFunc.Invoke <int>(context.Domain, null);
         }
     });
 }
예제 #12
0
 public TestResult Execute(IDictionary <string, object> variables, bool verbose)
 {
     using (var context = AppDomainContext.Create(new AppDomainSetup()
     {
         ConfigurationFile = this._appConfigFile
     }))
     {
         context.RemoteResolver.AddProbePath(this._binPath);
         return(RemoteFunc.Invoke(context.Domain, variables, verbose, this.InternalExecute));
     }
 }
예제 #13
0
 public IDictionary <string, string> GetAvailableMethods()
 {
     using (var context = AppDomainContext.Create(new AppDomainSetup()
     {
         ConfigurationFile = this._appConfigFile
     }))
     {
         context.RemoteResolver.AddProbePath(this._binPath);
         return(RemoteFunc.Invoke(context.Domain, this.InternalGetAvailableMethods));
     }
 }
예제 #14
0
        public ExecutionResult Execute(Stream assemblyStream, Stream symbolStream, IWorkSession session)
        {
            AssemblyDefinition assembly;

            using (assemblyStream)
                using (symbolStream) {
                    assembly = AssemblyDefinition.ReadAssembly(assemblyStream, new ReaderParameters {
                        ReadSymbols      = true,
                        SymbolStream     = symbolStream,
                        AssemblyResolver = PreCachedAssemblyResolver.Instance
                    });
                }

            /*
             #if DEBUG
             * assembly.Write(@"d:\Temp\assembly\" + DateTime.Now.Ticks + "-before-rewrite.dll");
             #endif
             */
            foreach (var rewriter in _rewriters)
            {
                rewriter.Rewrite(assembly, session);
            }
            if (assembly.EntryPoint == null)
            {
                throw new ArgumentException("Failed to find an entry point (Main?) in assembly.", nameof(assemblyStream));
            }

            var guardToken = AssemblyGuard.Rewrite(assembly, GuardSettings);

            using (var rewrittenStream = _memoryStreamManager.GetStream()) {
                assembly.Write(rewrittenStream);

                /*
                 #if DEBUG
                 * assembly.Write(@"d:\Temp\assembly\" + DateTime.Now.Ticks + ".dll");
                 #endif
                 */
                rewrittenStream.Seek(0, SeekOrigin.Begin);

                var currentSetup = AppDomain.CurrentDomain.SetupInformation;
                using (var context = AppDomainContext.Create(new AppDomainSetup {
                    ApplicationBase = currentSetup.ApplicationBase,
                    PrivateBinPath = currentSetup.PrivateBinPath
                })) {
                    context.LoadAssembly(LoadMethod.LoadFrom, Assembly.GetExecutingAssembly().GetAssemblyFile().FullName);
                    var(result, exception) = RemoteFunc.Invoke(context.Domain, rewrittenStream, guardToken, Remote.Execute);
                    if (ShouldMonitorException(exception))
                    {
                        _monitor.Exception(exception, session);
                    }
                    return(result);
                }
            }
        }
예제 #15
0
        private ResultViewModel Run(string code)
        {
            var totalStopwatch       = Stopwatch.StartNew();
            var compilationStopwatch = new Stopwatch();
            var rewriteStopwatch     = new Stopwatch();
            var executionStopwatch   = new Stopwatch();

            ResultViewModel resultModel(string?output) => new ResultViewModel(
                output,
                compilationStopwatch.Elapsed,
                rewriteStopwatch.Elapsed,
                executionStopwatch.Elapsed,
                totalStopwatch.Elapsed
                );

            try {
                compilationStopwatch.Start();
                CSharpRoslynGuard.Validate(code);
                var compilation = CSharpCompilation.Create(
                    "_",
                    new[] { CSharpSyntaxTree.ParseText(code) },
                    MetadataReferences,
                    new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                    );
                using (var assemblyStream = MemoryStreamManager.GetStream())
                    using (var rewrittenStream = MemoryStreamManager.GetStream()) {
                        var compilationResult = compilation.Emit(assemblyStream);
                        compilationStopwatch.Stop();
                        if (!compilationResult.Success)
                        {
                            return(resultModel(string.Join("\r\n", compilationResult.Diagnostics)));
                        }
                        assemblyStream.Seek(0, SeekOrigin.Begin);
                        rewriteStopwatch.Start();
                        var guardToken = AssemblyGuard.Rewrite(assemblyStream, rewrittenStream);
                        rewriteStopwatch.Stop();
                        var currentSetup = AppDomain.CurrentDomain.SetupInformation;
                        using (var context = AppDomainContext.Create(new AppDomainSetup {
                            ApplicationBase = currentSetup.ApplicationBase,
                            PrivateBinPath = currentSetup.PrivateBinPath
                        })) {
                            context.LoadAssembly(LoadMethod.LoadFrom, Assembly.GetExecutingAssembly().GetAssemblyFile().FullName);
                            executionStopwatch.Start();
                            var result = RemoteFunc.Invoke(context.Domain, rewrittenStream, guardToken, RemoteRun);
                            executionStopwatch.Stop();
                            return(resultModel(result?.ToString()));
                        }
                    }
            }
            catch (Exception ex) {
                return(resultModel(ex.ToString()));
            }
        }
예제 #16
0
        protected override ExecutionResultWithException ExecuteWithIsolation(MemoryStream assemblyStream, RuntimeGuardToken guardToken, IWorkSession session)
        {
            var currentSetup = AppDomain.CurrentDomain.SetupInformation;

            using (var context = AppDomainContext.Create(new AppDomainSetup {
                ApplicationBase = currentSetup.ApplicationBase,
                PrivateBinPath = currentSetup.PrivateBinPath
            })) {
                context.LoadAssembly(LoadMethod.LoadFrom, Assembly.GetExecutingAssembly().GetAssemblyFile().FullName);
                return(RemoteFunc.Invoke(context.Domain, assemblyStream.ToArray(), guardToken, Current.ProcessId, ProfilerState.Active, Remote.Execute));
            }
        }
예제 #17
0
        public ValidatorResult Validate(string assemblyPath)
        {
            var setupInfo = new AppDomainSetup {
                ApplicationName = "WCValidationDomain"
            };
            var setupInformation = AppDomain.CurrentDomain.SetupInformation;

            setupInfo.PrivateBinPath  = setupInformation.PrivateBinPath;
            setupInfo.ApplicationBase = setupInformation.ApplicationBase;
            using (var context = AppDomainContext.Create(setupInfo)){
                return(RemoteFunc.Invoke(context.Domain, assemblyPath, ValidateCore));
            }
        }
예제 #18
0
        public void Calling_Complex_TypedSearch_IsAlsoFaster_AfterBeingCalledOnce()
        {
            using (var context = AppDomainContext.Create(_setupInfo))
            {
                var result = RemoteFunc.Invoke(context.Domain,
                                               () => new CallRoutine(c => c
                                                                     .Search <ElasticsearchProject>(s => s
                                                                                                    .Query(q => q.Term("field", "value") && q.Term(p => p.Name, "name"))
                                                                                                    .Filter(f => f.GeoPolygon(p => p.MyGeoShape, "1.0", "2.0", "3.0"))
                                                                                                    .Aggregations(a => a
                                                                                                                  .Terms("term_items", gh => gh
                                                                                                                         .Field(p => p.Content)
                                                                                                                         .Aggregations(gha => gha
                                                                                                                                       .SignificantTerms("bucket_agg", m => m
                                                                                                                                                         .Field(p => p.Content)
                                                                                                                                                         .Size(2)
                                                                                                                                                         .Aggregations(ma => ma.Terms("country", t => t.Field(p => p.Country)))
                                                                                                                                                         )
                                                                                                                                       )
                                                                                                                         )
                                                                                                                  )
                                                                                                    )
                                                                     )
                                               );

                result.ElapsedMilliseconds.Should().BeGreaterOrEqualTo(200);
                var againNoWarmup = RemoteFunc.Invoke(context.Domain,
                                                      () => new CallRoutine(c => c
                                                                            .Search <ElasticsearchProject>(s => s
                                                                                                           .Query(q => q.Term("field", "value") && q.Term(p => p.Name, "name"))
                                                                                                           .Filter(f => f.GeoPolygon(p => p.MyGeoShape, "1.0", "2.0", "3.0"))
                                                                                                           .Aggregations(a => a
                                                                                                                         .Terms("term_items", gh => gh
                                                                                                                                .Field(p => p.Content)
                                                                                                                                .Aggregations(gha => gha
                                                                                                                                              .SignificantTerms("bucket_agg", m => m
                                                                                                                                                                .Field(p => p.Content)
                                                                                                                                                                .Size(2)
                                                                                                                                                                .Aggregations(ma => ma.Terms("country", t => t.Field(p => p.Country)))
                                                                                                                                                                )
                                                                                                                                              )
                                                                                                                                )
                                                                                                                         )

                                                                                                           )
                                                                            )
                                                      );

                againNoWarmup.ElapsedMilliseconds.Should().BeLessOrEqualTo(10);
            }
        }
        private AppDomainFixtureContainer CreateRemoteFixtureContainer(ExceptionAggregator aggregator)
        {
            var remoteContainer = RemoteFunc.Invoke(_appDomainContext.Domain,
                                                    _appDomainFixtureTypes,
                                                    aggregator.ToException(),
                                                    (fixtureTypes, exception) =>
            {
                var exceptionAggregator = ObjectFactory.CreateExceptionAggregator(exception);
                return(new AppDomainFixtureContainer(fixtureTypes, exceptionAggregator));
            });

            remoteContainer.CreateFixtures();
            return(remoteContainer);
        }
예제 #20
0
        public ITestCase CreateTestCaseFrom(ITestCase testCase)
        {
            // serialize the test case in the caller's app domain (the default app domain)
            // then deserialize it in our app domain

            var serializedTestCase = SerializationHelper.Serialize(testCase);

            return(RemoteFunc.Invoke(_appDomain,
                                     serializedTestCase,
                                     _lazyRemoteTestCaseDeserializer,
                                     (data, deserializer) =>
            {
                var remoteDeserializer = deserializer.Value;
                return remoteDeserializer.Deserialize(data);
            }));
        }
예제 #21
0
        public void Calling_Search_TwiceInAppDomainIsFast()
        {
            using (var context = AppDomainContext.Create(_setupInfo))
            {
                var result = RemoteFunc.Invoke(context.Domain,
                                               () => new CallRoutine(c => c.Search <ElasticsearchProject>(s => s.MatchAll()))
                                               );

                result.ElapsedMilliseconds.Should().BeGreaterOrEqualTo(100);

                result = RemoteFunc.Invoke(context.Domain,
                                           () => new CallRoutine(c => c.Search <ElasticsearchProject>(s => s.MatchAll()))
                                           );

                result.ElapsedMilliseconds.Should().BeLessOrEqualTo(10);
            }
        }
예제 #22
0
파일: Executor.cs 프로젝트: jnm2/SharpLab
        private ExecutionResult ExecuteInAppDomain(MemoryStream assemblyStream, RuntimeGuardToken guardToken, IWorkSession session)
        {
            var currentSetup = AppDomain.CurrentDomain.SetupInformation;

            using (var context = AppDomainContext.Create(new AppDomainSetup {
                ApplicationBase = currentSetup.ApplicationBase,
                PrivateBinPath = currentSetup.PrivateBinPath
            })) {
                context.LoadAssembly(LoadMethod.LoadFrom, Assembly.GetExecutingAssembly().GetAssemblyFile().FullName);
                var(result, exception) = RemoteFunc.Invoke(context.Domain, assemblyStream, guardToken, CurrentProcess.Id, Remote.Execute);
                if (ShouldMonitorException(exception))
                {
                    _monitor.Exception(exception, session);
                }
                return(result);
            }
        }
예제 #23
0
        public void Calling_RootNodeInfo_TwiceInOneAssembly_IsFast()
        {
            using (var context = AppDomainContext.Create(_setupInfo))
            {
                var result = RemoteFunc.Invoke(context.Domain,
                                               () => new CallRoutine(c => c.RootNodeInfo())
                                               );

                result.ElapsedMilliseconds.Should().BeGreaterOrEqualTo(100);

                result = RemoteFunc.Invoke(context.Domain,
                                           () => new CallRoutine(c => c.RootNodeInfo())
                                           );

                result.ElapsedMilliseconds.Should().BeLessOrEqualTo(5);
            }
        }
        public void Invoke_Serializable_NoArguments()
        {
            using (var context = AppDomainContext.Create())
            {
                var actual = RemoteFunc.Invoke(
                    context.Domain,
                    () =>
                {
                    return(new Test()
                    {
                        Value1 = 10
                    });
                });

                Assert.IsNotNull(actual);
                Assert.AreEqual(10, actual.Value1);
            }
        }
        public void Invoke_Serializable_OneArg()
        {
            using (var context = AppDomainContext.Create())
            {
                var actual = RemoteFunc.Invoke(
                    context.Domain,
                    10,
                    (value) =>
                {
                    return(new Test()
                    {
                        Value1 = value
                    });
                });

                Assert.NotNull(actual);
                Assert.Equal(10, actual.Value1);
            }
        }
예제 #26
0
        public void Decompile(Stream assemblyStream, TextWriter codeWriter)
        {
            var currentSetup = AppDomain.CurrentDomain.SetupInformation;

            using (var dataTarget = DataTarget.AttachToProcess(CurrentProcess.Id, UInt32.MaxValue, AttachFlag.Passive))
                using (var context = AppDomainContext.Create(new AppDomainSetup {
                    ApplicationBase = currentSetup.ApplicationBase,
                    PrivateBinPath = currentSetup.PrivateBinPath
                })) {
                    context.LoadAssembly(LoadMethod.LoadFrom, Assembly.GetExecutingAssembly().GetAssemblyFile().FullName);
                    var results = RemoteFunc.Invoke(context.Domain, assemblyStream, Remote.GetCompiledMethods);

                    var currentMethodAddressRef = new Reference <ulong>();
                    var runtime    = dataTarget.ClrVersions.Single().CreateRuntime();
                    var translator = new IntelTranslator {
                        SymbolResolver = (Instruction instruction, long addr, ref long offset) =>
                                         ResolveSymbol(runtime, instruction, addr, currentMethodAddressRef.Value)
                    };

                    codeWriter.WriteLine("; This is an experimental implementation.");
                    codeWriter.WriteLine("; Please report any bugs to https://github.com/ashmind/TryRoslyn/issues.");
                    codeWriter.WriteLine();

                    WriteJitInfo(runtime.ClrInfo, codeWriter);

                    var architecture = MapArchitecture(runtime.ClrInfo.DacInfo.TargetArchitecture);
                    foreach (var result in results)
                    {
                        var methodHandle = (ulong)result.Handle.ToInt64();
                        var method       = runtime.GetMethodByHandle(methodHandle);
                        if (method == null)
                        {
                            codeWriter.WriteLine("    ; Method with handle 0x{0:X} was somehow not found by CLRMD.", methodHandle);
                            codeWriter.WriteLine("    ; See https://github.com/ashmind/TryRoslyn/issues/84.");
                            continue;
                        }

                        DisassembleAndWrite(method, result.Message, architecture, translator, currentMethodAddressRef, codeWriter);
                        codeWriter.WriteLine();
                    }
                }
        }
예제 #27
0
        public void Calling_RootNodeInfo_OnceInTwoAsemblies_SlowTwice()
        {
            using (var context = AppDomainContext.Create(_setupInfo))
            {
                var result = RemoteFunc.Invoke(context.Domain,
                                               () => new CallRoutine(c => c.RootNodeInfo())
                                               );

                result.ElapsedMilliseconds.Should().BeGreaterOrEqualTo(100);
            }

            using (var context = AppDomainContext.Create(_setupInfo))
            {
                var result = RemoteFunc.Invoke(context.Domain,
                                               () => new CallRoutine(c => c.RootNodeInfo())
                                               );

                result.ElapsedMilliseconds.Should().BeGreaterOrEqualTo(100);
            }
        }
예제 #28
0
        protected override JitAsmResultScope JitCompileAndGetMethods(MemoryStream assemblyStream)
        {
            AppDomainContext <AssemblyTargetLoader, PathBasedAssemblyResolver>?context = null;

            try {
                var currentSetup = AppDomain.CurrentDomain.SetupInformation;
                context = AppDomainContext.Create(new AppDomainSetup {
                    ApplicationBase = currentSetup.ApplicationBase,
                    PrivateBinPath  = currentSetup.PrivateBinPath
                });
                context.LoadAssembly(LoadMethod.LoadFrom, typeof(JitAsmDecompiler).Assembly.GetAssemblyFile().FullName);
                var results = RemoteFunc.Invoke(context.Domain, assemblyStream.ToArray(), Remote.GetCompiledMethods);

                return(new JitAsmResultScope(results, context));
            }
            catch {
                context?.Dispose();
                throw;
            }
        }
        public void Invoke_Serializable_TwoArg()
        {
            using (var context = AppDomainContext.Create())
            {
                var actual = RemoteFunc.Invoke(
                    context.Domain,
                    10,
                    (short)11,
                    (value1, value2) =>
                {
                    return(new Test()
                    {
                        Value1 = value1, Value2 = value2
                    });
                });

                Assert.IsNotNull(actual);
                Assert.AreEqual(10, actual.Value1);
                Assert.AreEqual(11, actual.Value2);
            }
        }
        public void Invoke_Serializable_ThreeArg()
        {
            using (var context = AppDomainContext.Create())
            {
                var actual = RemoteFunc.Invoke(
                    context.Domain,
                    10,
                    (short)11,
                    new Double?(12),
                    (value1, value2, value3) =>
                {
                    return(new Test()
                    {
                        Value1 = value1, Value2 = value2, Value3 = value3
                    });
                });

                Assert.NotNull(actual);
                Assert.Equal(10, actual.Value1);
                Assert.Equal(11, actual.Value2);
                Assert.Equal(12, actual.Value3);
            }
        }
예제 #31
0
 public async Task <Tr> RunRemoteFuncAsync <Tr, T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, Func <T1, T2, T3, T4, Tr> func)
 {
     return(await Task.Factory.StartNew(() =>
                                        RemoteFunc.Invoke <T1, T2, T3, T4, Tr>(_context.Domain, arg1, arg2, arg3, arg4, func)
                                        ));
 }
 public void Invoke_InstanceOneType_NullFunction()
 {
     var action = new RemoteFunc<int>();
     action.Invoke(null);
 }
 public void Invoke_InstanceTwoTypes_NullFunction()
 {
     var action = new RemoteFunc<int, int>();
     action.Invoke(1, null);
 }