Esempio n. 1
0
        public dnModule(byte[] module, string fileName, ModuleContext ctx)
        {
            RawData      = module;
            ErrorMessage = null;
            Name         = Path.GetFileName(fileName);

            var creator = new dnModuleStreamCreator(module, fileName);

            try {
                Image = new PEImage(creator, ImageLayout.File, true);
            }
            catch (Exception ex) {
                ErrorMessage += string.Format("Error while loading PE Image:{0}{1}{0}{0}",
                                              Environment.NewLine, ex);

                Image = null;
                return;
            }

            try {
                MetaData = MetaDataCreator.CreateMetaData(Image);
            }
            catch (Exception ex) {
                ErrorMessage += string.Format("Error while loading MetaData:{0}{1}{0}{0}",
                                              Environment.NewLine, ex);

                MetaData = null;
                return;
            }

            try {
                ModuleDef = (ModuleDefMD)loadInternal.Invoke(null, new object[] {
                    MetaData, new ModuleCreationOptions {
                        TryToLoadPdbFromDisk = true,
                        Context = ctx
                    }
                });
                ModuleDef.EnableTypeDefFindCache = true;
            }
            catch (Exception ex) {
                ErrorMessage = string.Format("Error while loading ModuleDef:{0}{1}{0}{0}",
                                             Environment.NewLine, ex);

                ModuleDef = null;
                return;
            }

            if (ModuleDef.Assembly != null)
            {
                Name = ModuleDef.Assembly.Name;
            }
            else
            {
                Name = ModuleDef.Name;
            }
            if (string.IsNullOrEmpty(Name))
            {
                Name = Path.GetFileName(fileName);
            }
        }
Esempio n. 2
0
 public static IMetaData TryCreateMetadata(RawModuleBytes moduleData, bool isFileLayout)
 {
     try {
         return(MetaDataCreator.CreateMetaData(new PEImage((IntPtr)moduleData.Pointer, moduleData.Size, isFileLayout ? ImageLayout.File : ImageLayout.Memory, verify: true)));
     }
     catch (IOException) {
     }
     catch (BadImageFormatException) {
     }
     return(null);
 }
Esempio n. 3
0
 public static IMetaData TryCreateMetadata(byte[] data)
 {
     try {
         return(MetaDataCreator.CreateMetaData(new PEImage(data)));
     }
     catch (IOException) {
     }
     catch (BadImageFormatException) {
     }
     return(null);
 }
        static string GetId(byte[] module)
        {
            var md          = MetaDataCreator.CreateMetaData(new PEImage(module));
            var assemblyRow = md.TablesStream.ReadAssemblyRow(1);
            var assembly    = new AssemblyNameInfo();

            assembly.Name             = md.StringsStream.ReadNoNull(assemblyRow.Name);
            assembly.Culture          = md.StringsStream.ReadNoNull(assemblyRow.Locale);
            assembly.PublicKeyOrToken = new PublicKey(md.BlobStream.Read(assemblyRow.PublicKey));
            assembly.HashAlgId        = (AssemblyHashAlgorithm)assemblyRow.HashAlgId;
            assembly.Version          = new Version(assemblyRow.MajorVersion, assemblyRow.MinorVersion, assemblyRow.BuildNumber, assemblyRow.RevisionNumber);
            assembly.Attributes       = (AssemblyAttributes)assemblyRow.Flags;
            return(GetId(assembly));
        }
Esempio n. 5
0
        public bool MakePublic()
        {
            try {
                md = MetaDataCreator.CreateMetaData(new PEImage(data));
            }
            catch (BadImageFormatException) {
                return(false);
            }

            UpdateTypeDefTable();
            UpdateFieldTable();
            UpdateMethodTable();
            UpdateExportedTypeTable();

            return(true);
        }
Esempio n. 6
0
        static void InitializeExeFieldsFrom(IPEImage peImage, out bool isExe, out bool isDll, out DateTime?timestamp, ref string version, out string assemblySimpleName)
        {
            isExe = (peImage.ImageNTHeaders.FileHeader.Characteristics & Characteristics.Dll) == 0;
            isDll = !isExe;

            // Roslyn sets bit 31 if /deterministic is used (the low 31 bits is not a timestamp)
            if (peImage.ImageNTHeaders.FileHeader.TimeDateStamp < 0x80000000)
            {
                timestamp = Epoch.AddSeconds(peImage.ImageNTHeaders.FileHeader.TimeDateStamp);
            }
            else
            {
                timestamp = null;
            }

            try {
                if (string.IsNullOrEmpty(version))
                {
                    using (var mod = ModuleDefMD.Load(peImage)) {
                        if (string.IsNullOrEmpty(version))
                        {
                            version = mod.Assembly?.Version.ToString();
                        }
                        assemblySimpleName = UTF8String.ToSystemString(mod.Assembly?.Name);
                    }
                }
                else
                {
                    using (var md = MetaDataCreator.CreateMetaData(peImage)) {
                        var row = md.TablesStream.ReadAssemblyRow(1);
                        if (row == null)
                        {
                            assemblySimpleName = null;
                        }
                        else
                        {
                            assemblySimpleName = md.StringsStream.Read(row.Name);
                        }
                    }
                }
            }
            catch {
                assemblySimpleName = null;
            }
        }
Esempio n. 7
0
 private static byte[] ExtractSection(byte[] file)
 {
     try
     {
         var md     = MetaDataCreator.CreateMetaData(new PEImage(file));
         var stream = md.AllStreams.FirstOrDefault(s => s.Name == "#Koi");
         if (stream == null)
         {
             return(file);
         }
         var str = stream.GetClonedImageStream();
         return(str.ReadBytes((int)str.Length));
     }
     catch
     {
         return(file);
     }
 }
Esempio n. 8
0
        public override bool Execute()
        {
            if (string.IsNullOrWhiteSpace(IVTString))
            {
                Log.LogMessageFromText(nameof(IVTString) + " is an empty string", MessageImportance.High);
                return(false);
            }

            if (string.IsNullOrWhiteSpace(DestinationDirectory))
            {
                Log.LogMessageFromText(nameof(DestinationDirectory) + " is an empty string", MessageImportance.High);
                return(false);
            }

            var assembliesToFix = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (var tmp in AssembliesToMakePublic.Split(';'))
            {
                var asmName       = tmp.Trim();
                var asmSimpleName = asmName;
                int index         = asmSimpleName.IndexOf(',');
                if (index >= 0)
                {
                    asmSimpleName = asmSimpleName.Substring(0, index).Trim();
                }
                if (asmSimpleName.Length == 0)
                {
                    continue;
                }
                assembliesToFix.Add(asmSimpleName);
            }

            OutputReferencePath = new ITaskItem[ReferencePath.Length];
            byte[] ivtBlob = null;
            for (int i = 0; i < ReferencePath.Length; i++)
            {
                var file = ReferencePath[i];
                OutputReferencePath[i] = file;
                var filename = file.ItemSpec;
                if (!File.Exists(filename))
                {
                    Log.LogMessageFromText($"File does not exist: {filename}", MessageImportance.High);
                    return(false);
                }
                var fileExt       = Path.GetExtension(filename);
                var asmSimpleName = Path.GetFileNameWithoutExtension(filename);
                if (!assembliesToFix.Contains(asmSimpleName))
                {
                    continue;
                }

                var patchDir = DestinationDirectory;
                Directory.CreateDirectory(patchDir);

                var  fileInfo  = new FileInfo(filename);
                long filesize  = fileInfo.Length;
                long writeTime = fileInfo.LastWriteTimeUtc.ToBinary();

                var extraInfo       = $"_{VERSION} {filesize} {writeTime}_";
                var patchedFilename = Path.Combine(patchDir, asmSimpleName + extraInfo + fileExt);
                if (StringComparer.OrdinalIgnoreCase.Equals(patchedFilename, filename))
                {
                    continue;
                }

                if (!File.Exists(patchedFilename))
                {
                    if (ivtBlob == null)
                    {
                        ivtBlob = CreateIVTBlob(IVTString);
                    }
                    var data = File.ReadAllBytes(filename);
                    try {
                        using (var peImage = new PEImage(data, filename, ImageLayout.File, verify: true)) {
                            using (var md = MetaDataCreator.CreateMetaData(peImage, verify: true)) {
                                var result = new IVTPatcher(data, md, ivtBlob).Patch();
                                if (result != IVTPatcherResult.OK)
                                {
                                    string errMsg;
                                    switch (result)
                                    {
                                    case IVTPatcherResult.NoCustomAttributes:
                                        errMsg = $"Assembly '{asmSimpleName}' has no custom attributes";
                                        break;

                                    case IVTPatcherResult.NoIVTs:
                                        errMsg = $"Assembly '{asmSimpleName}' has no InternalsVisibleToAttributes";
                                        break;

                                    case IVTPatcherResult.IVTBlobTooSmall:
                                        errMsg = $"Assembly '{asmSimpleName}' has no InternalsVisibleToAttribute blob that is big enough to store '{IVTString}'. Use a shorter assembly name and/or a shorter public key, or skip PublicKey=xxxx... altogether (if it's a C# assembly)";
                                        break;

                                    default:
                                        Debug.Fail($"Unknown error result: {result}");
                                        errMsg = "Unknown error";
                                        break;
                                    }
                                    Log.LogMessageFromText(errMsg, MessageImportance.High);
                                    return(false);
                                }
                                try {
                                    File.WriteAllBytes(patchedFilename, data);
                                }
                                catch {
                                    try { File.Delete(patchedFilename); } catch { }
                                    throw;
                                }
                            }
                        }
                    }
                    catch (Exception ex) when(ex is IOException || ex is BadImageFormatException)
                    {
                        Log.LogMessageFromText($"File '{filename}' is not a .NET file", MessageImportance.High);
                        return(false);
                    }

                    var xmlDocFile = Path.ChangeExtension(filename, "xml");
                    if (File.Exists(xmlDocFile))
                    {
                        var newXmlDocFile = Path.ChangeExtension(patchedFilename, "xml");
                        if (File.Exists(newXmlDocFile))
                        {
                            File.Delete(newXmlDocFile);
                        }
                        File.Copy(xmlDocFile, newXmlDocFile);
                    }
                }

                OutputReferencePath[i] = new TaskItem(patchedFilename);
            }

            return(true);
        }
Esempio n. 9
0
        static DmdEcma335MetadataReader Create(DmdModuleImpl module, IPEImage peImage)
        {
            var metadata = MetaDataCreator.CreateMetaData(peImage);

            return(new DmdEcma335MetadataReader(module, metadata));
        }