void CreateSymbol() { var symbol = this.m_symbol.Text; var from = this.m_from.Text; var to = this.m_to.Text; var entry = new SymbolEntry(calculator, symbol, from, to); this.calculator.Symbols.Add(entry); this.symbols.Items.Add(entry); }
/// <summary> /// Gets the formatted string which represents specified symbol entry in name attribute of XML code documents. /// </summary> /// <param name="key">Symbol entry to get the name.</param> /// <returns>The formatted string which represents specified symbol entry in name attribute of XML code documents.</returns> public static String GetXmlDocumentName(SymbolEntry key) { return("Y:" + (key.LeftType != null ? key.LeftType.TryGetGenericTypeDefinition() == typeof(Static <>) ? "[" + GetXmlDocumentName(key.LeftType.GetGenericArguments()[0]).Substring(2) + "]." : GetXmlDocumentName(key.LeftType).Substring(2) + "." : "" ) + (key.DispatchType.HasFlag(DispatchTypes.Method) ? "(" + key.Name + ")" : key.Name )); }
/// <summary> /// Tries to manifest the compile time value as a symbol entry. This will only work for references (command-, function-, variable-). /// </summary> /// <param name = "entry">If the result is true, returns a symbol entry with the physical id set to the compile time value and the symbol interpretation set according to the interpretation of the compile time value. Otherwise the value is undefined.</param> /// <returns>true if the conversion was successful; false otherwise.</returns> public bool TryGetSymbolEntry(out SymbolEntry entry) { var er = Value as EntityRef; if (er != null) { entry = (SymbolEntry) er; return true; } else { entry = null; return false; } }
internal SymbolEntry CreateEntry(FinancialCalculator owner) { var result = new SymbolEntry(owner, this.Symbol, this.From, this.To) { Tag = this.Tag, ContractSize = this.ContractSize, Hedging = this.Hedging, MarginFactorOfPositions = this.MarginFactorOfPositions, MarginFactorOfLimitOrders = this.MarginFactorOfLimitOrders, MarginFactorOfStopOrders = this.MarginFactorOfStopOrders }; return result; }
/// <summary> /// Initializes a new instance of the <see cref="Antmicro.Renode.Core.Symbol"/> class. /// </summary> /// <param name="originalSymbol">Original symbol.</param> /// <param name="mayBeThumb">Set to <c>true</c> if symbol is related to architecture that allows thumb symbols.</param> public Symbol(SymbolEntry <TAddress> originalSymbol, bool mayBeThumb = false) { Start = originalSymbol.Value; IsThumbSymbol = false; thumbArchitecture = mayBeThumb; if (mayBeThumb) { UpdateIsThumbSymbol(); } End = Start + originalSymbol.Size; Name = DemangleSymbol(originalSymbol.Name); Type = originalSymbol.Type; Binding = originalSymbol.Binding; }
internal SymbolData(SymbolEntry entry) { if (entry == null) throw new ArgumentNullException(nameof(entry)); this.Tag = entry.Tag != null ? entry.Tag.ToString() : string.Empty; this.Symbol = entry.Symbol; this.From = entry.From; this.To = entry.To; this.ContractSize = entry.ContractSize; this.Hedging = entry.Hedging; this.MarginFactorOfPositions = entry.MarginFactorOfPositions; this.MarginFactorOfLimitOrders = entry.MarginFactorOfLimitOrders; this.MarginFactorOfStopOrders = entry.MarginFactorOfStopOrders; }
public void Process() { foreach (var currName in _currencies) { _calculator.Currencies.Add(currName); } foreach (var sym in Symbols) { var symbolValue = sym.Value; SymbolEntry symbolEntry = new SymbolEntry(_calculator, sym.Key, symbolValue.Currency, symbolValue.SettlementCurrency); symbolEntry.Hedging = symbolValue.MarginHedge; _calculator.Symbols.Add(symbolEntry); } PriceEntries priceEntries = _calculator.Prices; var feed = FdkHelper.Wrapper.ConnectLogic.Feed; var server = feed.Server; server.SubscribeToQuotes(_symbolInfoDic.Select(sym => sym.Name), 1); var autoResetEvent = new AutoResetEvent(true); feed.Tick += (arg, ev) => autoResetEvent.Set(); autoResetEvent.WaitOne(); Thread.Sleep(100); _symbolInfoDic.Each(sym => { var retries = 5; double price; while (!FdkHelper.Wrapper.ConnectLogic.Feed.Cache.TryGetBid(sym.Name, out price) && retries > 0) { Thread.Sleep(100); retries--; } try { priceEntries.Update(sym.Name, price, price); } catch (Exception ex) { Console.WriteLine("Exception on updating calculator for symbol: {0} exception: {1}", sym.Name, ex); } }); }
internal SymbolEntry CreateEntry(FinancialCalculator owner) { var result = new SymbolEntry(owner, this.Symbol, this.From, this.To) { Tag = this.Tag, ContractSize = this.ContractSize, Hedging = this.Hedging, MarginFactorOfPositions = this.MarginFactorOfPositions, MarginFactorOfLimitOrders = this.MarginFactorOfLimitOrders, MarginFactorOfStopOrders = this.MarginFactorOfStopOrders, StopOrderMarginReduction = this.StopOrderMarginReduction, HiddenLimitOrderMarginReduction = this.HiddenLimitOrderMarginReduction }; return(result); }
public static SymbolInfo ToSymbolInfo(SymbolEntry symbol) { return new SymbolInfo { Symbol = symbol.Symbol, MarginCurrency = symbol.MarginCurrency, MarginCurrencyId = (short)symbol.MarginCurrency.GetHashCode(), ProfitCurrency = symbol.ProfitCurrency, ProfitCurrencyId = (short)symbol.ProfitCurrency.GetHashCode(), ContractSizeFractional = symbol.ContractSize, MarginFactorFractional = symbol.MarginFactor, MarginHedged = symbol.Hedging, SortOrder = symbol.SortOrder, MarginMode = ToMarginCalculationModes(symbol.MarginCalcMode) }; }
private static void InitializeCalculator(FinancialCalculator calculator, DataFeed dataFeed, SymbolInfo[] symbols) { var dtUtcNow = DateTime.UtcNow; var currenciesHashSet = new HashSet <string>(); symbols.ToList().ForEach(s => { var symbolEntry = new SymbolEntry(calculator, s.Name, s.SettlementCurrency, s.Currency) { ContractSize = s.RoundLot, MarginFactor = s.MarginFactor, Hedging = s.MarginHedge }; calculator.Symbols.Add(symbolEntry); if (currenciesHashSet.Add(s.Currency)) { calculator.Currencies.Add(s.Currency); } if (currenciesHashSet.Add(s.SettlementCurrency)) { calculator.Currencies.Add(s.SettlementCurrency); } try { double priceBid = 0; double priceAsk = 0; TryGetBidAsk(dataFeed, s.Name, ref priceBid, ref priceAsk); try { calculator.Prices.Update(s.Name, priceBid, priceAsk); } catch (Exception ex) { Log.Error(string.Format("Failed to update calculator for symbol: {0} exception: {1}", s.Name, ex)); } } catch (Exception ex) { Log.Error(string.Format("Failed to get bid/ask for symbol {0}", s.Name)); } }); currenciesHashSet.Clear(); }
public static SymbolInfo ToSymbolInfo(SymbolEntry symbol) { return(new SymbolInfo { Symbol = symbol.Symbol, MarginCurrency = symbol.MarginCurrency, MarginCurrencyId = (short)symbol.MarginCurrency.GetHashCode(), ProfitCurrency = symbol.ProfitCurrency, ProfitCurrencyId = (short)symbol.ProfitCurrency.GetHashCode(), ContractSizeFractional = symbol.ContractSize, MarginFactorFractional = symbol.MarginFactor, MarginHedged = symbol.Hedging, SortOrder = symbol.SortOrder, MarginMode = ToMarginCalculationModes(symbol.MarginCalcMode), StopOrderMarginReduction = symbol.StopOrderMarginReduction ?? 1, HiddenLimitOrderMarginReduction = symbol.HiddenLimitOrderMarginReduction ?? 1 }); }
internal SymbolData(SymbolEntry entry) { if (entry == null) { throw new ArgumentNullException(nameof(entry)); } this.Tag = entry.Tag != null?entry.Tag.ToString() : string.Empty; this.Symbol = entry.Symbol; this.From = entry.From; this.To = entry.To; this.ContractSize = entry.ContractSize; this.Hedging = entry.Hedging; this.MarginFactorOfPositions = entry.MarginFactorOfPositions; this.MarginFactorOfLimitOrders = entry.MarginFactorOfLimitOrders; this.MarginFactorOfStopOrders = entry.MarginFactorOfStopOrders; this.StopOrderMarginReduction = entry.StopOrderMarginReduction; this.HiddenLimitOrderMarginReduction = entry.HiddenLimitOrderMarginReduction; }
public AdsErrorCode TryCreateVariableHandle(string variableName, out int clientHandle) { AdsErrorCode noError = AdsErrorCode.NoError; clientHandle = 0; bool flag = false; noError = AdsErrorCode.NoError; Dictionary <int, SymbolEntry> dictionary = this._symbolTable; lock (dictionary) { flag = this._symbolPathTable.TryGetValue(variableName, out clientHandle); } uint rdValue = (uint)clientHandle; if (!flag) { noError = this._syncPort.ReadWrite(0xf003, 0, variableName, false, out rdValue); } if (noError == AdsErrorCode.NoError) { clientHandle = (int)rdValue; SymbolEntry entry = null; Dictionary <int, SymbolEntry> dictionary2 = this._symbolTable; lock (dictionary2) { if (!flag) { this._symbolPathTable.Add(variableName, clientHandle); } if (!this._symbolTable.TryGetValue(clientHandle, out entry)) { entry = new SymbolEntry(rdValue, variableName); this._symbolTable.Add(clientHandle, entry); } } Interlocked.Increment(ref entry.referenceCount); } return(noError); }
byte[] GetData(uint symbolValue, ulong size) { Log.Debug($"ELF64.GetData: Looking for symbol value {symbolValue:X08}"); SymbolEntry <uint>?symbol = GetSymbol(DynamicSymbols, symbolValue); if (symbol == null && Symbols != null) { symbol = GetSymbol(Symbols, symbolValue); } if (symbol != null) { Log.Debug($"ELF64.GetData: found in section {symbol.PointedSection.Name}"); return(GetData(symbol)); } Section <uint> section = FindSectionForValue(symbolValue); Log.Debug($"ELF64.GetData: found in section {section} {section.Name}"); return(GetData(section, size, OffsetInSection(section, symbolValue))); }
private async Task <List <object> > GenerateArrayChecksums(SymbolEntry item) { List <object> list = new List <object>(); var items = (List <object>)item.value; for (int i = 0; i < items.Count; i++) { switch (item.subType) { case QScript.ESymbolType.ESYMBOLTYPE_NAME: if ((((List <object>)item.value)[i]).GetType() != typeof(System.Int64)) { var name = (((List <object>)item.value)[i]).ToString(); list.Add(await checksumResolver.GenerateChecksum(name)); } else { list.Add((System.Int64)((List <object>)item.value)[i]); } break; case QScript.ESymbolType.ESYMBOLTYPE_STRUCTURE: List <SymbolEntry> struct_value = (List <SymbolEntry>)(items)[i]; List <SymbolEntry> symbols = await GenerateChecksums(struct_value); list.Add(symbols); break; case QScript.ESymbolType.ESYMBOLTYPE_ARRAY: list.Add(GenerateArrayChecksums((SymbolEntry)((List <object>)item.value)[i])); break; default: list.Add(((List <object>)item.value)[i]); break; } } return(list); }
private void SymbolView_Load(object sender, EventArgs e) { AcceptButton = btnGoto; ActiveControl = textSearch; if (m_symbols == null) { listSymbols.Enabled = false; } else { listSymbols.Enabled = true; listSymbols.Items.Clear(); foreach (Symbols.SymbolEntry symbol in m_symbols.m_Symbols) { SymbolEntry entry = new SymbolEntry(); entry.Text = symbol.name; entry.Address = symbol.address; listSymbols.Items.Add(entry); } } }
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button != MouseButtons.Right) return; if (e.RowIndex < 0 || e.ColumnIndex < 0) return; var row = dataGridView1.Rows[e.RowIndex].DataBoundItem as SymbolEntry; clickedSymbolEntry = row; var relativeMousePosition = dataGridView1.PointToClient(Cursor.Position); MenuItem menu = new MenuItem(row.Name); menu.Enabled = false; ContextMenu m = new ContextMenu(); m.MenuItems.Add(menu); m.MenuItems.Add(new MenuItem("Copy to &Clipboard", new EventHandler(MenuItem3_Click))); m.MenuItems.Add(new MenuItem("Add to &Watch List", new EventHandler(MenuItem1_Click))); m.MenuItems.Add(new MenuItem("Set &Breakpoint", new EventHandler(MenuItem2_Click))); m.Show(dataGridView1, relativeMousePosition); }
private static AstGetSet _assembleImplCall(MacroContext context, SymbolEntry implementationSymbolEntry, ISourcePosition position) { var internalId = context.CreateConstant(implementationSymbolEntry.InternalId); var interpretation = implementationSymbolEntry.Interpretation.ToExpr(position); var moduleNameOpt = context.CreateConstantOrNull(implementationSymbolEntry.Module); var implCall = context.Factory.IndirectCall(context.Invocation.Position, context.Factory.Reference(context.Invocation.Position, EntityRef.Command.Create( Impl.Alias))); implCall.Arguments.Add(internalId); implCall.Arguments.Add(interpretation); implCall.Arguments.Add(moduleNameOpt); return implCall; }
public bool Read(string filename) { try { m_Symbols = new List <SymbolEntry>(); m_Filenames = new List <FilenameSection>(); byte[] data = System.IO.File.ReadAllBytes(filename); if (data.Length > 0) { GCHandle pinnedData = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr stream = pinnedData.AddrOfPinnedObject(); FilenameHeader filenameHeader = new FilenameHeader(); ChunkHeader chunkHeader = new ChunkHeader(); FilenameSection filenameSection = new FilenameSection(); AddressEntry addressEntry = new AddressEntry(); SymbolChunk symbolChunk = new SymbolChunk(); SymbolEntry symbolEntry = new SymbolEntry(); string readString; int bytesRead = 0; int currentLine = 0; //Read file header FileHeader fileHeader = new FileHeader(); bytesRead += Serialise(ref stream, out fileHeader); //Iterate over chunks while (bytesRead < data.Length) { //Read chunk header bytesRead += Serialise(ref stream, out chunkHeader); //What is it? switch (chunkHeader.chunkId) { case ChunkId.Filename: { //Read filename header bytesRead += Serialise(ref stream, out filenameHeader); EndianSwap(ref filenameHeader.length); //Read string bytesRead += Serialise(ref stream, filenameHeader.length, out readString); if (filenameHeader.flags == 0x1) { //This is the filename passed for assembly m_AssembledFile = readString; } else { //If filename already exists, continue adding data to it int sectionIdx = m_Filenames.FindIndex(element => element.filename == readString); if (sectionIdx >= 0) { //Continue filenameSection = m_Filenames[sectionIdx]; //Fetch line counter currentLine = filenameSection.addresses[filenameSection.addresses.Count - 1].lineTo; } else { //This is the first address in a filename chunk filenameSection = new FilenameSection(); filenameSection.addresses = new List <AddressEntry>(); filenameSection.filename = readString; //Reset line counter currentLine = 0; } //Chunk payload contains address addressEntry.address = chunkHeader.payload; addressEntry.lineFrom = currentLine; addressEntry.lineTo = filenameHeader.firstLine; currentLine = filenameHeader.firstLine; filenameSection.addresses.Add(addressEntry); //Add to filename list m_Filenames.Add(filenameSection); } break; } case ChunkId.Address: { //Chunk payload contains address addressEntry.address = chunkHeader.payload; //Set line range addressEntry.lineFrom = currentLine; currentLine++; addressEntry.lineTo = currentLine; //Add filenameSection.addresses.Add(addressEntry); break; } case ChunkId.AddressWithCount: { //Read line count byte lineCount = 0; bytesRead += Serialise(ref stream, out lineCount); //Chunk payload contains address addressEntry.address = chunkHeader.payload; //Set line range addressEntry.lineFrom = currentLine; currentLine += lineCount; addressEntry.lineTo = currentLine; //Add filenameSection.addresses.Add(addressEntry); break; } case ChunkId.Symbol: { //Read symbol string length byte stringLength = 0; bytesRead += Serialise(ref stream, out stringLength); //Read string bytesRead += Serialise(ref stream, stringLength, out symbolEntry.name); //Payload contains address symbolEntry.address = chunkHeader.payload; m_Symbols.Add(symbolEntry); break; } case ChunkId.EndOfSection: //Nothing of interest break; } } pinnedData.Free(); //Build address to file/line map m_Addr2FileLine = new Dictionary <uint, Tuple <string, int> >(); foreach (FilenameSection section in m_Filenames) { foreach (AddressEntry address in section.addresses) { if (!m_Addr2FileLine.ContainsKey(address.address)) { m_Addr2FileLine[address.address] = new Tuple <string, int>(section.filename, address.lineTo); } } } return(true); } } catch (Exception e) { Console.WriteLine(e.Message); } return(false); }
protected override byte[] GetData(SymbolEntry <uint> symbol) { ulong offset = symbol.Value - symbol.PointedSection.LoadAddress; return(GetData(symbol, symbol.Size, offset)); }
/// <summary> /// Gets the formatted string which represents specified symbol entry in name attribute of XML code documents. /// </summary> /// <param name="key">Symbol entry to get the name.</param> /// <returns>The formatted string which represents specified symbol entry in name attribute of XML code documents.</returns> public static String GetXmlDocumentName(SymbolEntry key) { return "Y:" + (key.LeftType != null ? key.LeftType.TryGetGenericTypeDefinition() == typeof(Static<>) ? "[" + GetXmlDocumentName(key.LeftType.GetGenericArguments()[0]).Substring(2) + "]." : GetXmlDocumentName(key.LeftType).Substring(2) + "." : "" ) + (key.DispatchType.HasFlag(DispatchTypes.Method) ? "(" + key.Name + ")" : key.Name ); }
void Initialize() { Recognized = false; if (BaseStream == null) { return; } byte[] buffer = new byte[Marshal.SizeOf(typeof(AtariHeader))]; BaseStream.Position = 0; BaseStream.Read(buffer, 0, buffer.Length); Header = BigEndianMarshal.ByteArrayToStructureBigEndian <AtariHeader>(buffer); Recognized = Header.signature == SIGNATURE; List <string> strings = new List <string>(); if (!Recognized) { return; } Type = "Atari ST executable"; if (Header.symb_len != 0) { BaseStream.Position = 0x1C + Header.text_len + Header.data_len; buffer = new byte[Marshal.SizeOf(typeof(SymbolEntry))]; symbols = new SymbolEntry[Header.symb_len / Marshal.SizeOf(typeof(SymbolEntry))]; for (int i = 0; i < symbols.Length; i++) { BaseStream.Read(buffer, 0, buffer.Length); symbols[i] = new SymbolEntry(); symbols[i] = BigEndianMarshal.ByteArrayToStructureBigEndian <SymbolEntry>(buffer); symbols[i].type = (SymbolType)Swapping.Swap((ushort)symbols[i].type); strings.Add(StringHandlers.CToString(symbols[i].name, Encoding.AtariSTEncoding)); } } Segments = new [] { new Segment { Name = ".text", Flags = $"{(PrgFlags)(Header.flags & 0xFFCF)} {(PrgSharing)(Header.flags & PF_SHARE_MASK)}", Offset = 0x1C, Size = Header.text_len }, new Segment { Name = ".data", Flags = "", Offset = 0x1C + Header.text_len, Size = Header.data_len }, new Segment { Name = ".bss", Flags = "", Offset = 0, Size = Header.bss_len } }; RequiredOperatingSystem = new OperatingSystem { Name = Header.mint == MINT_SIGNATURE ? "MiNT" : "Atari TOS" }; if (ResourceStream == null) { return; } buffer = new byte[Marshal.SizeOf(typeof(GEM.GemResourceHeader))]; ResourceStream.Position = 0; ResourceStream.Read(buffer, 0, buffer.Length); GEM.GemResourceHeader gemResourceHeader = BigEndianMarshal.ByteArrayToStructureBigEndian <GEM.GemResourceHeader>(buffer); if (gemResourceHeader.rsh_vrsn != 0 && gemResourceHeader.rsh_vrsn != 1 && gemResourceHeader.rsh_vrsn != 3 && gemResourceHeader.rsh_vrsn != 4 && gemResourceHeader.rsh_vrsn != 5) { return; } if (gemResourceHeader.rsh_vrsn == 3) { buffer = new byte[Marshal.SizeOf(typeof(GEM.MagiCResourceHeader))]; ResourceStream.Position = 0; ResourceStream.Read(buffer, 0, buffer.Length); ResourceHeader = BigEndianMarshal.ByteArrayToStructureBigEndian <GEM.MagiCResourceHeader>(buffer); RequiredOperatingSystem = new OperatingSystem { Name = "MagiC" }; } else { ResourceHeader = GEM.GemToMagiC(gemResourceHeader); } if ((ResourceHeader.rsh_vrsn & 4) == 4) { buffer = new byte[Marshal.SizeOf(typeof(GEM.GemResourceExtension))]; ResourceStream.Position = ResourceHeader.rsh_rssize; ResourceStream.Read(buffer, 0, buffer.Length); ResourceExtension = BigEndianMarshal.ByteArrayToStructureBigEndian <GEM.GemResourceExtension>(buffer); GemColorIcons = GEM.GetColorIcons(ResourceStream, ResourceExtension.color_ic, true, Encoding.AtariSTEncoding); } if (ResourceHeader.rsh_ntree > 0) { ResourceStream.Position = ResourceHeader.rsh_trindex; int[] treeOffsets = new int[ResourceHeader.rsh_ntree]; byte[] tmp = new byte[4]; for (int i = 0; i < ResourceHeader.rsh_ntree; i++) { ResourceStream.Read(tmp, 0, 4); treeOffsets[i] = BitConverter.ToInt32(tmp.Reverse().ToArray(), 0); } ResourceObjectRoots = new GEM.TreeObjectNode[ResourceHeader.rsh_ntree]; for (int i = 0; i < ResourceHeader.rsh_ntree; i++) { if (treeOffsets[i] <= 0 || treeOffsets[i] >= ResourceStream.Length) { continue; } ResourceStream.Position = treeOffsets[i]; List <GEM.ObjectNode> nodes = new List <GEM.ObjectNode>(); while (true) { buffer = new byte[Marshal.SizeOf(typeof(GEM.ObjectNode))]; ResourceStream.Read(buffer, 0, buffer.Length); GEM.ObjectNode node = BigEndianMarshal.ByteArrayToStructureBigEndian <GEM.ObjectNode>(buffer); nodes.Add(node); if (((GEM.ObjectFlags)node.ob_flags).HasFlag(GEM.ObjectFlags.Lastob)) { break; } } List <short> knownNodes = new List <short>(); ResourceObjectRoots[i] = GEM.ProcessResourceObject(nodes, ref knownNodes, 0, ResourceStream, strings, true, Encoding.AtariSTEncoding); } } else if (ResourceHeader.rsh_nobs > 0) { GEM.ObjectNode[] nodes = new GEM.ObjectNode[ResourceHeader.rsh_nobs]; ResourceStream.Position = ResourceHeader.rsh_object; for (short i = 0; i < ResourceHeader.rsh_nobs; i++) { buffer = new byte[Marshal.SizeOf(typeof(GEM.ObjectNode))]; ResourceStream.Read(buffer, 0, buffer.Length); nodes[i] = BigEndianMarshal.ByteArrayToStructureBigEndian <GEM.ObjectNode>(buffer); } List <short> knownNodes = new List <short>(); ResourceObjectRoots = new GEM.TreeObjectNode[1]; ResourceObjectRoots[0] = GEM.ProcessResourceObject(nodes, ref knownNodes, 0, ResourceStream, strings, true, Encoding.AtariSTEncoding); } if (strings.Count > 0) { strings.Sort(); Strings = strings.Distinct(); } }
protected override byte[] GetData(SymbolEntry <ulong> symbol) { return(GetData(symbol, symbol.Size, OffsetInSection(symbol.PointedSection, symbol.Value))); }
protected virtual byte[] GetData(SymbolEntry <uint> symbol) { throw new NotSupportedException(); }
private static string _toFunctionNameString(SymbolEntry si) { if (si.Module == null) return si.InternalId; else return string.Format("{0}/{1},{2}", si.InternalId, si.Module.Id, si.Module.Version); }
public bool Read(string filename) { //try { m_Symbols = new List <SymbolEntry>(); m_Filenames = new List <FilenameSection>(); byte[] data = System.IO.File.ReadAllBytes(filename); if (data.Length > 0) { GCHandle pinnedData = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr stream = pinnedData.AddrOfPinnedObject(); FilenameHeader filenameHeader = new FilenameHeader(); ChunkHeader chunkHeader = new ChunkHeader(); FilenameSection filenameSection = new FilenameSection(); AddressEntry addressEntry = new AddressEntry(); SymbolChunk symbolChunk = new SymbolChunk(); SymbolEntry symbolEntry = new SymbolEntry(); string readString; int bytesRead = 0; int totalBytes = data.Length; // Symbol lines are 1-based, text editor lines are 0-based int currentLine = 1; //Read file header FileHeader fileHeader = new FileHeader(); bytesRead += Serialise(ref stream, out fileHeader); void CheckSize(int chunkLength) { if ((bytesRead + chunkLength) >= totalBytes) { throw new Exception("Bad chunk length or malformed file"); } } //Iterate over chunks while (bytesRead < data.Length) { //Read chunk header bytesRead += Serialise(ref stream, out chunkHeader); //What is it? switch (chunkHeader.chunkId) { case ChunkId.Filename: { //Read filename header bytesRead += Serialise(ref stream, out filenameHeader); filenameHeader.length = Endian.Swap(filenameHeader.length); //Read string CheckSize(filenameHeader.length); bytesRead += Serialise(ref stream, filenameHeader.length, out readString); if (filenameHeader.flags == 0x1) { //This is the filename passed for assembly m_AssembledFile = readString; } else { //If filename already exists, continue adding data to it int sectionIdx = m_Filenames.FindIndex(element => element.filename == readString); if (sectionIdx >= 0) { //Continue filenameSection = m_Filenames[sectionIdx]; //Fetch line counter currentLine = filenameSection.addresses[filenameSection.addresses.Count - 1].lineTo; } else { //This is the first address in a filename chunk filenameSection = new FilenameSection(); filenameSection.addresses = new List <AddressEntry>(); try { string pathSanitised = System.IO.Path.GetFullPath(readString).ToUpper(); filenameSection.filename = pathSanitised; } catch (Exception e) { Console.WriteLine("Exception caught sanitising symbol path \'" + readString + "\': " + e.Message); } //Reset line counter currentLine = 1; } //Chunk payload contains address addressEntry.address = chunkHeader.payload; addressEntry.lineFrom = currentLine - 1; addressEntry.lineTo = filenameHeader.firstLine - 1; currentLine = filenameHeader.firstLine; filenameSection.addresses.Add(addressEntry); //Next currentLine++; //Add to filename list m_Filenames.Add(filenameSection); } break; } case ChunkId.Address: { //Chunk payload contains address for a single line addressEntry.address = chunkHeader.payload; //Set line range addressEntry.lineFrom = currentLine - 1; addressEntry.lineTo = currentLine - 1; //Next currentLine++; //Add filenameSection.addresses.Add(addressEntry); break; } case ChunkId.AddressWithCount: { //Chunk payload contains address for a rage of lines addressEntry.address = chunkHeader.payload; //Read line count byte lineCount = 0; bytesRead += Serialise(ref stream, out lineCount); //Set line range addressEntry.lineFrom = currentLine - 1; addressEntry.lineTo = currentLine + (lineCount - 1) - 1; //Next currentLine += lineCount; //Add filenameSection.addresses.Add(addressEntry); break; } case ChunkId.Symbol: { //Read symbol string length byte stringLength = 0; bytesRead += Serialise(ref stream, out stringLength); //Read string CheckSize(stringLength); bytesRead += Serialise(ref stream, stringLength, out symbolEntry.name); //Payload contains address symbolEntry.address = chunkHeader.payload; m_Symbols.Add(symbolEntry); break; } case ChunkId.EndOfSection: //Payload contains section size break; default: short mysteryWord = 0; bytesRead += Serialise(ref stream, out mysteryWord); break; } } pinnedData.Free(); //Build address to file/line map m_Addr2FileLine = new Dictionary <uint, Tuple <string, int, int> >(); foreach (FilenameSection section in m_Filenames) { foreach (AddressEntry address in section.addresses) { if (!m_Addr2FileLine.ContainsKey(address.address)) { m_Addr2FileLine[address.address] = new Tuple <string, int, int>(section.filename, address.lineFrom, address.lineTo); } } } return(true); } } //catch (Exception e) //{ // Console.WriteLine(e.Message); //} return(false); }