| ... | ... | @@ -7,6 +7,7 @@ const Module = @import("Module.zig"); |
| 7 | 7 | const fs = std.fs; |
| 8 | 8 | const elf = std.elf; |
| 9 | 9 | const codegen = @import("codegen.zig"); |
| 10 | const cgen = @import("cgen.zig"); |
| 10 | 11 | |
| 11 | 12 | const default_entry_addr = 0x8000000; |
| 12 | 13 | |
| ... | ... | @@ -21,6 +22,7 @@ pub const Options = struct { |
| 21 | 22 | /// Used for calculating how much space to reserve for executable program code in case |
| 22 | 23 | /// the binary file deos not already have such a section. |
| 23 | 24 | program_code_size_hint: u64 = 256 * 1024, |
| 25 | cbe: bool = false, |
| 24 | 26 | }; |
| 25 | 27 | |
| 26 | 28 | /// Attempts incremental linking, if the file already exists. |
| ... | ... | @@ -32,13 +34,22 @@ pub fn openBinFilePath( |
| 32 | 34 | dir: fs.Dir, |
| 33 | 35 | sub_path: []const u8, |
| 34 | 36 | options: Options, |
| 35 | | ) !ElfFile { |
| 36 | | const file = try dir.createFile(sub_path, .{ .truncate = false, .read = true, .mode = determineMode(options) }); |
| 37 | ) !*File { |
| 38 | const file = try dir.createFile(sub_path, .{ .truncate = options.cbe, .read = true, .mode = determineMode(options) }); |
| 37 | 39 | errdefer file.close(); |
| 38 | 40 | |
| 39 | | var bin_file = try openBinFile(allocator, file, options); |
| 40 | | bin_file.owns_file_handle = true; |
| 41 | | return bin_file; |
| 41 | if (options.cbe) { |
| 42 | var bin_file = try allocator.create(File.C); |
| 43 | errdefer allocator.destroy(bin_file); |
| 44 | bin_file.* = try openCFile(allocator, file, options); |
| 45 | return &bin_file.base; |
| 46 | } else { |
| 47 | var bin_file = try allocator.create(File.Elf); |
| 48 | errdefer allocator.destroy(bin_file); |
| 49 | bin_file.* = try openBinFile(allocator, file, options); |
| 50 | bin_file.owns_file_handle = true; |
| 51 | return &bin_file.base; |
| 52 | } |
| 42 | 53 | } |
| 43 | 54 | |
| 44 | 55 | /// Atomically overwrites the old file, if present. |
| ... | ... | @@ -75,12 +86,24 @@ pub fn writeFilePath( |
| 75 | 86 | return result; |
| 76 | 87 | } |
| 77 | 88 | |
| 89 | fn openCFile(allocator: *Allocator, file: fs.File, options: Options) !File.C { |
| 90 | return File.C{ |
| 91 | .allocator = allocator, |
| 92 | .file = file, |
| 93 | .options = options, |
| 94 | .main = std.ArrayList(u8).init(allocator), |
| 95 | .header = std.ArrayList(u8).init(allocator), |
| 96 | .constants = std.ArrayList(u8).init(allocator), |
| 97 | .called = std.StringHashMap(void).init(allocator), |
| 98 | }; |
| 99 | } |
| 100 | |
| 78 | 101 | /// Attempts incremental linking, if the file already exists. |
| 79 | 102 | /// If incremental linking fails, falls back to truncating the file and rewriting it. |
| 80 | 103 | /// Returns an error if `file` is not already open with +read +write +seek abilities. |
| 81 | 104 | /// A malicious file is detected as incremental link failure and does not cause Illegal Behavior. |
| 82 | 105 | /// This operation is not atomic. |
| 83 | | pub fn openBinFile(allocator: *Allocator, file: fs.File, options: Options) !ElfFile { |
| 106 | pub fn openBinFile(allocator: *Allocator, file: fs.File, options: Options) !File.Elf { |
| 84 | 107 | return openBinFileInner(allocator, file, options) catch |err| switch (err) { |
| 85 | 108 | error.IncrFailed => { |
| 86 | 109 | return createElfFile(allocator, file, options); |
| ... | ... | @@ -89,514 +112,592 @@ pub fn openBinFile(allocator: *Allocator, file: fs.File, options: Options) !ElfF |
| 89 | 112 | }; |
| 90 | 113 | } |
| 91 | 114 | |
| 92 | | pub const ElfFile = struct { |
| 93 | | allocator: *Allocator, |
| 94 | | file: ?fs.File, |
| 95 | | owns_file_handle: bool, |
| 96 | | options: Options, |
| 97 | | ptr_width: enum { p32, p64 }, |
| 98 | | |
| 99 | | /// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write. |
| 100 | | /// Same order as in the file. |
| 101 | | sections: std.ArrayListUnmanaged(elf.Elf64_Shdr) = std.ArrayListUnmanaged(elf.Elf64_Shdr){}, |
| 102 | | shdr_table_offset: ?u64 = null, |
| 103 | | |
| 104 | | /// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write. |
| 105 | | /// Same order as in the file. |
| 106 | | program_headers: std.ArrayListUnmanaged(elf.Elf64_Phdr) = std.ArrayListUnmanaged(elf.Elf64_Phdr){}, |
| 107 | | phdr_table_offset: ?u64 = null, |
| 108 | | /// The index into the program headers of a PT_LOAD program header with Read and Execute flags |
| 109 | | phdr_load_re_index: ?u16 = null, |
| 110 | | /// The index into the program headers of the global offset table. |
| 111 | | /// It needs PT_LOAD and Read flags. |
| 112 | | phdr_got_index: ?u16 = null, |
| 113 | | entry_addr: ?u64 = null, |
| 114 | | |
| 115 | | shstrtab: std.ArrayListUnmanaged(u8) = std.ArrayListUnmanaged(u8){}, |
| 116 | | shstrtab_index: ?u16 = null, |
| 117 | | |
| 118 | | text_section_index: ?u16 = null, |
| 119 | | symtab_section_index: ?u16 = null, |
| 120 | | got_section_index: ?u16 = null, |
| 121 | | |
| 122 | | /// The same order as in the file. ELF requires global symbols to all be after the |
| 123 | | /// local symbols, they cannot be mixed. So we must buffer all the global symbols and |
| 124 | | /// write them at the end. These are only the local symbols. The length of this array |
| 125 | | /// is the value used for sh_info in the .symtab section. |
| 126 | | local_symbols: std.ArrayListUnmanaged(elf.Elf64_Sym) = std.ArrayListUnmanaged(elf.Elf64_Sym){}, |
| 127 | | global_symbols: std.ArrayListUnmanaged(elf.Elf64_Sym) = std.ArrayListUnmanaged(elf.Elf64_Sym){}, |
| 128 | | |
| 129 | | local_symbol_free_list: std.ArrayListUnmanaged(u32) = std.ArrayListUnmanaged(u32){}, |
| 130 | | global_symbol_free_list: std.ArrayListUnmanaged(u32) = std.ArrayListUnmanaged(u32){}, |
| 131 | | offset_table_free_list: std.ArrayListUnmanaged(u32) = std.ArrayListUnmanaged(u32){}, |
| 132 | | |
| 133 | | /// Same order as in the file. The value is the absolute vaddr value. |
| 134 | | /// If the vaddr of the executable program header changes, the entire |
| 135 | | /// offset table needs to be rewritten. |
| 136 | | offset_table: std.ArrayListUnmanaged(u64) = std.ArrayListUnmanaged(u64){}, |
| 137 | | |
| 138 | | phdr_table_dirty: bool = false, |
| 139 | | shdr_table_dirty: bool = false, |
| 140 | | shstrtab_dirty: bool = false, |
| 141 | | offset_table_count_dirty: bool = false, |
| 142 | | |
| 143 | | error_flags: ErrorFlags = ErrorFlags{}, |
| 144 | | |
| 145 | | /// A list of text blocks that have surplus capacity. This list can have false |
| 146 | | /// positives, as functions grow and shrink over time, only sometimes being added |
| 147 | | /// or removed from the freelist. |
| 148 | | /// |
| 149 | | /// A text block has surplus capacity when its overcapacity value is greater than |
| 150 | | /// minimum_text_block_size * alloc_num / alloc_den. That is, when it has so |
| 151 | | /// much extra capacity, that we could fit a small new symbol in it, itself with |
| 152 | | /// ideal_capacity or more. |
| 153 | | /// |
| 154 | | /// Ideal capacity is defined by size * alloc_num / alloc_den. |
| 155 | | /// |
| 156 | | /// Overcapacity is measured by actual_capacity - ideal_capacity. Note that |
| 157 | | /// overcapacity can be negative. A simple way to have negative overcapacity is to |
| 158 | | /// allocate a fresh text block, which will have ideal capacity, and then grow it |
| 159 | | /// by 1 byte. It will then have -1 overcapacity. |
| 160 | | text_block_free_list: std.ArrayListUnmanaged(*TextBlock) = std.ArrayListUnmanaged(*TextBlock){}, |
| 161 | | last_text_block: ?*TextBlock = null, |
| 162 | | |
| 163 | | /// `alloc_num / alloc_den` is the factor of padding when allocating. |
| 164 | | const alloc_num = 4; |
| 165 | | const alloc_den = 3; |
| 166 | | |
| 167 | | /// In order for a slice of bytes to be considered eligible to keep metadata pointing at |
| 168 | | /// it as a possible place to put new symbols, it must have enough room for this many bytes |
| 169 | | /// (plus extra for reserved capacity). |
| 170 | | const minimum_text_block_size = 64; |
| 171 | | const min_text_capacity = minimum_text_block_size * alloc_num / alloc_den; |
| 172 | | |
| 173 | | pub const ErrorFlags = struct { |
| 174 | | no_entry_point_found: bool = false, |
| 175 | | }; |
| 176 | | |
| 177 | | pub const TextBlock = struct { |
| 178 | | /// Each decl always gets a local symbol with the fully qualified name. |
| 179 | | /// The vaddr and size are found here directly. |
| 180 | | /// The file offset is found by computing the vaddr offset from the section vaddr |
| 181 | | /// the symbol references, and adding that to the file offset of the section. |
| 182 | | /// If this field is 0, it means the codegen size = 0 and there is no symbol or |
| 183 | | /// offset table entry. |
| 184 | | local_sym_index: u32, |
| 185 | | /// This field is undefined for symbols with size = 0. |
| 186 | | offset_table_index: u32, |
| 187 | | /// Points to the previous and next neighbors, based on the `text_offset`. |
| 188 | | /// This can be used to find, for example, the capacity of this `TextBlock`. |
| 189 | | prev: ?*TextBlock, |
| 190 | | next: ?*TextBlock, |
| 191 | | |
| 192 | | pub const empty = TextBlock{ |
| 193 | | .local_sym_index = 0, |
| 194 | | .offset_table_index = undefined, |
| 195 | | .prev = null, |
| 196 | | .next = null, |
| 197 | | }; |
| 198 | | |
| 199 | | /// Returns how much room there is to grow in virtual address space. |
| 200 | | /// File offset relocation happens transparently, so it is not included in |
| 201 | | /// this calculation. |
| 202 | | fn capacity(self: TextBlock, elf_file: ElfFile) u64 { |
| 203 | | const self_sym = elf_file.local_symbols.items[self.local_sym_index]; |
| 204 | | if (self.next) |next| { |
| 205 | | const next_sym = elf_file.local_symbols.items[next.local_sym_index]; |
| 206 | | return next_sym.st_value - self_sym.st_value; |
| 207 | | } else { |
| 208 | | // We are the last block. The capacity is limited only by virtual address space. |
| 209 | | return std.math.maxInt(u32) - self_sym.st_value; |
| 210 | | } |
| 211 | | } |
| 115 | pub const File = struct { |
| 116 | tag: Tag, |
| 117 | pub fn cast(base: *File, comptime T: type) ?*T { |
| 118 | if (base.tag != T.base_tag) |
| 119 | return null; |
| 212 | 120 | |
| 213 | | fn freeListEligible(self: TextBlock, elf_file: ElfFile) bool { |
| 214 | | // No need to keep a free list node for the last block. |
| 215 | | const next = self.next orelse return false; |
| 216 | | const self_sym = elf_file.local_symbols.items[self.local_sym_index]; |
| 217 | | const next_sym = elf_file.local_symbols.items[next.local_sym_index]; |
| 218 | | const cap = next_sym.st_value - self_sym.st_value; |
| 219 | | const ideal_cap = self_sym.st_size * alloc_num / alloc_den; |
| 220 | | if (cap <= ideal_cap) return false; |
| 221 | | const surplus = cap - ideal_cap; |
| 222 | | return surplus >= min_text_capacity; |
| 223 | | } |
| 224 | | }; |
| 225 | | |
| 226 | | pub const Export = struct { |
| 227 | | sym_index: ?u32 = null, |
| 228 | | }; |
| 121 | return @fieldParentPtr(T, "base", base); |
| 122 | } |
| 229 | 123 | |
| 230 | | pub fn deinit(self: *ElfFile) void { |
| 231 | | self.sections.deinit(self.allocator); |
| 232 | | self.program_headers.deinit(self.allocator); |
| 233 | | self.shstrtab.deinit(self.allocator); |
| 234 | | self.local_symbols.deinit(self.allocator); |
| 235 | | self.global_symbols.deinit(self.allocator); |
| 236 | | self.global_symbol_free_list.deinit(self.allocator); |
| 237 | | self.local_symbol_free_list.deinit(self.allocator); |
| 238 | | self.offset_table_free_list.deinit(self.allocator); |
| 239 | | self.text_block_free_list.deinit(self.allocator); |
| 240 | | self.offset_table.deinit(self.allocator); |
| 241 | | if (self.owns_file_handle) { |
| 242 | | if (self.file) |f| f.close(); |
| 124 | pub fn makeWritable(base: *File, dir: fs.Dir, sub_path: []const u8) !void { |
| 125 | switch (base.tag) { |
| 126 | .Elf => return @fieldParentPtr(Elf, "base", base).makeWritable(dir, sub_path), |
| 127 | .C => {}, |
| 128 | else => unreachable, |
| 243 | 129 | } |
| 244 | 130 | } |
| 245 | 131 | |
| 246 | | pub fn makeExecutable(self: *ElfFile) !void { |
| 247 | | assert(self.owns_file_handle); |
| 248 | | if (self.file) |f| { |
| 249 | | f.close(); |
| 250 | | self.file = null; |
| 132 | pub fn makeExecutable(base: *File) !void { |
| 133 | switch (base.tag) { |
| 134 | .Elf => return @fieldParentPtr(Elf, "base", base).makeExecutable(), |
| 135 | else => unreachable, |
| 251 | 136 | } |
| 252 | 137 | } |
| 253 | 138 | |
| 254 | | pub fn makeWritable(self: *ElfFile, dir: fs.Dir, sub_path: []const u8) !void { |
| 255 | | assert(self.owns_file_handle); |
| 256 | | if (self.file != null) return; |
| 257 | | self.file = try dir.createFile(sub_path, .{ |
| 258 | | .truncate = false, |
| 259 | | .read = true, |
| 260 | | .mode = determineMode(self.options), |
| 261 | | }); |
| 139 | pub fn updateDecl(base: *File, module: *Module, decl: *Module.Decl) !void { |
| 140 | switch (base.tag) { |
| 141 | .Elf => return @fieldParentPtr(Elf, "base", base).updateDecl(module, decl), |
| 142 | .C => return @fieldParentPtr(C, "base", base).updateDecl(module, decl), |
| 143 | else => unreachable, |
| 144 | } |
| 262 | 145 | } |
| 263 | 146 | |
| 264 | | /// Returns end pos of collision, if any. |
| 265 | | fn detectAllocCollision(self: *ElfFile, start: u64, size: u64) ?u64 { |
| 266 | | const small_ptr = self.options.target.cpu.arch.ptrBitWidth() == 32; |
| 267 | | const ehdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Ehdr) else @sizeOf(elf.Elf64_Ehdr); |
| 268 | | if (start < ehdr_size) |
| 269 | | return ehdr_size; |
| 270 | | |
| 271 | | const end = start + satMul(size, alloc_num) / alloc_den; |
| 272 | | |
| 273 | | if (self.shdr_table_offset) |off| { |
| 274 | | const shdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Shdr) else @sizeOf(elf.Elf64_Shdr); |
| 275 | | const tight_size = self.sections.items.len * shdr_size; |
| 276 | | const increased_size = satMul(tight_size, alloc_num) / alloc_den; |
| 277 | | const test_end = off + increased_size; |
| 278 | | if (end > off and start < test_end) { |
| 279 | | return test_end; |
| 280 | | } |
| 147 | pub fn allocateDeclIndexes(base: *File, decl: *Module.Decl) !void { |
| 148 | switch (base.tag) { |
| 149 | .Elf => return @fieldParentPtr(Elf, "base", base).allocateDeclIndexes(decl), |
| 150 | .C => {}, |
| 151 | else => unreachable, |
| 281 | 152 | } |
| 153 | } |
| 282 | 154 | |
| 283 | | if (self.phdr_table_offset) |off| { |
| 284 | | const phdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Phdr) else @sizeOf(elf.Elf64_Phdr); |
| 285 | | const tight_size = self.sections.items.len * phdr_size; |
| 286 | | const increased_size = satMul(tight_size, alloc_num) / alloc_den; |
| 287 | | const test_end = off + increased_size; |
| 288 | | if (end > off and start < test_end) { |
| 289 | | return test_end; |
| 290 | | } |
| 155 | pub fn deinit(base: *File) void { |
| 156 | switch (base.tag) { |
| 157 | .Elf => @fieldParentPtr(Elf, "base", base).deinit(), |
| 158 | .C => @fieldParentPtr(C, "base", base).deinit(), |
| 159 | else => unreachable, |
| 291 | 160 | } |
| 161 | } |
| 292 | 162 | |
| 293 | | for (self.sections.items) |section| { |
| 294 | | const increased_size = satMul(section.sh_size, alloc_num) / alloc_den; |
| 295 | | const test_end = section.sh_offset + increased_size; |
| 296 | | if (end > section.sh_offset and start < test_end) { |
| 297 | | return test_end; |
| 298 | | } |
| 299 | | } |
| 300 | | for (self.program_headers.items) |program_header| { |
| 301 | | const increased_size = satMul(program_header.p_filesz, alloc_num) / alloc_den; |
| 302 | | const test_end = program_header.p_offset + increased_size; |
| 303 | | if (end > program_header.p_offset and start < test_end) { |
| 304 | | return test_end; |
| 305 | | } |
| 163 | pub fn destroy(base: *File) void { |
| 164 | switch (base.tag) { |
| 165 | .Elf => { |
| 166 | const parent = @fieldParentPtr(Elf, "base", base); |
| 167 | parent.deinit(); |
| 168 | parent.allocator.destroy(parent); |
| 169 | }, |
| 170 | .C => { |
| 171 | const parent = @fieldParentPtr(C, "base", base); |
| 172 | parent.deinit(); |
| 173 | parent.allocator.destroy(parent); |
| 174 | }, |
| 175 | else => unreachable, |
| 306 | 176 | } |
| 307 | | return null; |
| 308 | 177 | } |
| 309 | 178 | |
| 310 | | fn allocatedSize(self: *ElfFile, start: u64) u64 { |
| 311 | | var min_pos: u64 = std.math.maxInt(u64); |
| 312 | | if (self.shdr_table_offset) |off| { |
| 313 | | if (off > start and off < min_pos) min_pos = off; |
| 314 | | } |
| 315 | | if (self.phdr_table_offset) |off| { |
| 316 | | if (off > start and off < min_pos) min_pos = off; |
| 317 | | } |
| 318 | | for (self.sections.items) |section| { |
| 319 | | if (section.sh_offset <= start) continue; |
| 320 | | if (section.sh_offset < min_pos) min_pos = section.sh_offset; |
| 321 | | } |
| 322 | | for (self.program_headers.items) |program_header| { |
| 323 | | if (program_header.p_offset <= start) continue; |
| 324 | | if (program_header.p_offset < min_pos) min_pos = program_header.p_offset; |
| 325 | | } |
| 326 | | return min_pos - start; |
| 179 | pub fn flush(base: *File) !void { |
| 180 | try switch (base.tag) { |
| 181 | .Elf => @fieldParentPtr(Elf, "base", base).flush(), |
| 182 | .C => @fieldParentPtr(C, "base", base).flush(), |
| 183 | else => unreachable, |
| 184 | }; |
| 327 | 185 | } |
| 328 | 186 | |
| 329 | | fn findFreeSpace(self: *ElfFile, object_size: u64, min_alignment: u16) u64 { |
| 330 | | var start: u64 = 0; |
| 331 | | while (self.detectAllocCollision(start, object_size)) |item_end| { |
| 332 | | start = mem.alignForwardGeneric(u64, item_end, min_alignment); |
| 187 | pub fn freeDecl(base: *File, decl: *Module.Decl) void { |
| 188 | switch (base.tag) { |
| 189 | .Elf => @fieldParentPtr(Elf, "base", base).freeDecl(decl), |
| 190 | else => unreachable, |
| 333 | 191 | } |
| 334 | | return start; |
| 335 | 192 | } |
| 336 | 193 | |
| 337 | | fn makeString(self: *ElfFile, bytes: []const u8) !u32 { |
| 338 | | try self.shstrtab.ensureCapacity(self.allocator, self.shstrtab.items.len + bytes.len + 1); |
| 339 | | const result = self.shstrtab.items.len; |
| 340 | | self.shstrtab.appendSliceAssumeCapacity(bytes); |
| 341 | | self.shstrtab.appendAssumeCapacity(0); |
| 342 | | return @intCast(u32, result); |
| 194 | pub fn errorFlags(base: *File) ErrorFlags { |
| 195 | return switch (base.tag) { |
| 196 | .Elf => @fieldParentPtr(Elf, "base", base).error_flags, |
| 197 | .C => return .{ .no_entry_point_found = false }, |
| 198 | else => unreachable, |
| 199 | }; |
| 343 | 200 | } |
| 344 | 201 | |
| 345 | | fn getString(self: *ElfFile, str_off: u32) []const u8 { |
| 346 | | assert(str_off < self.shstrtab.items.len); |
| 347 | | return mem.spanZ(@ptrCast([*:0]const u8, self.shstrtab.items.ptr + str_off)); |
| 202 | pub fn options(base: *File) Options { |
| 203 | return switch (base.tag) { |
| 204 | .Elf => @fieldParentPtr(Elf, "base", base).options, |
| 205 | .C => @fieldParentPtr(C, "base", base).options, |
| 206 | }; |
| 348 | 207 | } |
| 349 | 208 | |
| 350 | | fn updateString(self: *ElfFile, old_str_off: u32, new_name: []const u8) !u32 { |
| 351 | | const existing_name = self.getString(old_str_off); |
| 352 | | if (mem.eql(u8, existing_name, new_name)) { |
| 353 | | return old_str_off; |
| 209 | /// Must be called only after a successful call to `updateDecl`. |
| 210 | pub fn updateDeclExports( |
| 211 | base: *File, |
| 212 | module: *Module, |
| 213 | decl: *const Module.Decl, |
| 214 | exports: []const *Module.Export, |
| 215 | ) !void { |
| 216 | switch (base.tag) { |
| 217 | .Elf => return @fieldParentPtr(Elf, "base", base).updateDeclExports(module, decl, exports), |
| 218 | .C => return {}, |
| 354 | 219 | } |
| 355 | | return self.makeString(new_name); |
| 356 | 220 | } |
| 357 | 221 | |
| 358 | | pub fn populateMissingMetadata(self: *ElfFile) !void { |
| 359 | | const small_ptr = switch (self.ptr_width) { |
| 360 | | .p32 => true, |
| 361 | | .p64 => false, |
| 362 | | }; |
| 363 | | const ptr_size: u8 = switch (self.ptr_width) { |
| 364 | | .p32 => 4, |
| 365 | | .p64 => 8, |
| 366 | | }; |
| 367 | | if (self.phdr_load_re_index == null) { |
| 368 | | self.phdr_load_re_index = @intCast(u16, self.program_headers.items.len); |
| 369 | | const file_size = self.options.program_code_size_hint; |
| 370 | | const p_align = 0x1000; |
| 371 | | const off = self.findFreeSpace(file_size, p_align); |
| 372 | | std.log.debug(.link, "found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size }); |
| 373 | | try self.program_headers.append(self.allocator, .{ |
| 374 | | .p_type = elf.PT_LOAD, |
| 375 | | .p_offset = off, |
| 376 | | .p_filesz = file_size, |
| 377 | | .p_vaddr = default_entry_addr, |
| 378 | | .p_paddr = default_entry_addr, |
| 379 | | .p_memsz = file_size, |
| 380 | | .p_align = p_align, |
| 381 | | .p_flags = elf.PF_X | elf.PF_R, |
| 382 | | }); |
| 383 | | self.entry_addr = null; |
| 384 | | self.phdr_table_dirty = true; |
| 385 | | } |
| 386 | | if (self.phdr_got_index == null) { |
| 387 | | self.phdr_got_index = @intCast(u16, self.program_headers.items.len); |
| 388 | | const file_size = @as(u64, ptr_size) * self.options.symbol_count_hint; |
| 389 | | // We really only need ptr alignment but since we are using PROGBITS, linux requires |
| 390 | | // page align. |
| 391 | | const p_align = 0x1000; |
| 392 | | const off = self.findFreeSpace(file_size, p_align); |
| 393 | | std.log.debug(.link, "found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size }); |
| 394 | | // TODO instead of hard coding the vaddr, make a function to find a vaddr to put things at. |
| 395 | | // we'll need to re-use that function anyway, in case the GOT grows and overlaps something |
| 396 | | // else in virtual memory. |
| 397 | | const default_got_addr = 0x4000000; |
| 398 | | try self.program_headers.append(self.allocator, .{ |
| 399 | | .p_type = elf.PT_LOAD, |
| 400 | | .p_offset = off, |
| 401 | | .p_filesz = file_size, |
| 402 | | .p_vaddr = default_got_addr, |
| 403 | | .p_paddr = default_got_addr, |
| 404 | | .p_memsz = file_size, |
| 405 | | .p_align = p_align, |
| 406 | | .p_flags = elf.PF_R, |
| 407 | | }); |
| 408 | | self.phdr_table_dirty = true; |
| 409 | | } |
| 410 | | if (self.shstrtab_index == null) { |
| 411 | | self.shstrtab_index = @intCast(u16, self.sections.items.len); |
| 412 | | assert(self.shstrtab.items.len == 0); |
| 413 | | try self.shstrtab.append(self.allocator, 0); // need a 0 at position 0 |
| 414 | | const off = self.findFreeSpace(self.shstrtab.items.len, 1); |
| 415 | | std.log.debug(.link, "found shstrtab free space 0x{x} to 0x{x}\n", .{ off, off + self.shstrtab.items.len }); |
| 416 | | try self.sections.append(self.allocator, .{ |
| 417 | | .sh_name = try self.makeString(".shstrtab"), |
| 418 | | .sh_type = elf.SHT_STRTAB, |
| 419 | | .sh_flags = 0, |
| 420 | | .sh_addr = 0, |
| 421 | | .sh_offset = off, |
| 422 | | .sh_size = self.shstrtab.items.len, |
| 423 | | .sh_link = 0, |
| 424 | | .sh_info = 0, |
| 425 | | .sh_addralign = 1, |
| 426 | | .sh_entsize = 0, |
| 427 | | }); |
| 428 | | self.shstrtab_dirty = true; |
| 429 | | self.shdr_table_dirty = true; |
| 430 | | } |
| 431 | | if (self.text_section_index == null) { |
| 432 | | self.text_section_index = @intCast(u16, self.sections.items.len); |
| 433 | | const phdr = &self.program_headers.items[self.phdr_load_re_index.?]; |
| 222 | pub const Tag = enum { |
| 223 | Elf, |
| 224 | C, |
| 225 | }; |
| 434 | 226 | |
| 435 | | try self.sections.append(self.allocator, .{ |
| 436 | | .sh_name = try self.makeString(".text"), |
| 437 | | .sh_type = elf.SHT_PROGBITS, |
| 438 | | .sh_flags = elf.SHF_ALLOC | elf.SHF_EXECINSTR, |
| 439 | | .sh_addr = phdr.p_vaddr, |
| 440 | | .sh_offset = phdr.p_offset, |
| 441 | | .sh_size = phdr.p_filesz, |
| 442 | | .sh_link = 0, |
| 443 | | .sh_info = 0, |
| 444 | | .sh_addralign = phdr.p_align, |
| 445 | | .sh_entsize = 0, |
| 446 | | }); |
| 447 | | self.shdr_table_dirty = true; |
| 227 | pub const ErrorFlags = struct { |
| 228 | no_entry_point_found: bool = false, |
| 229 | }; |
| 230 | |
| 231 | pub const C = struct { |
| 232 | pub const base_tag: Tag = .C; |
| 233 | base: File = File{ .tag = base_tag }, |
| 234 | |
| 235 | allocator: *Allocator, |
| 236 | header: std.ArrayList(u8), |
| 237 | constants: std.ArrayList(u8), |
| 238 | main: std.ArrayList(u8), |
| 239 | file: ?fs.File, |
| 240 | options: Options, |
| 241 | called: std.StringHashMap(void), |
| 242 | need_stddef: bool = false, |
| 243 | need_stdint: bool = false, |
| 244 | need_noreturn: bool = false, |
| 245 | error_msg: *Module.ErrorMsg = undefined, |
| 246 | |
| 247 | pub fn fail(self: *C, src: usize, comptime format: []const u8, args: var) !void { |
| 248 | self.error_msg = try Module.ErrorMsg.create(self.allocator, src, format, args); |
| 249 | return error.CGenFailure; |
| 448 | 250 | } |
| 449 | | if (self.got_section_index == null) { |
| 450 | | self.got_section_index = @intCast(u16, self.sections.items.len); |
| 451 | | const phdr = &self.program_headers.items[self.phdr_got_index.?]; |
| 452 | 251 | |
| 453 | | try self.sections.append(self.allocator, .{ |
| 454 | | .sh_name = try self.makeString(".got"), |
| 455 | | .sh_type = elf.SHT_PROGBITS, |
| 456 | | .sh_flags = elf.SHF_ALLOC, |
| 457 | | .sh_addr = phdr.p_vaddr, |
| 458 | | .sh_offset = phdr.p_offset, |
| 459 | | .sh_size = phdr.p_filesz, |
| 460 | | .sh_link = 0, |
| 461 | | .sh_info = 0, |
| 462 | | .sh_addralign = phdr.p_align, |
| 463 | | .sh_entsize = 0, |
| 464 | | }); |
| 465 | | self.shdr_table_dirty = true; |
| 252 | pub fn deinit(self: *File.C) void { |
| 253 | self.main.deinit(); |
| 254 | self.header.deinit(); |
| 255 | self.constants.deinit(); |
| 256 | self.called.deinit(); |
| 257 | if (self.file) |f| |
| 258 | f.close(); |
| 466 | 259 | } |
| 467 | | if (self.symtab_section_index == null) { |
| 468 | | self.symtab_section_index = @intCast(u16, self.sections.items.len); |
| 469 | | const min_align: u16 = if (small_ptr) @alignOf(elf.Elf32_Sym) else @alignOf(elf.Elf64_Sym); |
| 470 | | const each_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Sym) else @sizeOf(elf.Elf64_Sym); |
| 471 | | const file_size = self.options.symbol_count_hint * each_size; |
| 472 | | const off = self.findFreeSpace(file_size, min_align); |
| 473 | | std.log.debug(.link, "found symtab free space 0x{x} to 0x{x}\n", .{ off, off + file_size }); |
| 474 | | |
| 475 | | try self.sections.append(self.allocator, .{ |
| 476 | | .sh_name = try self.makeString(".symtab"), |
| 477 | | .sh_type = elf.SHT_SYMTAB, |
| 478 | | .sh_flags = 0, |
| 479 | | .sh_addr = 0, |
| 480 | | .sh_offset = off, |
| 481 | | .sh_size = file_size, |
| 482 | | // The section header index of the associated string table. |
| 483 | | .sh_link = self.shstrtab_index.?, |
| 484 | | .sh_info = @intCast(u32, self.local_symbols.items.len), |
| 485 | | .sh_addralign = min_align, |
| 486 | | .sh_entsize = each_size, |
| 487 | | }); |
| 488 | | self.shdr_table_dirty = true; |
| 489 | | try self.writeSymbol(0); |
| 260 | |
| 261 | pub fn updateDecl(self: *File.C, module: *Module, decl: *Module.Decl) !void { |
| 262 | cgen.generate(self, decl) catch |err| { |
| 263 | if (err == error.CGenFailure) { |
| 264 | try module.failed_decls.put(module.gpa, decl, self.error_msg); |
| 265 | } |
| 266 | return err; |
| 267 | }; |
| 490 | 268 | } |
| 491 | | const shsize: u64 = switch (self.ptr_width) { |
| 492 | | .p32 => @sizeOf(elf.Elf32_Shdr), |
| 493 | | .p64 => @sizeOf(elf.Elf64_Shdr), |
| 494 | | }; |
| 495 | | const shalign: u16 = switch (self.ptr_width) { |
| 496 | | .p32 => @alignOf(elf.Elf32_Shdr), |
| 497 | | .p64 => @alignOf(elf.Elf64_Shdr), |
| 498 | | }; |
| 499 | | if (self.shdr_table_offset == null) { |
| 500 | | self.shdr_table_offset = self.findFreeSpace(self.sections.items.len * shsize, shalign); |
| 501 | | self.shdr_table_dirty = true; |
| 269 | |
| 270 | pub fn flush(self: *File.C) !void { |
| 271 | const writer = self.file.?.writer(); |
| 272 | try writer.writeAll(@embedFile("cbe.h")); |
| 273 | var includes = false; |
| 274 | if (self.need_stddef) { |
| 275 | try writer.writeAll("#include <stddef.h>\n"); |
| 276 | includes = true; |
| 277 | } |
| 278 | if (self.need_stdint) { |
| 279 | try writer.writeAll("#include <stdint.h>\n"); |
| 280 | includes = true; |
| 281 | } |
| 282 | if (includes) { |
| 283 | try writer.writeByte('\n'); |
| 284 | } |
| 285 | if (self.header.items.len > 0) { |
| 286 | try writer.print("{}\n", .{self.header.items}); |
| 287 | } |
| 288 | if (self.constants.items.len > 0) { |
| 289 | try writer.print("{}\n", .{self.constants.items}); |
| 290 | } |
| 291 | if (self.main.items.len > 1) { |
| 292 | const last_two = self.main.items[self.main.items.len - 2 ..]; |
| 293 | if (std.mem.eql(u8, last_two, "\n\n")) { |
| 294 | self.main.items.len -= 1; |
| 295 | } |
| 296 | } |
| 297 | try writer.writeAll(self.main.items); |
| 298 | self.file.?.close(); |
| 299 | self.file = null; |
| 502 | 300 | } |
| 503 | | const phsize: u64 = switch (self.ptr_width) { |
| 504 | | .p32 => @sizeOf(elf.Elf32_Phdr), |
| 505 | | .p64 => @sizeOf(elf.Elf64_Phdr), |
| 301 | }; |
| 302 | |
| 303 | pub const Elf = struct { |
| 304 | pub const base_tag: Tag = .Elf; |
| 305 | base: File = File{ .tag = base_tag }, |
| 306 | |
| 307 | allocator: *Allocator, |
| 308 | file: ?fs.File, |
| 309 | owns_file_handle: bool, |
| 310 | options: Options, |
| 311 | ptr_width: enum { p32, p64 }, |
| 312 | |
| 313 | /// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write. |
| 314 | /// Same order as in the file. |
| 315 | sections: std.ArrayListUnmanaged(elf.Elf64_Shdr) = std.ArrayListUnmanaged(elf.Elf64_Shdr){}, |
| 316 | shdr_table_offset: ?u64 = null, |
| 317 | |
| 318 | /// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write. |
| 319 | /// Same order as in the file. |
| 320 | program_headers: std.ArrayListUnmanaged(elf.Elf64_Phdr) = std.ArrayListUnmanaged(elf.Elf64_Phdr){}, |
| 321 | phdr_table_offset: ?u64 = null, |
| 322 | /// The index into the program headers of a PT_LOAD program header with Read and Execute flags |
| 323 | phdr_load_re_index: ?u16 = null, |
| 324 | /// The index into the program headers of the global offset table. |
| 325 | /// It needs PT_LOAD and Read flags. |
| 326 | phdr_got_index: ?u16 = null, |
| 327 | entry_addr: ?u64 = null, |
| 328 | |
| 329 | shstrtab: std.ArrayListUnmanaged(u8) = std.ArrayListUnmanaged(u8){}, |
| 330 | shstrtab_index: ?u16 = null, |
| 331 | |
| 332 | text_section_index: ?u16 = null, |
| 333 | symtab_section_index: ?u16 = null, |
| 334 | got_section_index: ?u16 = null, |
| 335 | |
| 336 | /// The same order as in the file. ELF requires global symbols to all be after the |
| 337 | /// local symbols, they cannot be mixed. So we must buffer all the global symbols and |
| 338 | /// write them at the end. These are only the local symbols. The length of this array |
| 339 | /// is the value used for sh_info in the .symtab section. |
| 340 | local_symbols: std.ArrayListUnmanaged(elf.Elf64_Sym) = std.ArrayListUnmanaged(elf.Elf64_Sym){}, |
| 341 | global_symbols: std.ArrayListUnmanaged(elf.Elf64_Sym) = std.ArrayListUnmanaged(elf.Elf64_Sym){}, |
| 342 | |
| 343 | local_symbol_free_list: std.ArrayListUnmanaged(u32) = std.ArrayListUnmanaged(u32){}, |
| 344 | global_symbol_free_list: std.ArrayListUnmanaged(u32) = std.ArrayListUnmanaged(u32){}, |
| 345 | offset_table_free_list: std.ArrayListUnmanaged(u32) = std.ArrayListUnmanaged(u32){}, |
| 346 | |
| 347 | /// Same order as in the file. The value is the absolute vaddr value. |
| 348 | /// If the vaddr of the executable program header changes, the entire |
| 349 | /// offset table needs to be rewritten. |
| 350 | offset_table: std.ArrayListUnmanaged(u64) = std.ArrayListUnmanaged(u64){}, |
| 351 | |
| 352 | phdr_table_dirty: bool = false, |
| 353 | shdr_table_dirty: bool = false, |
| 354 | shstrtab_dirty: bool = false, |
| 355 | offset_table_count_dirty: bool = false, |
| 356 | |
| 357 | error_flags: ErrorFlags = ErrorFlags{}, |
| 358 | |
| 359 | /// A list of text blocks that have surplus capacity. This list can have false |
| 360 | /// positives, as functions grow and shrink over time, only sometimes being added |
| 361 | /// or removed from the freelist. |
| 362 | /// |
| 363 | /// A text block has surplus capacity when its overcapacity value is greater than |
| 364 | /// minimum_text_block_size * alloc_num / alloc_den. That is, when it has so |
| 365 | /// much extra capacity, that we could fit a small new symbol in it, itself with |
| 366 | /// ideal_capacity or more. |
| 367 | /// |
| 368 | /// Ideal capacity is defined by size * alloc_num / alloc_den. |
| 369 | /// |
| 370 | /// Overcapacity is measured by actual_capacity - ideal_capacity. Note that |
| 371 | /// overcapacity can be negative. A simple way to have negative overcapacity is to |
| 372 | /// allocate a fresh text block, which will have ideal capacity, and then grow it |
| 373 | /// by 1 byte. It will then have -1 overcapacity. |
| 374 | text_block_free_list: std.ArrayListUnmanaged(*TextBlock) = std.ArrayListUnmanaged(*TextBlock){}, |
| 375 | last_text_block: ?*TextBlock = null, |
| 376 | |
| 377 | /// `alloc_num / alloc_den` is the factor of padding when allocating. |
| 378 | const alloc_num = 4; |
| 379 | const alloc_den = 3; |
| 380 | |
| 381 | /// In order for a slice of bytes to be considered eligible to keep metadata pointing at |
| 382 | /// it as a possible place to put new symbols, it must have enough room for this many bytes |
| 383 | /// (plus extra for reserved capacity). |
| 384 | const minimum_text_block_size = 64; |
| 385 | const min_text_capacity = minimum_text_block_size * alloc_num / alloc_den; |
| 386 | |
| 387 | pub const TextBlock = struct { |
| 388 | /// Each decl always gets a local symbol with the fully qualified name. |
| 389 | /// The vaddr and size are found here directly. |
| 390 | /// The file offset is found by computing the vaddr offset from the section vaddr |
| 391 | /// the symbol references, and adding that to the file offset of the section. |
| 392 | /// If this field is 0, it means the codegen size = 0 and there is no symbol or |
| 393 | /// offset table entry. |
| 394 | local_sym_index: u32, |
| 395 | /// This field is undefined for symbols with size = 0. |
| 396 | offset_table_index: u32, |
| 397 | /// Points to the previous and next neighbors, based on the `text_offset`. |
| 398 | /// This can be used to find, for example, the capacity of this `TextBlock`. |
| 399 | prev: ?*TextBlock, |
| 400 | next: ?*TextBlock, |
| 401 | |
| 402 | pub const empty = TextBlock{ |
| 403 | .local_sym_index = 0, |
| 404 | .offset_table_index = undefined, |
| 405 | .prev = null, |
| 406 | .next = null, |
| 407 | }; |
| 408 | |
| 409 | /// Returns how much room there is to grow in virtual address space. |
| 410 | /// File offset relocation happens transparently, so it is not included in |
| 411 | /// this calculation. |
| 412 | fn capacity(self: TextBlock, elf_file: Elf) u64 { |
| 413 | const self_sym = elf_file.local_symbols.items[self.local_sym_index]; |
| 414 | if (self.next) |next| { |
| 415 | const next_sym = elf_file.local_symbols.items[next.local_sym_index]; |
| 416 | return next_sym.st_value - self_sym.st_value; |
| 417 | } else { |
| 418 | // We are the last block. The capacity is limited only by virtual address space. |
| 419 | return std.math.maxInt(u32) - self_sym.st_value; |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | fn freeListEligible(self: TextBlock, elf_file: Elf) bool { |
| 424 | // No need to keep a free list node for the last block. |
| 425 | const next = self.next orelse return false; |
| 426 | const self_sym = elf_file.local_symbols.items[self.local_sym_index]; |
| 427 | const next_sym = elf_file.local_symbols.items[next.local_sym_index]; |
| 428 | const cap = next_sym.st_value - self_sym.st_value; |
| 429 | const ideal_cap = self_sym.st_size * alloc_num / alloc_den; |
| 430 | if (cap <= ideal_cap) return false; |
| 431 | const surplus = cap - ideal_cap; |
| 432 | return surplus >= min_text_capacity; |
| 433 | } |
| 506 | 434 | }; |
| 507 | | const phalign: u16 = switch (self.ptr_width) { |
| 508 | | .p32 => @alignOf(elf.Elf32_Phdr), |
| 509 | | .p64 => @alignOf(elf.Elf64_Phdr), |
| 435 | |
| 436 | pub const Export = struct { |
| 437 | sym_index: ?u32 = null, |
| 510 | 438 | }; |
| 511 | | if (self.phdr_table_offset == null) { |
| 512 | | self.phdr_table_offset = self.findFreeSpace(self.program_headers.items.len * phsize, phalign); |
| 513 | | self.phdr_table_dirty = true; |
| 514 | | } |
| 515 | | { |
| 516 | | // Iterate over symbols, populating free_list and last_text_block. |
| 517 | | if (self.local_symbols.items.len != 1) { |
| 518 | | @panic("TODO implement setting up free_list and last_text_block from existing ELF file"); |
| 439 | |
| 440 | pub fn deinit(self: *Elf) void { |
| 441 | self.sections.deinit(self.allocator); |
| 442 | self.program_headers.deinit(self.allocator); |
| 443 | self.shstrtab.deinit(self.allocator); |
| 444 | self.local_symbols.deinit(self.allocator); |
| 445 | self.global_symbols.deinit(self.allocator); |
| 446 | self.global_symbol_free_list.deinit(self.allocator); |
| 447 | self.local_symbol_free_list.deinit(self.allocator); |
| 448 | self.offset_table_free_list.deinit(self.allocator); |
| 449 | self.text_block_free_list.deinit(self.allocator); |
| 450 | self.offset_table.deinit(self.allocator); |
| 451 | if (self.owns_file_handle) { |
| 452 | if (self.file) |f| f.close(); |
| 519 | 453 | } |
| 520 | | // We are starting with an empty file. The default values are correct, null and empty list. |
| 521 | 454 | } |
| 522 | | } |
| 523 | 455 | |
| 524 | | /// Commit pending changes and write headers. |
| 525 | | pub fn flush(self: *ElfFile) !void { |
| 526 | | const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian(); |
| 456 | pub fn makeExecutable(self: *Elf) !void { |
| 457 | assert(self.owns_file_handle); |
| 458 | if (self.file) |f| { |
| 459 | f.close(); |
| 460 | self.file = null; |
| 461 | } |
| 462 | } |
| 527 | 463 | |
| 528 | | // Unfortunately these have to be buffered and done at the end because ELF does not allow |
| 529 | | // mixing local and global symbols within a symbol table. |
| 530 | | try self.writeAllGlobalSymbols(); |
| 464 | pub fn makeWritable(self: *Elf, dir: fs.Dir, sub_path: []const u8) !void { |
| 465 | assert(self.owns_file_handle); |
| 466 | if (self.file != null) return; |
| 467 | self.file = try dir.createFile(sub_path, .{ |
| 468 | .truncate = false, |
| 469 | .read = true, |
| 470 | .mode = determineMode(self.options), |
| 471 | }); |
| 472 | } |
| 531 | 473 | |
| 532 | | if (self.phdr_table_dirty) { |
| 533 | | const phsize: u64 = switch (self.ptr_width) { |
| 534 | | .p32 => @sizeOf(elf.Elf32_Phdr), |
| 535 | | .p64 => @sizeOf(elf.Elf64_Phdr), |
| 536 | | }; |
| 537 | | const phalign: u16 = switch (self.ptr_width) { |
| 538 | | .p32 => @alignOf(elf.Elf32_Phdr), |
| 539 | | .p64 => @alignOf(elf.Elf64_Phdr), |
| 540 | | }; |
| 541 | | const allocated_size = self.allocatedSize(self.phdr_table_offset.?); |
| 542 | | const needed_size = self.program_headers.items.len * phsize; |
| 474 | /// Returns end pos of collision, if any. |
| 475 | fn detectAllocCollision(self: *Elf, start: u64, size: u64) ?u64 { |
| 476 | const small_ptr = self.options.target.cpu.arch.ptrBitWidth() == 32; |
| 477 | const ehdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Ehdr) else @sizeOf(elf.Elf64_Ehdr); |
| 478 | if (start < ehdr_size) |
| 479 | return ehdr_size; |
| 480 | |
| 481 | const end = start + satMul(size, alloc_num) / alloc_den; |
| 482 | |
| 483 | if (self.shdr_table_offset) |off| { |
| 484 | const shdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Shdr) else @sizeOf(elf.Elf64_Shdr); |
| 485 | const tight_size = self.sections.items.len * shdr_size; |
| 486 | const increased_size = satMul(tight_size, alloc_num) / alloc_den; |
| 487 | const test_end = off + increased_size; |
| 488 | if (end > off and start < test_end) { |
| 489 | return test_end; |
| 490 | } |
| 491 | } |
| 543 | 492 | |
| 544 | | if (needed_size > allocated_size) { |
| 545 | | self.phdr_table_offset = null; // free the space |
| 546 | | self.phdr_table_offset = self.findFreeSpace(needed_size, phalign); |
| 493 | if (self.phdr_table_offset) |off| { |
| 494 | const phdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Phdr) else @sizeOf(elf.Elf64_Phdr); |
| 495 | const tight_size = self.sections.items.len * phdr_size; |
| 496 | const increased_size = satMul(tight_size, alloc_num) / alloc_den; |
| 497 | const test_end = off + increased_size; |
| 498 | if (end > off and start < test_end) { |
| 499 | return test_end; |
| 500 | } |
| 547 | 501 | } |
| 548 | 502 | |
| 549 | | switch (self.ptr_width) { |
| 550 | | .p32 => { |
| 551 | | const buf = try self.allocator.alloc(elf.Elf32_Phdr, self.program_headers.items.len); |
| 552 | | defer self.allocator.free(buf); |
| 503 | for (self.sections.items) |section| { |
| 504 | const increased_size = satMul(section.sh_size, alloc_num) / alloc_den; |
| 505 | const test_end = section.sh_offset + increased_size; |
| 506 | if (end > section.sh_offset and start < test_end) { |
| 507 | return test_end; |
| 508 | } |
| 509 | } |
| 510 | for (self.program_headers.items) |program_header| { |
| 511 | const increased_size = satMul(program_header.p_filesz, alloc_num) / alloc_den; |
| 512 | const test_end = program_header.p_offset + increased_size; |
| 513 | if (end > program_header.p_offset and start < test_end) { |
| 514 | return test_end; |
| 515 | } |
| 516 | } |
| 517 | return null; |
| 518 | } |
| 553 | 519 | |
| 554 | | for (buf) |*phdr, i| { |
| 555 | | phdr.* = progHeaderTo32(self.program_headers.items[i]); |
| 556 | | if (foreign_endian) { |
| 557 | | bswapAllFields(elf.Elf32_Phdr, phdr); |
| 558 | | } |
| 559 | | } |
| 560 | | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.phdr_table_offset.?); |
| 561 | | }, |
| 562 | | .p64 => { |
| 563 | | const buf = try self.allocator.alloc(elf.Elf64_Phdr, self.program_headers.items.len); |
| 564 | | defer self.allocator.free(buf); |
| 520 | fn allocatedSize(self: *Elf, start: u64) u64 { |
| 521 | var min_pos: u64 = std.math.maxInt(u64); |
| 522 | if (self.shdr_table_offset) |off| { |
| 523 | if (off > start and off < min_pos) min_pos = off; |
| 524 | } |
| 525 | if (self.phdr_table_offset) |off| { |
| 526 | if (off > start and off < min_pos) min_pos = off; |
| 527 | } |
| 528 | for (self.sections.items) |section| { |
| 529 | if (section.sh_offset <= start) continue; |
| 530 | if (section.sh_offset < min_pos) min_pos = section.sh_offset; |
| 531 | } |
| 532 | for (self.program_headers.items) |program_header| { |
| 533 | if (program_header.p_offset <= start) continue; |
| 534 | if (program_header.p_offset < min_pos) min_pos = program_header.p_offset; |
| 535 | } |
| 536 | return min_pos - start; |
| 537 | } |
| 565 | 538 | |
| 566 | | for (buf) |*phdr, i| { |
| 567 | | phdr.* = self.program_headers.items[i]; |
| 568 | | if (foreign_endian) { |
| 569 | | bswapAllFields(elf.Elf64_Phdr, phdr); |
| 570 | | } |
| 571 | | } |
| 572 | | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.phdr_table_offset.?); |
| 573 | | }, |
| 539 | fn findFreeSpace(self: *Elf, object_size: u64, min_alignment: u16) u64 { |
| 540 | var start: u64 = 0; |
| 541 | while (self.detectAllocCollision(start, object_size)) |item_end| { |
| 542 | start = mem.alignForwardGeneric(u64, item_end, min_alignment); |
| 574 | 543 | } |
| 575 | | self.phdr_table_dirty = false; |
| 544 | return start; |
| 576 | 545 | } |
| 577 | 546 | |
| 578 | | { |
| 579 | | const shstrtab_sect = &self.sections.items[self.shstrtab_index.?]; |
| 580 | | if (self.shstrtab_dirty or self.shstrtab.items.len != shstrtab_sect.sh_size) { |
| 581 | | const allocated_size = self.allocatedSize(shstrtab_sect.sh_offset); |
| 582 | | const needed_size = self.shstrtab.items.len; |
| 547 | fn makeString(self: *Elf, bytes: []const u8) !u32 { |
| 548 | try self.shstrtab.ensureCapacity(self.allocator, self.shstrtab.items.len + bytes.len + 1); |
| 549 | const result = self.shstrtab.items.len; |
| 550 | self.shstrtab.appendSliceAssumeCapacity(bytes); |
| 551 | self.shstrtab.appendAssumeCapacity(0); |
| 552 | return @intCast(u32, result); |
| 553 | } |
| 583 | 554 | |
| 584 | | if (needed_size > allocated_size) { |
| 585 | | shstrtab_sect.sh_size = 0; // free the space |
| 586 | | shstrtab_sect.sh_offset = self.findFreeSpace(needed_size, 1); |
| 587 | | } |
| 588 | | shstrtab_sect.sh_size = needed_size; |
| 589 | | std.log.debug(.link, "shstrtab start=0x{x} end=0x{x}\n", .{ shstrtab_sect.sh_offset, shstrtab_sect.sh_offset + needed_size }); |
| 555 | fn getString(self: *Elf, str_off: u32) []const u8 { |
| 556 | assert(str_off < self.shstrtab.items.len); |
| 557 | return mem.spanZ(@ptrCast([*:0]const u8, self.shstrtab.items.ptr + str_off)); |
| 558 | } |
| 590 | 559 | |
| 591 | | try self.file.?.pwriteAll(self.shstrtab.items, shstrtab_sect.sh_offset); |
| 592 | | if (!self.shdr_table_dirty) { |
| 593 | | // Then it won't get written with the others and we need to do it. |
| 594 | | try self.writeSectHeader(self.shstrtab_index.?); |
| 595 | | } |
| 596 | | self.shstrtab_dirty = false; |
| 560 | fn updateString(self: *Elf, old_str_off: u32, new_name: []const u8) !u32 { |
| 561 | const existing_name = self.getString(old_str_off); |
| 562 | if (mem.eql(u8, existing_name, new_name)) { |
| 563 | return old_str_off; |
| 597 | 564 | } |
| 565 | return self.makeString(new_name); |
| 598 | 566 | } |
| 599 | | if (self.shdr_table_dirty) { |
| 567 | |
| 568 | pub fn populateMissingMetadata(self: *Elf) !void { |
| 569 | const small_ptr = switch (self.ptr_width) { |
| 570 | .p32 => true, |
| 571 | .p64 => false, |
| 572 | }; |
| 573 | const ptr_size: u8 = switch (self.ptr_width) { |
| 574 | .p32 => 4, |
| 575 | .p64 => 8, |
| 576 | }; |
| 577 | if (self.phdr_load_re_index == null) { |
| 578 | self.phdr_load_re_index = @intCast(u16, self.program_headers.items.len); |
| 579 | const file_size = self.options.program_code_size_hint; |
| 580 | const p_align = 0x1000; |
| 581 | const off = self.findFreeSpace(file_size, p_align); |
| 582 | std.log.debug(.link, "found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size }); |
| 583 | try self.program_headers.append(self.allocator, .{ |
| 584 | .p_type = elf.PT_LOAD, |
| 585 | .p_offset = off, |
| 586 | .p_filesz = file_size, |
| 587 | .p_vaddr = default_entry_addr, |
| 588 | .p_paddr = default_entry_addr, |
| 589 | .p_memsz = file_size, |
| 590 | .p_align = p_align, |
| 591 | .p_flags = elf.PF_X | elf.PF_R, |
| 592 | }); |
| 593 | self.entry_addr = null; |
| 594 | self.phdr_table_dirty = true; |
| 595 | } |
| 596 | if (self.phdr_got_index == null) { |
| 597 | self.phdr_got_index = @intCast(u16, self.program_headers.items.len); |
| 598 | const file_size = @as(u64, ptr_size) * self.options.symbol_count_hint; |
| 599 | // We really only need ptr alignment but since we are using PROGBITS, linux requires |
| 600 | // page align. |
| 601 | const p_align = 0x1000; |
| 602 | const off = self.findFreeSpace(file_size, p_align); |
| 603 | std.log.debug(.link, "found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size }); |
| 604 | // TODO instead of hard coding the vaddr, make a function to find a vaddr to put things at. |
| 605 | // we'll need to re-use that function anyway, in case the GOT grows and overlaps something |
| 606 | // else in virtual memory. |
| 607 | const default_got_addr = 0x4000000; |
| 608 | try self.program_headers.append(self.allocator, .{ |
| 609 | .p_type = elf.PT_LOAD, |
| 610 | .p_offset = off, |
| 611 | .p_filesz = file_size, |
| 612 | .p_vaddr = default_got_addr, |
| 613 | .p_paddr = default_got_addr, |
| 614 | .p_memsz = file_size, |
| 615 | .p_align = p_align, |
| 616 | .p_flags = elf.PF_R, |
| 617 | }); |
| 618 | self.phdr_table_dirty = true; |
| 619 | } |
| 620 | if (self.shstrtab_index == null) { |
| 621 | self.shstrtab_index = @intCast(u16, self.sections.items.len); |
| 622 | assert(self.shstrtab.items.len == 0); |
| 623 | try self.shstrtab.append(self.allocator, 0); // need a 0 at position 0 |
| 624 | const off = self.findFreeSpace(self.shstrtab.items.len, 1); |
| 625 | std.log.debug(.link, "found shstrtab free space 0x{x} to 0x{x}\n", .{ off, off + self.shstrtab.items.len }); |
| 626 | try self.sections.append(self.allocator, .{ |
| 627 | .sh_name = try self.makeString(".shstrtab"), |
| 628 | .sh_type = elf.SHT_STRTAB, |
| 629 | .sh_flags = 0, |
| 630 | .sh_addr = 0, |
| 631 | .sh_offset = off, |
| 632 | .sh_size = self.shstrtab.items.len, |
| 633 | .sh_link = 0, |
| 634 | .sh_info = 0, |
| 635 | .sh_addralign = 1, |
| 636 | .sh_entsize = 0, |
| 637 | }); |
| 638 | self.shstrtab_dirty = true; |
| 639 | self.shdr_table_dirty = true; |
| 640 | } |
| 641 | if (self.text_section_index == null) { |
| 642 | self.text_section_index = @intCast(u16, self.sections.items.len); |
| 643 | const phdr = &self.program_headers.items[self.phdr_load_re_index.?]; |
| 644 | |
| 645 | try self.sections.append(self.allocator, .{ |
| 646 | .sh_name = try self.makeString(".text"), |
| 647 | .sh_type = elf.SHT_PROGBITS, |
| 648 | .sh_flags = elf.SHF_ALLOC | elf.SHF_EXECINSTR, |
| 649 | .sh_addr = phdr.p_vaddr, |
| 650 | .sh_offset = phdr.p_offset, |
| 651 | .sh_size = phdr.p_filesz, |
| 652 | .sh_link = 0, |
| 653 | .sh_info = 0, |
| 654 | .sh_addralign = phdr.p_align, |
| 655 | .sh_entsize = 0, |
| 656 | }); |
| 657 | self.shdr_table_dirty = true; |
| 658 | } |
| 659 | if (self.got_section_index == null) { |
| 660 | self.got_section_index = @intCast(u16, self.sections.items.len); |
| 661 | const phdr = &self.program_headers.items[self.phdr_got_index.?]; |
| 662 | |
| 663 | try self.sections.append(self.allocator, .{ |
| 664 | .sh_name = try self.makeString(".got"), |
| 665 | .sh_type = elf.SHT_PROGBITS, |
| 666 | .sh_flags = elf.SHF_ALLOC, |
| 667 | .sh_addr = phdr.p_vaddr, |
| 668 | .sh_offset = phdr.p_offset, |
| 669 | .sh_size = phdr.p_filesz, |
| 670 | .sh_link = 0, |
| 671 | .sh_info = 0, |
| 672 | .sh_addralign = phdr.p_align, |
| 673 | .sh_entsize = 0, |
| 674 | }); |
| 675 | self.shdr_table_dirty = true; |
| 676 | } |
| 677 | if (self.symtab_section_index == null) { |
| 678 | self.symtab_section_index = @intCast(u16, self.sections.items.len); |
| 679 | const min_align: u16 = if (small_ptr) @alignOf(elf.Elf32_Sym) else @alignOf(elf.Elf64_Sym); |
| 680 | const each_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Sym) else @sizeOf(elf.Elf64_Sym); |
| 681 | const file_size = self.options.symbol_count_hint * each_size; |
| 682 | const off = self.findFreeSpace(file_size, min_align); |
| 683 | std.log.debug(.link, "found symtab free space 0x{x} to 0x{x}\n", .{ off, off + file_size }); |
| 684 | |
| 685 | try self.sections.append(self.allocator, .{ |
| 686 | .sh_name = try self.makeString(".symtab"), |
| 687 | .sh_type = elf.SHT_SYMTAB, |
| 688 | .sh_flags = 0, |
| 689 | .sh_addr = 0, |
| 690 | .sh_offset = off, |
| 691 | .sh_size = file_size, |
| 692 | // The section header index of the associated string table. |
| 693 | .sh_link = self.shstrtab_index.?, |
| 694 | .sh_info = @intCast(u32, self.local_symbols.items.len), |
| 695 | .sh_addralign = min_align, |
| 696 | .sh_entsize = each_size, |
| 697 | }); |
| 698 | self.shdr_table_dirty = true; |
| 699 | try self.writeSymbol(0); |
| 700 | } |
| 600 | 701 | const shsize: u64 = switch (self.ptr_width) { |
| 601 | 702 | .p32 => @sizeOf(elf.Elf32_Shdr), |
| 602 | 703 | .p64 => @sizeOf(elf.Elf64_Shdr), |
| ... | ... | @@ -605,757 +706,867 @@ pub const ElfFile = struct { |
| 605 | 706 | .p32 => @alignOf(elf.Elf32_Shdr), |
| 606 | 707 | .p64 => @alignOf(elf.Elf64_Shdr), |
| 607 | 708 | }; |
| 608 | | const allocated_size = self.allocatedSize(self.shdr_table_offset.?); |
| 609 | | const needed_size = self.sections.items.len * shsize; |
| 610 | | |
| 611 | | if (needed_size > allocated_size) { |
| 612 | | self.shdr_table_offset = null; // free the space |
| 613 | | self.shdr_table_offset = self.findFreeSpace(needed_size, shalign); |
| 709 | if (self.shdr_table_offset == null) { |
| 710 | self.shdr_table_offset = self.findFreeSpace(self.sections.items.len * shsize, shalign); |
| 711 | self.shdr_table_dirty = true; |
| 712 | } |
| 713 | const phsize: u64 = switch (self.ptr_width) { |
| 714 | .p32 => @sizeOf(elf.Elf32_Phdr), |
| 715 | .p64 => @sizeOf(elf.Elf64_Phdr), |
| 716 | }; |
| 717 | const phalign: u16 = switch (self.ptr_width) { |
| 718 | .p32 => @alignOf(elf.Elf32_Phdr), |
| 719 | .p64 => @alignOf(elf.Elf64_Phdr), |
| 720 | }; |
| 721 | if (self.phdr_table_offset == null) { |
| 722 | self.phdr_table_offset = self.findFreeSpace(self.program_headers.items.len * phsize, phalign); |
| 723 | self.phdr_table_dirty = true; |
| 724 | } |
| 725 | { |
| 726 | // Iterate over symbols, populating free_list and last_text_block. |
| 727 | if (self.local_symbols.items.len != 1) { |
| 728 | @panic("TODO implement setting up free_list and last_text_block from existing ELF file"); |
| 729 | } |
| 730 | // We are starting with an empty file. The default values are correct, null and empty list. |
| 614 | 731 | } |
| 732 | } |
| 615 | 733 | |
| 616 | | switch (self.ptr_width) { |
| 617 | | .p32 => { |
| 618 | | const buf = try self.allocator.alloc(elf.Elf32_Shdr, self.sections.items.len); |
| 619 | | defer self.allocator.free(buf); |
| 734 | /// Commit pending changes and write headers. |
| 735 | pub fn flush(self: *Elf) !void { |
| 736 | const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian(); |
| 620 | 737 | |
| 621 | | for (buf) |*shdr, i| { |
| 622 | | shdr.* = sectHeaderTo32(self.sections.items[i]); |
| 623 | | if (foreign_endian) { |
| 624 | | bswapAllFields(elf.Elf32_Shdr, shdr); |
| 738 | // Unfortunately these have to be buffered and done at the end because ELF does not allow |
| 739 | // mixing local and global symbols within a symbol table. |
| 740 | try self.writeAllGlobalSymbols(); |
| 741 | |
| 742 | if (self.phdr_table_dirty) { |
| 743 | const phsize: u64 = switch (self.ptr_width) { |
| 744 | .p32 => @sizeOf(elf.Elf32_Phdr), |
| 745 | .p64 => @sizeOf(elf.Elf64_Phdr), |
| 746 | }; |
| 747 | const phalign: u16 = switch (self.ptr_width) { |
| 748 | .p32 => @alignOf(elf.Elf32_Phdr), |
| 749 | .p64 => @alignOf(elf.Elf64_Phdr), |
| 750 | }; |
| 751 | const allocated_size = self.allocatedSize(self.phdr_table_offset.?); |
| 752 | const needed_size = self.program_headers.items.len * phsize; |
| 753 | |
| 754 | if (needed_size > allocated_size) { |
| 755 | self.phdr_table_offset = null; // free the space |
| 756 | self.phdr_table_offset = self.findFreeSpace(needed_size, phalign); |
| 757 | } |
| 758 | |
| 759 | switch (self.ptr_width) { |
| 760 | .p32 => { |
| 761 | const buf = try self.allocator.alloc(elf.Elf32_Phdr, self.program_headers.items.len); |
| 762 | defer self.allocator.free(buf); |
| 763 | |
| 764 | for (buf) |*phdr, i| { |
| 765 | phdr.* = progHeaderTo32(self.program_headers.items[i]); |
| 766 | if (foreign_endian) { |
| 767 | bswapAllFields(elf.Elf32_Phdr, phdr); |
| 768 | } |
| 625 | 769 | } |
| 770 | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.phdr_table_offset.?); |
| 771 | }, |
| 772 | .p64 => { |
| 773 | const buf = try self.allocator.alloc(elf.Elf64_Phdr, self.program_headers.items.len); |
| 774 | defer self.allocator.free(buf); |
| 775 | |
| 776 | for (buf) |*phdr, i| { |
| 777 | phdr.* = self.program_headers.items[i]; |
| 778 | if (foreign_endian) { |
| 779 | bswapAllFields(elf.Elf64_Phdr, phdr); |
| 780 | } |
| 781 | } |
| 782 | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.phdr_table_offset.?); |
| 783 | }, |
| 784 | } |
| 785 | self.phdr_table_dirty = false; |
| 786 | } |
| 787 | |
| 788 | { |
| 789 | const shstrtab_sect = &self.sections.items[self.shstrtab_index.?]; |
| 790 | if (self.shstrtab_dirty or self.shstrtab.items.len != shstrtab_sect.sh_size) { |
| 791 | const allocated_size = self.allocatedSize(shstrtab_sect.sh_offset); |
| 792 | const needed_size = self.shstrtab.items.len; |
| 793 | |
| 794 | if (needed_size > allocated_size) { |
| 795 | shstrtab_sect.sh_size = 0; // free the space |
| 796 | shstrtab_sect.sh_offset = self.findFreeSpace(needed_size, 1); |
| 626 | 797 | } |
| 627 | | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.shdr_table_offset.?); |
| 628 | | }, |
| 629 | | .p64 => { |
| 630 | | const buf = try self.allocator.alloc(elf.Elf64_Shdr, self.sections.items.len); |
| 631 | | defer self.allocator.free(buf); |
| 798 | shstrtab_sect.sh_size = needed_size; |
| 799 | std.log.debug(.link, "shstrtab start=0x{x} end=0x{x}\n", .{ shstrtab_sect.sh_offset, shstrtab_sect.sh_offset + needed_size }); |
| 632 | 800 | |
| 633 | | for (buf) |*shdr, i| { |
| 634 | | shdr.* = self.sections.items[i]; |
| 635 | | std.log.debug(.link, "writing section {}\n", .{shdr.*}); |
| 636 | | if (foreign_endian) { |
| 637 | | bswapAllFields(elf.Elf64_Shdr, shdr); |
| 638 | | } |
| 801 | try self.file.?.pwriteAll(self.shstrtab.items, shstrtab_sect.sh_offset); |
| 802 | if (!self.shdr_table_dirty) { |
| 803 | // Then it won't get written with the others and we need to do it. |
| 804 | try self.writeSectHeader(self.shstrtab_index.?); |
| 639 | 805 | } |
| 640 | | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.shdr_table_offset.?); |
| 641 | | }, |
| 806 | self.shstrtab_dirty = false; |
| 807 | } |
| 642 | 808 | } |
| 643 | | self.shdr_table_dirty = false; |
| 644 | | } |
| 645 | | if (self.entry_addr == null and self.options.output_mode == .Exe) { |
| 646 | | std.log.debug(.link, "no_entry_point_found = true\n", .{}); |
| 647 | | self.error_flags.no_entry_point_found = true; |
| 648 | | } else { |
| 649 | | self.error_flags.no_entry_point_found = false; |
| 650 | | try self.writeElfHeader(); |
| 651 | | } |
| 809 | if (self.shdr_table_dirty) { |
| 810 | const shsize: u64 = switch (self.ptr_width) { |
| 811 | .p32 => @sizeOf(elf.Elf32_Shdr), |
| 812 | .p64 => @sizeOf(elf.Elf64_Shdr), |
| 813 | }; |
| 814 | const shalign: u16 = switch (self.ptr_width) { |
| 815 | .p32 => @alignOf(elf.Elf32_Shdr), |
| 816 | .p64 => @alignOf(elf.Elf64_Shdr), |
| 817 | }; |
| 818 | const allocated_size = self.allocatedSize(self.shdr_table_offset.?); |
| 819 | const needed_size = self.sections.items.len * shsize; |
| 652 | 820 | |
| 653 | | // The point of flush() is to commit changes, so nothing should be dirty after this. |
| 654 | | assert(!self.phdr_table_dirty); |
| 655 | | assert(!self.shdr_table_dirty); |
| 656 | | assert(!self.shstrtab_dirty); |
| 657 | | assert(!self.offset_table_count_dirty); |
| 658 | | const syms_sect = &self.sections.items[self.symtab_section_index.?]; |
| 659 | | assert(syms_sect.sh_info == self.local_symbols.items.len); |
| 660 | | } |
| 821 | if (needed_size > allocated_size) { |
| 822 | self.shdr_table_offset = null; // free the space |
| 823 | self.shdr_table_offset = self.findFreeSpace(needed_size, shalign); |
| 824 | } |
| 661 | 825 | |
| 662 | | fn writeElfHeader(self: *ElfFile) !void { |
| 663 | | var hdr_buf: [@sizeOf(elf.Elf64_Ehdr)]u8 = undefined; |
| 826 | switch (self.ptr_width) { |
| 827 | .p32 => { |
| 828 | const buf = try self.allocator.alloc(elf.Elf32_Shdr, self.sections.items.len); |
| 829 | defer self.allocator.free(buf); |
| 664 | 830 | |
| 665 | | var index: usize = 0; |
| 666 | | hdr_buf[0..4].* = "\x7fELF".*; |
| 667 | | index += 4; |
| 831 | for (buf) |*shdr, i| { |
| 832 | shdr.* = sectHeaderTo32(self.sections.items[i]); |
| 833 | if (foreign_endian) { |
| 834 | bswapAllFields(elf.Elf32_Shdr, shdr); |
| 835 | } |
| 836 | } |
| 837 | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.shdr_table_offset.?); |
| 838 | }, |
| 839 | .p64 => { |
| 840 | const buf = try self.allocator.alloc(elf.Elf64_Shdr, self.sections.items.len); |
| 841 | defer self.allocator.free(buf); |
| 842 | |
| 843 | for (buf) |*shdr, i| { |
| 844 | shdr.* = self.sections.items[i]; |
| 845 | std.log.debug(.link, "writing section {}\n", .{shdr.*}); |
| 846 | if (foreign_endian) { |
| 847 | bswapAllFields(elf.Elf64_Shdr, shdr); |
| 848 | } |
| 849 | } |
| 850 | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), self.shdr_table_offset.?); |
| 851 | }, |
| 852 | } |
| 853 | self.shdr_table_dirty = false; |
| 854 | } |
| 855 | if (self.entry_addr == null and self.options.output_mode == .Exe) { |
| 856 | std.log.debug(.link, "no_entry_point_found = true\n", .{}); |
| 857 | self.error_flags.no_entry_point_found = true; |
| 858 | } else { |
| 859 | self.error_flags.no_entry_point_found = false; |
| 860 | try self.writeElfHeader(); |
| 861 | } |
| 668 | 862 | |
| 669 | | hdr_buf[index] = switch (self.ptr_width) { |
| 670 | | .p32 => elf.ELFCLASS32, |
| 671 | | .p64 => elf.ELFCLASS64, |
| 672 | | }; |
| 673 | | index += 1; |
| 863 | // The point of flush() is to commit changes, so nothing should be dirty after this. |
| 864 | assert(!self.phdr_table_dirty); |
| 865 | assert(!self.shdr_table_dirty); |
| 866 | assert(!self.shstrtab_dirty); |
| 867 | assert(!self.offset_table_count_dirty); |
| 868 | const syms_sect = &self.sections.items[self.symtab_section_index.?]; |
| 869 | assert(syms_sect.sh_info == self.local_symbols.items.len); |
| 870 | } |
| 674 | 871 | |
| 675 | | const endian = self.options.target.cpu.arch.endian(); |
| 676 | | hdr_buf[index] = switch (endian) { |
| 677 | | .Little => elf.ELFDATA2LSB, |
| 678 | | .Big => elf.ELFDATA2MSB, |
| 679 | | }; |
| 680 | | index += 1; |
| 872 | fn writeElfHeader(self: *Elf) !void { |
| 873 | var hdr_buf: [@sizeOf(elf.Elf64_Ehdr)]u8 = undefined; |
| 681 | 874 | |
| 682 | | hdr_buf[index] = 1; // ELF version |
| 683 | | index += 1; |
| 875 | var index: usize = 0; |
| 876 | hdr_buf[0..4].* = "\x7fELF".*; |
| 877 | index += 4; |
| 684 | 878 | |
| 685 | | // OS ABI, often set to 0 regardless of target platform |
| 686 | | // ABI Version, possibly used by glibc but not by static executables |
| 687 | | // padding |
| 688 | | mem.set(u8, hdr_buf[index..][0..9], 0); |
| 689 | | index += 9; |
| 879 | hdr_buf[index] = switch (self.ptr_width) { |
| 880 | .p32 => elf.ELFCLASS32, |
| 881 | .p64 => elf.ELFCLASS64, |
| 882 | }; |
| 883 | index += 1; |
| 690 | 884 | |
| 691 | | assert(index == 16); |
| 885 | const endian = self.options.target.cpu.arch.endian(); |
| 886 | hdr_buf[index] = switch (endian) { |
| 887 | .Little => elf.ELFDATA2LSB, |
| 888 | .Big => elf.ELFDATA2MSB, |
| 889 | }; |
| 890 | index += 1; |
| 692 | 891 | |
| 693 | | const elf_type = switch (self.options.output_mode) { |
| 694 | | .Exe => elf.ET.EXEC, |
| 695 | | .Obj => elf.ET.REL, |
| 696 | | .Lib => switch (self.options.link_mode) { |
| 697 | | .Static => elf.ET.REL, |
| 698 | | .Dynamic => elf.ET.DYN, |
| 699 | | }, |
| 700 | | }; |
| 701 | | mem.writeInt(u16, hdr_buf[index..][0..2], @enumToInt(elf_type), endian); |
| 702 | | index += 2; |
| 892 | hdr_buf[index] = 1; // ELF version |
| 893 | index += 1; |
| 703 | 894 | |
| 704 | | const machine = self.options.target.cpu.arch.toElfMachine(); |
| 705 | | mem.writeInt(u16, hdr_buf[index..][0..2], @enumToInt(machine), endian); |
| 706 | | index += 2; |
| 895 | // OS ABI, often set to 0 regardless of target platform |
| 896 | // ABI Version, possibly used by glibc but not by static executables |
| 897 | // padding |
| 898 | mem.set(u8, hdr_buf[index..][0..9], 0); |
| 899 | index += 9; |
| 707 | 900 | |
| 708 | | // ELF Version, again |
| 709 | | mem.writeInt(u32, hdr_buf[index..][0..4], 1, endian); |
| 710 | | index += 4; |
| 901 | assert(index == 16); |
| 711 | 902 | |
| 712 | | const e_entry = if (elf_type == .REL) 0 else self.entry_addr.?; |
| 903 | const elf_type = switch (self.options.output_mode) { |
| 904 | .Exe => elf.ET.EXEC, |
| 905 | .Obj => elf.ET.REL, |
| 906 | .Lib => switch (self.options.link_mode) { |
| 907 | .Static => elf.ET.REL, |
| 908 | .Dynamic => elf.ET.DYN, |
| 909 | }, |
| 910 | }; |
| 911 | mem.writeInt(u16, hdr_buf[index..][0..2], @enumToInt(elf_type), endian); |
| 912 | index += 2; |
| 713 | 913 | |
| 714 | | switch (self.ptr_width) { |
| 715 | | .p32 => { |
| 716 | | mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(u32, e_entry), endian); |
| 717 | | index += 4; |
| 914 | const machine = self.options.target.cpu.arch.toElfMachine(); |
| 915 | mem.writeInt(u16, hdr_buf[index..][0..2], @enumToInt(machine), endian); |
| 916 | index += 2; |
| 718 | 917 | |
| 719 | | // e_phoff |
| 720 | | mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(u32, self.phdr_table_offset.?), endian); |
| 721 | | index += 4; |
| 918 | // ELF Version, again |
| 919 | mem.writeInt(u32, hdr_buf[index..][0..4], 1, endian); |
| 920 | index += 4; |
| 722 | 921 | |
| 723 | | // e_shoff |
| 724 | | mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(u32, self.shdr_table_offset.?), endian); |
| 725 | | index += 4; |
| 726 | | }, |
| 727 | | .p64 => { |
| 728 | | // e_entry |
| 729 | | mem.writeInt(u64, hdr_buf[index..][0..8], e_entry, endian); |
| 730 | | index += 8; |
| 731 | | |
| 732 | | // e_phoff |
| 733 | | mem.writeInt(u64, hdr_buf[index..][0..8], self.phdr_table_offset.?, endian); |
| 734 | | index += 8; |
| 735 | | |
| 736 | | // e_shoff |
| 737 | | mem.writeInt(u64, hdr_buf[index..][0..8], self.shdr_table_offset.?, endian); |
| 738 | | index += 8; |
| 739 | | }, |
| 740 | | } |
| 922 | const e_entry = if (elf_type == .REL) 0 else self.entry_addr.?; |
| 741 | 923 | |
| 742 | | const e_flags = 0; |
| 743 | | mem.writeInt(u32, hdr_buf[index..][0..4], e_flags, endian); |
| 744 | | index += 4; |
| 924 | switch (self.ptr_width) { |
| 925 | .p32 => { |
| 926 | mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(u32, e_entry), endian); |
| 927 | index += 4; |
| 745 | 928 | |
| 746 | | const e_ehsize: u16 = switch (self.ptr_width) { |
| 747 | | .p32 => @sizeOf(elf.Elf32_Ehdr), |
| 748 | | .p64 => @sizeOf(elf.Elf64_Ehdr), |
| 749 | | }; |
| 750 | | mem.writeInt(u16, hdr_buf[index..][0..2], e_ehsize, endian); |
| 751 | | index += 2; |
| 929 | // e_phoff |
| 930 | mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(u32, self.phdr_table_offset.?), endian); |
| 931 | index += 4; |
| 752 | 932 | |
| 753 | | const e_phentsize: u16 = switch (self.ptr_width) { |
| 754 | | .p32 => @sizeOf(elf.Elf32_Phdr), |
| 755 | | .p64 => @sizeOf(elf.Elf64_Phdr), |
| 756 | | }; |
| 757 | | mem.writeInt(u16, hdr_buf[index..][0..2], e_phentsize, endian); |
| 758 | | index += 2; |
| 933 | // e_shoff |
| 934 | mem.writeInt(u32, hdr_buf[index..][0..4], @intCast(u32, self.shdr_table_offset.?), endian); |
| 935 | index += 4; |
| 936 | }, |
| 937 | .p64 => { |
| 938 | // e_entry |
| 939 | mem.writeInt(u64, hdr_buf[index..][0..8], e_entry, endian); |
| 940 | index += 8; |
| 759 | 941 | |
| 760 | | const e_phnum = @intCast(u16, self.program_headers.items.len); |
| 761 | | mem.writeInt(u16, hdr_buf[index..][0..2], e_phnum, endian); |
| 762 | | index += 2; |
| 942 | // e_phoff |
| 943 | mem.writeInt(u64, hdr_buf[index..][0..8], self.phdr_table_offset.?, endian); |
| 944 | index += 8; |
| 763 | 945 | |
| 764 | | const e_shentsize: u16 = switch (self.ptr_width) { |
| 765 | | .p32 => @sizeOf(elf.Elf32_Shdr), |
| 766 | | .p64 => @sizeOf(elf.Elf64_Shdr), |
| 767 | | }; |
| 768 | | mem.writeInt(u16, hdr_buf[index..][0..2], e_shentsize, endian); |
| 769 | | index += 2; |
| 946 | // e_shoff |
| 947 | mem.writeInt(u64, hdr_buf[index..][0..8], self.shdr_table_offset.?, endian); |
| 948 | index += 8; |
| 949 | }, |
| 950 | } |
| 770 | 951 | |
| 771 | | const e_shnum = @intCast(u16, self.sections.items.len); |
| 772 | | mem.writeInt(u16, hdr_buf[index..][0..2], e_shnum, endian); |
| 773 | | index += 2; |
| 952 | const e_flags = 0; |
| 953 | mem.writeInt(u32, hdr_buf[index..][0..4], e_flags, endian); |
| 954 | index += 4; |
| 774 | 955 | |
| 775 | | mem.writeInt(u16, hdr_buf[index..][0..2], self.shstrtab_index.?, endian); |
| 776 | | index += 2; |
| 956 | const e_ehsize: u16 = switch (self.ptr_width) { |
| 957 | .p32 => @sizeOf(elf.Elf32_Ehdr), |
| 958 | .p64 => @sizeOf(elf.Elf64_Ehdr), |
| 959 | }; |
| 960 | mem.writeInt(u16, hdr_buf[index..][0..2], e_ehsize, endian); |
| 961 | index += 2; |
| 777 | 962 | |
| 778 | | assert(index == e_ehsize); |
| 963 | const e_phentsize: u16 = switch (self.ptr_width) { |
| 964 | .p32 => @sizeOf(elf.Elf32_Phdr), |
| 965 | .p64 => @sizeOf(elf.Elf64_Phdr), |
| 966 | }; |
| 967 | mem.writeInt(u16, hdr_buf[index..][0..2], e_phentsize, endian); |
| 968 | index += 2; |
| 779 | 969 | |
| 780 | | try self.file.?.pwriteAll(hdr_buf[0..index], 0); |
| 781 | | } |
| 970 | const e_phnum = @intCast(u16, self.program_headers.items.len); |
| 971 | mem.writeInt(u16, hdr_buf[index..][0..2], e_phnum, endian); |
| 972 | index += 2; |
| 782 | 973 | |
| 783 | | fn freeTextBlock(self: *ElfFile, text_block: *TextBlock) void { |
| 784 | | var already_have_free_list_node = false; |
| 785 | | { |
| 786 | | var i: usize = 0; |
| 787 | | while (i < self.text_block_free_list.items.len) { |
| 788 | | if (self.text_block_free_list.items[i] == text_block) { |
| 789 | | _ = self.text_block_free_list.swapRemove(i); |
| 790 | | continue; |
| 791 | | } |
| 792 | | if (self.text_block_free_list.items[i] == text_block.prev) { |
| 793 | | already_have_free_list_node = true; |
| 794 | | } |
| 795 | | i += 1; |
| 796 | | } |
| 797 | | } |
| 974 | const e_shentsize: u16 = switch (self.ptr_width) { |
| 975 | .p32 => @sizeOf(elf.Elf32_Shdr), |
| 976 | .p64 => @sizeOf(elf.Elf64_Shdr), |
| 977 | }; |
| 978 | mem.writeInt(u16, hdr_buf[index..][0..2], e_shentsize, endian); |
| 979 | index += 2; |
| 798 | 980 | |
| 799 | | if (self.last_text_block == text_block) { |
| 800 | | // TODO shrink the .text section size here |
| 801 | | self.last_text_block = text_block.prev; |
| 802 | | } |
| 981 | const e_shnum = @intCast(u16, self.sections.items.len); |
| 982 | mem.writeInt(u16, hdr_buf[index..][0..2], e_shnum, endian); |
| 983 | index += 2; |
| 803 | 984 | |
| 804 | | if (text_block.prev) |prev| { |
| 805 | | prev.next = text_block.next; |
| 985 | mem.writeInt(u16, hdr_buf[index..][0..2], self.shstrtab_index.?, endian); |
| 986 | index += 2; |
| 806 | 987 | |
| 807 | | if (!already_have_free_list_node and prev.freeListEligible(self.*)) { |
| 808 | | // The free list is heuristics, it doesn't have to be perfect, so we can |
| 809 | | // ignore the OOM here. |
| 810 | | self.text_block_free_list.append(self.allocator, prev) catch {}; |
| 811 | | } |
| 812 | | } else { |
| 813 | | text_block.prev = null; |
| 814 | | } |
| 988 | assert(index == e_ehsize); |
| 815 | 989 | |
| 816 | | if (text_block.next) |next| { |
| 817 | | next.prev = text_block.prev; |
| 818 | | } else { |
| 819 | | text_block.next = null; |
| 990 | try self.file.?.pwriteAll(hdr_buf[0..index], 0); |
| 820 | 991 | } |
| 821 | | } |
| 822 | 992 | |
| 823 | | fn shrinkTextBlock(self: *ElfFile, text_block: *TextBlock, new_block_size: u64) void { |
| 824 | | // TODO check the new capacity, and if it crosses the size threshold into a big enough |
| 825 | | // capacity, insert a free list node for it. |
| 826 | | } |
| 827 | | |
| 828 | | fn growTextBlock(self: *ElfFile, text_block: *TextBlock, new_block_size: u64, alignment: u64) !u64 { |
| 829 | | const sym = self.local_symbols.items[text_block.local_sym_index]; |
| 830 | | const align_ok = mem.alignBackwardGeneric(u64, sym.st_value, alignment) == sym.st_value; |
| 831 | | const need_realloc = !align_ok or new_block_size > text_block.capacity(self.*); |
| 832 | | if (!need_realloc) return sym.st_value; |
| 833 | | return self.allocateTextBlock(text_block, new_block_size, alignment); |
| 834 | | } |
| 835 | | |
| 836 | | fn allocateTextBlock(self: *ElfFile, text_block: *TextBlock, new_block_size: u64, alignment: u64) !u64 { |
| 837 | | const phdr = &self.program_headers.items[self.phdr_load_re_index.?]; |
| 838 | | const shdr = &self.sections.items[self.text_section_index.?]; |
| 839 | | const new_block_ideal_capacity = new_block_size * alloc_num / alloc_den; |
| 840 | | |
| 841 | | // We use these to indicate our intention to update metadata, placing the new block, |
| 842 | | // and possibly removing a free list node. |
| 843 | | // It would be simpler to do it inside the for loop below, but that would cause a |
| 844 | | // problem if an error was returned later in the function. So this action |
| 845 | | // is actually carried out at the end of the function, when errors are no longer possible. |
| 846 | | var block_placement: ?*TextBlock = null; |
| 847 | | var free_list_removal: ?usize = null; |
| 848 | | |
| 849 | | // First we look for an appropriately sized free list node. |
| 850 | | // The list is unordered. We'll just take the first thing that works. |
| 851 | | const vaddr = blk: { |
| 852 | | var i: usize = 0; |
| 853 | | while (i < self.text_block_free_list.items.len) { |
| 854 | | const big_block = self.text_block_free_list.items[i]; |
| 855 | | // We now have a pointer to a live text block that has too much capacity. |
| 856 | | // Is it enough that we could fit this new text block? |
| 857 | | const sym = self.local_symbols.items[big_block.local_sym_index]; |
| 858 | | const capacity = big_block.capacity(self.*); |
| 859 | | const ideal_capacity = capacity * alloc_num / alloc_den; |
| 860 | | const ideal_capacity_end_vaddr = sym.st_value + ideal_capacity; |
| 861 | | const capacity_end_vaddr = sym.st_value + capacity; |
| 862 | | const new_start_vaddr_unaligned = capacity_end_vaddr - new_block_ideal_capacity; |
| 863 | | const new_start_vaddr = mem.alignBackwardGeneric(u64, new_start_vaddr_unaligned, alignment); |
| 864 | | if (new_start_vaddr < ideal_capacity_end_vaddr) { |
| 865 | | // Additional bookkeeping here to notice if this free list node |
| 866 | | // should be deleted because the block that it points to has grown to take up |
| 867 | | // more of the extra capacity. |
| 868 | | if (!big_block.freeListEligible(self.*)) { |
| 993 | fn freeTextBlock(self: *Elf, text_block: *TextBlock) void { |
| 994 | var already_have_free_list_node = false; |
| 995 | { |
| 996 | var i: usize = 0; |
| 997 | while (i < self.text_block_free_list.items.len) { |
| 998 | if (self.text_block_free_list.items[i] == text_block) { |
| 869 | 999 | _ = self.text_block_free_list.swapRemove(i); |
| 870 | | } else { |
| 871 | | i += 1; |
| 1000 | continue; |
| 872 | 1001 | } |
| 873 | | continue; |
| 874 | | } |
| 875 | | // At this point we know that we will place the new block here. But the |
| 876 | | // remaining question is whether there is still yet enough capacity left |
| 877 | | // over for there to still be a free list node. |
| 878 | | const remaining_capacity = new_start_vaddr - ideal_capacity_end_vaddr; |
| 879 | | const keep_free_list_node = remaining_capacity >= min_text_capacity; |
| 880 | | |
| 881 | | // Set up the metadata to be updated, after errors are no longer possible. |
| 882 | | block_placement = big_block; |
| 883 | | if (!keep_free_list_node) { |
| 884 | | free_list_removal = i; |
| 1002 | if (self.text_block_free_list.items[i] == text_block.prev) { |
| 1003 | already_have_free_list_node = true; |
| 1004 | } |
| 1005 | i += 1; |
| 885 | 1006 | } |
| 886 | | break :blk new_start_vaddr; |
| 887 | | } else if (self.last_text_block) |last| { |
| 888 | | const sym = self.local_symbols.items[last.local_sym_index]; |
| 889 | | const ideal_capacity = sym.st_size * alloc_num / alloc_den; |
| 890 | | const ideal_capacity_end_vaddr = sym.st_value + ideal_capacity; |
| 891 | | const new_start_vaddr = mem.alignForwardGeneric(u64, ideal_capacity_end_vaddr, alignment); |
| 892 | | // Set up the metadata to be updated, after errors are no longer possible. |
| 893 | | block_placement = last; |
| 894 | | break :blk new_start_vaddr; |
| 895 | | } else { |
| 896 | | break :blk phdr.p_vaddr; |
| 897 | 1007 | } |
| 898 | | }; |
| 899 | 1008 | |
| 900 | | const expand_text_section = block_placement == null or block_placement.?.next == null; |
| 901 | | if (expand_text_section) { |
| 902 | | const text_capacity = self.allocatedSize(shdr.sh_offset); |
| 903 | | const needed_size = (vaddr + new_block_size) - phdr.p_vaddr; |
| 904 | | if (needed_size > text_capacity) { |
| 905 | | // Must move the entire text section. |
| 906 | | const new_offset = self.findFreeSpace(needed_size, 0x1000); |
| 907 | | const text_size = if (self.last_text_block) |last| blk: { |
| 908 | | const sym = self.local_symbols.items[last.local_sym_index]; |
| 909 | | break :blk (sym.st_value + sym.st_size) - phdr.p_vaddr; |
| 910 | | } else 0; |
| 911 | | const amt = try self.file.?.copyRangeAll(shdr.sh_offset, self.file.?, new_offset, text_size); |
| 912 | | if (amt != text_size) return error.InputOutput; |
| 913 | | shdr.sh_offset = new_offset; |
| 914 | | phdr.p_offset = new_offset; |
| 1009 | if (self.last_text_block == text_block) { |
| 1010 | // TODO shrink the .text section size here |
| 1011 | self.last_text_block = text_block.prev; |
| 915 | 1012 | } |
| 916 | | self.last_text_block = text_block; |
| 917 | 1013 | |
| 918 | | shdr.sh_size = needed_size; |
| 919 | | phdr.p_memsz = needed_size; |
| 920 | | phdr.p_filesz = needed_size; |
| 1014 | if (text_block.prev) |prev| { |
| 1015 | prev.next = text_block.next; |
| 921 | 1016 | |
| 922 | | self.phdr_table_dirty = true; // TODO look into making only the one program header dirty |
| 923 | | self.shdr_table_dirty = true; // TODO look into making only the one section dirty |
| 924 | | } |
| 1017 | if (!already_have_free_list_node and prev.freeListEligible(self.*)) { |
| 1018 | // The free list is heuristics, it doesn't have to be perfect, so we can |
| 1019 | // ignore the OOM here. |
| 1020 | self.text_block_free_list.append(self.allocator, prev) catch {}; |
| 1021 | } |
| 1022 | } else { |
| 1023 | text_block.prev = null; |
| 1024 | } |
| 925 | 1025 | |
| 926 | | // This function can also reallocate a text block. |
| 927 | | // In this case we need to "unplug" it from its previous location before |
| 928 | | // plugging it in to its new location. |
| 929 | | if (text_block.prev) |prev| { |
| 930 | | prev.next = text_block.next; |
| 931 | | } |
| 932 | | if (text_block.next) |next| { |
| 933 | | next.prev = text_block.prev; |
| 1026 | if (text_block.next) |next| { |
| 1027 | next.prev = text_block.prev; |
| 1028 | } else { |
| 1029 | text_block.next = null; |
| 1030 | } |
| 934 | 1031 | } |
| 935 | 1032 | |
| 936 | | if (block_placement) |big_block| { |
| 937 | | text_block.prev = big_block; |
| 938 | | text_block.next = big_block.next; |
| 939 | | big_block.next = text_block; |
| 940 | | } else { |
| 941 | | text_block.prev = null; |
| 942 | | text_block.next = null; |
| 1033 | fn shrinkTextBlock(self: *Elf, text_block: *TextBlock, new_block_size: u64) void { |
| 1034 | // TODO check the new capacity, and if it crosses the size threshold into a big enough |
| 1035 | // capacity, insert a free list node for it. |
| 943 | 1036 | } |
| 944 | | if (free_list_removal) |i| { |
| 945 | | _ = self.text_block_free_list.swapRemove(i); |
| 946 | | } |
| 947 | | return vaddr; |
| 948 | | } |
| 949 | 1037 | |
| 950 | | pub fn allocateDeclIndexes(self: *ElfFile, decl: *Module.Decl) !void { |
| 951 | | if (decl.link.local_sym_index != 0) return; |
| 952 | | |
| 953 | | // Here we also ensure capacity for the free lists so that they can be appended to without fail. |
| 954 | | try self.local_symbols.ensureCapacity(self.allocator, self.local_symbols.items.len + 1); |
| 955 | | try self.local_symbol_free_list.ensureCapacity(self.allocator, self.local_symbols.items.len); |
| 956 | | try self.offset_table.ensureCapacity(self.allocator, self.offset_table.items.len + 1); |
| 957 | | try self.offset_table_free_list.ensureCapacity(self.allocator, self.local_symbols.items.len); |
| 958 | | |
| 959 | | if (self.local_symbol_free_list.popOrNull()) |i| { |
| 960 | | std.log.debug(.link, "reusing symbol index {} for {}\n", .{i, decl.name}); |
| 961 | | decl.link.local_sym_index = i; |
| 962 | | } else { |
| 963 | | std.log.debug(.link, "allocating symbol index {} for {}\n", .{self.local_symbols.items.len, decl.name}); |
| 964 | | decl.link.local_sym_index = @intCast(u32, self.local_symbols.items.len); |
| 965 | | _ = self.local_symbols.addOneAssumeCapacity(); |
| 1038 | fn growTextBlock(self: *Elf, text_block: *TextBlock, new_block_size: u64, alignment: u64) !u64 { |
| 1039 | const sym = self.local_symbols.items[text_block.local_sym_index]; |
| 1040 | const align_ok = mem.alignBackwardGeneric(u64, sym.st_value, alignment) == sym.st_value; |
| 1041 | const need_realloc = !align_ok or new_block_size > text_block.capacity(self.*); |
| 1042 | if (!need_realloc) return sym.st_value; |
| 1043 | return self.allocateTextBlock(text_block, new_block_size, alignment); |
| 966 | 1044 | } |
| 967 | 1045 | |
| 968 | | if (self.offset_table_free_list.popOrNull()) |i| { |
| 969 | | decl.link.offset_table_index = i; |
| 970 | | } else { |
| 971 | | decl.link.offset_table_index = @intCast(u32, self.offset_table.items.len); |
| 972 | | _ = self.offset_table.addOneAssumeCapacity(); |
| 973 | | self.offset_table_count_dirty = true; |
| 974 | | } |
| 1046 | fn allocateTextBlock(self: *Elf, text_block: *TextBlock, new_block_size: u64, alignment: u64) !u64 { |
| 1047 | const phdr = &self.program_headers.items[self.phdr_load_re_index.?]; |
| 1048 | const shdr = &self.sections.items[self.text_section_index.?]; |
| 1049 | const new_block_ideal_capacity = new_block_size * alloc_num / alloc_den; |
| 1050 | |
| 1051 | // We use these to indicate our intention to update metadata, placing the new block, |
| 1052 | // and possibly removing a free list node. |
| 1053 | // It would be simpler to do it inside the for loop below, but that would cause a |
| 1054 | // problem if an error was returned later in the function. So this action |
| 1055 | // is actually carried out at the end of the function, when errors are no longer possible. |
| 1056 | var block_placement: ?*TextBlock = null; |
| 1057 | var free_list_removal: ?usize = null; |
| 1058 | |
| 1059 | // First we look for an appropriately sized free list node. |
| 1060 | // The list is unordered. We'll just take the first thing that works. |
| 1061 | const vaddr = blk: { |
| 1062 | var i: usize = 0; |
| 1063 | while (i < self.text_block_free_list.items.len) { |
| 1064 | const big_block = self.text_block_free_list.items[i]; |
| 1065 | // We now have a pointer to a live text block that has too much capacity. |
| 1066 | // Is it enough that we could fit this new text block? |
| 1067 | const sym = self.local_symbols.items[big_block.local_sym_index]; |
| 1068 | const capacity = big_block.capacity(self.*); |
| 1069 | const ideal_capacity = capacity * alloc_num / alloc_den; |
| 1070 | const ideal_capacity_end_vaddr = sym.st_value + ideal_capacity; |
| 1071 | const capacity_end_vaddr = sym.st_value + capacity; |
| 1072 | const new_start_vaddr_unaligned = capacity_end_vaddr - new_block_ideal_capacity; |
| 1073 | const new_start_vaddr = mem.alignBackwardGeneric(u64, new_start_vaddr_unaligned, alignment); |
| 1074 | if (new_start_vaddr < ideal_capacity_end_vaddr) { |
| 1075 | // Additional bookkeeping here to notice if this free list node |
| 1076 | // should be deleted because the block that it points to has grown to take up |
| 1077 | // more of the extra capacity. |
| 1078 | if (!big_block.freeListEligible(self.*)) { |
| 1079 | _ = self.text_block_free_list.swapRemove(i); |
| 1080 | } else { |
| 1081 | i += 1; |
| 1082 | } |
| 1083 | continue; |
| 1084 | } |
| 1085 | // At this point we know that we will place the new block here. But the |
| 1086 | // remaining question is whether there is still yet enough capacity left |
| 1087 | // over for there to still be a free list node. |
| 1088 | const remaining_capacity = new_start_vaddr - ideal_capacity_end_vaddr; |
| 1089 | const keep_free_list_node = remaining_capacity >= min_text_capacity; |
| 1090 | |
| 1091 | // Set up the metadata to be updated, after errors are no longer possible. |
| 1092 | block_placement = big_block; |
| 1093 | if (!keep_free_list_node) { |
| 1094 | free_list_removal = i; |
| 1095 | } |
| 1096 | break :blk new_start_vaddr; |
| 1097 | } else if (self.last_text_block) |last| { |
| 1098 | const sym = self.local_symbols.items[last.local_sym_index]; |
| 1099 | const ideal_capacity = sym.st_size * alloc_num / alloc_den; |
| 1100 | const ideal_capacity_end_vaddr = sym.st_value + ideal_capacity; |
| 1101 | const new_start_vaddr = mem.alignForwardGeneric(u64, ideal_capacity_end_vaddr, alignment); |
| 1102 | // Set up the metadata to be updated, after errors are no longer possible. |
| 1103 | block_placement = last; |
| 1104 | break :blk new_start_vaddr; |
| 1105 | } else { |
| 1106 | break :blk phdr.p_vaddr; |
| 1107 | } |
| 1108 | }; |
| 975 | 1109 | |
| 976 | | const phdr = &self.program_headers.items[self.phdr_load_re_index.?]; |
| 1110 | const expand_text_section = block_placement == null or block_placement.?.next == null; |
| 1111 | if (expand_text_section) { |
| 1112 | const text_capacity = self.allocatedSize(shdr.sh_offset); |
| 1113 | const needed_size = (vaddr + new_block_size) - phdr.p_vaddr; |
| 1114 | if (needed_size > text_capacity) { |
| 1115 | // Must move the entire text section. |
| 1116 | const new_offset = self.findFreeSpace(needed_size, 0x1000); |
| 1117 | const text_size = if (self.last_text_block) |last| blk: { |
| 1118 | const sym = self.local_symbols.items[last.local_sym_index]; |
| 1119 | break :blk (sym.st_value + sym.st_size) - phdr.p_vaddr; |
| 1120 | } else 0; |
| 1121 | const amt = try self.file.?.copyRangeAll(shdr.sh_offset, self.file.?, new_offset, text_size); |
| 1122 | if (amt != text_size) return error.InputOutput; |
| 1123 | shdr.sh_offset = new_offset; |
| 1124 | phdr.p_offset = new_offset; |
| 1125 | } |
| 1126 | self.last_text_block = text_block; |
| 977 | 1127 | |
| 978 | | self.local_symbols.items[decl.link.local_sym_index] = .{ |
| 979 | | .st_name = 0, |
| 980 | | .st_info = 0, |
| 981 | | .st_other = 0, |
| 982 | | .st_shndx = 0, |
| 983 | | .st_value = phdr.p_vaddr, |
| 984 | | .st_size = 0, |
| 985 | | }; |
| 986 | | self.offset_table.items[decl.link.offset_table_index] = 0; |
| 987 | | } |
| 1128 | shdr.sh_size = needed_size; |
| 1129 | phdr.p_memsz = needed_size; |
| 1130 | phdr.p_filesz = needed_size; |
| 988 | 1131 | |
| 989 | | pub fn freeDecl(self: *ElfFile, decl: *Module.Decl) void { |
| 990 | | self.freeTextBlock(&decl.link); |
| 991 | | if (decl.link.local_sym_index != 0) { |
| 992 | | self.local_symbol_free_list.appendAssumeCapacity(decl.link.local_sym_index); |
| 993 | | self.offset_table_free_list.appendAssumeCapacity(decl.link.offset_table_index); |
| 1132 | self.phdr_table_dirty = true; // TODO look into making only the one program header dirty |
| 1133 | self.shdr_table_dirty = true; // TODO look into making only the one section dirty |
| 1134 | } |
| 994 | 1135 | |
| 995 | | self.local_symbols.items[decl.link.local_sym_index].st_info = 0; |
| 1136 | // This function can also reallocate a text block. |
| 1137 | // In this case we need to "unplug" it from its previous location before |
| 1138 | // plugging it in to its new location. |
| 1139 | if (text_block.prev) |prev| { |
| 1140 | prev.next = text_block.next; |
| 1141 | } |
| 1142 | if (text_block.next) |next| { |
| 1143 | next.prev = text_block.prev; |
| 1144 | } |
| 996 | 1145 | |
| 997 | | decl.link.local_sym_index = 0; |
| 1146 | if (block_placement) |big_block| { |
| 1147 | text_block.prev = big_block; |
| 1148 | text_block.next = big_block.next; |
| 1149 | big_block.next = text_block; |
| 1150 | } else { |
| 1151 | text_block.prev = null; |
| 1152 | text_block.next = null; |
| 1153 | } |
| 1154 | if (free_list_removal) |i| { |
| 1155 | _ = self.text_block_free_list.swapRemove(i); |
| 1156 | } |
| 1157 | return vaddr; |
| 998 | 1158 | } |
| 999 | | } |
| 1000 | 1159 | |
| 1001 | | pub fn updateDecl(self: *ElfFile, module: *Module, decl: *Module.Decl) !void { |
| 1002 | | var code_buffer = std.ArrayList(u8).init(self.allocator); |
| 1003 | | defer code_buffer.deinit(); |
| 1004 | | |
| 1005 | | const typed_value = decl.typed_value.most_recent.typed_value; |
| 1006 | | const code = switch (try codegen.generateSymbol(self, decl.src(), typed_value, &code_buffer)) { |
| 1007 | | .externally_managed => |x| x, |
| 1008 | | .appended => code_buffer.items, |
| 1009 | | .fail => |em| { |
| 1010 | | decl.analysis = .codegen_failure; |
| 1011 | | _ = try module.failed_decls.put(module.gpa, decl, em); |
| 1012 | | return; |
| 1013 | | }, |
| 1014 | | }; |
| 1160 | pub fn allocateDeclIndexes(self: *Elf, decl: *Module.Decl) !void { |
| 1161 | if (decl.link.local_sym_index != 0) return; |
| 1015 | 1162 | |
| 1016 | | const required_alignment = typed_value.ty.abiAlignment(self.options.target); |
| 1163 | // Here we also ensure capacity for the free lists so that they can be appended to without fail. |
| 1164 | try self.local_symbols.ensureCapacity(self.allocator, self.local_symbols.items.len + 1); |
| 1165 | try self.local_symbol_free_list.ensureCapacity(self.allocator, self.local_symbols.items.len); |
| 1166 | try self.offset_table.ensureCapacity(self.allocator, self.offset_table.items.len + 1); |
| 1167 | try self.offset_table_free_list.ensureCapacity(self.allocator, self.local_symbols.items.len); |
| 1017 | 1168 | |
| 1018 | | const stt_bits: u8 = switch (typed_value.ty.zigTypeTag()) { |
| 1019 | | .Fn => elf.STT_FUNC, |
| 1020 | | else => elf.STT_OBJECT, |
| 1021 | | }; |
| 1169 | if (self.local_symbol_free_list.popOrNull()) |i| { |
| 1170 | std.log.debug(.link, "reusing symbol index {} for {}\n", .{i, decl.name}); |
| 1171 | decl.link.local_sym_index = i; |
| 1172 | } else { |
| 1173 | std.log.debug(.link, "allocating symbol index {} for {}\n", .{self.local_symbols.items.len, decl.name}); |
| 1174 | decl.link.local_sym_index = @intCast(u32, self.local_symbols.items.len); |
| 1175 | _ = self.local_symbols.addOneAssumeCapacity(); |
| 1176 | } |
| 1022 | 1177 | |
| 1023 | | assert(decl.link.local_sym_index != 0); // Caller forgot to allocateDeclIndexes() |
| 1024 | | const local_sym = &self.local_symbols.items[decl.link.local_sym_index]; |
| 1025 | | if (local_sym.st_size != 0) { |
| 1026 | | const capacity = decl.link.capacity(self.*); |
| 1027 | | const need_realloc = code.len > capacity or |
| 1028 | | !mem.isAlignedGeneric(u64, local_sym.st_value, required_alignment); |
| 1029 | | if (need_realloc) { |
| 1030 | | const vaddr = try self.growTextBlock(&decl.link, code.len, required_alignment); |
| 1031 | | std.log.debug(.link, "growing {} from 0x{x} to 0x{x}\n", .{ decl.name, local_sym.st_value, vaddr }); |
| 1032 | | if (vaddr != local_sym.st_value) { |
| 1033 | | local_sym.st_value = vaddr; |
| 1034 | | |
| 1035 | | std.log.debug(.link, " (writing new offset table entry)\n", .{}); |
| 1036 | | self.offset_table.items[decl.link.offset_table_index] = vaddr; |
| 1037 | | try self.writeOffsetTableEntry(decl.link.offset_table_index); |
| 1038 | | } |
| 1039 | | } else if (code.len < local_sym.st_size) { |
| 1040 | | self.shrinkTextBlock(&decl.link, code.len); |
| 1178 | if (self.offset_table_free_list.popOrNull()) |i| { |
| 1179 | decl.link.offset_table_index = i; |
| 1180 | } else { |
| 1181 | decl.link.offset_table_index = @intCast(u32, self.offset_table.items.len); |
| 1182 | _ = self.offset_table.addOneAssumeCapacity(); |
| 1183 | self.offset_table_count_dirty = true; |
| 1041 | 1184 | } |
| 1042 | | local_sym.st_size = code.len; |
| 1043 | | local_sym.st_name = try self.updateString(local_sym.st_name, mem.spanZ(decl.name)); |
| 1044 | | local_sym.st_info = (elf.STB_LOCAL << 4) | stt_bits; |
| 1045 | | local_sym.st_other = 0; |
| 1046 | | local_sym.st_shndx = self.text_section_index.?; |
| 1047 | | // TODO this write could be avoided if no fields of the symbol were changed. |
| 1048 | | try self.writeSymbol(decl.link.local_sym_index); |
| 1049 | | } else { |
| 1050 | | const decl_name = mem.spanZ(decl.name); |
| 1051 | | const name_str_index = try self.makeString(decl_name); |
| 1052 | | const vaddr = try self.allocateTextBlock(&decl.link, code.len, required_alignment); |
| 1053 | | std.log.debug(.link, "allocated text block for {} at 0x{x}\n", .{ decl_name, vaddr }); |
| 1054 | | errdefer self.freeTextBlock(&decl.link); |
| 1055 | | |
| 1056 | | local_sym.* = .{ |
| 1057 | | .st_name = name_str_index, |
| 1058 | | .st_info = (elf.STB_LOCAL << 4) | stt_bits, |
| 1185 | |
| 1186 | const phdr = &self.program_headers.items[self.phdr_load_re_index.?]; |
| 1187 | |
| 1188 | self.local_symbols.items[decl.link.local_sym_index] = .{ |
| 1189 | .st_name = 0, |
| 1190 | .st_info = 0, |
| 1059 | 1191 | .st_other = 0, |
| 1060 | | .st_shndx = self.text_section_index.?, |
| 1061 | | .st_value = vaddr, |
| 1062 | | .st_size = code.len, |
| 1192 | .st_shndx = 0, |
| 1193 | .st_value = phdr.p_vaddr, |
| 1194 | .st_size = 0, |
| 1063 | 1195 | }; |
| 1064 | | self.offset_table.items[decl.link.offset_table_index] = vaddr; |
| 1065 | | |
| 1066 | | try self.writeSymbol(decl.link.local_sym_index); |
| 1067 | | try self.writeOffsetTableEntry(decl.link.offset_table_index); |
| 1196 | self.offset_table.items[decl.link.offset_table_index] = 0; |
| 1068 | 1197 | } |
| 1069 | 1198 | |
| 1070 | | const section_offset = local_sym.st_value - self.program_headers.items[self.phdr_load_re_index.?].p_vaddr; |
| 1071 | | const file_offset = self.sections.items[self.text_section_index.?].sh_offset + section_offset; |
| 1072 | | try self.file.?.pwriteAll(code, file_offset); |
| 1199 | pub fn freeDecl(self: *Elf, decl: *Module.Decl) void { |
| 1200 | self.freeTextBlock(&decl.link); |
| 1201 | if (decl.link.local_sym_index != 0) { |
| 1202 | self.local_symbol_free_list.appendAssumeCapacity(decl.link.local_sym_index); |
| 1203 | self.offset_table_free_list.appendAssumeCapacity(decl.link.offset_table_index); |
| 1073 | 1204 | |
| 1074 | | // Since we updated the vaddr and the size, each corresponding export symbol also needs to be updated. |
| 1075 | | const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{}; |
| 1076 | | return self.updateDeclExports(module, decl, decl_exports); |
| 1077 | | } |
| 1205 | self.local_symbols.items[decl.link.local_sym_index].st_info = 0; |
| 1078 | 1206 | |
| 1079 | | /// Must be called only after a successful call to `updateDecl`. |
| 1080 | | pub fn updateDeclExports( |
| 1081 | | self: *ElfFile, |
| 1082 | | module: *Module, |
| 1083 | | decl: *const Module.Decl, |
| 1084 | | exports: []const *Module.Export, |
| 1085 | | ) !void { |
| 1086 | | // In addition to ensuring capacity for global_symbols, we also ensure capacity for freeing all of |
| 1087 | | // them, so that deleting exports is guaranteed to succeed. |
| 1088 | | try self.global_symbols.ensureCapacity(self.allocator, self.global_symbols.items.len + exports.len); |
| 1089 | | try self.global_symbol_free_list.ensureCapacity(self.allocator, self.global_symbols.items.len); |
| 1090 | | const typed_value = decl.typed_value.most_recent.typed_value; |
| 1091 | | if (decl.link.local_sym_index == 0) return; |
| 1092 | | const decl_sym = self.local_symbols.items[decl.link.local_sym_index]; |
| 1093 | | |
| 1094 | | for (exports) |exp| { |
| 1095 | | if (exp.options.section) |section_name| { |
| 1096 | | if (!mem.eql(u8, section_name, ".text")) { |
| 1097 | | try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1); |
| 1098 | | module.failed_exports.putAssumeCapacityNoClobber( |
| 1099 | | exp, |
| 1100 | | try Module.ErrorMsg.create(self.allocator, 0, "Unimplemented: ExportOptions.section", .{}), |
| 1101 | | ); |
| 1102 | | continue; |
| 1103 | | } |
| 1207 | decl.link.local_sym_index = 0; |
| 1104 | 1208 | } |
| 1105 | | const stb_bits: u8 = switch (exp.options.linkage) { |
| 1106 | | .Internal => elf.STB_LOCAL, |
| 1107 | | .Strong => blk: { |
| 1108 | | if (mem.eql(u8, exp.options.name, "_start")) { |
| 1109 | | self.entry_addr = decl_sym.st_value; |
| 1110 | | } |
| 1111 | | break :blk elf.STB_GLOBAL; |
| 1112 | | }, |
| 1113 | | .Weak => elf.STB_WEAK, |
| 1114 | | .LinkOnce => { |
| 1115 | | try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1); |
| 1116 | | module.failed_exports.putAssumeCapacityNoClobber( |
| 1117 | | exp, |
| 1118 | | try Module.ErrorMsg.create(self.allocator, 0, "Unimplemented: GlobalLinkage.LinkOnce", .{}), |
| 1119 | | ); |
| 1120 | | continue; |
| 1209 | } |
| 1210 | |
| 1211 | pub fn updateDecl(self: *Elf, module: *Module, decl: *Module.Decl) !void { |
| 1212 | var code_buffer = std.ArrayList(u8).init(self.allocator); |
| 1213 | defer code_buffer.deinit(); |
| 1214 | |
| 1215 | const typed_value = decl.typed_value.most_recent.typed_value; |
| 1216 | const code = switch (try codegen.generateSymbol(self, decl.src(), typed_value, &code_buffer)) { |
| 1217 | .externally_managed => |x| x, |
| 1218 | .appended => code_buffer.items, |
| 1219 | .fail => |em| { |
| 1220 | decl.analysis = .codegen_failure; |
| 1221 | try module.failed_decls.put(module.gpa, decl, em); |
| 1222 | return; |
| 1121 | 1223 | }, |
| 1122 | 1224 | }; |
| 1123 | | const stt_bits: u8 = @truncate(u4, decl_sym.st_info); |
| 1124 | | if (exp.link.sym_index) |i| { |
| 1125 | | const sym = &self.global_symbols.items[i]; |
| 1126 | | sym.* = .{ |
| 1127 | | .st_name = try self.updateString(sym.st_name, exp.options.name), |
| 1128 | | .st_info = (stb_bits << 4) | stt_bits, |
| 1129 | | .st_other = 0, |
| 1130 | | .st_shndx = self.text_section_index.?, |
| 1131 | | .st_value = decl_sym.st_value, |
| 1132 | | .st_size = decl_sym.st_size, |
| 1133 | | }; |
| 1225 | |
| 1226 | const required_alignment = typed_value.ty.abiAlignment(self.options.target); |
| 1227 | |
| 1228 | const stt_bits: u8 = switch (typed_value.ty.zigTypeTag()) { |
| 1229 | .Fn => elf.STT_FUNC, |
| 1230 | else => elf.STT_OBJECT, |
| 1231 | }; |
| 1232 | |
| 1233 | assert(decl.link.local_sym_index != 0); // Caller forgot to allocateDeclIndexes() |
| 1234 | const local_sym = &self.local_symbols.items[decl.link.local_sym_index]; |
| 1235 | if (local_sym.st_size != 0) { |
| 1236 | const capacity = decl.link.capacity(self.*); |
| 1237 | const need_realloc = code.len > capacity or |
| 1238 | !mem.isAlignedGeneric(u64, local_sym.st_value, required_alignment); |
| 1239 | if (need_realloc) { |
| 1240 | const vaddr = try self.growTextBlock(&decl.link, code.len, required_alignment); |
| 1241 | std.log.debug(.link, "growing {} from 0x{x} to 0x{x}\n", .{ decl.name, local_sym.st_value, vaddr }); |
| 1242 | if (vaddr != local_sym.st_value) { |
| 1243 | local_sym.st_value = vaddr; |
| 1244 | |
| 1245 | std.log.debug(.link, " (writing new offset table entry)\n", .{}); |
| 1246 | self.offset_table.items[decl.link.offset_table_index] = vaddr; |
| 1247 | try self.writeOffsetTableEntry(decl.link.offset_table_index); |
| 1248 | } |
| 1249 | } else if (code.len < local_sym.st_size) { |
| 1250 | self.shrinkTextBlock(&decl.link, code.len); |
| 1251 | } |
| 1252 | local_sym.st_size = code.len; |
| 1253 | local_sym.st_name = try self.updateString(local_sym.st_name, mem.spanZ(decl.name)); |
| 1254 | local_sym.st_info = (elf.STB_LOCAL << 4) | stt_bits; |
| 1255 | local_sym.st_other = 0; |
| 1256 | local_sym.st_shndx = self.text_section_index.?; |
| 1257 | // TODO this write could be avoided if no fields of the symbol were changed. |
| 1258 | try self.writeSymbol(decl.link.local_sym_index); |
| 1134 | 1259 | } else { |
| 1135 | | const name = try self.makeString(exp.options.name); |
| 1136 | | const i = if (self.global_symbol_free_list.popOrNull()) |i| i else blk: { |
| 1137 | | _ = self.global_symbols.addOneAssumeCapacity(); |
| 1138 | | break :blk self.global_symbols.items.len - 1; |
| 1139 | | }; |
| 1140 | | self.global_symbols.items[i] = .{ |
| 1141 | | .st_name = name, |
| 1142 | | .st_info = (stb_bits << 4) | stt_bits, |
| 1260 | const decl_name = mem.spanZ(decl.name); |
| 1261 | const name_str_index = try self.makeString(decl_name); |
| 1262 | const vaddr = try self.allocateTextBlock(&decl.link, code.len, required_alignment); |
| 1263 | std.log.debug(.link, "allocated text block for {} at 0x{x}\n", .{ decl_name, vaddr }); |
| 1264 | errdefer self.freeTextBlock(&decl.link); |
| 1265 | |
| 1266 | local_sym.* = .{ |
| 1267 | .st_name = name_str_index, |
| 1268 | .st_info = (elf.STB_LOCAL << 4) | stt_bits, |
| 1143 | 1269 | .st_other = 0, |
| 1144 | 1270 | .st_shndx = self.text_section_index.?, |
| 1145 | | .st_value = decl_sym.st_value, |
| 1146 | | .st_size = decl_sym.st_size, |
| 1271 | .st_value = vaddr, |
| 1272 | .st_size = code.len, |
| 1147 | 1273 | }; |
| 1274 | self.offset_table.items[decl.link.offset_table_index] = vaddr; |
| 1148 | 1275 | |
| 1149 | | exp.link.sym_index = @intCast(u32, i); |
| 1276 | try self.writeSymbol(decl.link.local_sym_index); |
| 1277 | try self.writeOffsetTableEntry(decl.link.offset_table_index); |
| 1150 | 1278 | } |
| 1151 | | } |
| 1152 | | } |
| 1153 | 1279 | |
| 1154 | | pub fn deleteExport(self: *ElfFile, exp: Export) void { |
| 1155 | | const sym_index = exp.sym_index orelse return; |
| 1156 | | self.global_symbol_free_list.appendAssumeCapacity(sym_index); |
| 1157 | | self.global_symbols.items[sym_index].st_info = 0; |
| 1158 | | } |
| 1280 | const section_offset = local_sym.st_value - self.program_headers.items[self.phdr_load_re_index.?].p_vaddr; |
| 1281 | const file_offset = self.sections.items[self.text_section_index.?].sh_offset + section_offset; |
| 1282 | try self.file.?.pwriteAll(code, file_offset); |
| 1159 | 1283 | |
| 1160 | | fn writeProgHeader(self: *ElfFile, index: usize) !void { |
| 1161 | | const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian(); |
| 1162 | | const offset = self.program_headers.items[index].p_offset; |
| 1163 | | switch (self.options.target.cpu.arch.ptrBitWidth()) { |
| 1164 | | 32 => { |
| 1165 | | var phdr = [1]elf.Elf32_Phdr{progHeaderTo32(self.program_headers.items[index])}; |
| 1166 | | if (foreign_endian) { |
| 1167 | | bswapAllFields(elf.Elf32_Phdr, &phdr[0]); |
| 1168 | | } |
| 1169 | | return self.file.?.pwriteAll(mem.sliceAsBytes(&phdr), offset); |
| 1170 | | }, |
| 1171 | | 64 => { |
| 1172 | | var phdr = [1]elf.Elf64_Phdr{self.program_headers.items[index]}; |
| 1173 | | if (foreign_endian) { |
| 1174 | | bswapAllFields(elf.Elf64_Phdr, &phdr[0]); |
| 1175 | | } |
| 1176 | | return self.file.?.pwriteAll(mem.sliceAsBytes(&phdr), offset); |
| 1177 | | }, |
| 1178 | | else => return error.UnsupportedArchitecture, |
| 1284 | // Since we updated the vaddr and the size, each corresponding export symbol also needs to be updated. |
| 1285 | const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{}; |
| 1286 | return self.updateDeclExports(module, decl, decl_exports); |
| 1179 | 1287 | } |
| 1180 | | } |
| 1181 | 1288 | |
| 1182 | | fn writeSectHeader(self: *ElfFile, index: usize) !void { |
| 1183 | | const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian(); |
| 1184 | | const offset = self.sections.items[index].sh_offset; |
| 1185 | | switch (self.options.target.cpu.arch.ptrBitWidth()) { |
| 1186 | | 32 => { |
| 1187 | | var shdr: [1]elf.Elf32_Shdr = undefined; |
| 1188 | | shdr[0] = sectHeaderTo32(self.sections.items[index]); |
| 1189 | | if (foreign_endian) { |
| 1190 | | bswapAllFields(elf.Elf32_Shdr, &shdr[0]); |
| 1191 | | } |
| 1192 | | return self.file.?.pwriteAll(mem.sliceAsBytes(&shdr), offset); |
| 1193 | | }, |
| 1194 | | 64 => { |
| 1195 | | var shdr = [1]elf.Elf64_Shdr{self.sections.items[index]}; |
| 1196 | | if (foreign_endian) { |
| 1197 | | bswapAllFields(elf.Elf64_Shdr, &shdr[0]); |
| 1289 | /// Must be called only after a successful call to `updateDecl`. |
| 1290 | pub fn updateDeclExports( |
| 1291 | self: *Elf, |
| 1292 | module: *Module, |
| 1293 | decl: *const Module.Decl, |
| 1294 | exports: []const *Module.Export, |
| 1295 | ) !void { |
| 1296 | // In addition to ensuring capacity for global_symbols, we also ensure capacity for freeing all of |
| 1297 | // them, so that deleting exports is guaranteed to succeed. |
| 1298 | try self.global_symbols.ensureCapacity(self.allocator, self.global_symbols.items.len + exports.len); |
| 1299 | try self.global_symbol_free_list.ensureCapacity(self.allocator, self.global_symbols.items.len); |
| 1300 | const typed_value = decl.typed_value.most_recent.typed_value; |
| 1301 | if (decl.link.local_sym_index == 0) return; |
| 1302 | const decl_sym = self.local_symbols.items[decl.link.local_sym_index]; |
| 1303 | |
| 1304 | for (exports) |exp| { |
| 1305 | if (exp.options.section) |section_name| { |
| 1306 | if (!mem.eql(u8, section_name, ".text")) { |
| 1307 | try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1); |
| 1308 | module.failed_exports.putAssumeCapacityNoClobber( |
| 1309 | exp, |
| 1310 | try Module.ErrorMsg.create(self.allocator, 0, "Unimplemented: ExportOptions.section", .{}), |
| 1311 | ); |
| 1312 | continue; |
| 1313 | } |
| 1198 | 1314 | } |
| 1199 | | return self.file.?.pwriteAll(mem.sliceAsBytes(&shdr), offset); |
| 1200 | | }, |
| 1201 | | else => return error.UnsupportedArchitecture, |
| 1202 | | } |
| 1203 | | } |
| 1315 | const stb_bits: u8 = switch (exp.options.linkage) { |
| 1316 | .Internal => elf.STB_LOCAL, |
| 1317 | .Strong => blk: { |
| 1318 | if (mem.eql(u8, exp.options.name, "_start")) { |
| 1319 | self.entry_addr = decl_sym.st_value; |
| 1320 | } |
| 1321 | break :blk elf.STB_GLOBAL; |
| 1322 | }, |
| 1323 | .Weak => elf.STB_WEAK, |
| 1324 | .LinkOnce => { |
| 1325 | try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1); |
| 1326 | module.failed_exports.putAssumeCapacityNoClobber( |
| 1327 | exp, |
| 1328 | try Module.ErrorMsg.create(self.allocator, 0, "Unimplemented: GlobalLinkage.LinkOnce", .{}), |
| 1329 | ); |
| 1330 | continue; |
| 1331 | }, |
| 1332 | }; |
| 1333 | const stt_bits: u8 = @truncate(u4, decl_sym.st_info); |
| 1334 | if (exp.link.sym_index) |i| { |
| 1335 | const sym = &self.global_symbols.items[i]; |
| 1336 | sym.* = .{ |
| 1337 | .st_name = try self.updateString(sym.st_name, exp.options.name), |
| 1338 | .st_info = (stb_bits << 4) | stt_bits, |
| 1339 | .st_other = 0, |
| 1340 | .st_shndx = self.text_section_index.?, |
| 1341 | .st_value = decl_sym.st_value, |
| 1342 | .st_size = decl_sym.st_size, |
| 1343 | }; |
| 1344 | } else { |
| 1345 | const name = try self.makeString(exp.options.name); |
| 1346 | const i = if (self.global_symbol_free_list.popOrNull()) |i| i else blk: { |
| 1347 | _ = self.global_symbols.addOneAssumeCapacity(); |
| 1348 | break :blk self.global_symbols.items.len - 1; |
| 1349 | }; |
| 1350 | self.global_symbols.items[i] = .{ |
| 1351 | .st_name = name, |
| 1352 | .st_info = (stb_bits << 4) | stt_bits, |
| 1353 | .st_other = 0, |
| 1354 | .st_shndx = self.text_section_index.?, |
| 1355 | .st_value = decl_sym.st_value, |
| 1356 | .st_size = decl_sym.st_size, |
| 1357 | }; |
| 1204 | 1358 | |
| 1205 | | fn writeOffsetTableEntry(self: *ElfFile, index: usize) !void { |
| 1206 | | const shdr = &self.sections.items[self.got_section_index.?]; |
| 1207 | | const phdr = &self.program_headers.items[self.phdr_got_index.?]; |
| 1208 | | const entry_size: u16 = switch (self.ptr_width) { |
| 1209 | | .p32 => 4, |
| 1210 | | .p64 => 8, |
| 1211 | | }; |
| 1212 | | if (self.offset_table_count_dirty) { |
| 1213 | | // TODO Also detect virtual address collisions. |
| 1214 | | const allocated_size = self.allocatedSize(shdr.sh_offset); |
| 1215 | | const needed_size = self.local_symbols.items.len * entry_size; |
| 1216 | | if (needed_size > allocated_size) { |
| 1217 | | // Must move the entire got section. |
| 1218 | | const new_offset = self.findFreeSpace(needed_size, entry_size); |
| 1219 | | const amt = try self.file.?.copyRangeAll(shdr.sh_offset, self.file.?, new_offset, shdr.sh_size); |
| 1220 | | if (amt != shdr.sh_size) return error.InputOutput; |
| 1221 | | shdr.sh_offset = new_offset; |
| 1222 | | phdr.p_offset = new_offset; |
| 1359 | exp.link.sym_index = @intCast(u32, i); |
| 1360 | } |
| 1223 | 1361 | } |
| 1224 | | shdr.sh_size = needed_size; |
| 1225 | | phdr.p_memsz = needed_size; |
| 1226 | | phdr.p_filesz = needed_size; |
| 1362 | } |
| 1227 | 1363 | |
| 1228 | | self.shdr_table_dirty = true; // TODO look into making only the one section dirty |
| 1229 | | self.phdr_table_dirty = true; // TODO look into making only the one program header dirty |
| 1364 | pub fn deleteExport(self: *Elf, exp: Export) void { |
| 1365 | const sym_index = exp.sym_index orelse return; |
| 1366 | self.global_symbol_free_list.appendAssumeCapacity(sym_index); |
| 1367 | self.global_symbols.items[sym_index].st_info = 0; |
| 1368 | } |
| 1230 | 1369 | |
| 1231 | | self.offset_table_count_dirty = false; |
| 1370 | fn writeProgHeader(self: *Elf, index: usize) !void { |
| 1371 | const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian(); |
| 1372 | const offset = self.program_headers.items[index].p_offset; |
| 1373 | switch (self.options.target.cpu.arch.ptrBitWidth()) { |
| 1374 | 32 => { |
| 1375 | var phdr = [1]elf.Elf32_Phdr{progHeaderTo32(self.program_headers.items[index])}; |
| 1376 | if (foreign_endian) { |
| 1377 | bswapAllFields(elf.Elf32_Phdr, &phdr[0]); |
| 1378 | } |
| 1379 | return self.file.?.pwriteAll(mem.sliceAsBytes(&phdr), offset); |
| 1380 | }, |
| 1381 | 64 => { |
| 1382 | var phdr = [1]elf.Elf64_Phdr{self.program_headers.items[index]}; |
| 1383 | if (foreign_endian) { |
| 1384 | bswapAllFields(elf.Elf64_Phdr, &phdr[0]); |
| 1385 | } |
| 1386 | return self.file.?.pwriteAll(mem.sliceAsBytes(&phdr), offset); |
| 1387 | }, |
| 1388 | else => return error.UnsupportedArchitecture, |
| 1389 | } |
| 1232 | 1390 | } |
| 1233 | | const endian = self.options.target.cpu.arch.endian(); |
| 1234 | | const off = shdr.sh_offset + @as(u64, entry_size) * index; |
| 1235 | | switch (self.ptr_width) { |
| 1236 | | .p32 => { |
| 1237 | | var buf: [4]u8 = undefined; |
| 1238 | | mem.writeInt(u32, &buf, @intCast(u32, self.offset_table.items[index]), endian); |
| 1239 | | try self.file.?.pwriteAll(&buf, off); |
| 1240 | | }, |
| 1241 | | .p64 => { |
| 1242 | | var buf: [8]u8 = undefined; |
| 1243 | | mem.writeInt(u64, &buf, self.offset_table.items[index], endian); |
| 1244 | | try self.file.?.pwriteAll(&buf, off); |
| 1245 | | }, |
| 1391 | |
| 1392 | fn writeSectHeader(self: *Elf, index: usize) !void { |
| 1393 | const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian(); |
| 1394 | const offset = self.sections.items[index].sh_offset; |
| 1395 | switch (self.options.target.cpu.arch.ptrBitWidth()) { |
| 1396 | 32 => { |
| 1397 | var shdr: [1]elf.Elf32_Shdr = undefined; |
| 1398 | shdr[0] = sectHeaderTo32(self.sections.items[index]); |
| 1399 | if (foreign_endian) { |
| 1400 | bswapAllFields(elf.Elf32_Shdr, &shdr[0]); |
| 1401 | } |
| 1402 | return self.file.?.pwriteAll(mem.sliceAsBytes(&shdr), offset); |
| 1403 | }, |
| 1404 | 64 => { |
| 1405 | var shdr = [1]elf.Elf64_Shdr{self.sections.items[index]}; |
| 1406 | if (foreign_endian) { |
| 1407 | bswapAllFields(elf.Elf64_Shdr, &shdr[0]); |
| 1408 | } |
| 1409 | return self.file.?.pwriteAll(mem.sliceAsBytes(&shdr), offset); |
| 1410 | }, |
| 1411 | else => return error.UnsupportedArchitecture, |
| 1412 | } |
| 1246 | 1413 | } |
| 1247 | | } |
| 1248 | 1414 | |
| 1249 | | fn writeSymbol(self: *ElfFile, index: usize) !void { |
| 1250 | | const syms_sect = &self.sections.items[self.symtab_section_index.?]; |
| 1251 | | // Make sure we are not pointlessly writing symbol data that will have to get relocated |
| 1252 | | // due to running out of space. |
| 1253 | | if (self.local_symbols.items.len != syms_sect.sh_info) { |
| 1254 | | const sym_size: u64 = switch (self.ptr_width) { |
| 1255 | | .p32 => @sizeOf(elf.Elf32_Sym), |
| 1256 | | .p64 => @sizeOf(elf.Elf64_Sym), |
| 1257 | | }; |
| 1258 | | const sym_align: u16 = switch (self.ptr_width) { |
| 1259 | | .p32 => @alignOf(elf.Elf32_Sym), |
| 1260 | | .p64 => @alignOf(elf.Elf64_Sym), |
| 1415 | fn writeOffsetTableEntry(self: *Elf, index: usize) !void { |
| 1416 | const shdr = &self.sections.items[self.got_section_index.?]; |
| 1417 | const phdr = &self.program_headers.items[self.phdr_got_index.?]; |
| 1418 | const entry_size: u16 = switch (self.ptr_width) { |
| 1419 | .p32 => 4, |
| 1420 | .p64 => 8, |
| 1261 | 1421 | }; |
| 1262 | | const needed_size = (self.local_symbols.items.len + self.global_symbols.items.len) * sym_size; |
| 1263 | | if (needed_size > self.allocatedSize(syms_sect.sh_offset)) { |
| 1264 | | // Move all the symbols to a new file location. |
| 1265 | | const new_offset = self.findFreeSpace(needed_size, sym_align); |
| 1266 | | const existing_size = @as(u64, syms_sect.sh_info) * sym_size; |
| 1267 | | const amt = try self.file.?.copyRangeAll(syms_sect.sh_offset, self.file.?, new_offset, existing_size); |
| 1268 | | if (amt != existing_size) return error.InputOutput; |
| 1269 | | syms_sect.sh_offset = new_offset; |
| 1422 | if (self.offset_table_count_dirty) { |
| 1423 | // TODO Also detect virtual address collisions. |
| 1424 | const allocated_size = self.allocatedSize(shdr.sh_offset); |
| 1425 | const needed_size = self.local_symbols.items.len * entry_size; |
| 1426 | if (needed_size > allocated_size) { |
| 1427 | // Must move the entire got section. |
| 1428 | const new_offset = self.findFreeSpace(needed_size, entry_size); |
| 1429 | const amt = try self.file.?.copyRangeAll(shdr.sh_offset, self.file.?, new_offset, shdr.sh_size); |
| 1430 | if (amt != shdr.sh_size) return error.InputOutput; |
| 1431 | shdr.sh_offset = new_offset; |
| 1432 | phdr.p_offset = new_offset; |
| 1433 | } |
| 1434 | shdr.sh_size = needed_size; |
| 1435 | phdr.p_memsz = needed_size; |
| 1436 | phdr.p_filesz = needed_size; |
| 1437 | |
| 1438 | self.shdr_table_dirty = true; // TODO look into making only the one section dirty |
| 1439 | self.phdr_table_dirty = true; // TODO look into making only the one program header dirty |
| 1440 | |
| 1441 | self.offset_table_count_dirty = false; |
| 1442 | } |
| 1443 | const endian = self.options.target.cpu.arch.endian(); |
| 1444 | const off = shdr.sh_offset + @as(u64, entry_size) * index; |
| 1445 | switch (self.ptr_width) { |
| 1446 | .p32 => { |
| 1447 | var buf: [4]u8 = undefined; |
| 1448 | mem.writeInt(u32, &buf, @intCast(u32, self.offset_table.items[index]), endian); |
| 1449 | try self.file.?.pwriteAll(&buf, off); |
| 1450 | }, |
| 1451 | .p64 => { |
| 1452 | var buf: [8]u8 = undefined; |
| 1453 | mem.writeInt(u64, &buf, self.offset_table.items[index], endian); |
| 1454 | try self.file.?.pwriteAll(&buf, off); |
| 1455 | }, |
| 1270 | 1456 | } |
| 1271 | | syms_sect.sh_info = @intCast(u32, self.local_symbols.items.len); |
| 1272 | | syms_sect.sh_size = needed_size; // anticipating adding the global symbols later |
| 1273 | | self.shdr_table_dirty = true; // TODO look into only writing one section |
| 1274 | 1457 | } |
| 1275 | | const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian(); |
| 1276 | | switch (self.ptr_width) { |
| 1277 | | .p32 => { |
| 1278 | | var sym = [1]elf.Elf32_Sym{ |
| 1279 | | .{ |
| 1280 | | .st_name = self.local_symbols.items[index].st_name, |
| 1281 | | .st_value = @intCast(u32, self.local_symbols.items[index].st_value), |
| 1282 | | .st_size = @intCast(u32, self.local_symbols.items[index].st_size), |
| 1283 | | .st_info = self.local_symbols.items[index].st_info, |
| 1284 | | .st_other = self.local_symbols.items[index].st_other, |
| 1285 | | .st_shndx = self.local_symbols.items[index].st_shndx, |
| 1286 | | }, |
| 1458 | |
| 1459 | fn writeSymbol(self: *Elf, index: usize) !void { |
| 1460 | const syms_sect = &self.sections.items[self.symtab_section_index.?]; |
| 1461 | // Make sure we are not pointlessly writing symbol data that will have to get relocated |
| 1462 | // due to running out of space. |
| 1463 | if (self.local_symbols.items.len != syms_sect.sh_info) { |
| 1464 | const sym_size: u64 = switch (self.ptr_width) { |
| 1465 | .p32 => @sizeOf(elf.Elf32_Sym), |
| 1466 | .p64 => @sizeOf(elf.Elf64_Sym), |
| 1287 | 1467 | }; |
| 1288 | | if (foreign_endian) { |
| 1289 | | bswapAllFields(elf.Elf32_Sym, &sym[0]); |
| 1290 | | } |
| 1291 | | const off = syms_sect.sh_offset + @sizeOf(elf.Elf32_Sym) * index; |
| 1292 | | try self.file.?.pwriteAll(mem.sliceAsBytes(sym[0..1]), off); |
| 1293 | | }, |
| 1294 | | .p64 => { |
| 1295 | | var sym = [1]elf.Elf64_Sym{self.local_symbols.items[index]}; |
| 1296 | | if (foreign_endian) { |
| 1297 | | bswapAllFields(elf.Elf64_Sym, &sym[0]); |
| 1468 | const sym_align: u16 = switch (self.ptr_width) { |
| 1469 | .p32 => @alignOf(elf.Elf32_Sym), |
| 1470 | .p64 => @alignOf(elf.Elf64_Sym), |
| 1471 | }; |
| 1472 | const needed_size = (self.local_symbols.items.len + self.global_symbols.items.len) * sym_size; |
| 1473 | if (needed_size > self.allocatedSize(syms_sect.sh_offset)) { |
| 1474 | // Move all the symbols to a new file location. |
| 1475 | const new_offset = self.findFreeSpace(needed_size, sym_align); |
| 1476 | const existing_size = @as(u64, syms_sect.sh_info) * sym_size; |
| 1477 | const amt = try self.file.?.copyRangeAll(syms_sect.sh_offset, self.file.?, new_offset, existing_size); |
| 1478 | if (amt != existing_size) return error.InputOutput; |
| 1479 | syms_sect.sh_offset = new_offset; |
| 1298 | 1480 | } |
| 1299 | | const off = syms_sect.sh_offset + @sizeOf(elf.Elf64_Sym) * index; |
| 1300 | | try self.file.?.pwriteAll(mem.sliceAsBytes(sym[0..1]), off); |
| 1301 | | }, |
| 1302 | | } |
| 1303 | | } |
| 1304 | | |
| 1305 | | fn writeAllGlobalSymbols(self: *ElfFile) !void { |
| 1306 | | const syms_sect = &self.sections.items[self.symtab_section_index.?]; |
| 1307 | | const sym_size: u64 = switch (self.ptr_width) { |
| 1308 | | .p32 => @sizeOf(elf.Elf32_Sym), |
| 1309 | | .p64 => @sizeOf(elf.Elf64_Sym), |
| 1310 | | }; |
| 1311 | | const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian(); |
| 1312 | | const global_syms_off = syms_sect.sh_offset + self.local_symbols.items.len * sym_size; |
| 1313 | | switch (self.ptr_width) { |
| 1314 | | .p32 => { |
| 1315 | | const buf = try self.allocator.alloc(elf.Elf32_Sym, self.global_symbols.items.len); |
| 1316 | | defer self.allocator.free(buf); |
| 1317 | | |
| 1318 | | for (buf) |*sym, i| { |
| 1319 | | sym.* = .{ |
| 1320 | | .st_name = self.global_symbols.items[i].st_name, |
| 1321 | | .st_value = @intCast(u32, self.global_symbols.items[i].st_value), |
| 1322 | | .st_size = @intCast(u32, self.global_symbols.items[i].st_size), |
| 1323 | | .st_info = self.global_symbols.items[i].st_info, |
| 1324 | | .st_other = self.global_symbols.items[i].st_other, |
| 1325 | | .st_shndx = self.global_symbols.items[i].st_shndx, |
| 1481 | syms_sect.sh_info = @intCast(u32, self.local_symbols.items.len); |
| 1482 | syms_sect.sh_size = needed_size; // anticipating adding the global symbols later |
| 1483 | self.shdr_table_dirty = true; // TODO look into only writing one section |
| 1484 | } |
| 1485 | const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian(); |
| 1486 | switch (self.ptr_width) { |
| 1487 | .p32 => { |
| 1488 | var sym = [1]elf.Elf32_Sym{ |
| 1489 | .{ |
| 1490 | .st_name = self.local_symbols.items[index].st_name, |
| 1491 | .st_value = @intCast(u32, self.local_symbols.items[index].st_value), |
| 1492 | .st_size = @intCast(u32, self.local_symbols.items[index].st_size), |
| 1493 | .st_info = self.local_symbols.items[index].st_info, |
| 1494 | .st_other = self.local_symbols.items[index].st_other, |
| 1495 | .st_shndx = self.local_symbols.items[index].st_shndx, |
| 1496 | }, |
| 1326 | 1497 | }; |
| 1327 | 1498 | if (foreign_endian) { |
| 1328 | | bswapAllFields(elf.Elf32_Sym, sym); |
| 1499 | bswapAllFields(elf.Elf32_Sym, &sym[0]); |
| 1329 | 1500 | } |
| 1330 | | } |
| 1331 | | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), global_syms_off); |
| 1332 | | }, |
| 1333 | | .p64 => { |
| 1334 | | const buf = try self.allocator.alloc(elf.Elf64_Sym, self.global_symbols.items.len); |
| 1335 | | defer self.allocator.free(buf); |
| 1336 | | |
| 1337 | | for (buf) |*sym, i| { |
| 1338 | | sym.* = .{ |
| 1339 | | .st_name = self.global_symbols.items[i].st_name, |
| 1340 | | .st_value = self.global_symbols.items[i].st_value, |
| 1341 | | .st_size = self.global_symbols.items[i].st_size, |
| 1342 | | .st_info = self.global_symbols.items[i].st_info, |
| 1343 | | .st_other = self.global_symbols.items[i].st_other, |
| 1344 | | .st_shndx = self.global_symbols.items[i].st_shndx, |
| 1345 | | }; |
| 1501 | const off = syms_sect.sh_offset + @sizeOf(elf.Elf32_Sym) * index; |
| 1502 | try self.file.?.pwriteAll(mem.sliceAsBytes(sym[0..1]), off); |
| 1503 | }, |
| 1504 | .p64 => { |
| 1505 | var sym = [1]elf.Elf64_Sym{self.local_symbols.items[index]}; |
| 1346 | 1506 | if (foreign_endian) { |
| 1347 | | bswapAllFields(elf.Elf64_Sym, sym); |
| 1507 | bswapAllFields(elf.Elf64_Sym, &sym[0]); |
| 1348 | 1508 | } |
| 1349 | | } |
| 1350 | | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), global_syms_off); |
| 1351 | | }, |
| 1509 | const off = syms_sect.sh_offset + @sizeOf(elf.Elf64_Sym) * index; |
| 1510 | try self.file.?.pwriteAll(mem.sliceAsBytes(sym[0..1]), off); |
| 1511 | }, |
| 1512 | } |
| 1352 | 1513 | } |
| 1353 | | } |
| 1514 | |
| 1515 | fn writeAllGlobalSymbols(self: *Elf) !void { |
| 1516 | const syms_sect = &self.sections.items[self.symtab_section_index.?]; |
| 1517 | const sym_size: u64 = switch (self.ptr_width) { |
| 1518 | .p32 => @sizeOf(elf.Elf32_Sym), |
| 1519 | .p64 => @sizeOf(elf.Elf64_Sym), |
| 1520 | }; |
| 1521 | const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian(); |
| 1522 | const global_syms_off = syms_sect.sh_offset + self.local_symbols.items.len * sym_size; |
| 1523 | switch (self.ptr_width) { |
| 1524 | .p32 => { |
| 1525 | const buf = try self.allocator.alloc(elf.Elf32_Sym, self.global_symbols.items.len); |
| 1526 | defer self.allocator.free(buf); |
| 1527 | |
| 1528 | for (buf) |*sym, i| { |
| 1529 | sym.* = .{ |
| 1530 | .st_name = self.global_symbols.items[i].st_name, |
| 1531 | .st_value = @intCast(u32, self.global_symbols.items[i].st_value), |
| 1532 | .st_size = @intCast(u32, self.global_symbols.items[i].st_size), |
| 1533 | .st_info = self.global_symbols.items[i].st_info, |
| 1534 | .st_other = self.global_symbols.items[i].st_other, |
| 1535 | .st_shndx = self.global_symbols.items[i].st_shndx, |
| 1536 | }; |
| 1537 | if (foreign_endian) { |
| 1538 | bswapAllFields(elf.Elf32_Sym, sym); |
| 1539 | } |
| 1540 | } |
| 1541 | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), global_syms_off); |
| 1542 | }, |
| 1543 | .p64 => { |
| 1544 | const buf = try self.allocator.alloc(elf.Elf64_Sym, self.global_symbols.items.len); |
| 1545 | defer self.allocator.free(buf); |
| 1546 | |
| 1547 | for (buf) |*sym, i| { |
| 1548 | sym.* = .{ |
| 1549 | .st_name = self.global_symbols.items[i].st_name, |
| 1550 | .st_value = self.global_symbols.items[i].st_value, |
| 1551 | .st_size = self.global_symbols.items[i].st_size, |
| 1552 | .st_info = self.global_symbols.items[i].st_info, |
| 1553 | .st_other = self.global_symbols.items[i].st_other, |
| 1554 | .st_shndx = self.global_symbols.items[i].st_shndx, |
| 1555 | }; |
| 1556 | if (foreign_endian) { |
| 1557 | bswapAllFields(elf.Elf64_Sym, sym); |
| 1558 | } |
| 1559 | } |
| 1560 | try self.file.?.pwriteAll(mem.sliceAsBytes(buf), global_syms_off); |
| 1561 | }, |
| 1562 | } |
| 1563 | } |
| 1564 | }; |
| 1354 | 1565 | }; |
| 1355 | 1566 | |
| 1356 | 1567 | /// Truncates the existing file contents and overwrites the contents. |
| 1357 | 1568 | /// Returns an error if `file` is not already open with +read +write +seek abilities. |
| 1358 | | pub fn createElfFile(allocator: *Allocator, file: fs.File, options: Options) !ElfFile { |
| 1569 | pub fn createElfFile(allocator: *Allocator, file: fs.File, options: Options) !File.Elf { |
| 1359 | 1570 | switch (options.output_mode) { |
| 1360 | 1571 | .Exe => {}, |
| 1361 | 1572 | .Obj => {}, |
| ... | ... | @@ -1369,7 +1580,7 @@ pub fn createElfFile(allocator: *Allocator, file: fs.File, options: Options) !El |
| 1369 | 1580 | .wasm => return error.TODOImplementWritingWasmObjects, |
| 1370 | 1581 | } |
| 1371 | 1582 | |
| 1372 | | var self: ElfFile = .{ |
| 1583 | var self: File.Elf = .{ |
| 1373 | 1584 | .allocator = allocator, |
| 1374 | 1585 | .file = file, |
| 1375 | 1586 | .options = options, |
| ... | ... | @@ -1413,7 +1624,7 @@ pub fn createElfFile(allocator: *Allocator, file: fs.File, options: Options) !El |
| 1413 | 1624 | } |
| 1414 | 1625 | |
| 1415 | 1626 | /// Returns error.IncrFailed if incremental update could not be performed. |
| 1416 | | fn openBinFileInner(allocator: *Allocator, file: fs.File, options: Options) !ElfFile { |
| 1627 | fn openBinFileInner(allocator: *Allocator, file: fs.File, options: Options) !File.Elf { |
| 1417 | 1628 | switch (options.output_mode) { |
| 1418 | 1629 | .Exe => {}, |
| 1419 | 1630 | .Obj => {}, |
| ... | ... | @@ -1426,7 +1637,7 @@ fn openBinFileInner(allocator: *Allocator, file: fs.File, options: Options) !Elf |
| 1426 | 1637 | .macho => return error.IncrFailed, |
| 1427 | 1638 | .wasm => return error.IncrFailed, |
| 1428 | 1639 | } |
| 1429 | | var self: ElfFile = .{ |
| 1640 | var self: File.Elf = .{ |
| 1430 | 1641 | .allocator = allocator, |
| 1431 | 1642 | .file = file, |
| 1432 | 1643 | .owns_file_handle = false, |