Exemple #1
0
        private static Mi.PE.Unmanaged.Export.Header GetExportFor(string file, PEFile pe)
        {
            var stream = new MemoryStream(File.ReadAllBytes(file));
            var reader = new BinaryStreamReader(stream, new byte[1024]);
            pe.ReadFrom(reader);

            var exportDirectory = pe.OptionalHeader.DataDirectories[(int)DataDirectoryKind.ExportSymbols];

            var rvaStream = new RvaStream(
                stream,
                pe.SectionHeaders.Select(
                s => new RvaStream.Range
                {
                    PhysicalAddress = s.PointerToRawData,
                    Size = s.VirtualSize,
                    VirtualAddress = s.VirtualAddress
                })
                .ToArray());

            rvaStream.Position = exportDirectory.VirtualAddress;

            var sectionReader = new BinaryStreamReader(rvaStream, new byte[32]);

            var exports = new Mi.PE.Unmanaged.Export.Header();
            exports.ReadExports(sectionReader, exportDirectory.Size);
            return exports;
        }
Exemple #2
0
        private static BaseRelocationBlock[] GetBaseRelocationsFor(string file, PEFile pe)
        {
            var stream = new MemoryStream(File.ReadAllBytes(file));
            var reader = new BinaryStreamReader(stream, new byte[1024]);
            pe.ReadFrom(reader);

            var baseRelocationDirectory = pe.OptionalHeader.DataDirectories[(int)DataDirectoryKind.BaseRelocation];

            var rvaStream = new RvaStream(
                stream,
                pe.SectionHeaders.Select(
                s => new RvaStream.Range
                {
                    PhysicalAddress = s.PointerToRawData,
                    Size = s.VirtualSize,
                    VirtualAddress = s.VirtualAddress
                })
                .ToArray());

            rvaStream.Position = baseRelocationDirectory.VirtualAddress;

            var sectionReader = new BinaryStreamReader(rvaStream, new byte[32]);

            var result = BaseRelocationBlock.ReadBlocks(sectionReader, baseRelocationDirectory.Size);
            return result;
        }
Exemple #3
0
        private static ModuleDefinition GetClrBasicsFor(string file, PEFile pe)
        {
            var stream = new MemoryStream(File.ReadAllBytes(file));
            var reader = new BinaryStreamReader(stream, new byte[1024]);
            pe.ReadFrom(reader);

            var clrDirectory = pe.OptionalHeader.DataDirectories[(int)DataDirectoryKind.Clr];

            var rvaStream = new RvaStream(
                stream,
                pe.SectionHeaders.Select(
                s => new RvaStream.Range
                {
                    PhysicalAddress = s.PointerToRawData,
                    Size = s.VirtualSize,
                    VirtualAddress = s.VirtualAddress
                })
                .ToArray());

            rvaStream.Position = clrDirectory.VirtualAddress;

            var sectionReader = new BinaryStreamReader(rvaStream, new byte[32]);

            var clrmod = new ModuleDefinition();
            ClrModuleReader.Read(sectionReader, clrmod);

            return clrmod;
        }
Exemple #4
0
        static void Main(string[] args)
        {
            string filename = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.System),
                "kernel32.dll");

            Console.WriteLine(Path.GetFileName(filename));
            var pe = new PEFile();
            var resources = GetResourcesFor(filename, pe);
            Print(resources);

            filename = typeof(int).Assembly.Location;

            Console.WriteLine(Path.GetFileName(filename));
            pe = new PEFile();
            resources = GetResourcesFor(filename, pe);
            Print(resources);

            filename = typeof(Program).Assembly.Location;

            Console.WriteLine(Path.GetFileName(filename));
            pe = new PEFile();
            resources = GetResourcesFor(filename, pe);
            Print(resources);

            filename = typeof(PEFile).Assembly.Location;

            Console.WriteLine(Path.GetFileName(filename));
            pe = new PEFile();
            resources = GetResourcesFor(filename, pe);
            Print(resources);
        }
Exemple #5
0
        static ResourceDirectory GetResourcesFor(string file, PEFile pe)
        {
            var stream = new MemoryStream(File.ReadAllBytes(file));
            var reader = new BinaryStreamReader(stream, new byte[1024]);
            pe.ReadFrom(reader);

            var resDataDir = pe.OptionalHeader.DataDirectories[(int)DataDirectoryKind.Resources];

            var rvaStream = new RvaStream(
                stream,
                pe.SectionHeaders.Select(
                s => new RvaStream.Range
                {
                    PhysicalAddress = s.PointerToRawData,
                    Size = s.VirtualSize,
                    VirtualAddress = s.VirtualAddress
                })
                .ToArray());

            rvaStream.Position = resDataDir.VirtualAddress;

            var sectionReader = new BinaryStreamReader(rvaStream, new byte[32]);

            var res = new ResourceDirectory();
            res.Read(sectionReader);

            return res;
        }
Exemple #6
0
        private async void openFileButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var pi = new FileOpenPicker();
                pi.SuggestedStartLocation = PickerLocationId.Downloads;
                pi.FileTypeFilter.Add(".dll");
                //{
                //    //SettingsIdentifier = "PE Viewer",
                //    SuggestedStartLocation = PickerLocationId.Downloads,
                //    ViewMode = PickerViewMode.List
                //};
                ////pi.FileTypeFilter.Add("DLL and EXE files|*.dll;*.exe");
                ////pi.FileTypeFilter.Add("All files|*.*");

                var fi = await pi.PickSingleFileAsync();

                var fiStream = await fi.OpenAsync(Windows.Storage.FileAccessMode.Read);
                var stream = fiStream.OpenRead();

                var buf = await ReadAll(stream);

                var bufStream = new MemoryStream(buf);

                var pe = new PEFile();
                pe.ReadFrom(new BinaryStreamReader(bufStream, new byte[32]));

                LayoutRoot.Children.Add(new PEFileView { DataContext = pe });
            }
            catch (Exception error)
            {
                openFileButton.Content = error;
            }
        }
Exemple #7
0
 static PEFile Read(byte[] bytes)
 {
     var stream = new MemoryStream(bytes);
     var reader = new BinaryStreamReader(stream, new byte[32]);
     var pe = new PEFile();
     pe.ReadFrom(reader);
     return pe;
 }
        public SectionHeaderListModel(PEFile peFile, PEHeaderModel peHeader, OptionalHeaderModel optionalHeader)
            : base("Section headers")
        {
            this.peFile = peFile;

            this.m_Items = new ReadOnlyObservableCollection<SectionHeaderModel>(itemsCore);

            BindAddressToOptionalHeader(optionalHeader);
            BindToPEHeader(peHeader);
        }
Exemple #9
0
        public MainPage()
        {
            InitializeComponent();

            var streamInfo = Application.GetResourceStream(new Uri("PEHeaderViewer.dll", UriKind.Relative));

            var reader = new BinaryStreamReader(streamInfo.Stream, new byte[32]);

            var pe = new PEFile();
            pe.ReadFrom(reader);

            {
                var tabControl = LayoutRoot.Children.OfType<TabControl>().FirstOrDefault();
                if (tabControl == null)
                {
                    tabControl = new TabControl();
                    LayoutRoot.Children.Add(tabControl);
                }

                var tabItem = new TabItem
                {
                    Header = "Self",
                    Content = new ScrollViewer
                    {
                        VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                        HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                        //Background = Brushes.White,
                        Padding = new Thickness(5),
                        Content = new PEFileView { DataContext = new PEFileViewModel(pe) }
                    }
                };

                tabControl.Items.Add(tabItem);

                tabControl.SelectedIndex = tabControl.Items.Count - 1;
            }

            this.Drop += new DragEventHandler(MainPage_Drop);

            if (Application.Current.IsRunningOutOfBrowser)
            {
                var timer = new DispatcherTimer
                {
                    Interval = TimeSpan.FromSeconds(1)
                };
                timer.Tick += delegate
                {
                    timer.Stop();

                    Application.Current.CheckAndDownloadUpdateAsync();
                };
            }
        }
Exemple #10
0
    private static void MeasureManyFilesLoad(string[] dllFiles)
    {
        var buffer = new byte[1024];

        var start = DateTime.UtcNow;
        foreach (var dll in dllFiles)
        {
            using (var dllStream = File.OpenRead(dll))
            {
                var pe = new PEFile();
                pe.ReadFrom(new BinaryStreamReader(dllStream, buffer));
            }
        }

        TimeSpan headersOnly = DateTime.UtcNow - start;

        byte[] buf = new byte[1024];
        byte[] contentBuf = new byte[1024*1024];
        start = DateTime.UtcNow;
        foreach (var dll in dllFiles)
        {
            using (var dllStream = File.OpenRead(dll))
            {
                var pe = new PEFile();
                var reader = new BinaryStreamReader(dllStream, buf);
                pe.ReadFrom(reader);

                while(reader.Position<dllStream.Length)
                {
                    reader.ReadBytes(contentBuf, 0, (int)Math.Min(contentBuf.Length, dllStream.Length - reader.Position));
                }
            }
        }

        TimeSpan headersAndContent = DateTime.UtcNow - start;

        start = DateTime.UtcNow;
        foreach (var dll in dllFiles)
        {
            System.Reflection.Assembly.Load(File.ReadAllBytes(dll));
        }

        TimeSpan reflectionLoad = DateTime.UtcNow - start;

        Console.WriteLine(
            dllFiles.Length + " dlls\t" +
            "Headers only: " + headersOnly.TotalSeconds.ToString("#0.000") + " sec." +
            "  " +
            "Headers and content: " + headersAndContent.TotalSeconds.ToString("#0.000") + " sec." +
            "  " +
            "Reflection: " + reflectionLoad.TotalSeconds.ToString("#0.000") + " sec." +
            "");
    }
Exemple #11
0
        static void Main(string[] args)
        {
            string mscolib = typeof(int).Assembly.Location;

            var pe = new PEFile();

            Console.WriteLine(Path.GetFileName(mscolib));
            var clrBasics = GetClrBasicsFor(mscolib, pe);

            PrintClrHeader(clrBasics);

            string self = typeof(Program).Assembly.Location;
            Console.WriteLine(Path.GetFileName(self));
            var clrBasics2 = GetClrBasicsFor(self, pe);

            PrintClrHeader(clrBasics2);
        }
Exemple #12
0
        static void Main(string[] args)
        {
            string kernel32 = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.System),
                "kernel32.dll");

            Console.WriteLine(Path.GetFileName(kernel32));
            var pe = new PEFile();
            var exports = GetExportFor(kernel32, pe);

            Console.WriteLine("PEHeader.Timestamp: "+pe.PEHeader.Timestamp);
            Console.WriteLine(exports.DllName + " " + exports.Timestamp);
            foreach (var i in exports.Exports)
            {
                Console.WriteLine("  " + i.ToString());
            }
        }
Exemple #13
0
        static void Main(string[] args)
        {
            var pe = new PEFile();
            var originalBytes = Properties.Resources.console_anycpu;
            var reader = new BinaryStreamReader(new MemoryStream(originalBytes), new byte[1024]);
            pe.ReadFrom(reader);

            using (var output = File.Create("console.anycpu.exe"))
            {
                var writer = new BinaryStreamWriter(output);
                pe.WriteTo(writer);

                while (reader.Position < originalBytes.Length)
                {
                    writer.WriteByte(reader.ReadByte());
                }
            }
        }
Exemple #14
0
        static void Main(string[] args)
        {
            string kernel32 = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.System),
                "kernel32.dll");

            var pe = new PEFile();

            Console.WriteLine(Path.GetFileName(kernel32));
            var relocBlocks = GetBaseRelocationsFor(kernel32, pe);

            PrintBaseRelocations(relocBlocks);

            string self = typeof(Program).Assembly.Location;
            Console.WriteLine(Path.GetFileName(self));
            relocBlocks = GetBaseRelocationsFor(self, pe);

            PrintBaseRelocations(relocBlocks);
        }
Exemple #15
0
        private async void parseButton_Click(object sender, RoutedEventArgs e)
        {
            var pe = new PEFile();

            var metroExe =
                (from f in await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFilesAsync()
                 where string.Equals(f.FileName, this.GetType().Namespace + ".exe", StringComparison.OrdinalIgnoreCase)
                 select f).First();

            var fiStream = await metroExe.OpenForReadAsync();
            using (var inputStream = fiStream.AsStream())
            {
                var buf = await ReadAll(inputStream);

                var bufStream = new MemoryStream(buf);

                pe.ReadFrom(new BinaryStreamReader(bufStream, new byte[32]));
            }
            LayoutRoot.Children.Add(new PEFileView { DataContext = pe });
        }
Exemple #16
0
        void MainPage_Drop(object sender, DragEventArgs e)
        {
            if (e.Data != null)
            {
                var files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];

                if (files != null)
                {
                    foreach (var fi in files)
                    {
                        PEFile pe = new PEFile();
                        using(var stream = fi.OpenRead())
                        {
                            var reader = new BinaryStreamReader(stream, new byte[1024]);
                            pe.ReadFrom(reader);
                        }

                        myContentControl.Content = new Model.PEFileModel(fi.Name, pe);
                    }
                }
            }
        }
Exemple #17
0
        static void Main(string[] args)
        {
            var pe = new PEFile();
            var stream = new MemoryStream(Properties.Resources.console_anycpu);
            var reader = new BinaryStreamReader(stream, new byte[1024]);
            pe.ReadFrom(reader);

            uint lowestPointerToRawData = uint.MaxValue;
            uint lowestVirtualAddress = uint.MaxValue;
            uint highestVirtualAddress = uint.MinValue;

            foreach (var s in pe.SectionHeaders)
            {
                lowestPointerToRawData = Math.Min(lowestPointerToRawData, s.PointerToRawData);
                lowestVirtualAddress = Math.Min(lowestVirtualAddress, s.VirtualAddress);
                highestVirtualAddress = Math.Max(highestVirtualAddress, s.VirtualAddress + (uint)s.VirtualSize);
            }

            byte[] allSectionContent = new byte[highestVirtualAddress - lowestVirtualAddress];
            foreach (var s in pe.SectionHeaders)
            {
                reader.Position = s.PointerToRawData;
                reader.ReadBytes(allSectionContent, (int)(s.VirtualAddress - lowestVirtualAddress), (int)s.VirtualSize);
            }

            pe.PEHeader.NumberOfSections = 1;
            var singleSection = pe.SectionHeaders[0];
            singleSection.VirtualSize = (uint)allSectionContent.Length;
            pe.SectionHeaders = new[] { singleSection };

            using (var peFileStream = File.Create("console.anycpu.insane.exe"))
            {
                var writer = new BinaryStreamWriter(peFileStream);
                pe.WriteTo(writer);
                writer.Position = lowestPointerToRawData;
                writer.WriteBytes(allSectionContent, 0, allSectionContent.Length);
            }
        }
Exemple #18
0
        public MainPage()
        {
            InitializeComponent();

            Application.Current.Host.Settings.EnableAutoZoom = false;

            string fileName = new AssemblyName(this.GetType().Assembly.FullName).Name+".dll";
            var streamInfo = Application.GetResourceStream(new Uri(fileName, UriKind.Relative));

            var reader = new BinaryStreamReader(streamInfo.Stream, new byte[32]);

            var pe = new PEFile();
            pe.ReadFrom(reader);

            myContentControl.Content = new Model.PEFileModel(fileName, pe);
            myContentControl.Visibility = System.Windows.Visibility.Visible;

            this.MouseWheel += new MouseWheelEventHandler(MainPage_MouseWheel);

            this.AllowDrop = true;

            this.Drop += new DragEventHandler(MainPage_Drop);
        }
Exemple #19
0
        public void ReadDosHeader_InvalidMZ()
        {
            var pe = new PEFile();

            pe.ReadFrom(new BinaryStreamReader(new MemoryStream(new byte[10]), new byte[32]));
        }
        public void ReadOptionalHeader_InvalidPEMagic()
        {
            byte[] bytes = Properties.Resources.console_anycpu;
            bytes[152] = 0;

            var pe = new PEFile();
            pe.ReadFrom(new BinaryStreamReader(new MemoryStream(bytes), new byte[32]));
        }
        public void ReadDosHeader_NoDosStub()
        {
            byte[] bytes = Properties.Resources.console_anycpu;

            uint lfaNew = (uint)BitConverter.ToInt32(bytes, DosHeader.Size - 4);
            byte[] modifiedLfaNewBytes = BitConverter.GetBytes(DosHeader.Size);

            Array.Copy(
                modifiedLfaNewBytes, 0,
                bytes, DosHeader.Size - 4,
                4);

            Array.Copy(
                bytes, lfaNew,
                bytes, DosHeader.Size,
                bytes.Length - lfaNew);

            var stream = new MemoryStream(bytes, 0, bytes.Length - ((int)lfaNew - DosHeader.Size), false);

            var pe = new PEFile();
            pe.ReadFrom(new BinaryStreamReader(stream, new byte[32]));

            Assert.AreEqual((uint)DosHeader.Size, pe.DosHeader.lfanew);
            Assert.IsNull(pe.DosStub);
        }
 public void ReadDosHeader_InvalidMZ()
 {
     var pe = new PEFile();
     pe.ReadFrom(new BinaryStreamReader(new MemoryStream(new byte[10]), new byte[32]));
 }
        private static void AssertReadWriteRoundtrip(byte[] originalBytes, Action<PEFile> modifyPEFile)
        {
            var pe = new PEFile();
            var stream = new MemoryStream(originalBytes);
            var reader = new BinaryStreamReader(stream, new byte[32]);
            pe.ReadFrom(reader);
            int pos = (int)reader.Position;

            if (modifyPEFile != null)
                modifyPEFile(pe);

            var buf = new MemoryStream();
            var writer = new BinaryStreamWriter(buf);
            pe.WriteTo(writer);
            buf.Write(originalBytes, pos, originalBytes.Length - pos);

            byte[] outputBytes = buf.ToArray();
            Assert.AreEqual(originalBytes.Length, outputBytes.Length, "outputBytes.Length");

            for (int i = 0; i < outputBytes.Length; i++)
            {
                Assert.AreEqual(originalBytes[i], outputBytes[i], "outputBytes[" + i + "]");
            }
        }
Exemple #24
0
        private void AddFile(FileInfo fi)
        {
            var tabControl = LayoutRoot.Children.OfType<TabControl>().FirstOrDefault();
            if (tabControl == null)
            {
                tabControl = new TabControl();
                LayoutRoot.Children.Add(tabControl);
            }

            PEFile pe;
            using (var stream = fi.OpenRead())
            {
                var reader = new BinaryStreamReader(stream, new byte[32]);
                pe = new PEFile();
                pe.ReadFrom(reader);
            }

            var tabItem = new TabItem
            {
                Header = fi.Name,
                Content = new ScrollViewer
                {
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                    HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                    //Background = Brushes.White,
                    Padding = new Thickness(5),
                    Content = new PEFileView { DataContext = new PEFileViewModel(pe) }
                }
            };

            tabControl.Items.Add(tabItem);

            tabControl.SelectedIndex = tabControl.Items.Count - 1;
        }
Exemple #25
0
 public PEFileViewModel(PEFile peFile)
 {
     this.m_PEFile = peFile;
 }