public IList<TestFileSummary> Read(ProcessStream processStream, TestOptions testOptions, TestContext testContext, ITestMethodRunnerCallback callback, bool debugEnabled) { if (processStream == null) throw new ArgumentNullException("processStream"); if (testOptions == null) throw new ArgumentNullException("testOptions"); if (testContext == null) throw new ArgumentNullException("testContext"); lastTestEvent = DateTime.Now; var timeout = (testContext.TestFileSettings.TestFileTimeout ?? testOptions.TestFileTimeoutMilliseconds) + 500; // Add buffer to timeout to account for serialization var readerTask = Task<IList<TestFileSummary>>.Factory.StartNew(() => ReadFromStream(processStream.StreamReader, testContext, testOptions, callback, debugEnabled)); while (readerTask.Status == TaskStatus.WaitingToRun || (readerTask.Status == TaskStatus.Running && (DateTime.Now - lastTestEvent).TotalMilliseconds < timeout)) { Thread.Sleep(100); } if (readerTask.IsCompleted) { ChutzpahTracer.TraceInformation("Finished reading stream from test file '{0}'", testContext.FirstInputTestFile); return readerTask.Result; } else { // We timed out so kill the process and return an empty test file summary ChutzpahTracer.TraceError("Test file '{0}' timed out after running for {1} milliseconds", testContext.FirstInputTestFile, (DateTime.Now - lastTestEvent).TotalMilliseconds); processStream.TimedOut = true; processStream.KillProcess(); return testContext.ReferencedFiles.Where(x => x.IsFileUnderTest).Select(file => new TestFileSummary(file.Path)).ToList(); } }
public static ProcessStream GetProcessFromHandle(IntPtr handle) { ProcessStream pcsStream = new ProcessStream(); pcsStream.ProcessHandle = handle; pcsStream.IsOpened = true; return pcsStream; }
public ExecutionResult(Process proc) { ProcessStream ps = new ProcessStream(); ps.Read(ref proc, 30); StandardOutput = ps.StandardOutput; StandardError = ps.StandardError; ExitCode = proc.ExitCode; }
public ProcessScanner(Process process) { if (process == null) throw new ArgumentNullException(); Process = process; Memory = new ProcessStream(process.Handle); }
public void Will_throw_argument_null_exception_if_context_is_null() { var reader = new TestableTestCaseStreamReader(); var processStream = new ProcessStream(new Mock <IProcessWrapper>().Object, new StreamReader(new MemoryStream())); var model = Record.Exception(() => reader.ClassUnderTest.Read(processStream, new TestOptions(), null, null, true)) as ArgumentNullException; Assert.NotNull(model); }
public static string Evaluate(this WatchExpression watchExp, ProcessStream stream) { if (watchExp.Error != null) { return(watchExp.Error); } return(""); }
public IList <TestFileSummary> Read(ProcessStream processStream, TestOptions testOptions, TestContext testContext, ITestMethodRunnerCallback callback, bool debugEnabled) { if (processStream == null) { throw new ArgumentNullException("processStream"); } if (testOptions == null) { throw new ArgumentNullException("testOptions"); } if (testContext == null) { throw new ArgumentNullException("testContext"); } lastTestEvent = DateTime.Now; var timeout = (testContext.TestFileSettings.TestFileTimeout ?? testOptions.TestFileTimeoutMilliseconds) + 500; // Add buffer to timeout to account for serialization var codeCoverageEnabled = (!testContext.TestFileSettings.EnableCodeCoverage.HasValue && testOptions.CoverageOptions.Enabled) || (testContext.TestFileSettings.EnableCodeCoverage.HasValue && testContext.TestFileSettings.EnableCodeCoverage.Value); var streamingTestFileContexts = testContext.ReferencedFiles .Where(x => x.IsFileUnderTest) .Select(x => new StreamingTestFileContext(x, testContext, codeCoverageEnabled)) .ToList(); var deferredEvents = new List <Action <StreamingTestFileContext> >(); var readerTask = Task <IList <TestFileSummary> > .Factory.StartNew(() => ReadFromStream(processStream.StreamReader, testContext, testOptions, streamingTestFileContexts, deferredEvents, callback, debugEnabled)); while (readerTask.Status == TaskStatus.WaitingToRun || (readerTask.Status == TaskStatus.Running && (DateTime.Now - lastTestEvent).TotalMilliseconds < timeout)) { Thread.Sleep(100); } if (readerTask.IsCompleted) { ChutzpahTracer.TraceInformation("Finished reading stream from test file '{0}'", testContext.FirstInputTestFile); return(readerTask.Result); } else { // Since we times out make sure we play the deferred events so we do not lose errors // We will just attach these events to the first test context at this point since we do // not know where they belong PlayDeferredEvents(streamingTestFileContexts.FirstOrDefault(), deferredEvents); // We timed out so kill the process and return an empty test file summary ChutzpahTracer.TraceError("Test file '{0}' timed out after running for {1} milliseconds", testContext.FirstInputTestFile, (DateTime.Now - lastTestEvent).TotalMilliseconds); processStream.TimedOut = true; processStream.KillProcess(); return(testContext.ReferencedFiles.Where(x => x.IsFileUnderTest).Select(file => new TestFileSummary(file.Path)).ToList()); } }
public void InitializeVariableLabels(ProcessStream stream) { this.labelMassFlowRate.InitializeVariable(stream.MassFlowRate); this.labelVolumeFlowRate.InitializeVariable(stream.VolumeFlowRate); this.labelPressure.InitializeVariable(stream.Pressure); this.labelTemperature.InitializeVariable(stream.Temperature); this.labelEnthalpy.InitializeVariable(stream.SpecificEnthalpy); this.labelSpecificHeat.InitializeVariable(stream.SpecificHeat); this.labelDensity.InitializeVariable(stream.Density); }
public static bool SetBytes(this WatchVariable watchVar, ProcessStream stream, uint offset, byte[] dataBytes) { if (dataBytes == null) { return(false); } return(stream.WriteRam(dataBytes, watchVar.OtherOffset ? offset + watchVar.Address : watchVar.Address, watchVar.AbsoluteAddressing)); }
public HttpStatusCode Post( string requestUri, string postData, ProcessStream responseStreamProcessor) { return(Post( requestUri, new ProcessStream(new DefaultRequestStreamProcessor(postData).Process), responseStreamProcessor)); }
private ProcessBinaryWriter(IntPtr baseAddress, Stream inputStream) : base(inputStream) { this.baseStream = (ProcessStream)this.BaseStream; this.baseAddress = (ulong)unchecked (baseAddress.ToInt64()); this.processDiagnostics = new ProcessDiagnosticsWrapper(); this.baseStream.ProcessDiagnostics = processDiagnostics; this.regions = new Dictionary <ulong, ProcessBinaryReader>(); }
public ProcessStreamControl(Flowsheet flowsheet, Point location, ProcessStream processStream) : base(flowsheet, location, processStream) { InitializeComponent(); this.Size = new System.Drawing.Size(UI.STREAM_CTRL_W, UI.STREAM_CTRL_H); UI.SetStatusColor(this, this.ProcessStream.SolveState); this.Orientation = StreamOrientation.Right; this.UpdateBackImage(); this.flowsheet.ConnectionManager.UpdateConnections(this); }
public override void WriteLine(ProcessRunner runner, string data, ProcessStream stream) { lock (this) { base.WriteLine(runner, data, stream); if (stream == ProcessStream.StandardOut) { _lastCommandOutput.AppendLine(data); } } }
/// <summary> /// Executes a command-line program, specifying a maximum time to wait /// for it to complete. /// </summary> /// <param name="command"> /// The path to the program executable. /// </param> /// <param name="args"> /// The command-line arguments for the program. /// </param> /// <param name="timeout"> /// The maximum time to wait for the subprocess to complete, in milliseconds. /// </param> /// <returns> /// A <see cref="SubprocessResult"/> containing the results of /// running the program. /// </returns> public static SubprocessResult RunProgram(CommandArgs objCommandArgs) { bool timedOut = false; ProcessStartInfo pinfo = new ProcessStartInfo(objCommandArgs.command); pinfo.Arguments = objCommandArgs.Args; pinfo.UseShellExecute = false; pinfo.CreateNoWindow = true; //pinfo.WorkingDirectory = ? pinfo.RedirectStandardOutput = true; pinfo.RedirectStandardError = true; Process subprocess = Process.Start(pinfo); ProcessStream processStream = new ProcessStream(); try { processStream.Read(subprocess); subprocess.WaitForExit(objCommandArgs.TimeOut); processStream.Stop(); if (!subprocess.HasExited) { // OK, we waited until the timeout but it still didn't exit; just kill the process now timedOut = true; try { subprocess.Kill(); processStream.Stop(); } catch { } subprocess.WaitForExit(); } } catch (Exception ex) { subprocess.Kill(); processStream.Stop(); throw ex; } finally { processStream.Stop(); } TimeSpan duration = subprocess.ExitTime - subprocess.StartTime; float executionTime = (float)duration.TotalSeconds; SubprocessResult result = new SubprocessResult( executionTime, processStream.StandardOutput.Trim(), processStream.StandardError.Trim(), subprocess.ExitCode, timedOut); return result; }
public void Will_fire_file_started_event() { var reader = new TestableTestCaseStreamReader(); var json = JsonStreamEvents.FileStartEventJson + JsonStreamEvents.TestStartEventJson; var context = reader.BuildContext("file"); var stream = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(json))); var processStream = new ProcessStream(new Mock <IProcessWrapper>().Object, stream); var callback = new Mock <ITestMethodRunnerCallback>(); reader.ClassUnderTest.Read(processStream, new TestOptions(), context, callback.Object, false); callback.Verify(x => x.FileStarted("file")); }
public HackManager(ProcessStream stream, List <RomHack> hacks, CheckedListBox checkList) { _checkList = checkList; _hacks = hacks; _stream = stream; foreach (var hack in _hacks) { _checkList.Items.Add(hack); } _checkList.ItemCheck += _checkList_ItemCheck; }
public virtual void WriteLine(ProcessRunner runner, string data, ProcessStream stream) { lock (this) { StringBuilder lineBuffer = AppendToLineBuffer(runner, stream, data); //Ensure all output is written even if it isn't a full line before we log input if (stream == ProcessStream.StandardIn) { FlushOutput(); } _output.WriteLine(lineBuffer.ToString()); _lineBuffers[(int)stream] = null; } }
private void InjectDll(uint processId, string dllPath) { var targetProcessHandle = Kernel32.OpenProcess(ProcessAccessFlags.All, false, processId); var loadLibraryExportAddress = Kernel32.GetProcAddress(Kernel32.GetModuleHandle("kernel32.dll"), "LoadLibraryA"); var dllMemoryAddress = Kernel32.VirtualAllocEx(targetProcessHandle, UIntPtr.Zero, (uint)dllPath.Length, MemoryAllocationType.Reserve | MemoryAllocationType.Commit, MemoryProtect.ReadWrite); using (ProcessStream ps = new ProcessStream(targetProcessHandle)) { ps.Write((uint)dllMemoryAddress.ToUInt64(), Encoding.Default.GetBytes(dllPath)); } Kernel32.CreateRemoteThread(targetProcessHandle, loadLibraryExportAddress, dllMemoryAddress); }
public WatchVariableControl(ProcessStream stream, WatchVariable watchVar, uint otherOffset = 0) { _specialName = watchVar.Name; _watchVar = watchVar; _stream = stream; OtherOffset = otherOffset; CreateControls(); if (watchVar.BackroundColor.HasValue) { Color = watchVar.BackroundColor.Value; } }
public override void Write(ProcessRunner runner, string data, ProcessStream stream) { lock (this) { base.Write(runner, data, stream); if (stream == ProcessStream.StandardOut) { _lastCommandOutput.Append(data); string lastCommandOutput = _lastCommandOutput.ToString(); bool commandError = false; bool commandEnd = false; switch (_debugger) { case NativeDebugger.Cdb: // Some commands like DumpStack have ===> or -> in the output that looks // like the cdb prompt. Using a regex here to better match the cdb prompt // is way to slow. if (lastCommandOutput.EndsWith("=> ") || lastCommandOutput.EndsWith("-> ")) { return; } commandEnd = lastCommandOutput.EndsWith("> "); break; case NativeDebugger.Lldb: commandError = lastCommandOutput.EndsWith("<END_COMMAND_ERROR>"); commandEnd = commandError || lastCommandOutput.EndsWith("<END_COMMAND_OUTPUT>"); break; case NativeDebugger.Gdb: commandEnd = lastCommandOutput.EndsWith("(gdb) "); break; default: throw new Exception("Debugger prompt not supported"); } if (commandEnd) { FlushOutput(); _taskSource.TrySetResult(new CommandResult(lastCommandOutput, !commandError)); _lastCommandOutput.Clear(); AddTask(); } } } }
public static byte[] GetByteData(this WatchVariable watchVar, ProcessStream stream, uint offset) { // Get dataBytes var byteCount = WatchVariable.TypeSize[watchVar.Type]; var dataBytes = stream.ReadRam(watchVar.OtherOffset ? offset + watchVar.Address : watchVar.Address, byteCount, watchVar.AbsoluteAddressing); // Make sure offset is a valid pointer if (watchVar.OtherOffset && offset == 0) { return(null); } return(dataBytes); }
public void Will_fire_file_started_event() { var reader = new TestableTestCaseStreamReader(); var json = @"#_#FileStart#_# {""type"": ""FileStart"", ""timetaken"":88}"; var context = new TestContext { InputTestFile = "file" }; var stream = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(json))); var processStream = new ProcessStream(new Mock <IProcessWrapper>().Object, stream); var callback = new Mock <ITestMethodRunnerCallback>(); reader.ClassUnderTest.Read(processStream, new TestOptions(), context, callback.Object, false); callback.Verify(x => x.FileStarted("file")); }
public void ClearPayload(ProcessStream stream) { bool success = true; stream.Suspend(); foreach (var address in _originalMemory) { // Read original memory before replacing success &= stream.WriteRam(address.Item2, address.Item1, false, false); } stream.Resume(); Enabled = !success; }
public MapManager(ProcessStream stream, MapAssociations mapAssoc, ObjectAssociations objAssoc, MapGui mapGui) { _stream = stream; MapAssoc = mapAssoc; _mapGui = mapGui; _marioMapObj = new MapObject(objAssoc.MarioMapImage, 1); _marioMapObj.UsesRotation = true; _holpMapObj = new MapObject(objAssoc.HolpImage, 2); _cameraMapObj = new MapObject(objAssoc.CameraMapImage, 1); _cameraMapObj.UsesRotation = true; _floorTriangleMapObj = new TriangleMapObject(Color.FromArgb(200, Color.Yellow), 3); }
public void Will_supress_internal_log_event() { var reader = new TestableTestCaseStreamReader(); var json = JsonStreamEvents.FileStartEventJson + JsonStreamEvents.TestStartEventJson + string.Format(JsonStreamEvents.LogEventJsonTemplate, "!!_!! log"); var context = reader.BuildContext("file"); var stream = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(json))); var processStream = new ProcessStream(new Mock <IProcessWrapper>().Object, stream); var callback = new Mock <ITestMethodRunnerCallback>(); TestLog result = null; callback.Setup(x => x.FileLog(It.IsAny <TestLog>())).Callback <TestLog>(t => result = t); reader.ClassUnderTest.Read(processStream, new TestOptions(), context, callback.Object, false); Assert.Null(result); }
public ScriptManager(ProcessStream stream, ScriptParser parser, CheckBox useRomHackChecBox) { _stream = stream; _parser = parser; _useRomHackChecBox = useRomHackChecBox; _freeMemPtr = _parser.FreeMemoryArea; // Find spots to allocate script memory foreach (var script in _parser.Scripts) { script.ExecutionSpace = _freeMemPtr; _freeMemPtr += (uint)(script.Script.Length * sizeof(uint)); _freeMemPtr += (uint)(4 * sizeof(uint)); } }
public IList<TestFileSummary> Read(ProcessStream processStream, TestOptions testOptions, TestContext testContext, ITestMethodRunnerCallback callback, bool debugEnabled) { if (processStream == null) throw new ArgumentNullException("processStream"); if (testOptions == null) throw new ArgumentNullException("testOptions"); if (testContext == null) throw new ArgumentNullException("testContext"); lastTestEvent = DateTime.Now; var timeout = (testContext.TestFileSettings.TestFileTimeout ?? testOptions.TestFileTimeoutMilliseconds) + 500; // Add buffer to timeout to account for serialization var codeCoverageEnabled = (!testContext.TestFileSettings.EnableCodeCoverage.HasValue && testOptions.CoverageOptions.Enabled) || (testContext.TestFileSettings.EnableCodeCoverage.HasValue && testContext.TestFileSettings.EnableCodeCoverage.Value); var streamingTestFileContexts = testContext.ReferencedFiles .Where(x => x.IsFileUnderTest) .Select(x => new StreamingTestFileContext(x, testContext, codeCoverageEnabled)) .ToList(); var deferredEvents = new List<Action<StreamingTestFileContext>>(); var readerTask = Task<IList<TestFileSummary>>.Factory.StartNew(() => ReadFromStream(processStream.StreamReader, testContext, testOptions, streamingTestFileContexts, deferredEvents, callback, debugEnabled)); while (readerTask.Status == TaskStatus.WaitingToRun || (readerTask.Status == TaskStatus.Running && (DateTime.Now - lastTestEvent).TotalMilliseconds < timeout)) { Thread.Sleep(100); } if (readerTask.IsCompleted) { ChutzpahTracer.TraceInformation("Finished reading stream from test file '{0}'", testContext.FirstInputTestFile); return readerTask.Result; } else { // Since we times out make sure we play the deferred events so we do not lose errors // We will just attach these events to the first test context at this point since we do // not know where they belong PlayDeferredEvents(streamingTestFileContexts.FirstOrDefault(), deferredEvents); // We timed out so kill the process and return an empty test file summary ChutzpahTracer.TraceError("Test file '{0}' timed out after running for {1} milliseconds", testContext.FirstInputTestFile, (DateTime.Now - lastTestEvent).TotalMilliseconds); processStream.TimedOut = true; processStream.KillProcess(); return testContext.ReferencedFiles.Where(x => x.IsFileUnderTest).Select(file => new TestFileSummary(file.Path)).ToList(); } }
public void Will_fire_file_finished_event() { var reader = new TestableTestCaseStreamReader(); var json = JsonStreamEvents.FileStartEventJson + JsonStreamEvents.TestStartEventJson + JsonStreamEvents.TestDoneEventJson + JsonStreamEvents.FileDoneEventJson; var context = reader.BuildContext("file"); var stream = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(json))); var processStream = new ProcessStream(new Mock <IProcessWrapper>().Object, stream); var callback = new Mock <ITestMethodRunnerCallback>(); TestFileSummary result = null; callback.Setup(x => x.FileFinished("file", It.IsAny <TestFileSummary>())).Callback <string, TestFileSummary>((f, t) => result = t);; reader.ClassUnderTest.Read(processStream, new TestOptions(), context, callback.Object, false); Assert.NotNull(result); Assert.Equal(10, result.TimeTaken); }
public void Will_put_coverage_object_in_summary() { var reader = new TestableTestCaseStreamReader(); var json = JsonStreamEvents.FileStartEventJson + JsonStreamEvents.TestStartEventJson + JsonStreamEvents.CoverageEventJson; var context = reader.BuildContext("file"); var stream = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(json))); var processStream = new ProcessStream(new Mock <IProcessWrapper>().Object, stream); var callback = new Mock <ITestMethodRunnerCallback>(); reader.Mock <ICoverageEngine>().Setup(ce => ce.DeserializeCoverageObject(It.IsAny <string>(), context)). Returns(new CoverageData()); var summary = reader.ClassUnderTest.Read(processStream, new TestOptions(), context, callback.Object, false)[0]; Assert.NotNull(summary.CoverageObject); }
public override void WriteLine(ProcessRunner runner, string data, ProcessStream stream) { lock (this) { base.WriteLine(runner, data, stream); switch (stream) { case ProcessStream.StandardOut: _standardOutput.AppendLine(data); break; case ProcessStream.StandardError: _standardError.AppendLine(data); break; } } }
public static uint GetRamAddress(this WatchVariable watchVar, ProcessStream stream, uint offset = 0, bool addressArea = true) { uint offsetedAddress = offset + watchVar.Address; uint address; if (watchVar.AbsoluteAddressing) { address = LittleEndianessAddressing.AddressFix((uint)(offsetedAddress - stream.ProcessMemoryOffset), watchVar.GetByteCount()); } else { address = offsetedAddress; } return(addressArea ? address | 0x80000000 : address& 0x0FFFFFFF); }
public IEnumerable <string> Request( string requestUri, string method, ProcessStream requestStreamProcessor) { HttpWebRequest request = PrepareRequest(method, requestUri, requestStreamProcessor); using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse()) using (Stream sm = resp.GetResponseStream()) using (StreamReader sr = new StreamReader(sm, Encoding.Default)) { _statusCode = resp.StatusCode; _location = resp.Headers["Location"]; if (resp.ResponseUri.AbsoluteUri.StartsWith(BaseUri) == false) { BaseUri = resp.ResponseUri.Scheme + "://" + resp.ResponseUri.Host; } CookieCollection cc = request.CookieContainer.GetCookies(request.RequestUri); // This code fixes the case when a server sets a cookie without the 'path'. // IE takes this as the root ('/') value, // the HttpWebRequest class as the RequestUri.AbsolutePath value. // foreach (Cookie c in cc) { if (c.Path == request.RequestUri.AbsolutePath) { CookieContainer.Add(new Cookie(c.Name, c.Value, "/", c.Domain)); } } while (true) { string str = sr.ReadLine(); if (str == null) { break; } yield return(str); } } }
public HttpStatusCode Post( string requestUri, ProcessStream requestStreamProcessor, ProcessStream responseStreamProcessor) { Request(requestUri, "POST", requestStreamProcessor, responseStreamProcessor); for (int i = 0; i < 10; i++) { bool post = false; switch (StatusCode) { case HttpStatusCode.MultipleChoices: // 300 case HttpStatusCode.MovedPermanently: // 301 case HttpStatusCode.Found: // 302 case HttpStatusCode.SeeOther: // 303 break; case HttpStatusCode.TemporaryRedirect: // 307 post = true; break; default: return(StatusCode); } if (Location == null) { break; } Uri uri = new Uri(new Uri(PreviousUri), Location); BaseUri = uri.Scheme + "://" + uri.Host; requestUri = uri.AbsolutePath + uri.Query; Request( requestUri, post? "POST": "GET", post? requestStreamProcessor: null, responseStreamProcessor); } return(StatusCode); }
public void Will_put_logs_in_summary() { var reader = new TestableTestCaseStreamReader(); var json = JsonStreamEvents.FileStartEventJson + JsonStreamEvents.TestStartEventJson + string.Format(JsonStreamEvents.LogEventJsonTemplate, "hi") + string.Format(JsonStreamEvents.LogEventJsonTemplate, "bye"); var context = reader.BuildContext("file"); var stream = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(json))); var processStream = new ProcessStream(new Mock <IProcessWrapper>().Object, stream); var callback = new Mock <ITestMethodRunnerCallback>(); var summary = reader.ClassUnderTest.Read(processStream, new TestOptions(), context, callback.Object, false)[0]; Assert.Equal(2, summary.Logs.Count); Assert.Equal("file", summary.Logs[0].InputTestFile); Assert.Equal("hi", summary.Logs[0].Message); Assert.Equal("bye", summary.Logs[1].Message); }
public void Will_set_timed_out_after_test_file_timeout_and_kill_process() { var reader = new TestableTestCaseStreamReader(); var context = reader.BuildContext("file"); var stream = new WaitingStreamReader(new MemoryStream(Encoding.UTF8.GetBytes("")), 1000); var process = new Mock <IProcessWrapper>(); var processStream = new ProcessStream(process.Object, stream); var callback = new Mock <ITestMethodRunnerCallback>(); var summary = reader.ClassUnderTest.Read(processStream, new TestOptions { TestFileTimeoutMilliseconds = 200 }, context, callback.Object, false)[0]; Assert.NotNull(summary); Assert.True(processStream.TimedOut); process.Verify(x => x.Kill()); }
public void Will_supress_internal_log_event() { var reader = new TestableTestCaseStreamReader(); var json = @"#_#Log#_# {""type"":""Log"",""Log"":{""message"":""!!_!! hi""}}"; var context = new TestContext { InputTestFile = "file" }; var stream = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(json))); var processStream = new ProcessStream(new Mock <IProcessWrapper>().Object, stream); var callback = new Mock <ITestMethodRunnerCallback>(); TestLog result = null; callback.Setup(x => x.FileLog(It.IsAny <TestLog>())).Callback <TestLog>(t => result = t); reader.ClassUnderTest.Read(processStream, new TestOptions(), context, callback.Object, false); Assert.Null(result); }
/// <summary> /// Executes a command-line program, specifying a maximum time to wait /// for it to complete. /// </summary> /// <param name="command"> /// The path to the program executable. /// </param> /// <param name="workingDirectory"> /// The path of the working directory for the process executing the program executable. /// </param> /// <param name="args"> /// The command-line arguments for the program. /// </param> /// <param name="timeout"> /// The maximum time to wait for the subprocess to complete, in milliseconds. /// </param> /// <param name="input"> /// Input to be sent via standard input. /// </param> /// <returns> /// A <see cref="CommandLineProgramProcessResult"/> containing the results of /// running the program. /// </returns> public static CommandLineProgramProcessResult RunProgram( string command, string workingDirectory, string args, int timeout, string input, Encoding inputEncoding = null) { bool timedOut = false; ProcessStartInfo pinfo = new ProcessStartInfo(command); pinfo.Arguments = args; pinfo.UseShellExecute = false; pinfo.CreateNoWindow = true; pinfo.WorkingDirectory = workingDirectory; pinfo.RedirectStandardInput = true; pinfo.RedirectStandardOutput = true; pinfo.RedirectStandardError = true; Process process = Process.Start(pinfo); ProcessStream processStream = new ProcessStream(); StreamWriter inputStreamWriter; if (inputEncoding == null) { inputStreamWriter = process.StandardInput; } else { inputStreamWriter = new StreamWriter(process.StandardInput.BaseStream, inputEncoding); } Encoding standardInputEncoding = inputStreamWriter.Encoding; try { if (!String.IsNullOrEmpty(input)) inputStreamWriter.Write(input); inputStreamWriter.Close(); processStream.Read(process); process.WaitForExit(timeout); processStream.Stop(); if (!process.HasExited) { // OK, we waited until the timeout but it still didn't exit; just kill the process now timedOut = true; try { process.Kill(); processStream.Stop(); } catch { } process.WaitForExit(); } } catch (Exception ex) { process.Kill(); processStream.Stop(); throw ex; } finally { processStream.Stop(); } TimeSpan duration = process.ExitTime - process.StartTime; float executionTime = (float)duration.TotalSeconds; CommandLineProgramProcessResult result = new CommandLineProgramProcessResult( executionTime, processStream.StandardOutput.Trim(), processStream.StandardError.Trim(), process.ExitCode, timedOut, standardInputEncoding); return result; }
private static void GetCoordDetails( ProcessStream pc, int ptr, byte[] dets, out int coordPointer, out int coordSize ) { pc.Seek( ptr + dets[0], SeekOrigin.Begin ); coordPointer = Read( pc, dets[1] ); if ( dets[2] < 0xFF ) { pc.Seek( coordPointer, SeekOrigin.Begin ); coordPointer = Read( pc, dets[2] ); } if ( dets[3] < 0xFF ) { pc.Seek( ptr + dets[3], SeekOrigin.Begin ); coordPointer += Read( pc, dets[4] ); } coordSize = dets[5]; }
public static int Read(ProcessStream pc, int bytes) { byte[] buffer = new byte[bytes]; pc.Read(buffer, 0, bytes); switch (bytes) { case 1: return (int) (sbyte) buffer[0]; case 2: return (int) (short) ((int) buffer[0] | (int) buffer[1] << 8); case 4: return (int) buffer[0] | (int) buffer[1] << 8 | (int) buffer[2] << 16 | (int) buffer[3] << 24; default: int num1 = 0; int num2 = 0; for (int index = 0; index < buffer.Length; ++index) { num1 |= (int) buffer[index] << num2; num2 += 8; } return num1; } }
/// <summary> /// Initializes core components. /// </summary> private void Initialize(Process process) { // get process info Process = process; ProcessHandle = Kernel32.OpenProcess(ProcessAccessFlags.All, false, (uint)Process.Id); MainThreadId = User32.GetWindowThreadProcessId(Process.MainWindowHandle); MainThreadHandle = Kernel32.OpenThread(ThreadAccessFlags.All, false, MainThreadId); ModuleContext = new ModuleAddressContext(ImageBaseAddress, ProcessBaseAddress, (uint)Process.MainModule.ModuleMemorySize); // look away! - get original image base address and build time from PE header - http://blogs.msdn.com/b/kstanton/archive/2004/03/31/105060.aspx using (FileStream fs = new FileStream(Process.MainModule.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (BinaryReader br = new BinaryReader(fs)) { fs.Position = Marshal.OffsetOf(typeof(ImageDosHeader), nameof(ImageDosHeader.e_lfanew)).ToInt32(); int ntHeaderOffset = br.ReadInt32(); int fileHeaderOffset = Marshal.OffsetOf(typeof(ImageNtHeaders32), nameof(ImageNtHeaders32.FileHeader)).ToInt32(); fs.Position = ntHeaderOffset + fileHeaderOffset + Marshal.OffsetOf(typeof(ImageFileHeader32), nameof(ImageFileHeader32.TimeDateStamp)).ToInt32(); Version = (GameVersion)br.ReadUInt32(); int fileHeaderSize = Marshal.SizeOf(typeof(ImageFileHeader32)); int imageBaseOffset = Marshal.OffsetOf(typeof(ImageOptionalHeader32), nameof(ImageOptionalHeader32.ImageBase)).ToInt32(); fs.Position = ntHeaderOffset + fileHeaderOffset + fileHeaderSize + imageBaseOffset; ImageBaseAddress = br.ReadUInt32(); } // initialize access to various sub-systems Memory = new ProcessStream(ProcessHandle); TlsAddress = GetTlsAddress(MainThreadHandle); TagCache = new TagCache(this); Addresses = new GameAddresses(this); }
private void PathOrLaunch(bool bPatch, ConfigArgs caTouse) { if (caTouse == null) return; int iResultEncLogin = 0; int iResultEncLoginId = 0; // ---------------------- int iResultEncGame = 0; // ---------------------- List<int> iResultIP = new List<int>(); int iResultIPId = 0; // ---------------------- ENCRYPTION_PATCH_TYPE encType = caTouse.encType; // !bPatch Process prcTostart = null; // bPatch FileStream fsToPatch = null; if (!bPatch) { prcTostart = new Process(); prcTostart.StartInfo.FileName = this.txtUokrPath.Text + @"\" + StaticData.UOKR_CLIENT; prcTostart.StartInfo.WorkingDirectory = this.txtUokrPath.Text; if (!prcTostart.Start()) { MessageBox.Show("Cannot start the client !", Application.ProductName + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } else { try { File.Copy(this.txtUokrPath.Text + @"\" + StaticData.UOKR_CLIENT, this.txtUokrPath.Text + @"\" + StaticData.UOKR_PATCHCLIENT, true); } catch (Exception) { MessageBox.Show("Cannot create file " + this.txtUokrPath.Text + @"\" + StaticData.UOKR_PATCHCLIENT + " !", Application.ProductName + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { fsToPatch = File.Open(this.txtUokrPath.Text + @"\" + StaticData.UOKR_PATCHCLIENT, FileMode.Open, FileAccess.ReadWrite); } catch (Exception) { MessageBox.Show("Cannot open file " + this.txtUokrPath.Text + @"\" + StaticData.UOKR_PATCHCLIENT + " !", Application.ProductName + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } Stream strGeneric; if (bPatch) { strGeneric = fsToPatch; } else { strGeneric = new ProcessStream((IntPtr)prcTostart.Id); } for (iResultIPId = 0; iResultIPId < StaticData.UOKR_IPDATA_VERSION; iResultIPId++) { List<byte[]> listBytes = StaticData.GetIPData(iResultIPId); foreach (byte[] bIpData in listBytes) { iResultIP.Add(Utility.Search(strGeneric, bIpData, bPatch)); } if (ListValidValues(iResultIP)) { break; } else { iResultIP.Clear(); } } if (!ListValidValues(iResultIP)) { strGeneric.Close(); if (!bPatch) prcTostart.Kill(); MessageBox.Show("Cannot patch IP on the client !", Application.ProductName + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((encType == ENCRYPTION_PATCH_TYPE.Login) || (encType == ENCRYPTION_PATCH_TYPE.Both)) { for (iResultEncLoginId = 0; iResultEncLoginId < StaticData.UOKR_LOGDATA_VERSION; iResultEncLoginId++) { iResultEncLogin = Utility.Search(strGeneric, StaticData.GetLoginData(iResultEncLoginId), bPatch); if (iResultEncLogin != 0) break; } if (iResultEncLogin == 0) { strGeneric.Close(); if (!bPatch) prcTostart.Kill(); MessageBox.Show("Cannot patch Login Encryption on the client !", Application.ProductName + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } if ((encType == ENCRYPTION_PATCH_TYPE.Game) || (encType == ENCRYPTION_PATCH_TYPE.Both)) { iResultEncGame = Utility.Search(strGeneric, StaticData.UOKR_ENCDATA, bPatch); if (iResultEncGame == 0) { strGeneric.Close(); if (!bPatch) prcTostart.Kill(); MessageBox.Show("Cannot patch Game Encryption on the client !", Application.ProductName + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } if (bPatch) { strGeneric.Seek(0, SeekOrigin.Begin); } List<byte[]> newDataIp = StaticData.GetPatchedIPData(iResultIPId, caTouse.ipHost, caTouse.uPort); for(int i = 0; i < newDataIp.Count; i++) { strGeneric.Seek(iResultIP[i], SeekOrigin.Begin); strGeneric.Write(newDataIp[i], 0, newDataIp[i].Length); } if ((encType == ENCRYPTION_PATCH_TYPE.Login) || (encType == ENCRYPTION_PATCH_TYPE.Both)) { byte[] encLoginToPatch = StaticData.GetPatchedLoginData(iResultEncLoginId); strGeneric.Seek(iResultEncLogin, SeekOrigin.Begin); strGeneric.Write(encLoginToPatch, 0, encLoginToPatch.Length); } if ((encType == ENCRYPTION_PATCH_TYPE.Game) || (encType == ENCRYPTION_PATCH_TYPE.Both)) { strGeneric.Seek(iResultEncGame, SeekOrigin.Begin); strGeneric.Write(StaticData.UOKR_ENCPATCHDATA, 0, StaticData.UOKR_ENCPATCHDATA.Length); } strGeneric.Close(); if (!bPatch) { System.Threading.Thread.Sleep(10); Close(); } else { this.ckbRemind.Checked = false; MessageBox.Show("Client " + this.txtUokrPath.Text + @"\" + StaticData.UOKR_PATCHCLIENT + " succesfully patched.", "Patch Done", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
private static void GetCoordDetails(ProcessStream pc, int ptr, byte[] dets, out int coordPointer, out int coordSize) { pc.Seek(ptr + dets[0], SeekOrigin.Begin); coordPointer = Read(pc, dets[1]); if (dets[2] < 0xFF) { pc.Seek(coordPointer, SeekOrigin.Begin); coordPointer = Read(pc, dets[2]); } if (dets[3] < 0xFF) { pc.Seek(ptr + dets[3], SeekOrigin.Begin); coordPointer += Read(pc, dets[4]); } /* * arul: * The variable 'dets[6]' represents an offset into the struct that holds an info about players current location. * Added not to break functionality with the older clients (I hope). * * The struct looks as follows: * * DWORD fLoggedIn; * DWORD Z; * DWORD Y; * DWORD X; * DWORD Facet; * */ if (dets.Length == 7 && dets[6] < 0xFF) { coordPointer += dets[6]; } coordSize = dets[5]; }
public static int Search(ProcessStream pc, byte[] mask, byte[] vals) { if (mask.Length != vals.Length) throw new Exception(); int count = 4096 + mask.Length; pc.BeginAccess(); byte[] buffer = new byte[count]; int num = 0; while (true) { pc.Seek((long) (4194304 + num * 4096), SeekOrigin.Begin); if (pc.Read(buffer, 0, count) == count) { for (int index1 = 0; index1 < 4096; ++index1) { bool flag = true; for (int index2 = 0; flag && index2 < mask.Length; ++index2) flag = ((int) buffer[index1 + index2] & (int) mask[index2]) == (int) vals[index2]; if (flag) { pc.EndAccess(); return 4194304 + num * 4096 + index1; } } ++num; } else break; } pc.EndAccess(); return 0; }
public static int Search(ProcessStream pc, byte[] mask, byte[] vals) { if (mask.Length != vals.Length) { throw new Exception(); } const int chunkSize = 4096; int readSize = chunkSize + mask.Length; pc.BeginAccess(); var read = new byte[readSize]; for (int i = 0;; ++i) { pc.Seek(0x400000 + (i * chunkSize), SeekOrigin.Begin); int count = pc.Read(read, 0, readSize); if (count != readSize) { break; } for (int j = 0; j < chunkSize; ++j) { bool ok = true; for (int k = 0; ok && k < mask.Length; ++k) { ok = ((read[j + k] & mask[k]) == vals[k]); } if (ok) { pc.EndAccess(); return 0x400000 + (i * chunkSize) + j; } } } pc.EndAccess(); return 0; }
public static int Search(ProcessStream pc, byte[] buffer) { const int chunkSize = 4096; int readSize = chunkSize + buffer.Length; pc.BeginAccess(); var read = new byte[readSize]; for (int i = 0;; ++i) { pc.Seek(0x400000 + (i * chunkSize), SeekOrigin.Begin); int count = pc.Read(read, 0, readSize); if (count != readSize) { break; } for (int j = 0; j < chunkSize; ++j) { bool ok = true; for (int k = 0; ok && k < buffer.Length; ++k) { ok = (buffer[k] == read[j + k]); } if (ok) { pc.EndAccess(); return 0x400000 + (i * chunkSize) + j; } } } pc.EndAccess(); return 0; }
public static int Read(ProcessStream pc, int bytes) { var buffer = new byte[bytes]; pc.Read(buffer, 0, bytes); switch (bytes) { case 1: return (sbyte)buffer[0]; case 2: return (short)(buffer[0] | (buffer[1] << 8)); case 4: return (buffer[0] | (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24)); } int val = 0; int bits = 0; for (int i = 0; i < buffer.Length; ++i) { val |= buffer[i] << bits; bits += 8; } return val; }
static Stream StreamBuilder(Connection conn) { switch(conn.Type) { case "TCP": if (conn.Client) { return new TCPStream(conn.IP, conn.Port); } else { return new TCPStream(conn.Port); } case "EXEC": var stream = new ProcessStream(conn.Executable, ""); stream.Start(); return stream; default: return new StreamCombiner(Console.OpenStandardInput(), Console.OpenStandardOutput()); } }
private static void GetCoordDetails(ProcessStream pc, int ptr, byte[] dets, out int coordPointer, out int coordSize) { pc.Seek((long) (ptr + (int) dets[0]), SeekOrigin.Begin); coordPointer = Client.Read(pc, (int) dets[1]); if ((int) dets[2] < (int) byte.MaxValue) { pc.Seek((long) coordPointer, SeekOrigin.Begin); coordPointer = Client.Read(pc, (int) dets[2]); } if ((int) dets[3] < (int) byte.MaxValue) { pc.Seek((long) (ptr + (int) dets[3]), SeekOrigin.Begin); coordPointer += Client.Read(pc, (int) dets[4]); } coordSize = (int) dets[5]; }
private void InjectDll(uint processId, string dllPath) { var targetProcessHandle = Kernel32.OpenProcess(ProcessAccessFlags.All, false, processId); var loadLibraryExportAddress = Kernel32.GetProcAddress(Kernel32.GetModuleHandle("kernel32.dll"), "LoadLibraryA"); var dllMemoryAddress = Kernel32.VirtualAllocEx(targetProcessHandle, UIntPtr.Zero, (uint) dllPath.Length, MemoryAllocationType.Reserve | MemoryAllocationType.Commit, MemoryProtect.ReadWrite); using (ProcessStream ps = new ProcessStream(targetProcessHandle)) { ps.Write((uint)dllMemoryAddress.ToUInt64(), Encoding.Default.GetBytes(dllPath)); } Kernel32.CreateRemoteThread(targetProcessHandle, loadLibraryExportAddress, dllMemoryAddress); }
public static int Search(ProcessStream pc, byte[] buffer) { int count = 4096 + buffer.Length; pc.BeginAccess(); byte[] buffer1 = new byte[count]; int num = 0; while (true) { pc.Seek((long) (4194304 + num * 4096), SeekOrigin.Begin); if (pc.Read(buffer1, 0, count) == count) { for (int index1 = 0; index1 < 4096; ++index1) { bool flag = true; for (int index2 = 0; flag && index2 < buffer.Length; ++index2) flag = (int) buffer[index2] == (int) buffer1[index1 + index2]; if (flag) { pc.EndAccess(); return 4194304 + num * 4096 + index1; } } ++num; } else break; } pc.EndAccess(); return 0; }