private void OnThisPropertyChanged(object?sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(TerritoryService.CurrentWeatherId)) { ushort current; if (GposeService.Instance.IsGpose) { current = MemoryService.Read <ushort>(AddressService.GPoseWeather); if (current != this.CurrentWeatherId) { MemoryService.Write <ushort>(AddressService.GPoseWeather, this.CurrentWeatherId, "Gpose weather Changed"); } } else { current = MemoryService.Read <byte>(AddressService.Weather); if (current != this.CurrentWeatherId) { MemoryService.Write <byte>(AddressService.Weather, (byte)this.CurrentWeatherId, "Overworld weather Changed"); } } } else if (e.PropertyName == nameof(TerritoryService.CurrentWeather)) { if (this.CurrentWeather == null) { return; } if (this.CurrentWeatherId == this.CurrentWeather.WeatherId) { return; } this.CurrentWeatherId = this.CurrentWeather.WeatherId; } }
/// <summary> /// Add all the services needed by commands /// </summary> private void AddServices(DataTarget target) { _serviceProvider.AddService(target); _serviceProvider.AddService(target.DataReader); _serviceProvider.AddService<IConsoleService>(_consoleProvider); _serviceProvider.AddService(_commandProcessor); _serviceProvider.AddServiceFactory(typeof(IHelpBuilder), _commandProcessor.CreateHelpBuilder); if (!(target.DataReader is IThreadReader threadReader)) { throw new InvalidOperationException("IThreadReader not implemented"); } // Create common analyze context for commands var analyzeContext = new AnalyzeContext() { CurrentThreadId = threadReader.EnumerateOSThreadIds().FirstOrDefault() }; _serviceProvider.AddService(analyzeContext); // Add the thread, memory, SOSHost and ClrRuntime services var threadService = new ThreadService(target.DataReader); _serviceProvider.AddService<IThreadService>(threadService); var memoryService = new MemoryService(target.DataReader); _serviceProvider.AddService(memoryService); _serviceProvider.AddServiceFactory(typeof(ClrRuntime), () => CreateRuntime(target)); _serviceProvider.AddServiceFactory(typeof(SOSHost), () => { var sosHost = new SOSHost(_serviceProvider); sosHost.InitializeSOSHost(SymbolReader.TempDirectory, _isDesktop, _dacFilePath, dbiFilePath: null); return sosHost; }); // ClrMD helper for extended commands _serviceProvider.AddServiceFactory(typeof(ClrMDHelper), () => new ClrMDHelper(_serviceProvider) ); }
private async Task Tick() { while (this.IsAlive) { await Task.Delay(50); if (!GposeService.Instance.IsGpose || GposeService.Instance.IsChangingState) { this.LockCameraPosition = false; continue; } if (this.LockCameraPosition) { MemoryService.Write(AddressService.GPoseCamera, this.CameraPosition); } else { this.CameraPosition = MemoryService.Read <Vector>(AddressService.GPoseCamera); } } }
private async Task Tick() { while (this.IsAlive) { await Task.Delay(50); if (this.Camera == null) { continue; } this.Camera.Pointer = AddressService.Camera; if (!GposeService.Instance.IsGpose || GposeService.Instance.IsChangingState) { this.DelimitCamera = false; this.LockCameraPosition = false; this.Camera.FreezeAngle = false; continue; } try { if (this.LockCameraPosition) { MemoryService.Write(AddressService.GPoseCamera, this.CameraPosition, "Camera Locked"); } else { this.CameraPosition = MemoryService.Read <Vector>(AddressService.GPoseCamera); } } catch (Exception ex) { Log.Warning(ex, "Failed to update camera"); } } }
private static Task GetBaseAddressFromSignature(string signature, int skip, bool moduleBase, Action <IntPtr> callback) { if (MemoryService.Scanner == null) { throw new Exception("No memory scanner"); } return(Task.Run(() => { if (MemoryService.Process?.MainModule == null) { return; } try { IntPtr ptr = MemoryService.Scanner.ScanText(signature); ptr += skip; int offset = MemoryService.Read <int>(ptr); if (moduleBase) { ptr = MemoryService.Process.MainModule.BaseAddress + offset; } else { ptr += offset + 4; } callback.Invoke(ptr); } catch (Exception ex) { Log.Fatal(ex, "Failed to scan memory for base address from signature (Have you tried restarting FFXIV?)"); } })); }
/// <summary> /// Returns information about the PE file. /// </summary> /// <param name="isVirtual">the memory layout of the module</param> /// <param name="address">module base address</param> /// <param name="size">module size</param> /// <param name="pdbInfo">the pdb record or null</param> /// <param name="version">the PE version or null</param> /// <param name="flags">module flags</param> /// <returns>PEImage instance or null</returns> private PEImage GetPEInfo(bool isVirtual, ulong address, ulong size, ref PdbInfo pdbInfo, ref VersionInfo?version, ref Module.Flags flags) { Stream stream = MemoryService.CreateMemoryStream(address, size); try { stream.Position = 0; var peImage = new PEImage(stream, leaveOpen: false, isVirtual); if (peImage.IsValid) { flags |= Module.Flags.IsPEImage; flags |= peImage.IsManaged ? Module.Flags.IsManaged : Module.Flags.None; pdbInfo = peImage.DefaultPdb; if (!version.HasValue) { FileVersionInfo fileVersionInfo = peImage.GetFileVersionInfo(); if (fileVersionInfo != null) { version = fileVersionInfo.VersionInfo; } } flags &= ~(Module.Flags.IsLoadedLayout | Module.Flags.IsFileLayout); flags |= isVirtual ? Module.Flags.IsLoadedLayout : Module.Flags.IsFileLayout; return(peImage); } else { Trace.TraceError($"GetPEInfo: PE invalid {address:X16} isVirtual {isVirtual}"); } } catch (Exception ex) when(ex is BadImageFormatException || ex is EndOfStreamException || ex is IOException) { Trace.TraceError($"GetPEInfo: loaded {address:X16} isVirtual {isVirtual} exception {ex.Message}"); } return(null); }
private static byte ReadByte(IntPtr baseAddress, int offset = 0) { byte[] buffer = new byte[1]; MemoryService.Read(baseAddress + offset, buffer, 1); return(buffer[0]); }
public ValuesController(MemoryService memory, AzureServiceBusService serviceBus) { _memory = memory; _serviceBus = serviceBus; }
public void Setup() { _delayHelperMock = new Mock <IDelayHelper>(MockBehavior.Strict); _memoryService = new MemoryService(_delayHelperMock.Object); }
static void Main(string[] args) { var ptr = MemoryService.Allocate(1024, false); bool result = MemoryService.Free(ptr); }
/// <summary> /// Load native symbols and modules (i.e. DAC, DBI). /// </summary> /// <param name="callback">called back for each symbol file loaded</param> /// <param name="parameter">callback parameter</param> /// <param name="config">Target configuration: Windows, Linux or OSX</param> /// <param name="moduleFilePath">module path</param> /// <param name="address">module base address</param> /// <param name="size">module size</param> /// <param name="readMemory">read memory callback delegate</param> private void LoadNativeSymbols( IntPtr self, SymbolFileCallback callback, IntPtr parameter, RuntimeConfiguration config, string moduleFilePath, ulong address, uint size) { if (_symbolService.IsSymbolStoreEnabled) { try { Stream stream = MemoryService.CreateMemoryStream(address, size); KeyGenerator generator = null; if (config == RuntimeConfiguration.UnixCore) { var elfFile = new ELFFile(new StreamAddressSpace(stream), 0, true); generator = new ELFFileKeyGenerator(Tracer.Instance, elfFile, moduleFilePath); } else if (config == RuntimeConfiguration.OSXCore) { var machOFile = new MachOFile(new StreamAddressSpace(stream), 0, true); generator = new MachOFileKeyGenerator(Tracer.Instance, machOFile, moduleFilePath); } else if (config == RuntimeConfiguration.WindowsCore || config == RuntimeConfiguration.WindowsDesktop) { var peFile = new PEFile(new StreamAddressSpace(stream), true); generator = new PEFileKeyGenerator(Tracer.Instance, peFile, moduleFilePath); } else { Trace.TraceError("LoadNativeSymbols: unsupported config {0}", config); } if (generator != null) { IEnumerable <SymbolStoreKey> keys = generator.GetKeys(KeyTypeFlags.SymbolKey | KeyTypeFlags.DacDbiKeys); foreach (SymbolStoreKey key in keys) { string moduleFileName = Path.GetFileName(key.FullPathName); Trace.TraceInformation("{0} {1}", key.FullPathName, key.Index); string downloadFilePath = _symbolService.DownloadFile(key); if (downloadFilePath != null) { Trace.TraceInformation("{0}: {1}", moduleFileName, downloadFilePath); callback(parameter, moduleFileName, downloadFilePath); } } } } catch (Exception ex) when (ex is DiagnosticsException || ex is BadInputFormatException || ex is InvalidVirtualAddressException || ex is ArgumentOutOfRangeException || ex is IndexOutOfRangeException || ex is TaskCanceledException) { Trace.TraceError("{0} address {1:X16}: {2}", moduleFilePath, address, ex.Message); } } }
private async Task Update() { while (this.IsAlive) { try { await Task.Delay(10); if (!MemoryService.IsProcessAlive) { continue; } // Update territory int newTerritoryId = MemoryService.Read <int>(AddressService.Territory); if (newTerritoryId == -1) { this.currentWeatherId = 0; this.CurrentTerritoryId = 0; this.CurrentTerritory = null; this.CurrentTerritoryName = "Menu"; } else { if (newTerritoryId != this.CurrentTerritoryId) { this.CurrentTerritoryId = (uint)newTerritoryId; if (GameDataService.Territories == null) { this.CurrentTerritoryName = $"Unkown ({this.CurrentTerritoryId})"; } else { this.CurrentTerritory = GameDataService.Territories.Get(this.CurrentTerritoryId); this.CurrentTerritoryName = this.CurrentTerritory?.Place + " (" + this.CurrentTerritory?.Region + ")"; } } // Update weather ushort weatherId; if (GposeService.Instance.IsGpose) { weatherId = MemoryService.Read <ushort>(AddressService.GPoseWeather); } else { weatherId = MemoryService.Read <byte>(AddressService.Weather); } if (weatherId != this.CurrentWeatherId) { this.CurrentWeatherId = weatherId; } } } catch (Exception) { Log.Information("Failed to update territory"); this.currentWeatherId = 0; this.CurrentTerritoryId = 0; this.CurrentTerritory = null; this.CurrentTerritoryName = "Unknown"; } } }
/// <summary> /// Get the version string from a Linux or MacOS image /// </summary> /// <param name="address">image base</param> /// <returns>version string or null</returns> protected string GetVersionString(ulong address) { Stream stream = MemoryService.CreateMemoryStream(); try { if (Target.OperatingSystem == OSPlatform.Linux) { var elfFile = new ELFFile(new StreamAddressSpace(stream), address, true); if (elfFile.IsValid()) { foreach (ELFProgramHeader programHeader in elfFile.Segments.Select((segment) => segment.Header)) { uint flags = MemoryService.PointerSize == 8 ? programHeader.Flags : programHeader.Flags32; if (programHeader.Type == ELFProgramHeaderType.Load && (flags & (uint)ELFProgramHeaderAttributes.Writable) != 0) { ulong loadAddress = programHeader.VirtualAddress.Value; long loadSize = (long)programHeader.VirtualSize; if (SearchVersionString(address + loadAddress, loadSize, out string productVersion)) { return(productVersion); } } } Trace.TraceInformation($"GetVersionString: not found in ELF file {address:X16}"); } else { Trace.TraceError($"GetVersionString: invalid ELF file {address:X16}"); } } else if (Target.OperatingSystem == OSPlatform.OSX) { var machOFile = new MachOFile(new StreamAddressSpace(stream), address, true); if (machOFile.IsValid()) { foreach (MachSegmentLoadCommand loadCommand in machOFile.Segments.Select((segment) => segment.LoadCommand)) { if (loadCommand.Command == LoadCommandType.Segment64 && (loadCommand.InitProt & VmProtWrite) != 0 && loadCommand.SegName.ToString() != "__LINKEDIT") { ulong loadAddress = loadCommand.VMAddress + machOFile.PreferredVMBaseAddress; long loadSize = (long)loadCommand.VMSize; if (SearchVersionString(loadAddress, loadSize, out string productVersion)) { return(productVersion); } } } Trace.TraceInformation($"GetVersionString: not found in MachO file {address:X16}"); } else { Trace.TraceError($"GetVersionString: invalid MachO file {address:X16}"); } } else { Trace.TraceError("GetVersionString: unsupported platform {0}", Target.OperatingSystem); } } catch (Exception ex) when(ex is InvalidVirtualAddressException || ex is BadInputFormatException || ex is IOException) { Trace.TraceError($"GetVersionString: {address:X16} exception {ex.Message}"); } return(null); }
public async Task ChangeCurrency(string currencyName) { ms = new MemoryService(); await ms.ChangeCurrency(currencySetting); }
internal ReadVirtualCache(MemoryService memoryService) { _memoryService = memoryService; Clear(); }
private void FinishMakingPdf() { if (_conversionOrder.ReportMemoryUsage) { Console.WriteLine("Making the PDF took {0}", DateTime.Now - _startMakingPdf); MemoryManagement.CheckMemory(false, "Memory use after printing", false); } if (_conversionOrder.ReduceMemoryUse) { if (!File.Exists(_currentFile)) { throw new ApplicationException(string.Format( "GeckoFxHtmlToPdf was not able to create the PDF file ({0}).{1}{1}Details: Gecko did not produce the expected document.", _currentFile, Environment.NewLine)); } // collect all the memory we can between pages GC.Collect(); GC.WaitForPendingFinalizers(); MemoryService.MinimizeHeap(true); _browser.Window.WindowUtils.GarbageCollect(null /*hopefully nulls ok*/, 0); var length = new FileInfo(_currentFile).Length; if (IsPrintingFinished(length)) { CombinePageFilesTogether(); if (_conversionOrder.ReportMemoryUsage) { MemoryManagement.CheckMemory(false, "Memory use after combining all the pages", false); Console.WriteLine("Making all the PDF pages took {0}", DateTime.Now - _beginPages); } RaiseFinished(); return; } ++_currentPage; _printSettings.SetStartPageRangeAttribute(_currentPage); _printSettings.SetEndPageRangeAttribute(_currentPage); _currentFile = String.Format("{0}-page{1:000}", _pathToTempPdf, _currentPage); _printSettings.SetToFileNameAttribute(_currentFile); _finished = false; _startMakingPdf = DateTime.Now; Status = String.Format("Making Page {0} of PDF...", _currentPage); RaiseStatusChanged(new PdfMakingStatus() { percentage = 0, statusLabel = Status }); _print.Print(_printSettings, this); _checkForPdfFinishedTimer.Enabled = true; return; } if (!File.Exists(_pathToTempPdf)) { throw new ApplicationException(string.Format( "GeckoFxHtmlToPdf was not able to create the PDF file ({0}).{1}{1}Details: Gecko did not produce the expected document.", _pathToTempPdf, Environment.NewLine)); } try { File.Move(_pathToTempPdf, _conversionOrder.OutputPdfPath); RaiseFinished(); } catch (IOException e) { // We can get here for a different reason: the source file is still in use throw new ApplicationException( string.Format( "Tried to move the file {0} to {1}, but the Operating System said that one of these files was locked. Please try again.{2}{2}Details: {3}", _pathToTempPdf, _conversionOrder.OutputPdfPath, Environment.NewLine, e.Message)); } }
private static long ReadInt64(IntPtr baseAddress, int offset = 0) { byte[] buffer = new byte[8]; MemoryService.Read(baseAddress + offset, buffer, 8); return(BitConverter.ToInt64(buffer)); }
public MemoryToNetworkAdapter(MemoryService service) { this.service = service; }
public async Task ChangeToggleNotifications(bool areNotificationsEnabled) { ms = new MemoryService(); await ms.ChangeNotificationsEnabled(areNotificationsEnabled); }
static void Main(string[] args) { var running = true; IDelayHelper delayHelper = new DelayHelper(); IMemoryService memoryService = new MemoryService(delayHelper); Console.WriteLine("Hello and welcome to Memory"); var playingBoard = memoryService.IntializePlayingBoard(); memoryService.boardChangeEvent += () => { var playingBoard = memoryService.Board; Console.Clear(); Console.WriteLine($"BOARDSTATE: {memoryService.GetName(memoryService.BoardState)}"); Console.WriteLine($"SCORE : {memoryService.Score}"); Console.WriteLine($"{playingBoard.PrintBoard(4)}"); }; while (running) { var incorrectInput = true; Card chosenCard = null; Console.WriteLine($"{playingBoard.PrintBoard(4)}"); while (incorrectInput) { Console.WriteLine("Enter which card to flip"); try { var row = Convert.ToInt32(Console.ReadLine()); chosenCard = playingBoard.First(x => x.Index == row); incorrectInput = false; } catch (Exception) { Console.WriteLine("Incorrect input"); continue; } } var boardState = memoryService.FlipCard(ref chosenCard); if (boardState == Memory.Core.Constants.GameStates.GAME_WON) { Console.WriteLine("You have won!!"); Console.WriteLine($"BOARDSTATE: {memoryService.GetName(boardState)}"); Console.WriteLine($"SCORE : {memoryService.Score}"); var startOverInput = true; while (startOverInput) { Console.WriteLine("Would you like to start a new round? (Y/N)"); var input = Console.ReadLine(); if (input.ToUpper() == "Y") { playingBoard = memoryService.IntializePlayingBoard(); startOverInput = false; continue; } else if (input.ToUpper() == "N") { running = false; startOverInput = false; continue; } } } Console.Clear(); Console.WriteLine($"BOARDSTATE: {memoryService.GetName(boardState)}"); Console.WriteLine($"SCORE : {memoryService.Score}"); } }
private static int ReadInt32(IntPtr baseAddress, int offset = 0) { byte[] buffer = new byte[4]; MemoryService.Read(baseAddress + offset, buffer, 4); return(BitConverter.ToInt32(buffer)); }
public static RepositoryMemory AsDataStore(this MemoryService service) { return(new MemoryToDataStoreAdapter(service)); }
private static short ReadInt16(IntPtr baseAddress, int offset = 0) { byte[] buffer = new byte[2]; MemoryService.Read(baseAddress + offset, buffer, 2); return(BitConverter.ToInt16(buffer)); }
public MemoryController(MemoryService service) { this.service = service; }
/// <summary> /// Load native symbols and modules (i.e. DAC, DBI). /// </summary> /// <param name="callback">called back for each symbol file loaded</param> /// <param name="parameter">callback parameter</param> /// <param name="config">Target configuration: Windows, Linux or OSX</param> /// <param name="moduleFilePath">module path</param> /// <param name="address">module base address</param> /// <param name="size">module size</param> /// <param name="readMemory">read memory callback delegate</param> private void LoadNativeSymbols( IntPtr self, SymbolFileCallback callback, IntPtr parameter, RuntimeConfiguration config, string moduleFilePath, ulong address, uint size) { if (_symbolService.IsSymbolStoreEnabled) { OSPlatform platform; switch (config) { case RuntimeConfiguration.UnixCore: platform = OSPlatform.Linux; break; case RuntimeConfiguration.OSXCore: platform = OSPlatform.OSX; break; case RuntimeConfiguration.WindowsCore: case RuntimeConfiguration.WindowsDesktop: platform = OSPlatform.Windows; break; default: Trace.TraceError($"Invalid runtime config {config}"); return; } try { KeyGenerator generator = MemoryService.GetKeyGenerator(platform, moduleFilePath, address, size); if (generator != null) { IEnumerable <SymbolStoreKey> keys = generator.GetKeys(KeyTypeFlags.SymbolKey | KeyTypeFlags.DacDbiKeys); foreach (SymbolStoreKey key in keys) { string moduleFileName = Path.GetFileName(key.FullPathName); Trace.TraceInformation("{0} {1}", key.FullPathName, key.Index); string downloadFilePath = _symbolService.DownloadFile(key); if (downloadFilePath != null) { Trace.TraceInformation("{0}: {1}", moduleFileName, downloadFilePath); callback(parameter, moduleFileName, downloadFilePath); } } } } catch (Exception ex) when (ex is DiagnosticsException || ex is BadInputFormatException || ex is InvalidVirtualAddressException || ex is ArgumentOutOfRangeException || ex is IndexOutOfRangeException || ex is TaskCanceledException) { Trace.TraceError("{0} address {1:X16}: {2}", moduleFilePath, address, ex.Message); } } }
public override void Invoke() { if (Address.HasValue) { _lastAddress = Address.Value; } int length = Length; if (length < 0) { length = MemoryService.PointerSize; } switch (length) { case 1: case 2: case 4: case 8: break; default: length = 4; break; } Length = length; if (EndAddress.HasValue) { if (EndAddress.Value <= _lastAddress) { throw new ArgumentException("Cannot dump a negative range"); } int range = (int)(EndAddress.Value - _lastAddress); Count = range / length; } if (AsciiString || UnicodeString) { var sb = new StringBuilder(); while (true) { char ch = ReadChar(_lastAddress, UnicodeString, true); _lastAddress += (ulong)(UnicodeString ? 2 : 1); if (ch == 0) { break; } sb.Append(ch); Console.CancellationToken.ThrowIfCancellationRequested(); } WriteLine("Text: '{0}'", sb.ToString()); } else { int count = Count > 0 ? Count : 32; Count = count; int width = Width > 0 ? Width : 32 / length; Width = width; count *= length; ulong address = _lastAddress; var sb = new StringBuilder(); while (count > 0) { if (ShowAddress) { sb.AppendFormat("{0:x16}:", address); } for (int column = 0; column < width; column++) { int offset = column * length; sb.Append(" "); if (offset < count) { byte[] data = new byte[length]; if (!MemoryService.ReadMemory(address + (ulong)offset, data, length, out int bytesRead)) { data = Array.Empty <byte>(); } if (bytesRead >= length) { if (HexPrefix) { sb.Append("0x"); } switch (length) { case 1: sb.AppendFormat("{0:x2}", data[0]); break; case 2: sb.AppendFormat("{0:x4}", BitConverter.ToUInt16(data, 0)); break; case 4: sb.AppendFormat("{0:x8}", BitConverter.ToUInt32(data, 0)); break; case 8: sb.AppendFormat("{0:x16}", BitConverter.ToUInt64(data, 0)); break; } } else { if (HexPrefix) { sb.Append(" "); } sb.Append('?', length * 2); } } else { if (HexPrefix) { sb.Append(" "); } sb.Append(' ', length * 2); } } if (Ascii || Unicode) { sb.Append(" "); for (int column = 0; column < width; column++) { int offset = column * length; if (offset < count) { char val = ReadChar(address + (ulong)offset, Unicode, false); sb.Append(val); } } } address += (ulong)(width * length); count -= width * length; WriteLine(sb.ToString()); sb.Clear(); Console.CancellationToken.ThrowIfCancellationRequested(); } _lastAddress = address; } }
public NewItemPageModel(INavigation navigation) { ms = new MemoryService(); this.navigation = navigation; }
public void Setup() { mem = new MemoryService(new RAMModel(new Mock <Port>().Object, new Mock <Port>().Object), new Stack <short>(MemoryConstants.PC_STACK_CAPACITY)); opHelpers = new OperationHelpers(mem); }
public MemoryToDataStoreAdapter(MemoryService service) { this.service = service; }
public static NetworkPoolMemory AsNetwork(this MemoryService service) { return(new MemoryToNetworkAdapter(service)); }