private void Serialize(uint totalSize) { /* Allocate enough space to contain the whole new file */ byte[] file = new byte[totalSize]; uint filePosition = SerializeHeader(ref file); Array.Copy(PEUtility.RawSerialize(dataDirectories), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_DATA_DIRECTORIES))); filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_DATA_DIRECTORIES)); // XXX: Sections must be sorted in layout order! foreach (PESection section in sections) { Array.Copy(PEUtility.RawSerialize(section.Header), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER))); filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)); } /* Copy the section data */ filePosition = optionalHeader.SizeOfHeaders; sections.Sort(new SectionPhysicalComparer()); foreach (PESection s in sections) { Array.Copy(s.Data, 0, file, filePosition, s.Data.Length); filePosition += s.RawSize; break; } /* Overwrite the container data */ rawData = file; }
private uint SerializeHeader(ref byte[] file) { uint filePosition = 0; Array.Copy(PEUtility.RawSerialize(dosHeader), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_DOS_HEADER))); filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)); Array.Copy(dosStub, 0, file, filePosition, dosStub.Length); filePosition += (uint)dosStub.Length; Array.Copy(PEUtility.RawSerialize(ntSignature), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_NT_HEADERS))); filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_NT_HEADERS)); Array.Copy(PEUtility.RawSerialize(fileHeader), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_FILE_HEADER))); filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_FILE_HEADER)); Array.Copy(PEUtility.RawSerialize(optionalHeader), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_OPTIONAL_HEADER32))); filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_OPTIONAL_HEADER32)); return(filePosition); }