using System.Text; namespace EvilEngine.Adapters.Tests.Support; public static class ElfWriter { public static byte[] Build(byte[] buildId, string section = ".note.gnu.build-id") { var note = new byte[16 + (buildId.Length + 3) / 4 * 4]; BitConverter.GetBytes(4).CopyTo(note, 0); BitConverter.GetBytes(buildId.Length).CopyTo(note, 4); BitConverter.GetBytes(3).CopyTo(note, 8); "GNU\0"u8.CopyTo(note.AsSpan(12)); buildId.CopyTo(note, 16); var names = Encoding.ASCII.GetBytes("\0.shstrtab\0" + section + "\0"); const int header = 64; var noteAt = header; var namesAt = noteAt + note.Length; var table = (namesAt + names.Length + 7) / 8 * 8; var image = new byte[table + 3 * 64]; "\u007fELF"u8.CopyTo(image); image[4] = 2; image[5] = 1; image[6] = 1; BitConverter.GetBytes((ushort)2).CopyTo(image, 0x10); BitConverter.GetBytes((ushort)0x3E).CopyTo(image, 0x12); BitConverter.GetBytes((ulong)table).CopyTo(image, 0x28); BitConverter.GetBytes((ushort)64).CopyTo(image, 0x34); BitConverter.GetBytes((ushort)64).CopyTo(image, 0x3A); BitConverter.GetBytes((ushort)3).CopyTo(image, 0x3C); BitConverter.GetBytes((ushort)2).CopyTo(image, 0x3E); note.CopyTo(image, noteAt); names.CopyTo(image, namesAt); Section(image, table + 64, 11, 7, noteAt, note.Length); Section(image, table + 128, 1, 3, namesAt, names.Length); return image; } private static void Section(byte[] image, int at, uint name, uint type, long offset, long size) { BitConverter.GetBytes(name).CopyTo(image, at); BitConverter.GetBytes(type).CopyTo(image, at + 4); BitConverter.GetBytes((ulong)offset).CopyTo(image, at + 24); BitConverter.GetBytes((ulong)size).CopyTo(image, at + 32); } }