static string ReadToken(EmbeddedResource resources, string token) { using (var resourceStream = resources.GetResourceStream()) using (var resourceSet = new ResourceSet(resourceStream)) return resourceSet.GetString(token, true); }
private bool InitResourceGridRows(EmbeddedResource er) { ResourceReader rr; try { rr = new ResourceReader(er.GetResourceStream()); } catch { rr = null; } if (rr == null) return false; DataRow dr; IDictionaryEnumerator de = rr.GetEnumerator(); int count = 0; while (de.MoveNext()) { dr = _dtResource.NewRow(); string name = de.Key as string; dr["no"] = count.ToString(); count++; dr["name"] = name; object value = de.Value; dr["type"] = value == null ? null : value.GetType().FullName; try { DataGridViewTextAndImageCellValue cv = new DataGridViewTextAndImageCellValue(name, value); cv.Image = ConvertToImage(name, value); dr["value"] = cv; } catch //(Exception ex) { dr["value"] = new DataGridViewTextAndImageCellValue(String.Empty, value); //dr["value"] = new DataGridViewTextAndImageCellValue(String.Empty, String.Format("Error: {0}", ex.Message)); //dr["type"] = "System.String"; } _dtResource.Rows.Add(dr); } rr.Close(); return true; }
private void CheckSatelliteResource (EmbeddedResource mainResource, EmbeddedResource satelliteResource, IMetadataTokenProvider satelliteAssembly) { using (Stream resourceStream = satelliteResource.GetResourceStream ()) using (ResourceSet resourceSet = new ResourceSet (resourceStream)) { foreach (DictionaryEntry entry in resourceSet) { string resourceName = (string) entry.Key; object satelliteValue = entry.Value; object mainValue; if (!mainAssemblyResourceCache.TryGetMainResource (mainResource, resourceName, out mainValue)) { Runner.Report (satelliteAssembly, Severity.Low, Confidence.High, String.Format ("The resource {0} in the file {1} exist in the satellite assembly but not in the main assembly", resourceName, satelliteResource.Name)); continue; } Type satelliteType = satelliteValue.GetType (); Type mainType = mainValue.GetType (); if (!satelliteType.Equals (mainType)) { Runner.Report (satelliteAssembly, Severity.High, Confidence.High, String.Format ("The resource {0} in the file {1} is of type {2} in the satellite assembly but of type {3} in the main assembly", resourceName, satelliteResource.Name, satelliteType, mainType)); continue; } if (satelliteType.Equals (typeof (string))) { Bitmask<int> mainParameters = GetStringFormatExpectedParameters ((string) mainValue); Bitmask<int> satelliteParameters = GetStringFormatExpectedParameters ((string) satelliteValue); if (!mainParameters.Equals (satelliteParameters)) Runner.Report (satelliteAssembly, Severity.High, Confidence.Normal, String.Format ("The string resource {0} in the file {1} does not use the same string format parameters in the satellite and main assemblies", resourceName, satelliteResource.Name)); } } } }
private static string[] GetRepackListFromResource(EmbeddedResource resource) { return (string[])new BinaryFormatter().Deserialize(resource.GetResourceStream()); }
byte[] decryptResource(EmbeddedResource resource) { using (var rsrcStream = resource.GetResourceStream()) { using (var reader = new BinaryReader(rsrcStream)) { var key = reader.ReadString(); var data = reader.ReadBytes((int)(rsrcStream.Length - rsrcStream.Position)); var cryptoTransform = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(key), IV = Encoding.ASCII.GetBytes(key), }.CreateDecryptor(); var memStream = new MemoryStream(data); using (var reader2 = new BinaryReader(new CryptoStream(memStream, cryptoTransform, CryptoStreamMode.Read))) { return reader2.ReadBytes((int)memStream.Length); } } } }
private void AddResource (EmbeddedResource resource) { if (embedded_resource_parser == null) { return; } if (Path.GetExtension (resource.Name) == ".resources") { using (var reader = new ResourceReader (resource.GetResourceStream ())) { foreach (DictionaryEntry re in reader) { if (embedded_resource_parser.SupportedFileExtensions.Contains (Path.GetExtension (re.Key as string))) { embedded_resource_parser.Add (re.Value as Stream, re.Key as string); } } } } else if (embedded_resource_parser.SupportedFileExtensions.Contains (Path.GetExtension(resource.Name))) { embedded_resource_parser.Add (resource.GetResourceStream (), resource.Name); } }
private void ProcessXamlResources(EmbeddedResource resource, ModuleDefinition module) { string targetDir = Path.GetDirectoryName(TargetPath); using (ResourceReader resourceReader = new ResourceReader(resource.GetResourceStream())) { foreach (System.Collections.DictionaryEntry resourceEntry in resourceReader) { string xamlResourceKey = Utilities.GetXamlResourceKey(resourceEntry, module); bool isBamlResource = ((string)resourceEntry.Key).EndsWith(".baml", StringComparison.OrdinalIgnoreCase); string xamlResourceRelativePath = xamlResourcesToPathsMap[xamlResourceKey]; string fullPath = Path.Combine(targetDir, xamlResourceRelativePath); string fullClassName = TryWriteBamlResource(fullPath, isBamlResource, resourceEntry.Value as UnmanagedMemoryStream); if (fullClassName != null) { fileGenContext.XamlFullNameToRelativePathMap.Add(fullClassName, xamlResourceRelativePath); } else { fileGenContext.OtherXamlResources.Add(new ProjectItemGroupResource() { Include = xamlResourceRelativePath }); } IFileGeneratedInfo args = new FileGeneratedInfo(fullPath, false); OnProjectFileCreated(args); } } }
private void ShowResource(EmbeddedResource er) { if (PathUtils.IsResourceExt(er.Name)) { if (InitResourceGridRows(er)) { //ShowDetailsControl(DetailTypes.Resources); if (_dtResource.Rows.Count == 0) { ShowText(String.Empty); } else { ShowText((string)null); } } else { ShowBinary(er, false); } } else if (ResourceFile.Default.IsTextResource(er.Name)) { ShowText(er.GetResourceStream(), null, false); } else if (PathUtils.IsIconExt(er.Name)) { Icon ico = new Icon(er.GetResourceStream()); pbResource.Image = ico.ToBitmap(); ShowDetailsControl(DetailTypes.ImageResource); } else if (PathUtils.IsCursorExt(er.Name)) { Cursor c = LoadCursor(er.GetResourceStream()); Bitmap bmp = ConvertToBitmap(c); pbResource.Image = bmp; ShowDetailsControl(DetailTypes.ImageResource); } else if (ResourceFile.Default.IsImageResource(er.Name)) { //wmf size is wrong with Image.FromStream //pbResource.Image = new Bitmap(er.GetResourceStream()); Bitmap bmp = new Bitmap(er.GetResourceStream()); pbResource.Image = bmp; //if (!ImageAnimator.CanAnimate(bmp)) //{ // pbResource.Image = bmp; //} //else //{ // pbResource.Image = new Bitmap(bmp.Width, bmp.Height); //} ShowDetailsControl(DetailTypes.ImageResource); } else { //always try to parse as .resources if (InitResourceGridRows(er)) { //ShowDetailsControl(DetailTypes.Resources); if (_dtResource.Rows.Count == 0) { ShowText(String.Empty); } else { ShowText((string)null); } } else { ShowBinary(er, false); } } }
/// <summary>Tries to load assembly for other assembly resources.</summary> /// <param name="resource">The resource.</param> /// <param name="guid">The GUID.</param> /// <returns>Loaded assembly image.</returns> private static byte[] TryLoadAssembly(EmbeddedResource resource, string guid) { var match = ResourceNameRx.Match(resource.Name); if (!match.Success || match.Groups["guid"].Value != guid) return null; try { var flags = match.Groups["flags"].Value; var size = int.Parse(match.Groups["size"].Value); var compressed = flags.Contains("z"); var buffer = new byte[size]; using (var rstream = resource.GetResourceStream()) { if (rstream == null) return null; using (var zstream = compressed ? new DeflateStream(rstream, CompressionMode.Decompress) : rstream) { zstream.Read(buffer, 0, size); } } return buffer; } catch { return null; } }
private bool TryCreateResXFile(EmbeddedResource embeddedResource, string resourceFilePath) { List<System.Collections.DictionaryEntry> resourceEntries = new List<System.Collections.DictionaryEntry>(); using (ResourceReader resourceReader = new ResourceReader(embeddedResource.GetResourceStream())) { IDictionaryEnumerator enumerator = resourceReader.GetEnumerator(); while (enumerator.MoveNext()) { try { resourceEntries.Add(enumerator.Entry); } catch (Exception ex) { if (ResourceWritingFailure != null) { ResourceWritingFailure(this, embeddedResource.Name, ex); } if (this.projectNotifier != null) { this.projectNotifier.OnResourceWritingFailure(embeddedResource.Name, ex); } } } } string dirPath = Path.GetDirectoryName(resourceFilePath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } #if !NET35 using (ResXResourceWriter resXWriter = new ResXResourceWriter(resourceFilePath, ResourceTypeNameConverter)) #else using (ResXResourceWriter resXWriter = new ResXResourceWriter(resourceFilePath)) #endif { foreach (System.Collections.DictionaryEntry resourceEntry in resourceEntries) { resXWriter.AddResource((string)resourceEntry.Key, resourceEntry.Value); } } return true; }
public void init(ResourceDecrypter resourceDecrypter) { if (decrypterType == null) return; encryptedResource = CoUtils.getResource(module, DotNetUtils.getCodeStrings(DotNetUtils.getMethod(decrypterType, ".cctor"))); constantsData = resourceDecrypter.decrypt(encryptedResource.GetResourceStream()); }
public void decrypt(ResourceDecrypter resourceDecrypter) { if (decryptMethod == null) return; resource = CoUtils.getResource(module, decrypterCctor); if (resource == null) return; var decrypted = resourceDecrypter.decrypt(resource.GetResourceStream()); var reader = new BinaryReader(new MemoryStream(decrypted)); int numEncrypted = reader.ReadInt32(); Log.v("Restoring {0} encrypted methods", numEncrypted); Log.indent(); for (int i = 0; i < numEncrypted; i++) { int delegateTypeToken = reader.ReadInt32(); uint codeOffset = reader.ReadUInt32(); var origOffset = reader.BaseStream.Position; reader.BaseStream.Position = codeOffset; decrypt(reader, delegateTypeToken); reader.BaseStream.Position = origOffset; } Log.deIndent(); }
byte[] getMethodsData(EmbeddedResource resource) { var reader = new BinaryReader(resource.GetResourceStream()); reader.BaseStream.Position = startOffset; if ((reader.ReadInt32() & 1) != 0) return decompress(reader); else return reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position)); }
public EmbeddedResource RemoveResource(EmbeddedResource er, string[] keys) { try { Cursor.Current = Cursors.WaitCursor; var rr = new ResourceReader(er.GetResourceStream()); var ms = new MemoryStream(); var rw = new ResourceWriter(ms); var de = rr.GetEnumerator(); while (de.MoveNext()) { string deKey = de.Key as string; bool toBeDeleted = false; foreach (string key in keys) { if (key == deKey) { toBeDeleted = true; break; } } if (toBeDeleted) continue; rw.AddResource(deKey, de.Value); } rw.Generate(); rw.Close(); rr.Close(); var newEr = new EmbeddedResource(er.Name, er.Attributes, ms.ToArray()); ms.Close(); return newEr; } catch { throw; } finally { Cursor.Current = Cursors.Default; } }
static XPathDocument GetExternalDescriptor (EmbeddedResource resource) { using (var sr = new StreamReader (resource.GetResourceStream ())) { return new XPathDocument (new StringReader (sr.ReadToEnd ())); } }
public EmbeddedResource ReplaceResource(EmbeddedResource er, string key, byte[] data) { try { Cursor.Current = Cursors.WaitCursor; var rr = new ResourceReader(er.GetResourceStream()); var ms = new MemoryStream(); var rw = new ResourceWriter(ms); var de = rr.GetEnumerator(); while (de.MoveNext()) { string deKey = de.Key as string; if (key == deKey) { object o = RestoreResourceObject(key, de.Value.GetType().FullName, data); rw.AddResource(key, o); } else { rw.AddResource(deKey, de.Value); } } rw.Generate(); rw.Close(); rr.Close(); var newEr = new EmbeddedResource(er.Name, er.Attributes, ms.ToArray()); ms.Close(); return newEr; } catch { throw; } finally { Cursor.Current = Cursors.Default; } }
private void SaveResourceFile(EmbeddedResource er, string outputFile) { byte[] bytes = er.GetResourceData(); using (FileStream fs = File.Create(outputFile)) { fs.Write(bytes, 0, bytes.Length); } _form.SetStatusText(String.Format("{0} saved.", outputFile)); if (PathUtils.IsResourceExt(outputFile)) { using (ResourceReader rr = new ResourceReader(er.GetResourceStream())) { string resxFile = Path.ChangeExtension(outputFile, ".resx"); using (ResXResourceWriter xw = new ResXResourceWriter(resxFile)) { IDictionaryEnumerator de = rr.GetEnumerator(); while (de.MoveNext()) { bool handled = false; if (de.Value != null) { Type type = de.Value.GetType(); if (type.FullName.EndsWith("Stream")) { Stream s = de.Value as Stream; if (s != null) { byte[] tmpBytes = new byte[s.Length]; if (s.CanSeek) s.Seek(0, SeekOrigin.Begin); s.Read(tmpBytes, 0, tmpBytes.Length); xw.AddResource(de.Key.ToString(), new MemoryStream(tmpBytes)); handled = true; } } } if (handled) continue; xw.AddResource(de.Key.ToString(), de.Value); } } } } else if (PathUtils.IsBamlExt(outputFile)) { try { using (StreamWriter sw = File.CreateText(Path.ChangeExtension(outputFile, ".xaml"))) { sw.WriteLine(_form.ResourceHandler.DecompileBaml(new MemoryStream(bytes))); } } catch (Exception ex) { _form.SetStatusText(String.Format("Failed to translate {0}: {1}", er.Name, ex.Message)); } } }
void rename(TypeDefinition type, EmbeddedResource resource) { newNames.Clear(); var resourceSet = ResourceReader.read(module, resource.GetResourceStream()); var renamed = new List<RenameInfo>(); foreach (var elem in resourceSet.ResourceElements) { if (nameChecker.isValidResourceKeyName(elem.Name)) { newNames.Add(elem.Name, true); continue; } renamed.Add(new RenameInfo(elem, getNewName(elem))); } if (renamed.Count == 0) return; rename(type, renamed); var outStream = new MemoryStream(); ResourceWriter.write(module, outStream, resourceSet); outStream.Position = 0; var newResource = new EmbeddedResource(resource.Name, resource.Attributes, outStream); int resourceIndex = module.Resources.IndexOf(resource); if (resourceIndex < 0) throw new ApplicationException("Could not find index of resource"); module.Resources[resourceIndex] = newResource; }
private static Dictionary<string, List<int>> GetIkvmExportsListsFromResource(EmbeddedResource extra) { Dictionary<string, List<int>> ikvmExportsLists = new Dictionary<string, List<int>>(); BinaryReader rdr = new BinaryReader(extra.GetResourceStream()); int assemblyCount = rdr.ReadInt32(); for (int i = 0; i < assemblyCount; i++) { var str = rdr.ReadString(); int typeCount = rdr.ReadInt32(); if (typeCount == 0) { ikvmExportsLists.Add(str, null); } else { var types = new List<int>(); ikvmExportsLists.Add(str, types); for (int j = 0; j < typeCount; j++) types.Add(rdr.ReadInt32()); } } return ikvmExportsLists; }
public void init(ResourceDecrypter resourceDecrypter) { if (decryptedData != null) return; var resourceName = getResourceName(); stringResource = DotNetUtils.getResource(module, resourceName) as EmbeddedResource; if (stringResource == null) return; Log.v("Adding string decrypter. Resource: {0}", Utils.toCsharpString(stringResource.Name)); decryptedData = resourceDecrypter.decrypt(stringResource.GetResourceStream()); }
private Resource FixResxResource( AssemblyDefinition containingAssembly, EmbeddedResource er, List<IResProcessor> resourcePrcessors, IEmbeddedResourceProcessor embeddedResourceProcessor) { MemoryStream stream = (MemoryStream)er.GetResourceStream(); var output = new MemoryStream((int)stream.Length); var rw = new ResourceWriter(output); using (var rr = new ResReader(stream)) { foreach (var res in rr) { foreach (var processor in resourcePrcessors) { if (processor.Process(containingAssembly, res, rr, rw)) break; } } } // do a final processing, if any, on the embeddedResource itself embeddedResourceProcessor?.Process(er, rw); rw.Generate(); output.Position = 0; return new EmbeddedResource(er.Name, er.Attributes, output); }
void dumpEmbeddedFile(EmbeddedResource resource, string assemblyName, string extension, string reason) { DeobfuscatedFile.createAssemblyFile(resourceDecrypter.decrypt(resource.GetResourceStream()), Utils.getAssemblySimpleName(assemblyName), extension); addResourceToBeRemoved(resource, reason); }
public bool TryGetMainResource (EmbeddedResource embeddedResource, string resourceName, out object value) { value = null; if (values == null) { // Build cache of resources values values = new Dictionary<EmbeddedResource, Dictionary<string, object>> (); } Dictionary<string, object> fileResources; if (!values.TryGetValue (embeddedResource, out fileResources)) { fileResources = new Dictionary<string, object> (); using (Stream resourceStream = embeddedResource.GetResourceStream ()) using (ResourceSet resourceSet = new ResourceSet (resourceStream)) { foreach (DictionaryEntry entry in resourceSet) fileResources.Add ((string) entry.Key, entry.Value); } values.Add (embeddedResource, fileResources); } return fileResources.TryGetValue (resourceName, out value); }