pub const Coff = struct data: []const u8is_loaded: boolSet if data is backed by the image as loaded by the loader
is_image: boolcoff_header_offset: usizeguid: [16]u8 = undefinedage: u32 = undefinedpub fn init(data: []const u8, is_loaded: bool) errorpub fn getPdbPath(self: *Coff) !?[]const u8pub fn getHeader(self: Coff) Headerpub fn getOptionalHeader(self: Coff) OptionalHeaderpub fn getOptionalHeader32(self: Coff) OptionalHeader.PE32pub fn getOptionalHeader64(self: Coff) OptionalHeader.@"PE32+"pub fn getImageBase(self: Coff) u64pub fn getNumberOfDataDirectories(self: Coff) u32pub fn getDataDirectories(self: *const Coff) []align(1) const ImageDataDirectorypub fn getSymtab(self: *const Coff) ?Symtabpub fn getStrtab(self: *const Coff) errorpub fn strtabRequired(self: *const Coff) boolpub fn getSectionHeaders(self: *const Coff) []align(1) const SectionHeaderpub fn getSectionHeadersAlloc(self: *const Coff, allocator: mem.Allocator) ![]SectionHeaderpub fn getSectionName(self: *const Coff, sect_hdr: *align(1) const SectionHeader) errorpub fn getSectionByName(self: *const Coff, comptime name: []const u8) ?*align(1) const SectionHeaderpub fn getSectionData(self: *const Coff, sec: *align(1) const SectionHeader) []const u8pub fn getSectionDataAlloc(self: *const Coff, sec: *align(1) const SectionHeader, allocator: mem.Allocator) ![]u81018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226pub const Coff = struct {
data: []const u8,
// Set if `data` is backed by the image as loaded by the loader
is_loaded: bool,
is_image: bool,
coff_header_offset: usize,
guid: [16]u8 = undefined,
age: u32 = undefined,
// The lifetime of `data` must be longer than the lifetime of the returned Coff
pub fn init(data: []const u8, is_loaded: bool) error{ EndOfStream, MissingPEHeader }!Coff {
if (data.len < pe_pointer_offset + 4) return error.EndOfStream;
const header_offset = mem.readInt(u32, data[pe_pointer_offset..][0..4], .little);
if (data.len < header_offset + 4) return error.EndOfStream;
const is_image = mem.eql(u8, data[header_offset..][0..4], pe_signature);
const coff: Coff = .{
.data = data,
.is_image = is_image,
.is_loaded = is_loaded,
.coff_header_offset = o: {
if (is_image) break :o header_offset + 4;
break :o header_offset;
},
};
// Do some basic validation upfront
if (is_image) {
const coff_header = coff.getHeader();
if (coff_header.size_of_optional_header == 0) return error.MissingPEHeader;
}
// JK: we used to check for architecture here and throw an error if not x86 or derivative.
// However I am willing to take a leap of faith and let aarch64 have a shot also.
return coff;
}
pub fn getPdbPath(self: *Coff) !?[]const u8 {
assert(self.is_image);
const data_dirs = self.getDataDirectories();
if (@backingInt(IMAGE.DIRECTORY_ENTRY.DEBUG) >= data_dirs.len) return null;
const debug_dir = data_dirs[@backingInt(IMAGE.DIRECTORY_ENTRY.DEBUG)];
var reader: std.Io.Reader = .fixed(self.data);
if (self.is_loaded) {
reader.seek = debug_dir.virtual_address;
} else {
// Find what section the debug_dir is in, in order to convert the RVA to a file offset
for (self.getSectionHeaders()) |*sect| {
if (debug_dir.virtual_address >= sect.virtual_address and debug_dir.virtual_address < sect.virtual_address + sect.virtual_size) {
reader.seek = sect.pointer_to_raw_data + (debug_dir.virtual_address - sect.virtual_address);
break;
}
} else return error.InvalidDebugDirectory;
}
// Find the correct DebugDirectoryEntry, and where its data is stored.
// It can be in any section.
const debug_dir_entry_count = debug_dir.size / @sizeOf(DebugDirectoryEntry);
var i: u32 = 0;
while (i < debug_dir_entry_count) : (i += 1) {
const debug_dir_entry = try reader.takeStruct(DebugDirectoryEntry, .little);
if (debug_dir_entry.type == .CODEVIEW) {
const dir_offset = if (self.is_loaded) debug_dir_entry.address_of_raw_data else debug_dir_entry.pointer_to_raw_data;
reader.seek = dir_offset;
break;
}
} else return null;
const code_view_signature = try reader.takeArray(4);
// 'RSDS' indicates PDB70 format, used by lld.
if (!mem.eql(u8, code_view_signature, "RSDS"))
return error.InvalidPEMagic;
try reader.readSliceAll(self.guid[0..]);
self.age = try reader.takeInt(u32, .little);
// Finally read the null-terminated string.
const start = reader.seek;
const len = std.mem.findScalar(u8, self.data[start..], 0) orelse return null;
return self.data[start .. start + len];
}
pub fn getHeader(self: Coff) Header {
return @as(*align(1) const Header, @ptrCast(self.data[self.coff_header_offset..][0..@sizeOf(Header)])).*;
}
pub fn getOptionalHeader(self: Coff) OptionalHeader {
assert(self.is_image);
const offset = self.coff_header_offset + @sizeOf(Header);
return @as(*align(1) const OptionalHeader, @ptrCast(self.data[offset..][0..@sizeOf(OptionalHeader)])).*;
}
pub fn getOptionalHeader32(self: Coff) OptionalHeader.PE32 {
assert(self.is_image);
const offset = self.coff_header_offset + @sizeOf(Header);
return @as(*align(1) const OptionalHeader.PE32, @ptrCast(self.data[offset..][0..@sizeOf(OptionalHeader.PE32)])).*;
}
pub fn getOptionalHeader64(self: Coff) OptionalHeader.@"PE32+" {
assert(self.is_image);
const offset = self.coff_header_offset + @sizeOf(Header);
return @as(*align(1) const OptionalHeader.@"PE32+", @ptrCast(self.data[offset..][0..@sizeOf(OptionalHeader.@"PE32+")])).*;
}
pub fn getImageBase(self: Coff) u64 {
const hdr = self.getOptionalHeader();
return switch (@backingInt(hdr.magic)) {
IMAGE_NT_OPTIONAL_HDR32_MAGIC => self.getOptionalHeader32().image_base,
IMAGE_NT_OPTIONAL_HDR64_MAGIC => self.getOptionalHeader64().image_base,
else => unreachable, // We assume we have validated the header already
};
}
pub fn getNumberOfDataDirectories(self: Coff) u32 {
const hdr = self.getOptionalHeader();
return switch (@backingInt(hdr.magic)) {
IMAGE_NT_OPTIONAL_HDR32_MAGIC => self.getOptionalHeader32().number_of_rva_and_sizes,
IMAGE_NT_OPTIONAL_HDR64_MAGIC => self.getOptionalHeader64().number_of_rva_and_sizes,
else => unreachable, // We assume we have validated the header already
};
}
pub fn getDataDirectories(self: *const Coff) []align(1) const ImageDataDirectory {
const hdr = self.getOptionalHeader();
const size: usize = switch (@backingInt(hdr.magic)) {
IMAGE_NT_OPTIONAL_HDR32_MAGIC => @sizeOf(OptionalHeader.PE32),
IMAGE_NT_OPTIONAL_HDR64_MAGIC => @sizeOf(OptionalHeader.@"PE32+"),
else => unreachable, // We assume we have validated the header already
};
const offset = self.coff_header_offset + @sizeOf(Header) + size;
return @as([*]align(1) const ImageDataDirectory, @ptrCast(self.data[offset..]))[0..self.getNumberOfDataDirectories()];
}
pub fn getSymtab(self: *const Coff) ?Symtab {
const coff_header = self.getHeader();
if (coff_header.pointer_to_symbol_table == 0) return null;
const offset = coff_header.pointer_to_symbol_table;
const size = coff_header.number_of_symbols * Symbol.sizeOf();
return .{ .buffer = self.data[offset..][0..size] };
}
pub fn getStrtab(self: *const Coff) error{InvalidStrtabSize}!?Strtab {
const coff_header = self.getHeader();
if (coff_header.pointer_to_symbol_table == 0) return null;
const offset = coff_header.pointer_to_symbol_table + Symbol.sizeOf() * coff_header.number_of_symbols;
const size = mem.readInt(u32, self.data[offset..][0..4], .little);
if ((offset + size) > self.data.len) return error.InvalidStrtabSize;
return Strtab{ .buffer = self.data[offset..][0..size] };
}
pub fn strtabRequired(self: *const Coff) bool {
for (self.getSectionHeaders()) |*sect_hdr| if (sect_hdr.getName() == null) return true;
return false;
}
pub fn getSectionHeaders(self: *const Coff) []align(1) const SectionHeader {
const coff_header = self.getHeader();
const offset = self.coff_header_offset + @sizeOf(Header) + coff_header.size_of_optional_header;
return @as([*]align(1) const SectionHeader, @ptrCast(self.data.ptr + offset))[0..coff_header.number_of_sections];
}
pub fn getSectionHeadersAlloc(self: *const Coff, allocator: mem.Allocator) ![]SectionHeader {
const section_headers = self.getSectionHeaders();
const out_buff = try allocator.alloc(SectionHeader, section_headers.len);
for (out_buff, 0..) |*section_header, i| {
section_header.* = section_headers[i];
}
return out_buff;
}
pub fn getSectionName(self: *const Coff, sect_hdr: *align(1) const SectionHeader) error{InvalidStrtabSize}![]const u8 {
const name = sect_hdr.getName() orelse blk: {
const strtab = (try self.getStrtab()).?;
const name_offset = sect_hdr.getNameOffset().?;
break :blk strtab.get(name_offset);
};
return name;
}
pub fn getSectionByName(self: *const Coff, comptime name: []const u8) ?*align(1) const SectionHeader {
for (self.getSectionHeaders()) |*sect| {
const section_name = self.getSectionName(sect) catch |e| switch (e) {
error.InvalidStrtabSize => continue, //ignore invalid(?) strtab entries - see also GitHub issue #15238
};
if (mem.eql(u8, section_name, name)) {
return sect;
}
}
return null;
}
pub fn getSectionData(self: *const Coff, sec: *align(1) const SectionHeader) []const u8 {
const offset = if (self.is_loaded) sec.virtual_address else sec.pointer_to_raw_data;
return self.data[offset..][0..sec.virtual_size];
}
pub fn getSectionDataAlloc(self: *const Coff, sec: *align(1) const SectionHeader, allocator: mem.Allocator) ![]u8 {
const section_data = self.getSectionData(sec);
return allocator.dupe(u8, section_data);
}
}