public static BamlContext ConstructContext(ModuleDef module, BamlDocument document, CancellationToken token) { var ctx = new BamlContext(module); foreach (var record in document) { token.ThrowIfCancellationRequested(); if (record is AssemblyInfoRecord) { var assemblyInfo = (AssemblyInfoRecord)record; if (assemblyInfo.AssemblyId == ctx.AssemblyIdMap.Count) ctx.AssemblyIdMap.Add(assemblyInfo.AssemblyId, assemblyInfo); } else if (record is AttributeInfoRecord) { var attrInfo = (AttributeInfoRecord)record; if (attrInfo.AttributeId == ctx.AttributeIdMap.Count) ctx.AttributeIdMap.Add(attrInfo.AttributeId, attrInfo); } else if (record is StringInfoRecord) { var strInfo = (StringInfoRecord)record; if (strInfo.StringId == ctx.StringIdMap.Count) ctx.StringIdMap.Add(strInfo.StringId, strInfo); } else if (record is TypeInfoRecord) { var typeInfo = (TypeInfoRecord)record; if (typeInfo.TypeId == ctx.TypeIdMap.Count) ctx.TypeIdMap.Add(typeInfo.TypeId, typeInfo); } } return ctx; }
private void ProcessDocument(BamlDocument document) { foreach (var record in document) { switch (record) { case AssemblyInfoRecord assemblyInfoRecord: { ProcessRecord(assemblyInfoRecord); } break; case XmlnsPropertyRecord xmlnsPropertyRecord: { ProcessRecord(xmlnsPropertyRecord); } break; case PropertyWithConverterRecord propertyWithConverterRecord: { ProcessRecord(propertyWithConverterRecord); } break; case TextWithConverterRecord textWithConverterRecord: { ProcessRecord(textWithConverterRecord); } break; case TypeInfoRecord typeInfoRecord: { ProcessRecord(typeInfoRecord); } break; } } }
private void ParseResource(EmbeddedResource resource) { ResourceReader reader; try { reader = new ResourceReader(resource.CreateReader().AsStream()); } catch (ArgumentException) { Console.WriteLine("This resource can not be parsed."); //throw; return; } var e = reader.GetEnumerator(); while (e.MoveNext()) { if (e.Key.ToString().ToLower().EndsWith(".baml")) { reader.GetResourceData(e.Key.ToString(), out _, out var contents); //MARK:AF 3E 00 00 contents = contents.Skip(4).ToArray(); //MARK:the first 4 bytes = length using (var ms = new MemoryStream(contents)) { BamlDocument b = BamlReader.ReadDocument(ms); BamlFiles.TryAdd(e.Key.ToString(), b); } } } }
void Disassemble(ModuleDef module, BamlDocument document, IDecompilerOutput output, CancellationToken token) { var disassembler = new BamlDisassembler(output, token); disassembler.Disassemble(module, document); }
public static void WriteDocument(BamlDocument doc, Stream str) { var writer = new BamlBinaryWriter(str); { var wtr = new BinaryWriter(str, Encoding.Unicode); int len = doc.Signature.Length * 2; wtr.Write(len); wtr.Write(doc.Signature.ToCharArray()); wtr.Write(new byte[((len + 3) & ~3) - len]); } writer.Write(doc.ReaderVersion.Major); writer.Write(doc.ReaderVersion.Minor); writer.Write(doc.UpdaterVersion.Major); writer.Write(doc.UpdaterVersion.Minor); writer.Write(doc.WriterVersion.Major); writer.Write(doc.WriterVersion.Minor); var defers = new List<int>(); for (int i = 0; i < doc.Count; i++) { BamlRecord rec = doc[i]; rec.Position = str.Position; writer.Write((byte)rec.Type); rec.Write(writer); if (rec is IBamlDeferRecord) defers.Add(i); } foreach (int i in defers) (doc[i] as IBamlDeferRecord).WriteDefer(doc, i, writer); }
public void Disassemble(ModuleDef module, BamlDocument document) { WriteText("Signature: \t"); WriteString(document.Signature); output.WriteLine(); WriteText("Reader Version: \t"); WriteVersion(document.ReaderVersion); output.WriteLine(); WriteText("Updater Version:\t"); WriteVersion(document.UpdaterVersion); output.WriteLine(); WriteText("Writer Version: \t"); WriteVersion(document.WriterVersion); output.WriteLine(); WriteText("Record #: \t"); output.Write(document.Count.ToString(CultureInfo.InvariantCulture), BoxedTextColor.Number); output.WriteLine(); output.WriteLine(); var ctx = BamlContext.ConstructContext(module, document, token); scopeStack.Clear(); foreach (var record in document) { token.ThrowIfCancellationRequested(); DisassembleRecord(ctx, record); } }
void Decompile(ModuleDef module, BamlDocument document, IDecompiler lang, IDecompilerOutput output, CancellationToken token) { var decompiler = new XamlDecompiler(); var xaml = decompiler.Decompile(module, document, token, BamlDecompilerOptions.Create(lang), null); var xamlText = new XamlOutputCreator(xamlOutputOptionsProvider.Default).CreateText(xaml); documentWriterService.Write(output, xamlText, ContentTypes.Xaml); }
public ResourcePart(DictionaryEntry entry) { name = (string)entry.Key; stream = (Stream)entry.Value; if (Path.GetExtension(name) != ".baml") { return; } baml = BamlReader.ReadDocument(stream); stream.Position = 0; foreach (BamlRecord record in baml) { if (record.Type == BamlRecordType.TypeInfo) { TypeInfoRecord typeInfo = (TypeInfoRecord)record; typeName = typeInfo.TypeFullName; break; } if (record.Type == BamlRecordType.ElementStart) { break; } } }
void Decompile(ModuleDef module, BamlDocument document, Language lang, ITextOutput output, out IHighlightingDefinition highlight, CancellationToken token) { var decompiler = new XamlDecompiler(); var xaml = decompiler.Decompile(module, document, token); output.Write(xaml.ToString(), TextTokenType.Text); highlight = HighlightingManager.Instance.GetDefinitionByExtension(".xml"); }
void Decompile(ModuleDef module, BamlDocument document, ILanguage lang, IDecompilerOutput output, CancellationToken token) { var decompiler = new XamlDecompiler(); var xaml = decompiler.Decompile(module, document, token, BamlDecompilerOptions.Create(lang), null); output.Write(xaml.ToString(), BoxedTextColor.Text); }
void Disassemble(ModuleDef module, BamlDocument document, ILanguage lang, ITextOutput output, out string ext, CancellationToken token) { var disassembler = new BamlDisassembler(lang, output, token); disassembler.Disassemble(module, document); ext = ".cs"; }
void Disassemble(ModuleDef module, BamlDocument document, Language lang, ITextOutput output, out IHighlightingDefinition highlight, CancellationToken token) { var disassembler = new BamlDisassembler(lang, output, token); disassembler.Disassemble(module, document); highlight = HighlightingManager.Instance.GetDefinitionByExtension(".cs"); }
void Decompile(ModuleDef module, BamlDocument document, ILanguage lang, ITextOutput output, out string ext, CancellationToken token) { var decompiler = new XamlDecompiler(); var xaml = decompiler.Decompile(module, document, token, BamlDecompilerOptions.Create(lang), null); output.Write(xaml.ToString(), TextTokenKind.Text); ext = ".xml"; }
void Decompile(ModuleDef module, BamlDocument document, Language lang, ITextOutput output, out IHighlightingDefinition highlight, CancellationToken token) { var decompiler = new XamlDecompiler(); var xaml = decompiler.Decompile(module, document, token); output.Write(xaml.ToString(), TextTokenType.Text); highlight = HighlightingManager.Instance.GetDefinitionByExtension(".xml"); }
void Decompile(ModuleDef module, BamlDocument document, ILanguage lang, ITextOutput output, out string ext, CancellationToken token) { var decompiler = new XamlDecompiler(); var xaml = decompiler.Decompile(module, document, token, BamlDecompilerOptions.Create(lang), null); output.Write(xaml.ToString(), TextTokenKind.Text); ext = ".xml"; }
void Decompile(ModuleDef module, BamlDocument document, IDecompiler lang, IDecompilerOutput output, CancellationToken token) { var decompiler = new XamlDecompiler(); var xaml = decompiler.Decompile(module, document, token, BamlDecompilerOptions.Create(lang), null); var xamlText = new XamlOutputCreator(xamlOutputOptionsProvider.Default).CreateText(xaml); documentWriterService.Write(output, xamlText, ContentTypes.Xaml); }
void BuildPIMappings(BamlDocument document) { foreach (var record in document) { var piMap = record as PIMappingRecord; if (piMap == null) continue; XmlNs.SetPIMapping(piMap.XmlNamespace, piMap.ClrNamespace, Baml.ResolveAssembly(piMap.AssemblyId)); } }
private static void AssertDocumentsAreEquivalent(BamlDocument actualDocument, BamlDocument expectedBamlDocument) { Assert.That(actualDocument, new BamlDocumentMatcher(expectedBamlDocument)); // Verify that we can parse the generated document byte[] actualDocumentBytes = BamlUtils.ToResourceBytes(actualDocument); BamlDocument newDocument = BamlUtils.FromResourceBytes(actualDocumentBytes); Assert.That(newDocument, new BamlDocumentMatcher(expectedBamlDocument)); }
private void PatchExistingGenericThemesXaml( ResourceWriter resourceWriter, BamlDocument bamlDocument, IEnumerable <string> genericThemeResources) { _logger.Info("Patching existing themes/generic.xaml"); _bamlGenerator.AddMergedDictionaries(bamlDocument, genericThemeResources); SetPreserializedData(resourceWriter, GenericThemesBamlName, BamlUtils.ToResourceBytes(bamlDocument)); }
public static byte[] ToResourceBytes(BamlDocument document) { using (var targetStream = new MemoryStream()) { BamlWriter.WriteDocument(document, targetStream); targetStream.Position = 0; return(BitConverter.GetBytes((int)targetStream.Length).Concat(targetStream.ToArray()).ToArray()); } }
public static byte[] ToResourceBytes(BamlDocument document) { using (var targetStream = new MemoryStream()) { BamlWriter.WriteDocument(document, targetStream); targetStream.Position = 0; return BitConverter.GetBytes((int)targetStream.Length).Concat(targetStream.ToArray()).ToArray(); } }
private static void AssertDocumentsAreEquivalent(BamlDocument actualDocument, BamlDocument expectedBamlDocument) { Assert.That(actualDocument, new BamlDocumentMatcher(expectedBamlDocument)); // Verify that we can parse the generated document byte[] actualDocumentBytes = BamlUtils.ToResourceBytes(actualDocument); BamlDocument newDocument = BamlUtils.FromResourceBytes(actualDocumentBytes); Assert.That(newDocument, new BamlDocumentMatcher(expectedBamlDocument)); }
public static XamlContext Construct(ModuleDef module, BamlDocument document, CancellationToken token) { var ctx = new XamlContext(module); ctx.CancellationToken = token; ctx.Baml = BamlContext.ConstructContext(module, document, token); ctx.RootNode = BamlNode.Parse(document, token); ctx.BuildPIMappings(document); ctx.BuildNodeMap(ctx.RootNode as BamlBlockNode, new RecursionCounter()); return ctx; }
private bool HaveSameVersion( string versionProperty, BamlDocument actualDocument, BamlDocument expectedDocument) { var actualVersion = (BamlDocument.BamlVersion)actualDocument.GetPropertyValue(versionProperty); var expectedVersion = (BamlDocument.BamlVersion)expectedDocument.GetPropertyValue(versionProperty); _context = versionProperty + ".Major"; if (!AreEqual(actualVersion.Major, actualVersion.Major)) return false; _context = versionProperty + ".Minor"; return AreEqual(actualVersion.Minor, expectedVersion.Minor); }
private byte[] GetProcessedResource(Res resource, AssemblyDefinition containingAssembly) { BamlDocument bamlDocument = BamlUtils.FromResourceBytes(resource.data); foreach (dynamic node in bamlDocument) { ProcessRecord(node, containingAssembly); } //TODO: diminishing return optimisation: remove duplications + update assembly ids return(BamlUtils.ToResourceBytes(bamlDocument)); }
void BuildPIMappings(BamlDocument document) { foreach (var record in document) { var piMap = record as PIMappingRecord; if (piMap is null) { continue; } XmlNs.SetPIMapping(piMap.XmlNamespace, piMap.ClrNamespace, Baml.ResolveAssembly(piMap.AssemblyId)); } }
public static XamlContext Construct(ModuleDef module, BamlDocument document, CancellationToken token) { var ctx = new XamlContext(module); ctx.CancellationToken = token; ctx.Baml = BamlContext.ConstructContext(module, document, token); ctx.RootNode = BamlNode.Parse(document, token); ctx.BuildPIMappings(document); ctx.BuildNodeMap(ctx.RootNode as BamlBlockNode, new RecursionCounter()); return(ctx); }
void AnalyzeResources(ConfuserContext context, INameService service, ModuleDefMD module) { if (analyzer == null) { analyzer = new BAMLAnalyzer(context, service); analyzer.AnalyzeElement += AnalyzeBAMLElement; } var wpfResInfo = new Dictionary <string, Dictionary <string, BamlDocument> >(); foreach (EmbeddedResource res in module.Resources.OfType <EmbeddedResource>()) { Match match = ResourceNamePattern.Match(res.Name); if (!match.Success) { continue; } var resInfo = new Dictionary <string, BamlDocument>(); res.Data.Position = 0; var reader = new ResourceReader(new ImageStream(res.Data)); IDictionaryEnumerator enumerator = reader.GetEnumerator(); while (enumerator.MoveNext()) { var name = (string)enumerator.Key; if (!name.EndsWith(".baml")) { continue; } string typeName; byte[] data; reader.GetResourceData(name, out typeName, out data); BamlDocument document = analyzer.Analyze(module, name, data); document.DocumentName = name; resInfo.Add(name, document); } if (resInfo.Count > 0) { wpfResInfo.Add(res.Name, resInfo); } } if (wpfResInfo.Count > 0) { context.Annotations.Set(module, BAMLKey, wpfResInfo); } }
private bool HaveSameVersion( string versionProperty, BamlDocument actualDocument, BamlDocument expectedDocument) { var actualVersion = (BamlDocument.BamlVersion)actualDocument.GetPropertyValue(versionProperty); var expectedVersion = (BamlDocument.BamlVersion)expectedDocument.GetPropertyValue(versionProperty); _context = versionProperty + ".Major"; if (!AreEqual(actualVersion.Major, actualVersion.Major)) { return(false); } _context = versionProperty + ".Minor"; return(AreEqual(actualVersion.Minor, expectedVersion.Minor)); }
public static XamlContext Construct(IDecompilerTypeSystem typeSystem, BamlDocument document, CancellationToken token, BamlDecompilerOptions bamlDecompilerOptions) { var ctx = new XamlContext(typeSystem); ctx.CancellationToken = token; ctx.BamlDecompilerOptions = bamlDecompilerOptions ?? new BamlDecompilerOptions(); ctx.Baml = BamlContext.ConstructContext(typeSystem, document, token); ctx.RootNode = BamlNode.Parse(document, token); ctx.BuildPIMappings(document); ctx.BuildNodeMap(ctx.RootNode as BamlBlockNode); return(ctx); }
public XDocument Decompile(ModuleDef module, BamlDocument document, CancellationToken token) { var ctx = XamlContext.Construct(module, document, token); var handler = HandlerMap.LookupHandler(ctx.RootNode.Type); var elem = handler.Translate(ctx, ctx.RootNode, null); var xaml = new XDocument(); xaml.Add(elem.Xaml.Element); foreach (var pass in rewritePasses) { token.ThrowIfCancellationRequested(); pass.Run(ctx, xaml); } return xaml; }
private byte[] GetProcessedResource(Res resource, AssemblyDefinition containingAssembly) { BamlDocument bamlDocument = BamlUtils.FromResourceBytes(resource.data); foreach (BamlRecord node in bamlDocument) { ProcessRecord(node as PropertyWithConverterRecord, containingAssembly); ProcessRecord(node as TextWithConverterRecord, containingAssembly); ProcessRecord(node as AssemblyInfoRecord, containingAssembly); ProcessRecord(node as XmlnsPropertyRecord, containingAssembly); ProcessRecord(node as TypeInfoRecord, containingAssembly); } //TODO: diminishing return optimisation: remove duplications + update assembly ids return(BamlUtils.ToResourceBytes(bamlDocument)); }
private void ParseBamlForRefSign(BamlDocument baml, string keyToken, string replaceToken = "null") { foreach (var brecord in baml) { if (brecord.Type == BamlRecordType.AssemblyInfo) { var r = (AssemblyInfoRecord)brecord; var name = r.AssemblyFullName; if (!name.Contains("PublicKeyToken=" + keyToken)) { continue; } r.AssemblyFullName = name.Replace(keyToken, replaceToken); } } }
private byte[] GetProcessedResource(Res resource, AssemblyDefinition containingAssembly) { BamlDocument bamlDocument = BamlUtils.FromResourceBytes(resource.data); foreach (BamlRecord node in bamlDocument) { Action <BamlRecord, AssemblyDefinition> recordProcessor; if (_nodeProcessors.TryGetValue(node.GetType(), out recordProcessor)) { recordProcessor(node, containingAssembly); } } //TODO: diminishing return optimisation: remove duplications + update assembly ids return(BamlUtils.ToResourceBytes(bamlDocument)); }
public XDocument Decompile(ModuleDef module, BamlDocument document, CancellationToken token, BamlDecompilerOptions bamlDecompilerOptions, List<string> assemblyReferences) { var ctx = XamlContext.Construct(module, document, token, bamlDecompilerOptions); var handler = HandlerMap.LookupHandler(ctx.RootNode.Type); var elem = handler.Translate(ctx, ctx.RootNode, null); var xaml = new XDocument(); xaml.Add(elem.Xaml.Element); foreach (var pass in rewritePasses) { token.ThrowIfCancellationRequested(); pass.Run(ctx, xaml); } if (assemblyReferences != null) assemblyReferences.AddRange(ctx.Baml.AssemblyIdMap.Select(a => a.Value.AssemblyFullName)); return xaml; }
private void AddAssemblyInfos(BamlDocument document) { var assemblyNames = new[] { "WindowsBase", "PresentationCore", "PresentationFramework" }; var references = _targetAssemblyReferences. Where(asm => assemblyNames.Any(prefix => asm.Name.Equals(prefix))); ushort assemblyId = 0; foreach (AssemblyNameReference reference in references) { document.Add(new AssemblyInfoRecord { AssemblyFullName = reference.FullName, AssemblyId = assemblyId }); ++assemblyId; } }
public XDocument Decompile(ModuleDef module, BamlDocument document, CancellationToken token) { var ctx = XamlContext.Construct(module, document, token); var handler = HandlerMap.LookupHandler(ctx.RootNode.Type); var elem = handler.Translate(ctx, ctx.RootNode, null); var xaml = new XDocument(); xaml.Add(elem.Xaml.Element); foreach (var pass in rewritePasses) { token.ThrowIfCancellationRequested(); pass.Run(ctx, xaml); } return(xaml); }
public static BamlElement Read(BamlDocument document) { Debug.Assert(document.Count > 0 && document[0].Type == BamlRecordType.DocumentStart); BamlElement current = null; var stack = new Stack<BamlElement>(); for (int i = 0; i < document.Count; i++) { if (IsHeader(document[i])) { BamlElement prev = current; current = new BamlElement(); current.Header = document[i]; current.Body = new List<BamlRecord>(); current.Children = new List<BamlElement>(); if (prev != null) { prev.Children.Add(current); current.Parent = prev; stack.Push(prev); } } else if (IsFooter(document[i])) { if (current == null) throw new Exception("Unexpected footer."); while (!IsMatch(current.Header, document[i])) { // End record can be omited (sometimes). if (stack.Count > 0) current = stack.Pop(); } current.Footer = document[i]; if (stack.Count > 0) current = stack.Pop(); } else current.Body.Add(document[i]); } Debug.Assert(stack.Count == 0); return current; }
public void AddMergedDictionaries( BamlDocument document, IEnumerable <string> importedFiles) { BamlRecord mergedDictionaryRecord = document.FirstOrDefault(IsMergedDictionaryAttribute); if (mergedDictionaryRecord != null) { HandleMergedDictionary(document, importedFiles, mergedDictionaryRecord as AttributeInfoRecord); } else { if (document.FindIndex(IsResourceDictionaryElementStart) == -1) { //TODO: throw? (Let's hope people read the logs ^_^) _logger.Error(string.Format( "Existing 'Themes/generic.xaml' in {0} is *not* a ResourceDictionary. " + "This will prevent proper WPF application merging.", _mainAssemblyName)); return; } int attributeInfosStartIndex = document.FindLastIndex(r => r is AssemblyInfoRecord); if (attributeInfosStartIndex == -1) { _logger.Error("Invalid BAML detected. (no AssemblyInfoRecord)"); return; } var extraAttributes = GetMergedDictionariesAttributes().ToList(); AdjustAttributeIds(document, (ushort)extraAttributes.Count); document.InsertRange(attributeInfosStartIndex + 1, extraAttributes); int defferableRecordIndex = document.FindIndex(r => r is DeferableContentStartRecord); if (attributeInfosStartIndex == -1) { _logger.Error("Invalid BAML detected. (No DeferableContentStartRecord)"); } document.InsertRange(defferableRecordIndex, GetDictionariesList(importedFiles)); } }
public BamlDocument GenerateThemesGenericXaml(IEnumerable <string> importedFiles) { BamlDocument document = new BamlDocument { Signature = "MSBAML", ReaderVersion = BamlVersion, WriterVersion = BamlVersion, UpdaterVersion = BamlVersion }; document.Add(new DocumentStartRecord()); AddAssemblyInfos(document); document.AddRange(GetMergedDictionariesAttributes()); document.Add(new ElementStartRecord { TypeId = ResourceDictionaryTypeId }); document.Add(new XmlnsPropertyRecord { Prefix = string.Empty, XmlNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation", AssemblyIds = document.OfType <AssemblyInfoRecord>().Select(asm => asm.AssemblyId).ToArray() }); document.AddRange(GetDictionariesList(importedFiles)); ElementEndRecord lastEndRecord = new ElementEndRecord(); document.Add(new DeferableContentStartRecord { Record = lastEndRecord }); document.Add(lastEndRecord); document.Add(new DocumentEndRecord()); return(document); }
public BamlDocument GenerateThemesGenericXaml(IEnumerable<string> importedFiles) { BamlDocument document = new BamlDocument { Signature = "MSBAML", ReaderVersion = BamlVersion, WriterVersion = BamlVersion, UpdaterVersion = BamlVersion }; document.Add(new DocumentStartRecord()); AddAssemblyInfos(document); document.AddRange(GetMergedDictionariesAttributes()); document.Add(new ElementStartRecord { TypeId = ResourceDictionaryTypeId }); document.Add(new XmlnsPropertyRecord { Prefix = string.Empty, XmlNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation", AssemblyIds = document.OfType<AssemblyInfoRecord>().Select(asm => asm.AssemblyId).ToArray() }); document.AddRange(GetDictionariesList(importedFiles)); ElementEndRecord lastEndRecord = new ElementEndRecord(); document.Add(new DeferableContentStartRecord { Record = lastEndRecord }); document.Add(lastEndRecord); document.Add(new DocumentEndRecord()); return document; }
private static void AdjustAttributeIds(BamlDocument document, ushort offset) { const string AttributeIdPropertyName = "AttributeId"; var existingAttributeInfoRecords = document.OfType <AttributeInfoRecord>().ToList(); foreach (var record in document) { ushort?attributeId = record.TryGetPropertyValue(AttributeIdPropertyName) as ushort?; if (attributeId == null || record is AttributeInfoRecord || !existingAttributeInfoRecords.Any(r => r.AttributeId == attributeId)) { continue; } record.TrySetPropertyValue(AttributeIdPropertyName, (ushort)(attributeId.Value + offset)); } foreach (var attributeInfoRecord in existingAttributeInfoRecords) { attributeInfoRecord.AttributeId += offset; } }
public XDocument Decompile(IDecompilerTypeSystem typeSystem, BamlDocument document, CancellationToken token, BamlDecompilerOptions bamlDecompilerOptions, List <string> assemblyReferences) { var ctx = XamlContext.Construct(typeSystem, document, token, bamlDecompilerOptions); var handler = HandlerMap.LookupHandler(ctx.RootNode.Type); var elem = handler.Translate(ctx, ctx.RootNode, null); var xaml = new XDocument(); xaml.Add(elem.Xaml.Element); foreach (var pass in rewritePasses) { token.ThrowIfCancellationRequested(); pass.Run(ctx, xaml); } if (assemblyReferences != null) { assemblyReferences.AddRange(ctx.Baml.AssemblyIdMap.Select(a => a.Value.AssemblyFullName)); } return(xaml); }
private void HandleMergedDictionary( BamlDocument document, IEnumerable <string> importedFiles, AttributeInfoRecord mergedDictionariesRecord) { int indexStart = document.FindIndex( r => r is PropertyListStartRecord && ((PropertyListStartRecord)r).AttributeId == mergedDictionariesRecord.AttributeId); int insertIndex = indexStart + 1; if (document[insertIndex] is LineNumberAndPositionRecord) { insertIndex++; } List <string> existingUris = document.Skip(indexStart) .TakeWhile(r => !(r is PropertyListEndRecord)) .OfType <PropertyWithConverterRecord>() .Select(GetFileNameFromPropertyRecord) .ToList(); document.InsertRange(insertIndex, GetImportRecords(importedFiles.Except(existingUris))); }
private void HandleMergedDictionary( BamlDocument document, IEnumerable<string> importedFiles, AttributeInfoRecord mergedDictionariesRecord) { int indexStart = document.FindIndex( r => r is PropertyListStartRecord && ((PropertyListStartRecord)r).AttributeId == mergedDictionariesRecord.AttributeId); int insertIndex = indexStart + 1; if (document[insertIndex] is LineNumberAndPositionRecord) insertIndex++; List<string> existingUris = document.Skip(indexStart) .TakeWhile(r => !(r is PropertyListEndRecord)) .OfType<PropertyWithConverterRecord>() .Select(GetFileNameFromPropertyRecord) .ToList(); document.InsertRange(insertIndex, GetImportRecords(importedFiles.Except(existingUris))); }
public void WriteDefer(BamlDocument doc, int index, BinaryWriter wtr) { wtr.BaseStream.Seek(pos, SeekOrigin.Begin); wtr.Write((uint)(Record.Position - (pos + 4))); }
public void ReadDefer(BamlDocument doc, int index, Func<long, BamlRecord> resolve) { Record = resolve(pos + size); }
static void NavigateTree(BamlDocument doc, BamlRecordType start, BamlRecordType end, ref int index) { index++; while (true) { if (doc[index].Type == start) NavigateTree(doc, start, end, ref index); else if (doc[index].Type == end) return; index++; } }
public void WriteDefer(BamlDocument doc, int index, BinaryWriter wtr) { bool keys = true; do { switch (doc[index].Type) { case BamlRecordType.DefAttributeKeyString: case BamlRecordType.DefAttributeKeyType: case BamlRecordType.OptimizedStaticResource: keys = true; break; case BamlRecordType.StaticResourceStart: NavigateTree(doc, BamlRecordType.StaticResourceStart, BamlRecordType.StaticResourceEnd, ref index); keys = true; break; case BamlRecordType.KeyElementStart: NavigateTree(doc, BamlRecordType.KeyElementStart, BamlRecordType.KeyElementEnd, ref index); keys = true; break; default: keys = false; index--; break; } index++; } while (keys); wtr.BaseStream.Seek(pos, SeekOrigin.Begin); wtr.Write((uint)(Record.Position - doc[index].Position)); }
public void ReadDefer(BamlDocument doc, int index, Func<long, BamlRecord> resolve) { bool keys = true; do { switch (doc[index].Type) { case BamlRecordType.DefAttributeKeyString: case BamlRecordType.DefAttributeKeyType: case BamlRecordType.OptimizedStaticResource: keys = true; break; case BamlRecordType.StaticResourceStart: NavigateTree(doc, BamlRecordType.StaticResourceStart, BamlRecordType.StaticResourceEnd, ref index); keys = true; break; case BamlRecordType.KeyElementStart: NavigateTree(doc, BamlRecordType.KeyElementStart, BamlRecordType.KeyElementEnd, ref index); keys = true; break; default: keys = false; index--; break; } index++; } while (keys); Record = resolve(doc[index].Position + pos); }
private void AddAssemblyInfos(BamlDocument document) { var assemblyNames = new[] { "WindowsBase", "PresentationCore", "PresentationFramework" }; var references = _targetAssemblyReferences. Where(asm => assemblyNames.Any(prefix => asm.Name.Equals(prefix))); ushort assemblyId = 0; foreach (AssemblyNameReference reference in references) { document.Add(new AssemblyInfoRecord { AssemblyFullName = reference.FullName, AssemblyId = assemblyId }); ++assemblyId; } }
public void AddMergedDictionaries( BamlDocument document, IEnumerable<string> importedFiles) { BamlRecord mergedDictionaryRecord = document.FirstOrDefault(IsMergedDictionaryAttribute); if (mergedDictionaryRecord != null) { HandleMergedDictionary(document, importedFiles, mergedDictionaryRecord as AttributeInfoRecord); } else { if (document.FindIndex(IsResourceDictionaryElementStart) == -1) { //TODO: throw? (Let's hope people read the logs ^_^) _logger.Error(string.Format( "Existing 'Themes/generic.xaml' in {0} is *not* a ResourceDictionary. " + "This will prevent proper WPF application merging.", _mainAssemblyName)); return; } int attributeInfosStartIndex = document.FindLastIndex(r => r is AssemblyInfoRecord); if (attributeInfosStartIndex == -1) { _logger.Error("Invalid BAML detected. (no AssemblyInfoRecord)"); return; } var extraAttributes = GetMergedDictionariesAttributes().ToList(); AdjustAttributeIds(document, (ushort)extraAttributes.Count); document.InsertRange(attributeInfosStartIndex + 1, extraAttributes); int defferableRecordIndex = document.FindIndex(r => r is DeferableContentStartRecord); if (attributeInfosStartIndex == -1) { _logger.Error("Invalid BAML detected. (No DeferableContentStartRecord)"); } document.InsertRange(defferableRecordIndex, GetDictionariesList(importedFiles)); } }
private static void AdjustAttributeIds(BamlDocument document, ushort offset) { const string AttributeIdPropertyName = "AttributeId"; var existingAttributeInfoRecords = document.OfType<AttributeInfoRecord>().ToList(); foreach (var record in document) { ushort? attributeId = record.TryGetPropertyValue(AttributeIdPropertyName) as ushort?; if (attributeId == null || record is AttributeInfoRecord || !existingAttributeInfoRecords.Any(r => r.AttributeId == attributeId)) { continue; } record.TrySetPropertyValue(AttributeIdPropertyName, (ushort)(attributeId.Value + offset)); } foreach (var attributeInfoRecord in existingAttributeInfoRecords) { attributeInfoRecord.AttributeId += offset; } }
public XmlNsContext(BamlDocument doc, Dictionary<ushort, AssemblyDef> assemblyRefs) { this.doc = doc; this.assemblyRefs = new Dictionary<AssemblyDef, ushort>(); foreach (var entry in assemblyRefs) this.assemblyRefs[entry.Value] = entry.Key; for (int i = 0; i < doc.Count; i++) if (doc[i] is ElementStartRecord) { rootIndex = i + 1; break; } Debug.Assert(rootIndex != -1); }
private void PopulateReferences(BamlDocument document) { var clrNs = new Dictionary<string, List<Tuple<AssemblyDef, string>>>(); assemblyRefs.Clear(); foreach (AssemblyInfoRecord rec in document.OfType<AssemblyInfoRecord>()) { AssemblyDef assembly = context.Resolver.ResolveThrow(rec.AssemblyFullName, module); assemblyRefs.Add(rec.AssemblyId, assembly); if (!context.Modules.Any(m => m.Assembly == assembly)) continue; foreach (CustomAttribute attr in assembly.CustomAttributes.FindAll("System.Windows.Markup.XmlnsDefinitionAttribute")) { clrNs.AddListEntry( (UTF8String)attr.ConstructorArguments[0].Value, Tuple.Create(assembly, (string)(UTF8String)attr.ConstructorArguments[1].Value)); } } xmlnsCtx = new XmlNsContext(document, assemblyRefs); typeRefs.Clear(); foreach (TypeInfoRecord rec in document.OfType<TypeInfoRecord>()) { AssemblyDef assembly; var asmId = (short)(rec.AssemblyId & 0xfff); if (asmId == -1) assembly = things.FrameworkAssembly; else assembly = assemblyRefs[(ushort)asmId]; // WPF uses Assembly.GetType to load it, so if no assembly specified in the TypeSig, it must be in current assembly. AssemblyDef assemblyRef = module.Assembly == assembly ? null : context.Resolver.ResolveThrow(module.GetAssemblyRefs().Single(r => r.FullName == assembly.FullName), module); TypeSig typeSig = TypeNameParser.ParseAsTypeSigReflectionThrow(module, rec.TypeFullName, new DummyAssemblyRefFinder(assemblyRef)); typeRefs[rec.TypeId] = typeSig; AddTypeSigReference(typeSig, new BAMLTypeReference(typeSig, rec)); } attrRefs.Clear(); foreach (AttributeInfoRecord rec in document.OfType<AttributeInfoRecord>()) { TypeSig declType; if (typeRefs.TryGetValue(rec.OwnerTypeId, out declType)) { TypeDef type = declType.ToBasicTypeDefOrRef().ResolveTypeDefThrow(); attrRefs[rec.AttributeId] = AnalyzeAttributeReference(type, rec); } else { Debug.Assert((short)rec.OwnerTypeId < 0); TypeDef declTypeDef = things.Types((KnownTypes)(-(short)rec.OwnerTypeId)); attrRefs[rec.AttributeId] = AnalyzeAttributeReference(declTypeDef, rec); } } strings.Clear(); foreach (StringInfoRecord rec in document.OfType<StringInfoRecord>()) { strings[rec.StringId] = rec; } foreach (PIMappingRecord rec in document.OfType<PIMappingRecord>()) { var asmId = (short)(rec.AssemblyId & 0xfff); AssemblyDef assembly; if (asmId == -1) assembly = things.FrameworkAssembly; else assembly = assemblyRefs[(ushort)asmId]; Tuple<AssemblyDef, string> scope = Tuple.Create(assembly, rec.ClrNamespace); clrNs.AddListEntry(rec.XmlNamespace, scope); } xmlns.Clear(); foreach (XmlnsPropertyRecord rec in document.OfType<XmlnsPropertyRecord>()) { List<Tuple<AssemblyDef, string>> clrMap; if (clrNs.TryGetValue(rec.XmlNamespace, out clrMap)) { xmlns[rec.Prefix] = clrMap; foreach (var scope in clrMap) xmlnsCtx.AddNsMap(scope, rec.Prefix); } } }
public static BamlDocument ReadDocument(Stream str) { var ret = new BamlDocument(); var reader = new BamlBinaryReader(str); { var rdr = new BinaryReader(str, Encoding.Unicode); uint len = rdr.ReadUInt32(); ret.Signature = new string(rdr.ReadChars((int)(len >> 1))); rdr.ReadBytes((int)(((len + 3) & ~3) - len)); } if (ret.Signature != "MSBAML") throw new NotSupportedException(); ret.ReaderVersion = new BamlDocument.BamlVersion { Major = reader.ReadUInt16(), Minor = reader.ReadUInt16() }; ret.UpdaterVersion = new BamlDocument.BamlVersion { Major = reader.ReadUInt16(), Minor = reader.ReadUInt16() }; ret.WriterVersion = new BamlDocument.BamlVersion { Major = reader.ReadUInt16(), Minor = reader.ReadUInt16() }; if (ret.ReaderVersion.Major != 0 || ret.ReaderVersion.Minor != 0x60 || ret.UpdaterVersion.Major != 0 || ret.UpdaterVersion.Minor != 0x60 || ret.WriterVersion.Major != 0 || ret.WriterVersion.Minor != 0x60) throw new NotSupportedException(); var recs = new Dictionary<long, BamlRecord>(); while (str.Position < str.Length) { long pos = str.Position; var type = (BamlRecordType)reader.ReadByte(); BamlRecord rec = null; switch (type) { case BamlRecordType.AssemblyInfo: rec = new AssemblyInfoRecord(); break; case BamlRecordType.AttributeInfo: rec = new AttributeInfoRecord(); break; case BamlRecordType.ConstructorParametersStart: rec = new ConstructorParametersStartRecord(); break; case BamlRecordType.ConstructorParametersEnd: rec = new ConstructorParametersEndRecord(); break; case BamlRecordType.ConstructorParameterType: rec = new ConstructorParameterTypeRecord(); break; case BamlRecordType.ConnectionId: rec = new ConnectionIdRecord(); break; case BamlRecordType.ContentProperty: rec = new ContentPropertyRecord(); break; case BamlRecordType.DefAttribute: rec = new DefAttributeRecord(); break; case BamlRecordType.DefAttributeKeyString: rec = new DefAttributeKeyStringRecord(); break; case BamlRecordType.DefAttributeKeyType: rec = new DefAttributeKeyTypeRecord(); break; case BamlRecordType.DeferableContentStart: rec = new DeferableContentStartRecord(); break; case BamlRecordType.DocumentEnd: rec = new DocumentEndRecord(); break; case BamlRecordType.DocumentStart: rec = new DocumentStartRecord(); break; case BamlRecordType.ElementEnd: rec = new ElementEndRecord(); break; case BamlRecordType.ElementStart: rec = new ElementStartRecord(); break; case BamlRecordType.KeyElementEnd: rec = new KeyElementEndRecord(); break; case BamlRecordType.KeyElementStart: rec = new KeyElementStartRecord(); break; case BamlRecordType.LineNumberAndPosition: rec = new LineNumberAndPositionRecord(); break; case BamlRecordType.LinePosition: rec = new LinePositionRecord(); break; case BamlRecordType.LiteralContent: rec = new LiteralContentRecord(); break; case BamlRecordType.NamedElementStart: rec = new NamedElementStartRecord(); break; case BamlRecordType.OptimizedStaticResource: rec = new OptimizedStaticResourceRecord(); break; case BamlRecordType.PIMapping: rec = new PIMappingRecord(); break; case BamlRecordType.PresentationOptionsAttribute: rec = new PresentationOptionsAttributeRecord(); break; case BamlRecordType.Property: rec = new PropertyRecord(); break; case BamlRecordType.PropertyArrayEnd: rec = new PropertyArrayEndRecord(); break; case BamlRecordType.PropertyArrayStart: rec = new PropertyArrayStartRecord(); break; case BamlRecordType.PropertyComplexEnd: rec = new PropertyComplexEndRecord(); break; case BamlRecordType.PropertyComplexStart: rec = new PropertyComplexStartRecord(); break; case BamlRecordType.PropertyCustom: rec = new PropertyCustomRecord(); break; case BamlRecordType.PropertyDictionaryEnd: rec = new PropertyDictionaryEndRecord(); break; case BamlRecordType.PropertyDictionaryStart: rec = new PropertyDictionaryStartRecord(); break; case BamlRecordType.PropertyListEnd: rec = new PropertyListEndRecord(); break; case BamlRecordType.PropertyListStart: rec = new PropertyListStartRecord(); break; case BamlRecordType.PropertyStringReference: rec = new PropertyStringReferenceRecord(); break; case BamlRecordType.PropertyTypeReference: rec = new PropertyTypeReferenceRecord(); break; case BamlRecordType.PropertyWithConverter: rec = new PropertyWithConverterRecord(); break; case BamlRecordType.PropertyWithExtension: rec = new PropertyWithExtensionRecord(); break; case BamlRecordType.PropertyWithStaticResourceId: rec = new PropertyWithStaticResourceIdRecord(); break; case BamlRecordType.RoutedEvent: rec = new RoutedEventRecord(); break; case BamlRecordType.StaticResourceEnd: rec = new StaticResourceEndRecord(); break; case BamlRecordType.StaticResourceId: rec = new StaticResourceIdRecord(); break; case BamlRecordType.StaticResourceStart: rec = new StaticResourceStartRecord(); break; case BamlRecordType.StringInfo: rec = new StringInfoRecord(); break; case BamlRecordType.Text: rec = new TextRecord(); break; case BamlRecordType.TextWithConverter: rec = new TextWithConverterRecord(); break; case BamlRecordType.TextWithId: rec = new TextWithIdRecord(); break; case BamlRecordType.TypeInfo: rec = new TypeInfoRecord(); break; case BamlRecordType.TypeSerializerInfo: rec = new TypeSerializerInfoRecord(); break; case BamlRecordType.XmlnsProperty: rec = new XmlnsPropertyRecord(); break; case BamlRecordType.XmlAttribute: case BamlRecordType.ProcessingInstruction: case BamlRecordType.LastRecordType: case BamlRecordType.EndAttributes: case BamlRecordType.DefTag: case BamlRecordType.ClrEvent: case BamlRecordType.Comment: default: throw new NotSupportedException(); } rec.Position = pos; rec.Read(reader); ret.Add(rec); recs.Add(pos, rec); } for (int i = 0; i < ret.Count; i++) { var defer = ret[i] as IBamlDeferRecord; if (defer != null) defer.ReadDefer(ret, i, _ => recs[_]); } return ret; }
void Disassemble(ModuleDef module, BamlDocument document, Language lang, ITextOutput output, out IHighlightingDefinition highlight, CancellationToken token) { var disassembler = new BamlDisassembler(lang, output, token); disassembler.Disassemble(module, document); highlight = HighlightingManager.Instance.GetDefinitionByExtension(".cs"); }
public BamlTypeExtReference(PropertyWithConverterRecord rec, BamlDocument doc, string assembly) { this.rec = rec; this.doc = doc; this.assembly = assembly; }
private void ProcessBaml(ModuleDefinition mod, Dictionary<string, BamlDocument> bamls, ref int cc, DictionaryEntry entry, Stream stream) { cc++; docName = entry.Key as string; doc = BamlReader.ReadDocument(stream); (mod as IAnnotationProvider).Annotations[RenMode] = NameMode.Letters; for (int i = 0; i < doc.Count; i++) { if (doc[i] is LineNumberAndPositionRecord || doc[i] is LinePositionRecord) { doc.RemoveAt(i); i--; } } int asmId = -1; Dictionary<ushort, AssemblyDefinition> asms = new Dictionary<ushort, AssemblyDefinition>(); foreach (var rec in doc.OfType<AssemblyInfoRecord>()) { AssemblyNameReference nameRef = AssemblyNameReference.Parse(rec.AssemblyFullName); if (nameRef.Name == mod.Assembly.Name.Name) { asmId = rec.AssemblyId; rec.AssemblyFullName = GetBamlAssemblyFullName(mod.Assembly.Name); asms.Add(rec.AssemblyId, mod.Assembly); PopulateMembers(mod.Assembly); nameRef = null; } else { bool added = false; foreach (var i in ivtMap) if (i.Key.Name.Name == nameRef.Name) { rec.AssemblyFullName = GetBamlAssemblyFullName(i.Key.Name); asms.Add(rec.AssemblyId, i.Key); PopulateMembers(i.Key); nameRef = null; added = true; break; } if (!added) { var asmRefDef = GlobalAssemblyResolver.Instance.Resolve(nameRef); if (asmRefDef != null) { PopulateMembers(asmRefDef); } } } } Dictionary<ushort, TypeDefinition> types = new Dictionary<ushort, TypeDefinition>(); foreach (var rec in doc.OfType<TypeInfoRecord>()) { AssemblyDefinition asm; if (asms.TryGetValue((ushort)(rec.AssemblyId & 0xfff), out asm)) { TypeReference type = TypeParser.ParseType(asm.MainModule, rec.TypeFullName); if (type != null) { types.Add(rec.TypeId, type.Resolve()); AddTypeRenRefs(type, type, rec); rec.TypeFullName = TypeParser.ToParseable(type); } } } Dictionary<string, string> xmlns = new Dictionary<string, string>(); foreach (var rec in doc.OfType<XmlnsPropertyRecord>()) xmlns[rec.Prefix] = rec.XmlNamespace; Dictionary<ushort, string> ps = new Dictionary<ushort, string>(); foreach (var rec in doc.OfType<AttributeInfoRecord>()) { if (types.ContainsKey(rec.OwnerTypeId)) { PropertyDefinition prop = types[rec.OwnerTypeId].Properties.SingleOrDefault(p => p.Name == rec.Name); if (prop != null) { ((prop as IAnnotationProvider).Annotations[RenRef] as List<IReference>).Add(new BamlAttributeReference(rec)); } EventDefinition evt = types[rec.OwnerTypeId].Events.SingleOrDefault(p => p.Name == rec.Name); if (evt != null) { ((evt as IAnnotationProvider).Annotations[RenRef] as List<IReference>).Add(new BamlAttributeReference(rec)); } FieldDefinition field = types[rec.OwnerTypeId].Fields.SingleOrDefault(p => p.Name == rec.Name); if (field != null) { ((field as IAnnotationProvider).Annotations[RenRef] as List<IReference>).Add(new BamlAttributeReference(rec)); } //Attached property MethodDefinition getM = types[rec.OwnerTypeId].Methods.SingleOrDefault(p => p.Name == "Get" + rec.Name); if (getM != null) { (getM as IAnnotationProvider).Annotations[RenOk] = false; } MethodDefinition setM = types[rec.OwnerTypeId].Methods.SingleOrDefault(p => p.Name == "Set" + rec.Name); if (setM != null) { (setM as IAnnotationProvider).Annotations[RenOk] = false; } } ps.Add(rec.AttributeId, rec.Name); } foreach (var rec in doc.OfType<PropertyWithConverterRecord>()) { if (rec.ConverterTypeId == 0xfd4c || ((short)rec.AttributeId > 0 && ps[rec.AttributeId] == "TypeName")) //TypeExtension { string type = rec.Value; string xmlNamespace; if (type.IndexOf(':') != -1) { xmlNamespace = xmlns[type.Substring(0, type.IndexOf(':'))]; type = type.Substring(type.IndexOf(':') + 1, type.Length - type.IndexOf(':') - 1); } else { xmlNamespace = xmlns[""]; } TypeDefinition typeDef; if ((typeDef = ResolveXmlns(xmlNamespace, type, mod.Assembly, asms.Values)) != null) { ((typeDef as IAnnotationProvider).Annotations[RenRef] as List<IReference>).Add(new BamlTypeExtReference(rec, doc, typeDef.Module.Assembly.Name.Name)); } } if (rec.ConverterTypeId == 0xff77 || rec.ConverterTypeId == 0xfe14 || rec.ConverterTypeId == 0xfd99) { ProcessProperty(rec, rec.Value); } } for (int i = 1; i < doc.Count; i++) { ElementStartRecord binding = doc[i - 1] as ElementStartRecord; ConstructorParametersStartRecord param = doc[i] as ConstructorParametersStartRecord; if (binding != null && param != null && binding.TypeId == 0xffec)//Binding { TextRecord path = doc[i + 1] as TextRecord; ProcessProperty(path, path.Value); } } var rootRec = doc.OfType<ElementStartRecord>().FirstOrDefault(); if (rootRec != null && types.ContainsKey(rootRec.TypeId)) { TypeDefinition root = types[rootRec.TypeId]; Dictionary<string, IMemberDefinition> m = new Dictionary<string, IMemberDefinition>(); foreach (PropertyDefinition prop in root.Properties) m.Add(prop.Name, prop); foreach (EventDefinition evt in root.Events) m.Add(evt.Name, evt); //foreach (MethodDefinition mtd in root.Methods) // mems.Add(mtd.Name, mtd); foreach (var rec in doc.OfType<PropertyRecord>()) { if (!(rec.Value is string)) continue; if (m.ContainsKey((string)rec.Value)) { ((m[(string)rec.Value] as IAnnotationProvider).Annotations[RenRef] as List<IReference>).Add(new BamlPropertyReference(rec)); } } } bamls.Add(entry.Key as string, doc); }
void Disassemble(ModuleDef module, BamlDocument document, IDecompilerOutput output, CancellationToken token) { var disassembler = new BamlDisassembler(output, token); disassembler.Disassemble(module, document); }