Пример #1
0
        public static int Main(string[] args)
        {
            if (args.Length > 0 && args[0].Equals("RunTest", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("In RunTest, exiting.");
                return(100);
            }

            string serverName     = ReverseServer.MakeServerAddress();
            Task   backgroundTask = Task.Run(() =>
            {
                ReverseServer server = null;
                try
                {
                    Task task = Task.Run(async() =>
                    {
                        server = new ReverseServer(serverName);
                        using (Stream serverStream = await server.AcceptAsync())
                        {
                            IpcAdvertise advertise = IpcAdvertise.Parse(serverStream);
                            Console.WriteLine($"Got IpcAdvertise: {advertise}");

                            int processId = (int)advertise.ProcessId;

                            // While we are paused in startup send the profiler startup command
                            string profilerPath             = GetProfilerPath();
                            DiagnosticsIPCWorkaround client = new DiagnosticsIPCWorkaround(processId);
                            client.SetStartupProfiler(ReverseStartupProfilerGuid, profilerPath);

                            // Resume runtime message
                            IpcMessage resumeMessage = new IpcMessage(0x04, 0x01);
                            Console.WriteLine($"Sent resume runtime message: {resumeMessage.ToString()}");
                            IpcMessage resumeResponse = IpcClient.SendMessage(serverStream, resumeMessage);
                            Logger.logger.Log($"Received: {resumeResponse.ToString()}");
                        }
                    });

                    task.Wait();
                }
                catch (Exception e)
                {
                    Console.WriteLine($"ReverseServer saw exception {e.Message}");
                    Console.WriteLine(e.StackTrace);


                    Console.WriteLine($"Inner exception {e.InnerException?.Message}");
                    Console.WriteLine(e.InnerException?.StackTrace);
                }
                finally
                {
                    server?.Shutdown();
                }
            });

            return(ProfilerTestRunner.Run(profileePath: System.Reflection.Assembly.GetExecutingAssembly().Location,
                                          testName: "ReverseStartup",
                                          profilerClsid: Guid.Empty,
                                          profileeOptions: ProfileeOptions.NoStartupAttach | ProfileeOptions.ReverseDiagnosticsMode,
                                          reverseServerName: serverName));
        }
        /// <summary>
        /// Trigger a core dump generation.
        /// </summary>
        /// <param name="dumpType">Type of the dump to be generated</param>
        /// <param name="dumpPath">Full path to the dump to be generated. By default it is /tmp/coredump.{pid}</param>
        /// <param name="logDumpGeneration">When set to true, display the dump generation debug log to the console.</param>
        public void WriteDump(DumpType dumpType, string dumpPath, bool logDumpGeneration = false)
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                throw new PlatformNotSupportedException($"Unsupported operating system: {RuntimeInformation.OSDescription}");
            }

            if (string.IsNullOrEmpty(dumpPath))
            {
                throw new ArgumentNullException($"{nameof(dumpPath)} required");
            }

            var payload  = SerializeCoreDump(dumpPath, dumpType, logDumpGeneration);
            var message  = new IpcMessage(DiagnosticsServerCommandSet.Dump, (byte)DumpCommandId.GenerateCoreDump, payload);
            var response = IpcClient.SendMessage(_processId, message);
            var hr       = 0;

            switch ((DiagnosticsServerCommandId)response.Header.CommandId)
            {
            case DiagnosticsServerCommandId.Error:
                hr = BitConverter.ToInt32(response.Payload, 0);
                throw new ServerErrorException($"Writing dump failed (HRESULT: 0x{hr:X8})");

            case DiagnosticsServerCommandId.OK:
                return;

            default:
                throw new ServerErrorException($"Writing dump failed - server responded with unknown command");
            }
        }
Пример #3
0
        internal static IntPtr TraceTree(IntPtr handle, IntPtr baseAddr, int[] offsets, int finalOffset)
        {
#if x64
            const int size = 8;
#elif x86
            const int size = 4;
#endif // Arch
            var buffer = new byte[size];
            foreach (var offset in offsets)
            {
                if (!ReadProcessMemory(handle, IntPtr.Add(baseAddr, offset), buffer, size, out _))
                {
                    IpcClient.SendSignal(Signal.InternalException, new[] { "Unable to calculate address: " + Marshal.GetLastWin32Error(), "MemoryCore", "TraceTree" });
                    throw new Exception("Unable to calculate address: " + Marshal.GetLastWin32Error());
                }
#if x64
                baseAddr = new IntPtr(BitConverter.ToInt64(buffer, 0));
#elif x86
                baseAddr = new IntPtr(BitConverter.ToInt32(buffer, 0));
#endif // Arch
                if (baseAddr == IntPtr.Zero)
                {
                    return(IntPtr.Zero);
                }
            }

            return(IntPtr.Add(baseAddr, finalOffset));
        }
        /// <summary>
        /// Attach a profiler.
        /// </summary>
        /// <param name="attachTimeout">Timeout for attaching the profiler</param>
        /// <param name="profilerGuid">Guid for the profiler to be attached</param>
        /// <param name="profilerPath">Path to the profiler to be attached</param>
        /// <param name="additionalData">Additional data to be passed to the profiler</param>
        public void AttachProfiler(TimeSpan attachTimeout, Guid profilerGuid, string profilerPath, byte[] additionalData = null)
        {
            if (profilerGuid == null || profilerGuid == Guid.Empty)
            {
                throw new ArgumentException($"{nameof(profilerGuid)} must be a valid Guid");
            }

            if (String.IsNullOrEmpty(profilerPath))
            {
                throw new ArgumentException($"{nameof(profilerPath)} must be non-null");
            }

            byte[] serializedConfiguration = SerializeProfilerAttach((uint)attachTimeout.TotalSeconds, profilerGuid, profilerPath, additionalData);
            var    message  = new IpcMessage(DiagnosticsServerCommandSet.Profiler, (byte)ProfilerCommandId.AttachProfiler, serializedConfiguration);
            var    response = IpcClient.SendMessage(_processId, message);

            switch ((DiagnosticsServerCommandId)response.Header.CommandId)
            {
            case DiagnosticsServerCommandId.Error:
                var hr = BitConverter.ToInt32(response.Payload, 0);
                throw new ServerErrorException($"Profiler attach failed (HRESULT: 0x{hr:X8})");

            case DiagnosticsServerCommandId.OK:
                return;

            default:
                throw new ServerErrorException($"Profiler attach failed - server responded with unknown command");
            }

            // The call to set up the pipe and send the message operates on a different timeout than attachTimeout, which is for the runtime.
            // We should eventually have a configurable timeout for the message passing, potentially either separately from the
            // runtime timeout or respect attachTimeout as one total duration.
        }
Пример #5
0
        public static void Main()
        {
            var client = new IpcClient("ExamplePipeName");

            client.Connected    += () => Console.WriteLine("Connected");
            client.Disconnected += () => Console.WriteLine("Disconnected");
            client.Message      += message => Console.WriteLine($"Message Received: {message}");

            client.Connect();

            Thread.Sleep(1000);

            client.Send("Client 1");

            Thread.Sleep(1000);

            client.Send("Client 2");

            Thread.Sleep(1000);

            client.Send("Client 3");

            Thread.Sleep(10000);

            client.Stop();

            Console.WriteLine("End");
        }
Пример #6
0
        public static int Main(string[] args)
        {
            Process currentProcess = Process.GetCurrentProcess();
            int     pid            = currentProcess.Id;

            Logger.logger.Log($"Test PID: {pid}");

            Stream stream = ConnectionHelper.GetStandardTransport(pid);

            // 0x04 = ProcessCommandSet, 0x04 = ProcessInfo2
            var processInfoMessage = new IpcMessage(0x04, 0x04);

            Logger.logger.Log($"Wrote: {processInfoMessage}");
            IpcMessage response = IpcClient.SendMessage(stream, processInfoMessage);

            Logger.logger.Log($"Received: <omitted>");

            Utils.Assert(response.Header.CommandSet == 0xFF, $"Response must have Server command set. Expected: 0xFF, Received: 0x{response.Header.CommandSet:X2}"); // server
            Utils.Assert(response.Header.CommandId == 0x00, $"Response must have OK command id. Expected: 0x00, Received: 0x{response.Header.CommandId:X2}");        // OK

            // Parse payload
            // uint64_t ProcessId;
            // GUID RuntimeCookie;
            // LPCWSTR CommandLine;
            // LPCWSTR OS;
            // LPCWSTR Arch;

            int totalSize = response.Payload.Length;

            Logger.logger.Log($"Total size of Payload = {totalSize} bytes");

            // VALIDATE PID
            int    start     = 0;
            int    end       = start + 8 /* sizeof(uint63_t) */;
            UInt64 processId = BitConverter.ToUInt64(response.Payload[start..end]);
Пример #7
0
        public static async Task <bool> TEST_TracesHaveRelevantEvents()
        {
            bool   fSuccess   = true;
            string serverName = ReverseServer.MakeServerAddress();

            Logger.logger.Log($"Server name is '{serverName}'");
            var server = new ReverseServer(serverName);

            using var memoryStream = new MemoryStream();
            Task <bool> subprocessTask = Utils.RunSubprocess(
                currentAssembly: Assembly.GetExecutingAssembly(),
                environment: new Dictionary <string, string> {
                { Utils.DiagnosticPortsEnvKey, $"{serverName}" }
            },
                duringExecution: async(pid) =>
            {
                Stream stream          = await server.AcceptAsync();
                IpcAdvertise advertise = IpcAdvertise.Parse(stream);
                Logger.logger.Log(advertise.ToString());

                var config = new SessionConfiguration(
                    circularBufferSizeMB: 1000,
                    format: EventPipeSerializationFormat.NetTrace,
                    providers: new List <Provider> {
                    new Provider("Microsoft-Windows-DotNETRuntimePrivate", 0x80000000, EventLevel.Verbose)
                });
                Logger.logger.Log("Starting EventPipeSession over standard connection");
                using Stream eventStream = EventPipeClient.CollectTracing(pid, config, out var sessionId);
                Logger.logger.Log($"Started EventPipeSession over standard connection with session id: 0x{sessionId:x}");
                Task readerTask = eventStream.CopyToAsync(memoryStream);

                Logger.logger.Log($"Send ResumeRuntime Diagnostics IPC Command");
                // send ResumeRuntime command (0x04=ProcessCommandSet, 0x01=ResumeRuntime commandid)
                var message = new IpcMessage(0x04, 0x01);
                Logger.logger.Log($"Sent: {message.ToString()}");
                IpcMessage response = IpcClient.SendMessage(stream, message);
                Logger.logger.Log($"received: {response.ToString()}");

                await Task.Delay(TimeSpan.FromSeconds(2));
                Logger.logger.Log("Stopping EventPipeSession over standard connection");
                EventPipeClient.StopTracing(pid, sessionId);
                await readerTask;
                Logger.logger.Log("Stopped EventPipeSession over standard connection");
            }
                );

            fSuccess &= await subprocessTask;

            memoryStream.Seek(0, SeekOrigin.Begin);
            using var source = new EventPipeEventSource(memoryStream);
            var  parser = new ClrPrivateTraceEventParser(source);
            bool isStartupEventPresent = false;

            parser.StartupEEStartupStart += (eventData) => isStartupEventPresent = true;
            source.Process();

            Logger.logger.Log($"isStartupEventPresent: {isStartupEventPresent}");

            return(isStartupEventPresent && fSuccess);
        }
Пример #8
0
        private static void UserInputLoop(IpcClient<ICalculator> client)
        {
            var line = string.Empty;

            Console.WriteLine("Enter addition, like '4+1' or 'quit'..");
            while ((line = Console.ReadLine()) != "quit")
            {
                if (line.Contains("+"))
                {
                    var tokens = line.Split('+');
                    if (tokens.Length == 2)
                    {
                        try
                        {
                            var a = int.Parse(tokens[0]);
                            var b = int.Parse(tokens[1]);

                            var res = client.Proxy.Add(a, b);

                            Console.WriteLine("The result of the addition is {0}", res);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unsupported command. Please try again..");
                    }
                }
            }
        }
Пример #9
0
        public void VerifyBasicSendReceive()
        {
            var fooStub = new FooStub();
            fooStub.ReturnValueOfBar = "Bar";

            var dispatcherThread = new DispatcherThread(Dispatcher.Run);
            dispatcherThread.Start();

            var ipcServer = new IpcServer<IFoo>(fooStub, dispatcherThread.Dispatcher, IPAddress.Loopback, 62000, new JsonDotNetSerializer());
            ipcServer.Listen();

            var ipcClient = new IpcClient<IFoo>(IPAddress.Loopback, 62000, new JsonDotNetSerializer());

            object response;

            ipcClient.Proxy.Foo();

            Assert.AreEqual(1, fooStub.NumberOfFooCalls);

            response = ipcClient.Proxy.Bar();

            Assert.AreEqual(fooStub.ReturnValueOfBar, response);
            Assert.AreEqual(1, fooStub.NumberOfBarCalls);

            ipcClient.Dispose();
            ipcServer.Dispose();

            dispatcherThread.Shutdown();
        }
Пример #10
0
        private static void UserInputLoop(IpcClient <ICalculator> client)
        {
            var line = string.Empty;

            Console.WriteLine("Enter addition, like '4+1' or 'quit'..");
            while ((line = Console.ReadLine()) != "quit")
            {
                if (line.Contains("+"))
                {
                    var tokens = line.Split('+');
                    if (tokens.Length == 2)
                    {
                        try
                        {
                            var a = int.Parse(tokens[0]);
                            var b = int.Parse(tokens[1]);

                            var res = client.Proxy.Add(a, b);

                            Console.WriteLine("The result of the addition is {0}", res);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unsupported command. Please try again..");
                    }
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Initiate a core dump in the target process runtime.
        /// </summary>
        /// <param name="processId">.NET Core process id</param>
        /// <param name="dumpName">Path and file name of core dump</param>
        /// <param name="dumpType">Type of dump</param>
        /// <param name="diagnostics">If true, log to console the dump generation diagnostics</param>
        /// <returns>DiagnosticsServerErrorCode</returns>
        public static int GenerateCoreDump(int processId, string dumpName, DumpType dumpType, bool diagnostics)
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                throw new PlatformNotSupportedException($"Unsupported operating system: {RuntimeInformation.OSDescription}");
            }

            if (string.IsNullOrEmpty(dumpName))
            {
                throw new ArgumentNullException($"{nameof(dumpName)} required");
            }


            var payload = SerializeCoreDump(dumpName, dumpType, diagnostics);
            var message = new IpcMessage(DiagnosticsServerCommandSet.Dump, (byte)DumpCommandId.GenerateCoreDump, payload);

            var response = IpcClient.SendMessage(processId, message);

            var hr = 0;

            switch ((DiagnosticsServerCommandId)response.Header.CommandId)
            {
            case DiagnosticsServerCommandId.Error:
            case DiagnosticsServerCommandId.OK:
                hr = BitConverter.ToInt32(response.Payload, 0);
                break;

            default:
                return(-1);
            }

            return(hr);
        }
Пример #12
0
        public TCPPacket(byte[] buffer, int ignoreLength)
        {
            try
            {
                GlobalOffset = ignoreLength;

                SourcePort      = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, ignoreLength + 0));
                DestinationPort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, ignoreLength + 2));

                var offsetAndFlags = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, ignoreLength + 12));
                DataOffset = (byte)((offsetAndFlags >> 12) * 4);
                Flags      = (TCPFlags)(offsetAndFlags & 511); // 0b111111111 = 511

                Payload = buffer.Skip(ignoreLength + DataOffset).ToArray();

                IsValid = true;
            }
            catch
            {
                SourcePort      = 0;
                DestinationPort = 0;
                DataOffset      = 0;
                Flags           = TCPFlags.NONE;

                Payload = null;

                IsValid = false;
                IpcClient.SendSignal(Signal.ClientPacketParseFail, new[] { "unable to tcplize" }, true);
            }
        }
Пример #13
0
        public static async Task <bool> TEST_RuntimeResumesExecutionWithCommand()
        {
            bool   fSuccess   = true;
            string serverName = ReverseServer.MakeServerAddress();

            Logger.logger.Log($"Server name is '{serverName}'");
            var         server         = new ReverseServer(serverName);
            Task <bool> subprocessTask = Utils.RunSubprocess(
                currentAssembly: Assembly.GetExecutingAssembly(),
                environment: new Dictionary <string, string> {
                { Utils.DiagnosticPortsEnvKey, $"{serverName}" }
            },
                duringExecution: async(_) =>
            {
                Stream stream          = await server.AcceptAsync();
                IpcAdvertise advertise = IpcAdvertise.Parse(stream);
                Logger.logger.Log(advertise.ToString());
                // send ResumeRuntime command (0x04=ProcessCommandSet, 0x01=ResumeRuntime commandid)
                var message = new IpcMessage(0x04, 0x01);
                Logger.logger.Log($"Sent: {message.ToString()}");
                IpcMessage response = IpcClient.SendMessage(stream, message);
                Logger.logger.Log($"received: {response.ToString()}");
            }
                );

            fSuccess &= await subprocessTask;

            return(fSuccess);
        }
Пример #14
0
        public void Start()
        {
            this._isStopping = false;

            Task.Run(() =>
            {
                Log.Warning("MessageDispatcher Output Thread Started");

                foreach (var data in this._outputQueue.GetConsumingEnumerable())
                {
                    try
                    {
                        var output = data.Consumer(data.Message, data.HeaderLength);

                        data.Listener(data.Header, output);
                        Interlocked.Increment(ref this._messagesDispatched);
                    }
                    catch (Exception e)
                    {
                        IpcClient.SendSignal(Signal.InternalExternalException, new[] { e.Message, e.StackTrace, "MessageDispatcher", "Start" });
                    }
                }

                Log.Warning("MessageDispatcher Output Thread Exited");
            });
        }
Пример #15
0
        public void Chat_Client(int port)
        {
            try
            {
                Task.Factory.StartNew(() =>
                {
                    var c = new IpcClient();

                    c.Initialize(port);

                    listBox1.Items.Add("Started client.");

                    var rep = c.Send("Hello from client");

                    listBox1.Items.Add(rep);
                });
                //while(true)
                //{
                //    Thread.Sleep(1000);
                //}
            }
            catch (Exception ex)
            {
                listBox1.Items.Add(ex.Message);
            }


            //Console.WriteLine();
        }
Пример #16
0
 public void Restart()
 {
     // Do not block UI when calling other process via named pipe
     Task.Run(() =>
     {
         try
         {
             if (!IpcClient.GetRunningApps().Contains("ClientLauncher"))
             {
                 string clPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Tools", "MP2-ClientLauncher", "MP2-ClientLauncher.exe");
                 Process.Start(clPath);
                 int waitCounter = 10;
                 // Wait until process is running and the pipe was created.
                 while (waitCounter-- > 0 && !IpcClient.GetRunningApps().Contains("ClientLauncher"))
                 {
                     Thread.Sleep(200);
                 }
             }
             // Sends a command to tray launcher that we want to be restarted.
             using (var client = new IpcClient("ClientLauncher"))
             {
                 client.Connect();
                 client.RequestRestart();
             }
         }
         catch (Exception ex)
         {
             ServiceRegistration.Get <ILogger>().Error("Error trying to send restart request.", ex);
         }
     });
 }
Пример #17
0
        /// <summary>
        /// Lists the namespaces.
        /// </summary>
        /// <param name="classId">The assembly location.</param>
        /// <param name="is32Bit"></param>
        /// <returns></returns>
        List <string> ListNamespaces(string classId, bool is32Bit)
        {
            try
            {
                if (is32Bit)
                {
                    var execute       = IpcClient.GetIPCExecutor(_clientStreamWrapper).Invoke(classId.ToGuid(), "", Execute.GetNamespaces, new ParameterInfoTO[] { });
                    var namespaceList = execute as List <string>;
                    return(namespaceList);
                }
                var type           = GetType(classId, false);
                var loadedAssembly = type.Assembly;
                // ensure we flush out the rubbish that GAC brings ;)
                var namespaces = loadedAssembly.GetTypes()
                                 .Select(t => t.FullName)
                                 .Distinct()
                                 .Where(q => q.IndexOf("`", StringComparison.Ordinal) < 0 &&
                                        q.IndexOf("+", StringComparison.Ordinal) < 0 &&
                                        q.IndexOf("<", StringComparison.Ordinal) < 0 &&
                                        !q.StartsWith("_")).ToList();

                return(namespaces);
            }
            catch (BadImageFormatException e)
            {
                Dev2Logger.Error(e, GlobalConstants.WarewolfError);
                throw;
            }
        }
Пример #18
0
        Type GetType(string classId, bool is32Bit)
        {
            Guid.TryParse(classId, out Guid clasID);
            var  is64BitProcess = Environment.Is64BitProcess;
            Type type;

            if (is64BitProcess && is32Bit)
            {
                try
                {
                    var execute = IpcClient.GetIPCExecutor(_clientStreamWrapper).Invoke(clasID, "", Execute.GetType, new ParameterInfoTO[] { });
                    type = execute as Type;
                }
                catch (Exception ex)
                {
                    Dev2Logger.Error("GetType", ex, GlobalConstants.WarewolfError);
                    type = Type.GetTypeFromCLSID(clasID, true);
                }
            }
            else
            {
                type = Type.GetTypeFromCLSID(clasID, true);
            }
            return(string.IsNullOrEmpty(classId) ? null : type);
        }
        private bool disposedValue = false; // To detect redundant calls

        internal EventPipeSession(int processId, IEnumerable <EventPipeProvider> providers, bool requestRundown, int circularBufferMB)
        {
            _processId        = processId;
            _providers        = providers;
            _requestRundown   = requestRundown;
            _circularBufferMB = circularBufferMB;

            var config  = new EventPipeSessionConfiguration(circularBufferMB, EventPipeSerializationFormat.NetTrace, providers, requestRundown);
            var message = new IpcMessage(DiagnosticsServerCommandSet.EventPipe, (byte)EventPipeCommandId.CollectTracing2, config.SerializeV2());

            EventStream = IpcClient.SendMessage(processId, message, out var response);
            switch ((DiagnosticsServerCommandId)response.Header.CommandId)
            {
            case DiagnosticsServerCommandId.OK:
                _sessionId = BitConverter.ToInt64(response.Payload, 0);
                break;

            case DiagnosticsServerCommandId.Error:
                var hr = BitConverter.ToInt32(response.Payload, 0);
                throw new ServerErrorException($"EventPipe session start failed (HRESULT: 0x{hr:X8})");

            default:
                throw new ServerErrorException($"EventPipe session start failed - Server responded with unknown command");
            }
        }
Пример #20
0
        public static IClient GetClient()
        {
            var client = new IpcClient("./geth.ipc");

            return(new RpcClient(new Uri("https://eth2.augur.net")));
            //return new RpcClient(new Uri("http://localhost:8545/"));
        }
Пример #21
0
        public void VerifyBasicSendReceive()
        {
            var fooStub = new FooStub();

            fooStub.ReturnValueOfBar = "Bar";

            var dispatcherThread = new DispatcherThread(Dispatcher.Run);

            dispatcherThread.Start();

            var ipcServer = new IpcServer <IFoo>(fooStub, dispatcherThread.Dispatcher, IPAddress.Loopback, 62000, new JsonDotNetSerializer());

            ipcServer.Listen();

            var ipcClient = new IpcClient <IFoo>(IPAddress.Loopback, 62000, new JsonDotNetSerializer());

            object response;

            ipcClient.Proxy.Foo();

            Assert.AreEqual(1, fooStub.NumberOfFooCalls);

            response = ipcClient.Proxy.Bar();

            Assert.AreEqual(fooStub.ReturnValueOfBar, response);
            Assert.AreEqual(1, fooStub.NumberOfBarCalls);

            ipcClient.Dispose();
            ipcServer.Dispose();

            dispatcherThread.Shutdown();
        }
Пример #22
0
        public void VerifyCanPerformFunctionCallAfterBulk()
        {
            int numberKiloBytes = 1024 * 1024 * 1;
            var buffer          = new byte[numberKiloBytes];

            for (int i = 0; i < numberKiloBytes; ++i)
            {
                buffer[i] = (byte)(i % 2);
            }

            var bulkDataStub = new BulkDataStub(buffer);

            var dispatcherThread = new DispatcherThread(Dispatcher.Run);

            dispatcherThread.Start();

            var ipcServer = new IpcServer <IBulkData>(bulkDataStub, dispatcherThread.Dispatcher, IPAddress.Loopback, 62000, new MsDataContractJsonSerializer());

            ipcServer.Listen();

            var ipcClient = new IpcClient <IBulkData>(IPAddress.Loopback, 62000, new MsDataContractJsonSerializer());

            ipcClient.Proxy.GetBulkyData();

            var fooResult = ipcClient.Proxy.Foo();

            Assert.AreEqual("Bar", fooResult);

            ipcClient.Dispose();
            ipcServer.Dispose();

            bulkDataStub.Dispose();

            dispatcherThread.Shutdown();
        }
Пример #23
0
        public static async Task <bool> TEST_CanGetProcessInfo2WhileSuspended()
        {
            bool        fSuccess       = true;
            Task <bool> subprocessTask = Utils.RunSubprocess(
                currentAssembly: Assembly.GetExecutingAssembly(),
                environment: new Dictionary <string, string>
            {
                { Utils.DiagnosticPortSuspend, "1" }
            },
                duringExecution: (int pid) =>
            {
                Stream stream = ConnectionHelper.GetStandardTransport(pid);

                // 0x04 = ProcessCommandSet, 0x04 = ProcessInfo2
                var processInfoMessage = new IpcMessage(0x04, 0x04);
                Logger.logger.Log($"Wrote: {processInfoMessage}");
                IpcMessage response = IpcClient.SendMessage(stream, processInfoMessage);
                Logger.logger.Log($"Received: [{response.Payload.Select(b => b.ToString("X2") + " ").Aggregate(string.Concat)}]");
                ProcessInfo2 processInfo2 = ProcessInfo2.TryParse(response.Payload);
                Utils.Assert(String.IsNullOrEmpty(processInfo2.ManagedEntrypointAssemblyName));

                // send resume command on this connection
                var message = new IpcMessage(0x04, 0x01);
                Logger.logger.Log($"Sent: {message.ToString()}");
                response = IpcClient.SendMessage(ConnectionHelper.GetStandardTransport(pid), message);
                Logger.logger.Log($"Received: {response.ToString()}");

                return(Task.FromResult(true));
            }
                );

            fSuccess &= await subprocessTask;

            return(fSuccess);
        }
Пример #24
0
        public void SetStartupProfiler(Guid profilerGuid, string profilerPath)
        {
            MethodInfo startupProfiler = typeof(DiagnosticsClient).GetMethod("SetStartupProfiler", BindingFlags.Public);

            if (startupProfiler != null)
            {
                throw new Exception("You updated DiagnosticsClient to a version that supports SetStartupProfiler, please remove this and use the real code.");
            }

            Console.WriteLine("Sending startup profiler message.");

            using (var stream = new MemoryStream())
                using (var writer = new BinaryWriter(stream))
                {
                    writer.Write(profilerGuid.ToByteArray());
                    writer.WriteString(profilerPath);

                    writer.Flush();
                    byte[] payload = stream.ToArray();

                    var message = new IpcMessage(0x03, 0x02, payload);
                    Console.WriteLine($"Sent: {message.ToString()}");
                    IpcMessage response = IpcClient.SendMessage(ConnectionHelper.GetStandardTransport(_processId), message);
                    Console.WriteLine($"Received: {response.ToString()}");
                }

            Console.WriteLine("Finished sending startup profiler message.");
        }
Пример #25
0
        public static void Main(string[] args)
        {
            var client = new IpcClient<ICalculator>(IPAddress.Loopback, 62001, new JsonDotNetSerializer());

            var line = string.Empty;

            Console.WriteLine("Enter addition, like '4+1' or 'quit'..");
            while ((line = Console.ReadLine()) != "quit")
            {
                if (line.Contains("+"))
                {
                    var tokens = line.Split('+');
                    if (tokens.Length == 2)
                    {
                        try
                        {
                            var a = int.Parse(tokens[0]);
                            var b = int.Parse(tokens[1]);

                            var res = client.Proxy.Add(a, b);

                            Console.WriteLine("The result of the addition is {0}", res);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unsupported command. Please try again..");
                    }
                }
            }
        }
Пример #26
0
        public static void Main(string[] args)
        {
            var client = new IpcClient <ICalculator>(IPAddress.Loopback, 62001, new JsonDotNetSerializer());

            var line = string.Empty;

            Console.WriteLine("Enter addition, like '4+1' or 'quit'..");
            while ((line = Console.ReadLine()) != "quit")
            {
                if (line.Contains("+"))
                {
                    var tokens = line.Split('+');
                    if (tokens.Length == 2)
                    {
                        try
                        {
                            var a = int.Parse(tokens[0]);
                            var b = int.Parse(tokens[1]);

                            var res = client.Proxy.Add(a, b);

                            Console.WriteLine("The result of the addition is {0}", res);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unsupported command. Please try again..");
                    }
                }
            }
        }
Пример #27
0
        public static int Main(string[] args)
        {
            Process currentProcess = Process.GetCurrentProcess();
            int     pid            = currentProcess.Id;

            Logger.logger.Log($"Test PID: {pid}");
            var testEnvPairs = new Dictionary <string, string>
            {
                { "TESTKEY1", "TESTVAL1" },
                { "TESTKEY2", "TESTVAL2" },
                { "TESTKEY3", "__TEST__VAL=;--3" }
            };

            foreach (var(key, val) in testEnvPairs)
            {
                System.Environment.SetEnvironmentVariable(key, val);
            }

            Stream stream = ConnectionHelper.GetStandardTransport(pid);

            // 0x04 = ProcessCommandSet, 0x02 = ProcessInfo
            var processInfoMessage = new IpcMessage(0x04, 0x02);

            Logger.logger.Log($"Wrote: {processInfoMessage}");
            Stream continuationStream = IpcClient.SendMessage(stream, processInfoMessage, out IpcMessage response);

            Logger.logger.Log($"Received: {response}");

            Utils.Assert(response.Header.CommandSet == 0xFF, $"Response must have Server command set. Expected: 0xFF, Received: 0x{response.Header.CommandSet:X2}"); // server
            Utils.Assert(response.Header.CommandId == 0x00, $"Response must have OK command id. Expected: 0x00, Received: 0x{response.Header.CommandId:X2}");        // OK

            UInt32 continuationSizeInBytes = BitConverter.ToUInt32(response.Payload[0..4]);
        public void BuildValuedTypeParams_GivenValid_ShouldPassThrough()
        {
            //---------------Set up test pack-------------------
            var pipeMock        = new Mock <INamedPipeClientStreamWrapper>();
            var memoryStream    = new MemoryStream();
            var serializeObject = JsonConvert.SerializeObject(GetType());

            memoryStream.WriteByte(Encoding.ASCII.GetBytes(serializeObject)[0]);
            pipeMock.Setup(wrapper => wrapper.GetInternalStream()).Returns(memoryStream);
            var client               = IpcClient.GetIPCExecutor(pipeMock.Object);
            var type                 = typeof(ComPluginRuntimeHandler);
            var methodInfo           = type.GetMethod("BuildValuedTypeParams", BindingFlags.Static | BindingFlags.NonPublic);
            ComPluginInvokeArgs args = new ComPluginInvokeArgs
            {
                ClsId      = adodbConnectionClassId,
                Is32Bit    = false,
                Method     = "ToString",
                Parameters = new List <MethodParameter>()
                {
                    new MethodParameter()
                    {
                        Value    = "hi",
                        TypeName = typeof(string).FullName
                    }
                }
            };

            //---------------Assert Precondition----------------
            Assert.IsNotNull(client);
            //---------------Execute Test ----------------------
            var enumerable = methodInfo.Invoke("BuildValuedTypeParams", new object[] { args }) as IEnumerable <object>;

            //---------------Test Result -----------------------
            Assert.AreEqual(1, enumerable?.Count());
        }
Пример #29
0
        /// <summary>
        /// Initialize the GameScanner instance with a MemoryReader
        /// </summary>
        /// <param name="purgeCache">If true, pointer cache will not be used</param>
        public void Initialize(bool purgeCache)
        {
            Log.Debug($"GS Initialize - Start Initialize");

            //foreach (ThreadNr threadNr in Enum.GetValues(typeof(ThreadNr)))
            //{
            //    if (_trdPtr.ContainsKey(threadNr)) continue;

            //    if (threadNr == ThreadNr.NoThread) continue;

            //    _trdPtr.Add(threadNr, _reader.GetThreadStack((int)threadNr));

            //    Log.Verbose($"GS Initialize - Scanned Thread Stack {(int)threadNr}: {_trdPtr[threadNr].ToInt64():X}");
            //}

            if (!purgeCache && ReadBaseOffsetCache())
            {
                return;
            }

            var unscanned = new List <SigRecord>();

            foreach (SignatureType signatureType in Enum.GetValues(typeof(SignatureType)))
            {
                if (_sigPtr.ContainsKey(signatureType))
                {
                    continue;
                }

                if (!Signature.SignatureLib.TryGetValue(signatureType, out var pattern))
                {
                    continue;
                }
                unscanned.Add(pattern);
            }

            var result = Search(ref unscanned);

            Log.Warning($"GS Initialize - Unscanned Signature: {string.Join(", ", unscanned.Select(x => Enum.GetName(typeof(SignatureType), x.SelfType)))}");

            foreach (var kvp in result)
            {
                if (kvp.Value != IntPtr.Zero)
                {
                    _sigPtr.Add(kvp.Key, kvp.Value);
                }
            }

            if (!ValidateSignatures())
            {
                IpcClient.SendSignal(Signal.MilvanethNeedUpdate, new[] { "Memory", "ValidateSignatures" });
                throw new InvalidOperationException("Backbone service self validate failed");
            }

            WriteBaseOffsetCache();

            Log.Debug($"GS Initialize - Finish Initialize");
        }
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
            SimpleIoc.Default.Register <MainViewModel>();
            SimpleIoc.Default.Register <IClientOberver, ClientObserver>();
            var client = new IpcClient <string>(".", "test", ServiceLocator.Current.GetInstance <IClientOberver>());

            clientWorked = client.Create();
        }
Пример #31
0
        private static void SetupEnvironment(string[] args)
        {
#if DEBUG_PARAMTER
#warning DebugVal
            _parentPid = -1;                            // -p 1234
            _gamePid   = Helper.GetProcess()?.Id ?? -1; // -g 1234
            //_gamePid = -1;
            _dataBusId = -1;                            // -b 1234
            _venvId    = -1;                            // -v 1234
            _debugLog  = false;                         // --debug
            _logLines  = true;                          // --chatlog

            //_parentPid = 28340;
            //_gamePid = -1;
            //_logLines = false;
            //_debugLog = false;
            //_dataBusId = 2032234920;
            //_venvId = 614562325;
#else
            _parentPid = int.MinValue; // -p 1234, gui process id, -1 = don't watch
            _gamePid   = int.MinValue; // -g 1234, game process id, -1 = wait next
            _dataBusId = int.MinValue; // -b 1234, data bus id
            _venvId    = int.MinValue; // -v 1234, virtual env id, -1 = don't use
            _debugLog  = false;        // --debug, log debug information to file
            _logLines  = false;        // --chatlog, enable chatlog logging (enable debugLog to log to file)
            // don't consider recycle slave instance, just run another

            var p = new OptionSet()
                    .Add("p=", v => _parentPid     = int.Parse(v))
                    .Add("g=", v => _gamePid       = int.Parse(v))
                    .Add("b=", v => _dataBusId     = int.Parse(v))
                    .Add("v=", v => _venvId        = int.Parse(v))
                    .Add("debug", v => _debugLog   = true)
                    .Add("chatlog", v => _logLines = true);
            p.Parse(args);

            if (_parentPid == int.MinValue || _gamePid == int.MinValue || _dataBusId == int.MinValue || _venvId == int.MinValue)
            {
                Environment.Exit(0);
            }
#endif

            _currentPid = Process.GetCurrentProcess().Id;
            Logger.Initialize(_debugLog, _logLines);

            Log.Fatal(
                $"Process Start: Type Slave /" +
                $" ProcId {_currentPid} /" +
                $" ParId {_parentPid} /" +
                $" GameId {_gamePid} /" +
                $" BusId {_dataBusId} /" +
                $" Debug {_debugLog} /" +
                $" Chat {_logLines}");

            Helper.SetMilFileVenv(_venvId);
            IpcClient.EnsureBus(_dataBusId);
        }
Пример #32
0
        public void Setup()
        {
            var endpoint = new TestIpcEndpoint();

            _repositorySource = new Mock <IRepositorySource>();

            _client = new IpcClient(endpoint);
            _server = new IpcServer(endpoint, _repositorySource.Object);
        }
Пример #33
0
        public static async Task Main()
        {
            var config = JsonSerializer.Deserialize <Config>(await File.ReadAllTextAsync("./config.json"));

            Console.WriteLine("g");
            var discord = new DiscordWebhookClient(config !.WebhookId, config.WebhookToken);

            Console.WriteLine("r");
            var eventClient = new IpcClient(Environment.GetEnvironmentVariable("JAND_PIPE") ??
                                            JanD.Program.DefaultPipeName);
            var client = new IpcClient(Environment.GetEnvironmentVariable("JAND_PIPE") ??
                                       JanD.Program.DefaultPipeName);

            Console.WriteLine("b");
            Console.WriteLine(eventClient.RequestString("subscribe-events", "255"));
            Console.WriteLine("h");
            eventClient.ListenEvents(ev =>
            {
                Console.WriteLine(ev.Event);
                JanD.Program.JanDRuntimeProcess info;
                try
                {
                    info = client.RequestJson <JanD.Program.JanDRuntimeProcess>("get-process-info", ev.Process);
                }
                catch
                {
                    info = null;
                }

#pragma warning disable 4014
                discord.SendMessageAsync(embeds: new List <DiscordEmbed>
#pragma warning restore 4014
                {
                    new()
                    {
                        Title = ev !.Event switch
                        {
                            "procstart" => "Process Started",
                            "procdel" => "Process Deleted",
                            "procadd" => "Process Added",
                            "procstop" => "Process Stopped",
                            "procren" => "Process Renamed",
                            "procprop" => "Process Property Updated",
                            _ => ev.Event
                        },
                        Description = ev.Event switch
                        {
                            "procstart" => $"`{ev.Process}` has started.",
                            "procdel" => $"`{ev.Process}` has been deleted.",
                            "procadd" => @$ "`{ev.Process}` has been added.
        **Command:** `{info.Command}`
        **Directory:** `{info.WorkingDirectory}`",
                            "procstop" => @$ "`{ev.Process}` has stopped.
        **Exit Code:** `{info.ExitCode}`",
                            "procren" => $@"`{ev.Process}` => `{ev.Value}`",
                            "procprop" => $@"`{ev.Process}`
Property `{ev.Value[..ev.Value.IndexOf(':')]}` changed to `{ev.Value[(ev.Value.IndexOf(':') + 1)..]}`",
Пример #34
0
        private static void ServiceDiscovererOnOnServiceFound(IPAddress ipAddress)
        {
            _serviceDiscoverer.OnServiceFound -= ServiceDiscovererOnOnServiceFound;

            var client = new IpcClient<ICalculator>(ipAddress, 62005, new JsonDotNetSerializer());

            UserInputLoop(client);

            client.Dispose();
            Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
        }
Пример #35
0
        public static void Main(string[] args)
        {
            var ipAddress = IPAddress.Loopback;

            if (args.Length == 1)
            {
                ipAddress = IPAddress.Parse(args[0]);
            }

            var client = new IpcClient<IFileTransfer>(ipAddress, 63000, new JsonDotNetSerializer());
            client.BulkProgress += OnBulkProgress;
           
            var line = string.Empty;

            Console.WriteLine(@"Enter filename 'c:\images\photo.bmp' or 'quit'..");
            while ((line = Console.ReadLine()) != "quit")
            {
                try
                {
                    var sw = new Stopwatch();
                    sw.Start();
           
                    using (var memoryStream = client.Proxy.TransferFile(line))
                    {
                        sw.Stop();
                        var newName = line + ".cpy";
                        using (var fs = File.Create(newName))
                        {
                            memoryStream.Position = 0;
                            memoryStream.CopyTo(fs);
                            memoryStream.Flush();
                            fs.Close();
                        }

                        int megaByte = memoryStream.Capacity / 1024 / 1024;
                        double megaBytePerSec = megaByte / sw.Elapsed.TotalSeconds;
                        Console.WriteLine("Successfully wrote file '{0} @ {1:.0} MB/s.", newName, megaBytePerSec);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            client.BulkProgress -= OnBulkProgress;
            client.Dispose();

            Environment.Exit(0);
        }
Пример #36
0
        public void VerifyPerformance()
        {
            var fooStub = new FooStub();
            fooStub.ReturnValueOfBar = "Bar";

            var dispatcherThread = new DispatcherThread(Dispatcher.Run);
            dispatcherThread.Start();

            var ipcServer = new IpcServer<IFoo>(fooStub, dispatcherThread.Dispatcher, IPAddress.Loopback, 62000, new JsonDotNetSerializer());
            ipcServer.Listen();

            var ipcClient = new IpcClient<IFoo>(IPAddress.Loopback, 62000, new JsonDotNetSerializer());

            var numberOfCalls = 1000;
            var nanoSecs = Performance.MeasureMs(() =>
            {
                for (var i = 0; i < numberOfCalls; i++)
                {
                    ipcClient.Proxy.Foo();
                }
            });

            var fooAverageMs = nanoSecs/numberOfCalls;
            Console.WriteLine("Foo call took: {0}ms", fooAverageMs);

            Assert.AreEqual(numberOfCalls, fooStub.NumberOfFooCalls);
            Assert.LessOrEqual(TimeSpan.FromMilliseconds(fooAverageMs), TimeSpan.FromMilliseconds(10));

            nanoSecs = Performance.MeasureMs(() =>
            {
                for (var i = 0; i < numberOfCalls; i++)
                {
                    ipcClient.Proxy.Bar();
                }
            });

            var barAverageMs = nanoSecs/numberOfCalls;
            Console.WriteLine("Bar call took: {0}ms", barAverageMs);

            Assert.AreEqual(numberOfCalls, fooStub.NumberOfBarCalls);
            Assert.LessOrEqual(TimeSpan.FromMilliseconds(barAverageMs), TimeSpan.FromMilliseconds(10));

            ipcClient.Dispose();
            ipcServer.Dispose();

            dispatcherThread.Shutdown();
        }
Пример #37
0
        public void VerifyServerExceptionsAreForwardedToClientAndServerRemainsAlive()
        {
            var fooStub = new FooStubThrowsException();

            var dispatcherThread = new DispatcherThread(Dispatcher.Run);
            dispatcherThread.Start();

            var ipcServer = new IpcServer<IFoo>(fooStub, dispatcherThread.Dispatcher, IPAddress.Loopback, 62000, new JsonDotNetSerializer());
            ipcServer.Listen();

            var ipcClient = new IpcClient<IFoo>(IPAddress.Loopback, 62000, new JsonDotNetSerializer());

            var caughtException = false;
            try
            {
                ipcClient.Proxy.Foo();
            }
            catch (Exception)
            {
                caughtException = true;
            }

            Assert.IsTrue(caughtException);

            //See if server survives failed method call
            ipcClient.Proxy.Bar();
            Assert.IsTrue(fooStub.NumberOfBarCalls == 1);

            ipcClient.Dispose();
            ipcServer.Dispose();

            dispatcherThread.Shutdown();
        }
Пример #38
0
        public void VerifyBulkyData_using_Json_dot_NET_serializer(int mb)
        {
            int numberKiloBytes = 1024 * 1024 * mb;
            var buffer = new byte[numberKiloBytes];
            for (int i = 0; i < numberKiloBytes; ++i)
            {
                buffer[i] = (byte)(i % 2);
            }

            var bulkDataStub = new BulkDataStub(buffer);
            var bulkDataHash = ComputeHash(bulkDataStub.GetBulkyData());

            var dispatcherThread = new DispatcherThread(Dispatcher.Run);
            dispatcherThread.Start();

            var ipcServer = new IpcServer<IBulkData>(bulkDataStub, dispatcherThread.Dispatcher, IPAddress.Loopback, 62000, new JsonDotNetSerializer());
            ipcServer.Listen();

            var ipcClient = new IpcClient<IBulkData>(IPAddress.Loopback, 62000, new JsonDotNetSerializer());

            Stream receivingStream = null;
            double ms = Performance.MeasureMs(() =>
            {
                receivingStream = ipcClient.Proxy.GetBulkyData();
            });

            var receivingHash = ComputeHash(receivingStream);
            Assert.That(receivingHash, Is.EqualTo(bulkDataHash));

            Console.WriteLine("Sending of {0}MB took {1}ms", mb, ms);

            ipcClient.Dispose();
            ipcServer.Dispose();

            bulkDataStub.Dispose();
            receivingStream.Dispose();

            dispatcherThread.Shutdown();
        }
Пример #39
0
        public void VerifyCanPerformFunctionCallAfterBulk()
        {
            int numberKiloBytes = 1024 * 1024 * 1;
            var buffer = new byte[numberKiloBytes];
            for (int i = 0; i < numberKiloBytes; ++i)
            {
                buffer[i] = (byte)(i % 2);
            }

            var bulkDataStub = new BulkDataStub(buffer);

            var dispatcherThread = new DispatcherThread(Dispatcher.Run);
            dispatcherThread.Start();

            var ipcServer = new IpcServer<IBulkData>(bulkDataStub, dispatcherThread.Dispatcher, IPAddress.Loopback, 62000, new MsDataContractJsonSerializer());
            ipcServer.Listen();

            var ipcClient = new IpcClient<IBulkData>(IPAddress.Loopback, 62000, new MsDataContractJsonSerializer());

            ipcClient.Proxy.GetBulkyData();

            var fooResult = ipcClient.Proxy.Foo();
            Assert.AreEqual("Bar", fooResult);

            ipcClient.Dispose();
            ipcServer.Dispose();

            bulkDataStub.Dispose();

            dispatcherThread.Shutdown();
        }