| ... | @@ -17,11 +17,40 @@ const target_util = @import("../target.zig"); | ... | @@ -17,11 +17,40 @@ const target_util = @import("../target.zig"); |
| 17 | const Type = @import("../Type.zig"); | 17 | const Type = @import("../Type.zig"); |
| 18 | const Value = @import("../Value.zig"); | 18 | const Value = @import("../Value.zig"); |
| 19 | const Zcu = @import("../Zcu.zig"); | 19 | const Zcu = @import("../Zcu.zig"); |
| | 20 | const ModuleDefinition = @import("../libs/mingw/def.zig").ModuleDefinition; |
| | 21 | const implib = @import("../libs/mingw/implib.zig"); |
| | 22 | const Path = std.Build.Cache.Path; |
| 20 | | 23 | |
| 21 | base: link.File, | 24 | base: link.File, |
| | 25 | options: link.File.OpenOptions, |
| 22 | mf: MappedFile, | 26 | mf: MappedFile, |
| 23 | nodes: std.MultiArrayList(Node), | 27 | nodes: std.MultiArrayList(Node), |
| | 28 | members: std.ArrayList(Member), |
| | 29 | pending_members: std.array_hash_map.Auto(Member.Index, void), |
| | 30 | lib_string_table: std.ArrayList(String), |
| | 31 | lib_string_len: u32, |
| | 32 | long_names_table: LongNamesTable, |
| 24 | import_table: ImportTable, | 33 | import_table: ImportTable, |
| | 34 | export_table: ExportTable, |
| | 35 | symbol_table: SymbolTable, |
| | 36 | inputs: std.array_hash_map.Custom(std.Build.Cache.Path, void, std.Build.Cache.Path.TableAdapter, false), |
| | 37 | input_archives: std.ArrayList(InputArchive), |
| | 38 | input_archive_members: std.ArrayList(InputArchive.Member), |
| | 39 | input_archive_symbols: std.ArrayList(InputArchive.Member.Symbol), |
| | 40 | input_archive_symbol_indices: std.array_hash_map.Auto(String, InputArchive.SearchList), |
| | 41 | pending_input: ?InputArchive.Member.Index, |
| | 42 | pending_default_libs: std.ArrayList(struct { |
| | 43 | path: []const u8, |
| | 44 | ioi: InputObject.Index, |
| | 45 | }), |
| | 46 | alternate_names: std.array_hash_map.Auto(String, String), |
| | 47 | input_objects: std.ArrayList(InputObject), |
| | 48 | input_symbols: std.ArrayList(struct { si: Symbol.Index, name: String }), |
| | 49 | input_sections: std.ArrayList(Node.InputSection), |
| | 50 | input_section_pending_index: u32, |
| | 51 | inputs_complete: bool, |
| | 52 | exports_complete: bool, |
| | 53 | pending_special_symbol: SpecialSymbol, |
| 25 | strings: std.HashMapUnmanaged( | 54 | strings: std.HashMapUnmanaged( |
| 26 | u32, | 55 | u32, |
| 27 | void, | 56 | void, |
| ... | @@ -29,11 +58,13 @@ strings: std.HashMapUnmanaged( | ... | @@ -29,11 +58,13 @@ strings: std.HashMapUnmanaged( |
| 29 | std.hash_map.default_max_load_percentage, | 58 | std.hash_map.default_max_load_percentage, |
| 30 | ), | 59 | ), |
| 31 | string_bytes: std.ArrayList(u8), | 60 | string_bytes: std.ArrayList(u8), |
| 32 | image_section_table: std.ArrayList(Symbol.Index), | 61 | section_table: std.array_hash_map.Auto(String, Section), |
| 33 | pseudo_section_table: std.array_hash_map.Auto(String, Symbol.Index), | 62 | pseudo_section_table: std.array_hash_map.Auto(String, Symbol.Index), |
| 34 | object_section_table: std.array_hash_map.Auto(String, Symbol.Index), | 63 | object_section_table: std.array_hash_map.Auto(String, Symbol.Index), |
| 35 | symbol_table: std.ArrayList(Symbol), | 64 | section_merges: std.array_hash_map.Auto(String, String), |
| 36 | globals: std.array_hash_map.Auto(GlobalName, Symbol.Index), | 65 | section_merge_pending_index: u32, |
| | 66 | symbols: std.ArrayList(Symbol), |
| | 67 | globals: std.array_hash_map.Auto(String, Global), |
| 37 | global_pending_index: u32, | 68 | global_pending_index: u32, |
| 38 | navs: std.array_hash_map.Auto(InternPool.Nav.Index, Symbol.Index), | 69 | navs: std.array_hash_map.Auto(InternPool.Nav.Index, Symbol.Index), |
| 39 | uavs: std.array_hash_map.Auto(InternPool.Index, Symbol.Index), | 70 | uavs: std.array_hash_map.Auto(InternPool.Index, Symbol.Index), |
| ... | @@ -45,8 +76,13 @@ pending_uavs: std.array_hash_map.Auto(Node.UavMapIndex, struct { | ... | @@ -45,8 +76,13 @@ pending_uavs: std.array_hash_map.Auto(Node.UavMapIndex, struct { |
| 45 | alignment: InternPool.Alignment, | 76 | alignment: InternPool.Alignment, |
| 46 | }), | 77 | }), |
| 47 | relocs: std.ArrayList(Reloc), | 78 | relocs: std.ArrayList(Reloc), |
| | 79 | first_free_reloc: Reloc.Index, |
| | 80 | last_free_reloc: Reloc.Index, |
| 48 | const_prog_node: std.Progress.Node, | 81 | const_prog_node: std.Progress.Node, |
| 49 | synth_prog_node: std.Progress.Node, | 82 | synth_prog_node: std.Progress.Node, |
| | 83 | symbol_prog_node: std.Progress.Node, |
| | 84 | member_prog_node: std.Progress.Node, |
| | 85 | input_prog_node: std.Progress.Node, |
| 50 | | 86 | |
| 51 | pub const default_file_alignment: u16 = 0x200; | 87 | pub const default_file_alignment: u16 = 0x200; |
| 52 | pub const default_size_of_stack_reserve: u32 = 0x1000000; | 88 | pub const default_size_of_stack_reserve: u32 = 0x1000000; |
| ... | @@ -54,6 +90,17 @@ pub const default_size_of_stack_commit: u32 = 0x1000; | ... | @@ -54,6 +90,17 @@ pub const default_size_of_stack_commit: u32 = 0x1000; |
| 54 | pub const default_size_of_heap_reserve: u32 = 0x100000; | 90 | pub const default_size_of_heap_reserve: u32 = 0x100000; |
| 55 | pub const default_size_of_heap_commit: u32 = 0x1000; | 91 | pub const default_size_of_heap_commit: u32 = 0x1000; |
| 56 | | 92 | |
| | 93 | pub const imp_prefix = "__imp_"; |
| | 94 | |
| | 95 | const header_name_max_len = @typeInfo(@FieldType(std.coff.SectionHeader, "name")).array.len; |
| | 96 | |
| | 97 | const Error = link.Error || error{MappedFileIo}; |
| | 98 | const LoadInputError = Error || |
| | 99 | Io.File.SeekError || |
| | 100 | Io.File.Reader.SizeError || |
| | 101 | Io.Reader.Error || |
| | 102 | MappedFile.Error; |
| | 103 | |
| 57 | /// This is the start of a Portable Executable (PE) file. | 104 | /// This is the start of a Portable Executable (PE) file. |
| 58 | /// It starts with a MS-DOS header followed by a MS-DOS stub program. | 105 | /// It starts with a MS-DOS header followed by a MS-DOS stub program. |
| 59 | /// This data does not change so we include it as follows in all binaries. | 106 | /// This data does not change so we include it as follows in all binaries. |
| ... | @@ -134,25 +181,53 @@ pub const msdos_stub: [120]u8 = .{ | ... | @@ -134,25 +181,53 @@ pub const msdos_stub: [120]u8 = .{ |
| 134 | pub const Node = union(enum) { | 181 | pub const Node = union(enum) { |
| 135 | file, | 182 | file, |
| 136 | header, | 183 | header, |
| | 184 | /// Images and archives only. |
| 137 | signature, | 185 | signature, |
| | 186 | /// Archives only. |
| | 187 | archive_member_header: Member.Index, |
| | 188 | archive_member: Member.Index, |
| | 189 | |
| 138 | coff_header, | 190 | coff_header, |
| | 191 | |
| | 192 | /// Image only |
| 139 | optional_header, | 193 | optional_header, |
| 140 | data_directories, | 194 | data_directories, |
| | 195 | |
| 141 | section_table, | 196 | section_table, |
| | 197 | |
| | 198 | /// Archives and objects only |
| | 199 | symbol_table, |
| | 200 | string_table, |
| | 201 | relocation_table: Symbol.SectionNumber, |
| | 202 | relocation_table_entry: Reloc.Index, |
| | 203 | |
| 142 | image_section: Symbol.Index, | 204 | image_section: Symbol.Index, |
| 143 | | 205 | |
| | 206 | /// Images only |
| 144 | import_directory_table, | 207 | import_directory_table, |
| 145 | import_lookup_table: ImportTable.Index, | 208 | import_lookup_table: ImportTable.Index, |
| 146 | import_address_table: ImportTable.Index, | 209 | import_address_table: ImportTable.Index, |
| 147 | import_hint_name_table: ImportTable.Index, | 210 | import_hint_name_table: ImportTable.Index, |
| 148 | | 211 | |
| | 212 | /// Images only |
| | 213 | export_directory_table, |
| | 214 | export_address_table, |
| | 215 | export_name_pointer_table, |
| | 216 | export_ordinal_table, |
| | 217 | export_name_table, |
| | 218 | |
| 149 | pseudo_section: PseudoSectionMapIndex, | 219 | pseudo_section: PseudoSectionMapIndex, |
| 150 | object_section: ObjectSectionMapIndex, | 220 | object_section: ObjectSectionMapIndex, |
| 151 | global: GlobalMapIndex, | 221 | input_section: InputSection.Index, |
| | 222 | import_thunk: GlobalMapIndex, |
| 152 | nav: NavMapIndex, | 223 | nav: NavMapIndex, |
| 153 | uav: UavMapIndex, | 224 | uav: UavMapIndex, |
| 154 | lazy_code: LazyMapRef.Index(.code), | 225 | lazy_code: LazyMapRef.Index(.code), |
| 155 | lazy_const_data: LazyMapRef.Index(.const_data), | 226 | lazy_const_data: LazyMapRef.Index(.const_data), |
| | 227 | builtin: Symbol.Index, |
| | 228 | |
| | 229 | /// Takes the place of a known node index when that node is not present in the output |
| | 230 | placeholder, |
| 156 | | 231 | |
| 157 | pub const PseudoSectionMapIndex = enum(u32) { | 232 | pub const PseudoSectionMapIndex = enum(u32) { |
| 158 | _, | 233 | _, |
| ... | @@ -179,14 +254,30 @@ pub const Node = union(enum) { | ... | @@ -179,14 +254,30 @@ pub const Node = union(enum) { |
| 179 | }; | 254 | }; |
| 180 | | 255 | |
| 181 | pub const GlobalMapIndex = enum(u32) { | 256 | pub const GlobalMapIndex = enum(u32) { |
| | 257 | none, |
| 182 | _, | 258 | _, |
| 183 | | 259 | |
| 184 | pub fn globalName(gmi: GlobalMapIndex, coff: *const Coff) GlobalName { | 260 | pub fn wrap(i: ?u32) GlobalMapIndex { |
| 185 | return coff.globals.keys()[@intFromEnum(gmi)]; | 261 | return @enumFromInt((i orelse return .none) + 1); |
| | 262 | } |
| | 263 | |
| | 264 | pub fn unwrap(gmi: GlobalMapIndex) ?u32 { |
| | 265 | return switch (gmi) { |
| | 266 | .none => null, |
| | 267 | _ => @intFromEnum(gmi) - 1, |
| | 268 | }; |
| | 269 | } |
| | 270 | |
| | 271 | pub fn name(gmi: GlobalMapIndex, coff: *const Coff) String { |
| | 272 | return coff.globals.keys()[gmi.unwrap().?]; |
| 186 | } | 273 | } |
| 187 | | 274 | |
| 188 | pub fn symbol(gmi: GlobalMapIndex, coff: *const Coff) Symbol.Index { | 275 | pub fn symbol(gmi: GlobalMapIndex, coff: *const Coff) Symbol.Index { |
| 189 | return coff.globals.values()[@intFromEnum(gmi)]; | 276 | return coff.globals.values()[gmi.unwrap().?].si; |
| | 277 | } |
| | 278 | |
| | 279 | pub fn libName(gmi: GlobalMapIndex, coff: *const Coff) String.Optional { |
| | 280 | return coff.globals.values()[gmi.unwrap().?].lib_name; |
| 190 | } | 281 | } |
| 191 | }; | 282 | }; |
| 192 | | 283 | |
| ... | @@ -214,6 +305,47 @@ pub const Node = union(enum) { | ... | @@ -214,6 +305,47 @@ pub const Node = union(enum) { |
| 214 | } | 305 | } |
| 215 | }; | 306 | }; |
| 216 | | 307 | |
| | 308 | const InputSection = struct { |
| | 309 | ioi: InputObject.Index, |
| | 310 | si: Symbol.Index, |
| | 311 | comdat_si: Symbol.Index, |
| | 312 | file_location: MappedFile.Node.FileLocation, |
| | 313 | first_li: Node.InputSection.LocalIndex, |
| | 314 | crc: u32, |
| | 315 | |
| | 316 | pub const Index = enum(u32) { |
| | 317 | _, |
| | 318 | |
| | 319 | pub fn inputSection(isi: Index, coff: *const Coff) *InputSection { |
| | 320 | return &coff.input_sections.items[@intFromEnum(isi)]; |
| | 321 | } |
| | 322 | |
| | 323 | pub fn input(isi: Index, coff: *const Coff) InputObject.Index { |
| | 324 | return coff.input_sections.items[@intFromEnum(isi)].ioi; |
| | 325 | } |
| | 326 | |
| | 327 | pub fn fileLocation(isi: Index, coff: *const Coff) MappedFile.Node.FileLocation { |
| | 328 | return coff.input_sections.items[@intFromEnum(isi)].file_location; |
| | 329 | } |
| | 330 | |
| | 331 | pub fn symbol(isi: Index, coff: *const Coff) Symbol.Index { |
| | 332 | return coff.input_sections.items[@intFromEnum(isi)].si; |
| | 333 | } |
| | 334 | |
| | 335 | pub fn firstSymbol(isi: Index, coff: *const Coff) LocalIndex { |
| | 336 | return coff.input_sections.items[@intFromEnum(isi)].first_li; |
| | 337 | } |
| | 338 | }; |
| | 339 | |
| | 340 | const LocalIndex = enum(u32) { |
| | 341 | _, |
| | 342 | |
| | 343 | pub fn name(isli: LocalIndex, coff: *const Coff) String { |
| | 344 | return coff.input_symbols.items[@intFromEnum(isli)].name; |
| | 345 | } |
| | 346 | }; |
| | 347 | }; |
| | 348 | |
| 217 | pub const LazyMapRef = struct { | 349 | pub const LazyMapRef = struct { |
| 218 | kind: link.File.LazySymbol.Kind, | 350 | kind: link.File.LazySymbol.Kind, |
| 219 | index: u32, | 351 | index: u32, |
| ... | @@ -253,6 +385,14 @@ pub const Node = union(enum) { | ... | @@ -253,6 +385,14 @@ pub const Node = union(enum) { |
| 253 | file, | 385 | file, |
| 254 | header, | 386 | header, |
| 255 | signature, | 387 | signature, |
| | 388 | first_linker_member_header, |
| | 389 | first_linker_member, |
| | 390 | second_linker_member_header, |
| | 391 | second_linker_member, |
| | 392 | longnames_member_header, |
| | 393 | longnames_member, |
| | 394 | zcu_member_header, |
| | 395 | zcu_member, |
| 256 | coff_header, | 396 | coff_header, |
| 257 | optional_header, | 397 | optional_header, |
| 258 | data_directories, | 398 | data_directories, |
| ... | @@ -270,14 +410,338 @@ pub const Node = union(enum) { | ... | @@ -270,14 +410,338 @@ pub const Node = union(enum) { |
| 270 | } | 410 | } |
| 271 | }; | 411 | }; |
| 272 | | 412 | |
| | 413 | pub const InputArchive = struct { |
| | 414 | path: std.Build.Cache.Path, |
| | 415 | |
| | 416 | const Index = enum(u32) { |
| | 417 | _, |
| | 418 | |
| | 419 | pub fn path(iai: InputArchive.Index, coff: *Coff) std.Build.Cache.Path { |
| | 420 | return coff.input_archives.items[@intFromEnum(iai)].path; |
| | 421 | } |
| | 422 | }; |
| | 423 | |
| | 424 | pub const Member = struct { |
| | 425 | iai: InputArchive.Index, |
| | 426 | name: String, |
| | 427 | content: union(enum) { |
| | 428 | // This range includes the member header |
| | 429 | object: MappedFile.Node.FileLocation, |
| | 430 | import: struct { |
| | 431 | symbol_name: String, |
| | 432 | lib_name: String, |
| | 433 | // Either ordinal or hint, depending on value of name_type |
| | 434 | import_ordinal_hint: u16, |
| | 435 | type: std.coff.ImportType, |
| | 436 | name_type: std.coff.ImportNameType, |
| | 437 | }, |
| | 438 | }, |
| | 439 | flags: packed struct { |
| | 440 | // Set if an attempt was made to load this member |
| | 441 | is_loaded: bool, |
| | 442 | }, |
| | 443 | |
| | 444 | const Index = enum(u32) { |
| | 445 | _, |
| | 446 | |
| | 447 | pub fn member(iami: InputArchive.Member.Index, coff: *Coff) *InputArchive.Member { |
| | 448 | return &coff.input_archive_members.items[@intFromEnum(iami)]; |
| | 449 | } |
| | 450 | }; |
| | 451 | |
| | 452 | pub const Symbol = struct { |
| | 453 | iami: InputArchive.Member.Index, |
| | 454 | // Set to its own index to indicate its the last in the list |
| | 455 | next: InputArchive.Member.Symbol.Index, |
| | 456 | |
| | 457 | const Index = enum(u32) { |
| | 458 | _, |
| | 459 | }; |
| | 460 | }; |
| | 461 | }; |
| | 462 | |
| | 463 | pub const SearchList = struct { |
| | 464 | first: InputArchive.Member.Symbol.Index, |
| | 465 | last: InputArchive.Member.Symbol.Index, |
| | 466 | }; |
| | 467 | }; |
| | 468 | |
| | 469 | pub const InputObject = struct { |
| | 470 | path: std.Build.Cache.Path, |
| | 471 | member_name: ?[]const u8, |
| | 472 | source_name: String.Optional, |
| | 473 | |
| | 474 | pub const Index = enum(u32) { |
| | 475 | _, |
| | 476 | |
| | 477 | pub fn path(ioi: Index, coff: *const Coff) std.Build.Cache.Path { |
| | 478 | return coff.input_objects.items[@intFromEnum(ioi)].path; |
| | 479 | } |
| | 480 | |
| | 481 | pub fn memberName(ioi: Index, coff: *const Coff) ?[]const u8 { |
| | 482 | return coff.input_objects.items[@intFromEnum(ioi)].member_name; |
| | 483 | } |
| | 484 | }; |
| | 485 | }; |
| | 486 | |
| | 487 | pub const Member = struct { |
| | 488 | kind: std.coff.ArchiveMemberHeader.Kind, |
| | 489 | header_ni: MappedFile.Node.Index, |
| | 490 | content_ni: MappedFile.Node.Index, |
| | 491 | first_linker_indices: std.array_hash_map.Auto(struct { |
| | 492 | mi: Member.Index, |
| | 493 | name: String, |
| | 494 | }, FirstLinkerIndex), |
| | 495 | |
| | 496 | pub const Index = enum(u16) { |
| | 497 | first, |
| | 498 | second, |
| | 499 | longnames, |
| | 500 | _, |
| | 501 | |
| | 502 | const known_count = @typeInfo(Index).@"enum".field_names.len; |
| | 503 | |
| | 504 | pub fn get(member_index: Member.Index, coff: *Coff) *Member { |
| | 505 | return &coff.members.items[@intFromEnum(member_index)]; |
| | 506 | } |
| | 507 | }; |
| | 508 | |
| | 509 | pub const FirstLinkerIndex = enum(u32) { |
| | 510 | _, |
| | 511 | }; |
| | 512 | |
| | 513 | pub fn headerPtr(member: *Member, coff: *Coff) *std.coff.ArchiveMemberHeader { |
| | 514 | return @ptrCast(@alignCast(member.header_ni.slice(&coff.mf))); |
| | 515 | } |
| | 516 | |
| | 517 | /// Sets `name` as the name field of this member's header, either directly (if it's short enough), |
| | 518 | /// or by creating an entry in the longnames member and storing a reference to that entry. |
| | 519 | pub fn initHeader(member: *Member, coff: *Coff, name: []const u8, timestamp: u32) !void { |
| | 520 | const max_name_len = @typeInfo(@FieldType(std.coff.ArchiveMemberHeader, "name")).array.len; |
| | 521 | const opt_name_offset = if (name.len >= max_name_len) offset: { |
| | 522 | const gpa = coff.base.comp.gpa; |
| | 523 | const entries_ctx = LongNamesTable.Adapter{ .coff = coff }; |
| | 524 | const gop = try coff.long_names_table.entries.getOrPutAdapted( |
| | 525 | gpa, |
| | 526 | name, |
| | 527 | entries_ctx, |
| | 528 | ); |
| | 529 | |
| | 530 | if (!gop.found_existing) { |
| | 531 | errdefer _ = coff.export_table.entries.pop(); |
| | 532 | |
| | 533 | _, const old_size = Node.known.longnames_member.location(&coff.mf).resolve(&coff.mf); |
| | 534 | const new_size = old_size + name.len + 1; |
| | 535 | assert(new_size < comptime try std.math.powi(u64, 10, max_name_len - 1)); |
| | 536 | |
| | 537 | try Node.known.longnames_member.resize(&coff.mf, gpa, new_size); |
| | 538 | const name_table_slice = Node.known.longnames_member.slice(&coff.mf); |
| | 539 | const name_slice = name_table_slice[@intCast(old_size)..][0 .. name.len + 1]; |
| | 540 | @memcpy(name_slice[0..name.len], name); |
| | 541 | name_slice[name.len] = 0; |
| | 542 | |
| | 543 | gop.value_ptr.* = .{ |
| | 544 | .offset = old_size, |
| | 545 | .len = name.len, |
| | 546 | }; |
| | 547 | } |
| | 548 | |
| | 549 | break :offset gop.value_ptr.offset; |
| | 550 | } else null; |
| | 551 | |
| | 552 | const header = member.headerPtr(coff); |
| | 553 | if (opt_name_offset) |name_offset| { |
| | 554 | header.name[0] = '/'; |
| | 555 | storeHeaderDecimalStr(header.name[1..], name_offset); |
| | 556 | } else { |
| | 557 | @memcpy(header.name[0..name.len], name); |
| | 558 | header.name[name.len] = '/'; |
| | 559 | const padding = max_name_len - name.len - 1; |
| | 560 | @memset(header.name[max_name_len - padding ..], ' '); |
| | 561 | } |
| | 562 | |
| | 563 | storeHeaderDecimalStr(&header.date, timestamp); |
| | 564 | |
| | 565 | // Matching the Microsoft behaviour of emitting blanks for these fields |
| | 566 | header.user_id = @splat(' '); |
| | 567 | header.group_id = @splat(' '); |
| | 568 | |
| | 569 | // file_mode is actually octal, but we only ever write 0 to it |
| | 570 | storeHeaderDecimalStr(&header.file_mode, 0); |
| | 571 | if (!member.content_ni.hasResized(&coff.mf)) |
| | 572 | storeHeaderDecimalStr( |
| | 573 | &header.size, |
| | 574 | member.content_ni.location(&coff.mf).resolve(&coff.mf)[1], |
| | 575 | ); |
| | 576 | |
| | 577 | @memcpy(&header.end_of_header, std.coff.archive_end_of_header); |
| | 578 | } |
| | 579 | |
| | 580 | pub fn storeHeaderDecimalStr(field_ptr: anytype, value: u64) void { |
| | 581 | const array_info = @typeInfo(@typeInfo(@TypeOf(field_ptr)).pointer.child).array; |
| | 582 | assert(array_info.child == u8); |
| | 583 | assert(value < comptime try std.math.powi(u64, 10, array_info.len)); |
| | 584 | _ = std.fmt.printInt(field_ptr, value, 10, .lower, .{ |
| | 585 | .width = array_info.len, |
| | 586 | .alignment = .left, |
| | 587 | .fill = ' ', |
| | 588 | }); |
| | 589 | } |
| | 590 | |
| | 591 | pub fn loadHeaderDecimalStr(field_ptr: anytype, value: u64) void { |
| | 592 | const array_info = @typeInfo(@typeInfo(@TypeOf(field_ptr)).pointer.child).array; |
| | 593 | assert(array_info.child == u8); |
| | 594 | assert(value < comptime try std.math.powi(u64, 10, array_info.len)); |
| | 595 | _ = std.fmt.printInt(field_ptr, value, 10, .lower, .{ |
| | 596 | .width = array_info.len, |
| | 597 | .alignment = .left, |
| | 598 | .fill = ' ', |
| | 599 | }); |
| | 600 | } |
| | 601 | }; |
| | 602 | |
| | 603 | pub const LongNamesTable = struct { |
| | 604 | ni: MappedFile.Node.Index = .none, |
| | 605 | entries: std.array_hash_map.Auto(void, Entry), |
| | 606 | |
| | 607 | pub const Entry = struct { |
| | 608 | offset: u64, |
| | 609 | len: u64, |
| | 610 | }; |
| | 611 | |
| | 612 | const Adapter = struct { |
| | 613 | coff: *Coff, |
| | 614 | |
| | 615 | pub fn eql(adapter: Adapter, lhs_key: []const u8, _: void, rhs_index: usize) bool { |
| | 616 | assert(adapter.coff.isArchive()); |
| | 617 | const longnames_slice = Node.known.longnames_member.slice(&adapter.coff.mf); |
| | 618 | const rhs = adapter.coff.long_names_table.entries.values()[rhs_index]; |
| | 619 | return std.mem.eql(u8, longnames_slice[@intCast(rhs.offset)..][0..@intCast(rhs.len)], lhs_key); |
| | 620 | } |
| | 621 | |
| | 622 | pub fn hash(_: Adapter, key: []const u8) u32 { |
| | 623 | assert(std.mem.indexOfScalar(u8, key, 0) == null); |
| | 624 | return std.array_hash_map.hashString(key); |
| | 625 | } |
| | 626 | }; |
| | 627 | }; |
| | 628 | |
| | 629 | pub const SymbolTable = struct { |
| | 630 | ni: MappedFile.Node.Index, |
| | 631 | strings_ni: MappedFile.Node.Index, |
| | 632 | strings: std.array_hash_map.Auto(String, StringIndex), |
| | 633 | symbols: std.array_hash_map.Auto(Symbol.Index, SymbolTable.Index), |
| | 634 | pending_symbol_index: u32, |
| | 635 | |
| | 636 | // Resizing the symbol table node has the result of accumulating padding |
| | 637 | // between the last symbol in the symbol table node and the start of the |
| | 638 | // string table node, due to the shifting method when resizing the parent in MappedFile. |
| | 639 | // The spec requires the string table begin immediately after the last symbol, |
| | 640 | // so we compact the symbol table node and move the string table back if needed. |
| | 641 | pending_shrink: bool, |
| | 642 | |
| | 643 | pub const StringIndex = enum(u32) { |
| | 644 | _, |
| | 645 | }; |
| | 646 | |
| | 647 | pub const SymbolName = union(enum) { |
| | 648 | short: []const u8, |
| | 649 | long: StringIndex, |
| | 650 | |
| | 651 | pub fn store(name: SymbolName, coff: *const Coff, field: *[8]u8) void { |
| | 652 | switch (name) { |
| | 653 | .short => |s| { |
| | 654 | @memcpy(field[0..s.len], s); |
| | 655 | @memset(field[s.len..], 0); |
| | 656 | }, |
| | 657 | .long => |l| { |
| | 658 | @memset(field[0..4], 0); |
| | 659 | std.mem.writePackedInt(u32, field[4..], 0, @intFromEnum(l), coff.targetEndian()); |
| | 660 | }, |
| | 661 | } |
| | 662 | } |
| | 663 | }; |
| | 664 | |
| | 665 | // Symbol.Index does not map 1:1 with SymbolTable.Index: |
| | 666 | // - Not all symbols need a symbol table entry |
| | 667 | // - A variable number of auxiliary entries may trail each symbol |
| | 668 | pub const Index = enum(u32) { |
| | 669 | none, |
| | 670 | _, |
| | 671 | |
| | 672 | pub fn wrap(i: u32) Index { |
| | 673 | return @enumFromInt(i + 1); |
| | 674 | } |
| | 675 | |
| | 676 | pub fn unwrap(sti: Index) ?u32 { |
| | 677 | return switch (sti) { |
| | 678 | .none => null, |
| | 679 | _ => @intFromEnum(sti) - 1, |
| | 680 | }; |
| | 681 | } |
| | 682 | }; |
| | 683 | }; |
| | 684 | |
| | 685 | pub const ExportTable = struct { |
| | 686 | ni: MappedFile.Node.Index, |
| | 687 | export_directory_table_ni: MappedFile.Node.Index, |
| | 688 | export_address_table_si: Symbol.Index, |
| | 689 | name_pointer_table_ni: MappedFile.Node.Index, |
| | 690 | ordinal_table_ni: MappedFile.Node.Index, |
| | 691 | name_table_ni: MappedFile.Node.Index, |
| | 692 | entries: std.array_hash_map.Auto(void, Entry), |
| | 693 | pending_sort: bool = false, |
| | 694 | |
| | 695 | pub const Entry = struct { |
| | 696 | si: Symbol.Index, |
| | 697 | name_index: u32, |
| | 698 | name_len: u32, |
| | 699 | export_address_table_ri: Reloc.Index, |
| | 700 | }; |
| | 701 | |
| | 702 | const Adapter = struct { |
| | 703 | coff: *Coff, |
| | 704 | |
| | 705 | pub fn eql(adapter: Adapter, lhs_key: []const u8, _: void, rhs_index: usize) bool { |
| | 706 | const coff = adapter.coff; |
| | 707 | const name_table_slice = coff.export_table.name_table_ni.slice(&coff.mf); |
| | 708 | const rhs = coff.export_table.entries.values()[rhs_index]; |
| | 709 | return std.mem.eql(u8, name_table_slice[rhs.name_index..][0..rhs.name_len], lhs_key); |
| | 710 | } |
| | 711 | |
| | 712 | pub fn hash(_: Adapter, key: []const u8) u32 { |
| | 713 | assert(std.mem.indexOfScalar(u8, key, 0) == null); |
| | 714 | return std.array_hash_map.hashString(key); |
| | 715 | } |
| | 716 | }; |
| | 717 | |
| | 718 | pub const Ordinal = enum(u16) { |
| | 719 | _, |
| | 720 | |
| | 721 | pub fn get(export_index: ExportTable.Ordinal, coff: *Coff) *Entry { |
| | 722 | return &coff.export_table.entries.values()[@intFromEnum(export_index)]; |
| | 723 | } |
| | 724 | }; |
| | 725 | }; |
| | 726 | |
| 273 | pub const ImportTable = struct { | 727 | pub const ImportTable = struct { |
| 274 | ni: MappedFile.Node.Index, | 728 | ni: MappedFile.Node.Index, |
| 275 | entries: std.array_hash_map.Auto(void, Entry), | 729 | entries: std.array_hash_map.Auto(void, Entry), |
| | 730 | iat_symbol_indices: std.array_hash_map.Auto(struct { |
| | 731 | iti: ImportTable.Index, |
| | 732 | name: String.Optional, |
| | 733 | // If name == .none this is the ordinal, otherwise the hint |
| | 734 | ordinal_hint: u16, |
| | 735 | }, u32), |
| 276 | | 736 | |
| 277 | pub const Entry = struct { | 737 | pub const Entry = struct { |
| 278 | import_lookup_table_ni: MappedFile.Node.Index, | 738 | import_lookup_table_ni: MappedFile.Node.Index, |
| 279 | import_address_table_si: Symbol.Index, | 739 | import_address_table_si: Symbol.Index, |
| 280 | import_hint_name_table_ni: MappedFile.Node.Index, | 740 | import_hint_name_table_ni: MappedFile.Node.Index, |
| | 741 | // All .iat_ptr globals that reference this table. |
| | 742 | // This is separate from `iat_symbol_indices` because multiple symbols |
| | 743 | // can reference to the same iat entry, after name demangling. |
| | 744 | import_address_table_symbols: std.ArrayList(Symbol.Index), |
| 281 | len: u32, | 745 | len: u32, |
| 282 | hint_name_len: u32, | 746 | hint_name_len: u32, |
| 283 | }; | 747 | }; |
| ... | @@ -314,13 +778,32 @@ pub const String = enum(u32) { | ... | @@ -314,13 +778,32 @@ pub const String = enum(u32) { |
| 314 | @".rdata" = 13, | 778 | @".rdata" = 13, |
| 315 | @".text" = 20, | 779 | @".text" = 20, |
| 316 | @".tls$" = 26, | 780 | @".tls$" = 26, |
| | 781 | @".edata" = 32, |
| | 782 | @".ctors" = 39, |
| | 783 | @".ctors$ZZZ" = 46, |
| | 784 | @".dtors" = 57, |
| | 785 | @".dtors$ZZZ" = 64, |
| | 786 | @".bss" = 75, |
| | 787 | @".fptable" = 80, |
| | 788 | @".tls" = 89, |
| | 789 | @".thunks" = 94, |
| 317 | _, | 790 | _, |
| 318 | | 791 | |
| 319 | pub const Optional = enum(u32) { | 792 | pub const Optional = enum(u32) { |
| 320 | @".data" = @intFromEnum(String.@".data"), | 793 | @".data" = @intFromEnum(String.@".data"), |
| | 794 | @".idata" = @intFromEnum(String.@".idata"), |
| 321 | @".rdata" = @intFromEnum(String.@".rdata"), | 795 | @".rdata" = @intFromEnum(String.@".rdata"), |
| 322 | @".text" = @intFromEnum(String.@".text"), | 796 | @".text" = @intFromEnum(String.@".text"), |
| 323 | @".tls$" = @intFromEnum(String.@".tls$"), | 797 | @".tls$" = @intFromEnum(String.@".tls$"), |
| | 798 | @".edata" = @intFromEnum(String.@".edata"), |
| | 799 | @".ctors" = @intFromEnum(String.@".ctors"), |
| | 800 | @".ctors$ZZZ" = @intFromEnum(String.@".ctors$ZZZ"), |
| | 801 | @".dtors" = @intFromEnum(String.@".dtors"), |
| | 802 | @".dtors$ZZZ" = @intFromEnum(String.@".dtors$ZZZ"), |
| | 803 | @".bss" = @intFromEnum(String.@".bss"), |
| | 804 | @".fptable" = @intFromEnum(String.@".fptable"), |
| | 805 | @".tls" = @intFromEnum(String.@".tls"), |
| | 806 | @".thunks" = @intFromEnum(String.@".thunks"), |
| 324 | none = std.math.maxInt(u32), | 807 | none = std.math.maxInt(u32), |
| 325 | _, | 808 | _, |
| 326 | | 809 | |
| ... | @@ -346,20 +829,176 @@ pub const String = enum(u32) { | ... | @@ -346,20 +829,176 @@ pub const String = enum(u32) { |
| 346 | } | 829 | } |
| 347 | }; | 830 | }; |
| 348 | | 831 | |
| 349 | pub const GlobalName = struct { name: String, lib_name: String.Optional }; | 832 | pub const Section = struct { |
| | 833 | si: Symbol.Index, |
| | 834 | relocation_table_ni: MappedFile.Node.Index, |
| | 835 | |
| | 836 | pub const RelocationIndex = enum(u16) { |
| | 837 | none, |
| | 838 | _, |
| | 839 | |
| | 840 | pub fn wrap(i: ?u16) RelocationIndex { |
| | 841 | return @enumFromInt((i orelse return .none) + 1); |
| | 842 | } |
| | 843 | |
| | 844 | pub fn unwrap(sri: RelocationIndex) ?u16 { |
| | 845 | return switch (sri) { |
| | 846 | .none => null, |
| | 847 | _ => @intFromEnum(sri) - 1, |
| | 848 | }; |
| | 849 | } |
| | 850 | |
| | 851 | pub fn entry( |
| | 852 | sri: RelocationIndex, |
| | 853 | coff: *Coff, |
| | 854 | sn: Symbol.SectionNumber, |
| | 855 | ) ?*align(2) std.coff.Relocation { |
| | 856 | if (sri == .none) return null; |
| | 857 | const table_slice = sn.section(coff).relocation_table_ni.slice(&coff.mf); |
| | 858 | return @ptrCast(@alignCast(&table_slice[@as(u32, sri.unwrap().?) * std.coff.Relocation.sizeOf()])); |
| | 859 | } |
| | 860 | }; |
| | 861 | }; |
| | 862 | |
| | 863 | pub const Global = struct { |
| | 864 | si: Symbol.Index, |
| | 865 | lib_name: String.Optional, |
| | 866 | }; |
| | 867 | |
| | 868 | pub const WeakExternalStrat = enum(u3) { |
| | 869 | none, |
| | 870 | no_library, |
| | 871 | library, |
| | 872 | alias, |
| | 873 | anti_dependency, |
| | 874 | |
| | 875 | pub fn fromFlag(flag: std.coff.WeakExternalFlag) WeakExternalStrat { |
| | 876 | return switch (flag) { |
| | 877 | .SEARCH_NOLIBRARY => .no_library, |
| | 878 | .SEARCH_LIBRARY => .library, |
| | 879 | .SEARCH_ALIAS => .alias, |
| | 880 | .ANTI_DEPENDENCY => .anti_dependency, |
| | 881 | _ => unreachable, |
| | 882 | }; |
| | 883 | } |
| | 884 | }; |
| | 885 | |
| | 886 | const SpecialSymbol = enum { |
| | 887 | entry, |
| | 888 | tls, |
| | 889 | none, |
| | 890 | }; |
| 350 | | 891 | |
| 351 | pub const Symbol = struct { | 892 | pub const Symbol = struct { |
| 352 | ni: MappedFile.Node.Index, | 893 | ni: MappedFile.Node.Index, |
| 353 | rva: u32, | 894 | rva: u32, |
| 354 | size: u32, | 895 | value: std.meta.BareUnion(Symbol.Value), |
| | 896 | extra: std.meta.BareUnion(Symbol.Extra), |
| | 897 | flags: packed struct(u16) { |
| | 898 | value_tag: ValueTag, |
| | 899 | extra_tag: ExtraTag, |
| | 900 | type: Symbol.Type, |
| | 901 | dll_storage_class: DllStorageClass, |
| | 902 | weak_external_strat: WeakExternalStrat, |
| | 903 | _: u5 = 0, |
| | 904 | }, |
| 355 | /// Relocations contained within this symbol | 905 | /// Relocations contained within this symbol |
| 356 | loc_relocs: Reloc.Index, | 906 | loc_relocs: Reloc.Index, |
| 357 | /// Relocations targeting this symbol | 907 | /// Relocations targeting this symbol |
| 358 | target_relocs: Reloc.Index, | 908 | target_relocs: Reloc.Index, |
| 359 | section_number: SectionNumber, | 909 | section_number: SectionNumber, |
| 360 | unused0: u32 = 0, | 910 | gmi: Node.GlobalMapIndex, |
| 361 | unused1: u32 = 0, | 911 | |
| 362 | unused2: u16 = 0, | 912 | pub const DllStorageClass = enum(u2) { |
| | 913 | default, |
| | 914 | dllimport, |
| | 915 | dllexport, |
| | 916 | }; |
| | 917 | |
| | 918 | pub const Type = enum(u2) { |
| | 919 | unknown, |
| | 920 | code, |
| | 921 | data, |
| | 922 | }; |
| | 923 | |
| | 924 | const ValueTag = enum(u2) { |
| | 925 | none, |
| | 926 | node_offset, |
| | 927 | weak_alias_si, |
| | 928 | weak_alias_name, |
| | 929 | }; |
| | 930 | |
| | 931 | pub const Value = union(ValueTag) { |
| | 932 | none, |
| | 933 | /// The offset of the symbol within its node. Used with symbols that |
| | 934 | /// don't create their own nodes: .input_section, .import_address_table |
| | 935 | /// Images only. |
| | 936 | node_offset: u32, |
| | 937 | /// Images: the weak alias that should replace this symbol if it is not resolved. |
| | 938 | /// Objects: he target of a weak external that hasn't been assigned an sti yet. |
| | 939 | /// Globals only. |
| | 940 | weak_alias_si: Symbol.Index, |
| | 941 | /// For weak externals that have an alias that is also an undef |
| | 942 | /// external, this is the name of the alias global that should |
| | 943 | /// be generated and resolved if this symbol is not resolved. |
| | 944 | /// Globals only, images only. |
| | 945 | weak_alias_name: String, |
| | 946 | }; |
| | 947 | |
| | 948 | const ExtraTag = enum(u2) { |
| | 949 | size, |
| | 950 | isli, |
| | 951 | next_alias_si, |
| | 952 | }; |
| | 953 | |
| | 954 | pub const Extra = union(ExtraTag) { |
| | 955 | // The size of the symbol |
| | 956 | size: u32, |
| | 957 | /// Only valid when .ni == .input_section and .value_tag == .node_offset |
| | 958 | isli: Node.InputSection.LocalIndex, |
| | 959 | /// The next symbol in the list of aliases of this symbol. |
| | 960 | next_alias_si: Symbol.Index, |
| | 961 | }; |
| | 962 | |
| | 963 | pub fn setValue(sym: *Symbol, value: Symbol.Value) void { |
| | 964 | sym.flags.value_tag = std.meta.activeTag(value); |
| | 965 | sym.value = switch (sym.flags.value_tag) { |
| | 966 | inline else => |t| @unionInit( |
| | 967 | @FieldType(Symbol, "value"), |
| | 968 | @tagName(t), |
| | 969 | @field(value, @tagName(t)), |
| | 970 | ), |
| | 971 | }; |
| | 972 | } |
| | 973 | |
| | 974 | pub fn setExtra(sym: *Symbol, extra: Symbol.Extra) void { |
| | 975 | sym.flags.extra_tag = std.meta.activeTag(extra); |
| | 976 | sym.extra = switch (sym.flags.extra_tag) { |
| | 977 | inline else => |t| @unionInit( |
| | 978 | @FieldType(Symbol, "extra"), |
| | 979 | @tagName(t), |
| | 980 | @field(extra, @tagName(t)), |
| | 981 | ), |
| | 982 | }; |
| | 983 | } |
| | 984 | |
| | 985 | pub fn nodeOffset(sym: *const Symbol, coff: *Coff) u32 { |
| | 986 | return switch (sym.flags.value_tag) { |
| | 987 | .node_offset => offset: { |
| | 988 | assert(switch (coff.getNode(sym.ni)) { |
| | 989 | // Separate nodes are not created for these entries per-symbol |
| | 990 | .input_section, .import_address_table => true, |
| | 991 | else => false, |
| | 992 | }); |
| | 993 | break :offset sym.value.node_offset; |
| | 994 | }, |
| | 995 | else => 0, |
| | 996 | }; |
| | 997 | } |
| | 998 | |
| | 999 | pub fn size(sym: *const Symbol) u32 { |
| | 1000 | return if (sym.flags.extra_tag == .size) sym.extra.size else 0; |
| | 1001 | } |
| 363 | | 1002 | |
| 364 | pub const SectionNumber = enum(i16) { | 1003 | pub const SectionNumber = enum(i16) { |
| 365 | UNDEFINED = 0, | 1004 | UNDEFINED = 0, |
| ... | @@ -371,8 +1010,20 @@ pub const Symbol = struct { | ... | @@ -371,8 +1010,20 @@ pub const Symbol = struct { |
| 371 | return @intCast(@intFromEnum(sn) - 1); | 1010 | return @intCast(@intFromEnum(sn) - 1); |
| 372 | } | 1011 | } |
| 373 | | 1012 | |
| | 1013 | fn hasIndex(sn: SectionNumber) bool { |
| | 1014 | return @intFromEnum(sn) > 0; |
| | 1015 | } |
| | 1016 | |
| 374 | pub fn symbol(sn: SectionNumber, coff: *const Coff) Symbol.Index { | 1017 | pub fn symbol(sn: SectionNumber, coff: *const Coff) Symbol.Index { |
| 375 | return coff.image_section_table.items[sn.toIndex()]; | 1018 | return sn.section(coff).si; |
| | 1019 | } |
| | 1020 | |
| | 1021 | pub fn name(sn: SectionNumber, coff: *const Coff) String { |
| | 1022 | return coff.section_table.keys()[sn.toIndex()]; |
| | 1023 | } |
| | 1024 | |
| | 1025 | pub fn section(sn: SectionNumber, coff: *const Coff) *Section { |
| | 1026 | return &coff.section_table.values()[sn.toIndex()]; |
| 376 | } | 1027 | } |
| 377 | | 1028 | |
| 378 | pub fn header(sn: SectionNumber, coff: *Coff) *std.coff.SectionHeader { | 1029 | pub fn header(sn: SectionNumber, coff: *Coff) *std.coff.SectionHeader { |
| ... | @@ -382,6 +1033,7 @@ pub const Symbol = struct { | ... | @@ -382,6 +1033,7 @@ pub const Symbol = struct { |
| 382 | | 1033 | |
| 383 | pub const Index = enum(u32) { | 1034 | pub const Index = enum(u32) { |
| 384 | null, | 1035 | null, |
| | 1036 | bss, |
| 385 | data, | 1037 | data, |
| 386 | rdata, | 1038 | rdata, |
| 387 | text, | 1039 | text, |
| ... | @@ -390,7 +1042,12 @@ pub const Symbol = struct { | ... | @@ -390,7 +1042,12 @@ pub const Symbol = struct { |
| 390 | const known_count = @typeInfo(Index).@"enum".field_names.len; | 1042 | const known_count = @typeInfo(Index).@"enum".field_names.len; |
| 391 | | 1043 | |
| 392 | pub fn get(si: Symbol.Index, coff: *Coff) *Symbol { | 1044 | pub fn get(si: Symbol.Index, coff: *Coff) *Symbol { |
| 393 | return &coff.symbol_table.items[@intFromEnum(si)]; | 1045 | return &coff.symbols.items[@intFromEnum(si)]; |
| | 1046 | } |
| | 1047 | |
| | 1048 | pub fn unwrap(si: Symbol.Index) ?Symbol.Index { |
| | 1049 | if (si == .null) return null; |
| | 1050 | return si; |
| 394 | } | 1051 | } |
| 395 | | 1052 | |
| 396 | pub fn node(si: Symbol.Index, coff: *Coff) MappedFile.Node.Index { | 1053 | pub fn node(si: Symbol.Index, coff: *Coff) MappedFile.Node.Index { |
| ... | @@ -399,37 +1056,92 @@ pub const Symbol = struct { | ... | @@ -399,37 +1056,92 @@ pub const Symbol = struct { |
| 399 | return ni; | 1056 | return ni; |
| 400 | } | 1057 | } |
| 401 | | 1058 | |
| 402 | pub fn flushMoved(si: Symbol.Index, coff: *Coff) void { | 1059 | pub fn sti(si: Symbol.Index, coff: *Coff) SymbolTable.Index { |
| 403 | const sym = si.get(coff); | 1060 | assert(!coff.isImage()); |
| 404 | sym.rva = coff.computeNodeRva(sym.ni); | 1061 | return coff.symbol_table.symbols.get(si) orelse .none; |
| 405 | si.applyLocationRelocs(coff); | 1062 | } |
| 406 | si.applyTargetRelocs(coff); | 1063 | |
| | 1064 | pub fn next(si: Symbol.Index) Symbol.Index { |
| | 1065 | return @enumFromInt(@intFromEnum(si) + 1); |
| | 1066 | } |
| | 1067 | |
| | 1068 | pub fn knownString(si: Symbol.Index) String.Optional { |
| | 1069 | return switch (si) { |
| | 1070 | .null, _ => .none, |
| | 1071 | inline else => |tag| @field(String.Optional, "." ++ @tagName(tag)), |
| | 1072 | }; |
| 407 | } | 1073 | } |
| 408 | | 1074 | |
| 409 | pub fn applyLocationRelocs(si: Symbol.Index, coff: *Coff) void { | 1075 | pub fn flushMoved(si: Symbol.Index, coff: *Coff) !void { |
| 410 | for (coff.relocs.items[@intFromEnum(si.get(coff).loc_relocs)..]) |*reloc| { | 1076 | const sym = si.get(coff); |
| 411 | if (reloc.loc != si) break; | 1077 | sym.rva = coff.computeNodeRva(sym.ni) + sym.nodeOffset(coff); |
| 412 | reloc.apply(coff); | 1078 | try si.applyLocationRelocs(coff); |
| | 1079 | try si.applyTargetRelocs(coff, .none); |
| | 1080 | |
| | 1081 | var alias_sym = sym; |
| | 1082 | while (alias_sym.flags.extra_tag == .next_alias_si) { |
| | 1083 | const alias_si = alias_sym.extra.next_alias_si; |
| | 1084 | alias_sym = alias_si.get(coff); |
| | 1085 | assert(alias_sym.ni == sym.ni); |
| | 1086 | alias_sym.rva = sym.rva; |
| | 1087 | try alias_si.applyTargetRelocs(coff, .none); |
| 413 | } | 1088 | } |
| 414 | } | 1089 | } |
| 415 | | 1090 | |
| 416 | pub fn applyTargetRelocs(si: Symbol.Index, coff: *Coff) void { | 1091 | pub fn flushSymbolTableIndex(si: Symbol.Index, coff: *Coff) void { |
| 417 | var ri = si.get(coff).target_relocs; | 1092 | const sym = si.get(coff); |
| | 1093 | const index = si.sti(coff).unwrap().?; |
| | 1094 | var ri = sym.target_relocs; |
| 418 | while (ri != .none) { | 1095 | while (ri != .none) { |
| 419 | const reloc = ri.get(coff); | 1096 | const reloc = ri.get(coff); |
| 420 | assert(reloc.target == si); | 1097 | assert(reloc.target == si); |
| 421 | reloc.apply(coff); | 1098 | if (reloc.sri.entry(coff, reloc.loc.get(coff).section_number)) |entry| |
| | 1099 | coff.targetStore(&entry.symbol_table_index, index); |
| | 1100 | ri = reloc.next; |
| | 1101 | } |
| | 1102 | } |
| | 1103 | |
| | 1104 | pub fn applyLocationRelocs(si: Symbol.Index, coff: *Coff) !void { |
| | 1105 | const sym = si.get(coff); |
| | 1106 | switch (sym.loc_relocs) { |
| | 1107 | .none => {}, |
| | 1108 | else => |loc_relocs| { |
| | 1109 | for (coff.relocs.items[@intFromEnum(loc_relocs)..]) |*reloc| { |
| | 1110 | if (reloc.loc != si) break; |
| | 1111 | if (reloc.sri.entry(coff, sym.section_number)) |entry| coff.targetStore( |
| | 1112 | &entry.virtual_address, |
| | 1113 | @intCast(coff.computeSymbolSectionOffset(sym, .image) + reloc.offset), |
| | 1114 | ); |
| | 1115 | try reloc.apply(coff); |
| | 1116 | } |
| | 1117 | }, |
| | 1118 | } |
| | 1119 | } |
| | 1120 | |
| | 1121 | pub fn applyTargetRelocs(si: Symbol.Index, coff: *Coff, end: Reloc.Index) !void { |
| | 1122 | const sym = si.get(coff); |
| | 1123 | |
| | 1124 | var ri = sym.target_relocs; |
| | 1125 | while (ri != end) { |
| | 1126 | const reloc = ri.get(coff); |
| | 1127 | assert(reloc.target == si); |
| | 1128 | try reloc.apply(coff); |
| 422 | ri = reloc.next; | 1129 | ri = reloc.next; |
| 423 | } | 1130 | } |
| 424 | } | 1131 | } |
| 425 | | 1132 | |
| 426 | pub fn deleteLocationRelocs(si: Symbol.Index, coff: *Coff) void { | 1133 | pub fn deleteLocationRelocs(si: Symbol.Index, coff: *Coff) void { |
| 427 | const sym = si.get(coff); | 1134 | const sym = si.get(coff); |
| 428 | for (coff.relocs.items[@intFromEnum(sym.loc_relocs)..]) |*reloc| { | 1135 | switch (sym.loc_relocs) { |
| 429 | if (reloc.loc != si) break; | 1136 | .none => {}, |
| 430 | reloc.delete(coff); | 1137 | else => |loc_relocs| { |
| | 1138 | for (coff.relocs.items[@intFromEnum(loc_relocs)..]) |*reloc| { |
| | 1139 | if (reloc.loc != si) break; |
| | 1140 | reloc.delete(coff); |
| | 1141 | } |
| | 1142 | sym.loc_relocs = .none; |
| | 1143 | }, |
| 431 | } | 1144 | } |
| 432 | sym.loc_relocs = .none; | | |
| 433 | } | 1145 | } |
| 434 | }; | 1146 | }; |
| 435 | | 1147 | |
| ... | @@ -439,14 +1151,24 @@ pub const Symbol = struct { | ... | @@ -439,14 +1151,24 @@ pub const Symbol = struct { |
| 439 | }; | 1151 | }; |
| 440 | | 1152 | |
| 441 | pub const Reloc = extern struct { | 1153 | pub const Reloc = extern struct { |
| 442 | type: Reloc.Type, | 1154 | offset: u64, |
| | 1155 | addend: i64, |
| | 1156 | type: Reloc.Type, |
| | 1157 | sri: Section.RelocationIndex, |
| 443 | prev: Reloc.Index, | 1158 | prev: Reloc.Index, |
| 444 | next: Reloc.Index, | 1159 | next: Reloc.Index, |
| 445 | loc: Symbol.Index, | 1160 | loc: Symbol.Index, |
| 446 | target: Symbol.Index, | 1161 | target: Symbol.Index, |
| 447 | unused: u32, | 1162 | flags: packed struct(u8) { |
| 448 | offset: u64, | 1163 | /// Indicates the addend is not known and should be recovered from the location itself. |
| 449 | addend: i64, | 1164 | /// COFF relocation tables don't encode the addend, only the location. |
| | 1165 | recover_addend: bool, |
| | 1166 | /// Set if this reloc is in the free list. |
| | 1167 | /// When set, `prev` / `next` refer to other relocs in the free list. |
| | 1168 | /// All other fields are undefined. |
| | 1169 | free: bool, |
| | 1170 | _: u6 = 0, |
| | 1171 | }, |
| 450 | | 1172 | |
| 451 | pub const Type = extern union { | 1173 | pub const Type = extern union { |
| 452 | AMD64: std.coff.IMAGE.REL.AMD64, | 1174 | AMD64: std.coff.IMAGE.REL.AMD64, |
| ... | @@ -464,135 +1186,319 @@ pub const Reloc = extern struct { | ... | @@ -464,135 +1186,319 @@ pub const Reloc = extern struct { |
| 464 | none = std.math.maxInt(u32), | 1186 | none = std.math.maxInt(u32), |
| 465 | _, | 1187 | _, |
| 466 | | 1188 | |
| 467 | pub fn get(si: Reloc.Index, coff: *Coff) *Reloc { | 1189 | pub fn wrap(i: ?u32) Reloc.Index { |
| 468 | return &coff.relocs.items[@intFromEnum(si)]; | 1190 | return @enumFromInt((i orelse return .none) + 1); |
| | 1191 | } |
| | 1192 | |
| | 1193 | pub fn get(ri: Reloc.Index, coff: *Coff) *Reloc { |
| | 1194 | return &coff.relocs.items[@intFromEnum(ri)]; |
| 469 | } | 1195 | } |
| 470 | }; | 1196 | }; |
| 471 | | 1197 | |
| 472 | pub fn apply(reloc: *const Reloc, coff: *Coff) void { | 1198 | pub fn apply(reloc: *Reloc, coff: *Coff) !void { |
| 473 | const loc_sym = reloc.loc.get(coff); | 1199 | const loc_sym = reloc.loc.get(coff); |
| 474 | switch (loc_sym.ni) { | 1200 | switch (loc_sym.ni) { |
| 475 | .none => return, | 1201 | .none => return, |
| 476 | else => |ni| if (ni.hasMoved(&coff.mf)) return, | 1202 | else => |ni| if (ni.hasMoved(&coff.mf)) return, |
| 477 | } | 1203 | } |
| 478 | const target_sym = reloc.target.get(coff); | 1204 | |
| 479 | switch (target_sym.ni) { | | |
| 480 | .none => return, | | |
| 481 | else => |ni| if (ni.hasMoved(&coff.mf)) return, | | |
| 482 | } | | |
| 483 | const loc_slice = loc_sym.ni.slice(&coff.mf)[@intCast(reloc.offset)..]; | 1205 | const loc_slice = loc_sym.ni.slice(&coff.mf)[@intCast(reloc.offset)..]; |
| 484 | const target_rva = target_sym.rva +% @as(u64, @bitCast(reloc.addend)); | | |
| 485 | const target_endian = coff.targetEndian(); | 1206 | const target_endian = coff.targetEndian(); |
| 486 | switch (coff.targetLoad(&coff.headerPtr().machine)) { | 1207 | const target_machine = coff.targetLoad(&coff.headerPtr().machine); |
| 487 | else => |machine| @panic(@tagName(machine)), | 1208 | |
| 488 | .AMD64 => switch (reloc.type.AMD64) { | 1209 | if (!coff.isImage()) { |
| 489 | else => |kind| @panic(@tagName(kind)), | 1210 | assert(!reloc.flags.recover_addend); |
| 490 | .ABSOLUTE => {}, | 1211 | switch (target_machine) { |
| 491 | .ADDR64 => std.mem.writeInt( | 1212 | else => |machine| @panic(@tagName(machine)), |
| 492 | u64, | 1213 | .AMD64 => switch (reloc.type.AMD64) { |
| 493 | loc_slice[0..8], | 1214 | else => |kind| @panic(@tagName(kind)), |
| 494 | coff.optionalHeaderField(.image_base) + target_rva, | 1215 | .ABSOLUTE => {}, |
| 495 | target_endian, | 1216 | .ADDR64 => std.mem.writeInt( |
| 496 | ), | 1217 | u64, |
| 497 | .ADDR32 => std.mem.writeInt( | 1218 | loc_slice[0..8], |
| 498 | u32, | 1219 | @intCast(reloc.addend), |
| 499 | loc_slice[0..4], | 1220 | target_endian, |
| 500 | @intCast(coff.optionalHeaderField(.image_base) + target_rva), | 1221 | ), |
| 501 | target_endian, | 1222 | .ADDR32, |
| 502 | ), | 1223 | .ADDR32NB, |
| 503 | .ADDR32NB => std.mem.writeInt( | 1224 | .SECREL, |
| 504 | u32, | 1225 | => std.mem.writeInt( |
| 505 | loc_slice[0..4], | 1226 | u32, |
| 506 | @intCast(target_rva), | 1227 | loc_slice[0..4], |
| 507 | target_endian, | 1228 | @intCast(reloc.addend), |
| 508 | ), | 1229 | target_endian, |
| 509 | .REL32 => std.mem.writeInt( | 1230 | ), |
| 510 | i32, | 1231 | .REL32, |
| 511 | loc_slice[0..4], | 1232 | .REL32_1, |
| 512 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 4)))), | 1233 | .REL32_2, |
| 513 | target_endian, | 1234 | .REL32_3, |
| 514 | ), | 1235 | .REL32_4, |
| 515 | .REL32_1 => std.mem.writeInt( | 1236 | .REL32_5, |
| 516 | i32, | 1237 | => std.mem.writeInt( |
| 517 | loc_slice[0..4], | 1238 | i32, |
| 518 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 5)))), | 1239 | loc_slice[0..4], |
| 519 | target_endian, | 1240 | @intCast(reloc.addend), |
| 520 | ), | 1241 | target_endian, |
| 521 | .REL32_2 => std.mem.writeInt( | 1242 | ), |
| 522 | i32, | 1243 | }, |
| 523 | loc_slice[0..4], | 1244 | .I386 => switch (reloc.type.I386) { |
| 524 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 6)))), | 1245 | else => |kind| @panic(@tagName(kind)), |
| 525 | target_endian, | 1246 | .ABSOLUTE => {}, |
| 526 | ), | 1247 | .DIR16, |
| 527 | .REL32_3 => std.mem.writeInt( | 1248 | => std.mem.writeInt( |
| 528 | i32, | 1249 | u16, |
| 529 | loc_slice[0..4], | 1250 | loc_slice[0..2], |
| 530 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 7)))), | 1251 | @intCast(reloc.addend), |
| 531 | target_endian, | 1252 | target_endian, |
| 532 | ), | 1253 | ), |
| 533 | .REL32_4 => std.mem.writeInt( | 1254 | .REL16, |
| 534 | i32, | 1255 | => std.mem.writeInt( |
| 535 | loc_slice[0..4], | 1256 | i16, |
| 536 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 8)))), | 1257 | loc_slice[0..2], |
| 537 | target_endian, | 1258 | @intCast(reloc.addend), |
| 538 | ), | 1259 | target_endian, |
| 539 | .REL32_5 => std.mem.writeInt( | 1260 | ), |
| 540 | i32, | 1261 | .DIR32, |
| 541 | loc_slice[0..4], | 1262 | .DIR32NB, |
| 542 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 9)))), | 1263 | .SECREL, |
| 543 | target_endian, | 1264 | => std.mem.writeInt( |
| 544 | ), | 1265 | u32, |
| 545 | .SECREL => std.mem.writeInt( | 1266 | loc_slice[0..4], |
| 546 | u32, | 1267 | @intCast(reloc.addend), |
| 547 | loc_slice[0..4], | 1268 | target_endian, |
| 548 | coff.computeNodeSectionOffset(target_sym.ni), | 1269 | ), |
| 549 | target_endian, | 1270 | .REL32, |
| 550 | ), | 1271 | => std.mem.writeInt( |
| 551 | }, | 1272 | i32, |
| 552 | .I386 => switch (reloc.type.I386) { | 1273 | loc_slice[0..4], |
| 553 | else => |kind| @panic(@tagName(kind)), | 1274 | @intCast(reloc.addend), |
| 554 | .ABSOLUTE => {}, | 1275 | target_endian, |
| 555 | .DIR16 => std.mem.writeInt( | 1276 | ), |
| 556 | u16, | 1277 | }, |
| 557 | loc_slice[0..2], | 1278 | } |
| 558 | @intCast(coff.optionalHeaderField(.image_base) + target_rva), | 1279 | |
| 559 | target_endian, | 1280 | return; |
| 560 | ), | 1281 | } else if (reloc.flags.recover_addend) { |
| 561 | .REL16 => std.mem.writeInt( | 1282 | reloc.flags.recover_addend = false; |
| 562 | i16, | 1283 | reloc.addend = switch (target_machine) { |
| 563 | loc_slice[0..2], | 1284 | else => |machine| @panic(@tagName(machine)), |
| 564 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 2)))), | 1285 | .AMD64 => switch (reloc.type.AMD64) { |
| 565 | target_endian, | 1286 | else => |kind| @panic(@tagName(kind)), |
| 566 | ), | 1287 | .ABSOLUTE => 0, |
| 567 | .DIR32 => std.mem.writeInt( | 1288 | .ADDR64 => @bitCast(std.mem.readInt( |
| 568 | u32, | 1289 | u64, |
| 569 | loc_slice[0..4], | 1290 | loc_slice[0..8], |
| 570 | @intCast(coff.optionalHeaderField(.image_base) + target_rva), | 1291 | target_endian, |
| 571 | target_endian, | 1292 | )), |
| 572 | ), | 1293 | .ADDR32, |
| 573 | .DIR32NB => std.mem.writeInt( | 1294 | .ADDR32NB, |
| 574 | u32, | 1295 | .SECREL, |
| 575 | loc_slice[0..4], | 1296 | .REL32, |
| 576 | @intCast(target_rva), | 1297 | .REL32_1, |
| 577 | target_endian, | 1298 | .REL32_2, |
| 578 | ), | 1299 | .REL32_3, |
| 579 | .REL32 => std.mem.writeInt( | 1300 | .REL32_4, |
| 580 | i32, | 1301 | .REL32_5, |
| 581 | loc_slice[0..4], | 1302 | => std.mem.readInt( |
| 582 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 4)))), | 1303 | i32, |
| 583 | target_endian, | 1304 | loc_slice[0..4], |
| 584 | ), | 1305 | target_endian, |
| 585 | .SECREL => std.mem.writeInt( | 1306 | ), |
| 586 | u32, | 1307 | }, |
| 587 | loc_slice[0..4], | 1308 | .I386 => switch (reloc.type.I386) { |
| 588 | coff.computeNodeSectionOffset(target_sym.ni), | 1309 | else => |kind| @panic(@tagName(kind)), |
| 589 | target_endian, | 1310 | .ABSOLUTE => 0, |
| 590 | ), | 1311 | .DIR16, |
| 591 | }, | 1312 | .REL16, |
| | 1313 | => std.mem.readInt( |
| | 1314 | i16, |
| | 1315 | loc_slice[0..2], |
| | 1316 | target_endian, |
| | 1317 | ), |
| | 1318 | .DIR32, |
| | 1319 | .DIR32NB, |
| | 1320 | .SECREL, |
| | 1321 | .REL32, |
| | 1322 | => std.mem.readInt( |
| | 1323 | i32, |
| | 1324 | loc_slice[0..4], |
| | 1325 | target_endian, |
| | 1326 | ), |
| | 1327 | }, |
| | 1328 | }; |
| | 1329 | } |
| | 1330 | |
| | 1331 | const target_sym = reloc.target.get(coff); |
| | 1332 | const is_abs = switch (target_sym.ni) { |
| | 1333 | .none => if (target_sym.section_number == .ABSOLUTE) true else return, |
| | 1334 | else => |ni| if (ni.hasMoved(&coff.mf)) return else false, |
| | 1335 | }; |
| | 1336 | |
| | 1337 | const target_rva = target_sym.rva +% @as(u64, @bitCast(reloc.addend)); |
| | 1338 | if (is_abs) { |
| | 1339 | switch (target_machine) { |
| | 1340 | else => |machine| @panic(@tagName(machine)), |
| | 1341 | .AMD64 => switch (reloc.type.AMD64) { |
| | 1342 | // TODO: Could wait to report these later, in reportUndefs -> reportRelocErrs, |
| | 1343 | // so that this function doesn't return an err |
| | 1344 | else => |kind| return coff.base.comp.link_diags.fail( |
| | 1345 | "absolute symbol '{s}' targeted by invalid relocation type: {t}", |
| | 1346 | .{ target_sym.gmi.name(coff).toSlice(coff), kind }, |
| | 1347 | ), |
| | 1348 | .ABSOLUTE => {}, |
| | 1349 | .ADDR64 => std.mem.writeInt( |
| | 1350 | u64, |
| | 1351 | loc_slice[0..8], |
| | 1352 | target_rva, |
| | 1353 | target_endian, |
| | 1354 | ), |
| | 1355 | .ADDR32 => std.mem.writeInt( |
| | 1356 | u32, |
| | 1357 | loc_slice[0..4], |
| | 1358 | @intCast(target_rva), |
| | 1359 | target_endian, |
| | 1360 | ), |
| | 1361 | }, |
| | 1362 | .I386 => switch (reloc.type.I386) { |
| | 1363 | else => |kind| return coff.base.comp.link_diags.fail( |
| | 1364 | "absolute symbol '{s}' targeted by invalid relocation type: {t}", |
| | 1365 | .{ target_sym.gmi.name(coff).toSlice(coff), kind }, |
| | 1366 | ), |
| | 1367 | .ABSOLUTE => {}, |
| | 1368 | .DIR16 => std.mem.writeInt( |
| | 1369 | u16, |
| | 1370 | loc_slice[0..2], |
| | 1371 | @intCast(target_rva), |
| | 1372 | target_endian, |
| | 1373 | ), |
| | 1374 | .DIR32 => std.mem.writeInt( |
| | 1375 | u32, |
| | 1376 | loc_slice[0..4], |
| | 1377 | @intCast(target_rva), |
| | 1378 | target_endian, |
| | 1379 | ), |
| | 1380 | }, |
| | 1381 | } |
| | 1382 | } else { |
| | 1383 | switch (target_machine) { |
| | 1384 | else => |machine| @panic(@tagName(machine)), |
| | 1385 | .AMD64 => switch (reloc.type.AMD64) { |
| | 1386 | else => |kind| @panic(@tagName(kind)), |
| | 1387 | .ABSOLUTE => {}, |
| | 1388 | .ADDR64 => std.mem.writeInt( |
| | 1389 | u64, |
| | 1390 | loc_slice[0..8], |
| | 1391 | coff.optionalHeaderField(.image_base) + target_rva, |
| | 1392 | target_endian, |
| | 1393 | ), |
| | 1394 | .ADDR32 => std.mem.writeInt( |
| | 1395 | u32, |
| | 1396 | loc_slice[0..4], |
| | 1397 | @intCast(coff.optionalHeaderField(.image_base) + target_rva), |
| | 1398 | target_endian, |
| | 1399 | ), |
| | 1400 | .ADDR32NB => std.mem.writeInt( |
| | 1401 | u32, |
| | 1402 | loc_slice[0..4], |
| | 1403 | @intCast(target_rva), |
| | 1404 | target_endian, |
| | 1405 | ), |
| | 1406 | .REL32 => std.mem.writeInt( |
| | 1407 | i32, |
| | 1408 | loc_slice[0..4], |
| | 1409 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 4)))), |
| | 1410 | target_endian, |
| | 1411 | ), |
| | 1412 | .REL32_1 => std.mem.writeInt( |
| | 1413 | i32, |
| | 1414 | loc_slice[0..4], |
| | 1415 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 5)))), |
| | 1416 | target_endian, |
| | 1417 | ), |
| | 1418 | .REL32_2 => std.mem.writeInt( |
| | 1419 | i32, |
| | 1420 | loc_slice[0..4], |
| | 1421 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 6)))), |
| | 1422 | target_endian, |
| | 1423 | ), |
| | 1424 | .REL32_3 => std.mem.writeInt( |
| | 1425 | i32, |
| | 1426 | loc_slice[0..4], |
| | 1427 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 7)))), |
| | 1428 | target_endian, |
| | 1429 | ), |
| | 1430 | .REL32_4 => std.mem.writeInt( |
| | 1431 | i32, |
| | 1432 | loc_slice[0..4], |
| | 1433 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 8)))), |
| | 1434 | target_endian, |
| | 1435 | ), |
| | 1436 | .REL32_5 => std.mem.writeInt( |
| | 1437 | i32, |
| | 1438 | loc_slice[0..4], |
| | 1439 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 9)))), |
| | 1440 | target_endian, |
| | 1441 | ), |
| | 1442 | .SECREL => std.mem.writeInt( |
| | 1443 | u32, |
| | 1444 | loc_slice[0..4], |
| | 1445 | @intCast(coff.computeSymbolSectionOffset(target_sym, .pseudo) + reloc.addend), |
| | 1446 | target_endian, |
| | 1447 | ), |
| | 1448 | }, |
| | 1449 | .I386 => switch (reloc.type.I386) { |
| | 1450 | else => |kind| @panic(@tagName(kind)), |
| | 1451 | .ABSOLUTE => {}, |
| | 1452 | .DIR16 => std.mem.writeInt( |
| | 1453 | u16, |
| | 1454 | loc_slice[0..2], |
| | 1455 | @intCast(coff.optionalHeaderField(.image_base) + target_rva), |
| | 1456 | target_endian, |
| | 1457 | ), |
| | 1458 | .REL16 => std.mem.writeInt( |
| | 1459 | i16, |
| | 1460 | loc_slice[0..2], |
| | 1461 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 2)))), |
| | 1462 | target_endian, |
| | 1463 | ), |
| | 1464 | .DIR32 => std.mem.writeInt( |
| | 1465 | u32, |
| | 1466 | loc_slice[0..4], |
| | 1467 | @intCast(coff.optionalHeaderField(.image_base) + target_rva), |
| | 1468 | target_endian, |
| | 1469 | ), |
| | 1470 | .DIR32NB => std.mem.writeInt( |
| | 1471 | u32, |
| | 1472 | loc_slice[0..4], |
| | 1473 | @intCast(target_rva), |
| | 1474 | target_endian, |
| | 1475 | ), |
| | 1476 | .REL32 => std.mem.writeInt( |
| | 1477 | i32, |
| | 1478 | loc_slice[0..4], |
| | 1479 | @intCast(@as(i64, @bitCast(target_rva -% (loc_sym.rva + reloc.offset + 4)))), |
| | 1480 | target_endian, |
| | 1481 | ), |
| | 1482 | .SECREL => std.mem.writeInt( |
| | 1483 | u32, |
| | 1484 | loc_slice[0..4], |
| | 1485 | @intCast(coff.computeSymbolSectionOffset(target_sym, .pseudo) + reloc.addend), |
| | 1486 | target_endian, |
| | 1487 | ), |
| | 1488 | }, |
| | 1489 | } |
| 592 | } | 1490 | } |
| 593 | } | 1491 | } |
| 594 | | 1492 | |
| 595 | pub fn delete(reloc: *Reloc, coff: *Coff) void { | 1493 | pub fn delete(reloc: *Reloc, coff: *Coff) void { |
| | 1494 | if (reloc.sri != .none) { |
| | 1495 | // TODO: Need to remove this from the COFF relocation table (maybe removeswap?) |
| | 1496 | // TODO: If this was the last reloc causing something to be in the symbol table, we should remove |
| | 1497 | // the symbol table entry (and unset sti). That will require flushSymbolTableIndex on the |
| | 1498 | // swapped symbol if we exchange indices |
| | 1499 | @panic("TODO implement symbol table reloc deletions"); |
| | 1500 | } |
| | 1501 | |
| 596 | switch (reloc.prev) { | 1502 | switch (reloc.prev) { |
| 597 | .none => { | 1503 | .none => { |
| 598 | const target = reloc.target.get(coff); | 1504 | const target = reloc.target.get(coff); |
| ... | @@ -605,7 +1511,24 @@ pub const Reloc = extern struct { | ... | @@ -605,7 +1511,24 @@ pub const Reloc = extern struct { |
| 605 | .none => {}, | 1511 | .none => {}, |
| 606 | else => |next| next.get(coff).prev = reloc.prev, | 1512 | else => |next| next.get(coff).prev = reloc.prev, |
| 607 | } | 1513 | } |
| | 1514 | |
| 608 | reloc.* = undefined; | 1515 | reloc.* = undefined; |
| | 1516 | reloc.flags = .{ |
| | 1517 | .recover_addend = false, |
| | 1518 | .free = true, |
| | 1519 | }; |
| | 1520 | |
| | 1521 | const ri: Reloc.Index = .wrap(@intCast(reloc - coff.relocs.items.ptr)); |
| | 1522 | if (coff.last_free_reloc == .none) { |
| | 1523 | assert(coff.first_free_reloc == .none); |
| | 1524 | coff.first_free_reloc = ri; |
| | 1525 | coff.last_free_reloc = ri; |
| | 1526 | } else { |
| | 1527 | coff.last_free_reloc.get(coff).next = ri; |
| | 1528 | reloc.prev = coff.last_free_reloc; |
| | 1529 | reloc.next = .none; |
| | 1530 | coff.last_free_reloc = ri; |
| | 1531 | } |
| 609 | } | 1532 | } |
| 610 | | 1533 | |
| 611 | comptime { | 1534 | comptime { |
| ... | @@ -639,14 +1562,6 @@ fn create( | ... | @@ -639,14 +1562,6 @@ fn create( |
| 639 | assert(target.ofmt == .coff); | 1562 | assert(target.ofmt == .coff); |
| 640 | if (target.cpu.arch.endian() != comptime targetEndian(undefined)) | 1563 | if (target.cpu.arch.endian() != comptime targetEndian(undefined)) |
| 641 | return error.UnsupportedCOFFArchitecture; | 1564 | return error.UnsupportedCOFFArchitecture; |
| 642 | const is_image = switch (comp.config.output_mode) { | | |
| 643 | .Exe => true, | | |
| 644 | .Lib => switch (comp.config.link_mode) { | | |
| 645 | .static => false, | | |
| 646 | .dynamic => true, | | |
| 647 | }, | | |
| 648 | .Obj => false, | | |
| 649 | }; | | |
| 650 | const machine = target.toCoffMachine(); | 1565 | const machine = target.toCoffMachine(); |
| 651 | const timestamp: u32 = 0; | 1566 | const timestamp: u32 = 0; |
| 652 | const major_subsystem_version = options.major_subsystem_version orelse 6; | 1567 | const major_subsystem_version = options.major_subsystem_version orelse 6; |
| ... | @@ -689,18 +1604,61 @@ fn create( | ... | @@ -689,18 +1604,61 @@ fn create( |
| 689 | .allow_shlib_undefined = false, | 1604 | .allow_shlib_undefined = false, |
| 690 | .stack_size = 0, | 1605 | .stack_size = 0, |
| 691 | }, | 1606 | }, |
| | 1607 | .options = options, |
| 692 | .mf = try .init(file, comp.gpa, io), | 1608 | .mf = try .init(file, comp.gpa, io), |
| 693 | .nodes = .empty, | 1609 | .nodes = .empty, |
| | 1610 | .members = .empty, |
| | 1611 | .pending_members = .empty, |
| | 1612 | .lib_string_table = .empty, |
| | 1613 | .lib_string_len = 0, |
| | 1614 | .long_names_table = .{ |
| | 1615 | .entries = .empty, |
| | 1616 | }, |
| 694 | .import_table = .{ | 1617 | .import_table = .{ |
| 695 | .ni = .none, | 1618 | .ni = .none, |
| 696 | .entries = .empty, | 1619 | .entries = .empty, |
| | 1620 | .iat_symbol_indices = .empty, |
| | 1621 | }, |
| | 1622 | .export_table = .{ |
| | 1623 | .ni = .none, |
| | 1624 | .export_directory_table_ni = .none, |
| | 1625 | .export_address_table_si = .null, |
| | 1626 | .name_pointer_table_ni = .none, |
| | 1627 | .ordinal_table_ni = .none, |
| | 1628 | .name_table_ni = .none, |
| | 1629 | .entries = .empty, |
| | 1630 | }, |
| | 1631 | .symbol_table = .{ |
| | 1632 | .ni = .none, |
| | 1633 | .strings_ni = .none, |
| | 1634 | .strings = .empty, |
| | 1635 | .symbols = .empty, |
| | 1636 | .pending_symbol_index = 0, |
| | 1637 | .pending_shrink = false, |
| 697 | }, | 1638 | }, |
| | 1639 | .inputs = .empty, |
| | 1640 | .input_archives = .empty, |
| | 1641 | .input_archive_members = .empty, |
| | 1642 | .input_archive_symbols = .empty, |
| | 1643 | .input_archive_symbol_indices = .empty, |
| | 1644 | .pending_input = null, |
| | 1645 | .pending_default_libs = .empty, |
| | 1646 | .alternate_names = .empty, |
| | 1647 | .input_objects = .empty, |
| | 1648 | .input_symbols = .empty, |
| | 1649 | .input_sections = .empty, |
| | 1650 | .input_section_pending_index = 0, |
| | 1651 | .inputs_complete = false, |
| | 1652 | .exports_complete = false, |
| | 1653 | .pending_special_symbol = .entry, |
| 698 | .strings = .empty, | 1654 | .strings = .empty, |
| 699 | .string_bytes = .empty, | 1655 | .string_bytes = .empty, |
| 700 | .image_section_table = .empty, | 1656 | .section_table = .empty, |
| 701 | .pseudo_section_table = .empty, | 1657 | .pseudo_section_table = .empty, |
| 702 | .object_section_table = .empty, | 1658 | .object_section_table = .empty, |
| 703 | .symbol_table = .empty, | 1659 | .section_merges = .empty, |
| | 1660 | .section_merge_pending_index = 0, |
| | 1661 | .symbols = .empty, |
| 704 | .globals = .empty, | 1662 | .globals = .empty, |
| 705 | .global_pending_index = 0, | 1663 | .global_pending_index = 0, |
| 706 | .navs = .empty, | 1664 | .navs = .empty, |
| ... | @@ -711,8 +1669,13 @@ fn create( | ... | @@ -711,8 +1669,13 @@ fn create( |
| 711 | }), | 1669 | }), |
| 712 | .pending_uavs = .empty, | 1670 | .pending_uavs = .empty, |
| 713 | .relocs = .empty, | 1671 | .relocs = .empty, |
| | 1672 | .first_free_reloc = .none, |
| | 1673 | .last_free_reloc = .none, |
| 714 | .const_prog_node = .none, | 1674 | .const_prog_node = .none, |
| 715 | .synth_prog_node = .none, | 1675 | .synth_prog_node = .none, |
| | 1676 | .symbol_prog_node = .none, |
| | 1677 | .member_prog_node = .none, |
| | 1678 | .input_prog_node = .none, |
| 716 | }; | 1679 | }; |
| 717 | errdefer coff.deinit(); | 1680 | errdefer coff.deinit(); |
| 718 | | 1681 | |
| ... | @@ -725,14 +1688,20 @@ fn create( | ... | @@ -725,14 +1688,20 @@ fn create( |
| 725 | } | 1688 | } |
| 726 | | 1689 | |
| 727 | try coff.initHeaders( | 1690 | try coff.initHeaders( |
| 728 | is_image, | | |
| 729 | machine, | 1691 | machine, |
| 730 | timestamp, | 1692 | timestamp, |
| 731 | major_subsystem_version, | 1693 | major_subsystem_version, |
| 732 | minor_subsystem_version, | 1694 | minor_subsystem_version, |
| 733 | magic, | 1695 | magic, |
| | 1696 | if (options.subsystem) |s| switch (s) { |
| | 1697 | .console => .WINDOWS_CUI, |
| | 1698 | .windows => .WINDOWS_GUI, |
| | 1699 | else => return error.UnsupportedCOFFSubsystem, |
| | 1700 | } else .WINDOWS_CUI, |
| 734 | section_align, | 1701 | section_align, |
| | 1702 | std.fs.path.basename(path.sub_path), |
| 735 | ); | 1703 | ); |
| | 1704 | try coff.initBuiltins(); |
| 736 | return coff; | 1705 | return coff; |
| 737 | } | 1706 | } |
| 738 | | 1707 | |
| ... | @@ -740,13 +1709,31 @@ pub fn deinit(coff: *Coff) void { | ... | @@ -740,13 +1709,31 @@ pub fn deinit(coff: *Coff) void { |
| 740 | const gpa = coff.base.comp.gpa; | 1709 | const gpa = coff.base.comp.gpa; |
| 741 | coff.mf.deinit(gpa); | 1710 | coff.mf.deinit(gpa); |
| 742 | coff.nodes.deinit(gpa); | 1711 | coff.nodes.deinit(gpa); |
| | 1712 | coff.pending_members.deinit(gpa); |
| | 1713 | coff.lib_string_table.deinit(gpa); |
| | 1714 | coff.long_names_table.entries.deinit(gpa); |
| 743 | coff.import_table.entries.deinit(gpa); | 1715 | coff.import_table.entries.deinit(gpa); |
| | 1716 | coff.import_table.iat_symbol_indices.deinit(gpa); |
| | 1717 | coff.export_table.entries.deinit(gpa); |
| | 1718 | coff.symbol_table.strings.deinit(gpa); |
| | 1719 | coff.symbol_table.symbols.deinit(gpa); |
| | 1720 | coff.inputs.deinit(gpa); |
| | 1721 | coff.input_archives.deinit(gpa); |
| | 1722 | coff.input_archive_members.deinit(gpa); |
| | 1723 | coff.input_archive_symbols.deinit(gpa); |
| | 1724 | coff.input_archive_symbol_indices.deinit(gpa); |
| | 1725 | for (coff.pending_default_libs.items) |l| gpa.free(l.path); |
| | 1726 | coff.pending_default_libs.deinit(gpa); |
| | 1727 | coff.alternate_names.deinit(gpa); |
| | 1728 | coff.input_objects.deinit(gpa); |
| | 1729 | coff.input_symbols.deinit(gpa); |
| | 1730 | coff.input_sections.deinit(gpa); |
| 744 | coff.strings.deinit(gpa); | 1731 | coff.strings.deinit(gpa); |
| 745 | coff.string_bytes.deinit(gpa); | 1732 | coff.string_bytes.deinit(gpa); |
| 746 | coff.image_section_table.deinit(gpa); | 1733 | coff.section_table.deinit(gpa); |
| 747 | coff.pseudo_section_table.deinit(gpa); | 1734 | coff.pseudo_section_table.deinit(gpa); |
| 748 | coff.object_section_table.deinit(gpa); | 1735 | coff.object_section_table.deinit(gpa); |
| 749 | coff.symbol_table.deinit(gpa); | 1736 | coff.symbols.deinit(gpa); |
| 750 | coff.globals.deinit(gpa); | 1737 | coff.globals.deinit(gpa); |
| 751 | coff.navs.deinit(gpa); | 1738 | coff.navs.deinit(gpa); |
| 752 | coff.uavs.deinit(gpa); | 1739 | coff.uavs.deinit(gpa); |
| ... | @@ -756,21 +1743,65 @@ pub fn deinit(coff: *Coff) void { | ... | @@ -756,21 +1743,65 @@ pub fn deinit(coff: *Coff) void { |
| 756 | coff.* = undefined; | 1743 | coff.* = undefined; |
| 757 | } | 1744 | } |
| 758 | | 1745 | |
| | 1746 | fn isImage(coff: *const Coff) bool { |
| | 1747 | const comp = coff.base.comp; |
| | 1748 | return switch (comp.config.output_mode) { |
| | 1749 | .Exe => true, |
| | 1750 | .Lib => switch (comp.config.link_mode) { |
| | 1751 | .static => false, |
| | 1752 | .dynamic => true, |
| | 1753 | }, |
| | 1754 | .Obj => false, |
| | 1755 | }; |
| | 1756 | } |
| | 1757 | |
| | 1758 | fn isArchive(coff: *const Coff) bool { |
| | 1759 | const comp = coff.base.comp; |
| | 1760 | return switch (comp.config.output_mode) { |
| | 1761 | .Exe => false, |
| | 1762 | .Lib => switch (comp.config.link_mode) { |
| | 1763 | .static => true, |
| | 1764 | .dynamic => false, |
| | 1765 | }, |
| | 1766 | .Obj => false, |
| | 1767 | }; |
| | 1768 | } |
| | 1769 | |
| | 1770 | fn isExe(coff: *const Coff) bool { |
| | 1771 | return coff.base.comp.config.output_mode == .Exe; |
| | 1772 | } |
| | 1773 | |
| | 1774 | fn isObj(coff: *const Coff) bool { |
| | 1775 | return coff.base.comp.config.output_mode == .Obj; |
| | 1776 | } |
| | 1777 | |
| | 1778 | fn hasCoffHeader(coff: *const Coff) bool { |
| | 1779 | return coff.base.comp.zcu != null or !coff.isArchive(); |
| | 1780 | } |
| | 1781 | |
| | 1782 | fn sectionParent(coff: *Coff) MappedFile.Node.Index { |
| | 1783 | assert(coff.hasCoffHeader()); |
| | 1784 | return if (coff.isArchive()) Node.known.zcu_member else Node.known.file; |
| | 1785 | } |
| | 1786 | |
| 759 | fn initHeaders( | 1787 | fn initHeaders( |
| 760 | coff: *Coff, | 1788 | coff: *Coff, |
| 761 | is_image: bool, | | |
| 762 | machine: std.coff.IMAGE.FILE.MACHINE, | 1789 | machine: std.coff.IMAGE.FILE.MACHINE, |
| 763 | timestamp: u32, | 1790 | timestamp: u32, |
| 764 | major_subsystem_version: u16, | 1791 | major_subsystem_version: u16, |
| 765 | minor_subsystem_version: u16, | 1792 | minor_subsystem_version: u16, |
| 766 | magic: std.coff.OptionalHeader.Magic, | 1793 | magic: std.coff.OptionalHeader.Magic, |
| | 1794 | subsystem: std.coff.Subsystem, |
| 767 | section_align: std.mem.Alignment, | 1795 | section_align: std.mem.Alignment, |
| | 1796 | file_name: []const u8, |
| 768 | ) !void { | 1797 | ) !void { |
| 769 | const comp = coff.base.comp; | 1798 | const comp = coff.base.comp; |
| 770 | const gpa = comp.gpa; | 1799 | const gpa = comp.gpa; |
| 771 | const target_endian = coff.targetEndian(); | 1800 | const target_endian = coff.targetEndian(); |
| 772 | const file_align: std.mem.Alignment = comptime .fromByteUnits(default_file_alignment); | 1801 | const file_align: std.mem.Alignment = comptime .fromByteUnits(default_file_alignment); |
| 773 | | 1802 | const is_image = coff.isImage(); |
| | 1803 | const is_archive = coff.isArchive(); |
| | 1804 | const target = &comp.root_mod.resolved_target.result; |
| 774 | const optional_header_size: u16 = if (is_image) switch (magic) { | 1805 | const optional_header_size: u16 = if (is_image) switch (magic) { |
| 775 | _ => unreachable, | 1806 | _ => unreachable, |
| 776 | inline else => |ct_magic| @sizeOf(@field(std.coff.OptionalHeader, @tagName(ct_magic))), | 1807 | inline else => |ct_magic| @sizeOf(@field(std.coff.OptionalHeader, @tagName(ct_magic))), |
| ... | @@ -780,33 +1811,120 @@ fn initHeaders( | ... | @@ -780,33 +1811,120 @@ fn initHeaders( |
| 780 | else | 1811 | else |
| 781 | 0; | 1812 | 0; |
| 782 | | 1813 | |
| 783 | const expected_nodes_len = Node.known_count + 6 + | 1814 | var expected_nodes_len: usize = Node.known_count; |
| 784 | @as(usize, @intFromBool(comp.config.any_non_single_threaded)) * 2; | 1815 | if (coff.hasCoffHeader()) { |
| | 1816 | // Sections |
| | 1817 | expected_nodes_len += 4; |
| | 1818 | |
| | 1819 | if (is_image) { |
| | 1820 | // Pseudo-sections and import / export table |
| | 1821 | expected_nodes_len += 9; |
| | 1822 | if (comp.config.link_libc and target.abi == .msvc) |
| | 1823 | expected_nodes_len += 1; |
| | 1824 | } else |
| | 1825 | // Symbol table |
| | 1826 | expected_nodes_len += 2; |
| | 1827 | |
| | 1828 | // TLS section |
| | 1829 | if (comp.config.any_non_single_threaded) { |
| | 1830 | if (!is_image) expected_nodes_len += 1; |
| | 1831 | expected_nodes_len += 1; |
| | 1832 | } |
| | 1833 | } |
| | 1834 | defer assert(coff.nodes.len == expected_nodes_len); |
| | 1835 | |
| 785 | try coff.nodes.ensureTotalCapacity(gpa, expected_nodes_len); | 1836 | try coff.nodes.ensureTotalCapacity(gpa, expected_nodes_len); |
| 786 | coff.nodes.appendAssumeCapacity(.file); | 1837 | coff.nodes.appendAssumeCapacity(.file); |
| 787 | | 1838 | |
| 788 | const header_ni = Node.known.header; | 1839 | const header_ni = Node.known.header; |
| 789 | assert(header_ni == try coff.mf.addOnlyChildNode(gpa, .root, .{ | 1840 | assert(header_ni == try coff.mf.addOnlyChildNode(gpa, Node.known.file, .{ |
| 790 | .alignment = coff.mf.flags.block_size, | 1841 | .alignment = coff.mf.flags.block_size, |
| 791 | .fixed = true, | 1842 | .fixed = true, |
| 792 | })); | 1843 | })); |
| 793 | coff.nodes.appendAssumeCapacity(.header); | 1844 | coff.nodes.appendAssumeCapacity(.header); |
| 794 | | 1845 | |
| 795 | const signature_ni = Node.known.signature; | 1846 | const signature_ni = Node.known.signature; |
| 796 | assert(signature_ni == try coff.mf.addOnlyChildNode(gpa, header_ni, .{ | 1847 | assert(signature_ni == try coff.mf.addLastChildNode(gpa, if (is_image or !is_archive) header_ni else Node.known.file, .{ |
| 797 | .size = (if (is_image) msdos_stub.len else 0) + "PE\x00\x00".len, | 1848 | .size = if (is_image) |
| | 1849 | msdos_stub.len + std.coff.pe_signature.len |
| | 1850 | else if (is_archive) |
| | 1851 | std.coff.archive_signature.len |
| | 1852 | else |
| | 1853 | 0, |
| 798 | .alignment = .@"4", | 1854 | .alignment = .@"4", |
| 799 | .fixed = true, | 1855 | .fixed = true, |
| 800 | })); | 1856 | })); |
| 801 | coff.nodes.appendAssumeCapacity(.signature); | 1857 | coff.nodes.appendAssumeCapacity(.signature); |
| 802 | { | 1858 | |
| 803 | const signature_slice = signature_ni.slice(&coff.mf); | 1859 | const signature_slice = signature_ni.slice(&coff.mf); |
| 804 | if (is_image) @memcpy(signature_slice[0..msdos_stub.len], &msdos_stub); | 1860 | if (is_image) { |
| 805 | @memcpy(signature_slice[signature_slice.len - 4 ..], "PE\x00\x00"); | 1861 | @memcpy(signature_slice[0..msdos_stub.len], &msdos_stub); |
| | 1862 | @memcpy(signature_slice[signature_slice.len - std.coff.pe_signature.len ..], std.coff.pe_signature); |
| | 1863 | } else if (is_archive) { |
| | 1864 | @memcpy(signature_slice, std.coff.archive_signature); |
| 806 | } | 1865 | } |
| 807 | | 1866 | |
| | 1867 | const opt_coff_parent_ni = if (is_archive) parent: { |
| | 1868 | const initial_member_count = Member.Index.known_count + @intFromBool(comp.zcu != null); |
| | 1869 | try coff.members.ensureTotalCapacity(gpa, initial_member_count); |
| | 1870 | |
| | 1871 | assert(Member.Index.first == try coff.addMemberAssumeCapacity(.first_linker, @sizeOf(u32))); |
| | 1872 | coff.targetStore(coff.firstLinkerMemberNumSymbolsPtr(), 0); |
| | 1873 | |
| | 1874 | assert(Member.Index.second == try coff.addMemberAssumeCapacity(.second_linker, 2 * @sizeOf(u32))); |
| | 1875 | coff.targetStore(coff.secondLinkerMemberNumMembersPtr(), 0); |
| | 1876 | coff.targetStore(coff.secondLinkerMemberNumSymbolsPtr(), 0); |
| | 1877 | |
| | 1878 | assert(Member.Index.longnames == try coff.addMemberAssumeCapacity(.longnames, 0)); |
| | 1879 | |
| | 1880 | const first_linker_member = Member.Index.first.get(coff); |
| | 1881 | const second_linker_member = Member.Index.second.get(coff); |
| | 1882 | const longnames_member = Member.Index.longnames.get(coff); |
| | 1883 | |
| | 1884 | try first_linker_member.initHeader(coff, "", timestamp); |
| | 1885 | try second_linker_member.initHeader(coff, "", timestamp); |
| | 1886 | try longnames_member.initHeader(coff, "/", timestamp); |
| | 1887 | |
| | 1888 | if (comp.zcu) |zcu| { |
| | 1889 | const zcu_mi = try coff.addMemberAssumeCapacity(.coff, @sizeOf(std.coff.Header)); |
| | 1890 | const zcu_member = zcu_mi.get(coff); |
| | 1891 | try zcu_member.initHeader(coff, zcu.main_mod.fully_qualified_name, timestamp); |
| | 1892 | |
| | 1893 | break :parent zcu_member.content_ni; |
| | 1894 | } |
| | 1895 | |
| | 1896 | // These placeholder nodes are placed before the first member - if there are |
| | 1897 | // no other members then the last linker member (longnames) needs to expand |
| | 1898 | // to fill the padding at the end of the file. |
| | 1899 | assert(Node.known.zcu_member_header == try coff.mf.addNodeAfter(gpa, Node.known.header, .{})); |
| | 1900 | assert(Node.known.zcu_member == try coff.mf.addNodeAfter(gpa, Node.known.header, .{})); |
| | 1901 | coff.nodes.appendAssumeCapacity(.placeholder); |
| | 1902 | coff.nodes.appendAssumeCapacity(.placeholder); |
| | 1903 | |
| | 1904 | break :parent null; |
| | 1905 | } else parent: { |
| | 1906 | // TODO: Not ideal to have this many placeholder nodes - use two distinct `Node.known` types? |
| | 1907 | while (true) { |
| | 1908 | const placeholder_ni = try coff.mf.addLastChildNode(gpa, Node.known.file, .{}); |
| | 1909 | coff.nodes.appendAssumeCapacity(.placeholder); |
| | 1910 | if (placeholder_ni == Node.known.zcu_member) break; |
| | 1911 | } |
| | 1912 | |
| | 1913 | break :parent Node.known.header; |
| | 1914 | }; |
| | 1915 | |
| | 1916 | const coff_parent_ni = opt_coff_parent_ni orelse { |
| | 1917 | // If we're not generating any code, no more known nodes are used |
| | 1918 | while (coff.nodes.len < Node.known_count) { |
| | 1919 | _ = try coff.mf.addNodeAfter(gpa, Node.known.header, .{}); |
| | 1920 | coff.nodes.appendAssumeCapacity(.placeholder); |
| | 1921 | } |
| | 1922 | |
| | 1923 | return; |
| | 1924 | }; |
| | 1925 | |
| 808 | const coff_header_ni = Node.known.coff_header; | 1926 | const coff_header_ni = Node.known.coff_header; |
| 809 | assert(coff_header_ni == try coff.mf.addLastChildNode(gpa, header_ni, .{ | 1927 | assert(coff_header_ni == try coff.mf.addLastChildNode(gpa, coff_parent_ni, .{ |
| 810 | .size = @sizeOf(std.coff.Header), | 1928 | .size = @sizeOf(std.coff.Header), |
| 811 | .alignment = .@"4", | 1929 | .alignment = .@"4", |
| 812 | .fixed = true, | 1930 | .fixed = true, |
| ... | @@ -834,7 +1952,7 @@ fn initHeaders( | ... | @@ -834,7 +1952,7 @@ fn initHeaders( |
| 834 | } | 1952 | } |
| 835 | | 1953 | |
| 836 | const optional_header_ni = Node.known.optional_header; | 1954 | const optional_header_ni = Node.known.optional_header; |
| 837 | assert(optional_header_ni == try coff.mf.addLastChildNode(gpa, header_ni, .{ | 1955 | assert(optional_header_ni == try coff.mf.addLastChildNode(gpa, coff_parent_ni, .{ |
| 838 | .size = optional_header_size, | 1956 | .size = optional_header_size, |
| 839 | .alignment = .@"4", | 1957 | .alignment = .@"4", |
| 840 | .fixed = true, | 1958 | .fixed = true, |
| ... | @@ -876,7 +1994,7 @@ fn initHeaders( | ... | @@ -876,7 +1994,7 @@ fn initHeaders( |
| 876 | .size_of_image = 0, | 1994 | .size_of_image = 0, |
| 877 | .size_of_headers = 0, | 1995 | .size_of_headers = 0, |
| 878 | .checksum = 0, | 1996 | .checksum = 0, |
| 879 | .subsystem = .WINDOWS_CUI, | 1997 | .subsystem = subsystem, |
| 880 | .dll_flags = .{ | 1998 | .dll_flags = .{ |
| 881 | .HIGH_ENTROPY_VA = true, | 1999 | .HIGH_ENTROPY_VA = true, |
| 882 | .DYNAMIC_BASE = true, | 2000 | .DYNAMIC_BASE = true, |
| ... | @@ -925,7 +2043,7 @@ fn initHeaders( | ... | @@ -925,7 +2043,7 @@ fn initHeaders( |
| 925 | .size_of_image = 0, | 2043 | .size_of_image = 0, |
| 926 | .size_of_headers = 0, | 2044 | .size_of_headers = 0, |
| 927 | .checksum = 0, | 2045 | .checksum = 0, |
| 928 | .subsystem = .WINDOWS_CUI, | 2046 | .subsystem = subsystem, |
| 929 | .dll_flags = .{ | 2047 | .dll_flags = .{ |
| 930 | .HIGH_ENTROPY_VA = true, | 2048 | .HIGH_ENTROPY_VA = true, |
| 931 | .DYNAMIC_BASE = true, | 2049 | .DYNAMIC_BASE = true, |
| ... | @@ -946,13 +2064,13 @@ fn initHeaders( | ... | @@ -946,13 +2064,13 @@ fn initHeaders( |
| 946 | } | 2064 | } |
| 947 | | 2065 | |
| 948 | const data_directories_ni = Node.known.data_directories; | 2066 | const data_directories_ni = Node.known.data_directories; |
| 949 | assert(data_directories_ni == try coff.mf.addLastChildNode(gpa, header_ni, .{ | 2067 | assert(data_directories_ni == try coff.mf.addLastChildNode(gpa, coff_parent_ni, .{ |
| 950 | .size = data_directories_size, | 2068 | .size = data_directories_size, |
| 951 | .alignment = .@"4", | 2069 | .alignment = .@"4", |
| 952 | .fixed = true, | 2070 | .fixed = true, |
| 953 | })); | 2071 | })); |
| 954 | coff.nodes.appendAssumeCapacity(.data_directories); | 2072 | coff.nodes.appendAssumeCapacity(.data_directories); |
| 955 | { | 2073 | if (is_image) { |
| 956 | const data_directories = coff.dataDirectorySlice(); | 2074 | const data_directories = coff.dataDirectorySlice(); |
| 957 | @memset(data_directories, .{ .virtual_address = 0, .size = 0 }); | 2075 | @memset(data_directories, .{ .virtual_address = 0, .size = 0 }); |
| 958 | if (target_endian != native_endian) std.mem.byteSwapAllFields( | 2076 | if (target_endian != native_endian) std.mem.byteSwapAllFields( |
| ... | @@ -962,7 +2080,7 @@ fn initHeaders( | ... | @@ -962,7 +2080,7 @@ fn initHeaders( |
| 962 | } | 2080 | } |
| 963 | | 2081 | |
| 964 | const section_table_ni = Node.known.section_table; | 2082 | const section_table_ni = Node.known.section_table; |
| 965 | assert(section_table_ni == try coff.mf.addLastChildNode(gpa, header_ni, .{ | 2083 | assert(section_table_ni == try coff.mf.addLastChildNode(gpa, coff_parent_ni, .{ |
| 966 | .alignment = .@"4", | 2084 | .alignment = .@"4", |
| 967 | .fixed = true, | 2085 | .fixed = true, |
| 968 | })); | 2086 | })); |
| ... | @@ -970,65 +2088,292 @@ fn initHeaders( | ... | @@ -970,65 +2088,292 @@ fn initHeaders( |
| 970 | | 2088 | |
| 971 | assert(coff.nodes.len == Node.known_count); | 2089 | assert(coff.nodes.len == Node.known_count); |
| 972 | | 2090 | |
| 973 | try coff.symbol_table.ensureTotalCapacity(gpa, Symbol.Index.known_count); | 2091 | if (!is_image) { |
| 974 | coff.symbol_table.addOneAssumeCapacity().* = .{ | 2092 | // TODO: These two nodes could be inside one movable node? |
| 975 | .ni = .none, | 2093 | coff.symbol_table.ni = try coff.mf.addLastChildNode(gpa, coff_parent_ni, .{ |
| 976 | .rva = 0, | 2094 | .alignment = .@"2", |
| 977 | .size = 0, | 2095 | .fixed = true, |
| 978 | .loc_relocs = .none, | 2096 | .moved = true, |
| 979 | .target_relocs = .none, | 2097 | }); |
| 980 | .section_number = .UNDEFINED, | 2098 | coff.nodes.appendAssumeCapacity(.symbol_table); |
| 981 | }; | 2099 | |
| 982 | assert(try coff.addSection(".data", .{ | 2100 | coff.symbol_table.strings_ni = try coff.mf.addLastChildNode(gpa, coff_parent_ni, .{ |
| | 2101 | .size = @sizeOf(u32), |
| | 2102 | .fixed = true, |
| | 2103 | .resized = true, |
| | 2104 | }); |
| | 2105 | coff.nodes.appendAssumeCapacity(.string_table); |
| | 2106 | coff.targetStore(coff.symbolTableStringLenPtr(), @sizeOf(u32)); |
| | 2107 | } |
| | 2108 | |
| | 2109 | try coff.symbols.ensureTotalCapacity(gpa, Symbol.Index.known_count); |
| | 2110 | assert(coff.addSymbolAssumeCapacity() == .null); |
| | 2111 | |
| | 2112 | // TODO: How do we tell MappedFile not to allocate physical space for .bss? |
| | 2113 | // TODO: Could have a node flag 'virtual' that can never have slice* or fileLocation called on it |
| | 2114 | // TODO: Instead of it's own section, place .bss as a pseudo-section at the end of .text in the extra space |
| | 2115 | assert(try coff.addSection(.@".bss", .{ |
| | 2116 | .CNT_UNINITIALIZED_DATA = true, |
| | 2117 | .MEM_READ = true, |
| | 2118 | .MEM_WRITE = true, |
| | 2119 | }) == .bss); |
| | 2120 | assert(try coff.addSection(.@".data", .{ |
| 983 | .CNT_INITIALIZED_DATA = true, | 2121 | .CNT_INITIALIZED_DATA = true, |
| 984 | .MEM_READ = true, | 2122 | .MEM_READ = true, |
| 985 | .MEM_WRITE = true, | 2123 | .MEM_WRITE = true, |
| 986 | }) == .data); | 2124 | }) == .data); |
| 987 | assert(try coff.addSection(".rdata", .{ | 2125 | assert(try coff.addSection(.@".rdata", .{ |
| 988 | .CNT_INITIALIZED_DATA = true, | 2126 | .CNT_INITIALIZED_DATA = true, |
| 989 | .MEM_READ = true, | 2127 | .MEM_READ = true, |
| 990 | }) == .rdata); | 2128 | }) == .rdata); |
| 991 | assert(try coff.addSection(".text", .{ | 2129 | assert(try coff.addSection(.@".text", .{ |
| 992 | .CNT_CODE = true, | 2130 | .CNT_CODE = true, |
| 993 | .MEM_EXECUTE = true, | 2131 | .MEM_EXECUTE = true, |
| 994 | .MEM_READ = true, | 2132 | .MEM_READ = true, |
| 995 | }) == .text); | 2133 | }) == .text); |
| 996 | | 2134 | |
| 997 | coff.import_table.ni = try coff.mf.addLastChildNode( | 2135 | if (is_image) { |
| 998 | gpa, | 2136 | if (comp.config.link_libc and target.abi == .msvc) { |
| 999 | (try coff.objectSectionMapIndex( | 2137 | // This section contains a function pointer table used by control flow guard: |
| 1000 | .@".idata", | 2138 | // https://learn.microsoft.com/en-us/windows/win32/secbp/control-flow-guard |
| | 2139 | // The page containing it is set to PAGE_READONLY during startup, so this can't |
| | 2140 | // be merged into .data this protection would overlap writable memory. |
| | 2141 | _ = try coff.addSection(.@".fptable", .{ |
| | 2142 | .CNT_INITIALIZED_DATA = true, |
| | 2143 | .MEM_READ = true, |
| | 2144 | .MEM_WRITE = true, |
| | 2145 | }); |
| | 2146 | } |
| | 2147 | |
| | 2148 | // TODO: Lazily initialize this instead, avoid the extra logic for this in flushMoved / flushResized |
| | 2149 | coff.import_table.ni = try coff.mf.addLastChildNode( |
| | 2150 | gpa, |
| | 2151 | (try coff.objectSectionMapIndex( |
| | 2152 | .@".idata", |
| | 2153 | coff.mf.flags.block_size, |
| | 2154 | .{ .read = true, .initialized = true }, |
| | 2155 | )).symbol(coff).node(coff), |
| | 2156 | .{ .alignment = .@"4" }, |
| | 2157 | ); |
| | 2158 | coff.nodes.appendAssumeCapacity(.import_directory_table); |
| | 2159 | |
| | 2160 | coff.export_table.ni = (try coff.pseudoSectionMapIndex( |
| | 2161 | .@".edata", |
| | 2162 | .of(std.coff.ExportDirectoryTable), |
| | 2163 | .{ .read = true, .initialized = true }, |
| | 2164 | )).symbol(coff).node(coff); |
| | 2165 | |
| | 2166 | coff.export_table.export_directory_table_ni = try coff.mf.addLastChildNode( |
| | 2167 | gpa, |
| | 2168 | coff.export_table.ni, |
| | 2169 | .{ |
| | 2170 | .size = @sizeOf(std.coff.ExportDirectoryTable) + file_name.len + 1, |
| | 2171 | .moved = true, |
| | 2172 | .fixed = true, |
| | 2173 | }, |
| | 2174 | ); |
| | 2175 | coff.nodes.appendAssumeCapacity(.export_directory_table); |
| | 2176 | |
| | 2177 | const name_index = @sizeOf(std.coff.ExportDirectoryTable); |
| | 2178 | const table_slice = coff.export_table.export_directory_table_ni.slice(&coff.mf); |
| | 2179 | @memcpy(table_slice[name_index..][0..file_name.len], file_name[0..file_name.len]); |
| | 2180 | @memset(table_slice[name_index + file_name.len ..], 0); |
| | 2181 | |
| | 2182 | const export_address_table_ni = try coff.mf.addLastChildNode(gpa, coff.export_table.ni, .{ |
| | 2183 | .alignment = .of(std.coff.ExportAddressTableEntry), |
| | 2184 | .moved = true, |
| | 2185 | }); |
| | 2186 | coff.nodes.appendAssumeCapacity(.export_address_table); |
| | 2187 | |
| | 2188 | try coff.symbols.ensureUnusedCapacity(gpa, 1); |
| | 2189 | coff.export_table.export_address_table_si = coff.addSymbolAssumeCapacity(); |
| | 2190 | |
| | 2191 | const export_address_table_sym = coff.export_table.export_address_table_si.get(coff); |
| | 2192 | export_address_table_sym.ni = export_address_table_ni; |
| | 2193 | assert(export_address_table_sym.loc_relocs == .none); |
| | 2194 | export_address_table_sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| | 2195 | export_address_table_sym.section_number = |
| | 2196 | coff.getNode(coff.export_table.ni).pseudo_section.symbol(coff).get(coff).section_number; |
| | 2197 | |
| | 2198 | coff.export_table.name_pointer_table_ni = try coff.mf.addLastChildNode(gpa, coff.export_table.ni, .{ |
| | 2199 | .alignment = .of(std.coff.ExportNamePointerTableEntry), |
| | 2200 | .moved = true, |
| | 2201 | }); |
| | 2202 | coff.nodes.appendAssumeCapacity(.export_name_pointer_table); |
| | 2203 | |
| | 2204 | coff.export_table.ordinal_table_ni = try coff.mf.addLastChildNode(gpa, coff.export_table.ni, .{ |
| | 2205 | .alignment = .of(std.coff.ExportOrdinalTableEntry), |
| | 2206 | .moved = true, |
| | 2207 | }); |
| | 2208 | coff.nodes.appendAssumeCapacity(.export_ordinal_table); |
| | 2209 | |
| | 2210 | coff.export_table.name_table_ni = try coff.mf.addLastChildNode(gpa, coff.export_table.ni, .{ |
| | 2211 | .alignment = .of(u8), |
| | 2212 | .moved = true, |
| | 2213 | }); |
| | 2214 | coff.nodes.appendAssumeCapacity(.export_name_table); |
| | 2215 | |
| | 2216 | const export_directory_table = coff.exportDirectoryTable(); |
| | 2217 | export_directory_table.* = .{ |
| | 2218 | .flags = 0, |
| | 2219 | .time_date_stamp = timestamp, |
| | 2220 | .major_version = 0, |
| | 2221 | .minor_version = 0, |
| | 2222 | .name_rva = 0, |
| | 2223 | .ordinal_base = 1, |
| | 2224 | .number_of_entries = 0, |
| | 2225 | .number_of_names = 0, |
| | 2226 | .export_address_table_rva = 0, |
| | 2227 | .name_pointer_table_rva = 0, |
| | 2228 | .ordinal_table_rva = 0, |
| | 2229 | }; |
| | 2230 | if (target_endian != native_endian) |
| | 2231 | std.mem.byteSwapAllFields(std.coff.ExportDirectoryTable, export_directory_table); |
| | 2232 | } |
| | 2233 | |
| | 2234 | if (comp.config.any_non_single_threaded) { |
| | 2235 | if (!is_image) |
| | 2236 | _ = try coff.addSection(.@".tls$", .{ |
| | 2237 | .CNT_INITIALIZED_DATA = true, |
| | 2238 | .MEM_READ = true, |
| | 2239 | .MEM_WRITE = true, |
| | 2240 | }); |
| | 2241 | |
| | 2242 | // While tls variables allocated at runtime are writable, the template itself is not. |
| | 2243 | // In images, the template is in a .tls pseudo section in .rdata. |
| | 2244 | // In objects / archives, this section is part of the above .tls$ section. The suffix |
| | 2245 | // is maintained so merging can occur with other input tls symbols when linked later. |
| | 2246 | _ = try coff.pseudoSectionMapIndex( |
| | 2247 | if (is_image) .@".tls" else .@".tls$", |
| 1001 | coff.mf.flags.block_size, | 2248 | coff.mf.flags.block_size, |
| 1002 | .{ .read = true }, | 2249 | .{ .read = true, .write = !is_image, .initialized = true }, |
| 1003 | )).symbol(coff).node(coff), | 2250 | ); |
| 1004 | .{ .alignment = .@"4", .moved = true }, | 2251 | } |
| 1005 | ); | 2252 | } |
| 1006 | coff.nodes.appendAssumeCapacity(.import_directory_table); | | |
| 1007 | | 2253 | |
| 1008 | // While tls variables allocated at runtime are writable, the template itself is not | 2254 | pub fn initBuiltins(coff: *Coff) !void { |
| 1009 | if (comp.config.any_non_single_threaded) _ = try coff.objectSectionMapIndex( | 2255 | const comp = coff.base.comp; |
| 1010 | .@".tls$", | 2256 | const gpa = comp.gpa; |
| 1011 | coff.mf.flags.block_size, | 2257 | const target = &comp.root_mod.resolved_target.result; |
| 1012 | .{ .read = true }, | 2258 | if (coff.isImage()) { |
| 1013 | ); | 2259 | const si = try coff.globalSymbol(.{ .name = "__ImageBase", .type = .data }); |
| | 2260 | const sym = si.get(coff); |
| | 2261 | sym.ni = Node.known.header; |
| | 2262 | } |
| | 2263 | |
| | 2264 | defer coff.flushSectionMerges() catch unreachable; |
| | 2265 | if (coff.isImage() and target.isMinGW() and comp.config.link_libc) { |
| | 2266 | try coff.symbols.ensureUnusedCapacity(gpa, 8); |
| | 2267 | try coff.globals.ensureUnusedCapacity(gpa, 2); |
| | 2268 | try coff.nodes.ensureUnusedCapacity(gpa, 8); |
| | 2269 | try coff.section_merges.ensureUnusedCapacity(gpa, 2); |
| | 2270 | |
| | 2271 | const lists: []const struct { global: []const u8, start: String, end: String } = &.{ |
| | 2272 | .{ .global = "__CTOR_LIST__", .start = .@".ctors", .end = .@".ctors$ZZZ" }, |
| | 2273 | .{ .global = "__DTOR_LIST__", .start = .@".dtors", .end = .@".dtors$ZZZ" }, |
| | 2274 | }; |
| | 2275 | |
| | 2276 | // We need to explicitly merge these into .rdata as in objects they can be marked |
| | 2277 | // as MEM_WRITE, and would have mismatced section flags. |
| | 2278 | try coff.section_merges.put(gpa, .@".ctors", .@".rdata"); |
| | 2279 | try coff.section_merges.put(gpa, .@".dtors", .@".rdata"); |
| | 2280 | |
| | 2281 | for (lists) |list| { |
| | 2282 | const addr_info = coff.targetAddrInfo(); |
| | 2283 | |
| | 2284 | // Any .(c|d)tor$(.*) input sections will merge in between these sections |
| | 2285 | const start_osmi = try coff.objectSectionMapIndex( |
| | 2286 | list.start, |
| | 2287 | addr_info.alignment, |
| | 2288 | .{ .read = true, .initialized = true }, |
| | 2289 | ); |
| | 2290 | const end_osmi = try coff.objectSectionMapIndex( |
| | 2291 | list.end, |
| | 2292 | addr_info.alignment, |
| | 2293 | .{ .read = true, .initialized = true }, |
| | 2294 | ); |
| | 2295 | |
| | 2296 | // Additional nodes are used here, instead of just adding the sentinel |
| | 2297 | // directly to the section data, since once input sections are added |
| | 2298 | // as children, they would overwrite that data. |
| | 2299 | const start_sym = start_osmi.symbol(coff).get(coff); |
| | 2300 | const list_len_si = try coff.globalSymbol(.{ .name = list.global, .type = .data }); |
| | 2301 | const list_len_sym = list_len_si.get(coff); |
| | 2302 | list_len_sym.setExtra(.{ .size = addr_info.size }); |
| | 2303 | list_len_sym.ni = try coff.mf.addFirstChildNode(gpa, start_sym.ni, .{ |
| | 2304 | .size = addr_info.size, |
| | 2305 | .fixed = true, |
| | 2306 | }); |
| | 2307 | coff.nodes.appendAssumeCapacity(.{ .builtin = list_len_si }); |
| | 2308 | list_len_sym.section_number = start_sym.section_number; |
| | 2309 | |
| | 2310 | const start_slice = list_len_sym.ni.slice(&coff.mf); |
| | 2311 | switch (addr_info.magic) { |
| | 2312 | _ => unreachable, |
| | 2313 | inline .PE32, .@"PE32+" => |t| { |
| | 2314 | const addr: *TargetAddr(t) = @ptrCast(@alignCast(start_slice)); |
| | 2315 | // For __CTOR_LIST__ -1 indicates that the list is null terminated. |
| | 2316 | // For __DTOR_LIST__, this value is ignored, the list is always null terminated |
| | 2317 | coff.targetStore(addr, std.math.maxInt(TargetAddr(t))); |
| | 2318 | }, |
| | 2319 | } |
| | 2320 | |
| | 2321 | const end_sym = end_osmi.symbol(coff).get(coff); |
| | 2322 | const list_end_si = coff.addSymbolAssumeCapacity(); |
| | 2323 | const list_end_sym = list_end_si.get(coff); |
| | 2324 | list_end_sym.setExtra(.{ .size = addr_info.size }); |
| | 2325 | list_end_sym.ni = try coff.mf.addFirstChildNode(gpa, end_sym.ni, .{ |
| | 2326 | .size = addr_info.size, |
| | 2327 | .fixed = true, |
| | 2328 | }); |
| | 2329 | coff.nodes.appendAssumeCapacity(.{ .builtin = list_end_si }); |
| | 2330 | list_end_sym.section_number = start_sym.section_number; |
| 1014 | | 2331 | |
| 1015 | assert(coff.nodes.len == expected_nodes_len); | 2332 | @memset(list_end_sym.ni.slice(&coff.mf), 0); |
| | 2333 | |
| | 2334 | try list_len_si.flushMoved(coff); |
| | 2335 | try list_end_si.flushMoved(coff); |
| | 2336 | } |
| | 2337 | } |
| 1016 | } | 2338 | } |
| 1017 | | 2339 | |
| 1018 | pub fn startProgress(coff: *Coff, prog_node: std.Progress.Node) void { | 2340 | pub fn startProgress(coff: *Coff, prog_node: std.Progress.Node) void { |
| 1019 | prog_node.increaseEstimatedTotalItems(3); | 2341 | prog_node.increaseEstimatedTotalItems(3); |
| 1020 | coff.const_prog_node = prog_node.start("Constants", coff.pending_uavs.count()); | 2342 | coff.const_prog_node = prog_node.start("Constants", coff.pending_uavs.count()); |
| 1021 | coff.synth_prog_node = prog_node.start("Synthetics", count: { | 2343 | coff.synth_prog_node = prog_node.start("Synthetics", count: { |
| 1022 | var count = coff.globals.count() - coff.global_pending_index; | 2344 | var count = |
| | 2345 | coff.globals.count() - coff.global_pending_index + |
| | 2346 | coff.section_merges.count() - coff.section_merge_pending_index; |
| | 2347 | |
| 1023 | for (&coff.lazy.values) |*lazy| count += lazy.map.count() - lazy.pending_index; | 2348 | for (&coff.lazy.values) |*lazy| count += lazy.map.count() - lazy.pending_index; |
| 1024 | break :count count; | 2349 | break :count count; |
| 1025 | }); | 2350 | }); |
| | 2351 | if (!isImage(coff)) { |
| | 2352 | prog_node.increaseEstimatedTotalItems(2); |
| | 2353 | coff.symbol_prog_node = prog_node.start( |
| | 2354 | "Symbols", |
| | 2355 | coff.symbol_table.symbols.count() - coff.symbol_table.pending_symbol_index, |
| | 2356 | ); |
| | 2357 | coff.member_prog_node = prog_node.start("Members", coff.pending_members.count()); |
| | 2358 | } |
| | 2359 | coff.input_prog_node = prog_node.start( |
| | 2360 | "Inputs", |
| | 2361 | coff.input_sections.items.len - coff.input_section_pending_index, |
| | 2362 | ); |
| 1026 | coff.mf.update_prog_node = prog_node.start("Relocations", coff.mf.updates.items.len); | 2363 | coff.mf.update_prog_node = prog_node.start("Relocations", coff.mf.updates.items.len); |
| 1027 | } | 2364 | } |
| 1028 | | 2365 | |
| 1029 | pub fn endProgress(coff: *Coff) void { | 2366 | pub fn endProgress(coff: *Coff) void { |
| 1030 | coff.mf.update_prog_node.end(); | 2367 | coff.mf.update_prog_node.end(); |
| 1031 | coff.mf.update_prog_node = .none; | 2368 | coff.mf.update_prog_node = .none; |
| | 2369 | coff.input_prog_node.end(); |
| | 2370 | coff.input_prog_node = .none; |
| | 2371 | if (!coff.isImage()) { |
| | 2372 | coff.member_prog_node.end(); |
| | 2373 | coff.member_prog_node = .none; |
| | 2374 | coff.symbol_prog_node.end(); |
| | 2375 | coff.symbol_prog_node = .none; |
| | 2376 | } |
| 1032 | coff.synth_prog_node.end(); | 2377 | coff.synth_prog_node.end(); |
| 1033 | coff.synth_prog_node = .none; | 2378 | coff.synth_prog_node = .none; |
| 1034 | coff.const_prog_node.end(); | 2379 | coff.const_prog_node.end(); |
| ... | @@ -1044,10 +2389,20 @@ fn computeNodeRva(coff: *Coff, ni: MappedFile.Node.Index) u32 { | ... | @@ -1044,10 +2389,20 @@ fn computeNodeRva(coff: *Coff, ni: MappedFile.Node.Index) u32 { |
| 1044 | .file, | 2389 | .file, |
| 1045 | .header, | 2390 | .header, |
| 1046 | .signature, | 2391 | .signature, |
| | 2392 | .archive_member_header, |
| | 2393 | .archive_member, |
| 1047 | .coff_header, | 2394 | .coff_header, |
| 1048 | .optional_header, | 2395 | .optional_header, |
| 1049 | .data_directories, | 2396 | .data_directories, |
| 1050 | .section_table, | 2397 | .section_table, |
| | 2398 | .export_name_table, |
| | 2399 | .placeholder, |
| | 2400 | .symbol_table, |
| | 2401 | .string_table, |
| | 2402 | .relocation_table, |
| | 2403 | .relocation_table_entry, |
| | 2404 | .input_section, |
| | 2405 | .builtin, |
| 1051 | => unreachable, | 2406 | => unreachable, |
| 1052 | .image_section => |si| si, | 2407 | .image_section => |si| si, |
| 1053 | .import_directory_table => break :parent_rva coff.targetLoad( | 2408 | .import_directory_table => break :parent_rva coff.targetLoad( |
| ... | @@ -1062,9 +2417,21 @@ fn computeNodeRva(coff: *Coff, ni: MappedFile.Node.Index) u32 { | ... | @@ -1062,9 +2417,21 @@ fn computeNodeRva(coff: *Coff, ni: MappedFile.Node.Index) u32 { |
| 1062 | .import_hint_name_table => |import_index| break :parent_rva coff.targetLoad( | 2417 | .import_hint_name_table => |import_index| break :parent_rva coff.targetLoad( |
| 1063 | &coff.importDirectoryEntryPtr(import_index).name_rva, | 2418 | &coff.importDirectoryEntryPtr(import_index).name_rva, |
| 1064 | ), | 2419 | ), |
| | 2420 | .export_directory_table => break :parent_rva coff.targetLoad( |
| | 2421 | &coff.dataDirectoryPtr(.EXPORT).virtual_address, |
| | 2422 | ), |
| | 2423 | .export_address_table => break :parent_rva coff.targetLoad( |
| | 2424 | &coff.exportDirectoryTable().export_address_table_rva, |
| | 2425 | ), |
| | 2426 | .export_name_pointer_table => break :parent_rva coff.targetLoad( |
| | 2427 | &coff.exportDirectoryTable().name_pointer_table_rva, |
| | 2428 | ), |
| | 2429 | .export_ordinal_table => break :parent_rva coff.targetLoad( |
| | 2430 | &coff.exportDirectoryTable().ordinal_table_rva, |
| | 2431 | ), |
| 1065 | inline .pseudo_section, | 2432 | inline .pseudo_section, |
| 1066 | .object_section, | 2433 | .object_section, |
| 1067 | .global, | 2434 | .import_thunk, |
| 1068 | .nav, | 2435 | .nav, |
| 1069 | .uav, | 2436 | .uav, |
| 1070 | .lazy_code, | 2437 | .lazy_code, |
| ... | @@ -1076,24 +2443,55 @@ fn computeNodeRva(coff: *Coff, ni: MappedFile.Node.Index) u32 { | ... | @@ -1076,24 +2443,55 @@ fn computeNodeRva(coff: *Coff, ni: MappedFile.Node.Index) u32 { |
| 1076 | const offset, _ = ni.location(&coff.mf).resolve(&coff.mf); | 2443 | const offset, _ = ni.location(&coff.mf).resolve(&coff.mf); |
| 1077 | return @intCast(parent_rva + offset); | 2444 | return @intCast(parent_rva + offset); |
| 1078 | } | 2445 | } |
| 1079 | fn computeNodeSectionOffset(coff: *Coff, ni: MappedFile.Node.Index) u32 { | 2446 | |
| 1080 | var section_offset: u32 = 0; | 2447 | fn computeSymbolSectionOffset( |
| 1081 | var parent_ni = ni; | 2448 | coff: *Coff, |
| | 2449 | sym: *const Symbol, |
| | 2450 | relative_to: enum { image, pseudo }, |
| | 2451 | ) u32 { |
| | 2452 | var section_offset: u32 = sym.nodeOffset(coff); |
| | 2453 | var parent_ni = sym.ni; |
| 1082 | while (true) { | 2454 | while (true) { |
| 1083 | const offset, _ = parent_ni.location(&coff.mf).resolve(&coff.mf); | 2455 | const offset, _ = parent_ni.location(&coff.mf).resolve(&coff.mf); |
| 1084 | section_offset += @intCast(offset); | 2456 | section_offset += @intCast(offset); |
| 1085 | parent_ni = parent_ni.parent(&coff.mf); | 2457 | parent_ni = parent_ni.parent(&coff.mf); |
| 1086 | switch (coff.getNode(parent_ni)) { | 2458 | switch (coff.getNode(parent_ni)) { |
| 1087 | else => unreachable, | 2459 | else => unreachable, |
| 1088 | .image_section, .pseudo_section => return section_offset, | 2460 | .image_section => break, |
| 1089 | .object_section => {}, | 2461 | .pseudo_section => if (relative_to == .pseudo) break, |
| | 2462 | .object_section, |
| | 2463 | => {}, |
| 1090 | } | 2464 | } |
| 1091 | } | 2465 | } |
| | 2466 | |
| | 2467 | return section_offset; |
| 1092 | } | 2468 | } |
| 1093 | | 2469 | |
| 1094 | pub inline fn targetEndian(_: *const Coff) std.lang.Endian { | 2470 | pub inline fn targetEndian(_: *const Coff) std.lang.Endian { |
| 1095 | return .little; | 2471 | return .little; |
| 1096 | } | 2472 | } |
| | 2473 | |
| | 2474 | fn targetAddrInfo(coff: *Coff) struct { |
| | 2475 | size: u8, |
| | 2476 | alignment: std.mem.Alignment, |
| | 2477 | magic: std.coff.OptionalHeader.Magic, |
| | 2478 | } { |
| | 2479 | const magic = coff.targetLoad(&coff.optionalHeaderStandardPtr().magic); |
| | 2480 | switch (magic) { |
| | 2481 | _ => unreachable, |
| | 2482 | .PE32 => return .{ .size = 4, .alignment = .@"4", .magic = magic }, |
| | 2483 | .@"PE32+" => return .{ .size = 8, .alignment = .@"8", .magic = magic }, |
| | 2484 | } |
| | 2485 | } |
| | 2486 | |
| | 2487 | fn TargetAddr(comptime magic: std.coff.OptionalHeader.Magic) type { |
| | 2488 | return switch (magic) { |
| | 2489 | _ => comptime unreachable, |
| | 2490 | .PE32 => u32, |
| | 2491 | .@"PE32+" => u64, |
| | 2492 | }; |
| | 2493 | } |
| | 2494 | |
| 1097 | fn targetLoad(coff: *const Coff, ptr: anytype) @typeInfo(@TypeOf(ptr)).pointer.child { | 2495 | fn targetLoad(coff: *const Coff, ptr: anytype) @typeInfo(@TypeOf(ptr)).pointer.child { |
| 1098 | const Child = @typeInfo(@TypeOf(ptr)).pointer.child; | 2496 | const Child = @typeInfo(@TypeOf(ptr)).pointer.child; |
| 1099 | return switch (@typeInfo(Child)) { | 2497 | return switch (@typeInfo(Child)) { |
| ... | @@ -1122,9 +2520,55 @@ fn targetStore(coff: *const Coff, ptr: anytype, val: @typeInfo(@TypeOf(ptr)).poi | ... | @@ -1122,9 +2520,55 @@ fn targetStore(coff: *const Coff, ptr: anytype, val: @typeInfo(@TypeOf(ptr)).poi |
| 1122 | } | 2520 | } |
| 1123 | | 2521 | |
| 1124 | pub fn headerPtr(coff: *Coff) *std.coff.Header { | 2522 | pub fn headerPtr(coff: *Coff) *std.coff.Header { |
| | 2523 | assert(coff.hasCoffHeader()); |
| 1125 | return @ptrCast(@alignCast(Node.known.coff_header.slice(&coff.mf))); | 2524 | return @ptrCast(@alignCast(Node.known.coff_header.slice(&coff.mf))); |
| 1126 | } | 2525 | } |
| 1127 | | 2526 | |
| | 2527 | pub fn firstLinkerMemberNumSymbolsPtr(coff: *Coff) *u32 { |
| | 2528 | assert(coff.isArchive()); |
| | 2529 | return @ptrCast(@alignCast(Node.known.first_linker_member.slice(&coff.mf))); |
| | 2530 | } |
| | 2531 | |
| | 2532 | pub fn firstLinkerMemberOffsetsSlice(coff: *Coff) []u32 { |
| | 2533 | const len = std.mem.toNative(u32, coff.firstLinkerMemberNumSymbolsPtr().*, .big); |
| | 2534 | return @ptrCast(@alignCast(Node.known.first_linker_member.slice(&coff.mf)[@sizeOf(u32)..][0 .. len * @sizeOf(u32)])); |
| | 2535 | } |
| | 2536 | |
| | 2537 | pub fn secondLinkerMemberNumMembersPtr(coff: *Coff) *align(2) u32 { |
| | 2538 | assert(coff.isArchive()); |
| | 2539 | return @ptrCast(@alignCast(Node.known.second_linker_member.slice(&coff.mf))); |
| | 2540 | } |
| | 2541 | |
| | 2542 | pub fn secondLinkerMemberOffsetsSlice(coff: *Coff) []align(2) u32 { |
| | 2543 | const num_members = coff.targetLoad(coff.secondLinkerMemberNumMembersPtr()); |
| | 2544 | return @ptrCast(@alignCast( |
| | 2545 | Node.known.second_linker_member.slice(&coff.mf)[@sizeOf(u32)..][0 .. num_members * @sizeOf(u32)], |
| | 2546 | )); |
| | 2547 | } |
| | 2548 | |
| | 2549 | pub fn secondLinkerMemberNumSymbolsPtr(coff: *Coff) *align(2) u32 { |
| | 2550 | const num_members = coff.targetLoad(coff.secondLinkerMemberNumMembersPtr()); |
| | 2551 | return @ptrCast(@alignCast( |
| | 2552 | Node.known.second_linker_member.slice(&coff.mf)[(1 + num_members) * @sizeOf(u32) ..], |
| | 2553 | )); |
| | 2554 | } |
| | 2555 | |
| | 2556 | pub fn secondLinkerMemberIndicesSlice(coff: *Coff) []u16 { |
| | 2557 | const num_members = coff.targetLoad(coff.secondLinkerMemberNumMembersPtr()); |
| | 2558 | const num_symbols = coff.targetLoad(coff.secondLinkerMemberNumSymbolsPtr()); |
| | 2559 | return @ptrCast(@alignCast( |
| | 2560 | Node.known.second_linker_member.slice(&coff.mf)[(2 + num_members) * @sizeOf(u32) ..][0 .. num_symbols * @sizeOf(u16)], |
| | 2561 | )); |
| | 2562 | } |
| | 2563 | |
| | 2564 | pub fn secondLinkerMemberStringsSlice(coff: *Coff) []u8 { |
| | 2565 | const num_members = coff.targetLoad(coff.secondLinkerMemberNumMembersPtr()); |
| | 2566 | const num_symbols = coff.targetLoad(coff.secondLinkerMemberNumSymbolsPtr()); |
| | 2567 | return @ptrCast(@alignCast( |
| | 2568 | Node.known.second_linker_member.slice(&coff.mf)[(2 + num_members) * @sizeOf(u32) + num_symbols * @sizeOf(u16) ..], |
| | 2569 | )); |
| | 2570 | } |
| | 2571 | |
| 1128 | pub fn optionalHeaderStandardPtr(coff: *Coff) *std.coff.OptionalHeader { | 2572 | pub fn optionalHeaderStandardPtr(coff: *Coff) *std.coff.OptionalHeader { |
| 1129 | return @ptrCast(@alignCast( | 2573 | return @ptrCast(@alignCast( |
| 1130 | Node.known.optional_header.slice(&coff.mf)[0..@sizeOf(std.coff.OptionalHeader)], | 2574 | Node.known.optional_header.slice(&coff.mf)[0..@sizeOf(std.coff.OptionalHeader)], |
| ... | @@ -1136,6 +2580,7 @@ pub const OptionalHeaderPtr = union(std.coff.OptionalHeader.Magic) { | ... | @@ -1136,6 +2580,7 @@ pub const OptionalHeaderPtr = union(std.coff.OptionalHeader.Magic) { |
| 1136 | @"PE32+": *std.coff.OptionalHeader.@"PE32+", | 2580 | @"PE32+": *std.coff.OptionalHeader.@"PE32+", |
| 1137 | }; | 2581 | }; |
| 1138 | pub fn optionalHeaderPtr(coff: *Coff) OptionalHeaderPtr { | 2582 | pub fn optionalHeaderPtr(coff: *Coff) OptionalHeaderPtr { |
| | 2583 | assert(coff.isImage()); |
| 1139 | const slice = Node.known.optional_header.slice(&coff.mf); | 2584 | const slice = Node.known.optional_header.slice(&coff.mf); |
| 1140 | return switch (coff.targetLoad(&coff.optionalHeaderStandardPtr().magic)) { | 2585 | return switch (coff.targetLoad(&coff.optionalHeaderStandardPtr().magic)) { |
| 1141 | _ => unreachable, | 2586 | _ => unreachable, |
| ... | @@ -1150,6 +2595,7 @@ pub fn optionalHeaderField( | ... | @@ -1150,6 +2595,7 @@ pub fn optionalHeaderField( |
| 1150 | coff: *Coff, | 2595 | coff: *Coff, |
| 1151 | comptime field: std.meta.FieldEnum(std.coff.OptionalHeader.@"PE32+"), | 2596 | comptime field: std.meta.FieldEnum(std.coff.OptionalHeader.@"PE32+"), |
| 1152 | ) @FieldType(std.coff.OptionalHeader.@"PE32+", @tagName(field)) { | 2597 | ) @FieldType(std.coff.OptionalHeader.@"PE32+", @tagName(field)) { |
| | 2598 | assert(coff.isImage()); |
| 1153 | return switch (coff.optionalHeaderPtr()) { | 2599 | return switch (coff.optionalHeaderPtr()) { |
| 1154 | inline else => |optional_header| coff.targetLoad(&@field(optional_header, @tagName(field))), | 2600 | inline else => |optional_header| coff.targetLoad(&@field(optional_header, @tagName(field))), |
| 1155 | }; | 2601 | }; |
| ... | @@ -1158,6 +2604,7 @@ pub fn optionalHeaderField( | ... | @@ -1158,6 +2604,7 @@ pub fn optionalHeaderField( |
| 1158 | pub fn dataDirectorySlice( | 2604 | pub fn dataDirectorySlice( |
| 1159 | coff: *Coff, | 2605 | coff: *Coff, |
| 1160 | ) *[std.coff.IMAGE.DIRECTORY_ENTRY.len]std.coff.ImageDataDirectory { | 2606 | ) *[std.coff.IMAGE.DIRECTORY_ENTRY.len]std.coff.ImageDataDirectory { |
| | 2607 | assert(coff.isImage()); |
| 1161 | return @ptrCast(@alignCast(Node.known.data_directories.slice(&coff.mf))); | 2608 | return @ptrCast(@alignCast(Node.known.data_directories.slice(&coff.mf))); |
| 1162 | } | 2609 | } |
| 1163 | pub fn dataDirectoryPtr( | 2610 | pub fn dataDirectoryPtr( |
| ... | @@ -1168,10 +2615,48 @@ pub fn dataDirectoryPtr( | ... | @@ -1168,10 +2615,48 @@ pub fn dataDirectoryPtr( |
| 1168 | } | 2615 | } |
| 1169 | | 2616 | |
| 1170 | pub fn sectionTableSlice(coff: *Coff) []std.coff.SectionHeader { | 2617 | pub fn sectionTableSlice(coff: *Coff) []std.coff.SectionHeader { |
| 1171 | return @ptrCast(@alignCast(Node.known.section_table.slice(&coff.mf))); | 2618 | return @ptrCast(@alignCast( |
| | 2619 | Node.known.section_table.slice(&coff.mf)[0 .. coff.section_table.count() * @sizeOf(std.coff.SectionHeader)], |
| | 2620 | )); |
| | 2621 | } |
| | 2622 | |
| | 2623 | pub fn symbolTableEntryStoragePtr(coff: *Coff, index: u32) *[std.coff.Symbol.sizeOf()]u8 { |
| | 2624 | assert(!coff.isImage()); |
| | 2625 | const offset = index * std.coff.Symbol.sizeOf(); |
| | 2626 | return @ptrCast(@alignCast(coff.symbol_table.ni.slice(&coff.mf)[offset..][0..std.coff.Symbol.sizeOf()])); |
| | 2627 | } |
| | 2628 | |
| | 2629 | pub fn symbolTableEntryPtr(coff: *Coff, sti: SymbolTable.Index) ?*align(2) std.coff.Symbol { |
| | 2630 | if (sti.unwrap()) |index| |
| | 2631 | return @ptrCast(@alignCast(symbolTableEntryStoragePtr(coff, index))) |
| | 2632 | else |
| | 2633 | return null; |
| | 2634 | } |
| | 2635 | |
| | 2636 | pub fn symbolTableSectionAuxEntryPtr(coff: *Coff, sti: SymbolTable.Index) ?*align(2) std.coff.SectionDefinition { |
| | 2637 | if (symbolTableEntryPtr(coff, sti)) |entry| { |
| | 2638 | assert(entry.storage_class == .STATIC and entry.number_of_aux_symbols == 1); |
| | 2639 | return @ptrCast(@alignCast(symbolTableEntryStoragePtr(coff, sti.unwrap().? + 1))); |
| | 2640 | } else { |
| | 2641 | return null; |
| | 2642 | } |
| | 2643 | } |
| | 2644 | |
| | 2645 | pub fn symbolTableWeakExternalAuxEntryPtr(coff: *Coff, sti: SymbolTable.Index) ?*align(2) std.coff.WeakExternalDefinition { |
| | 2646 | if (symbolTableEntryPtr(coff, sti)) |entry| { |
| | 2647 | assert(entry.storage_class == .WEAK_EXTERNAL and entry.number_of_aux_symbols == 1); |
| | 2648 | return @ptrCast(@alignCast(symbolTableEntryStoragePtr(coff, sti.unwrap().? + 1))); |
| | 2649 | } else { |
| | 2650 | return null; |
| | 2651 | } |
| | 2652 | } |
| | 2653 | |
| | 2654 | pub fn symbolTableStringLenPtr(coff: *Coff) *align(1) u32 { |
| | 2655 | return @ptrCast(@alignCast(coff.symbol_table.strings_ni.slice(&coff.mf)[0..@sizeOf(u32)])); |
| 1172 | } | 2656 | } |
| 1173 | | 2657 | |
| 1174 | pub fn importDirectoryTableSlice(coff: *Coff) []std.coff.ImportDirectoryEntry { | 2658 | pub fn importDirectoryTableSlice(coff: *Coff) []std.coff.ImportDirectoryEntry { |
| | 2659 | assert(coff.isImage()); |
| 1175 | return @ptrCast(@alignCast(coff.import_table.ni.slice(&coff.mf))); | 2660 | return @ptrCast(@alignCast(coff.import_table.ni.slice(&coff.mf))); |
| 1176 | } | 2661 | } |
| 1177 | pub fn importDirectoryEntryPtr( | 2662 | pub fn importDirectoryEntryPtr( |
| ... | @@ -1181,16 +2666,40 @@ pub fn importDirectoryEntryPtr( | ... | @@ -1181,16 +2666,40 @@ pub fn importDirectoryEntryPtr( |
| 1181 | return &coff.importDirectoryTableSlice()[@intFromEnum(import_index)]; | 2666 | return &coff.importDirectoryTableSlice()[@intFromEnum(import_index)]; |
| 1182 | } | 2667 | } |
| 1183 | | 2668 | |
| | 2669 | pub fn exportDirectoryTable(coff: *Coff) *std.coff.ExportDirectoryTable { |
| | 2670 | return @ptrCast(@alignCast(coff.export_table.export_directory_table_ni.slice(&coff.mf))); |
| | 2671 | } |
| | 2672 | |
| | 2673 | pub fn exportNamePointerTableSlice(coff: *Coff) []std.coff.ExportNamePointerTableEntry { |
| | 2674 | const debug = coff.export_table.name_pointer_table_ni.slice(&coff.mf); |
| | 2675 | _ = debug; |
| | 2676 | |
| | 2677 | return @ptrCast(@alignCast(coff.export_table.name_pointer_table_ni.slice(&coff.mf))); |
| | 2678 | } |
| | 2679 | |
| | 2680 | pub fn exportOrdinalTableSlice(coff: *Coff) []std.coff.ExportOrdinalTableEntry { |
| | 2681 | return @ptrCast(@alignCast(coff.export_table.ordinal_table_ni.slice(&coff.mf))); |
| | 2682 | } |
| | 2683 | |
| 1184 | fn addSymbolAssumeCapacity(coff: *Coff) Symbol.Index { | 2684 | fn addSymbolAssumeCapacity(coff: *Coff) Symbol.Index { |
| 1185 | defer coff.symbol_table.addOneAssumeCapacity().* = .{ | 2685 | defer coff.symbols.addOneAssumeCapacity().* = .{ |
| 1186 | .ni = .none, | 2686 | .ni = .none, |
| 1187 | .rva = 0, | 2687 | .rva = 0, |
| 1188 | .size = 0, | 2688 | .value = .{ .none = {} }, |
| | 2689 | .extra = .{ .size = 0 }, |
| | 2690 | .flags = .{ |
| | 2691 | .value_tag = .none, |
| | 2692 | .extra_tag = .size, |
| | 2693 | .type = .unknown, |
| | 2694 | .dll_storage_class = .default, |
| | 2695 | .weak_external_strat = .none, |
| | 2696 | }, |
| 1189 | .loc_relocs = .none, | 2697 | .loc_relocs = .none, |
| 1190 | .target_relocs = .none, | 2698 | .target_relocs = .none, |
| 1191 | .section_number = .UNDEFINED, | 2699 | .section_number = .UNDEFINED, |
| | 2700 | .gmi = .none, |
| 1192 | }; | 2701 | }; |
| 1193 | return @enumFromInt(coff.symbol_table.items.len); | 2702 | return @enumFromInt(coff.symbols.items.len); |
| 1194 | } | 2703 | } |
| 1195 | | 2704 | |
| 1196 | fn initSymbolAssumeCapacity(coff: *Coff) !Symbol.Index { | 2705 | fn initSymbolAssumeCapacity(coff: *Coff) !Symbol.Index { |
| ... | @@ -1205,12 +2714,55 @@ fn getOrPutString(coff: *Coff, string: []const u8) !String { | ... | @@ -1205,12 +2714,55 @@ fn getOrPutString(coff: *Coff, string: []const u8) !String { |
| 1205 | fn getOrPutOptionalString(coff: *Coff, string: ?[]const u8) !String.Optional { | 2714 | fn getOrPutOptionalString(coff: *Coff, string: ?[]const u8) !String.Optional { |
| 1206 | return (try coff.getOrPutString(string orelse return .none)).toOptional(); | 2715 | return (try coff.getOrPutString(string orelse return .none)).toOptional(); |
| 1207 | } | 2716 | } |
| | 2717 | fn getString(coff: *Coff, string: []const u8) String.Optional { |
| | 2718 | if (coff.strings.getKeyAdapted( |
| | 2719 | string, |
| | 2720 | std.hash_map.StringIndexAdapter{ .bytes = &coff.string_bytes }, |
| | 2721 | )) |key| |
| | 2722 | return @as(String, @enumFromInt(key)).toOptional() |
| | 2723 | else |
| | 2724 | return .none; |
| | 2725 | } |
| | 2726 | |
| | 2727 | /// If the name does not fit in the symbol header, adds it to the symbol table string table. |
| | 2728 | /// If the caller knows this name already has a String associated with it, they can avoid |
| | 2729 | /// a redundant call to `getOrPutString` by specifying `opt_string`. |
| | 2730 | /// The lifetime of the return value matches that of `name`. |
| | 2731 | fn getOrPutSymbolName(coff: *Coff, name: []const u8, opt_string: ?String) !SymbolTable.SymbolName { |
| | 2732 | assert(!coff.isImage()); |
| | 2733 | const gpa = coff.base.comp.gpa; |
| | 2734 | |
| | 2735 | return if (name.len > header_name_max_len) name: { |
| | 2736 | const string = opt_string orelse try coff.getOrPutString(name); |
| | 2737 | const string_gop = try coff.symbol_table.strings.getOrPut(gpa, string); |
| | 2738 | if (!string_gop.found_existing) { |
| | 2739 | const string_index = coff.symbol_table.strings_ni.location(&coff.mf).resolve(&coff.mf)[1]; |
| | 2740 | string_gop.value_ptr.* = @enumFromInt(string_index); |
| | 2741 | |
| | 2742 | try coff.symbol_table.strings_ni.resize(&coff.mf, gpa, string_index + name.len + 1); |
| | 2743 | const slice = coff.symbol_table.strings_ni.slice(&coff.mf); |
| | 2744 | @memcpy(slice[@intCast(string_index)..][0..name.len], name); |
| | 2745 | slice[@intCast(string_index + name.len)] = 0; |
| | 2746 | } |
| | 2747 | |
| | 2748 | break :name .{ .long = string_gop.value_ptr.* }; |
| | 2749 | } else .{ .short = name }; |
| | 2750 | } |
| 1208 | | 2751 | |
| | 2752 | /// `len` does not include null terminators |
| 1209 | fn ensureUnusedStringCapacity(coff: *Coff, len: usize) !void { | 2753 | fn ensureUnusedStringCapacity(coff: *Coff, len: usize) !void { |
| 1210 | const gpa = coff.base.comp.gpa; | 2754 | const gpa = coff.base.comp.gpa; |
| 1211 | try coff.strings.ensureUnusedCapacityContext(gpa, 1, .{ .bytes = &coff.string_bytes }); | 2755 | try coff.strings.ensureUnusedCapacityContext(gpa, 1, .{ .bytes = &coff.string_bytes }); |
| 1212 | try coff.string_bytes.ensureUnusedCapacity(gpa, len + 1); | 2756 | try coff.string_bytes.ensureUnusedCapacity(gpa, len + 1); |
| 1213 | } | 2757 | } |
| | 2758 | |
| | 2759 | /// `total_len` includes null terminators |
| | 2760 | fn ensureManyUnusedStringCapacity(coff: *Coff, num_strings: u32, total_len: usize) !void { |
| | 2761 | const gpa = coff.base.comp.gpa; |
| | 2762 | try coff.strings.ensureUnusedCapacityContext(gpa, num_strings, .{ .bytes = &coff.string_bytes }); |
| | 2763 | try coff.string_bytes.ensureUnusedCapacity(gpa, total_len + num_strings); |
| | 2764 | } |
| | 2765 | |
| 1214 | fn getOrPutStringAssumeCapacity(coff: *Coff, string: []const u8) String { | 2766 | fn getOrPutStringAssumeCapacity(coff: *Coff, string: []const u8) String { |
| 1215 | const gop = coff.strings.getOrPutAssumeCapacityAdapted( | 2767 | const gop = coff.strings.getOrPutAssumeCapacityAdapted( |
| 1216 | string, | 2768 | string, |
| ... | @@ -1225,18 +2777,78 @@ fn getOrPutStringAssumeCapacity(coff: *Coff, string: []const u8) String { | ... | @@ -1225,18 +2777,78 @@ fn getOrPutStringAssumeCapacity(coff: *Coff, string: []const u8) String { |
| 1225 | return @enumFromInt(gop.key_ptr.*); | 2777 | return @enumFromInt(gop.key_ptr.*); |
| 1226 | } | 2778 | } |
| 1227 | | 2779 | |
| 1228 | pub fn globalSymbol(coff: *Coff, name: []const u8, lib_name: ?[]const u8) !Symbol.Index { | 2780 | const GlobalOptions = struct { |
| 1229 | const gpa = coff.base.comp.gpa; | 2781 | name: []const u8, |
| 1230 | try coff.symbol_table.ensureUnusedCapacity(gpa, 1); | 2782 | lib_name: ?[]const u8 = null, |
| 1231 | const sym_gop = try coff.globals.getOrPut(gpa, .{ | 2783 | type: Symbol.Type = .unknown, |
| 1232 | .name = try coff.getOrPutString(name), | 2784 | dll_storage_class: Symbol.DllStorageClass = .default, |
| 1233 | .lib_name = try coff.getOrPutOptionalString(lib_name), | 2785 | }; |
| 1234 | }); | 2786 | |
| | 2787 | fn getOrPutGlobalSymbol( |
| | 2788 | coff: *Coff, |
| | 2789 | opts: GlobalOptions, |
| | 2790 | ) !std.array_hash_map.Auto(String, Global).GetOrPutResult { |
| | 2791 | const comp = coff.base.comp; |
| | 2792 | const gpa = comp.gpa; |
| | 2793 | try coff.symbols.ensureUnusedCapacity(gpa, 1); |
| | 2794 | |
| | 2795 | const lib_name: String.Optional = if (opts.lib_name) |lib_name| lib_name: { |
| | 2796 | const is_libc = std.zig.target.isLibCLibName(&comp.root_mod.resolved_target.result, lib_name); |
| | 2797 | if (is_libc) { |
| | 2798 | // This is guaranteed by Sema.handleExternLibName |
| | 2799 | if (!comp.config.link_libc) unreachable; |
| | 2800 | |
| | 2801 | // TODO: The user has requested this symbol come from libc, but this logic allows |
| | 2802 | // it to come from anywhere. We need to know what inputs are libc inputs, |
| | 2803 | // and set a flag to only search them for this symbol. |
| | 2804 | break :lib_name .none; |
| | 2805 | } |
| | 2806 | |
| | 2807 | break :lib_name (try coff.getOrPutString(lib_name)).toOptional(); |
| | 2808 | } else .none; |
| | 2809 | |
| | 2810 | const sym_gop = try coff.globals.getOrPut(gpa, try coff.getOrPutString(opts.name)); |
| 1235 | if (!sym_gop.found_existing) { | 2811 | if (!sym_gop.found_existing) { |
| 1236 | sym_gop.value_ptr.* = coff.addSymbolAssumeCapacity(); | 2812 | const si = coff.addSymbolAssumeCapacity(); |
| | 2813 | const sym = si.get(coff); |
| | 2814 | sym.gmi = .wrap(@intCast(sym_gop.index)); |
| | 2815 | sym.flags.type = opts.type; |
| | 2816 | sym.flags.dll_storage_class = opts.dll_storage_class; |
| | 2817 | sym_gop.value_ptr.* = .{ |
| | 2818 | .si = si, |
| | 2819 | .lib_name = lib_name, |
| | 2820 | }; |
| 1237 | coff.synth_prog_node.increaseEstimatedTotalItems(1); | 2821 | coff.synth_prog_node.increaseEstimatedTotalItems(1); |
| | 2822 | |
| | 2823 | log.debug("globalSymbol({s}, {?s}) = {d}", .{ opts.name, opts.lib_name, si }); |
| | 2824 | } |
| | 2825 | |
| | 2826 | return sym_gop; |
| | 2827 | } |
| | 2828 | |
| | 2829 | fn getDefinedGlobal(coff: *Coff, name: []const u8) Symbol.Index { |
| | 2830 | if (coff.globals.get( |
| | 2831 | coff.getString(name).unwrap() orelse return .null, |
| | 2832 | )) |global| if (global.si.get(coff).ni != .none) return global.si; |
| | 2833 | return .null; |
| | 2834 | } |
| | 2835 | |
| | 2836 | pub fn globalSymbol(coff: *Coff, opts: GlobalOptions) !Symbol.Index { |
| | 2837 | const gop = try coff.getOrPutGlobalSymbol(opts); |
| | 2838 | return gop.value_ptr.si; |
| | 2839 | } |
| | 2840 | |
| | 2841 | pub fn pendingSymbolTableEntry(coff: *Coff, si: Symbol.Index) !void { |
| | 2842 | assert(!coff.isImage()); |
| | 2843 | const sym = si.get(coff); |
| | 2844 | |
| | 2845 | assert(sym.ni != .none or sym.gmi != .none); |
| | 2846 | const gpa = coff.base.comp.gpa; |
| | 2847 | const gop = try coff.symbol_table.symbols.getOrPut(gpa, si); |
| | 2848 | if (!gop.found_existing) { |
| | 2849 | coff.symbol_prog_node.increaseEstimatedTotalItems(1); |
| | 2850 | gop.value_ptr.* = .none; |
| 1238 | } | 2851 | } |
| 1239 | return sym_gop.value_ptr.*; | | |
| 1240 | } | 2852 | } |
| 1241 | | 2853 | |
| 1242 | fn navSection( | 2854 | fn navSection( |
| ... | @@ -1247,13 +2859,13 @@ fn navSection( | ... | @@ -1247,13 +2859,13 @@ fn navSection( |
| 1247 | const ip = &zcu.intern_pool; | 2859 | const ip = &zcu.intern_pool; |
| 1248 | const default: String, const attributes: ObjectSectionAttributes = | 2860 | const default: String, const attributes: ObjectSectionAttributes = |
| 1249 | if (nav_resolved.@"threadlocal" and coff.base.comp.config.any_non_single_threaded) .{ | 2861 | if (nav_resolved.@"threadlocal" and coff.base.comp.config.any_non_single_threaded) .{ |
| 1250 | .@".tls$", .{ .read = true, .write = true }, | 2862 | .@".tls$", .{ .read = true, .write = true, .initialized = true }, |
| 1251 | } else if (ip.isFunctionType(nav_resolved.type)) .{ | 2863 | } else if (ip.isFunctionType(nav_resolved.type)) .{ |
| 1252 | .@".text", .{ .read = true, .execute = true }, | 2864 | .@".text", .{ .read = true, .execute = true }, |
| 1253 | } else if (nav_resolved.@"const") .{ | 2865 | } else if (nav_resolved.@"const") .{ |
| 1254 | .@".rdata", .{ .read = true }, | 2866 | .@".rdata", .{ .read = true, .initialized = true }, |
| 1255 | } else .{ | 2867 | } else .{ |
| 1256 | .@".data", .{ .read = true, .write = true }, | 2868 | .@".data", .{ .read = true, .write = true, .initialized = true }, |
| 1257 | }; | 2869 | }; |
| 1258 | | 2870 | |
| 1259 | return (try coff.objectSectionMapIndex( | 2871 | return (try coff.objectSectionMapIndex( |
| ... | @@ -1270,7 +2882,7 @@ fn navSection( | ... | @@ -1270,7 +2882,7 @@ fn navSection( |
| 1270 | } | 2882 | } |
| 1271 | fn navMapIndex(coff: *Coff, zcu: *Zcu, nav_index: InternPool.Nav.Index) !Node.NavMapIndex { | 2883 | fn navMapIndex(coff: *Coff, zcu: *Zcu, nav_index: InternPool.Nav.Index) !Node.NavMapIndex { |
| 1272 | const gpa = zcu.gpa; | 2884 | const gpa = zcu.gpa; |
| 1273 | try coff.symbol_table.ensureUnusedCapacity(gpa, 1); | 2885 | try coff.symbols.ensureUnusedCapacity(gpa, 1); |
| 1274 | const sym_gop = try coff.navs.getOrPut(gpa, nav_index); | 2886 | const sym_gop = try coff.navs.getOrPut(gpa, nav_index); |
| 1275 | if (!sym_gop.found_existing) sym_gop.value_ptr.* = coff.addSymbolAssumeCapacity(); | 2887 | if (!sym_gop.found_existing) sym_gop.value_ptr.* = coff.addSymbolAssumeCapacity(); |
| 1276 | return @enumFromInt(sym_gop.index); | 2888 | return @enumFromInt(sym_gop.index); |
| ... | @@ -1278,17 +2890,20 @@ fn navMapIndex(coff: *Coff, zcu: *Zcu, nav_index: InternPool.Nav.Index) !Node.Na | ... | @@ -1278,17 +2890,20 @@ fn navMapIndex(coff: *Coff, zcu: *Zcu, nav_index: InternPool.Nav.Index) !Node.Na |
| 1278 | pub fn navSymbol(coff: *Coff, zcu: *Zcu, nav_index: InternPool.Nav.Index) !Symbol.Index { | 2890 | pub fn navSymbol(coff: *Coff, zcu: *Zcu, nav_index: InternPool.Nav.Index) !Symbol.Index { |
| 1279 | const ip = &zcu.intern_pool; | 2891 | const ip = &zcu.intern_pool; |
| 1280 | const nav = ip.getNav(nav_index); | 2892 | const nav = ip.getNav(nav_index); |
| 1281 | if (nav.getExtern(ip)) |@"extern"| return coff.globalSymbol( | 2893 | if (nav.getExtern(ip)) |@"extern"| return coff.globalSymbol(.{ |
| 1282 | @"extern".name.toSlice(ip), | 2894 | .name = @"extern".name.toSlice(ip), |
| 1283 | @"extern".lib_name.toSlice(ip), | 2895 | .lib_name = @"extern".lib_name.toSlice(ip), |
| 1284 | ); | 2896 | // TODO: Threadlocal as well? |
| | 2897 | .type = if (ip.isFunctionType(nav.resolved.?.type)) .code else .data, |
| | 2898 | .dll_storage_class = if (@"extern".is_dll_import) .dllimport else .default, |
| | 2899 | }); |
| 1285 | const nmi = try coff.navMapIndex(zcu, nav_index); | 2900 | const nmi = try coff.navMapIndex(zcu, nav_index); |
| 1286 | return nmi.symbol(coff); | 2901 | return nmi.symbol(coff); |
| 1287 | } | 2902 | } |
| 1288 | | 2903 | |
| 1289 | fn uavMapIndex(coff: *Coff, uav_val: InternPool.Index) !Node.UavMapIndex { | 2904 | fn uavMapIndex(coff: *Coff, uav_val: InternPool.Index) !Node.UavMapIndex { |
| 1290 | const gpa = coff.base.comp.gpa; | 2905 | const gpa = coff.base.comp.gpa; |
| 1291 | try coff.symbol_table.ensureUnusedCapacity(gpa, 1); | 2906 | try coff.symbols.ensureUnusedCapacity(gpa, 1); |
| 1292 | const sym_gop = try coff.uavs.getOrPut(gpa, uav_val); | 2907 | const sym_gop = try coff.uavs.getOrPut(gpa, uav_val); |
| 1293 | if (!sym_gop.found_existing) sym_gop.value_ptr.* = coff.addSymbolAssumeCapacity(); | 2908 | if (!sym_gop.found_existing) sym_gop.value_ptr.* = coff.addSymbolAssumeCapacity(); |
| 1294 | return @enumFromInt(sym_gop.index); | 2909 | return @enumFromInt(sym_gop.index); |
| ... | @@ -1300,7 +2915,7 @@ pub fn uavSymbol(coff: *Coff, uav_val: InternPool.Index) !Symbol.Index { | ... | @@ -1300,7 +2915,7 @@ pub fn uavSymbol(coff: *Coff, uav_val: InternPool.Index) !Symbol.Index { |
| 1300 | | 2915 | |
| 1301 | pub fn lazySymbol(coff: *Coff, lazy: link.File.LazySymbol) !Symbol.Index { | 2916 | pub fn lazySymbol(coff: *Coff, lazy: link.File.LazySymbol) !Symbol.Index { |
| 1302 | const gpa = coff.base.comp.gpa; | 2917 | const gpa = coff.base.comp.gpa; |
| 1303 | try coff.symbol_table.ensureUnusedCapacity(gpa, 1); | 2918 | try coff.symbols.ensureUnusedCapacity(gpa, 1); |
| 1304 | const sym_gop = try coff.lazy.getPtr(lazy.kind).map.getOrPut(gpa, lazy.ty); | 2919 | const sym_gop = try coff.lazy.getPtr(lazy.kind).map.getOrPut(gpa, lazy.ty); |
| 1305 | if (!sym_gop.found_existing) { | 2920 | if (!sym_gop.found_existing) { |
| 1306 | sym_gop.value_ptr.* = try coff.initSymbolAssumeCapacity(); | 2921 | sym_gop.value_ptr.* = try coff.initSymbolAssumeCapacity(); |
| ... | @@ -1314,7 +2929,7 @@ pub fn getNavVAddr( | ... | @@ -1314,7 +2929,7 @@ pub fn getNavVAddr( |
| 1314 | pt: Zcu.PerThread, | 2929 | pt: Zcu.PerThread, |
| 1315 | nav: InternPool.Nav.Index, | 2930 | nav: InternPool.Nav.Index, |
| 1316 | reloc_info: link.File.RelocInfo, | 2931 | reloc_info: link.File.RelocInfo, |
| 1317 | ) !u64 { | 2932 | ) link.Error!u64 { |
| 1318 | return coff.getVAddr(reloc_info, try coff.navSymbol(pt.zcu, nav)); | 2933 | return coff.getVAddr(reloc_info, try coff.navSymbol(pt.zcu, nav)); |
| 1319 | } | 2934 | } |
| 1320 | | 2935 | |
| ... | @@ -1322,30 +2937,426 @@ pub fn getUavVAddr( | ... | @@ -1322,30 +2937,426 @@ pub fn getUavVAddr( |
| 1322 | coff: *Coff, | 2937 | coff: *Coff, |
| 1323 | uav: InternPool.Index, | 2938 | uav: InternPool.Index, |
| 1324 | reloc_info: link.File.RelocInfo, | 2939 | reloc_info: link.File.RelocInfo, |
| 1325 | ) !u64 { | 2940 | ) link.Error!u64 { |
| 1326 | return coff.getVAddr(reloc_info, try coff.uavSymbol(uav)); | 2941 | return coff.getVAddr(reloc_info, try coff.uavSymbol(uav)); |
| 1327 | } | 2942 | } |
| 1328 | | 2943 | |
| 1329 | pub fn getVAddr(coff: *Coff, reloc_info: link.File.RelocInfo, target_si: Symbol.Index) !u64 { | 2944 | pub fn getVAddr(coff: *Coff, reloc_info: link.File.RelocInfo, target_si: Symbol.Index) link.Error!u64 { |
| 1330 | try coff.addReloc( | 2945 | try coff.addReloc( |
| 1331 | @enumFromInt(@intFromEnum(reloc_info.parent.atom_index)), | 2946 | @enumFromInt(@intFromEnum(reloc_info.parent.atom_index)), |
| 1332 | reloc_info.offset, | 2947 | reloc_info.offset, |
| 1333 | target_si, | 2948 | target_si, |
| 1334 | reloc_info.addend, | 2949 | .{ .known = reloc_info.addend }, |
| 1335 | switch (coff.targetLoad(&coff.headerPtr().machine)) { | 2950 | switch (coff.targetLoad(&coff.headerPtr().machine)) { |
| 1336 | else => unreachable, | 2951 | else => unreachable, |
| 1337 | .AMD64 => .{ .AMD64 = .ADDR64 }, | 2952 | .AMD64 => .{ .AMD64 = .ADDR64 }, |
| 1338 | .I386 => .{ .I386 = .DIR32 }, | 2953 | .I386 => .{ .I386 = .DIR32 }, |
| 1339 | }, | 2954 | }, |
| 1340 | ); | 2955 | ); |
| 1341 | return coff.optionalHeaderField(.image_base) + target_si.get(coff).rva; | 2956 | |
| | 2957 | var vaddr: u64 = target_si.get(coff).rva; |
| | 2958 | if (coff.isImage()) vaddr += coff.optionalHeaderField(.image_base); |
| | 2959 | return vaddr; |
| | 2960 | } |
| | 2961 | |
| | 2962 | /// Caller guarantees there is capacity for one member and two nodes |
| | 2963 | fn addMemberAssumeCapacity(coff: *Coff, kind: std.coff.ArchiveMemberHeader.Kind, size: u64) !Member.Index { |
| | 2964 | const comp = coff.base.comp; |
| | 2965 | const gpa = comp.gpa; |
| | 2966 | |
| | 2967 | // TODO: These two nodes could to be inside a movable node if kind == .coff|.import |
| | 2968 | const header_ni = try coff.mf.addLastChildNode(gpa, Node.known.file, .{ |
| | 2969 | .size = @sizeOf(std.coff.ArchiveMemberHeader), |
| | 2970 | .alignment = .@"2", |
| | 2971 | .fixed = true, |
| | 2972 | .moved = true, |
| | 2973 | }); |
| | 2974 | |
| | 2975 | const content_ni = try coff.mf.addLastChildNode(gpa, Node.known.file, .{ |
| | 2976 | // The actual alignment required by the spec is 2, but to allow aligned access to |
| | 2977 | // the various COFF data structures in-place during linking we overalign |
| | 2978 | .alignment = switch (kind) { |
| | 2979 | .coff => .@"4", |
| | 2980 | else => .@"2", |
| | 2981 | }, |
| | 2982 | .size = size, |
| | 2983 | .resized = size > 0, |
| | 2984 | .fixed = true, |
| | 2985 | }); |
| | 2986 | |
| | 2987 | const mi: Member.Index = @enumFromInt(coff.members.items.len); |
| | 2988 | coff.members.appendAssumeCapacity(.{ |
| | 2989 | .kind = kind, |
| | 2990 | .header_ni = header_ni, |
| | 2991 | .content_ni = content_ni, |
| | 2992 | .first_linker_indices = .empty, |
| | 2993 | }); |
| | 2994 | |
| | 2995 | coff.nodes.appendAssumeCapacity(.{ .archive_member_header = mi }); |
| | 2996 | coff.nodes.appendAssumeCapacity(.{ .archive_member = mi }); |
| | 2997 | |
| | 2998 | switch (kind) { |
| | 2999 | .first_linker, .second_linker, .longnames => {}, |
| | 3000 | else => { |
| | 3001 | const new_num_members = coff.members.items.len - Member.Index.known_count; |
| | 3002 | coff.targetStore( |
| | 3003 | coff.secondLinkerMemberNumMembersPtr(), |
| | 3004 | @intCast(new_num_members), |
| | 3005 | ); |
| | 3006 | |
| | 3007 | const old_size = Node.known.second_linker_member.location(&coff.mf).resolve(&coff.mf)[1]; |
| | 3008 | const old_header_size = new_num_members * @sizeOf(u32); |
| | 3009 | const trailing_size: usize = @intCast(old_size - old_header_size); |
| | 3010 | try Node.known.second_linker_member.resize(&coff.mf, gpa, old_size + @sizeOf(u32)); |
| | 3011 | |
| | 3012 | const slice = Node.known.second_linker_member.slice(&coff.mf); |
| | 3013 | @memmove( |
| | 3014 | slice[old_header_size + @sizeOf(u32) ..][0..trailing_size], |
| | 3015 | slice[old_header_size..][0..trailing_size], |
| | 3016 | ); |
| | 3017 | |
| | 3018 | // Offset will be written by flushMoved on header_ni |
| | 3019 | }, |
| | 3020 | } |
| | 3021 | |
| | 3022 | switch (kind) { |
| | 3023 | .first_linker, |
| | 3024 | .longnames, |
| | 3025 | .import, |
| | 3026 | => {}, |
| | 3027 | .second_linker, |
| | 3028 | .coff, |
| | 3029 | => { |
| | 3030 | try coff.pending_members.ensureTotalCapacity( |
| | 3031 | gpa, |
| | 3032 | coff.pending_members.capacity() + 1, |
| | 3033 | ); |
| | 3034 | coff.member_prog_node.increaseEstimatedTotalItems(1); |
| | 3035 | }, |
| | 3036 | } |
| | 3037 | |
| | 3038 | return mi; |
| | 3039 | } |
| | 3040 | |
| | 3041 | fn appendMemberSymbolString( |
| | 3042 | coff: *Coff, |
| | 3043 | strings_ni: MappedFile.Node.Index, |
| | 3044 | new_size: u64, |
| | 3045 | name: []const u8, |
| | 3046 | offset: u64, |
| | 3047 | ) !void { |
| | 3048 | try strings_ni.resize(&coff.mf, coff.base.comp.gpa, new_size); |
| | 3049 | const name_slice = strings_ni.slice(&coff.mf)[offset..][0 .. name.len + 1]; |
| | 3050 | @memcpy(name_slice[0..name.len], name); |
| | 3051 | name_slice[name.len] = 0; |
| | 3052 | } |
| | 3053 | |
| | 3054 | fn ensureMemberSymbol(coff: *Coff, mi: Member.Index, name: String) !void { |
| | 3055 | const gpa = coff.base.comp.gpa; |
| | 3056 | const member = mi.get(coff); |
| | 3057 | assert(member.kind == .coff); |
| | 3058 | |
| | 3059 | const gop = try member.first_linker_indices.getOrPut(gpa, .{ .mi = mi, .name = name }); |
| | 3060 | if (gop.found_existing) return; |
| | 3061 | |
| | 3062 | const mfli: Member.FirstLinkerIndex = blk: { |
| | 3063 | const num_symbols_ptr = coff.firstLinkerMemberNumSymbolsPtr(); |
| | 3064 | const num_symbols = std.mem.toNative(u32, num_symbols_ptr.*, .big); |
| | 3065 | num_symbols_ptr.* = std.mem.nativeTo(u32, num_symbols + 1, .big); |
| | 3066 | break :blk @enumFromInt(num_symbols); |
| | 3067 | }; |
| | 3068 | |
| | 3069 | gop.value_ptr.* = mfli; |
| | 3070 | |
| | 3071 | // Linker member fields are not modeled as nodes because MappedFile |
| | 3072 | // can't guarantee that they will be tightly packed after resizing |
| | 3073 | |
| | 3074 | const name_slice = name.toSlice(coff); |
| | 3075 | const new_string_table_size: u32 = @intCast(coff.lib_string_len + name_slice.len + 1); |
| | 3076 | defer coff.lib_string_len = new_string_table_size; |
| | 3077 | |
| | 3078 | { |
| | 3079 | const old_header_size: usize = @intCast(@sizeOf(u32) + @intFromEnum(mfli) * @sizeOf(u32)); |
| | 3080 | const new_header_size: usize = @intCast(old_header_size + @sizeOf(u32)); |
| | 3081 | try Node.known.first_linker_member.resize(&coff.mf, gpa, new_header_size + new_string_table_size); |
| | 3082 | |
| | 3083 | const slice = Node.known.first_linker_member.slice(&coff.mf); |
| | 3084 | @memmove(slice[new_header_size..][0..coff.lib_string_len], slice[old_header_size..][0..coff.lib_string_len]); |
| | 3085 | @memcpy(slice[new_header_size + coff.lib_string_len ..][0..name_slice.len], name_slice[0..name_slice.len]); |
| | 3086 | slice[new_header_size + coff.lib_string_len + name_slice.len] = 0; |
| | 3087 | |
| | 3088 | // New offset entry is written in flushMember |
| | 3089 | } |
| | 3090 | |
| | 3091 | { |
| | 3092 | const num_members = coff.targetLoad(coff.secondLinkerMemberNumMembersPtr()); |
| | 3093 | const old_header_size = 2 * @sizeOf(u32) + num_members * @sizeOf(u32) + @intFromEnum(mfli) * @sizeOf(u16); |
| | 3094 | const new_header_size = old_header_size + @sizeOf(u16); |
| | 3095 | try Node.known.second_linker_member.resize(&coff.mf, gpa, new_header_size + new_string_table_size); |
| | 3096 | |
| | 3097 | const old_needs_sort = coff.pending_members.get(Member.Index.second) != null; |
| | 3098 | const needs_sort = old_needs_sort or (if (coff.lib_string_table.items.len > 0) |
| | 3099 | std.mem.lessThan( |
| | 3100 | u8, |
| | 3101 | name_slice, |
| | 3102 | coff.lib_string_table.items[coff.lib_string_table.items.len - 1].toSlice(coff), |
| | 3103 | ) |
| | 3104 | else |
| | 3105 | false); |
| | 3106 | |
| | 3107 | try coff.lib_string_table.append(gpa, name); |
| | 3108 | |
| | 3109 | const slice = Node.known.second_linker_member.slice(&coff.mf); |
| | 3110 | coff.targetStore(coff.secondLinkerMemberNumSymbolsPtr(), @intFromEnum(mfli) + 1); |
| | 3111 | if (!needs_sort) { |
| | 3112 | @memmove(slice[new_header_size..][0..coff.lib_string_len], slice[old_header_size..][0..coff.lib_string_len]); |
| | 3113 | @memcpy(slice[new_header_size + coff.lib_string_len ..][0..name_slice.len], name_slice[0..name_slice.len]); |
| | 3114 | slice[new_header_size + coff.lib_string_len + name_slice.len] = 0; |
| | 3115 | } else if (!old_needs_sort) { |
| | 3116 | // The entire string table is rebuilt in flushMember after sorting |
| | 3117 | coff.pending_members.putAssumeCapacity(Member.Index.second, {}); |
| | 3118 | } |
| | 3119 | |
| | 3120 | // Indices in this table are 1-based |
| | 3121 | const index_ptr: *u16 = @ptrCast(@alignCast(slice[old_header_size..])); |
| | 3122 | coff.targetStore(index_ptr, @intCast(@intFromEnum(mi) - Member.Index.known_count + 1)); |
| | 3123 | } |
| | 3124 | |
| | 3125 | coff.pending_members.putAssumeCapacity(mi, {}); |
| | 3126 | coff.member_prog_node.increaseEstimatedTotalItems(1); |
| | 3127 | } |
| | 3128 | |
| | 3129 | fn flushSymbolTableEntry(coff: *Coff, index: u32, pt: Zcu.PerThread) !void { |
| | 3130 | assert(!coff.isImage()); |
| | 3131 | const gpa = coff.base.comp.gpa; |
| | 3132 | |
| | 3133 | const si = coff.symbol_table.symbols.keys()[index]; |
| | 3134 | const sti = &coff.symbol_table.symbols.values()[index]; |
| | 3135 | |
| | 3136 | const sym = si.get(coff); |
| | 3137 | assert(sym.ni != .none or sym.gmi != .none); |
| | 3138 | |
| | 3139 | const entry = coff.symbolTableEntryPtr(sti.*) orelse entry: { |
| | 3140 | var buf: [15]u8 = undefined; |
| | 3141 | const symbol_name, const num_aux_symbols: u8, const complex_type: std.coff.ComplexType = |
| | 3142 | if (sym.gmi != .none) blk: { |
| | 3143 | const name = sym.gmi.name(coff); |
| | 3144 | break :blk .{ |
| | 3145 | try coff.getOrPutSymbolName(name.toSlice(coff), name), |
| | 3146 | @intFromBool(sym.flags.weak_external_strat != .none), |
| | 3147 | if (Symbol.Index.text.get(coff).section_number == sym.section_number) |
| | 3148 | .FUNCTION |
| | 3149 | else |
| | 3150 | .NULL, |
| | 3151 | }; |
| | 3152 | } else blk: switch (coff.getNode(sym.ni)) { |
| | 3153 | .image_section => .{ |
| | 3154 | try coff.getOrPutSymbolName(&sym.section_number.header(coff).name, null), |
| | 3155 | 1, |
| | 3156 | .NULL, |
| | 3157 | }, |
| | 3158 | .nav => |nmi| { |
| | 3159 | const zcu = coff.base.comp.zcu.?; |
| | 3160 | const ip = &zcu.intern_pool; |
| | 3161 | const nav = ip.getNav(nmi.navIndex(coff)); |
| | 3162 | break :blk .{ |
| | 3163 | try coff.getOrPutSymbolName(nav.fqn.toSlice(ip), null), |
| | 3164 | 0, |
| | 3165 | if (ip.isFunctionType(nav.resolved.?.type)) .FUNCTION else .NULL, |
| | 3166 | }; |
| | 3167 | }, |
| | 3168 | .uav => |umi| { |
| | 3169 | var w = Io.Writer.fixed(&buf); |
| | 3170 | w.print("__anon_{x}", .{umi.uavValue(coff)}) catch unreachable; |
| | 3171 | break :blk .{ |
| | 3172 | try coff.getOrPutSymbolName(w.buffered(), null), |
| | 3173 | 0, |
| | 3174 | .NULL, |
| | 3175 | }; |
| | 3176 | }, |
| | 3177 | inline .lazy_code, .lazy_const_data => |mi, tag| { |
| | 3178 | const lazy_sym = mi.lazySymbol(coff); |
| | 3179 | const name = try std.fmt.allocPrint(gpa, "__lazy_{s}_{f}", .{ |
| | 3180 | @tagName(lazy_sym.kind), |
| | 3181 | Type.fromInterned(lazy_sym.ty).fmt(pt), |
| | 3182 | }); |
| | 3183 | defer gpa.free(name); |
| | 3184 | |
| | 3185 | const string = try coff.getOrPutString(name); |
| | 3186 | break :blk .{ |
| | 3187 | try coff.getOrPutSymbolName(string.toSlice(coff), string), |
| | 3188 | 0, |
| | 3189 | if (tag == .lazy_code) .FUNCTION else .NULL, |
| | 3190 | }; |
| | 3191 | }, |
| | 3192 | else => { |
| | 3193 | log.err("TODO implement symbol table init for {s} ({d})", .{ @tagName(coff.getNode(sym.ni)), si }); |
| | 3194 | unreachable; |
| | 3195 | }, |
| | 3196 | }; |
| | 3197 | |
| | 3198 | const old_num_symbols = coff.targetLoad(&coff.headerPtr().number_of_symbols); |
| | 3199 | const new_num_symbols = old_num_symbols + 1 + num_aux_symbols; |
| | 3200 | coff.targetStore(&coff.headerPtr().number_of_symbols, new_num_symbols); |
| | 3201 | |
| | 3202 | try coff.symbol_table.ni.resize(&coff.mf, gpa, new_num_symbols * std.coff.Symbol.sizeOf()); |
| | 3203 | |
| | 3204 | sti.* = .wrap(old_num_symbols); |
| | 3205 | si.flushSymbolTableIndex(coff); |
| | 3206 | |
| | 3207 | const entry = coff.symbolTableEntryPtr(sti.*).?; |
| | 3208 | symbol_name.store(coff, &entry.name); |
| | 3209 | |
| | 3210 | entry.section_number = @enumFromInt(@intFromEnum(sym.section_number)); |
| | 3211 | entry.type = .{ |
| | 3212 | .complex_type = complex_type, |
| | 3213 | .base_type = .NULL, |
| | 3214 | }; |
| | 3215 | |
| | 3216 | entry.storage_class = if (sym.gmi != .none) |
| | 3217 | .EXTERNAL |
| | 3218 | else if (sym.flags.extra_tag == .next_alias_si) storage: { |
| | 3219 | var alias_sym = sym; |
| | 3220 | const weak_external = while (alias_sym.flags.extra_tag == .next_alias_si) { |
| | 3221 | const alias_si = alias_sym.extra.next_alias_si; |
| | 3222 | alias_sym = alias_si.get(coff); |
| | 3223 | assert(alias_sym.ni == sym.ni); |
| | 3224 | if (alias_sym.flags.weak_external_strat != .none) |
| | 3225 | break true; |
| | 3226 | } else false; |
| | 3227 | break :storage if (weak_external) .EXTERNAL else .STATIC; |
| | 3228 | } else .STATIC; |
| | 3229 | |
| | 3230 | entry.number_of_aux_symbols = num_aux_symbols; |
| | 3231 | if (coff.targetEndian() != native_endian) |
| | 3232 | std.mem.byteSwapAllFieldsAligned(std.coff.Symbol, .@"2", entry); |
| | 3233 | |
| | 3234 | if (num_aux_symbols > 0) aux_init: { |
| | 3235 | if (sym.gmi != .none) { |
| | 3236 | entry.section_number = .UNDEFINED; |
| | 3237 | entry.storage_class = .WEAK_EXTERNAL; |
| | 3238 | |
| | 3239 | const tag_index = sym.value.weak_alias_si.sti(coff).unwrap().?; |
| | 3240 | const aux_ptr = coff.symbolTableWeakExternalAuxEntryPtr(sti.*).?; |
| | 3241 | aux_ptr.* = .{ |
| | 3242 | .tag_index = tag_index, |
| | 3243 | .flag = switch (sym.flags.weak_external_strat) { |
| | 3244 | .none => unreachable, |
| | 3245 | .no_library => .SEARCH_NOLIBRARY, |
| | 3246 | .library => .SEARCH_LIBRARY, |
| | 3247 | .alias => .SEARCH_ALIAS, |
| | 3248 | .anti_dependency => .ANTI_DEPENDENCY, |
| | 3249 | }, |
| | 3250 | .unused = @splat(0), |
| | 3251 | }; |
| | 3252 | if (coff.targetEndian() != native_endian) |
| | 3253 | std.mem.byteSwapAllFieldsAligned(std.coff.WeakExternalDefinition, .@"2", aux_ptr); |
| | 3254 | |
| | 3255 | break :aux_init; |
| | 3256 | } else switch (coff.getNode(sym.ni)) { |
| | 3257 | .image_section => |sec_si| { |
| | 3258 | assert(si == sec_si); |
| | 3259 | const header = sym.section_number.header(coff); |
| | 3260 | const aux_ptr = coff.symbolTableSectionAuxEntryPtr(sti.*).?; |
| | 3261 | aux_ptr.* = .{ |
| | 3262 | .length = @intCast(sym.ni.location(&coff.mf).resolve(&coff.mf)[1]), |
| | 3263 | .number_of_relocations = header.number_of_relocations, |
| | 3264 | .number_of_linenumbers = header.number_of_linenumbers, |
| | 3265 | .checksum = 0, |
| | 3266 | .number = 0, |
| | 3267 | .selection = .NONE, |
| | 3268 | .unused = @splat(0), |
| | 3269 | }; |
| | 3270 | if (coff.targetEndian() != native_endian) |
| | 3271 | std.mem.byteSwapAllFieldsAligned(std.coff.SectionDefinition, .@"2", aux_ptr); |
| | 3272 | |
| | 3273 | break :aux_init; |
| | 3274 | }, |
| | 3275 | else => {}, |
| | 3276 | } |
| | 3277 | |
| | 3278 | unreachable; |
| | 3279 | } |
| | 3280 | |
| | 3281 | break :entry entry; |
| | 3282 | }; |
| | 3283 | |
| | 3284 | coff.targetStore(&entry.value, switch (sym.section_number) { |
| | 3285 | .UNDEFINED => if (entry.storage_class == .WEAK_EXTERNAL) 0 else sym.size(), |
| | 3286 | .ABSOLUTE, |
| | 3287 | .DEBUG, |
| | 3288 | => unreachable, |
| | 3289 | else => switch (coff.getNode(sym.ni)) { |
| | 3290 | .image_section => 0, |
| | 3291 | else => coff.computeSymbolSectionOffset(sym, .image), |
| | 3292 | }, |
| | 3293 | }); |
| | 3294 | |
| | 3295 | log.debug("flushSymbolTableEntry({d}) = {d}", .{ si, sti.* }); |
| | 3296 | } |
| | 3297 | |
| | 3298 | fn flushInputMember(coff: *Coff, iami: InputArchive.Member.Index) !void { |
| | 3299 | const member = iami.member(coff); |
| | 3300 | assert(!member.flags.is_loaded); |
| | 3301 | defer member.flags.is_loaded = true; |
| | 3302 | switch (member.content) { |
| | 3303 | .import => unreachable, |
| | 3304 | .object => |file_location| { |
| | 3305 | if (file_location.size == 0) return; |
| | 3306 | const comp = coff.base.comp; |
| | 3307 | const io = comp.io; |
| | 3308 | const path = member.iai.path(coff); |
| | 3309 | const file = try path.root_dir.handle.openFile(io, path.sub_path, .{}); |
| | 3310 | defer file.close(io); |
| | 3311 | var buffer: [4096]u8 = undefined; |
| | 3312 | var fr = file.reader(io, &buffer); |
| | 3313 | const offset = file_location.offset + @sizeOf(std.coff.ArchiveMemberHeader); |
| | 3314 | try fr.seekTo(offset); |
| | 3315 | log.debug("flushInputMember({f}({s}))", .{ path, member.name.toSlice(coff) }); |
| | 3316 | try coff.loadObject(path, member.name.toSlice(coff), &fr, .{ |
| | 3317 | .offset = offset, |
| | 3318 | .size = file_location.size, |
| | 3319 | }); |
| | 3320 | }, |
| | 3321 | } |
| | 3322 | } |
| | 3323 | |
| | 3324 | fn flushInputSection(coff: *Coff, isi: Node.InputSection.Index) !void { |
| | 3325 | const file_loc = isi.fileLocation(coff); |
| | 3326 | if (file_loc.size == 0) return; |
| | 3327 | const comp = coff.base.comp; |
| | 3328 | const io = comp.io; |
| | 3329 | const gpa = comp.gpa; |
| | 3330 | const ioi = isi.input(coff); |
| | 3331 | const path = ioi.path(coff); |
| | 3332 | const file = try path.root_dir.handle.openFile(io, path.sub_path, .{}); |
| | 3333 | defer file.close(io); |
| | 3334 | var fr = file.reader(io, &.{}); |
| | 3335 | try fr.seekTo(file_loc.offset); |
| | 3336 | var nw: MappedFile.Node.Writer = undefined; |
| | 3337 | const si = isi.symbol(coff); |
| | 3338 | si.node(coff).writer(&coff.mf, gpa, &nw); |
| | 3339 | defer nw.deinit(); |
| | 3340 | log.debug("flushInputSection({f}{f}, {s}, {d}, n{d})", .{ |
| | 3341 | path, |
| | 3342 | fmtMemberNameString(ioi.memberName(coff)), |
| | 3343 | si.get(coff).section_number.name(coff).toSlice(coff), |
| | 3344 | si, |
| | 3345 | si.node(coff), |
| | 3346 | }); |
| | 3347 | if (try nw.interface.sendFileAll(&fr, .limited(@intCast(file_loc.size))) != file_loc.size) |
| | 3348 | return error.EndOfStream; |
| | 3349 | try si.applyLocationRelocs(coff); |
| 1342 | } | 3350 | } |
| 1343 | | 3351 | |
| 1344 | fn addSection(coff: *Coff, name: []const u8, flags: std.coff.SectionHeader.Flags) !Symbol.Index { | 3352 | fn addSection(coff: *Coff, name: String, flags: std.coff.SectionHeader.Flags) !Symbol.Index { |
| | 3353 | assert(coff.hasCoffHeader()); |
| | 3354 | |
| 1345 | const gpa = coff.base.comp.gpa; | 3355 | const gpa = coff.base.comp.gpa; |
| 1346 | try coff.nodes.ensureUnusedCapacity(gpa, 1); | 3356 | try coff.nodes.ensureUnusedCapacity(gpa, 1); |
| 1347 | try coff.image_section_table.ensureUnusedCapacity(gpa, 1); | 3357 | try coff.section_table.ensureUnusedCapacity(gpa, 1); |
| 1348 | try coff.symbol_table.ensureUnusedCapacity(gpa, 1); | 3358 | try coff.symbols.ensureUnusedCapacity(gpa, 1); |
| | 3359 | if (!isImage(coff)) try coff.symbol_table.symbols.ensureUnusedCapacity(gpa, 1); |
| 1349 | | 3360 | |
| 1350 | const coff_header = coff.headerPtr(); | 3361 | const coff_header = coff.headerPtr(); |
| 1351 | const section_index = coff.targetLoad(&coff_header.number_of_sections); | 3362 | const section_index = coff.targetLoad(&coff_header.number_of_sections); |
| ... | @@ -1356,21 +3367,32 @@ fn addSection(coff: *Coff, name: []const u8, flags: std.coff.SectionHeader.Flags | ... | @@ -1356,21 +3367,32 @@ fn addSection(coff: *Coff, name: []const u8, flags: std.coff.SectionHeader.Flags |
| 1356 | gpa, | 3367 | gpa, |
| 1357 | @sizeOf(std.coff.SectionHeader) * section_table_len, | 3368 | @sizeOf(std.coff.SectionHeader) * section_table_len, |
| 1358 | ); | 3369 | ); |
| 1359 | const ni = try coff.mf.addLastChildNode(gpa, .root, .{ | 3370 | |
| | 3371 | const ni = try coff.mf.addLastChildNode(gpa, coff.sectionParent(), .{ |
| 1360 | .alignment = coff.mf.flags.block_size, | 3372 | .alignment = coff.mf.flags.block_size, |
| 1361 | .moved = true, | 3373 | .moved = true, |
| 1362 | .bubbles_moved = false, | 3374 | .bubbles_moved = false, |
| 1363 | }); | 3375 | }); |
| | 3376 | |
| 1364 | const si = coff.addSymbolAssumeCapacity(); | 3377 | const si = coff.addSymbolAssumeCapacity(); |
| 1365 | coff.image_section_table.appendAssumeCapacity(si); | 3378 | coff.section_table.putAssumeCapacity(name, .{ |
| | 3379 | .si = si, |
| | 3380 | .relocation_table_ni = .none, |
| | 3381 | }); |
| 1366 | coff.nodes.appendAssumeCapacity(.{ .image_section = si }); | 3382 | coff.nodes.appendAssumeCapacity(.{ .image_section = si }); |
| 1367 | const section_table = coff.sectionTableSlice(); | 3383 | const section_table = coff.sectionTableSlice(); |
| 1368 | const virtual_size = coff.optionalHeaderField(.section_alignment); | 3384 | |
| 1369 | const rva: u32 = switch (section_index) { | 3385 | const virtual_size, const rva = if (coff.isImage()) block: { |
| 1370 | 0 => @intCast(Node.known.header.location(&coff.mf).resolve(&coff.mf)[1]), | 3386 | const virtual_size = coff.optionalHeaderField(.section_alignment); |
| 1371 | else => coff.image_section_table.items[section_index - 1].get(coff).rva + | 3387 | const rva: u32 = switch (section_index) { |
| 1372 | coff.targetLoad(&section_table[section_index - 1].virtual_size), | 3388 | 0 => @intCast(Node.known.header.location(&coff.mf).resolve(&coff.mf)[1]), |
| 1373 | }; | 3389 | else => coff.section_table.values()[section_index - 1].si.get(coff).rva + |
| | 3390 | coff.targetLoad(&section_table[section_index - 1].virtual_size), |
| | 3391 | }; |
| | 3392 | |
| | 3393 | break :block .{ virtual_size, rva }; |
| | 3394 | } else .{ 0, 0 }; |
| | 3395 | |
| 1374 | { | 3396 | { |
| 1375 | const sym = si.get(coff); | 3397 | const sym = si.get(coff); |
| 1376 | sym.ni = ni; | 3398 | sym.ni = ni; |
| ... | @@ -1390,16 +3412,24 @@ fn addSection(coff: *Coff, name: []const u8, flags: std.coff.SectionHeader.Flags | ... | @@ -1390,16 +3412,24 @@ fn addSection(coff: *Coff, name: []const u8, flags: std.coff.SectionHeader.Flags |
| 1390 | .number_of_linenumbers = 0, | 3412 | .number_of_linenumbers = 0, |
| 1391 | .flags = flags, | 3413 | .flags = flags, |
| 1392 | }; | 3414 | }; |
| 1393 | @memcpy(section.name[0..name.len], name); | | |
| 1394 | @memset(section.name[name.len..], 0); | | |
| 1395 | if (coff.targetEndian() != native_endian) | 3415 | if (coff.targetEndian() != native_endian) |
| 1396 | std.mem.byteSwapAllFields(std.coff.SectionHeader, section); | 3416 | std.mem.byteSwapAllFields(std.coff.SectionHeader, section); |
| 1397 | switch (coff.optionalHeaderPtr()) { | 3417 | |
| 1398 | inline else => |optional_header| coff.targetStore( | 3418 | const name_slice = name.toSlice(coff); |
| 1399 | &optional_header.size_of_image, | 3419 | if (coff.isImage()) { |
| 1400 | @intCast(rva + virtual_size), | 3420 | @memcpy(section.name[0..name_slice.len], name_slice); |
| 1401 | ), | 3421 | @memset(section.name[name_slice.len..], 0); |
| | 3422 | switch (coff.optionalHeaderPtr()) { |
| | 3423 | inline else => |optional_header| coff.targetStore( |
| | 3424 | &optional_header.size_of_image, |
| | 3425 | @intCast(rva + virtual_size), |
| | 3426 | ), |
| | 3427 | } |
| | 3428 | } else { |
| | 3429 | (try coff.getOrPutSymbolName(name_slice, name)).store(coff, &section.name); |
| | 3430 | try coff.pendingSymbolTableEntry(si); |
| 1402 | } | 3431 | } |
| | 3432 | |
| 1403 | return si; | 3433 | return si; |
| 1404 | } | 3434 | } |
| 1405 | | 3435 | |
| ... | @@ -1412,7 +3442,40 @@ const ObjectSectionAttributes = packed struct { | ... | @@ -1412,7 +3442,40 @@ const ObjectSectionAttributes = packed struct { |
| 1412 | nocache: bool = false, | 3442 | nocache: bool = false, |
| 1413 | discard: bool = false, | 3443 | discard: bool = false, |
| 1414 | remove: bool = false, | 3444 | remove: bool = false, |
| | 3445 | initialized: bool = false, |
| | 3446 | uninitialized: bool = false, |
| | 3447 | |
| | 3448 | pub fn fromFlags(flags: std.coff.SectionHeader.Flags) ObjectSectionAttributes { |
| | 3449 | return .{ |
| | 3450 | .read = flags.MEM_READ, |
| | 3451 | .write = flags.MEM_WRITE, |
| | 3452 | .execute = flags.MEM_EXECUTE, |
| | 3453 | .shared = flags.MEM_SHARED, |
| | 3454 | .nopage = flags.MEM_NOT_PAGED, |
| | 3455 | .nocache = flags.MEM_NOT_CACHED, |
| | 3456 | .discard = flags.MEM_DISCARDABLE, |
| | 3457 | .remove = flags.LNK_REMOVE, |
| | 3458 | .initialized = flags.CNT_INITIALIZED_DATA, |
| | 3459 | .uninitialized = flags.CNT_UNINITIALIZED_DATA, |
| | 3460 | }; |
| | 3461 | } |
| | 3462 | |
| | 3463 | pub fn asFlags(attr: ObjectSectionAttributes) std.coff.SectionHeader.Flags { |
| | 3464 | return .{ |
| | 3465 | .MEM_READ = attr.read, |
| | 3466 | .MEM_WRITE = attr.write, |
| | 3467 | .MEM_EXECUTE = attr.execute, |
| | 3468 | .MEM_SHARED = attr.shared, |
| | 3469 | .MEM_NOT_PAGED = attr.nopage, |
| | 3470 | .MEM_NOT_CACHED = attr.nocache, |
| | 3471 | .MEM_DISCARDABLE = attr.discard, |
| | 3472 | .LNK_REMOVE = attr.remove, |
| | 3473 | .CNT_INITIALIZED_DATA = attr.uninitialized, |
| | 3474 | .CNT_UNINITIALIZED_DATA = attr.uninitialized, |
| | 3475 | }; |
| | 3476 | } |
| 1415 | }; | 3477 | }; |
| | 3478 | |
| 1416 | fn pseudoSectionMapIndex( | 3479 | fn pseudoSectionMapIndex( |
| 1417 | coff: *Coff, | 3480 | coff: *Coff, |
| 1418 | name: String, | 3481 | name: String, |
| ... | @@ -1422,15 +3485,25 @@ fn pseudoSectionMapIndex( | ... | @@ -1422,15 +3485,25 @@ fn pseudoSectionMapIndex( |
| 1422 | const gpa = coff.base.comp.gpa; | 3485 | const gpa = coff.base.comp.gpa; |
| 1423 | const pseudo_section_gop = try coff.pseudo_section_table.getOrPut(gpa, name); | 3486 | const pseudo_section_gop = try coff.pseudo_section_table.getOrPut(gpa, name); |
| 1424 | const psmi: Node.PseudoSectionMapIndex = @enumFromInt(pseudo_section_gop.index); | 3487 | const psmi: Node.PseudoSectionMapIndex = @enumFromInt(pseudo_section_gop.index); |
| 1425 | if (!pseudo_section_gop.found_existing) { | 3488 | const parent_sn = if (!pseudo_section_gop.found_existing) sn: { |
| 1426 | const parent: Symbol.Index = if (attributes.execute) | 3489 | const effective_name = coff.section_merges.get(name) orelse name; |
| 1427 | .text | 3490 | const parent = if (coff.section_table.get(effective_name)) |existing_sec| |
| 1428 | else if (attributes.write) | 3491 | existing_sec.si |
| 1429 | .data | 3492 | else if (coff.isImage()) parent: { |
| 1430 | else | 3493 | const parent: Symbol.Index = if (attributes.uninitialized) |
| 1431 | .rdata; | 3494 | .bss |
| | 3495 | else if (attributes.execute) |
| | 3496 | .text |
| | 3497 | else if (attributes.write) |
| | 3498 | .data |
| | 3499 | else |
| | 3500 | .rdata; |
| | 3501 | |
| | 3502 | break :parent parent; |
| | 3503 | } else try coff.addSection(effective_name, attributes.asFlags()); |
| | 3504 | |
| 1432 | try coff.nodes.ensureUnusedCapacity(gpa, 1); | 3505 | try coff.nodes.ensureUnusedCapacity(gpa, 1); |
| 1433 | try coff.symbol_table.ensureUnusedCapacity(gpa, 1); | 3506 | try coff.symbols.ensureUnusedCapacity(gpa, 1); |
| 1434 | const ni = try coff.mf.addLastChildNode(gpa, parent.node(coff), .{ .alignment = alignment }); | 3507 | const ni = try coff.mf.addLastChildNode(gpa, parent.node(coff), .{ .alignment = alignment }); |
| 1435 | const si = coff.addSymbolAssumeCapacity(); | 3508 | const si = coff.addSymbolAssumeCapacity(); |
| 1436 | pseudo_section_gop.value_ptr.* = si; | 3509 | pseudo_section_gop.value_ptr.* = si; |
| ... | @@ -1441,9 +3514,30 @@ fn pseudoSectionMapIndex( | ... | @@ -1441,9 +3514,30 @@ fn pseudoSectionMapIndex( |
| 1441 | assert(sym.loc_relocs == .none); | 3514 | assert(sym.loc_relocs == .none); |
| 1442 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); | 3515 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| 1443 | coff.nodes.appendAssumeCapacity(.{ .pseudo_section = psmi }); | 3516 | coff.nodes.appendAssumeCapacity(.{ .pseudo_section = psmi }); |
| 1444 | } | 3517 | break :sn sym.section_number; |
| | 3518 | } else pseudo_section_gop.value_ptr.get(coff).section_number; |
| | 3519 | |
| | 3520 | try coff.verifyParentSectionAttributes( |
| | 3521 | parent_sn, |
| | 3522 | name, |
| | 3523 | .pseudo, |
| | 3524 | .fromFlags(parent_sn.header(coff).flags), |
| | 3525 | attributes, |
| | 3526 | ); |
| | 3527 | |
| 1445 | return psmi; | 3528 | return psmi; |
| 1446 | } | 3529 | } |
| | 3530 | |
| | 3531 | fn objectSectionParentName(coff: *Coff, name: []const u8) []const u8 { |
| | 3532 | // In images we want to sort object sections into the final root section name. |
| | 3533 | // Otherwise, we want to keep the full name so that this sort can occur correctly when |
| | 3534 | // the object is finally linked into an image. |
| | 3535 | return if (coff.isImage()) |
| | 3536 | name[0 .. std.mem.indexOfScalar(u8, name, '$') orelse name.len] |
| | 3537 | else |
| | 3538 | name; |
| | 3539 | } |
| | 3540 | |
| 1447 | fn objectSectionMapIndex( | 3541 | fn objectSectionMapIndex( |
| 1448 | coff: *Coff, | 3542 | coff: *Coff, |
| 1449 | name: String, | 3543 | name: String, |
| ... | @@ -1451,16 +3545,23 @@ fn objectSectionMapIndex( | ... | @@ -1451,16 +3545,23 @@ fn objectSectionMapIndex( |
| 1451 | attributes: ObjectSectionAttributes, | 3545 | attributes: ObjectSectionAttributes, |
| 1452 | ) !Node.ObjectSectionMapIndex { | 3546 | ) !Node.ObjectSectionMapIndex { |
| 1453 | const gpa = coff.base.comp.gpa; | 3547 | const gpa = coff.base.comp.gpa; |
| | 3548 | const name_slice = name.toSlice(coff); |
| | 3549 | // TODO: Should this be a section merge instead? |
| | 3550 | const effective_attributes = if (coff.isImage() and std.mem.startsWith(u8, name_slice, ".tls")) attr: { |
| | 3551 | // In images, the .tls section is a read-only template |
| | 3552 | var attr = attributes; |
| | 3553 | attr.write = false; |
| | 3554 | break :attr attr; |
| | 3555 | } else attributes; |
| | 3556 | |
| 1454 | const object_section_gop = try coff.object_section_table.getOrPut(gpa, name); | 3557 | const object_section_gop = try coff.object_section_table.getOrPut(gpa, name); |
| 1455 | const osmi: Node.ObjectSectionMapIndex = @enumFromInt(object_section_gop.index); | 3558 | const osmi: Node.ObjectSectionMapIndex = @enumFromInt(object_section_gop.index); |
| 1456 | if (!object_section_gop.found_existing) { | 3559 | const sym = if (!object_section_gop.found_existing) sym: { |
| 1457 | try coff.ensureUnusedStringCapacity(name.toSlice(coff).len); | 3560 | try coff.ensureUnusedStringCapacity(name_slice.len); |
| 1458 | const name_slice = name.toSlice(coff); | 3561 | const parent_name = coff.getOrPutStringAssumeCapacity(coff.objectSectionParentName(name_slice)); |
| 1459 | const parent = (try coff.pseudoSectionMapIndex(coff.getOrPutStringAssumeCapacity( | 3562 | const parent = (try coff.pseudoSectionMapIndex(parent_name, alignment, effective_attributes)).symbol(coff); |
| 1460 | name_slice[0 .. std.mem.indexOfScalar(u8, name_slice, '$') orelse name_slice.len], | | |
| 1461 | ), alignment, attributes)).symbol(coff); | | |
| 1462 | try coff.nodes.ensureUnusedCapacity(gpa, 1); | 3563 | try coff.nodes.ensureUnusedCapacity(gpa, 1); |
| 1463 | try coff.symbol_table.ensureUnusedCapacity(gpa, 1); | 3564 | try coff.symbols.ensureUnusedCapacity(gpa, 1); |
| 1464 | const parent_ni = parent.node(coff); | 3565 | const parent_ni = parent.node(coff); |
| 1465 | var prev_ni: MappedFile.Node.Index = .none; | 3566 | var prev_ni: MappedFile.Node.Index = .none; |
| 1466 | var next_it = parent_ni.children(&coff.mf); | 3567 | var next_it = parent_ni.children(&coff.mf); |
| ... | @@ -1492,30 +3593,219 @@ fn objectSectionMapIndex( | ... | @@ -1492,30 +3593,219 @@ fn objectSectionMapIndex( |
| 1492 | assert(sym.loc_relocs == .none); | 3593 | assert(sym.loc_relocs == .none); |
| 1493 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); | 3594 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| 1494 | coff.nodes.appendAssumeCapacity(.{ .object_section = osmi }); | 3595 | coff.nodes.appendAssumeCapacity(.{ .object_section = osmi }); |
| | 3596 | break :sym sym; |
| | 3597 | } else object_section_gop.value_ptr.get(coff); |
| | 3598 | |
| | 3599 | const parent_ni = sym.ni.parent(&coff.mf); |
| | 3600 | const parent_alignment = parent_ni.alignment(&coff.mf); |
| | 3601 | if (alignment.compare(.gt, parent_alignment)) { |
| | 3602 | log.debug("realignParent({s}, {d}) {d}->{d}", .{ name.toSlice(coff), parent_ni, parent_alignment, alignment }); |
| | 3603 | try parent_ni.realign(&coff.mf, gpa, alignment, .{ .set_alignment = true }); |
| | 3604 | } |
| | 3605 | |
| | 3606 | const old_alignment = sym.ni.alignment(&coff.mf); |
| | 3607 | if (alignment.compare(.gt, old_alignment)) { |
| | 3608 | log.debug("realignObject({s}) {d}->{d}", .{ name.toSlice(coff), old_alignment, alignment }); |
| | 3609 | try sym.ni.realign(&coff.mf, gpa, alignment, .{ .set_alignment = true }); |
| 1495 | } | 3610 | } |
| | 3611 | |
| | 3612 | try coff.verifyParentSectionAttributes( |
| | 3613 | sym.section_number, |
| | 3614 | name, |
| | 3615 | .object, |
| | 3616 | .fromFlags(sym.section_number.header(coff).flags), |
| | 3617 | effective_attributes, |
| | 3618 | ); |
| | 3619 | |
| 1496 | return osmi; | 3620 | return osmi; |
| 1497 | } | 3621 | } |
| 1498 | | 3622 | |
| | 3623 | fn verifyParentSectionAttributes( |
| | 3624 | coff: *Coff, |
| | 3625 | parent: Symbol.SectionNumber, |
| | 3626 | child_name: String, |
| | 3627 | child_kind: enum { pseudo, object }, |
| | 3628 | parent_attrs: ObjectSectionAttributes, |
| | 3629 | child_attrs: ObjectSectionAttributes, |
| | 3630 | ) !void { |
| | 3631 | if (parent_attrs == child_attrs) return; |
| | 3632 | |
| | 3633 | const was_merged = switch (child_kind) { |
| | 3634 | .pseudo => coff.section_merges.contains(child_name), |
| | 3635 | .object => if (coff.getString( |
| | 3636 | coff.objectSectionParentName(child_name.toSlice(coff)), |
| | 3637 | ).unwrap()) |pseudo_name| |
| | 3638 | coff.section_merges.contains(pseudo_name) |
| | 3639 | else |
| | 3640 | false, |
| | 3641 | }; |
| | 3642 | |
| | 3643 | // The section was intentionally merged by the user or builtin rule |
| | 3644 | if (was_merged) return; |
| | 3645 | |
| | 3646 | const BackingT = @typeInfo(ObjectSectionAttributes).@"struct".backing_integer.?; |
| | 3647 | const num_notes = @popCount(@as(BackingT, @bitCast(parent_attrs)) ^ @as(BackingT, @bitCast(child_attrs))); |
| | 3648 | var err = try coff.base.comp.link_diags.addErrorWithNotes(num_notes); |
| | 3649 | try err.addMsg("{t} section '{s}' was placed in parent section '{s}' with mismatched flags", .{ |
| | 3650 | child_kind, |
| | 3651 | child_name.toSlice(coff), |
| | 3652 | parent.name(coff).toSlice(coff), |
| | 3653 | }); |
| | 3654 | |
| | 3655 | inline for (comptime std.meta.fieldNames(ObjectSectionAttributes)) |field| { |
| | 3656 | if (@field(child_attrs, field) != @field(parent_attrs, field)) { |
| | 3657 | err.addNote("flags.{s} was {d} in {s}, but {d} in {s}", .{ |
| | 3658 | field, |
| | 3659 | @intFromBool(@field(child_attrs, field)), |
| | 3660 | child_name.toSlice(coff), |
| | 3661 | @intFromBool(@field(parent_attrs, field)), |
| | 3662 | parent.name(coff).toSlice(coff), |
| | 3663 | }); |
| | 3664 | } |
| | 3665 | } |
| | 3666 | |
| | 3667 | return error.AlreadyReported; |
| | 3668 | } |
| | 3669 | |
| | 3670 | const RelocAddend = union(enum) { |
| | 3671 | known: i64, |
| | 3672 | /// Relocs tables in input objects don't include the addend. |
| | 3673 | /// The value needs to be recovered from the reloc location. |
| | 3674 | pending: void, |
| | 3675 | }; |
| | 3676 | |
| | 3677 | // TODO: There should be an API where the caller can indicate how many contiguous relocs they need |
| | 3678 | // and it should attempt to allocate these from from the free list if available. We can cache |
| | 3679 | // the run length of each segment on Reloc when `free` is set. |
| 1499 | pub fn addReloc( | 3680 | pub fn addReloc( |
| 1500 | coff: *Coff, | 3681 | coff: *Coff, |
| 1501 | loc_si: Symbol.Index, | 3682 | loc_si: Symbol.Index, |
| 1502 | offset: u64, | 3683 | offset: u64, |
| 1503 | target_si: Symbol.Index, | 3684 | target_si: Symbol.Index, |
| 1504 | addend: i64, | 3685 | addend: RelocAddend, |
| | 3686 | @"type": Reloc.Type, |
| | 3687 | ) link.Error!void { |
| | 3688 | const diags = &coff.base.comp.link_diags; |
| | 3689 | try coff.ensureUnusedRelocCapacity(loc_si, 1); |
| | 3690 | coff.addRelocAssumeCapacity(loc_si, offset, target_si, addend, @"type") catch |err| switch (err) { |
| | 3691 | error.MappedFileIo => return diags.fail( |
| | 3692 | "failed to write output file: {t}", |
| | 3693 | .{coff.mf.io_err.?}, |
| | 3694 | ), |
| | 3695 | else => |e| return e, |
| | 3696 | }; |
| | 3697 | } |
| | 3698 | |
| | 3699 | fn ensureUnusedRelocCapacity(coff: *Coff, loc_si: Symbol.Index, len: usize) !void { |
| | 3700 | const gpa = coff.base.comp.gpa; |
| | 3701 | try coff.relocs.ensureUnusedCapacity(gpa, len); |
| | 3702 | if (isImage(coff)) return; |
| | 3703 | switch (loc_si.get(coff).section_number) { |
| | 3704 | .UNDEFINED, .ABSOLUTE, .DEBUG => {}, |
| | 3705 | else => |loc_sn| { |
| | 3706 | const section = loc_sn.section(coff); |
| | 3707 | if (section.relocation_table_ni == .none) |
| | 3708 | try coff.nodes.ensureUnusedCapacity(gpa, 1); |
| | 3709 | }, |
| | 3710 | } |
| | 3711 | } |
| | 3712 | |
| | 3713 | fn addRelocAssumeCapacity( |
| | 3714 | coff: *Coff, |
| | 3715 | loc_si: Symbol.Index, |
| | 3716 | offset: u64, |
| | 3717 | target_si: Symbol.Index, |
| | 3718 | addend: RelocAddend, |
| 1505 | @"type": Reloc.Type, | 3719 | @"type": Reloc.Type, |
| 1506 | ) !void { | 3720 | ) !void { |
| 1507 | const gpa = coff.base.comp.gpa; | 3721 | const gpa = coff.base.comp.gpa; |
| 1508 | const target = target_si.get(coff); | 3722 | const target = target_si.get(coff); |
| | 3723 | |
| 1509 | const ri: Reloc.Index = @enumFromInt(coff.relocs.items.len); | 3724 | const ri: Reloc.Index = @enumFromInt(coff.relocs.items.len); |
| 1510 | (try coff.relocs.addOne(gpa)).* = .{ | 3725 | log.debug("addReloc({d}@{d}+0x{x} -> {d}@{d}+0x{x}{s}) = {d}", .{ |
| | 3726 | loc_si, |
| | 3727 | loc_si.get(coff).section_number, |
| | 3728 | offset, |
| | 3729 | target_si, |
| | 3730 | target_si.get(coff).section_number, |
| | 3731 | if (addend == .pending) 0 else addend.known, |
| | 3732 | if (addend == .pending) "p" else "k", |
| | 3733 | ri, |
| | 3734 | }); |
| | 3735 | |
| | 3736 | const sri: Section.RelocationIndex = if (isImage(coff)) |
| | 3737 | .none |
| | 3738 | else switch (loc_si.get(coff).section_number) { |
| | 3739 | .UNDEFINED, |
| | 3740 | .ABSOLUTE, |
| | 3741 | .DEBUG, |
| | 3742 | => .none, |
| | 3743 | else => |loc_sn| sri: { |
| | 3744 | // The target may not have a node yet, or it could be an extern that will never |
| | 3745 | // have a node. In that case, flushGlobal will create the symbol table entry. |
| | 3746 | const existing_sti = target_si.sti(coff); |
| | 3747 | const sti: SymbolTable.Index = if (existing_sti != .none) |
| | 3748 | existing_sti |
| | 3749 | else if (target.ni != .none) sti: { |
| | 3750 | try coff.pendingSymbolTableEntry(target_si); |
| | 3751 | break :sti .none; |
| | 3752 | } else .none; |
| | 3753 | |
| | 3754 | const sri: Section.RelocationIndex = blk: { |
| | 3755 | const section = loc_sn.section(coff); |
| | 3756 | const header = loc_sn.header(coff); |
| | 3757 | const old_num_relocations = coff.targetLoad(&header.number_of_relocations); |
| | 3758 | const new_num_relocations = old_num_relocations + 1; |
| | 3759 | const new_size = @as(u32, new_num_relocations) * std.coff.Relocation.sizeOf(); |
| | 3760 | |
| | 3761 | coff.targetStore(&header.number_of_relocations, new_num_relocations); |
| | 3762 | if (coff.symbolTableSectionAuxEntryPtr(loc_sn.symbol(coff).sti(coff))) |aux_ptr| |
| | 3763 | coff.targetStore(&aux_ptr.number_of_relocations, new_num_relocations); |
| | 3764 | |
| | 3765 | if (section.relocation_table_ni == .none) { |
| | 3766 | section.relocation_table_ni = try coff.mf.addLastChildNode( |
| | 3767 | gpa, |
| | 3768 | coff.sectionParent(), |
| | 3769 | .{ |
| | 3770 | .size = new_size, |
| | 3771 | .alignment = .@"2", |
| | 3772 | .moved = true, |
| | 3773 | .resized = true, |
| | 3774 | }, |
| | 3775 | ); |
| | 3776 | coff.nodes.appendAssumeCapacity(.{ .relocation_table = loc_sn }); |
| | 3777 | } else { |
| | 3778 | try section.relocation_table_ni.resize(&coff.mf, gpa, new_size); |
| | 3779 | } |
| | 3780 | |
| | 3781 | // TODO: These need to allocate from a free list, once deleting relocs from the table is supported |
| | 3782 | break :blk .wrap(old_num_relocations); |
| | 3783 | }; |
| | 3784 | |
| | 3785 | const entry = sri.entry(coff, loc_sn).?; |
| | 3786 | if (sti.unwrap()) |index| coff.targetStore(&entry.symbol_table_index, index); |
| | 3787 | |
| | 3788 | // applyLocationRelocs updates `virtual_address` |
| | 3789 | // flushSymbolTableIndex updates `symbol_table_index` |
| | 3790 | coff.targetStore(&entry.type, @bitCast(@"type")); |
| | 3791 | |
| | 3792 | break :sri sri; |
| | 3793 | }, |
| | 3794 | }; |
| | 3795 | |
| | 3796 | coff.relocs.addOneAssumeCapacity().* = .{ |
| 1511 | .type = @"type", | 3797 | .type = @"type", |
| 1512 | .prev = .none, | 3798 | .prev = .none, |
| 1513 | .next = target.target_relocs, | 3799 | .next = target.target_relocs, |
| 1514 | .loc = loc_si, | 3800 | .loc = loc_si, |
| 1515 | .target = target_si, | 3801 | .target = target_si, |
| 1516 | .unused = 0, | 3802 | .sri = sri, |
| 1517 | .offset = offset, | 3803 | .offset = offset, |
| 1518 | .addend = addend, | 3804 | .addend = if (addend == .pending) 0 else addend.known, |
| | 3805 | .flags = .{ |
| | 3806 | .recover_addend = addend == .pending, |
| | 3807 | .free = false, |
| | 3808 | }, |
| 1519 | }; | 3809 | }; |
| 1520 | switch (target.target_relocs) { | 3810 | switch (target.target_relocs) { |
| 1521 | .none => {}, | 3811 | .none => {}, |
| ... | @@ -1524,15 +3814,1641 @@ pub fn addReloc( | ... | @@ -1524,15 +3814,1641 @@ pub fn addReloc( |
| 1524 | target.target_relocs = ri; | 3814 | target.target_relocs = ri; |
| 1525 | } | 3815 | } |
| 1526 | | 3816 | |
| | 3817 | fn failLoadInput( |
| | 3818 | coff: *Coff, |
| | 3819 | err: LoadInputError, |
| | 3820 | fr: *Io.File.Reader, |
| | 3821 | path: std.Build.Cache.Path, |
| | 3822 | ) link.Error { |
| | 3823 | const diags = &coff.base.comp.link_diags; |
| | 3824 | switch (err) { |
| | 3825 | else => |e| return e, |
| | 3826 | error.MappedFileIo => return diags.fail( |
| | 3827 | "failed to write output file: {t}", |
| | 3828 | .{coff.mf.io_err.?}, |
| | 3829 | ), |
| | 3830 | error.EndOfStream => return diags.failParse( |
| | 3831 | path, |
| | 3832 | "unexpected eof", |
| | 3833 | .{}, |
| | 3834 | ), |
| | 3835 | error.AccessDenied, |
| | 3836 | error.Unexpected, |
| | 3837 | error.Unseekable, |
| | 3838 | => |e| return diags.fail( |
| | 3839 | "failed to read \"{f}\": {t}", |
| | 3840 | .{ path.fmtEscapeString(), e }, |
| | 3841 | ), |
| | 3842 | error.PermissionDenied, |
| | 3843 | error.SystemResources, |
| | 3844 | error.Streaming, |
| | 3845 | => |e| return diags.fail( |
| | 3846 | "failed to stat \"{f}\": {t}", |
| | 3847 | .{ path.fmtEscapeString(), e }, |
| | 3848 | ), |
| | 3849 | error.ReadFailed => switch (fr.err.?) { |
| | 3850 | error.Canceled => |e| return e, |
| | 3851 | else => |e| return diags.fail( |
| | 3852 | "failed to read \"{f}\": {t}", |
| | 3853 | .{ path.fmtEscapeString(), e }, |
| | 3854 | ), |
| | 3855 | }, |
| | 3856 | } |
| | 3857 | } |
| | 3858 | |
| | 3859 | pub fn loadInput(coff: *Coff, input: link.Input) link.Error!void { |
| | 3860 | const comp = coff.base.comp; |
| | 3861 | const io = comp.io; |
| | 3862 | |
| | 3863 | const path = input.path() orelse unreachable; |
| | 3864 | const gop = try coff.inputs.getOrPut(comp.gpa, path); |
| | 3865 | if (gop.found_existing) return; |
| | 3866 | errdefer _ = coff.inputs.swapRemove(path); |
| | 3867 | |
| | 3868 | var buf: [4096]u8 = undefined; |
| | 3869 | switch (input) { |
| | 3870 | .object => |object| { |
| | 3871 | var fr = object.file.reader(io, &buf); |
| | 3872 | coff.loadObject(object.path, null, &fr, .{ |
| | 3873 | .offset = fr.logicalPos(), |
| | 3874 | .size = fr.getSize() catch |err| |
| | 3875 | return coff.failLoadInput(err, &fr, object.path), |
| | 3876 | }) catch |err| return coff.failLoadInput(err, &fr, object.path); |
| | 3877 | }, |
| | 3878 | .archive => |archive| { |
| | 3879 | var fr = archive.file.reader(io, &buf); |
| | 3880 | coff.loadArchive(archive.path, &fr) catch |err| |
| | 3881 | return coff.failLoadInput(err, &fr, archive.path); |
| | 3882 | }, |
| | 3883 | .res => |res| { |
| | 3884 | var fr = res.file.reader(io, &buf); |
| | 3885 | coff.loadRes(res.path, &fr) catch |err| |
| | 3886 | return coff.failLoadInput(err, &fr, res.path); |
| | 3887 | }, |
| | 3888 | .dso => |dso| { |
| | 3889 | var fr = dso.file.reader(io, &buf); |
| | 3890 | coff.loadDll(dso.path, &fr) catch |err| |
| | 3891 | return coff.failLoadInput(err, &fr, dso.path); |
| | 3892 | }, |
| | 3893 | .dso_exact => unreachable, |
| | 3894 | } |
| | 3895 | } |
| | 3896 | |
| | 3897 | fn fmtMemberNameString(memberName: ?[]const u8) std.fmt.Alt(?[]const u8, memberNameStringEscape) { |
| | 3898 | return .{ .data = memberName }; |
| | 3899 | } |
| | 3900 | |
| | 3901 | fn memberNameStringEscape(memberName: ?[]const u8, w: *std.Io.Writer) std.Io.Writer.Error!void { |
| | 3902 | try w.print("({f})", .{std.zig.fmtString(memberName orelse return)}); |
| | 3903 | } |
| | 3904 | |
| | 3905 | fn inputSectionHeaderNameSlice( |
| | 3906 | coff: *Coff, |
| | 3907 | header: *const std.coff.SectionHeader, |
| | 3908 | string_table: []const u8, |
| | 3909 | path: std.Build.Cache.Path, |
| | 3910 | section_i: usize, |
| | 3911 | ) ![]const u8 { |
| | 3912 | const diags = &coff.base.comp.link_diags; |
| | 3913 | return if (header.name[0] == '/') name: { |
| | 3914 | const offset_str = std.mem.sliceTo(header.name[1..], 0); |
| | 3915 | const name_offset = std.fmt.parseUnsigned(u24, offset_str, 10) catch |
| | 3916 | return diags.failParse(path, "ill-formed section name in section {d}: '{s}'", .{ |
| | 3917 | section_i, |
| | 3918 | header.name[0 .. offset_str.len + 1], |
| | 3919 | }); |
| | 3920 | |
| | 3921 | if (name_offset > string_table.len) |
| | 3922 | return diags.failParse(path, "out-of-bounds section name offset in section {d}: {d}", .{ section_i, name_offset }); |
| | 3923 | |
| | 3924 | break :name std.mem.sliceTo(string_table[name_offset..], 0); |
| | 3925 | } else std.mem.sliceTo(&header.name, 0); |
| | 3926 | } |
| | 3927 | |
| | 3928 | fn loadObject( |
| | 3929 | coff: *Coff, |
| | 3930 | path: std.Build.Cache.Path, |
| | 3931 | member_name: ?[]const u8, |
| | 3932 | fr: *Io.File.Reader, |
| | 3933 | fl: MappedFile.Node.FileLocation, |
| | 3934 | ) LoadInputError!void { |
| | 3935 | const comp = coff.base.comp; |
| | 3936 | const gpa = comp.gpa; |
| | 3937 | const diags = &comp.link_diags; |
| | 3938 | const r = &fr.interface; |
| | 3939 | const target = &comp.root_mod.resolved_target.result; |
| | 3940 | const target_endian = coff.targetEndian(); |
| | 3941 | const is_archive = coff.isArchive(); |
| | 3942 | assert(!coff.isObj()); |
| | 3943 | // We want to evaluate new merges as we see them in .drectve sections to avoid redundant work |
| | 3944 | assert(coff.section_merge_pending_index == coff.section_merges.count()); |
| | 3945 | |
| | 3946 | log.debug("loadObject({f}{f})", .{ path.fmtEscapeString(), fmtMemberNameString(member_name) }); |
| | 3947 | |
| | 3948 | const header = try r.peekStruct(std.coff.Header, .little); |
| | 3949 | if (header.machine != target.toCoffMachine()) |
| | 3950 | return diags.failParse(path, "machine mismatch: expected {t}, found {t}", .{ |
| | 3951 | target.toCoffMachine(), |
| | 3952 | header.machine, |
| | 3953 | }); |
| | 3954 | if (header.number_of_sections == 0) return; |
| | 3955 | if (@sizeOf(std.coff.Header) + @as(usize, header.number_of_sections) * @sizeOf(std.coff.SectionHeader) > fl.size) |
| | 3956 | return diags.failParse(path, "invalid section table", .{}); |
| | 3957 | const unexpected_header_flags: []const std.meta.FieldEnum(std.coff.Header.Flags) = &.{ |
| | 3958 | .RELOCS_STRIPPED, |
| | 3959 | .EXECUTABLE_IMAGE, |
| | 3960 | .AGGRESSIVE_WS_TRIM, |
| | 3961 | .RESERVED, |
| | 3962 | .BYTES_REVERSED_LO, |
| | 3963 | .DLL, |
| | 3964 | .BYTES_REVERSED_HI, |
| | 3965 | }; |
| | 3966 | inline for (unexpected_header_flags) |flag| |
| | 3967 | if (@field(header.flags, @tagName(flag))) |
| | 3968 | return diags.failParse(path, "unexpected flag set: {t}", .{flag}); |
| | 3969 | |
| | 3970 | if (header.size_of_optional_header != 0) |
| | 3971 | return diags.failParse(path, "unexpected optional header", .{}); |
| | 3972 | |
| | 3973 | const symbol_table_len = header.number_of_symbols * std.coff.Symbol.sizeOf(); |
| | 3974 | const symbol_table_end = header.pointer_to_symbol_table + symbol_table_len; |
| | 3975 | // String table length (which includes the length field) immediately trails the symbol table |
| | 3976 | if (symbol_table_end + @sizeOf(u32) > fl.size) |
| | 3977 | return diags.failParse(path, "bad symbol table location", .{}); |
| | 3978 | |
| | 3979 | try fr.seekTo(fl.offset + symbol_table_end); |
| | 3980 | const string_table_len = try r.peekInt(u32, target_endian); |
| | 3981 | if (string_table_len < @sizeOf(u32) or |
| | 3982 | symbol_table_end + string_table_len > fl.size) |
| | 3983 | return diags.failParse(path, "bad string table length: 0x{x}", .{string_table_len}); |
| | 3984 | |
| | 3985 | const ioi: InputObject.Index = @enumFromInt(coff.input_objects.items.len); |
| | 3986 | try coff.input_objects.ensureUnusedCapacity(gpa, 1); |
| | 3987 | const input = coff.input_objects.addOneAssumeCapacity(); |
| | 3988 | input.* = .{ |
| | 3989 | .path = path, |
| | 3990 | .member_name = if (member_name) |m| try gpa.dupe(u8, m) else null, |
| | 3991 | .source_name = .none, |
| | 3992 | }; |
| | 3993 | |
| | 3994 | const string_table = string_table: { |
| | 3995 | const string_table = try gpa.alloc(u8, string_table_len); |
| | 3996 | errdefer gpa.free(string_table); |
| | 3997 | try r.readSliceAll(string_table); |
| | 3998 | break :string_table string_table; |
| | 3999 | }; |
| | 4000 | defer gpa.free(string_table); |
| | 4001 | |
| | 4002 | try coff.ensureManyUnusedStringCapacity( |
| | 4003 | header.number_of_sections + header.number_of_symbols, |
| | 4004 | header.number_of_sections * 9 + |
| | 4005 | header.number_of_symbols * 9 + |
| | 4006 | string_table_len - @sizeOf(u32), |
| | 4007 | ); |
| | 4008 | |
| | 4009 | const PendingSymbolIndex = enum(u32) { |
| | 4010 | none, |
| | 4011 | _, |
| | 4012 | |
| | 4013 | pub fn wrap(i: ?u32) @This() { |
| | 4014 | return @enumFromInt((i orelse return .none) + 1); |
| | 4015 | } |
| | 4016 | |
| | 4017 | pub fn unwrap(i: @This()) ?u32 { |
| | 4018 | return switch (i) { |
| | 4019 | .none => null, |
| | 4020 | _ => @intFromEnum(i) - 1, |
| | 4021 | }; |
| | 4022 | } |
| | 4023 | }; |
| | 4024 | |
| | 4025 | const PendingInputSection = struct { |
| | 4026 | header: std.coff.SectionHeader, |
| | 4027 | name: String, |
| | 4028 | si: Symbol.Index, |
| | 4029 | parent_si: Symbol.Index, |
| | 4030 | psi: PendingSymbolIndex, |
| | 4031 | num_symbols: u32, |
| | 4032 | comdat: std.coff.ComdatSelection, |
| | 4033 | comdat_psi: PendingSymbolIndex, |
| | 4034 | comdat_crc: u32, |
| | 4035 | comdat_association: Symbol.SectionNumber, |
| | 4036 | comdat_result: union(enum) { |
| | 4037 | pending, |
| | 4038 | // Root of the association chain |
| | 4039 | pending_association: Symbol.SectionNumber, |
| | 4040 | include, |
| | 4041 | skip, |
| | 4042 | }, |
| | 4043 | }; |
| | 4044 | |
| | 4045 | const sections: []PendingInputSection = if (coff.isImage()) sections: { |
| | 4046 | const sections = try gpa.alloc(PendingInputSection, header.number_of_sections); |
| | 4047 | errdefer gpa.free(sections); |
| | 4048 | |
| | 4049 | try fr.seekTo(fl.offset + @sizeOf(std.coff.Header)); |
| | 4050 | for (sections, 0..) |*section, section_i| { |
| | 4051 | section.* = .{ |
| | 4052 | .header = try r.takeStruct(std.coff.SectionHeader, target_endian), |
| | 4053 | .name = undefined, |
| | 4054 | .si = .null, |
| | 4055 | .parent_si = .null, |
| | 4056 | .psi = .none, |
| | 4057 | .num_symbols = 0, |
| | 4058 | .comdat = .NONE, |
| | 4059 | .comdat_psi = .none, |
| | 4060 | .comdat_crc = 0, |
| | 4061 | .comdat_association = .UNDEFINED, |
| | 4062 | .comdat_result = .pending, |
| | 4063 | }; |
| | 4064 | |
| | 4065 | const section_name_slice = if (section.header.name[0] == '/') name: { |
| | 4066 | const offset_str = std.mem.sliceTo(section.header.name[1..], 0); |
| | 4067 | const name_offset = std.fmt.parseUnsigned(u24, offset_str, 10) catch |
| | 4068 | return diags.failParse(path, "ill-formed section name offset in section {d}: '{s}'", .{ |
| | 4069 | section_i, |
| | 4070 | section.header.name[0 .. offset_str.len + 1], |
| | 4071 | }); |
| | 4072 | |
| | 4073 | if (name_offset > string_table.len) |
| | 4074 | return diags.failParse( |
| | 4075 | path, |
| | 4076 | "out-of-bounds section name offset in section {d}: {d}", |
| | 4077 | .{ section_i, name_offset }, |
| | 4078 | ); |
| | 4079 | |
| | 4080 | break :name std.mem.sliceTo(string_table[name_offset..], 0); |
| | 4081 | } else std.mem.sliceTo(&section.header.name, 0); |
| | 4082 | section.name = coff.getOrPutStringAssumeCapacity(section_name_slice); |
| | 4083 | |
| | 4084 | if (section.header.pointer_to_linenumbers + |
| | 4085 | @as(u32, section.header.number_of_linenumbers) * std.coff.LineNumber.sizeOf() > fl.size) |
| | 4086 | return diags.failParse(path, "bad line numbers location in section {d} `{s}`", .{ |
| | 4087 | section_i, |
| | 4088 | section_name_slice, |
| | 4089 | }); |
| | 4090 | |
| | 4091 | if (section.header.pointer_to_relocations + |
| | 4092 | @as(u32, section.header.number_of_relocations) * std.coff.Relocation.sizeOf() > fl.size) |
| | 4093 | return diags.failParse(path, "bad relocations location in section {d} `{s}`", .{ |
| | 4094 | section_i, |
| | 4095 | section_name_slice, |
| | 4096 | }); |
| | 4097 | |
| | 4098 | if (section.header.pointer_to_raw_data + section.header.size_of_raw_data > fl.size) |
| | 4099 | return diags.failParse(path, "bad raw data location in section {d} `{s}`", .{ |
| | 4100 | section_i, |
| | 4101 | section_name_slice, |
| | 4102 | }); |
| | 4103 | } |
| | 4104 | |
| | 4105 | break :sections sections; |
| | 4106 | } else &.{}; |
| | 4107 | defer gpa.free(sections); |
| | 4108 | |
| | 4109 | const mi = if (is_archive) mi: { |
| | 4110 | try coff.nodes.ensureUnusedCapacity(gpa, 2); |
| | 4111 | try coff.members.ensureUnusedCapacity(gpa, 1); |
| | 4112 | const path_str = try path.toString(gpa); |
| | 4113 | defer gpa.free(path_str); |
| | 4114 | |
| | 4115 | const mi = try coff.addMemberAssumeCapacity(.coff, fl.size); |
| | 4116 | const member = mi.get(coff); |
| | 4117 | try member.initHeader(coff, path_str, header.time_date_stamp); |
| | 4118 | |
| | 4119 | { |
| | 4120 | // TODO: This should be deferred to an idle task (but resize it here!) |
| | 4121 | var nw: MappedFile.Node.Writer = undefined; |
| | 4122 | member.content_ni.writer(&coff.mf, gpa, &nw); |
| | 4123 | defer nw.deinit(); |
| | 4124 | |
| | 4125 | try fr.seekTo(fl.offset); |
| | 4126 | const written = nw.interface.sendFileAll(fr, .limited64(fl.size)) catch |err| switch (err) { |
| | 4127 | error.WriteFailed => return nw.err.?, |
| | 4128 | else => |e| return e, |
| | 4129 | }; |
| | 4130 | |
| | 4131 | if (written != fl.size) return error.EndOfStream; |
| | 4132 | } |
| | 4133 | |
| | 4134 | break :mi mi; |
| | 4135 | } else undefined; |
| | 4136 | |
| | 4137 | try fr.seekTo(fl.offset + header.pointer_to_symbol_table); |
| | 4138 | const symbol_size = std.coff.Symbol.sizeOf(); |
| | 4139 | |
| | 4140 | const PendingSymbol = struct { |
| | 4141 | name: String, |
| | 4142 | value: union(enum) { |
| | 4143 | // Size of the section |
| | 4144 | section: u32, |
| | 4145 | // If section is absolute, the symbol value. |
| | 4146 | // Otherwise, offset within the section. |
| | 4147 | static: u32, |
| | 4148 | // If section is undefined, the symbol size. |
| | 4149 | // If section is absolute, the symbol value. |
| | 4150 | // Otherwise offset within the section. |
| | 4151 | external: u32, |
| | 4152 | // The index of the target symbol of this weak external |
| | 4153 | weak_external: u32, |
| | 4154 | // Trails .weak_external |
| | 4155 | weak_external_aux: WeakExternalStrat, |
| | 4156 | }, |
| | 4157 | section_number: Symbol.SectionNumber, |
| | 4158 | si: Symbol.Index, |
| | 4159 | // If a weak external targets this symbol, the index of the weak external |
| | 4160 | weak_external_psi: PendingSymbolIndex, |
| | 4161 | }; |
| | 4162 | |
| | 4163 | var num_global_symbols: u32 = 0; |
| | 4164 | var pending_symbols: std.array_hash_map.Auto(u32, PendingSymbol) = .empty; |
| | 4165 | defer pending_symbols.deinit(gpa); |
| | 4166 | if (!is_archive) |
| | 4167 | try pending_symbols.ensureUnusedCapacity(gpa, header.number_of_symbols); |
| | 4168 | |
| | 4169 | var section_merges: std.ArrayList(struct { |
| | 4170 | from: String, |
| | 4171 | to: String, |
| | 4172 | }) = .empty; |
| | 4173 | defer section_merges.deinit(gpa); |
| | 4174 | |
| | 4175 | // Discover symbol names and COMDAT symbol mappings |
| | 4176 | var symbol_i: u32 = 0; |
| | 4177 | var num_included_symbols: u32 = 0; |
| | 4178 | while (symbol_i < header.number_of_symbols) { |
| | 4179 | var symbol: std.coff.Symbol = undefined; |
| | 4180 | @memcpy(std.mem.asBytes(&symbol)[0..symbol_size], try r.take(symbol_size)); |
| | 4181 | if (target_endian != native_endian) |
| | 4182 | std.mem.byteSwapAllFields(std.coff.Symbol, &symbol); |
| | 4183 | |
| | 4184 | const aux_symbols = if (symbol.number_of_aux_symbols > 0) |
| | 4185 | try r.take(symbol_size * symbol.number_of_aux_symbols) |
| | 4186 | else |
| | 4187 | &.{}; |
| | 4188 | defer symbol_i += symbol.number_of_aux_symbols + 1; |
| | 4189 | |
| | 4190 | const name = std.mem.sliceTo(if (std.mem.eql(u8, symbol.name[0..4], "\x00\x00\x00\x00")) name: { |
| | 4191 | const index = std.mem.readInt(u32, symbol.name[4..], target_endian); |
| | 4192 | if (index >= string_table.len) |
| | 4193 | return diags.failParse(path, "bad string offset for symbol 0x{x}", .{symbol_i}); |
| | 4194 | break :name string_table[index..]; |
| | 4195 | } else &symbol.name, 0); |
| | 4196 | |
| | 4197 | if (is_archive) { |
| | 4198 | if (switch (symbol.storage_class) { |
| | 4199 | .WEAK_EXTERNAL => true, |
| | 4200 | .EXTERNAL => symbol.section_number != .UNDEFINED, |
| | 4201 | else => false, |
| | 4202 | }) try coff.ensureMemberSymbol(mi, coff.getOrPutStringAssumeCapacity(name)); |
| | 4203 | |
| | 4204 | continue; |
| | 4205 | } |
| | 4206 | |
| | 4207 | switch (symbol.section_number) { |
| | 4208 | .UNDEFINED, .DEBUG, .ABSOLUTE => {}, |
| | 4209 | else => |sn| if (@intFromEnum(sn) > sections.len) |
| | 4210 | return diags.failParse(path, "out-of-bounds section number {d} in symbol 0x{x}", .{ sn, symbol_i }), |
| | 4211 | } |
| | 4212 | |
| | 4213 | const psi: PendingSymbolIndex = .wrap(@intCast(pending_symbols.count())); |
| | 4214 | const section_number: Symbol.SectionNumber = @enumFromInt(@intFromEnum(symbol.section_number)); |
| | 4215 | |
| | 4216 | const values: []const @FieldType(PendingSymbol, "value") = pending_symbols: switch (symbol.storage_class) { |
| | 4217 | .STATIC, .LABEL => |storage_class| switch (section_number) { |
| | 4218 | // TODO: Do we need to do anything with @feat.00? |
| | 4219 | // https://llvm.org/doxygen/namespacellvm_1_1COFF.html#aeffa16735e18df727a173beaf748c392 |
| | 4220 | .UNDEFINED, |
| | 4221 | .DEBUG, |
| | 4222 | => &.{}, |
| | 4223 | .ABSOLUTE => &.{.{ .static = symbol.value }}, |
| | 4224 | else => |sn| { |
| | 4225 | const section = &sections[sn.toIndex()]; |
| | 4226 | |
| | 4227 | // Section symbol |
| | 4228 | const is_section = storage_class == .STATIC and |
| | 4229 | symbol.value == 0 and |
| | 4230 | symbol.type == std.coff.SymType{ |
| | 4231 | .complex_type = .NULL, |
| | 4232 | .base_type = .NULL, |
| | 4233 | } and |
| | 4234 | symbol.number_of_aux_symbols > 0; |
| | 4235 | |
| | 4236 | if (is_section) { |
| | 4237 | if (symbol.number_of_aux_symbols > 1) |
| | 4238 | return diags.failParse(path, "invalid number of aux symbols for section symbol 0x{x}: {d}", .{ |
| | 4239 | symbol_i, |
| | 4240 | symbol.number_of_aux_symbols, |
| | 4241 | }); |
| | 4242 | |
| | 4243 | var section_def: std.coff.SectionDefinition = undefined; |
| | 4244 | @memcpy(std.mem.asBytes(&section_def)[0..symbol_size], aux_symbols[0..symbol_size]); |
| | 4245 | if (target_endian != native_endian) |
| | 4246 | std.mem.byteSwapAllFields(std.coff.SectionDefinition, &section_def); |
| | 4247 | |
| | 4248 | if (section_def.number_of_relocations != section.header.number_of_relocations) |
| | 4249 | return diags.failParse( |
| | 4250 | path, |
| | 4251 | "section aux symbol 0x{x} for '{s}' relocation count did not match section header: {d} vs {d}", |
| | 4252 | .{ symbol_i + 1, name, section_def.number_of_relocations, section.header.number_of_relocations }, |
| | 4253 | ); |
| | 4254 | |
| | 4255 | if (section_def.number_of_linenumbers != section.header.number_of_linenumbers) |
| | 4256 | return diags.failParse( |
| | 4257 | path, |
| | 4258 | "section aux symbol 0x{x} for '{s}' line number count did not match section header: {d} vs {d}", |
| | 4259 | .{ symbol_i + 1, name, section_def.number_of_linenumbers, section.header.number_of_linenumbers }, |
| | 4260 | ); |
| | 4261 | |
| | 4262 | if (section.header.flags.LNK_COMDAT) { |
| | 4263 | if (section_def.selection == .ASSOCIATIVE) { |
| | 4264 | if (section_def.number == 0 or section_def.number > sections.len) |
| | 4265 | return diags.failParse( |
| | 4266 | path, |
| | 4267 | "section aux symbol 0x{x} for '{s}' contained an invalid associated section number: 0x{x}", |
| | 4268 | .{ symbol_i + 1, name, section_def.number }, |
| | 4269 | ); |
| | 4270 | |
| | 4271 | section.comdat_association = @enumFromInt(section_def.number); |
| | 4272 | } |
| | 4273 | |
| | 4274 | section.comdat = section_def.selection; |
| | 4275 | section.comdat_crc = section_def.checksum; |
| | 4276 | } |
| | 4277 | |
| | 4278 | section.psi = psi; |
| | 4279 | } |
| | 4280 | |
| | 4281 | break :pending_symbols &.{if (is_section) |
| | 4282 | .{ .section = section.header.size_of_raw_data } |
| | 4283 | else |
| | 4284 | .{ .static = symbol.value }}; |
| | 4285 | }, |
| | 4286 | }, |
| | 4287 | .WEAK_EXTERNAL => switch (symbol.section_number) { |
| | 4288 | .UNDEFINED => { |
| | 4289 | if (symbol.value != 0) |
| | 4290 | return diags.failParse( |
| | 4291 | path, |
| | 4292 | "invalid value {d} for weak external symbol 0x{x}", |
| | 4293 | .{ symbol.value, symbol_i }, |
| | 4294 | ); |
| | 4295 | |
| | 4296 | var weak_external: std.coff.WeakExternalDefinition = undefined; |
| | 4297 | @memcpy(std.mem.asBytes(&weak_external)[0..symbol_size], aux_symbols[0..symbol_size]); |
| | 4298 | if (target_endian != native_endian) |
| | 4299 | std.mem.byteSwapAllFields(std.coff.WeakExternalDefinition, &weak_external); |
| | 4300 | |
| | 4301 | if (weak_external.tag_index >= header.number_of_symbols) |
| | 4302 | return diags.failParse( |
| | 4303 | path, |
| | 4304 | "invalid tag_index 0x{x} for weak external symbol 0x{x}", |
| | 4305 | .{ weak_external.tag_index, symbol_i }, |
| | 4306 | ); |
| | 4307 | |
| | 4308 | break :pending_symbols switch (weak_external.flag) { |
| | 4309 | else => |flag| &.{ |
| | 4310 | .{ .weak_external = weak_external.tag_index }, |
| | 4311 | .{ .weak_external_aux = WeakExternalStrat.fromFlag(flag) }, |
| | 4312 | }, |
| | 4313 | _ => return diags.failParse( |
| | 4314 | path, |
| | 4315 | "encountered unknown weak external characteristic 0x{x} for symbol 0x{x}", |
| | 4316 | .{ weak_external.flag, symbol_i }, |
| | 4317 | ), |
| | 4318 | }; |
| | 4319 | }, |
| | 4320 | else => |sn| return diags.failParse( |
| | 4321 | path, |
| | 4322 | "invalid section number {d} for weak external symbol 0x{x}", |
| | 4323 | .{ sn, symbol_i }, |
| | 4324 | ), |
| | 4325 | }, |
| | 4326 | .EXTERNAL => switch (section_number) { |
| | 4327 | .UNDEFINED, |
| | 4328 | .ABSOLUTE, |
| | 4329 | => &.{.{ .external = symbol.value }}, |
| | 4330 | .DEBUG => return diags.failParse( |
| | 4331 | path, |
| | 4332 | "unexpected external symbol 0x{x} in DEBUG section: '{s}'", |
| | 4333 | .{ symbol_i, name }, |
| | 4334 | ), |
| | 4335 | else => &.{.{ .external = symbol.value }}, |
| | 4336 | }, |
| | 4337 | .FILE => { |
| | 4338 | if (!std.mem.eql(u8, name, ".file")) |
| | 4339 | return diags.failParse( |
| | 4340 | path, |
| | 4341 | "unexpected symbol name '{s}' for file symbol 0x{x}", |
| | 4342 | .{ name, symbol_i }, |
| | 4343 | ); |
| | 4344 | |
| | 4345 | var file: std.coff.FileDefinition = undefined; |
| | 4346 | @memcpy(std.mem.asBytes(&file)[0..symbol_size], aux_symbols[0..symbol_size]); |
| | 4347 | |
| | 4348 | input.source_name = (try coff.getOrPutString(file.getFileName())).toOptional(); |
| | 4349 | break :pending_symbols &.{}; |
| | 4350 | }, |
| | 4351 | else => |storage_class| return diags.failParse( |
| | 4352 | path, |
| | 4353 | "TODO handle storage class {t} for symbol 0x{x}", |
| | 4354 | .{ storage_class, symbol_i }, |
| | 4355 | ), |
| | 4356 | }; |
| | 4357 | |
| | 4358 | for (values, 0..) |value, i| { |
| | 4359 | if (section_number == .ABSOLUTE) |
| | 4360 | num_included_symbols += 1; |
| | 4361 | |
| | 4362 | switch (value) { |
| | 4363 | .section => {}, |
| | 4364 | .static, |
| | 4365 | .external, |
| | 4366 | .weak_external, |
| | 4367 | => { |
| | 4368 | num_global_symbols += 1; |
| | 4369 | if (section_number.hasIndex()) { |
| | 4370 | const section = &sections[section_number.toIndex()]; |
| | 4371 | section.num_symbols += 1; |
| | 4372 | if (section.header.flags.LNK_COMDAT and section.comdat_psi == .none) |
| | 4373 | section.comdat_psi = psi; |
| | 4374 | } |
| | 4375 | }, |
| | 4376 | .weak_external_aux => {}, |
| | 4377 | } |
| | 4378 | |
| | 4379 | const symbol_name = coff.getOrPutStringAssumeCapacity(name); |
| | 4380 | pending_symbols.putAssumeCapacity(symbol_i + @as(u32, @intCast(i)), .{ |
| | 4381 | .name = symbol_name, |
| | 4382 | .value = value, |
| | 4383 | .section_number = section_number, |
| | 4384 | .si = .null, |
| | 4385 | .weak_external_psi = .none, |
| | 4386 | }); |
| | 4387 | } |
| | 4388 | } |
| | 4389 | |
| | 4390 | try coff.globals.ensureUnusedCapacity(gpa, num_global_symbols); |
| | 4391 | for (sections) |*section| { |
| | 4392 | if (section.header.flags.LNK_INFO) { |
| | 4393 | if (std.mem.eql(u8, &section.header.name, ".drectve")) { |
| | 4394 | try fr.seekTo(fl.offset + section.header.pointer_to_raw_data); |
| | 4395 | // TODO: Don't really want an additional buffer here, but want to limit to size_of_raw_data |
| | 4396 | var buf: [128]u8 = undefined; |
| | 4397 | var section_r = r.limited(.limited(section.header.size_of_raw_data), &buf); |
| | 4398 | while (section_r.interface.takeDelimiter(' ') catch |err| switch (err) { |
| | 4399 | error.StreamTooLong => return diags.failParse(path, "unexpectedly long .drectve argument", .{}), |
| | 4400 | else => |e| return e, |
| | 4401 | }) |arg| { |
| | 4402 | // Microsoft tools emit 3 space characters into this section even with /Zl |
| | 4403 | if (arg.len == 0) continue; |
| | 4404 | |
| | 4405 | if (std.ascii.startsWithIgnoreCase(arg, "-exclude-symbols:")) { |
| | 4406 | // TODO: When implementing mingw auto-exports (if at all?), track this to not export this symbol |
| | 4407 | } else if (std.ascii.startsWithIgnoreCase(arg, "/include:")) { |
| | 4408 | _ = try coff.globalSymbol(.{ .name = arg["/include:".len..] }); |
| | 4409 | } else if (std.ascii.startsWithIgnoreCase(arg, "/alternatename:")) { |
| | 4410 | var split = std.mem.splitScalar(u8, arg["/alternatename:".len..], '='); |
| | 4411 | const orig = split.first(); |
| | 4412 | const alt = split.next() orelse |
| | 4413 | return diags.failParse(path, "malformed .drectve argument: '{s}'", .{arg}); |
| | 4414 | |
| | 4415 | try coff.ensureManyUnusedStringCapacity(2, orig.len + alt.len + 2); |
| | 4416 | const orig_str = coff.getOrPutStringAssumeCapacity(orig); |
| | 4417 | const alt_str = coff.getOrPutStringAssumeCapacity(alt); |
| | 4418 | const gop = try coff.alternate_names.getOrPut(gpa, orig_str); |
| | 4419 | if (!gop.found_existing) { |
| | 4420 | log.debug("alternateName({s}={s})", .{ orig, alt }); |
| | 4421 | gop.value_ptr.* = alt_str; |
| | 4422 | } else if (gop.value_ptr.* != alt_str) |
| | 4423 | return diags.failParse( |
| | 4424 | path, |
| | 4425 | "conflicting /alternatename .drectve arguments: first seen as {s}={s}, now seen as {s}={s}", |
| | 4426 | .{ orig, gop.value_ptr.toSlice(coff), orig, alt }, |
| | 4427 | ); |
| | 4428 | } else if (std.ascii.startsWithIgnoreCase(arg, "/guardsym:")) { |
| | 4429 | // TODO: https://learn.microsoft.com/en-us/windows/win32/secbp/pe-metadata |
| | 4430 | } else if (std.ascii.startsWithIgnoreCase(arg, "/merge:")) merge: { |
| | 4431 | var split = std.mem.splitScalar(u8, arg["/merge:".len..], '='); |
| | 4432 | const from = split.first(); |
| | 4433 | const to = split.next() orelse |
| | 4434 | return diags.failParse(path, "malformed .drectve argument: '{s}'", .{arg}); |
| | 4435 | if (to.len > header_name_max_len) |
| | 4436 | return diags.failParse( |
| | 4437 | path, |
| | 4438 | "/merge .drectve target exceeds max length of {d}: '{s}'", |
| | 4439 | .{ header_name_max_len, arg }, |
| | 4440 | ); |
| | 4441 | if (std.mem.eql(u8, from, to)) break :merge; |
| | 4442 | |
| | 4443 | try coff.ensureManyUnusedStringCapacity(2, from.len + to.len + 2); |
| | 4444 | const from_str = coff.getOrPutStringAssumeCapacity(from); |
| | 4445 | const to_str = coff.getOrPutStringAssumeCapacity(to); |
| | 4446 | |
| | 4447 | { |
| | 4448 | var iter = to_str; |
| | 4449 | while (coff.section_merges.get(iter)) |next_to| { |
| | 4450 | if (next_to == from_str) |
| | 4451 | return diags.failParse( |
| | 4452 | path, |
| | 4453 | "/merge .drectve argument would create a cycle: {s}={s} leads to {s}={s}", |
| | 4454 | .{ from, to, iter.toSlice(coff), to }, |
| | 4455 | ); |
| | 4456 | |
| | 4457 | iter = next_to; |
| | 4458 | } |
| | 4459 | } |
| | 4460 | |
| | 4461 | try coff.section_merges.ensureUnusedCapacity(gpa, 1); |
| | 4462 | const gop = coff.section_merges.getOrPutAssumeCapacity(from_str); |
| | 4463 | if (!gop.found_existing) { |
| | 4464 | coff.synth_prog_node.increaseEstimatedTotalItems(1); |
| | 4465 | gop.value_ptr.* = to_str; |
| | 4466 | } else if (gop.value_ptr.* != to_str) |
| | 4467 | return diags.failParse( |
| | 4468 | path, |
| | 4469 | "conflicting /merge .drectve arguments: first seen as {s}={s}, now seen as {s}={s}", |
| | 4470 | .{ from, gop.value_ptr.toSlice(coff), from, to }, |
| | 4471 | ); |
| | 4472 | } else if (std.ascii.startsWithIgnoreCase(arg, "/disallowlib:")) { |
| | 4473 | const lib_name = arg["/disallowlib:".len..]; |
| | 4474 | // TODO: Track these and issue error in prelink if any match |
| | 4475 | _ = lib_name; |
| | 4476 | } else if (std.ascii.startsWithIgnoreCase(arg, "/defaultlib:")) { |
| | 4477 | const lib_path = arg["/defaultlib:".len..]; |
| | 4478 | const trim = std.mem.trim(u8, lib_path, "\""); |
| | 4479 | if (lib_path.len == trim.len or lib_path.len - 2 == trim.len) { |
| | 4480 | if (!comp.config.link_libc or comp.libc_installation == null) |
| | 4481 | return diags.failParse(path, "encountered /DEFAULTLIB .drectve argument when libc was not available: {s}", .{arg}); |
| | 4482 | |
| | 4483 | (try coff.pending_default_libs.addOne(gpa)).* = .{ |
| | 4484 | .path = try gpa.dupe(u8, lib_path), |
| | 4485 | .ioi = ioi, |
| | 4486 | }; |
| | 4487 | } else return diags.failParse( |
| | 4488 | path, |
| | 4489 | "malformed /DEFAULTLIB .drectve argument: `{s}`", |
| | 4490 | .{arg}, |
| | 4491 | ); |
| | 4492 | } else return diags.failParse(path, "unsupported argument in .drectve section: `{s}`", .{arg}); |
| | 4493 | } |
| | 4494 | } |
| | 4495 | |
| | 4496 | section.comdat_result = .skip; |
| | 4497 | continue; |
| | 4498 | } |
| | 4499 | |
| | 4500 | if (section.header.flags.LNK_REMOVE or |
| | 4501 | section.header.flags.MEM_DISCARDABLE) |
| | 4502 | { |
| | 4503 | // TODO: Convert .debug$* sections into PDB |
| | 4504 | section.comdat_result = .skip; |
| | 4505 | continue; |
| | 4506 | } |
| | 4507 | |
| | 4508 | section.comdat_result = comdat: switch (section.comdat) { |
| | 4509 | .NONE => .include, |
| | 4510 | .ASSOCIATIVE => { |
| | 4511 | // Associative COMDAT sections have no COMDAT symbol. |
| | 4512 | // They are linked if the assocated section is linked. |
| | 4513 | var iter = section; |
| | 4514 | var iter_sn = iter.comdat_association; |
| | 4515 | while (iter.comdat == .ASSOCIATIVE) { |
| | 4516 | iter = &sections[iter_sn.toIndex()]; |
| | 4517 | iter_sn = iter.comdat_association; |
| | 4518 | if (iter == section) |
| | 4519 | return diags.failParse( |
| | 4520 | path, |
| | 4521 | "circular COMDAT association loop detected, starting at symbol 0x{x}", |
| | 4522 | .{pending_symbols.keys()[section.psi.unwrap().?]}, |
| | 4523 | ); |
| | 4524 | } |
| | 4525 | |
| | 4526 | assert(iter != section); |
| | 4527 | break :comdat switch (iter.comdat_result) { |
| | 4528 | .pending => .{ .pending_association = iter_sn }, |
| | 4529 | else => |iter_result| iter_result, |
| | 4530 | }; |
| | 4531 | }, |
| | 4532 | else => |comdat| { |
| | 4533 | const psi = section.comdat_psi.unwrap() orelse section.psi.unwrap().?; |
| | 4534 | const symbol = &pending_symbols.values()[psi]; |
| | 4535 | const si = existing: switch (symbol.value) { |
| | 4536 | .weak_external => unreachable, |
| | 4537 | .weak_external_aux => unreachable, |
| | 4538 | .static => break :comdat .include, |
| | 4539 | .section => { |
| | 4540 | assert(section.comdat_psi == .none); |
| | 4541 | if (coff.object_section_table.get(section.name)) |si| |
| | 4542 | break :existing si |
| | 4543 | else if (coff.pseudo_section_table.get(section.name)) |si| |
| | 4544 | break :existing si |
| | 4545 | else if (coff.section_table.get(section.name)) |s| |
| | 4546 | break :existing s.si |
| | 4547 | else |
| | 4548 | break :comdat .include; |
| | 4549 | }, |
| | 4550 | .external => { |
| | 4551 | const global_gop = try coff.getOrPutGlobalSymbol(.{ |
| | 4552 | .name = symbol.name.toSlice(coff), |
| | 4553 | }); |
| | 4554 | |
| | 4555 | // TODO: What if the same symbol is incorrectly defined twice in this obj? |
| | 4556 | // Would need to mark this global as pending, or notice it later when .ni != none |
| | 4557 | if (!global_gop.found_existing or global_gop.value_ptr.si.get(coff).ni == .none) { |
| | 4558 | symbol.si = global_gop.value_ptr.si; |
| | 4559 | break :comdat .include; |
| | 4560 | } |
| | 4561 | |
| | 4562 | break :existing global_gop.value_ptr.si; |
| | 4563 | }, |
| | 4564 | }; |
| | 4565 | |
| | 4566 | const index = pending_symbols.keys()[psi]; |
| | 4567 | switch (comdat) { |
| | 4568 | .NODUPLICATES => return coff.failMultipleDefinitions( |
| | 4569 | path, |
| | 4570 | member_name, |
| | 4571 | symbol.name, |
| | 4572 | index, |
| | 4573 | si, |
| | 4574 | .duplicate, |
| | 4575 | ), |
| | 4576 | .ANY => { |
| | 4577 | symbol.si = si; |
| | 4578 | break :comdat .skip; |
| | 4579 | }, |
| | 4580 | .SAME_SIZE => { |
| | 4581 | // TODO: Verify that this node isn't resized after creation |
| | 4582 | _, const size = si.get(coff).ni.location(&coff.mf).resolve(&coff.mf); |
| | 4583 | if (size == section.header.size_of_raw_data) { |
| | 4584 | symbol.si = si; |
| | 4585 | break :comdat .skip; |
| | 4586 | } |
| | 4587 | |
| | 4588 | return coff.failMultipleDefinitions( |
| | 4589 | path, |
| | 4590 | member_name, |
| | 4591 | symbol.name, |
| | 4592 | index, |
| | 4593 | si, |
| | 4594 | .{ .size = .{ .a = size, .b = section.header.size_of_raw_data } }, |
| | 4595 | ); |
| | 4596 | }, |
| | 4597 | .EXACT_MATCH => { |
| | 4598 | const sym = si.get(coff); |
| | 4599 | const existing_crc = switch (coff.getNode(sym.ni)) { |
| | 4600 | .input_section => |isi| isi.inputSection(coff).crc, |
| | 4601 | else => std.hash.crc.Crc32Jamcrc.hash(sym.ni.sliceConst(&coff.mf)), |
| | 4602 | }; |
| | 4603 | |
| | 4604 | if (existing_crc == section.comdat_crc) { |
| | 4605 | symbol.si = si; |
| | 4606 | break :comdat .skip; |
| | 4607 | } |
| | 4608 | |
| | 4609 | return coff.failMultipleDefinitions( |
| | 4610 | path, |
| | 4611 | member_name, |
| | 4612 | symbol.name, |
| | 4613 | index, |
| | 4614 | si, |
| | 4615 | .{ .crc = .{ .a = existing_crc, .b = section.comdat_crc } }, |
| | 4616 | ); |
| | 4617 | }, |
| | 4618 | .LARGEST => { |
| | 4619 | // TODO: Resize existing .ni and replace with this section's contents |
| | 4620 | // TODO: This will be tricky, what to do about existing InputSection? |
| | 4621 | unreachable; |
| | 4622 | }, |
| | 4623 | .NONE, .ASSOCIATIVE, _ => unreachable, |
| | 4624 | } |
| | 4625 | }, |
| | 4626 | }; |
| | 4627 | } |
| | 4628 | |
| | 4629 | try coff.flushSectionMerges(); |
| | 4630 | |
| | 4631 | // Resolve pending associations, create parent sections |
| | 4632 | var num_included_sections: u16 = 0; |
| | 4633 | var num_included_relocs: u32 = 0; |
| | 4634 | for (sections) |*section| { |
| | 4635 | comdat: switch (section.comdat_result) { |
| | 4636 | .pending_association => |root_assoc_sn| { |
| | 4637 | const root_result = sections[root_assoc_sn.toIndex()].comdat_result; |
| | 4638 | assert(root_result != .pending_association); |
| | 4639 | section.comdat_result = root_result; |
| | 4640 | continue :comdat root_result; |
| | 4641 | }, |
| | 4642 | .include => {}, |
| | 4643 | .skip => { |
| | 4644 | assert(switch (section.comdat) { |
| | 4645 | .NONE, .ASSOCIATIVE => true, |
| | 4646 | else => if (section.comdat_psi.unwrap()) |psi| |
| | 4647 | pending_symbols.values()[psi].si != .null |
| | 4648 | else |
| | 4649 | pending_symbols.values()[section.psi.unwrap().?].si != .null, |
| | 4650 | }); |
| | 4651 | continue; |
| | 4652 | }, |
| | 4653 | .pending => unreachable, |
| | 4654 | } |
| | 4655 | |
| | 4656 | // Until we support sorting .pdata, we shouldn't merge these in, the result would be invalid |
| | 4657 | const section_name = section.name.toSlice(coff); |
| | 4658 | if (std.mem.startsWith(u8, section_name, ".pdata")) |
| | 4659 | continue; |
| | 4660 | |
| | 4661 | num_included_sections += 1; |
| | 4662 | num_included_symbols += section.num_symbols; |
| | 4663 | num_included_relocs += section.header.number_of_relocations; |
| | 4664 | |
| | 4665 | section.parent_si = (try coff.objectSectionMapIndex( |
| | 4666 | section.name, |
| | 4667 | section.header.flags.ALIGN.alignment() orelse .@"1", |
| | 4668 | .fromFlags(section.header.flags), |
| | 4669 | )).symbol(coff); |
| | 4670 | } |
| | 4671 | |
| | 4672 | try coff.nodes.ensureUnusedCapacity(gpa, num_included_sections); |
| | 4673 | try coff.relocs.ensureUnusedCapacity(gpa, num_included_relocs); |
| | 4674 | try coff.symbols.ensureUnusedCapacity(gpa, num_included_symbols + num_included_sections); |
| | 4675 | try coff.input_sections.ensureUnusedCapacity(gpa, num_included_sections); |
| | 4676 | |
| | 4677 | for (sections) |*section| { |
| | 4678 | if (section.parent_si == .null) continue; |
| | 4679 | |
| | 4680 | const ni = try coff.mf.addLastChildNode(gpa, section.parent_si.node(coff), .{ |
| | 4681 | .size = section.header.size_of_raw_data, |
| | 4682 | .alignment = section.header.flags.ALIGN.alignment() orelse .@"1", |
| | 4683 | .moved = true, |
| | 4684 | }); |
| | 4685 | coff.nodes.appendAssumeCapacity(.{ .input_section = @enumFromInt(coff.input_sections.items.len) }); |
| | 4686 | |
| | 4687 | section.si = coff.addSymbolAssumeCapacity(); |
| | 4688 | if (section.psi.unwrap()) |psi| |
| | 4689 | pending_symbols.values()[psi].si = section.si; |
| | 4690 | |
| | 4691 | const sym = section.si.get(coff); |
| | 4692 | sym.ni = ni; |
| | 4693 | sym.section_number = section.parent_si.get(coff).section_number; |
| | 4694 | |
| | 4695 | coff.input_sections.addOneAssumeCapacity().* = .{ |
| | 4696 | .ioi = ioi, |
| | 4697 | .si = section.si, |
| | 4698 | .file_location = .{ |
| | 4699 | .offset = fl.offset + section.header.pointer_to_raw_data, |
| | 4700 | .size = section.header.size_of_raw_data, |
| | 4701 | }, |
| | 4702 | .first_li = @enumFromInt(coff.input_symbols.items.len), |
| | 4703 | .crc = section.comdat_crc, |
| | 4704 | .comdat_si = if (section.comdat_psi.unwrap()) |psi| |
| | 4705 | pending_symbols.values()[psi].si |
| | 4706 | else |
| | 4707 | .null, |
| | 4708 | }; |
| | 4709 | |
| | 4710 | log.debug( |
| | 4711 | "addInputSection({s}, 0x{x}) = {d}@{d}", |
| | 4712 | .{ section.name.toSlice(coff), section.comdat_crc, section.si, sym.section_number }, |
| | 4713 | ); |
| | 4714 | coff.synth_prog_node.increaseEstimatedTotalItems(1); |
| | 4715 | } |
| | 4716 | |
| | 4717 | for (pending_symbols.values(), pending_symbols.keys(), 0..) |*symbol, index, i| { |
| | 4718 | switch (symbol.value) { |
| | 4719 | .weak_external_aux => continue, |
| | 4720 | else => {}, |
| | 4721 | } |
| | 4722 | |
| | 4723 | defer log.debug("addInputSymbol({s}, 0x{x}@{d}, {t}=0x{x}) = n{d} {d}@{d}", .{ |
| | 4724 | symbol.name.toSlice(coff), |
| | 4725 | index, |
| | 4726 | symbol.section_number, |
| | 4727 | symbol.value, |
| | 4728 | switch (symbol.value) { |
| | 4729 | .weak_external_aux => unreachable, |
| | 4730 | inline else => |v| v, |
| | 4731 | }, |
| | 4732 | symbol.si.get(coff).ni, |
| | 4733 | symbol.si, |
| | 4734 | symbol.si.get(coff).section_number, |
| | 4735 | }); |
| | 4736 | |
| | 4737 | const section = switch (symbol.section_number) { |
| | 4738 | .UNDEFINED => switch (symbol.value) { |
| | 4739 | .section, |
| | 4740 | .static, |
| | 4741 | .weak_external_aux, |
| | 4742 | => unreachable, |
| | 4743 | .external => { |
| | 4744 | if (symbol.weak_external_psi.unwrap()) |weak_external_i| { |
| | 4745 | // If the alias itself is an undef external, we need to wait until flushing the weak |
| | 4746 | // external global before creating a global for the alias, as another input could |
| | 4747 | // still provide the weak external. |
| | 4748 | const weak_sym = pending_symbols.values()[weak_external_i].si.get(coff); |
| | 4749 | weak_sym.setValue(.{ .weak_alias_name = symbol.name }); |
| | 4750 | weak_sym.flags.weak_external_strat = pending_symbols.values()[weak_external_i + 1].value.weak_external_aux; |
| | 4751 | } |
| | 4752 | |
| | 4753 | // Deferred until referenced by a reloc in this object. |
| | 4754 | // vcruntime.lib defines symbols like this (ie. memcpy_$fo$) that are not referenced |
| | 4755 | continue; |
| | 4756 | }, |
| | 4757 | .weak_external => |alias_index| { |
| | 4758 | const global_gop = try coff.getOrPutGlobalSymbol(.{ .name = symbol.name.toSlice(coff) }); |
| | 4759 | symbol.si = global_gop.value_ptr.si; |
| | 4760 | if (!global_gop.found_existing or symbol.si.get(coff).ni == .none) { |
| | 4761 | const sym = symbol.si.get(coff); |
| | 4762 | const alias = pending_symbols.getPtr(alias_index) orelse |
| | 4763 | return diags.failParse( |
| | 4764 | path, |
| | 4765 | "weak external 0x{x} {s}{f} targets unknown symbol index 0x{x}", |
| | 4766 | .{ |
| | 4767 | index, |
| | 4768 | symbol.name.toSlice(coff), |
| | 4769 | fmtMemberNameString(member_name), |
| | 4770 | alias_index, |
| | 4771 | }, |
| | 4772 | ); |
| | 4773 | |
| | 4774 | if (alias.si == .null and alias_index > index) { |
| | 4775 | // Resolve this once we see alias |
| | 4776 | alias.weak_external_psi = .wrap(@intCast(i)); |
| | 4777 | } else { |
| | 4778 | sym.setValue(if (alias.si.unwrap()) |alias_si| .{ |
| | 4779 | .weak_alias_si = alias_si, |
| | 4780 | } else .{ |
| | 4781 | .weak_alias_name = alias.name, |
| | 4782 | }); |
| | 4783 | sym.flags.weak_external_strat = pending_symbols.values()[i + 1].value.weak_external_aux; |
| | 4784 | } |
| | 4785 | } |
| | 4786 | |
| | 4787 | continue; |
| | 4788 | }, |
| | 4789 | }, |
| | 4790 | .ABSOLUTE => { |
| | 4791 | const value = sym: switch (symbol.value) { |
| | 4792 | .static => |value| { |
| | 4793 | symbol.si = coff.addSymbolAssumeCapacity(); |
| | 4794 | break :sym value; |
| | 4795 | }, |
| | 4796 | .external => |value| { |
| | 4797 | const global_gop = try coff.getOrPutGlobalSymbol(.{ .name = symbol.name.toSlice(coff) }); |
| | 4798 | symbol.si = global_gop.value_ptr.si; |
| | 4799 | if (global_gop.found_existing) |
| | 4800 | return coff.failMultipleDefinitions( |
| | 4801 | path, |
| | 4802 | member_name, |
| | 4803 | symbol.name, |
| | 4804 | index, |
| | 4805 | global_gop.value_ptr.si, |
| | 4806 | .none, |
| | 4807 | ); |
| | 4808 | break :sym value; |
| | 4809 | }, |
| | 4810 | else => unreachable, |
| | 4811 | }; |
| | 4812 | |
| | 4813 | const sym = symbol.si.get(coff); |
| | 4814 | sym.rva = value; |
| | 4815 | sym.section_number = .ABSOLUTE; |
| | 4816 | continue; |
| | 4817 | }, |
| | 4818 | .DEBUG => continue, |
| | 4819 | else => |sn| &sections[sn.toIndex()], |
| | 4820 | }; |
| | 4821 | |
| | 4822 | if (section.si == .null) |
| | 4823 | continue; |
| | 4824 | |
| | 4825 | if (symbol.si == .null) { |
| | 4826 | switch (symbol.value) { |
| | 4827 | .section => unreachable, |
| | 4828 | .static => { |
| | 4829 | symbol.si = coff.addSymbolAssumeCapacity(); |
| | 4830 | }, |
| | 4831 | .external => { |
| | 4832 | assert(index != section.comdat_psi.unwrap()); |
| | 4833 | const global_gop = try coff.getOrPutGlobalSymbol(.{ .name = symbol.name.toSlice(coff) }); |
| | 4834 | symbol.si = global_gop.value_ptr.si; |
| | 4835 | |
| | 4836 | const sym = symbol.si.get(coff); |
| | 4837 | if (global_gop.found_existing and sym.ni != .none) |
| | 4838 | return coff.failMultipleDefinitions( |
| | 4839 | path, |
| | 4840 | member_name, |
| | 4841 | symbol.name, |
| | 4842 | index, |
| | 4843 | global_gop.value_ptr.si, |
| | 4844 | .none, |
| | 4845 | ); |
| | 4846 | }, |
| | 4847 | .weak_external, |
| | 4848 | .weak_external_aux, |
| | 4849 | => unreachable, |
| | 4850 | } |
| | 4851 | |
| | 4852 | if (section.comdat_psi.unwrap() == @as(u32, @intCast(i))) |
| | 4853 | coff.getNode(section.si.get(coff).ni).input_section.inputSection(coff).comdat_si = symbol.si; |
| | 4854 | } |
| | 4855 | |
| | 4856 | if (symbol.weak_external_psi.unwrap()) |weak_external_i| { |
| | 4857 | assert(symbol.si != .null); |
| | 4858 | const weak_sym = pending_symbols.values()[weak_external_i].si.get(coff); |
| | 4859 | weak_sym.setValue(.{ .weak_alias_si = symbol.si }); |
| | 4860 | weak_sym.flags.weak_external_strat = pending_symbols.values()[weak_external_i + 1].value.weak_external_aux; |
| | 4861 | } |
| | 4862 | |
| | 4863 | if (section.si != symbol.si) { |
| | 4864 | const sym = symbol.si.get(coff); |
| | 4865 | assert(sym.ni == .none); |
| | 4866 | sym.ni = section.si.get(coff).ni; |
| | 4867 | switch (symbol.value) { |
| | 4868 | .section => |v| sym.setExtra(.{ .size = v }), |
| | 4869 | .static => |v| sym.setValue(.{ .node_offset = v }), |
| | 4870 | .external => |v| switch (symbol.section_number) { |
| | 4871 | .UNDEFINED, .ABSOLUTE, .DEBUG => unreachable, |
| | 4872 | else => sym.setValue(.{ .node_offset = v }), |
| | 4873 | }, |
| | 4874 | .weak_external, |
| | 4875 | .weak_external_aux, |
| | 4876 | => unreachable, |
| | 4877 | } |
| | 4878 | |
| | 4879 | sym.section_number = section.si.get(coff).section_number; |
| | 4880 | } |
| | 4881 | } |
| | 4882 | |
| | 4883 | const relocation_size = std.coff.Relocation.sizeOf(); |
| | 4884 | for (sections) |section| { |
| | 4885 | if (section.si == .null) continue; |
| | 4886 | |
| | 4887 | const loc_sym = section.si.get(coff); |
| | 4888 | assert(loc_sym.loc_relocs == .none); |
| | 4889 | loc_sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| | 4890 | |
| | 4891 | if (section.header.number_of_relocations == 0) continue; |
| | 4892 | |
| | 4893 | try fr.seekTo(fl.offset + section.header.pointer_to_relocations); |
| | 4894 | for (0..section.header.number_of_relocations) |reloc_i| { |
| | 4895 | var reloc: std.coff.Relocation = undefined; |
| | 4896 | @memcpy(std.mem.asBytes(&reloc)[0..relocation_size], try r.take(relocation_size)); |
| | 4897 | if (target_endian != native_endian) |
| | 4898 | std.mem.byteSwapAllFields(std.coff.Relocation, &reloc); |
| | 4899 | |
| | 4900 | const symbol = pending_symbols.getPtr(reloc.symbol_table_index) orelse |
| | 4901 | return diags.failParse( |
| | 4902 | path, |
| | 4903 | "relocation 0x{x} in section '{s}' of {f}{f} targets invalid symbol index 0x{x}", |
| | 4904 | .{ |
| | 4905 | reloc_i, |
| | 4906 | section.name.toSlice(coff), |
| | 4907 | path.fmtEscapeString(), |
| | 4908 | fmtMemberNameString(member_name), |
| | 4909 | reloc.symbol_table_index, |
| | 4910 | }, |
| | 4911 | ); |
| | 4912 | |
| | 4913 | if (symbol.si == .null) { |
| | 4914 | assert(symbol.section_number == .UNDEFINED); |
| | 4915 | switch (symbol.value) { |
| | 4916 | .external => |size| { |
| | 4917 | const global_gop = try coff.getOrPutGlobalSymbol(.{ .name = symbol.name.toSlice(coff) }); |
| | 4918 | symbol.si = global_gop.value_ptr.si; |
| | 4919 | if (!global_gop.found_existing or symbol.si.get(coff).ni == .none) { |
| | 4920 | const sym = symbol.si.get(coff); |
| | 4921 | sym.setExtra(.{ .size = @max(sym.size(), size) }); |
| | 4922 | } |
| | 4923 | }, |
| | 4924 | else => unreachable, |
| | 4925 | } |
| | 4926 | } |
| | 4927 | |
| | 4928 | assert(symbol.si != .null); |
| | 4929 | try coff.addReloc( |
| | 4930 | section.si, |
| | 4931 | reloc.virtual_address - section.header.virtual_address, |
| | 4932 | symbol.si, |
| | 4933 | .pending, |
| | 4934 | @bitCast(reloc.type), |
| | 4935 | ); |
| | 4936 | } |
| | 4937 | } |
| | 4938 | |
| | 4939 | // Set up contiguous symbol ranges in `input_symbols` for both symbols we just created, |
| | 4940 | // and symbols that were previously created as undefined, but we just defined. |
| | 4941 | const SortContext = struct { |
| | 4942 | v: []const PendingSymbol, |
| | 4943 | |
| | 4944 | pub fn lessThan(ctx: @This(), a_index: usize, b_index: usize) bool { |
| | 4945 | const lhs = &ctx.v[a_index]; |
| | 4946 | const rhs = &ctx.v[b_index]; |
| | 4947 | if (lhs.section_number == rhs.section_number) |
| | 4948 | return @intFromEnum(lhs.si) < @intFromEnum(rhs.si); |
| | 4949 | return @intFromEnum(lhs.section_number) < @intFromEnum(rhs.section_number); |
| | 4950 | } |
| | 4951 | }; |
| | 4952 | |
| | 4953 | pending_symbols.sortUnstable(SortContext{ .v = pending_symbols.values() }); |
| | 4954 | |
| | 4955 | try coff.input_symbols.ensureUnusedCapacity(gpa, num_included_symbols + num_included_sections); |
| | 4956 | var prev_sn: Symbol.SectionNumber = .DEBUG; |
| | 4957 | var include_section = false; |
| | 4958 | for (pending_symbols.values()) |symbol| { |
| | 4959 | // The symbol may have not been included, or it's an undefined external / aux |
| | 4960 | if (symbol.si == .null or symbol.si.get(coff).ni == .none) continue; |
| | 4961 | |
| | 4962 | if (prev_sn != symbol.section_number) { |
| | 4963 | prev_sn = symbol.section_number; |
| | 4964 | if (symbol.section_number.hasIndex()) { |
| | 4965 | const section = &sections[symbol.section_number.toIndex()]; |
| | 4966 | include_section = section.comdat_result == .include; |
| | 4967 | if (include_section) { |
| | 4968 | const isi = coff.getNode(section.si.get(coff).ni).input_section; |
| | 4969 | isi.inputSection(coff).first_li = @enumFromInt(coff.input_symbols.items.len); |
| | 4970 | } |
| | 4971 | } |
| | 4972 | } |
| | 4973 | |
| | 4974 | if (include_section) { |
| | 4975 | assert(coff.getNode(symbol.si.get(coff).ni) == .input_section); |
| | 4976 | symbol.si.get(coff).setExtra(.{ .isli = @enumFromInt(coff.input_symbols.items.len) }); |
| | 4977 | coff.input_symbols.addOneAssumeCapacity().* = .{ |
| | 4978 | .si = symbol.si, |
| | 4979 | .name = symbol.name, |
| | 4980 | }; |
| | 4981 | } |
| | 4982 | } |
| | 4983 | } |
| | 4984 | |
| | 4985 | fn failMultipleDefinitions( |
| | 4986 | coff: *Coff, |
| | 4987 | path: std.Build.Cache.Path, |
| | 4988 | member_name: ?[]const u8, |
| | 4989 | name: String, |
| | 4990 | index: u32, |
| | 4991 | existing_si: Symbol.Index, |
| | 4992 | comdat_reason: union(enum) { |
| | 4993 | none: void, |
| | 4994 | duplicate: void, |
| | 4995 | size: struct { a: u64, b: u64 }, |
| | 4996 | crc: struct { a: u32, b: u32 }, |
| | 4997 | }, |
| | 4998 | ) error{ AlreadyReported, OutOfMemory } { |
| | 4999 | const num_notes: usize = 2 + @as(usize, @intFromBool(comdat_reason != .none)); |
| | 5000 | var err = try coff.base.comp.link_diags.addErrorWithNotes(num_notes); |
| | 5001 | try err.addMsg("multiple definitions of '{s}'", .{name.toSlice(coff)}); |
| | 5002 | |
| | 5003 | switch (coff.getNode(existing_si.get(coff).ni)) { |
| | 5004 | .input_section => |isi| { |
| | 5005 | const other_ioi = isi.input(coff); |
| | 5006 | err.addNote("first seen in input '{f}{f}'", .{ |
| | 5007 | other_ioi.path(coff).fmtEscapeString(), |
| | 5008 | fmtMemberNameString(other_ioi.memberName(coff)), |
| | 5009 | }); |
| | 5010 | }, |
| | 5011 | .nav, .uav => err.addNote("first seen in module '{s}'", .{ |
| | 5012 | coff.base.comp.zcu.?.root_mod.fully_qualified_name, |
| | 5013 | }), |
| | 5014 | else => unreachable, |
| | 5015 | } |
| | 5016 | |
| | 5017 | err.addNote("defined again in input '{f}{f}' (0x{x}))", .{ path, fmtMemberNameString(member_name), index }); |
| | 5018 | switch (comdat_reason) { |
| | 5019 | .none => {}, |
| | 5020 | .duplicate => err.addNote("COMDAT rule requires no duplicates", .{}), |
| | 5021 | .size => |s| err.addNote( |
| | 5022 | "COMDAT rule require duplicates to have the same size ({d} vs {d})", |
| | 5023 | .{ s.a, s.b }, |
| | 5024 | ), |
| | 5025 | .crc => |s| err.addNote( |
| | 5026 | "COMDAT rule require duplicates to have the same CRC (0x{x} vs 0x{x})", |
| | 5027 | .{ s.a, s.b }, |
| | 5028 | ), |
| | 5029 | } |
| | 5030 | |
| | 5031 | return error.AlreadyReported; |
| | 5032 | } |
| | 5033 | |
| | 5034 | const ArchiveMemberHeader = struct { |
| | 5035 | name: []const u8, |
| | 5036 | size: u34, |
| | 5037 | }; |
| | 5038 | |
| | 5039 | /// Return value lifetime is that of `header` |
| | 5040 | fn parseArchiveMemberHeader( |
| | 5041 | diags: *link.Diags, |
| | 5042 | path: std.Build.Cache.Path, |
| | 5043 | header: *const std.coff.ArchiveMemberHeader, |
| | 5044 | opt_longnames: ?[]const u8, |
| | 5045 | ) !ArchiveMemberHeader { |
| | 5046 | return parseArchiveMemberHeaderInner(header, opt_longnames) catch |err| switch (err) { |
| | 5047 | error.BadName => return diags.failParse(path, "malformed member name: '{s}'", .{&header.name}), |
| | 5048 | error.BadSize => return diags.failParse(path, "malformed member size: '{s}'", .{&header.size}), |
| | 5049 | error.BadEndOfHeader => return diags.failParse(path, "end of header was invalid", .{}), |
| | 5050 | error.NoLongNames => return diags.failParse(path, "long name used without longnames member", .{}), |
| | 5051 | }; |
| | 5052 | } |
| | 5053 | |
| | 5054 | fn parseArchiveMemberHeaderInner( |
| | 5055 | header: *const std.coff.ArchiveMemberHeader, |
| | 5056 | opt_longnames: ?[]const u8, |
| | 5057 | ) !ArchiveMemberHeader { |
| | 5058 | const name = try header.parseName(opt_longnames); |
| | 5059 | const size = header.parseSize() catch return error.BadSize; |
| | 5060 | |
| | 5061 | if (!std.mem.eql(u8, &header.end_of_header, std.coff.archive_end_of_header)) |
| | 5062 | return error.BadEndOfHeader; |
| | 5063 | |
| | 5064 | return .{ |
| | 5065 | .name = name, |
| | 5066 | .size = size, |
| | 5067 | }; |
| | 5068 | } |
| | 5069 | |
| | 5070 | fn loadArchive(coff: *Coff, path: std.Build.Cache.Path, fr: *Io.File.Reader) LoadInputError!void { |
| | 5071 | const comp = coff.base.comp; |
| | 5072 | const gpa = comp.gpa; |
| | 5073 | const diags = &comp.link_diags; |
| | 5074 | const r = &fr.interface; |
| | 5075 | const target_endian = coff.targetEndian(); |
| | 5076 | |
| | 5077 | log.debug("loadArchive({f})", .{path.fmtEscapeString()}); |
| | 5078 | |
| | 5079 | const signature = try r.take(std.coff.archive_signature.len); |
| | 5080 | if (!std.mem.eql(u8, signature, std.coff.archive_signature)) |
| | 5081 | return diags.failParse(path, "bad signature", .{}); |
| | 5082 | |
| | 5083 | var opt_expected_kind: ?std.coff.ArchiveMemberHeader.Kind = .first_linker; |
| | 5084 | var opt_longnames: ?[]const u8 = null; |
| | 5085 | defer if (opt_longnames) |l| gpa.free(l); |
| | 5086 | |
| | 5087 | var members: std.ArrayList(struct { |
| | 5088 | offset: u32, |
| | 5089 | iami: ?InputArchive.Member.Index, |
| | 5090 | }) = .empty; |
| | 5091 | var symbol_member_indices: std.ArrayList(u32) = .empty; |
| | 5092 | |
| | 5093 | const iai: InputArchive.Index = @enumFromInt(coff.input_archives.items.len); |
| | 5094 | (try coff.input_archives.addOne(gpa)).* = .{ |
| | 5095 | .path = path, |
| | 5096 | }; |
| | 5097 | |
| | 5098 | const first_iami = coff.input_archive_members.items.len; |
| | 5099 | const first_iamsi = coff.input_archive_symbols.items.len; |
| | 5100 | const first_symbol_indices_index = coff.input_archive_symbol_indices.count(); |
| | 5101 | |
| | 5102 | errdefer { |
| | 5103 | for (coff.input_archive_symbol_indices.values()) |*v| { |
| | 5104 | if (@intFromEnum(v.last) < first_iamsi) continue; |
| | 5105 | if (@intFromEnum(v.first) >= first_iamsi) continue; |
| | 5106 | |
| | 5107 | var iter = v.first; |
| | 5108 | v.last = while (iter != v.last) { |
| | 5109 | const sym = &coff.input_archive_symbols.items[@intFromEnum(iter)]; |
| | 5110 | if (@intFromEnum(sym.next) >= first_iamsi) { |
| | 5111 | sym.next = iter; |
| | 5112 | break iter; |
| | 5113 | } |
| | 5114 | |
| | 5115 | iter = sym.next; |
| | 5116 | } else unreachable; |
| | 5117 | } |
| | 5118 | |
| | 5119 | // New entries in this map will only have pointed to iamsi we also just added |
| | 5120 | coff.input_archive_symbol_indices.shrinkRetainingCapacity(first_symbol_indices_index); |
| | 5121 | coff.input_archive_symbols.shrinkRetainingCapacity(first_iamsi); |
| | 5122 | coff.input_archive_members.shrinkRetainingCapacity(first_iami); |
| | 5123 | _ = coff.input_archives.pop(); |
| | 5124 | } |
| | 5125 | |
| | 5126 | var pos = fr.logicalPos(); |
| | 5127 | const size = try fr.getSize(); |
| | 5128 | while (pos < size) : (pos = fr.logicalPos()) { |
| | 5129 | if ((pos & 1) != 0) try r.discardAll(1); |
| | 5130 | const header = try r.takeStruct(std.coff.ArchiveMemberHeader, target_endian); |
| | 5131 | const res = try parseArchiveMemberHeader(diags, path, &header, opt_longnames); |
| | 5132 | |
| | 5133 | const member_end = fr.logicalPos() + res.size; |
| | 5134 | if (member_end > size) |
| | 5135 | return diags.failParse(path, "out-of-bounds length 0x{x} in member '{s}'", .{ res.size, res.name }); |
| | 5136 | |
| | 5137 | log.debug("loadArchiveMember({s})", .{res.name}); |
| | 5138 | |
| | 5139 | if (opt_expected_kind) |expected_kind| switch (expected_kind) { |
| | 5140 | .first_linker => { |
| | 5141 | if (!std.mem.eql(u8, res.name, "/")) |
| | 5142 | return diags.failParse(path, "expected first linker member, found '{s}'", .{res.name}); |
| | 5143 | |
| | 5144 | try fr.seekTo(fr.logicalPos() + res.size); |
| | 5145 | opt_expected_kind = .second_linker; |
| | 5146 | continue; |
| | 5147 | }, |
| | 5148 | .second_linker => { |
| | 5149 | if (!std.mem.eql(u8, res.name, "/")) |
| | 5150 | return diags.failParse(path, "expected second linker member, found '{s}'", .{res.name}); |
| | 5151 | |
| | 5152 | const num_members = try r.takeInt(u32, target_endian); |
| | 5153 | pos = fr.logicalPos(); |
| | 5154 | if (pos + num_members * @sizeOf(u32) > member_end) |
| | 5155 | return diags.failParse(path, "invalid member count 0x{x} in second linker member", .{num_members}); |
| | 5156 | |
| | 5157 | try members.ensureTotalCapacity(gpa, num_members); |
| | 5158 | for (0..num_members) |_| |
| | 5159 | members.addOneAssumeCapacity().* = .{ |
| | 5160 | .offset = try r.takeInt(u32, target_endian), |
| | 5161 | .iami = null, |
| | 5162 | }; |
| | 5163 | |
| | 5164 | const num_symbols = try r.takeInt(u32, target_endian); |
| | 5165 | pos = fr.logicalPos(); |
| | 5166 | if (pos + num_symbols * @sizeOf(u16) > member_end) |
| | 5167 | return diags.failParse(path, "invalid symbol count 0x{x} in second linker member", .{num_symbols}); |
| | 5168 | |
| | 5169 | try symbol_member_indices.ensureTotalCapacity(gpa, num_symbols); |
| | 5170 | for (0..num_symbols) |_| |
| | 5171 | symbol_member_indices.addOneAssumeCapacity().* = (try r.takeInt(u16, target_endian)) - 1; |
| | 5172 | |
| | 5173 | pos = fr.logicalPos(); |
| | 5174 | try coff.ensureManyUnusedStringCapacity(num_symbols, @intCast(member_end - pos)); |
| | 5175 | try coff.input_archive_members.ensureUnusedCapacity(gpa, num_members); |
| | 5176 | try coff.input_archive_symbols.ensureUnusedCapacity(gpa, num_symbols); |
| | 5177 | try coff.input_archive_symbol_indices.ensureUnusedCapacity(gpa, num_symbols); |
| | 5178 | |
| | 5179 | var symbol_i: u32 = 0; |
| | 5180 | while (pos < member_end and symbol_i < num_symbols) : ({ |
| | 5181 | pos = fr.logicalPos(); |
| | 5182 | symbol_i += 1; |
| | 5183 | }) { |
| | 5184 | const name = if (r.takeDelimiter(0) catch |err| switch (err) { |
| | 5185 | error.StreamTooLong => null, |
| | 5186 | else => |e| return e, |
| | 5187 | }) |n| n else return diags.failParse(path, "unterminated string found in second linker member", .{}); |
| | 5188 | |
| | 5189 | const string = coff.getOrPutStringAssumeCapacity(name); |
| | 5190 | const iamsi: InputArchive.Member.Symbol.Index = @enumFromInt(coff.input_archive_symbols.items.len); |
| | 5191 | const symbol_gop = coff.input_archive_symbol_indices.getOrPutAssumeCapacity(string); |
| | 5192 | if (!symbol_gop.found_existing) { |
| | 5193 | symbol_gop.value_ptr.* = .{ |
| | 5194 | .first = iamsi, |
| | 5195 | .last = iamsi, |
| | 5196 | }; |
| | 5197 | } else { |
| | 5198 | coff.input_archive_symbols.items[@intFromEnum(symbol_gop.value_ptr.last)].next = iamsi; |
| | 5199 | symbol_gop.value_ptr.last = iamsi; |
| | 5200 | } |
| | 5201 | |
| | 5202 | const iami = members.items[symbol_member_indices.items[symbol_i]].iami orelse iami: { |
| | 5203 | const iami: InputArchive.Member.Index = @enumFromInt(coff.input_archive_members.items.len); |
| | 5204 | const member_offset = members.items[symbol_member_indices.items[symbol_i]].offset; |
| | 5205 | coff.input_archive_members.addOneAssumeCapacity().* = .{ |
| | 5206 | .iai = iai, |
| | 5207 | .name = undefined, |
| | 5208 | .content = .{ |
| | 5209 | .object = .{ |
| | 5210 | .offset = member_offset, |
| | 5211 | .size = undefined, |
| | 5212 | }, |
| | 5213 | }, |
| | 5214 | .flags = .{ |
| | 5215 | .is_loaded = false, |
| | 5216 | }, |
| | 5217 | }; |
| | 5218 | |
| | 5219 | members.items[symbol_member_indices.items[symbol_i]].iami = iami; |
| | 5220 | break :iami iami; |
| | 5221 | }; |
| | 5222 | |
| | 5223 | log.debug("loadArchiveMemberSymbol({s}) = ({d}, {d}, {d})", .{ name, iai, iami, iamsi }); |
| | 5224 | |
| | 5225 | coff.input_archive_symbols.addOneAssumeCapacity().* = .{ |
| | 5226 | .iami = iami, |
| | 5227 | .next = iamsi, |
| | 5228 | }; |
| | 5229 | } |
| | 5230 | |
| | 5231 | if (symbol_i != num_symbols) |
| | 5232 | return diags.failParse( |
| | 5233 | path, |
| | 5234 | " expected {d} entries in second linker member string table, but found {d}", |
| | 5235 | .{ num_symbols, symbol_i }, |
| | 5236 | ); |
| | 5237 | |
| | 5238 | try fr.seekTo(member_end); |
| | 5239 | opt_expected_kind = .longnames; |
| | 5240 | continue; |
| | 5241 | }, |
| | 5242 | .longnames => { |
| | 5243 | // This member is optional |
| | 5244 | if (std.mem.eql(u8, res.name, "//")) |
| | 5245 | opt_longnames = try r.readAlloc(gpa, @intCast(res.size)); |
| | 5246 | |
| | 5247 | opt_expected_kind = null; |
| | 5248 | break; |
| | 5249 | }, |
| | 5250 | else => unreachable, |
| | 5251 | }; |
| | 5252 | } |
| | 5253 | |
| | 5254 | if (opt_expected_kind) |expected_kind| switch (expected_kind) { |
| | 5255 | .first_linker => return diags.failParse(path, "missing first linker member", .{}), |
| | 5256 | .second_linker => return diags.failParse(path, "missing second linker member", .{}), |
| | 5257 | else => {}, |
| | 5258 | }; |
| | 5259 | |
| | 5260 | // Validate / read names and sizes of all the referenced members, enumerate imports |
| | 5261 | for (coff.input_archive_members.items[first_iami..]) |*member| { |
| | 5262 | try fr.seekTo(member.content.object.offset); |
| | 5263 | |
| | 5264 | const header = try r.takeStruct(std.coff.ArchiveMemberHeader, target_endian); |
| | 5265 | const res = try parseArchiveMemberHeader(diags, path, &header, opt_longnames); |
| | 5266 | |
| | 5267 | try coff.ensureUnusedStringCapacity(res.name.len); |
| | 5268 | member.name = coff.getOrPutStringAssumeCapacity(res.name); |
| | 5269 | |
| | 5270 | const member_sig = try r.peek(4); |
| | 5271 | const machine: std.coff.IMAGE.FILE.MACHINE = |
| | 5272 | @enumFromInt(std.mem.readInt(u16, member_sig[0..2], target_endian)); |
| | 5273 | const sig = std.mem.readInt(u16, member_sig[2..4], target_endian); |
| | 5274 | |
| | 5275 | log.debug("verifyArchiveMember({s}) = 0x{x}+{x}", .{ |
| | 5276 | res.name, |
| | 5277 | member.content.object.offset, |
| | 5278 | res.size, |
| | 5279 | }); |
| | 5280 | |
| | 5281 | const expected_machine = comp.root_mod.resolved_target.result.toCoffMachine(); |
| | 5282 | if (machine == std.coff.IMAGE.FILE.MACHINE.UNKNOWN and sig == 0xffff) { |
| | 5283 | const import_header = try r.takeStruct(std.coff.ImportHeader, target_endian); |
| | 5284 | const strings = r.take(import_header.size_of_data) catch |err| switch (err) { |
| | 5285 | error.EndOfStream => return diags.failParse(path, "invalid data size in import header '{s}'", .{res.name}), |
| | 5286 | else => |e| return e, |
| | 5287 | }; |
| | 5288 | |
| | 5289 | var split = std.mem.splitScalar(u8, strings, 0); |
| | 5290 | const symbol_name = split.next() orelse |
| | 5291 | return diags.failParse(path, "invalid symbol name string in import header '{s}'", .{res.name}); |
| | 5292 | var lib_name = split.next() orelse |
| | 5293 | return diags.failParse(path, "invalid dll name string in import header '{s}' ('{s}')", .{ res.name, symbol_name }); |
| | 5294 | |
| | 5295 | if (import_header.machine != expected_machine) |
| | 5296 | return diags.failParse(path, "machine mismatch in import header '{s}' ('{s}'): expected {t}, found {t}", .{ |
| | 5297 | res.name, |
| | 5298 | symbol_name, |
| | 5299 | expected_machine, |
| | 5300 | machine, |
| | 5301 | }); |
| | 5302 | |
| | 5303 | const ext = ".dll"; |
| | 5304 | if (!std.mem.endsWith(u8, lib_name, ext)) |
| | 5305 | return diags.failParse( |
| | 5306 | path, |
| | 5307 | "unexpected extension for import '{s} ('{s}'): '{s}'", |
| | 5308 | .{ res.name, symbol_name, lib_name }, |
| | 5309 | ); |
| | 5310 | |
| | 5311 | lib_name = lib_name[0 .. lib_name.len - ext.len]; |
| | 5312 | log.debug("verifyArchiveImportHeader({s}, {s}, {s}) = {t} ({t})", .{ |
| | 5313 | res.name, |
| | 5314 | symbol_name, |
| | 5315 | lib_name, |
| | 5316 | import_header.types.type, |
| | 5317 | import_header.types.name_type, |
| | 5318 | }); |
| | 5319 | |
| | 5320 | try coff.ensureManyUnusedStringCapacity(2, strings.len - ext.len); |
| | 5321 | member.content = .{ |
| | 5322 | .import = .{ |
| | 5323 | .symbol_name = coff.getOrPutStringAssumeCapacity(symbol_name), |
| | 5324 | .lib_name = coff.getOrPutStringAssumeCapacity(lib_name), |
| | 5325 | .import_ordinal_hint = import_header.hint, |
| | 5326 | .type = import_header.types.type, |
| | 5327 | .name_type = import_header.types.name_type, |
| | 5328 | }, |
| | 5329 | }; |
| | 5330 | } else { |
| | 5331 | member.content.object.size = res.size; |
| | 5332 | // Microsoft's CRT contains members that set .UNKNOWN but do have undef symbols |
| | 5333 | if (machine != expected_machine and machine != .UNKNOWN) { |
| | 5334 | return diags.failParse(path, "machine mismatch in member header '{s}': expected {t}, found {t}", .{ |
| | 5335 | res.name, |
| | 5336 | expected_machine, |
| | 5337 | machine, |
| | 5338 | }); |
| | 5339 | } |
| | 5340 | } |
| | 5341 | } |
| | 5342 | } |
| | 5343 | |
| | 5344 | fn loadRes(coff: *Coff, path: std.Build.Cache.Path, fr: *Io.File.Reader) LoadInputError!void { |
| | 5345 | const comp = coff.base.comp; |
| | 5346 | const gpa = comp.gpa; |
| | 5347 | const diags = &comp.link_diags; |
| | 5348 | const r = &fr.interface; |
| | 5349 | |
| | 5350 | log.debug("loadRes({f})", .{path.fmtEscapeString()}); |
| | 5351 | |
| | 5352 | _ = gpa; |
| | 5353 | _ = diags; |
| | 5354 | _ = r; |
| | 5355 | } |
| | 5356 | |
| | 5357 | fn loadDll(coff: *Coff, path: std.Build.Cache.Path, fr: *Io.File.Reader) LoadInputError!void { |
| | 5358 | const comp = coff.base.comp; |
| | 5359 | const gpa = comp.gpa; |
| | 5360 | const diags = &comp.link_diags; |
| | 5361 | const r = &fr.interface; |
| | 5362 | |
| | 5363 | log.debug("loadDll({f})", .{path.fmtEscapeString()}); |
| | 5364 | |
| | 5365 | _ = gpa; |
| | 5366 | _ = diags; |
| | 5367 | _ = r; |
| | 5368 | } |
| | 5369 | |
| 1527 | pub fn prelink(coff: *Coff, prog_node: std.Progress.Node) link.Error!void { | 5370 | pub fn prelink(coff: *Coff, prog_node: std.Progress.Node) link.Error!void { |
| 1528 | _ = coff; | | |
| 1529 | _ = prog_node; | 5371 | _ = prog_node; |
| | 5372 | const base = coff.base; |
| | 5373 | const comp = base.comp; |
| | 5374 | |
| | 5375 | log.debug("prelink()", .{}); |
| | 5376 | |
| | 5377 | if (coff.pending_default_libs.items.len > 0) { |
| | 5378 | // Libs provided by /DEFAULTLIB arguments in objects are searched after all other inputs |
| | 5379 | const gpa = comp.gpa; |
| | 5380 | const arena = comp.arena; |
| | 5381 | const target = &comp.root_mod.resolved_target.result; |
| | 5382 | |
| | 5383 | defer { |
| | 5384 | for (coff.pending_default_libs.items) |l| gpa.free(l.path); |
| | 5385 | coff.pending_default_libs.clearAndFree(gpa); |
| | 5386 | } |
| | 5387 | |
| | 5388 | assert(comp.config.link_libc); |
| | 5389 | const libc_installation = comp.libc_installation.?; |
| | 5390 | const all_paths: [3]?[]const u8 = .{ |
| | 5391 | libc_installation.crt_dir, |
| | 5392 | libc_installation.msvc_lib_dir, |
| | 5393 | libc_installation.kernel32_lib_dir, |
| | 5394 | }; |
| | 5395 | const search_paths = all_paths[0..if (target.abi == .msvc or target.abi == .itanium) 3 else 1]; |
| | 5396 | lib: for (coff.pending_default_libs.items) |lib| { |
| | 5397 | if (!std.mem.eql(u8, std.fs.path.extension(lib.path), ".lib")) |
| | 5398 | return comp.link_diags.failParse( |
| | 5399 | lib.ioi.path(coff), |
| | 5400 | "/DEFAULTLIB library '{s}' had unexpected extension", |
| | 5401 | .{lib.path}, |
| | 5402 | ); |
| | 5403 | |
| | 5404 | log.debug("loadDefaultLib({s}, {f})", .{ lib.path, lib.ioi.path(coff) }); |
| | 5405 | for (search_paths) |opt_path| if (opt_path) |search_path| { |
| | 5406 | const lib_path = try Path.initCwd(search_path).join(arena, lib.path); |
| | 5407 | const archive = link.openObject(comp.io, lib_path, false, false) catch |err| switch (err) { |
| | 5408 | error.FileNotFound => { |
| | 5409 | arena.free(lib_path.sub_path); |
| | 5410 | continue; |
| | 5411 | }, |
| | 5412 | else => |e| return comp.link_diags.failParse( |
| | 5413 | lib.ioi.path(coff), |
| | 5414 | "error opening /DEFAULTLIB library '{s}': {t}", |
| | 5415 | .{ lib.path, e }, |
| | 5416 | ), |
| | 5417 | }; |
| | 5418 | errdefer archive.file.close(comp.io); |
| | 5419 | |
| | 5420 | coff.loadInput(.{ .archive = archive }) catch |err| switch (err) { |
| | 5421 | else => |e| return comp.link_diags.failParse( |
| | 5422 | lib.ioi.path(coff), |
| | 5423 | "error loading /DEFAULTLIB library '{s}': {t}", |
| | 5424 | .{ lib.path, e }, |
| | 5425 | ), |
| | 5426 | }; |
| | 5427 | |
| | 5428 | break :lib; |
| | 5429 | }; |
| | 5430 | |
| | 5431 | return comp.link_diags.failParse( |
| | 5432 | lib.ioi.path(coff), |
| | 5433 | "/DEFAULTLIB library '{s}' was not found", |
| | 5434 | .{lib.path}, |
| | 5435 | ); |
| | 5436 | } |
| | 5437 | } |
| | 5438 | |
| | 5439 | coff.inputs_complete = true; |
| | 5440 | if (comp.zcu == null) |
| | 5441 | coff.exports_complete = true; |
| 1530 | } | 5442 | } |
| 1531 | | 5443 | |
| 1532 | pub fn updateNav(coff: *Coff, pt: Zcu.PerThread, nav_index: InternPool.Nav.Index) !void { | 5444 | pub fn updateNav(coff: *Coff, pt: Zcu.PerThread, nav_index: InternPool.Nav.Index) link.Error!void { |
| 1533 | coff.updateNavInner(pt, nav_index) catch |err| switch (err) { | 5445 | coff.updateNavInner(pt, nav_index) catch |err| switch (err) { |
| | 5446 | error.MappedFileIo => return coff.base.cgFail( |
| | 5447 | nav_index, |
| | 5448 | "linker failed to update variable: {t}", |
| | 5449 | .{coff.mf.io_err.?}, |
| | 5450 | ), |
| 1534 | else => |e| return e, | 5451 | else => |e| return e, |
| 1535 | error.MappedFileIo => return coff.base.cgFail(nav_index, "linker failed to update variable: {t}", .{coff.mf.io_err.?}), | | |
| 1536 | }; | 5452 | }; |
| 1537 | } | 5453 | } |
| 1538 | fn updateNavInner(coff: *Coff, pt: Zcu.PerThread, nav_index: InternPool.Nav.Index) !void { | 5454 | fn updateNavInner(coff: *Coff, pt: Zcu.PerThread, nav_index: InternPool.Nav.Index) !void { |
| ... | @@ -1546,11 +5462,13 @@ fn updateNavInner(coff: *Coff, pt: Zcu.PerThread, nav_index: InternPool.Nav.Inde | ... | @@ -1546,11 +5462,13 @@ fn updateNavInner(coff: *Coff, pt: Zcu.PerThread, nav_index: InternPool.Nav.Inde |
| 1546 | | 5462 | |
| 1547 | const nmi = try coff.navMapIndex(zcu, nav_index); | 5463 | const nmi = try coff.navMapIndex(zcu, nav_index); |
| 1548 | const si = nmi.symbol(coff); | 5464 | const si = nmi.symbol(coff); |
| | 5465 | log.debug("updateNav({f}) = {d}", .{ nav.fqn.fmt(ip), si }); |
| 1549 | const ni = ni: { | 5466 | const ni = ni: { |
| 1550 | switch (si.get(coff).ni) { | 5467 | switch (si.get(coff).ni) { |
| 1551 | .none => { | 5468 | .none => { |
| 1552 | const sec_si = try coff.navSection(zcu, nav.resolved.?); | 5469 | const sec_si = try coff.navSection(zcu, nav.resolved.?); |
| 1553 | try coff.nodes.ensureUnusedCapacity(gpa, 1); | 5470 | try coff.nodes.ensureUnusedCapacity(gpa, 1); |
| | 5471 | if (!isImage(coff)) try coff.symbol_table.symbols.ensureUnusedCapacity(gpa, 1); |
| 1554 | const ni = try coff.mf.addLastChildNode(gpa, sec_si.node(coff), .{ | 5472 | const ni = try coff.mf.addLastChildNode(gpa, sec_si.node(coff), .{ |
| 1555 | .alignment = zcu.navAlignment(nav_index).toStdMem(), | 5473 | .alignment = zcu.navAlignment(nav_index).toStdMem(), |
| 1556 | .moved = true, | 5474 | .moved = true, |
| ... | @@ -1565,6 +5483,9 @@ fn updateNavInner(coff: *Coff, pt: Zcu.PerThread, nav_index: InternPool.Nav.Inde | ... | @@ -1565,6 +5483,9 @@ fn updateNavInner(coff: *Coff, pt: Zcu.PerThread, nav_index: InternPool.Nav.Inde |
| 1565 | const sym = si.get(coff); | 5483 | const sym = si.get(coff); |
| 1566 | assert(sym.loc_relocs == .none); | 5484 | assert(sym.loc_relocs == .none); |
| 1567 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); | 5485 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| | 5486 | if (!isImage(coff) and sym.target_relocs != .none) |
| | 5487 | try coff.pendingSymbolTableEntry(si); |
| | 5488 | |
| 1568 | break :ni sym.ni; | 5489 | break :ni sym.ni; |
| 1569 | }; | 5490 | }; |
| 1570 | | 5491 | |
| ... | @@ -1582,12 +5503,12 @@ fn updateNavInner(coff: *Coff, pt: Zcu.PerThread, nav_index: InternPool.Nav.Inde | ... | @@ -1582,12 +5503,12 @@ fn updateNavInner(coff: *Coff, pt: Zcu.PerThread, nav_index: InternPool.Nav.Inde |
| 1582 | error.WriteFailed => return nw.err.?, | 5503 | error.WriteFailed => return nw.err.?, |
| 1583 | else => |e| return e, | 5504 | else => |e| return e, |
| 1584 | }; | 5505 | }; |
| 1585 | si.get(coff).size = @intCast(nw.interface.end); | 5506 | si.get(coff).extra.size = @intCast(nw.interface.end); |
| 1586 | si.applyLocationRelocs(coff); | 5507 | try si.applyLocationRelocs(coff); |
| 1587 | } | 5508 | } |
| 1588 | | 5509 | |
| 1589 | if (nav.resolved.?.@"linksection".unwrap()) |_| { | 5510 | if (nav.resolved.?.@"linksection".unwrap()) |_| { |
| 1590 | try ni.resize(&coff.mf, gpa, si.get(coff).size); | 5511 | try ni.resize(&coff.mf, gpa, si.get(coff).extra.size); |
| 1591 | var parent_ni = ni; | 5512 | var parent_ni = ni; |
| 1592 | while (true) { | 5513 | while (true) { |
| 1593 | parent_ni = parent_ni.parent(&coff.mf); | 5514 | parent_ni = parent_ni.parent(&coff.mf); |
| ... | @@ -1610,7 +5531,7 @@ pub fn lowerUav( | ... | @@ -1610,7 +5531,7 @@ pub fn lowerUav( |
| 1610 | pt: Zcu.PerThread, | 5531 | pt: Zcu.PerThread, |
| 1611 | uav_val: InternPool.Index, | 5532 | uav_val: InternPool.Index, |
| 1612 | uav_align: InternPool.Alignment, | 5533 | uav_align: InternPool.Alignment, |
| 1613 | ) !link.File.SymbolId { | 5534 | ) link.Error!link.File.SymbolId { |
| 1614 | const zcu = pt.zcu; | 5535 | const zcu = pt.zcu; |
| 1615 | const gpa = zcu.gpa; | 5536 | const gpa = zcu.gpa; |
| 1616 | | 5537 | |
| ... | @@ -1639,7 +5560,7 @@ pub fn updateFunc( | ... | @@ -1639,7 +5560,7 @@ pub fn updateFunc( |
| 1639 | pt: Zcu.PerThread, | 5560 | pt: Zcu.PerThread, |
| 1640 | func_index: InternPool.Index, | 5561 | func_index: InternPool.Index, |
| 1641 | mir: *const codegen.AnyMir, | 5562 | mir: *const codegen.AnyMir, |
| 1642 | ) !void { | 5563 | ) link.Error!void { |
| 1643 | coff.updateFuncInner(pt, func_index, mir) catch |err| switch (err) { | 5564 | coff.updateFuncInner(pt, func_index, mir) catch |err| switch (err) { |
| 1644 | else => |e| return e, | 5565 | else => |e| return e, |
| 1645 | error.MappedFileIo => return coff.base.cgFail( | 5566 | error.MappedFileIo => return coff.base.cgFail( |
| ... | @@ -1669,6 +5590,7 @@ fn updateFuncInner( | ... | @@ -1669,6 +5590,7 @@ fn updateFuncInner( |
| 1669 | .none => { | 5590 | .none => { |
| 1670 | const sec_si = try coff.navSection(zcu, nav.resolved.?); | 5591 | const sec_si = try coff.navSection(zcu, nav.resolved.?); |
| 1671 | try coff.nodes.ensureUnusedCapacity(gpa, 1); | 5592 | try coff.nodes.ensureUnusedCapacity(gpa, 1); |
| | 5593 | if (!isImage(coff)) try coff.symbol_table.symbols.ensureUnusedCapacity(gpa, 1); |
| 1672 | const mod = zcu.navFileScope(func.owner_nav).mod.?; | 5594 | const mod = zcu.navFileScope(func.owner_nav).mod.?; |
| 1673 | const target = &mod.resolved_target.result; | 5595 | const target = &mod.resolved_target.result; |
| 1674 | const ni = try coff.mf.addLastChildNode(gpa, sec_si.node(coff), .{ | 5596 | const ni = try coff.mf.addLastChildNode(gpa, sec_si.node(coff), .{ |
| ... | @@ -1694,6 +5616,8 @@ fn updateFuncInner( | ... | @@ -1694,6 +5616,8 @@ fn updateFuncInner( |
| 1694 | const sym = si.get(coff); | 5616 | const sym = si.get(coff); |
| 1695 | assert(sym.loc_relocs == .none); | 5617 | assert(sym.loc_relocs == .none); |
| 1696 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); | 5618 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| | 5619 | if (!isImage(coff) and sym.target_relocs != .none) |
| | 5620 | try coff.pendingSymbolTableEntry(si); |
| 1697 | break :ni sym.ni; | 5621 | break :ni sym.ni; |
| 1698 | }; | 5622 | }; |
| 1699 | | 5623 | |
| ... | @@ -1712,21 +5636,245 @@ fn updateFuncInner( | ... | @@ -1712,21 +5636,245 @@ fn updateFuncInner( |
| 1712 | error.WriteFailed => return nw.err.?, | 5636 | error.WriteFailed => return nw.err.?, |
| 1713 | else => |e| return e, | 5637 | else => |e| return e, |
| 1714 | }; | 5638 | }; |
| 1715 | si.get(coff).size = @intCast(nw.interface.end); | 5639 | si.get(coff).extra.size = @intCast(nw.interface.end); |
| 1716 | si.applyLocationRelocs(coff); | 5640 | try si.applyLocationRelocs(coff); |
| | 5641 | } |
| | 5642 | |
| | 5643 | pub fn updateErrorData(coff: *Coff, pt: Zcu.PerThread) !void { |
| | 5644 | coff.flushLazy(pt, .{ |
| | 5645 | .kind = .const_data, |
| | 5646 | .index = @intCast(coff.lazy.getPtr(.const_data).map.getIndex(.anyerror_type) orelse return), |
| | 5647 | }) catch |err| switch (err) { |
| | 5648 | else => |e| return e, |
| | 5649 | error.MappedFileIo => return coff.base.comp.link_diags.fail( |
| | 5650 | "updateErrorData failed: {t}", |
| | 5651 | .{coff.mf.io_err.?}, |
| | 5652 | ), |
| | 5653 | }; |
| | 5654 | } |
| | 5655 | |
| | 5656 | fn flushImplib( |
| | 5657 | coff: *Coff, |
| | 5658 | implib_file: []const u8, |
| | 5659 | ) !void { |
| | 5660 | // Emitting implibs is only valid for images |
| | 5661 | assert(coff.export_table.ni != .none); |
| | 5662 | |
| | 5663 | const comp = coff.base.comp; |
| | 5664 | const gpa = comp.gpa; |
| | 5665 | const io = comp.io; |
| | 5666 | |
| | 5667 | const image_name = std.mem.sliceTo( |
| | 5668 | coff.export_table.ni.slice(&coff.mf)[@sizeOf(std.coff.ExportDirectoryTable)..], |
| | 5669 | 0, |
| | 5670 | ); |
| | 5671 | const machine_type = coff.targetLoad(&coff.headerPtr().machine); |
| | 5672 | const members = members: { |
| | 5673 | const def_arena: std.heap.ArenaAllocator = .init(gpa); |
| | 5674 | var def: ModuleDefinition = .{ |
| | 5675 | .name = image_name, |
| | 5676 | .arena = def_arena, |
| | 5677 | .type = .mingw, |
| | 5678 | }; |
| | 5679 | defer def.deinit(); |
| | 5680 | |
| | 5681 | try def.exports.ensureUnusedCapacity( |
| | 5682 | def.arena.allocator(), |
| | 5683 | coff.export_table.entries.count(), |
| | 5684 | ); |
| | 5685 | |
| | 5686 | const name_table_slice = coff.export_table.name_table_ni.slice(&coff.mf); |
| | 5687 | for (coff.export_table.entries.values(), 0..) |entry, ord| { |
| | 5688 | const name = name_table_slice[entry.name_index..][0..entry.name_len]; |
| | 5689 | const section_number = entry.si.get(coff).section_number; |
| | 5690 | const import_type: std.coff.ImportType = switch (section_number.symbol(coff)) { |
| | 5691 | .data, .rdata => .DATA, |
| | 5692 | .text => .CODE, |
| | 5693 | else => return comp.link_diags.fail( |
| | 5694 | "unsupported section for export '{s}': {s}", |
| | 5695 | .{ name, &section_number.header(coff).name }, |
| | 5696 | ), |
| | 5697 | }; |
| | 5698 | |
| | 5699 | def.exports.appendAssumeCapacity(.{ |
| | 5700 | .name = name, |
| | 5701 | .mangled_symbol_name = null, |
| | 5702 | .ext_name = null, |
| | 5703 | .import_name = null, |
| | 5704 | .export_as = null, |
| | 5705 | .no_name = false, |
| | 5706 | .ordinal = @intCast(ord), |
| | 5707 | .type = import_type, |
| | 5708 | .private = false, |
| | 5709 | }); |
| | 5710 | } |
| | 5711 | |
| | 5712 | def.fixupForImportLibraryGeneration(machine_type); |
| | 5713 | break :members try implib.getMembers(gpa, def, machine_type); |
| | 5714 | }; |
| | 5715 | defer members.deinit(); |
| | 5716 | |
| | 5717 | const lib_sub_path = try std.fs.path.join(gpa, &.{ |
| | 5718 | std.fs.path.dirname(coff.base.emit.sub_path) orelse "", |
| | 5719 | implib_file, |
| | 5720 | }); |
| | 5721 | defer gpa.free(lib_sub_path); |
| | 5722 | |
| | 5723 | const lib_final_file = try coff.base.emit.root_dir.handle.createFile(io, lib_sub_path, .{ .truncate = true }); |
| | 5724 | defer lib_final_file.close(io); |
| | 5725 | var buffer: [1024]u8 = undefined; |
| | 5726 | var file_writer = lib_final_file.writer(io, &buffer); |
| | 5727 | try implib.writeCoffArchive(gpa, &file_writer.interface, members); |
| | 5728 | try file_writer.interface.flush(); |
| 1717 | } | 5729 | } |
| 1718 | | 5730 | |
| 1719 | pub fn updateErrorData(coff: *Coff, pt: Zcu.PerThread) !void { | 5731 | fn reportUndefs(coff: *Coff, tid: Zcu.PerThread.Id) !void { |
| 1720 | coff.flushLazy(pt, .{ | 5732 | const comp = coff.base.comp; |
| 1721 | .kind = .const_data, | 5733 | const gpa = comp.gpa; |
| 1722 | .index = @intCast(coff.lazy.getPtr(.const_data).map.getIndex(.anyerror_type) orelse return), | 5734 | const max_notes = 4; |
| 1723 | }) catch |err| switch (err) { | 5735 | |
| 1724 | else => |e| return e, | 5736 | var undef_indices: std.ArrayListUnmanaged(u32) = .empty; |
| 1725 | error.MappedFileIo => return coff.base.comp.link_diags.fail( | 5737 | for (coff.relocs.items, 0..) |reloc, reloc_i| { |
| 1726 | "updateErrorData failed: {t}", | 5738 | if (reloc.flags.free) continue; |
| 1727 | .{coff.mf.io_err.?}, | 5739 | const target_sym = reloc.target.get(coff); |
| 1728 | ), | 5740 | switch (target_sym.ni) { |
| 1729 | }; | 5741 | .none => { |
| | 5742 | assert(target_sym.gmi != .none); |
| | 5743 | if (target_sym.section_number == .ABSOLUTE) continue; |
| | 5744 | (try undef_indices.addOne(gpa)).* = @intCast(reloc_i); |
| | 5745 | }, |
| | 5746 | else => continue, |
| | 5747 | } |
| | 5748 | } |
| | 5749 | |
| | 5750 | if (undef_indices.items.len == 0) return; |
| | 5751 | |
| | 5752 | const undefLessThan = struct { |
| | 5753 | fn lessThan(ctx: *const Coff, lhs: u32, rhs: u32) bool { |
| | 5754 | const reloc_l = &ctx.relocs.items[lhs]; |
| | 5755 | const reloc_r = &ctx.relocs.items[rhs]; |
| | 5756 | if (reloc_l.target == reloc_r.target) |
| | 5757 | return @intFromEnum(reloc_l.loc) < @intFromEnum(reloc_r.loc) |
| | 5758 | else |
| | 5759 | return @intFromEnum(reloc_l.target) < @intFromEnum(reloc_r.target); |
| | 5760 | } |
| | 5761 | }.lessThan; |
| | 5762 | |
| | 5763 | std.mem.sortUnstable(u32, undef_indices.items, coff, undefLessThan); |
| | 5764 | |
| | 5765 | var start_i: usize = 0; |
| | 5766 | var num_unique_references: usize = 1; |
| | 5767 | for (0..undef_indices.items.len) |i| { |
| | 5768 | const target = coff.relocs.items[undef_indices.items[start_i]].target; |
| | 5769 | if (i == undef_indices.items.len - 1 or target != coff.relocs.items[undef_indices.items[i + 1]].target) { |
| | 5770 | defer { |
| | 5771 | start_i = i + 1; |
| | 5772 | num_unique_references = 1; |
| | 5773 | } |
| | 5774 | |
| | 5775 | const num_full_notes = @min(max_notes, num_unique_references); |
| | 5776 | var err = try comp.link_diags.addErrorWithNotes( |
| | 5777 | num_full_notes + @intFromBool(num_unique_references > max_notes), |
| | 5778 | ); |
| | 5779 | const target_sym = target.get(coff); |
| | 5780 | try err.addMsg("undefined symbol: {s}", .{target_sym.gmi.name(coff).toSlice(coff)}); |
| | 5781 | |
| | 5782 | // TODO: If lib_name is set, show the user |
| | 5783 | |
| | 5784 | var prev_loc_si: Symbol.Index = .null; |
| | 5785 | for (undef_indices.items[start_i .. i + 1]) |reference_i| { |
| | 5786 | if (err.note_slot == num_full_notes) break; |
| | 5787 | |
| | 5788 | const reloc = &coff.relocs.items[reference_i]; |
| | 5789 | const loc_si = reloc.loc; |
| | 5790 | if (loc_si == prev_loc_si) continue; |
| | 5791 | defer prev_loc_si = loc_si; |
| | 5792 | |
| | 5793 | const loc_sym = loc_si.get(coff); |
| | 5794 | |
| | 5795 | // TODO: Make this a helper for anything that needs to report "referenced by" notes |
| | 5796 | switch (coff.getNode(loc_sym.ni)) { |
| | 5797 | .data_directories => { |
| | 5798 | const dir: std.coff.IMAGE.DIRECTORY_ENTRY = |
| | 5799 | @enumFromInt(reloc.offset / @sizeOf(std.coff.ImageDataDirectory)); |
| | 5800 | err.addNote("referenced by data directory entry: {t}", .{dir}); |
| | 5801 | }, |
| | 5802 | .optional_header => err.addNote("referenced by optional header field", .{}), |
| | 5803 | .input_section => |isi| { |
| | 5804 | const other_ioi = isi.input(coff); |
| | 5805 | if (loc_sym.gmi == .none) { |
| | 5806 | const section = isi.inputSection(coff); |
| | 5807 | const section_name = coff.getNode(loc_sym.ni.parent(&coff.mf)) |
| | 5808 | .object_section.name(coff).toSlice(coff); |
| | 5809 | |
| | 5810 | if (section.comdat_si != .null) { |
| | 5811 | const comdat_sym = section.comdat_si.get(coff); |
| | 5812 | const comdat_name = if (comdat_sym.gmi != .none) |
| | 5813 | comdat_sym.gmi.name(coff).toSlice(coff) |
| | 5814 | else |
| | 5815 | comdat_sym.extra.isli.name(coff).toSlice(coff); |
| | 5816 | |
| | 5817 | err.addNote("referenced by input COMDAT section '{s}={s}' '{f}{f}'", .{ |
| | 5818 | section_name, |
| | 5819 | comdat_name, |
| | 5820 | other_ioi.path(coff).fmtEscapeString(), |
| | 5821 | fmtMemberNameString(other_ioi.memberName(coff)), |
| | 5822 | }); |
| | 5823 | } else { |
| | 5824 | err.addNote("referenced by input section '{s}' '{f}{f}'", .{ |
| | 5825 | section_name, |
| | 5826 | other_ioi.path(coff).fmtEscapeString(), |
| | 5827 | fmtMemberNameString(other_ioi.memberName(coff)), |
| | 5828 | }); |
| | 5829 | } |
| | 5830 | } else { |
| | 5831 | err.addNote("referenced by input symbol '{s}' from '{f}{f}'", .{ |
| | 5832 | loc_sym.gmi.name(coff).toSlice(coff), |
| | 5833 | other_ioi.path(coff).fmtEscapeString(), |
| | 5834 | fmtMemberNameString(other_ioi.memberName(coff)), |
| | 5835 | }); |
| | 5836 | } |
| | 5837 | }, |
| | 5838 | .import_thunk => |gmi| err.addNote("referenced by import thunk for '{s}'", .{ |
| | 5839 | gmi.name(coff).toSlice(coff), |
| | 5840 | }), |
| | 5841 | inline .nav, |
| | 5842 | .uav, |
| | 5843 | .lazy_code, |
| | 5844 | .lazy_const_data, |
| | 5845 | => |val, tag| { |
| | 5846 | err.addNote("referenced by '{f}'", .{ |
| | 5847 | format: switch (tag) { |
| | 5848 | .nav => { |
| | 5849 | const ip = &comp.zcu.?.intern_pool; |
| | 5850 | break :format ip.getNav(val.navIndex(coff)).fqn.fmt(ip); |
| | 5851 | }, |
| | 5852 | .uav => Value.fromInterned(val.uavValue(coff)).fmtValue(.{ |
| | 5853 | .zcu = coff.base.comp.zcu.?, |
| | 5854 | .tid = tid, |
| | 5855 | }), |
| | 5856 | inline .lazy_code, .lazy_const_data => Type.fromInterned(val.lazySymbol(coff).ty).fmt(.{ |
| | 5857 | .zcu = coff.base.comp.zcu.?, |
| | 5858 | .tid = tid, |
| | 5859 | }), |
| | 5860 | else => unreachable, |
| | 5861 | }, |
| | 5862 | }); |
| | 5863 | }, |
| | 5864 | else => unreachable, |
| | 5865 | } |
| | 5866 | } |
| | 5867 | |
| | 5868 | if (num_unique_references > max_notes) |
| | 5869 | err.addNote("referenced {d} more times", .{num_unique_references - max_notes}); |
| | 5870 | } else if (i != start_i and |
| | 5871 | coff.relocs.items[undef_indices.items[i - 1]].loc != coff.relocs.items[undef_indices.items[i]].loc) |
| | 5872 | { |
| | 5873 | num_unique_references += 1; |
| | 5874 | } |
| | 5875 | } |
| | 5876 | |
| | 5877 | return error.AlreadyReported; |
| 1730 | } | 5878 | } |
| 1731 | | 5879 | |
| 1732 | pub fn flush( | 5880 | pub fn flush( |
| ... | @@ -1734,35 +5882,79 @@ pub fn flush( | ... | @@ -1734,35 +5882,79 @@ pub fn flush( |
| 1734 | arena: std.mem.Allocator, | 5882 | arena: std.mem.Allocator, |
| 1735 | tid: Zcu.PerThread.Id, | 5883 | tid: Zcu.PerThread.Id, |
| 1736 | prog_node: std.Progress.Node, | 5884 | prog_node: std.Progress.Node, |
| 1737 | ) !void { | 5885 | ) link.Error!void { |
| 1738 | _ = arena; | 5886 | _ = arena; |
| 1739 | _ = prog_node; | 5887 | _ = prog_node; |
| | 5888 | const comp = coff.base.comp; |
| | 5889 | |
| | 5890 | // TODO: When https://github.com/ziglang/zig/issues/23617 is in, |
| | 5891 | // this should be set after updateExports instead |
| | 5892 | coff.exports_complete = true; |
| | 5893 | |
| | 5894 | while (try coff.resolve(tid)) {} |
| 1740 | while (try coff.idle(tid)) {} | 5895 | while (try coff.idle(tid)) {} |
| 1741 | | 5896 | |
| 1742 | // hack for stage2_x86_64 + coff | 5897 | // This has to occur after all other flushMoved / flushResized have resolved, |
| 1743 | const comp = coff.base.comp; | 5898 | // but it will also generate one more set of resizes and moves. |
| 1744 | if (comp.compiler_rt_dyn_lib) |crt_file| { | 5899 | if (coff.symbol_table.pending_shrink) { |
| 1745 | const gpa = comp.gpa; | 5900 | coff.symbol_table.pending_shrink = false; |
| 1746 | const io = comp.io; | 5901 | |
| 1747 | const compiler_rt_sub_path = try std.fs.path.join(gpa, &.{ | 5902 | const number_of_symbols = coff.targetLoad(&coff.headerPtr().number_of_symbols); |
| 1748 | std.fs.path.dirname(coff.base.emit.sub_path) orelse "", | 5903 | coff.symbol_table.ni.shrink( |
| 1749 | std.fs.path.basename(crt_file.full_object_path.sub_path), | 5904 | &coff.mf, |
| 1750 | }); | 5905 | comp.gpa, |
| 1751 | defer gpa.free(compiler_rt_sub_path); | 5906 | number_of_symbols * std.coff.Symbol.sizeOf(), |
| 1752 | std.Io.Dir.copyFile( | 5907 | true, |
| 1753 | crt_file.full_object_path.root_dir.handle, | 5908 | ) catch |err| return comp.link_diags.fail( |
| 1754 | crt_file.full_object_path.sub_path, | 5909 | "linker failed to compact symbol table: {t}", |
| 1755 | coff.base.emit.root_dir.handle, | 5910 | .{err}, |
| 1756 | compiler_rt_sub_path, | 5911 | ); |
| 1757 | io, | | |
| 1758 | .{}, | | |
| 1759 | ) catch |err| return comp.link_diags.fail("copy '{s}' failed: {t}", .{ compiler_rt_sub_path, err }); | | |
| 1760 | } | 5912 | } |
| | 5913 | while (try coff.idle(tid)) {} |
| | 5914 | |
| | 5915 | if (coff.isImage()) |
| | 5916 | try coff.reportUndefs(tid); |
| | 5917 | |
| | 5918 | if (comp.emit_implib) |implib_file| |
| | 5919 | coff.flushImplib(implib_file) catch |err| |
| | 5920 | return comp.link_diags.fail("flushing implib '{s}' failed: {t}", .{ implib_file, err }); |
| | 5921 | |
| | 5922 | coff.mf.flush() catch |err| switch (err) { |
| | 5923 | error.Canceled => |e| return e, |
| | 5924 | else => |e| return comp.link_diags.fail("flush write failed: {t}", .{e}), |
| | 5925 | }; |
| | 5926 | |
| | 5927 | if (coff.options.enable_link_snapshots) |
| | 5928 | coff.dumpStderr(tid) catch |err| |
| | 5929 | return comp.link_diags.fail("dumping link snapshot failed: {t}", .{err}); |
| 1761 | } | 5930 | } |
| 1762 | | 5931 | |
| 1763 | pub fn idle(coff: *Coff, tid: Zcu.PerThread.Id) !bool { | 5932 | /// Runs a single "resolution" task. |
| | 5933 | /// These are tasks that need to modify the node structure in some way. |
| | 5934 | /// They must run in a defined order with respect to linker tasks. |
| | 5935 | fn resolve(coff: *Coff, tid: Zcu.PerThread.Id) !bool { |
| 1764 | const comp = coff.base.comp; | 5936 | const comp = coff.base.comp; |
| 1765 | task: { | 5937 | task: { |
| | 5938 | while (coff.section_merge_pending_index < coff.section_merges.count()) { |
| | 5939 | defer coff.section_merge_pending_index += 1; |
| | 5940 | const sub_prog_node = coff.synth_prog_node.start( |
| | 5941 | coff.section_merges.keys()[coff.section_merge_pending_index].toSlice(coff), |
| | 5942 | 0, |
| | 5943 | ); |
| | 5944 | defer sub_prog_node.end(); |
| | 5945 | coff.flushSectionMerge(coff.section_merge_pending_index) catch |err| switch (err) { |
| | 5946 | //error.OutOfMemory => |e| return e, |
| | 5947 | else => |e| return comp.link_diags.fail( |
| | 5948 | "linker failed to merge section {s} into {s}: {t}", |
| | 5949 | .{ |
| | 5950 | coff.section_merges.keys()[coff.section_merge_pending_index].toSlice(coff), |
| | 5951 | coff.section_merges.values()[coff.section_merge_pending_index].toSlice(coff), |
| | 5952 | e, |
| | 5953 | }, |
| | 5954 | ), |
| | 5955 | }; |
| | 5956 | break :task; |
| | 5957 | } |
| 1766 | while (coff.pending_uavs.pop()) |pending_uav| { | 5958 | while (coff.pending_uavs.pop()) |pending_uav| { |
| 1767 | const sub_prog_node = coff.idleProgNode(tid, coff.const_prog_node, .{ .uav = pending_uav.key }); | 5959 | const sub_prog_node = coff.idleProgNode(tid, coff.const_prog_node, .{ .uav = pending_uav.key }); |
| 1768 | defer sub_prog_node.end(); | 5960 | defer sub_prog_node.end(); |
| ... | @@ -1779,22 +5971,52 @@ pub fn idle(coff: *Coff, tid: Zcu.PerThread.Id) !bool { | ... | @@ -1779,22 +5971,52 @@ pub fn idle(coff: *Coff, tid: Zcu.PerThread.Id) !bool { |
| 1779 | }; | 5971 | }; |
| 1780 | break :task; | 5972 | break :task; |
| 1781 | } | 5973 | } |
| 1782 | if (coff.global_pending_index < coff.globals.count()) { | 5974 | if (coff.pending_input) |pending_iami| { |
| 1783 | const pt: Zcu.PerThread = .{ .zcu = comp.zcu.?, .tid = tid }; | 5975 | const name_slice = pending_iami.member(coff).name.toSlice(coff); |
| 1784 | const gmi: Node.GlobalMapIndex = @enumFromInt(coff.global_pending_index); | 5976 | const sub_prog_node = coff.input_prog_node.start( |
| 1785 | coff.global_pending_index += 1; | 5977 | name_slice, |
| | 5978 | 0, |
| | 5979 | ); |
| | 5980 | defer sub_prog_node.end(); |
| | 5981 | coff.pending_input = null; |
| | 5982 | coff.flushInputMember(pending_iami) catch |err| switch (err) { |
| | 5983 | error.OutOfMemory => return error.OutOfMemory, |
| | 5984 | else => |e| return comp.link_diags.fail( |
| | 5985 | "linker failed to load archive member '{f}{f}': {t}", |
| | 5986 | .{ |
| | 5987 | pending_iami.member(coff).iai.path(coff), |
| | 5988 | fmtMemberNameString(name_slice), |
| | 5989 | e, |
| | 5990 | }, |
| | 5991 | ), |
| | 5992 | }; |
| | 5993 | break :task; |
| | 5994 | } |
| | 5995 | if (coff.exports_complete and coff.global_pending_index < coff.globals.count()) { |
| | 5996 | const gmi: Node.GlobalMapIndex = .wrap(coff.global_pending_index); |
| 1786 | const sub_prog_node = coff.synth_prog_node.start( | 5997 | const sub_prog_node = coff.synth_prog_node.start( |
| 1787 | gmi.globalName(coff).name.toSlice(coff), | 5998 | gmi.name(coff).toSlice(coff), |
| 1788 | 0, | 5999 | 0, |
| 1789 | ); | 6000 | ); |
| 1790 | defer sub_prog_node.end(); | 6001 | defer sub_prog_node.end(); |
| 1791 | coff.flushGlobal(pt, gmi) catch |err| switch (err) { | 6002 | if (coff.flushGlobal(gmi) catch |err| switch (err) { |
| 1792 | else => |e| return e, | 6003 | else => |e| return e, |
| 1793 | error.MappedFileIo => return comp.link_diags.fail( | 6004 | error.MappedFileIo => return comp.link_diags.fail( |
| 1794 | "linker failed to lower constant: {t}", | 6005 | "linker failed to lower constant: {t}", |
| 1795 | .{coff.mf.io_err.?}, | 6006 | .{coff.mf.io_err.?}, |
| 1796 | ), | 6007 | ), |
| 1797 | }; | 6008 | }) coff.global_pending_index += 1; |
| | 6009 | break :task; |
| | 6010 | } |
| | 6011 | if (coff.exports_complete and coff.pending_special_symbol != .none) { |
| | 6012 | coff.pending_special_symbol = coff.flushSpecialSymbol(coff.pending_special_symbol) catch |err| |
| | 6013 | switch (err) { |
| | 6014 | error.OutOfMemory => |e| return e, |
| | 6015 | else => |e| return comp.link_diags.fail( |
| | 6016 | "linker failed to flush special symbols: {t}", |
| | 6017 | .{e}, |
| | 6018 | ), |
| | 6019 | }; |
| 1798 | break :task; | 6020 | break :task; |
| 1799 | } | 6021 | } |
| 1800 | var lazy_it = coff.lazy.iterator(); | 6022 | var lazy_it = coff.lazy.iterator(); |
| ... | @@ -1824,6 +6046,73 @@ pub fn idle(coff: *Coff, tid: Zcu.PerThread.Id) !bool { | ... | @@ -1824,6 +6046,73 @@ pub fn idle(coff: *Coff, tid: Zcu.PerThread.Id) !bool { |
| 1824 | }; | 6046 | }; |
| 1825 | break :task; | 6047 | break :task; |
| 1826 | }; | 6048 | }; |
| | 6049 | if (coff.symbol_table.pending_symbol_index < coff.symbol_table.symbols.count()) { |
| | 6050 | defer coff.symbol_table.pending_symbol_index += 1; |
| | 6051 | const si = coff.symbol_table.symbols.keys()[coff.symbol_table.pending_symbol_index]; |
| | 6052 | const sym = si.get(coff); |
| | 6053 | const sub_prog_node = coff.idleProgNode( |
| | 6054 | tid, |
| | 6055 | coff.symbol_prog_node, |
| | 6056 | if (sym.ni != .none) |
| | 6057 | coff.getNode(sym.ni) |
| | 6058 | else |
| | 6059 | .{ .import_thunk = sym.gmi }, |
| | 6060 | ); |
| | 6061 | defer sub_prog_node.end(); |
| | 6062 | coff.flushSymbolTableEntry( |
| | 6063 | coff.symbol_table.pending_symbol_index, |
| | 6064 | .{ .zcu = comp.zcu.?, .tid = tid }, |
| | 6065 | ) catch |err| switch (err) { |
| | 6066 | error.OutOfMemory => return error.OutOfMemory, |
| | 6067 | else => |e| return comp.link_diags.fail( |
| | 6068 | "linker failed to flush symbol table entry: {t}", |
| | 6069 | .{e}, |
| | 6070 | ), |
| | 6071 | }; |
| | 6072 | break :task; |
| | 6073 | } |
| | 6074 | } |
| | 6075 | |
| | 6076 | if (coff.section_merge_pending_index < coff.section_merges.count()) return true; |
| | 6077 | if (coff.pending_uavs.count() > 0) return true; |
| | 6078 | if (coff.pending_input != null) return true; |
| | 6079 | if (coff.exports_complete and coff.globals.count() > coff.global_pending_index) return true; |
| | 6080 | assert(!coff.exports_complete or coff.inputs_complete); |
| | 6081 | if (coff.exports_complete and coff.pending_special_symbol != .none) return true; |
| | 6082 | for (&coff.lazy.values) |lazy| if (lazy.map.count() > lazy.pending_index) return true; |
| | 6083 | if (coff.symbol_table.pending_symbol_index < coff.symbol_table.symbols.count()) return true; |
| | 6084 | return false; |
| | 6085 | } |
| | 6086 | |
| | 6087 | pub fn idle(coff: *Coff, tid: Zcu.PerThread.Id) !bool { |
| | 6088 | // Idle tasks should not modify create / modify nodes, otherwise the output is not reproducible. |
| | 6089 | coff.mf.nodes_lock.lock(); |
| | 6090 | defer coff.mf.nodes_lock.unlock(); |
| | 6091 | |
| | 6092 | const comp = coff.base.comp; |
| | 6093 | task: { |
| | 6094 | // TODO: Idle task for flushing obj into lib |
| | 6095 | if (coff.input_section_pending_index < coff.input_sections.items.len) { |
| | 6096 | const isi: Node.InputSection.Index = @enumFromInt(coff.input_section_pending_index); |
| | 6097 | coff.input_section_pending_index += 1; |
| | 6098 | const sub_prog_node = coff.idleProgNode(tid, coff.input_prog_node, coff.getNode(isi.symbol(coff).node(coff))); |
| | 6099 | defer sub_prog_node.end(); |
| | 6100 | coff.flushInputSection(isi) catch |err| switch (err) { |
| | 6101 | else => |e| { |
| | 6102 | const ioi = isi.input(coff); |
| | 6103 | return comp.link_diags.fail( |
| | 6104 | "linker failed to read input section '{s}' from \"{f}{f}\": {t}", |
| | 6105 | .{ |
| | 6106 | isi.symbol(coff).get(coff).section_number.name(coff).toSlice(coff), |
| | 6107 | ioi.path(coff).fmtEscapeString(), |
| | 6108 | fmtMemberNameString(ioi.memberName(coff)), |
| | 6109 | e, |
| | 6110 | }, |
| | 6111 | ); |
| | 6112 | }, |
| | 6113 | }; |
| | 6114 | break :task; |
| | 6115 | } |
| 1827 | while (coff.mf.updates.pop()) |ni| { | 6116 | while (coff.mf.updates.pop()) |ni| { |
| 1828 | const clean_moved = ni.cleanMoved(&coff.mf); | 6117 | const clean_moved = ni.cleanMoved(&coff.mf); |
| 1829 | const clean_resized = ni.cleanResized(&coff.mf); | 6118 | const clean_resized = ni.cleanResized(&coff.mf); |
| ... | @@ -1836,11 +6125,33 @@ pub fn idle(coff: *Coff, tid: Zcu.PerThread.Id) !bool { | ... | @@ -1836,11 +6125,33 @@ pub fn idle(coff: *Coff, tid: Zcu.PerThread.Id) !bool { |
| 1836 | break :task; | 6125 | break :task; |
| 1837 | } else coff.mf.update_prog_node.completeOne(); | 6126 | } else coff.mf.update_prog_node.completeOne(); |
| 1838 | } | 6127 | } |
| | 6128 | while (coff.pending_members.pop()) |pending_mi| { |
| | 6129 | const sub_prog_node = coff.idleProgNode( |
| | 6130 | tid, |
| | 6131 | coff.symbol_prog_node, |
| | 6132 | coff.getNode(pending_mi.key.get(coff).content_ni), |
| | 6133 | ); |
| | 6134 | defer sub_prog_node.end(); |
| | 6135 | try coff.flushMember(pending_mi.key); |
| | 6136 | break :task; |
| | 6137 | } |
| | 6138 | if (coff.exports_complete and coff.export_table.pending_sort) { |
| | 6139 | defer coff.export_table.pending_sort = false; |
| | 6140 | const sub_prog_node = coff.idleProgNode( |
| | 6141 | tid, |
| | 6142 | coff.synth_prog_node, |
| | 6143 | coff.getNode(coff.export_table.ni), |
| | 6144 | ); |
| | 6145 | defer sub_prog_node.end(); |
| | 6146 | |
| | 6147 | coff.flushExportsSort(); |
| | 6148 | break :task; |
| | 6149 | } |
| 1839 | } | 6150 | } |
| 1840 | if (coff.pending_uavs.count() > 0) return true; | 6151 | if (coff.input_sections.items.len > coff.input_section_pending_index) return true; |
| 1841 | if (coff.globals.count() > coff.global_pending_index) return true; | | |
| 1842 | for (&coff.lazy.values) |lazy| if (lazy.map.count() > lazy.pending_index) return true; | | |
| 1843 | if (coff.mf.updates.items.len > 0) return true; | 6152 | if (coff.mf.updates.items.len > 0) return true; |
| | 6153 | if (coff.pending_members.count() > 0) return true; |
| | 6154 | if (coff.exports_complete and coff.export_table.pending_sort) return true; |
| 1844 | return false; | 6155 | return false; |
| 1845 | } | 6156 | } |
| 1846 | | 6157 | |
| ... | @@ -1855,7 +6166,15 @@ fn idleProgNode( | ... | @@ -1855,7 +6166,15 @@ fn idleProgNode( |
| 1855 | else => |tag| @tagName(tag), | 6166 | else => |tag| @tagName(tag), |
| 1856 | .image_section => |si| std.mem.sliceTo(&si.get(coff).section_number.header(coff).name, 0), | 6167 | .image_section => |si| std.mem.sliceTo(&si.get(coff).section_number.header(coff).name, 0), |
| 1857 | inline .pseudo_section, .object_section => |smi| smi.name(coff).toSlice(coff), | 6168 | inline .pseudo_section, .object_section => |smi| smi.name(coff).toSlice(coff), |
| 1858 | .global => |gmi| gmi.globalName(coff).name.toSlice(coff), | 6169 | .input_section => |isi| { |
| | 6170 | const ioi = isi.input(coff); |
| | 6171 | break :name std.fmt.bufPrint(&name, "{f}{f} {s}", .{ |
| | 6172 | ioi.path(coff).fmtEscapeString(), |
| | 6173 | fmtMemberNameString(ioi.memberName(coff)), |
| | 6174 | coff.getNode(isi.symbol(coff).node(coff).parent(&coff.mf)).object_section.name(coff).toSlice(coff), |
| | 6175 | }) catch &name; |
| | 6176 | }, |
| | 6177 | .import_thunk => |gmi| gmi.name(coff).toSlice(coff), |
| 1859 | .nav => |nmi| { | 6178 | .nav => |nmi| { |
| 1860 | const ip = &coff.base.comp.zcu.?.intern_pool; | 6179 | const ip = &coff.base.comp.zcu.?.intern_pool; |
| 1861 | break :name ip.getNav(nmi.navIndex(coff)).fqn.toSlice(ip); | 6180 | break :name ip.getNav(nmi.navIndex(coff)).fqn.toSlice(ip); |
| ... | @@ -1866,6 +6185,7 @@ fn idleProgNode( | ... | @@ -1866,6 +6185,7 @@ fn idleProgNode( |
| 1866 | .tid = tid, | 6185 | .tid = tid, |
| 1867 | }), | 6186 | }), |
| 1868 | }) catch &name, | 6187 | }) catch &name, |
| | 6188 | .archive_member => |mi| &mi.get(coff).headerPtr(coff).name, |
| 1869 | }, 0); | 6189 | }, 0); |
| 1870 | } | 6190 | } |
| 1871 | | 6191 | |
| ... | @@ -1886,9 +6206,10 @@ fn flushUav( | ... | @@ -1886,9 +6206,10 @@ fn flushUav( |
| 1886 | const sec_si = (try coff.objectSectionMapIndex( | 6206 | const sec_si = (try coff.objectSectionMapIndex( |
| 1887 | .@".rdata", | 6207 | .@".rdata", |
| 1888 | coff.mf.flags.block_size, | 6208 | coff.mf.flags.block_size, |
| 1889 | .{ .read = true }, | 6209 | .{ .read = true, .initialized = true }, |
| 1890 | )).symbol(coff); | 6210 | )).symbol(coff); |
| 1891 | try coff.nodes.ensureUnusedCapacity(gpa, 1); | 6211 | try coff.nodes.ensureUnusedCapacity(gpa, 1); |
| | 6212 | if (!isImage(coff)) try coff.symbol_table.symbols.ensureUnusedCapacity(gpa, 1); |
| 1892 | const sym = si.get(coff); | 6213 | const sym = si.get(coff); |
| 1893 | const ni = try coff.mf.addLastChildNode(gpa, sec_si.node(coff), .{ | 6214 | const ni = try coff.mf.addLastChildNode(gpa, sec_si.node(coff), .{ |
| 1894 | .alignment = uav_align.toStdMem(), | 6215 | .alignment = uav_align.toStdMem(), |
| ... | @@ -1907,6 +6228,9 @@ fn flushUav( | ... | @@ -1907,6 +6228,9 @@ fn flushUav( |
| 1907 | const sym = si.get(coff); | 6228 | const sym = si.get(coff); |
| 1908 | assert(sym.loc_relocs == .none); | 6229 | assert(sym.loc_relocs == .none); |
| 1909 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); | 6230 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| | 6231 | if (!isImage(coff) and sym.target_relocs != .none) |
| | 6232 | try coff.pendingSymbolTableEntry(si); |
| | 6233 | |
| 1910 | break :ni sym.ni; | 6234 | break :ni sym.ni; |
| 1911 | }; | 6235 | }; |
| 1912 | | 6236 | |
| ... | @@ -1923,173 +6247,561 @@ fn flushUav( | ... | @@ -1923,173 +6247,561 @@ fn flushUav( |
| 1923 | error.WriteFailed => return nw.err.?, | 6247 | error.WriteFailed => return nw.err.?, |
| 1924 | else => |e| return e, | 6248 | else => |e| return e, |
| 1925 | }; | 6249 | }; |
| 1926 | si.get(coff).size = @intCast(nw.interface.end); | 6250 | si.get(coff).extra.size = @intCast(nw.interface.end); |
| 1927 | si.applyLocationRelocs(coff); | 6251 | try si.applyLocationRelocs(coff); |
| 1928 | } | 6252 | } |
| 1929 | | 6253 | |
| 1930 | fn flushGlobal(coff: *Coff, pt: Zcu.PerThread, gmi: Node.GlobalMapIndex) !void { | 6254 | fn aliasGlobal(coff: *Coff, gmi: Node.GlobalMapIndex, alias_si: Symbol.Index) !void { |
| 1931 | const zcu = pt.zcu; | 6255 | const si = gmi.symbol(coff); |
| 1932 | const comp = zcu.comp; | 6256 | const sym = si.get(coff); |
| 1933 | const gpa = zcu.gpa; | 6257 | const alias_sym = alias_si.get(coff); |
| 1934 | const gn = gmi.globalName(coff); | 6258 | assert(sym.section_number == .UNDEFINED); |
| 1935 | if (gn.lib_name.toSlice(coff)) |lib_name| { | 6259 | assert(sym.loc_relocs == .none); |
| 1936 | const name = gn.name.toSlice(coff); | 6260 | |
| 1937 | try coff.nodes.ensureUnusedCapacity(gpa, 4); | 6261 | log.debug("aliasGlobal({s}, {?s}) {d}->{d} ({?s})", .{ |
| 1938 | try coff.symbol_table.ensureUnusedCapacity(gpa, 1); | 6262 | gmi.name(coff).toSlice(coff), |
| | 6263 | gmi.libName(coff).toSlice(coff), |
| | 6264 | si, |
| | 6265 | alias_si, |
| | 6266 | if (alias_sym.gmi != .none) alias_sym.gmi.name(coff).toSlice(coff) else null, |
| | 6267 | }); |
| 1939 | | 6268 | |
| 1940 | const target_endian = coff.targetEndian(); | 6269 | var ri = sym.target_relocs; |
| 1941 | const magic = coff.targetLoad(&coff.optionalHeaderStandardPtr().magic); | 6270 | while (ri != .none) { |
| 1942 | const addr_size: u64, const addr_align: std.mem.Alignment = switch (magic) { | 6271 | const reloc = ri.get(coff); |
| 1943 | _ => unreachable, | 6272 | assert(reloc.target == si); |
| 1944 | .PE32 => .{ 4, .@"4" }, | 6273 | reloc.target = alias_si; |
| 1945 | .@"PE32+" => .{ 8, .@"8" }, | 6274 | if (reloc.next == .none) { |
| 1946 | }; | 6275 | reloc.next = alias_sym.target_relocs; |
| | 6276 | if (alias_sym.target_relocs != .none) |
| | 6277 | alias_sym.target_relocs.get(coff).prev = ri; |
| | 6278 | break; |
| | 6279 | } |
| | 6280 | ri = reloc.next; |
| | 6281 | } |
| 1947 | | 6282 | |
| 1948 | const gop = try coff.import_table.entries.getOrPutAdapted( | 6283 | const prev_target_relocs = alias_sym.target_relocs; |
| 1949 | gpa, | 6284 | if (sym.target_relocs != .none) |
| 1950 | lib_name, | 6285 | alias_sym.target_relocs = sym.target_relocs; |
| 1951 | ImportTable.Adapter{ .coff = coff }, | 6286 | sym.target_relocs = .none; |
| 1952 | ); | 6287 | sym.gmi = alias_sym.gmi; |
| 1953 | const import_hint_name_align: std.mem.Alignment = .@"2"; | 6288 | coff.globals.values()[gmi.unwrap().?].si = alias_si; |
| 1954 | if (!gop.found_existing) { | 6289 | // Only apply the new relocs |
| 1955 | errdefer _ = coff.import_table.entries.pop(); | 6290 | try alias_si.applyTargetRelocs(coff, prev_target_relocs); |
| 1956 | try coff.import_table.ni.resize( | 6291 | } |
| 1957 | &coff.mf, | 6292 | |
| 1958 | gpa, | 6293 | fn flushGlobal(coff: *Coff, gmi: Node.GlobalMapIndex) !bool { |
| 1959 | @sizeOf(std.coff.ImportDirectoryEntry) * (gop.index + 2), | 6294 | const comp = coff.base.comp; |
| | 6295 | const gpa = comp.gpa; |
| | 6296 | const name = gmi.name(coff); |
| | 6297 | const si = gmi.symbol(coff); |
| | 6298 | |
| | 6299 | log.debug( |
| | 6300 | "flushGlobal({s}, {?s}) = n{d} {d}@{d}", |
| | 6301 | .{ |
| | 6302 | name.toSlice(coff), |
| | 6303 | gmi.libName(coff).toSlice(coff), |
| | 6304 | si.get(coff).ni, |
| | 6305 | si, |
| | 6306 | si.get(coff).section_number, |
| | 6307 | }, |
| | 6308 | ); |
| | 6309 | |
| | 6310 | if (!coff.isImage()) { |
| | 6311 | try coff.pendingSymbolTableEntry(si); |
| | 6312 | if (coff.isArchive() and si.get(coff).ni != .none) |
| | 6313 | try coff.ensureMemberSymbol( |
| | 6314 | coff.getNode(Node.known.zcu_member).archive_member, |
| | 6315 | name, |
| 1960 | ); | 6316 | ); |
| 1961 | const import_hint_name_table_len = | 6317 | |
| 1962 | import_hint_name_align.forward(lib_name.len + ".dll".len + 1); | 6318 | return true; |
| 1963 | const idata_section_ni = coff.import_table.ni.parent(&coff.mf); | 6319 | } |
| 1964 | const import_lookup_table_ni = try coff.mf.addLastChildNode(gpa, idata_section_ni, .{ | 6320 | |
| 1965 | .size = addr_size * 2, | 6321 | if (si.get(coff).ni != .none) |
| 1966 | .alignment = addr_align, | 6322 | return true; |
| 1967 | .moved = true, | 6323 | |
| 1968 | }); | 6324 | const Import = struct { |
| 1969 | const import_address_table_ni = try coff.mf.addLastChildNode(gpa, idata_section_ni, .{ | 6325 | lib_name: String, |
| 1970 | .size = addr_size * 2, | 6326 | name: String.Optional, |
| 1971 | .alignment = addr_align, | 6327 | ordinal_hint: u16, |
| 1972 | .moved = true, | 6328 | kind: enum { |
| 1973 | }); | 6329 | iat_ptr, |
| 1974 | const import_address_table_si = coff.addSymbolAssumeCapacity(); | 6330 | thunk, |
| 1975 | { | 6331 | }, |
| 1976 | const import_address_table_sym = import_address_table_si.get(coff); | 6332 | }; |
| 1977 | import_address_table_sym.ni = import_address_table_ni; | 6333 | |
| 1978 | assert(import_address_table_sym.loc_relocs == .none); | 6334 | const import: Import = import: { |
| 1979 | import_address_table_sym.loc_relocs = @enumFromInt(coff.relocs.items.len); | 6335 | const sym = si.get(coff); |
| 1980 | import_address_table_sym.section_number = | 6336 | const name_slice = name.toSlice(coff); |
| 1981 | coff.getNode(idata_section_ni).object_section.symbol(coff).get(coff).section_number; | 6337 | const imp_match = std.mem.startsWith(u8, name_slice, imp_prefix); |
| | 6338 | |
| | 6339 | // Globals may have the __imp_ prefix already if they are undef externals from another input. |
| | 6340 | assert(sym.flags.dll_storage_class != .dllexport); |
| | 6341 | const search_name, const is_imp = if (imp_match or sym.flags.dll_storage_class != .dllimport) |
| | 6342 | .{ name, imp_match } |
| | 6343 | else name: { |
| | 6344 | try coff.ensureUnusedStringCapacity(imp_prefix.len + name_slice.len); |
| | 6345 | const imp_name = try std.fmt.allocPrint(gpa, imp_prefix ++ "{s}", .{name_slice}); |
| | 6346 | defer gpa.free(imp_name); |
| | 6347 | break :name .{ coff.getOrPutStringAssumeCapacity(imp_name), true }; |
| | 6348 | }; |
| | 6349 | |
| | 6350 | const opt_alt_search_name = coff.alternate_names.get(search_name); |
| | 6351 | const search_libs = switch (sym.flags.value_tag) { |
| | 6352 | .weak_alias_si, .weak_alias_name => switch (sym.flags.weak_external_strat) { |
| | 6353 | .none => unreachable, |
| | 6354 | .no_library => false, |
| | 6355 | .library, |
| | 6356 | .alias, |
| | 6357 | => true, |
| | 6358 | .anti_dependency => return comp.link_diags.fail( |
| | 6359 | // TODO: Figure out what the purpose of this is |
| | 6360 | "TODO support anti_dependency weak external: {s}", |
| | 6361 | .{name.toSlice(coff)}, |
| | 6362 | ), |
| | 6363 | }, |
| | 6364 | else => true, |
| | 6365 | }; |
| | 6366 | |
| | 6367 | const opt_indices_lists: []const ?InputArchive.SearchList = if (search_libs) &.{ |
| | 6368 | coff.input_archive_symbol_indices.get(search_name), |
| | 6369 | if (opt_alt_search_name) |alt| coff.input_archive_symbol_indices.get(alt) else null, |
| | 6370 | } else &.{}; |
| | 6371 | |
| | 6372 | for (opt_indices_lists) |opt_indices_list| { |
| | 6373 | const indices_list = opt_indices_list orelse continue; |
| | 6374 | var iter: InputArchive.Member.Symbol.Index = indices_list.first; |
| | 6375 | while (true) { |
| | 6376 | const archive_sym = &coff.input_archive_symbols.items[@intFromEnum(iter)]; |
| | 6377 | const member = &coff.input_archive_members.items[@intFromEnum(archive_sym.iami)]; |
| | 6378 | member: switch (member.content) { |
| | 6379 | .object => if (!member.flags.is_loaded) { |
| | 6380 | if (gmi.libName(coff).unwrap()) |lib_name| |
| | 6381 | if (!std.ascii.eqlIgnoreCase( |
| | 6382 | lib_name.toSlice(coff), |
| | 6383 | member.iai.path(coff).stem(), |
| | 6384 | )) break :member; |
| | 6385 | |
| | 6386 | // Try loading the input member and then retry. |
| | 6387 | // This could still be a member containing imports |
| | 6388 | // that use the older non-IMPORT_HEADER method. |
| | 6389 | coff.pending_input = archive_sym.iami; |
| | 6390 | return false; |
| | 6391 | }, |
| | 6392 | .import => |import| { |
| | 6393 | if (gmi.libName(coff).unwrap()) |lib_name| |
| | 6394 | if (!std.ascii.eqlIgnoreCase( |
| | 6395 | import.lib_name.toSlice(coff), |
| | 6396 | lib_name.toSlice(coff), |
| | 6397 | )) break :member; |
| | 6398 | |
| | 6399 | const imp_name: String.Optional = name: switch (import.name_type) { |
| | 6400 | .NAME, |
| | 6401 | .NAME_NOPREFIX, |
| | 6402 | .NAME_UNDECORATE, |
| | 6403 | => |tag| { |
| | 6404 | const symbol_name: []const u8 = import.symbol_name.toSlice(coff); |
| | 6405 | const end_match = std.mem.endsWith(u8, name_slice, symbol_name); |
| | 6406 | const len_delta = name_slice.len -% symbol_name.len; |
| | 6407 | if (!end_match or |
| | 6408 | (!imp_match and len_delta != 0) or |
| | 6409 | (imp_match and len_delta != imp_prefix.len)) |
| | 6410 | return comp.link_diags.fail( |
| | 6411 | "global '{s}' has mismatched symbol name in import header: '{s}'", |
| | 6412 | .{ |
| | 6413 | name.toSlice(coff), |
| | 6414 | import.symbol_name.toSlice(coff), |
| | 6415 | }, |
| | 6416 | ); |
| | 6417 | |
| | 6418 | const imp_name = if (tag == .NAME) import.symbol_name else undecorated: { |
| | 6419 | var imp_name = std.mem.trimStart(u8, symbol_name, "?@_"); |
| | 6420 | if (tag == .NAME_UNDECORATE) |
| | 6421 | imp_name = std.mem.sliceTo(imp_name, '@'); |
| | 6422 | |
| | 6423 | try coff.ensureUnusedStringCapacity(imp_name.len); |
| | 6424 | break :undecorated coff.getOrPutStringAssumeCapacity(imp_name); |
| | 6425 | }; |
| | 6426 | |
| | 6427 | break :name imp_name.toOptional(); |
| | 6428 | }, |
| | 6429 | .ORDINAL => break :name .none, |
| | 6430 | else => |t| return comp.link_diags.fail("TODO handle name_type {t}", .{t}), |
| | 6431 | }; |
| | 6432 | |
| | 6433 | break :import .{ |
| | 6434 | .lib_name = import.lib_name, |
| | 6435 | .name = imp_name, |
| | 6436 | .ordinal_hint = import.import_ordinal_hint, |
| | 6437 | .kind = if (import.type == .CODE and !is_imp) .thunk else .iat_ptr, |
| | 6438 | }; |
| | 6439 | }, |
| | 6440 | } |
| | 6441 | |
| | 6442 | if (archive_sym.next == iter) break; |
| | 6443 | iter = archive_sym.next; |
| 1982 | } | 6444 | } |
| 1983 | const import_hint_name_table_ni = try coff.mf.addLastChildNode(gpa, idata_section_ni, .{ | 6445 | } |
| 1984 | .size = import_hint_name_table_len, | 6446 | |
| 1985 | .alignment = import_hint_name_align, | 6447 | switch (sym.flags.value_tag) { |
| 1986 | .moved = true, | 6448 | .weak_alias_si => { |
| 1987 | }); | 6449 | try coff.aliasGlobal(gmi, sym.value.weak_alias_si); |
| 1988 | gop.value_ptr.* = .{ | 6450 | return true; |
| 1989 | .import_lookup_table_ni = import_lookup_table_ni, | 6451 | }, |
| 1990 | .import_address_table_si = import_address_table_si, | 6452 | .weak_alias_name => { |
| 1991 | .import_hint_name_table_ni = import_hint_name_table_ni, | 6453 | // Convert an unresolved weak external that itself refers to an undef external |
| 1992 | .len = 0, | 6454 | // into a (possibly new) global, so it can be resolved separately. |
| 1993 | .hint_name_len = @intCast(import_hint_name_table_len), | 6455 | const alias_gop = try coff.getOrPutGlobalSymbol(.{ |
| | 6456 | .name = sym.value.weak_alias_name.toSlice(coff), |
| | 6457 | }); |
| | 6458 | try coff.aliasGlobal(gmi, alias_gop.value_ptr.si); |
| | 6459 | return true; |
| | 6460 | }, |
| | 6461 | else => {}, |
| | 6462 | } |
| | 6463 | |
| | 6464 | // If there was an object that had the alternate name, we've attempted to load it |
| | 6465 | if (opt_alt_search_name) |alt_search_name| { |
| | 6466 | if (coff.globals.get(alt_search_name)) |alias_global| { |
| | 6467 | try coff.aliasGlobal(gmi, alias_global.si); |
| | 6468 | return true; |
| | 6469 | } |
| | 6470 | } |
| | 6471 | |
| | 6472 | // Allow importing symbols with no implib entry, if a lib_name was specified. |
| | 6473 | // This is necessary for certain ntdll symbols, such as LdrRegisterDllNotification, |
| | 6474 | // which are not in the implib. |
| | 6475 | if (sym.flags.type != .unknown) { |
| | 6476 | if (gmi.libName(coff).unwrap()) |lib_name| break :import .{ |
| | 6477 | .lib_name = lib_name, |
| | 6478 | .name = name.toOptional(), |
| | 6479 | .ordinal_hint = 0, |
| | 6480 | .kind = if (sym.flags.type == .code) .thunk else .iat_ptr, |
| 1994 | }; | 6481 | }; |
| 1995 | const import_hint_name_slice = import_hint_name_table_ni.slice(&coff.mf); | | |
| 1996 | @memcpy(import_hint_name_slice[0..lib_name.len], lib_name); | | |
| 1997 | @memcpy(import_hint_name_slice[lib_name.len..][0..".dll".len], ".dll"); | | |
| 1998 | @memset(import_hint_name_slice[lib_name.len + ".dll".len ..], 0); | | |
| 1999 | coff.nodes.appendAssumeCapacity(.{ .import_lookup_table = @enumFromInt(gop.index) }); | | |
| 2000 | coff.nodes.appendAssumeCapacity(.{ .import_address_table = @enumFromInt(gop.index) }); | | |
| 2001 | coff.nodes.appendAssumeCapacity(.{ .import_hint_name_table = @enumFromInt(gop.index) }); | | |
| 2002 | | | |
| 2003 | const import_directory_entries = coff.importDirectoryTableSlice()[gop.index..][0..2]; | | |
| 2004 | import_directory_entries.* = .{ .{ | | |
| 2005 | .import_lookup_table_rva = coff.computeNodeRva(import_lookup_table_ni), | | |
| 2006 | .time_date_stamp = 0, | | |
| 2007 | .forwarder_chain = 0, | | |
| 2008 | .name_rva = coff.computeNodeRva(import_hint_name_table_ni), | | |
| 2009 | .import_address_table_rva = coff.computeNodeRva(import_address_table_ni), | | |
| 2010 | }, .{ | | |
| 2011 | .import_lookup_table_rva = 0, | | |
| 2012 | .time_date_stamp = 0, | | |
| 2013 | .forwarder_chain = 0, | | |
| 2014 | .name_rva = 0, | | |
| 2015 | .import_address_table_rva = 0, | | |
| 2016 | } }; | | |
| 2017 | if (target_endian != native_endian) | | |
| 2018 | std.mem.byteSwapAllFields([2]std.coff.ImportDirectoryEntry, import_directory_entries); | | |
| 2019 | } | 6482 | } |
| | 6483 | |
| | 6484 | return true; |
| | 6485 | }; |
| | 6486 | |
| | 6487 | try coff.nodes.ensureUnusedCapacity(gpa, 4); |
| | 6488 | try coff.symbols.ensureUnusedCapacity(gpa, 2); |
| | 6489 | |
| | 6490 | const target_endian = coff.targetEndian(); |
| | 6491 | const addr_info = coff.targetAddrInfo(); |
| | 6492 | const lib_name = import.lib_name.toSlice(coff); |
| | 6493 | const gop = try coff.import_table.entries.getOrPutAdapted( |
| | 6494 | gpa, |
| | 6495 | lib_name, |
| | 6496 | ImportTable.Adapter{ .coff = coff }, |
| | 6497 | ); |
| | 6498 | const import_hint_name_align: std.mem.Alignment = .@"2"; |
| | 6499 | if (!gop.found_existing) { |
| | 6500 | errdefer _ = coff.import_table.entries.pop(); |
| | 6501 | try coff.import_table.ni.resize( |
| | 6502 | &coff.mf, |
| | 6503 | gpa, |
| | 6504 | @sizeOf(std.coff.ImportDirectoryEntry) * (gop.index + 2), |
| | 6505 | ); |
| | 6506 | const import_hint_name_table_len = |
| | 6507 | import_hint_name_align.forward(lib_name.len + ".dll".len + 1); |
| | 6508 | const idata_section_ni = coff.import_table.ni.parent(&coff.mf); |
| | 6509 | const import_lookup_table_ni = try coff.mf.addLastChildNode(gpa, idata_section_ni, .{ |
| | 6510 | .size = addr_info.size * 2, |
| | 6511 | .alignment = addr_info.alignment, |
| | 6512 | .moved = true, |
| | 6513 | }); |
| | 6514 | const import_address_table_ni = try coff.mf.addLastChildNode(gpa, idata_section_ni, .{ |
| | 6515 | .size = addr_info.size * 2, |
| | 6516 | .alignment = addr_info.alignment, |
| | 6517 | .moved = true, |
| | 6518 | }); |
| | 6519 | const import_address_table_si = coff.addSymbolAssumeCapacity(); |
| | 6520 | { |
| | 6521 | const import_address_table_sym = import_address_table_si.get(coff); |
| | 6522 | import_address_table_sym.ni = import_address_table_ni; |
| | 6523 | assert(import_address_table_sym.loc_relocs == .none); |
| | 6524 | import_address_table_sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| | 6525 | import_address_table_sym.section_number = |
| | 6526 | coff.getNode(idata_section_ni).object_section.symbol(coff).get(coff).section_number; |
| | 6527 | } |
| | 6528 | const import_hint_name_table_ni = try coff.mf.addLastChildNode(gpa, idata_section_ni, .{ |
| | 6529 | .size = import_hint_name_table_len, |
| | 6530 | .alignment = import_hint_name_align, |
| | 6531 | .moved = true, |
| | 6532 | }); |
| | 6533 | gop.value_ptr.* = .{ |
| | 6534 | .import_lookup_table_ni = import_lookup_table_ni, |
| | 6535 | .import_address_table_si = import_address_table_si, |
| | 6536 | .import_hint_name_table_ni = import_hint_name_table_ni, |
| | 6537 | .import_address_table_symbols = .empty, |
| | 6538 | .len = 0, |
| | 6539 | .hint_name_len = @intCast(import_hint_name_table_len), |
| | 6540 | }; |
| | 6541 | const import_hint_name_slice = import_hint_name_table_ni.slice(&coff.mf); |
| | 6542 | @memcpy(import_hint_name_slice[0..lib_name.len], lib_name); |
| | 6543 | @memcpy(import_hint_name_slice[lib_name.len..][0..".dll".len], ".dll"); |
| | 6544 | @memset(import_hint_name_slice[lib_name.len + ".dll".len ..], 0); |
| | 6545 | coff.nodes.appendAssumeCapacity(.{ .import_lookup_table = @enumFromInt(gop.index) }); |
| | 6546 | coff.nodes.appendAssumeCapacity(.{ .import_address_table = @enumFromInt(gop.index) }); |
| | 6547 | coff.nodes.appendAssumeCapacity(.{ .import_hint_name_table = @enumFromInt(gop.index) }); |
| | 6548 | |
| | 6549 | const import_directory_entries = coff.importDirectoryTableSlice()[gop.index..][0..2]; |
| | 6550 | import_directory_entries.* = .{ .{ |
| | 6551 | .import_lookup_table_rva = coff.computeNodeRva(import_lookup_table_ni), |
| | 6552 | .time_date_stamp = 0, |
| | 6553 | .forwarder_chain = 0, |
| | 6554 | .name_rva = coff.computeNodeRva(import_hint_name_table_ni), |
| | 6555 | .import_address_table_rva = coff.computeNodeRva(import_address_table_ni), |
| | 6556 | }, .{ |
| | 6557 | .import_lookup_table_rva = 0, |
| | 6558 | .time_date_stamp = 0, |
| | 6559 | .forwarder_chain = 0, |
| | 6560 | .name_rva = 0, |
| | 6561 | .import_address_table_rva = 0, |
| | 6562 | } }; |
| | 6563 | if (target_endian != native_endian) |
| | 6564 | std.mem.byteSwapAllFields([2]std.coff.ImportDirectoryEntry, import_directory_entries); |
| | 6565 | } |
| | 6566 | |
| | 6567 | log.debug( |
| | 6568 | "flushGlobalImport({s}, {?s}, {d}, {s})", |
| | 6569 | .{ name.toSlice(coff), import.name.toSlice(coff), import.ordinal_hint, lib_name }, |
| | 6570 | ); |
| | 6571 | |
| | 6572 | const iat_symbol_gop = try coff.import_table.iat_symbol_indices.getOrPut(gpa, .{ |
| | 6573 | .iti = @enumFromInt(gop.index), |
| | 6574 | .name = import.name, |
| | 6575 | .ordinal_hint = import.ordinal_hint, |
| | 6576 | }); |
| | 6577 | if (!iat_symbol_gop.found_existing) { |
| 2020 | const import_symbol_index = gop.value_ptr.len; | 6578 | const import_symbol_index = gop.value_ptr.len; |
| | 6579 | iat_symbol_gop.value_ptr.* = import_symbol_index; |
| | 6580 | |
| 2021 | gop.value_ptr.len = import_symbol_index + 1; | 6581 | gop.value_ptr.len = import_symbol_index + 1; |
| 2022 | const new_symbol_table_size = addr_size * (import_symbol_index + 2); | 6582 | const new_symbol_table_size = addr_info.size * (import_symbol_index + 2); |
| 2023 | const import_hint_name_index = gop.value_ptr.hint_name_len; | 6583 | |
| 2024 | gop.value_ptr.hint_name_len = @intCast( | | |
| 2025 | import_hint_name_align.forward(import_hint_name_index + 2 + name.len + 1), | | |
| 2026 | ); | | |
| 2027 | try gop.value_ptr.import_lookup_table_ni.resize(&coff.mf, gpa, new_symbol_table_size); | 6584 | try gop.value_ptr.import_lookup_table_ni.resize(&coff.mf, gpa, new_symbol_table_size); |
| 2028 | const import_address_table_ni = gop.value_ptr.import_address_table_si.node(coff); | 6585 | const import_address_table_ni = gop.value_ptr.import_address_table_si.node(coff); |
| 2029 | try import_address_table_ni.resize(&coff.mf, gpa, new_symbol_table_size); | 6586 | try import_address_table_ni.resize(&coff.mf, gpa, new_symbol_table_size); |
| 2030 | try gop.value_ptr.import_hint_name_table_ni.resize(&coff.mf, gpa, gop.value_ptr.hint_name_len); | 6587 | |
| | 6588 | const opt_imp_name = import.name.toSlice(coff); |
| | 6589 | const opt_import_hint_name_index = if (opt_imp_name) |imp_name| blk: { |
| | 6590 | const import_hint_name_index = gop.value_ptr.hint_name_len; |
| | 6591 | gop.value_ptr.hint_name_len = @intCast( |
| | 6592 | import_hint_name_align.forward(import_hint_name_index + 2 + imp_name.len + 1), |
| | 6593 | ); |
| | 6594 | try gop.value_ptr.import_hint_name_table_ni.resize(&coff.mf, gpa, gop.value_ptr.hint_name_len); |
| | 6595 | break :blk import_hint_name_index; |
| | 6596 | } else null; |
| | 6597 | |
| | 6598 | const import_hint_name_rva = if (opt_import_hint_name_index) |import_hint_name_index| blk: { |
| | 6599 | const import_hint_name_slice = gop.value_ptr.import_hint_name_table_ni.slice(&coff.mf); |
| | 6600 | const ordinal_hint: *u16 = @ptrCast(@alignCast(import_hint_name_slice[import_hint_name_index..][0..2])); |
| | 6601 | ordinal_hint.* = std.mem.nativeTo(u16, import.ordinal_hint, target_endian); |
| | 6602 | @memcpy(import_hint_name_slice[import_hint_name_index + 2 ..][0..opt_imp_name.?.len], opt_imp_name.?); |
| | 6603 | @memset(import_hint_name_slice[import_hint_name_index + 2 + opt_imp_name.?.len ..], 0); |
| | 6604 | break :blk coff.computeNodeRva(gop.value_ptr.import_hint_name_table_ni) + import_hint_name_index; |
| | 6605 | } else 0; |
| | 6606 | |
| 2031 | const import_lookup_slice = gop.value_ptr.import_lookup_table_ni.slice(&coff.mf); | 6607 | const import_lookup_slice = gop.value_ptr.import_lookup_table_ni.slice(&coff.mf); |
| 2032 | const import_address_slice = import_address_table_ni.slice(&coff.mf); | 6608 | const import_address_slice = import_address_table_ni.slice(&coff.mf); |
| 2033 | const import_hint_name_slice = gop.value_ptr.import_hint_name_table_ni.slice(&coff.mf); | 6609 | switch (addr_info.magic) { |
| 2034 | @memset(import_hint_name_slice[import_hint_name_index..][0..2], 0); | | |
| 2035 | @memcpy(import_hint_name_slice[import_hint_name_index + 2 ..][0..name.len], name); | | |
| 2036 | @memset(import_hint_name_slice[import_hint_name_index + 2 + name.len ..], 0); | | |
| 2037 | const import_hint_name_rva = | | |
| 2038 | coff.computeNodeRva(gop.value_ptr.import_hint_name_table_ni) + import_hint_name_index; | | |
| 2039 | switch (magic) { | | |
| 2040 | _ => unreachable, | 6610 | _ => unreachable, |
| 2041 | inline .PE32, .@"PE32+" => |ct_magic| { | 6611 | inline .PE32, .@"PE32+" => |ct_magic| { |
| 2042 | const Addr = switch (ct_magic) { | 6612 | const Entry = std.coff.ImportLookupTableEntry(ct_magic); |
| 2043 | _ => comptime unreachable, | 6613 | const import_lookup_table: []Entry = @ptrCast(@alignCast(import_lookup_slice)); |
| 2044 | .PE32 => u32, | 6614 | const import_address_table: []Entry = @ptrCast(@alignCast(import_address_slice)); |
| 2045 | .@"PE32+" => u64, | 6615 | var import_hint_name_rvas: [2]Entry = .{ |
| 2046 | }; | 6616 | .{ |
| 2047 | const import_lookup_table: []Addr = @ptrCast(@alignCast(import_lookup_slice)); | 6617 | .payload = if (import.name == .none) |
| 2048 | const import_address_table: []Addr = @ptrCast(@alignCast(import_address_slice)); | 6618 | .{ .ordinal = .{ .ordinal = import.ordinal_hint } } |
| 2049 | const import_hint_name_rvas: [2]Addr = .{ | 6619 | else |
| 2050 | std.mem.nativeTo(Addr, @intCast(import_hint_name_rva), target_endian), | 6620 | .{ .hint_name_rva = @intCast(import_hint_name_rva) }, |
| 2051 | std.mem.nativeTo(Addr, 0, target_endian), | 6621 | .is_ordinal = import.name == .none, |
| | 6622 | }, |
| | 6623 | @bitCast(@as(@typeInfo(Entry).@"struct".backing_integer.?, 0)), |
| 2052 | }; | 6624 | }; |
| | 6625 | if (native_endian != target_endian) |
| | 6626 | for (&import_hint_name_rvas) |*v| std.mem.byteSwapAllFields(Entry, v); |
| | 6627 | |
| 2053 | import_lookup_table[import_symbol_index..][0..2].* = import_hint_name_rvas; | 6628 | import_lookup_table[import_symbol_index..][0..2].* = import_hint_name_rvas; |
| 2054 | import_address_table[import_symbol_index..][0..2].* = import_hint_name_rvas; | 6629 | import_address_table[import_symbol_index..][0..2].* = import_hint_name_rvas; |
| 2055 | }, | 6630 | }, |
| 2056 | } | 6631 | } |
| 2057 | const si = gmi.symbol(coff); | 6632 | } |
| 2058 | const sym = si.get(coff); | 6633 | |
| 2059 | sym.section_number = Symbol.Index.text.get(coff).section_number; | 6634 | const sym = si.get(coff); |
| 2060 | assert(sym.loc_relocs == .none); | 6635 | assert(sym.loc_relocs == .none); |
| 2061 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); | 6636 | const iat_offset: u32 = @intCast(addr_info.size * iat_symbol_gop.value_ptr.*); |
| 2062 | switch (coff.targetLoad(&coff.headerPtr().machine)) { | 6637 | switch (import.kind) { |
| 2063 | else => |tag| @panic(@tagName(tag)), | 6638 | .iat_ptr => { |
| 2064 | .AMD64 => { | 6639 | const iat_sym = gop.value_ptr.import_address_table_si.get(coff); |
| 2065 | const init = [_]u8{ 0xff, 0x25, 0x00, 0x00, 0x00, 0x00 }; | 6640 | sym.section_number = iat_sym.section_number; |
| 2066 | const target = &comp.root_mod.resolved_target.result; | 6641 | sym.ni = iat_sym.ni; |
| 2067 | const ni = try coff.mf.addLastChildNode(gpa, Symbol.Index.text.node(coff), .{ | 6642 | sym.setValue(.{ .node_offset = iat_offset }); |
| 2068 | .alignment = switch (comp.root_mod.optimize_mode) { | 6643 | (try gop.value_ptr.import_address_table_symbols.addOne(gpa)).* = si; |
| 2069 | .Debug, | 6644 | }, |
| 2070 | .ReleaseSafe, | 6645 | .thunk => { |
| 2071 | .ReleaseFast, | 6646 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| 2072 | => target_util.defaultFunctionAlignment(target), | 6647 | |
| 2073 | .ReleaseSmall => target_util.minFunctionAlignment(target), | 6648 | const target = &comp.root_mod.resolved_target.result; |
| 2074 | }.toStdMem(), | 6649 | const alignment = switch (comp.root_mod.optimize_mode) { |
| 2075 | .size = init.len, | 6650 | .Debug, |
| 2076 | }); | 6651 | .ReleaseSafe, |
| 2077 | @memcpy(ni.slice(&coff.mf)[0..init.len], &init); | 6652 | .ReleaseFast, |
| 2078 | sym.ni = ni; | 6653 | => target_util.defaultFunctionAlignment(target), |
| 2079 | sym.size = init.len; | 6654 | .ReleaseSmall => target_util.minFunctionAlignment(target), |
| | 6655 | }.toStdMem(); |
| | 6656 | const parent_si = (try coff.pseudoSectionMapIndex( |
| | 6657 | .@".thunks", |
| | 6658 | alignment, |
| | 6659 | .{ .execute = true, .read = true }, |
| | 6660 | )).symbol(coff); |
| | 6661 | |
| | 6662 | const parent_sym = parent_si.get(coff); |
| | 6663 | sym.section_number = parent_sym.section_number; |
| | 6664 | |
| | 6665 | switch (coff.targetLoad(&coff.headerPtr().machine)) { |
| | 6666 | else => |tag| @panic(@tagName(tag)), |
| | 6667 | .AMD64 => { |
| | 6668 | const init = [_]u8{ 0xff, 0x25, 0x00, 0x00, 0x00, 0x00 }; |
| | 6669 | const ni = try coff.mf.addLastChildNode(gpa, parent_sym.ni, .{ |
| | 6670 | .alignment = alignment, |
| | 6671 | .size = init.len, |
| | 6672 | }); |
| | 6673 | @memcpy(ni.slice(&coff.mf)[0..init.len], &init); |
| | 6674 | sym.ni = ni; |
| | 6675 | sym.extra.size = init.len; |
| | 6676 | try coff.addReloc( |
| | 6677 | si, |
| | 6678 | init.len - 4, |
| | 6679 | gop.value_ptr.import_address_table_si, |
| | 6680 | .{ .known = iat_offset }, |
| | 6681 | .{ .AMD64 = .REL32 }, |
| | 6682 | ); |
| | 6683 | }, |
| | 6684 | } |
| | 6685 | coff.nodes.appendAssumeCapacity(.{ .import_thunk = gmi }); |
| | 6686 | }, |
| | 6687 | } |
| | 6688 | |
| | 6689 | try si.flushMoved(coff); |
| | 6690 | return true; |
| | 6691 | } |
| | 6692 | |
| | 6693 | fn flushSpecialSymbol(coff: *Coff, pending: SpecialSymbol) !SpecialSymbol { |
| | 6694 | const comp = coff.base.comp; |
| | 6695 | |
| | 6696 | if (!coff.isImage()) return .none; |
| | 6697 | const gpa = comp.gpa; |
| | 6698 | const machine = coff.targetLoad(&coff.headerPtr().machine); |
| | 6699 | const target = &comp.root_mod.resolved_target.result; |
| | 6700 | |
| | 6701 | return next: switch (pending) { |
| | 6702 | .entry => { |
| | 6703 | // TODO: Use explicitly specified entry if set, add err if not found |
| | 6704 | const entries: []const struct { ?[]const u8, []const u8 } = if (coff.isExe()) |
| | 6705 | if (comp.config.link_libc) switch (coff.optionalHeaderField(.subsystem)) { |
| | 6706 | .WINDOWS_CUI => &.{ |
| | 6707 | .{ "main", "mainCRTStartup" }, |
| | 6708 | .{ "wmain", "wmainCRTStartup" }, |
| | 6709 | }, |
| | 6710 | .WINDOWS_GUI => &.{ |
| | 6711 | .{ "WinMain", "WinMainCRTStartup" }, |
| | 6712 | .{ "wWinMain", "wWinMainCRTStartup" }, |
| | 6713 | }, |
| | 6714 | else => unreachable, |
| | 6715 | } else &.{ |
| | 6716 | .{ "wWinMainCRTStartup", "wWinMainCRTStartup" }, |
| | 6717 | } |
| | 6718 | else |
| | 6719 | &.{.{ null, if (target.abi.isGnu()) "DllMainCRTStartup" else "_DllMainCRTStartup" }}; |
| | 6720 | |
| | 6721 | const entry_si = for (entries) |entry| { |
| | 6722 | if (entry[0]) |required_name| |
| | 6723 | if (coff.getDefinedGlobal(required_name) == .null) continue; |
| | 6724 | |
| | 6725 | break try coff.globalSymbol(.{ .name = entry[1], .type = .code }); |
| | 6726 | } else .null; |
| | 6727 | |
| | 6728 | if (entry_si != .null) { |
| | 6729 | log.debug( |
| | 6730 | "entry({s}, {d})", |
| | 6731 | .{ entry_si.get(coff).gmi.name(coff).toSlice(coff), entry_si }, |
| | 6732 | ); |
| | 6733 | |
| | 6734 | try coff.symbols.ensureUnusedCapacity(gpa, 1); |
| | 6735 | const optional_hdr_si = coff.addSymbolAssumeCapacity(); |
| | 6736 | const optional_hdr_sym = optional_hdr_si.get(coff); |
| | 6737 | optional_hdr_sym.ni = Node.known.optional_header; |
| | 6738 | assert(optional_hdr_sym.loc_relocs == .none); |
| | 6739 | optional_hdr_sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| | 6740 | |
| | 6741 | const optional_hdr = coff.optionalHeaderStandardPtr(); |
| | 6742 | optional_hdr.address_of_entry_point = std.mem.nativeTo( |
| | 6743 | u32, |
| | 6744 | entry_si.get(coff).rva, |
| | 6745 | coff.targetEndian(), |
| | 6746 | ); |
| | 6747 | |
| | 6748 | try coff.addReloc( |
| | 6749 | optional_hdr_si, |
| | 6750 | @intFromPtr(&optional_hdr.address_of_entry_point) - @intFromPtr(optional_hdr), |
| | 6751 | entry_si, |
| | 6752 | .{ .known = 0 }, |
| | 6753 | switch (machine) { |
| | 6754 | else => |tag| @panic(@tagName(tag)), |
| | 6755 | .AMD64 => .{ .AMD64 = .ADDR32NB }, |
| | 6756 | .I386 => .{ .I386 = .DIR32NB }, |
| | 6757 | }, |
| | 6758 | ); |
| | 6759 | } |
| | 6760 | |
| | 6761 | // Referencing the startup functions may trigger loading the object containing them, |
| | 6762 | // we need to wait until that is done before looking for further symbols. |
| | 6763 | break :next .tls; |
| | 6764 | }, |
| | 6765 | .tls => { |
| | 6766 | if (coff.getDefinedGlobal("_tls_used").unwrap()) |tls_used_si| { |
| | 6767 | log.debug("tlsDir({d})", .{tls_used_si}); |
| | 6768 | |
| | 6769 | const tls_directory = coff.dataDirectoryPtr(.TLS); |
| | 6770 | tls_directory.* = .{ |
| | 6771 | .virtual_address = tls_used_si.get(coff).rva, |
| | 6772 | .size = switch (coff.targetLoad(&coff.optionalHeaderStandardPtr().magic)) { |
| | 6773 | _ => unreachable, |
| | 6774 | .PE32 => 24, |
| | 6775 | .@"PE32+" => 40, |
| | 6776 | }, |
| | 6777 | }; |
| | 6778 | if (coff.targetEndian() != native_endian) |
| | 6779 | std.mem.byteSwapAllFields(std.coff.ImageDataDirectory, tls_directory); |
| | 6780 | |
| | 6781 | try coff.symbols.ensureUnusedCapacity(gpa, 1); |
| | 6782 | const data_dir_si = coff.addSymbolAssumeCapacity(); |
| | 6783 | const data_dir_sym = data_dir_si.get(coff); |
| | 6784 | data_dir_sym.ni = Node.known.data_directories; |
| | 6785 | assert(data_dir_sym.loc_relocs == .none); |
| | 6786 | data_dir_sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| | 6787 | |
| 2080 | try coff.addReloc( | 6788 | try coff.addReloc( |
| 2081 | si, | 6789 | data_dir_si, |
| 2082 | init.len - 4, | 6790 | @intFromPtr(&tls_directory.virtual_address) - @intFromPtr(coff.dataDirectorySlice().ptr), |
| 2083 | gop.value_ptr.import_address_table_si, | 6791 | tls_used_si, |
| 2084 | @intCast(addr_size * import_symbol_index), | 6792 | .{ .known = 0 }, |
| 2085 | .{ .AMD64 = .REL32 }, | 6793 | switch (machine) { |
| | 6794 | else => |tag| @panic(@tagName(tag)), |
| | 6795 | .AMD64 => .{ .AMD64 = .ADDR32NB }, |
| | 6796 | .I386 => .{ .I386 = .DIR32NB }, |
| | 6797 | }, |
| 2086 | ); | 6798 | ); |
| 2087 | }, | 6799 | } |
| 2088 | } | 6800 | |
| 2089 | coff.nodes.appendAssumeCapacity(.{ .global = gmi }); | 6801 | break :next .none; |
| 2090 | sym.rva = coff.computeNodeRva(sym.ni); | 6802 | }, |
| 2091 | si.applyLocationRelocs(coff); | 6803 | .none => unreachable, |
| 2092 | } | 6804 | }; |
| 2093 | } | 6805 | } |
| 2094 | | 6806 | |
| 2095 | fn flushLazy(coff: *Coff, pt: Zcu.PerThread, lmr: Node.LazyMapRef) !void { | 6807 | fn flushLazy(coff: *Coff, pt: Zcu.PerThread, lmr: Node.LazyMapRef) !void { |
| ... | @@ -2119,6 +6831,9 @@ fn flushLazy(coff: *Coff, pt: Zcu.PerThread, lmr: Node.LazyMapRef) !void { | ... | @@ -2119,6 +6831,9 @@ fn flushLazy(coff: *Coff, pt: Zcu.PerThread, lmr: Node.LazyMapRef) !void { |
| 2119 | } | 6831 | } |
| 2120 | assert(sym.loc_relocs == .none); | 6832 | assert(sym.loc_relocs == .none); |
| 2121 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); | 6833 | sym.loc_relocs = @enumFromInt(coff.relocs.items.len); |
| | 6834 | if (!isImage(coff) and sym.target_relocs != .none) |
| | 6835 | try coff.pendingSymbolTableEntry(si); |
| | 6836 | |
| 2122 | break :ni sym.ni; | 6837 | break :ni sym.ni; |
| 2123 | }; | 6838 | }; |
| 2124 | | 6839 | |
| ... | @@ -2138,42 +6853,107 @@ fn flushLazy(coff: *Coff, pt: Zcu.PerThread, lmr: Node.LazyMapRef) !void { | ... | @@ -2138,42 +6853,107 @@ fn flushLazy(coff: *Coff, pt: Zcu.PerThread, lmr: Node.LazyMapRef) !void { |
| 2138 | error.WriteFailed => return nw.err.?, | 6853 | error.WriteFailed => return nw.err.?, |
| 2139 | else => |e| return e, | 6854 | else => |e| return e, |
| 2140 | }; | 6855 | }; |
| 2141 | si.get(coff).size = @intCast(nw.interface.end); | 6856 | si.get(coff).extra.size = @intCast(nw.interface.end); |
| 2142 | si.applyLocationRelocs(coff); | 6857 | try si.applyLocationRelocs(coff); |
| 2143 | } | 6858 | } |
| 2144 | | 6859 | |
| 2145 | fn flushMoved(coff: *Coff, ni: MappedFile.Node.Index) !void { | 6860 | fn flushMoved(coff: *Coff, ni: MappedFile.Node.Index) !void { |
| | 6861 | log.debug("flushMoved({s}, n{d})", .{ @tagName(coff.getNode(ni)), ni }); |
| 2146 | switch (coff.getNode(ni)) { | 6862 | switch (coff.getNode(ni)) { |
| 2147 | .file, | 6863 | .file, |
| 2148 | .header, | 6864 | .header, |
| 2149 | .signature, | 6865 | .signature, |
| | 6866 | => unreachable, |
| 2150 | .coff_header, | 6867 | .coff_header, |
| 2151 | .optional_header, | 6868 | .optional_header, |
| 2152 | .data_directories, | 6869 | .data_directories, |
| 2153 | .section_table, | 6870 | .section_table, |
| 2154 | => unreachable, | 6871 | .placeholder, |
| 2155 | .image_section => |si| return coff.targetStore( | 6872 | => assert(!coff.isImage()), |
| 2156 | &si.get(coff).section_number.header(coff).pointer_to_raw_data, | 6873 | .symbol_table, |
| 2157 | @intCast(ni.fileLocation(&coff.mf, false).offset), | 6874 | .string_table, |
| 2158 | ), | 6875 | => |_, tag| { |
| 2159 | .import_directory_table => coff.targetStore( | 6876 | if (tag == .symbol_table) |
| 2160 | &coff.dataDirectoryPtr(.IMPORT).virtual_address, | 6877 | coff.targetStore( |
| 2161 | coff.computeNodeRva(ni), | 6878 | &coff.headerPtr().pointer_to_symbol_table, |
| 2162 | ), | 6879 | @intCast(ni.location(&coff.mf).resolve(&coff.mf)[0]), |
| | 6880 | ); |
| | 6881 | |
| | 6882 | if (!coff.symbol_table.pending_shrink) { |
| | 6883 | const symbol_table_loc, const symbol_table_size = coff.symbol_table.ni.location(&coff.mf).resolve(&coff.mf); |
| | 6884 | const string_table_offset, _ = coff.symbol_table.strings_ni.location(&coff.mf).resolve(&coff.mf); |
| | 6885 | coff.symbol_table.pending_shrink = string_table_offset - (symbol_table_loc + symbol_table_size) > 0; |
| | 6886 | } |
| | 6887 | }, |
| | 6888 | .relocation_table => |sn| { |
| | 6889 | coff.targetStore( |
| | 6890 | &sn.header(coff).pointer_to_relocations, |
| | 6891 | @intCast(ni.location(&coff.mf).resolve(&coff.mf)[0]), |
| | 6892 | ); |
| | 6893 | }, |
| | 6894 | .relocation_table_entry => {}, |
| | 6895 | .archive_member_header => |mi| { |
| | 6896 | const member = mi.get(coff); |
| | 6897 | switch (member.kind) { |
| | 6898 | .first_linker, .second_linker, .longnames => {}, |
| | 6899 | else => coff.targetStore( |
| | 6900 | &coff.secondLinkerMemberOffsetsSlice()[@intFromEnum(mi) - Member.Index.known_count], |
| | 6901 | @intCast(ni.fileLocation(&coff.mf, false).offset), |
| | 6902 | ), |
| | 6903 | } |
| | 6904 | |
| | 6905 | if (member.kind == .coff) |
| | 6906 | try coff.pending_members.put(coff.base.comp.gpa, mi, {}); |
| | 6907 | }, |
| | 6908 | .archive_member, |
| | 6909 | => {}, |
| | 6910 | .image_section => |si| { |
| | 6911 | const sym = si.get(coff); |
| | 6912 | const flags = coff.targetLoad(&sym.section_number.header(coff).flags); |
| | 6913 | if (!flags.CNT_UNINITIALIZED_DATA) { |
| | 6914 | const file_offset = if (isArchive(coff)) |
| | 6915 | sym.ni.location(&coff.mf).resolve(&coff.mf)[0] |
| | 6916 | else |
| | 6917 | ni.fileLocation(&coff.mf, false).offset; |
| | 6918 | |
| | 6919 | return coff.targetStore( |
| | 6920 | &sym.section_number.header(coff).pointer_to_raw_data, |
| | 6921 | @intCast(file_offset), |
| | 6922 | ); |
| | 6923 | } |
| | 6924 | }, |
| | 6925 | .input_section => |isi| { |
| | 6926 | try isi.symbol(coff).flushMoved(coff); |
| | 6927 | for (coff.input_symbols.items[@intFromEnum(isi.firstSymbol(coff))..]) |input_symbol| { |
| | 6928 | if (input_symbol.si.get(coff).ni != ni) break; |
| | 6929 | try input_symbol.si.flushMoved(coff); |
| | 6930 | } |
| | 6931 | }, |
| | 6932 | .import_directory_table => { |
| | 6933 | _, const size = ni.location(&coff.mf).resolve(&coff.mf); |
| | 6934 | if (size > 0) |
| | 6935 | coff.targetStore( |
| | 6936 | &coff.dataDirectoryPtr(.IMPORT).virtual_address, |
| | 6937 | coff.computeNodeRva(ni), |
| | 6938 | ); |
| | 6939 | }, |
| 2163 | .import_lookup_table => |import_index| coff.targetStore( | 6940 | .import_lookup_table => |import_index| coff.targetStore( |
| 2164 | &coff.importDirectoryEntryPtr(import_index).import_lookup_table_rva, | 6941 | &coff.importDirectoryEntryPtr(import_index).import_lookup_table_rva, |
| 2165 | coff.computeNodeRva(ni), | 6942 | coff.computeNodeRva(ni), |
| 2166 | ), | 6943 | ), |
| 2167 | .import_address_table => |import_index| { | 6944 | .import_address_table => |import_index| { |
| 2168 | const import_address_table_si = import_index.get(coff).import_address_table_si; | 6945 | const entry = import_index.get(coff); |
| 2169 | import_address_table_si.flushMoved(coff); | 6946 | const import_address_table_si = entry.import_address_table_si; |
| | 6947 | try import_address_table_si.flushMoved(coff); |
| 2170 | coff.targetStore( | 6948 | coff.targetStore( |
| 2171 | &coff.importDirectoryEntryPtr(import_index).import_address_table_rva, | 6949 | &coff.importDirectoryEntryPtr(import_index).import_address_table_rva, |
| 2172 | import_address_table_si.get(coff).rva, | 6950 | import_address_table_si.get(coff).rva, |
| 2173 | ); | 6951 | ); |
| | 6952 | |
| | 6953 | for (entry.import_address_table_symbols.items) |iat_ptr_si| |
| | 6954 | try iat_ptr_si.flushMoved(coff); |
| 2174 | }, | 6955 | }, |
| 2175 | .import_hint_name_table => |import_index| { | 6956 | .import_hint_name_table => |import_index| { |
| 2176 | const target_endian = coff.targetEndian(); | | |
| 2177 | const magic = coff.targetLoad(&coff.optionalHeaderStandardPtr().magic); | 6957 | const magic = coff.targetLoad(&coff.optionalHeaderStandardPtr().magic); |
| 2178 | const import_hint_name_rva = coff.computeNodeRva(ni); | 6958 | const import_hint_name_rva = coff.computeNodeRva(ni); |
| 2179 | coff.targetStore( | 6959 | coff.targetStore( |
| ... | @@ -2186,78 +6966,173 @@ fn flushMoved(coff: *Coff, ni: MappedFile.Node.Index) !void { | ... | @@ -2186,78 +6966,173 @@ fn flushMoved(coff: *Coff, ni: MappedFile.Node.Index) !void { |
| 2186 | import_entry.import_address_table_si.node(coff).slice(&coff.mf); | 6966 | import_entry.import_address_table_si.node(coff).slice(&coff.mf); |
| 2187 | const import_hint_name_slice = ni.slice(&coff.mf); | 6967 | const import_hint_name_slice = ni.slice(&coff.mf); |
| 2188 | const import_hint_name_align = ni.alignment(&coff.mf); | 6968 | const import_hint_name_align = ni.alignment(&coff.mf); |
| | 6969 | |
| 2189 | var import_hint_name_index: u32 = 0; | 6970 | var import_hint_name_index: u32 = 0; |
| 2190 | for (0..import_entry.len) |import_symbol_index| { | 6971 | for (0..import_entry.len) |import_symbol_index| { |
| 2191 | import_hint_name_index = @intCast(import_hint_name_align.forward( | | |
| 2192 | std.mem.indexOfScalarPos( | | |
| 2193 | u8, | | |
| 2194 | import_hint_name_slice, | | |
| 2195 | import_hint_name_index, | | |
| 2196 | 0, | | |
| 2197 | ).? + 1, | | |
| 2198 | )); | | |
| 2199 | switch (magic) { | 6972 | switch (magic) { |
| 2200 | _ => unreachable, | 6973 | _ => unreachable, |
| 2201 | inline .PE32, .@"PE32+" => |ct_magic| { | 6974 | inline .PE32, .@"PE32+" => |ct_magic| { |
| 2202 | const Addr = switch (ct_magic) { | 6975 | const Entry = std.coff.ImportLookupTableEntry(ct_magic); |
| 2203 | _ => comptime unreachable, | 6976 | const import_lookup_table: []Entry = @ptrCast(@alignCast(import_lookup_slice)); |
| 2204 | .PE32 => u32, | 6977 | const import_address_table: []Entry = @ptrCast(@alignCast(import_address_slice)); |
| 2205 | .@"PE32+" => u64, | 6978 | |
| 2206 | }; | 6979 | var entry = coff.targetLoad(&import_lookup_table[import_symbol_index]); |
| 2207 | const import_lookup_table: []Addr = @ptrCast(@alignCast(import_lookup_slice)); | 6980 | if (entry.is_ordinal) |
| 2208 | const import_address_table: []Addr = @ptrCast(@alignCast(import_address_slice)); | 6981 | continue; |
| 2209 | const rva = std.mem.nativeTo( | 6982 | |
| 2210 | Addr, | 6983 | import_hint_name_index = @intCast(import_hint_name_align.forward( |
| 2211 | import_hint_name_rva + import_hint_name_index, | 6984 | std.mem.indexOfScalarPos( |
| 2212 | target_endian, | 6985 | u8, |
| 2213 | ); | 6986 | import_hint_name_slice, |
| 2214 | import_lookup_table[import_symbol_index] = rva; | 6987 | import_hint_name_index, |
| 2215 | import_address_table[import_symbol_index] = rva; | 6988 | 0, |
| | 6989 | ).? + 1, |
| | 6990 | )); |
| | 6991 | |
| | 6992 | entry.payload.hint_name_rva = @intCast(import_hint_name_rva + import_hint_name_index); |
| | 6993 | import_hint_name_index += 2; |
| | 6994 | |
| | 6995 | coff.targetStore(&import_lookup_table[import_symbol_index], entry); |
| | 6996 | coff.targetStore(&import_address_table[import_symbol_index], entry); |
| 2216 | }, | 6997 | }, |
| 2217 | } | 6998 | } |
| 2218 | import_hint_name_index += 2; | 6999 | } |
| | 7000 | }, |
| | 7001 | .export_directory_table => { |
| | 7002 | const rva = coff.computeNodeRva(ni); |
| | 7003 | coff.targetStore(&coff.dataDirectoryPtr(.EXPORT).virtual_address, rva); |
| | 7004 | coff.targetStore(&coff.exportDirectoryTable().name_rva, rva + @sizeOf(std.coff.ExportDirectoryTable)); |
| | 7005 | }, |
| | 7006 | .export_address_table => { |
| | 7007 | try coff.export_table.export_address_table_si.flushMoved(coff); |
| | 7008 | |
| | 7009 | // These relocs are applied directly here instead of via the above flushMoved call as |
| | 7010 | // they are non-contiguous, and not tracked under export_address_table_si. |
| | 7011 | for (coff.export_table.entries.values()) |entry| |
| | 7012 | try entry.export_address_table_ri.get(coff).apply(coff); |
| | 7013 | |
| | 7014 | coff.targetStore( |
| | 7015 | &coff.exportDirectoryTable().export_address_table_rva, |
| | 7016 | coff.computeNodeRva(ni), |
| | 7017 | ); |
| | 7018 | }, |
| | 7019 | .export_name_pointer_table => coff.targetStore( |
| | 7020 | &coff.exportDirectoryTable().name_pointer_table_rva, |
| | 7021 | coff.computeNodeRva(ni), |
| | 7022 | ), |
| | 7023 | .export_ordinal_table => coff.targetStore( |
| | 7024 | &coff.exportDirectoryTable().ordinal_table_rva, |
| | 7025 | coff.computeNodeRva(ni), |
| | 7026 | ), |
| | 7027 | .export_name_table => { |
| | 7028 | const name_table_rva = coff.computeNodeRva(coff.export_table.name_table_ni); |
| | 7029 | for ( |
| | 7030 | coff.exportNamePointerTableSlice(), |
| | 7031 | coff.exportOrdinalTableSlice(), |
| | 7032 | ) |*np, target_ord| { |
| | 7033 | const ord: ExportTable.Ordinal = @enumFromInt(coff.targetLoad(&target_ord.unbiased_ordinal)); |
| | 7034 | const entry = ord.get(coff); |
| | 7035 | coff.targetStore( |
| | 7036 | &np.name_rva, |
| | 7037 | @intCast(name_table_rva + entry.name_index), |
| | 7038 | ); |
| 2219 | } | 7039 | } |
| 2220 | }, | 7040 | }, |
| 2221 | inline .pseudo_section, | 7041 | inline .pseudo_section, |
| 2222 | .object_section, | 7042 | .object_section, |
| 2223 | .global, | 7043 | .import_thunk, |
| 2224 | .nav, | 7044 | .nav, |
| 2225 | .uav, | 7045 | .uav, |
| 2226 | .lazy_code, | 7046 | .lazy_code, |
| 2227 | .lazy_const_data, | 7047 | .lazy_const_data, |
| 2228 | => |mi| mi.symbol(coff).flushMoved(coff), | 7048 | => |mi| try mi.symbol(coff).flushMoved(coff), |
| | 7049 | .builtin => |si| try si.flushMoved(coff), |
| 2229 | } | 7050 | } |
| 2230 | try ni.childrenMoved(coff.base.comp.gpa, &coff.mf); | 7051 | try ni.childrenMoved(coff.base.comp.gpa, &coff.mf); |
| 2231 | } | 7052 | } |
| 2232 | | 7053 | |
| 2233 | fn flushResized(coff: *Coff, ni: MappedFile.Node.Index) !void { | 7054 | fn flushResized(coff: *Coff, ni: MappedFile.Node.Index) !void { |
| 2234 | _, const size = ni.location(&coff.mf).resolve(&coff.mf); | 7055 | const offset, const size = ni.location(&coff.mf).resolve(&coff.mf); |
| | 7056 | log.debug("flushResized({s}, n{d}, 0x{x})", .{ @tagName(coff.getNode(ni)), ni, size }); |
| | 7057 | |
| 2235 | switch (coff.getNode(ni)) { | 7058 | switch (coff.getNode(ni)) { |
| 2236 | .file => {}, | 7059 | .file => { |
| | 7060 | if (coff.isArchive() and coff.members.items.len > 0) { |
| | 7061 | const last_member = coff.members.items[coff.members.items.len - 1]; |
| | 7062 | // See .archive_member branch for reasoning |
| | 7063 | assert(Node.known.file.reverseChildren(&coff.mf).ni == last_member.content_ni); |
| | 7064 | try coff.flushResized(last_member.content_ni); |
| | 7065 | } |
| | 7066 | }, |
| 2237 | .header => { | 7067 | .header => { |
| 2238 | switch (coff.optionalHeaderPtr()) { | 7068 | if (coff.isImage()) { |
| 2239 | inline else => |optional_header| coff.targetStore( | 7069 | switch (coff.optionalHeaderPtr()) { |
| 2240 | &optional_header.size_of_headers, | 7070 | inline else => |optional_header| coff.targetStore( |
| 2241 | @intCast(size), | 7071 | &optional_header.size_of_headers, |
| 2242 | ), | 7072 | @intCast(size), |
| | 7073 | ), |
| | 7074 | } |
| | 7075 | |
| | 7076 | if (size > coff.section_table.values()[0].si.get(coff).rva) try coff.virtualSlide( |
| | 7077 | 0, |
| | 7078 | std.mem.alignForward( |
| | 7079 | u32, |
| | 7080 | @intCast(size * 4), |
| | 7081 | coff.optionalHeaderField(.section_alignment), |
| | 7082 | ), |
| | 7083 | ); |
| 2243 | } | 7084 | } |
| 2244 | if (size > coff.image_section_table.items[0].get(coff).rva) try coff.virtualSlide( | | |
| 2245 | 0, | | |
| 2246 | std.mem.alignForward( | | |
| 2247 | u32, | | |
| 2248 | @intCast(size * 4), | | |
| 2249 | coff.optionalHeaderField(.section_alignment), | | |
| 2250 | ), | | |
| 2251 | ); | | |
| 2252 | }, | 7085 | }, |
| 2253 | .signature, .coff_header, .optional_header, .data_directories => unreachable, | 7086 | .signature, |
| | 7087 | .archive_member_header, |
| | 7088 | => unreachable, |
| | 7089 | .archive_member => |mi| { |
| | 7090 | const content_ni = mi.get(coff).content_ni; |
| | 7091 | const next_ni = content_ni.next(&coff.mf); |
| | 7092 | const content_offset, _ = content_ni.location(&coff.mf).resolve(&coff.mf); |
| | 7093 | const next_offset = switch (next_ni) { |
| | 7094 | .none => offset: { |
| | 7095 | assert(content_ni.parent(&coff.mf) == Node.known.file); |
| | 7096 | // This must take into account the final file size. If there are trailing |
| | 7097 | // bytes, they will be expected to contain another valid member header |
| | 7098 | break :offset coff.mf.memory_map.memory.len; |
| | 7099 | }, |
| | 7100 | else => offset: { |
| | 7101 | assert(coff.getNode(next_ni) == .archive_member_header); |
| | 7102 | break :offset next_ni.location(&coff.mf).resolve(&coff.mf)[0]; |
| | 7103 | }, |
| | 7104 | }; |
| | 7105 | |
| | 7106 | // Not inserting IMAGE_ARCHIVE_PAD `\n` byte here, because we are expanding to full size |
| | 7107 | Member.storeHeaderDecimalStr(&mi.get(coff).headerPtr(coff).size, next_offset - content_offset); |
| | 7108 | }, |
| | 7109 | .coff_header, |
| | 7110 | .optional_header, |
| | 7111 | .data_directories, |
| | 7112 | => unreachable, |
| 2254 | .section_table => {}, | 7113 | .section_table => {}, |
| | 7114 | .symbol_table => { |
| | 7115 | assert(!coff.isImage()); |
| | 7116 | if (!coff.symbol_table.pending_shrink) { |
| | 7117 | const string_table_offset, _ = coff.symbol_table.strings_ni.location(&coff.mf).resolve(&coff.mf); |
| | 7118 | coff.symbol_table.pending_shrink = |
| | 7119 | size > coff.targetLoad(&coff.headerPtr().number_of_symbols) * std.coff.Symbol.sizeOf() or |
| | 7120 | string_table_offset - (offset + size) > 0; |
| | 7121 | } |
| | 7122 | }, |
| | 7123 | .string_table => { |
| | 7124 | assert(!coff.isImage()); |
| | 7125 | coff.targetStore(coff.symbolTableStringLenPtr(), @intCast(size)); |
| | 7126 | }, |
| | 7127 | .relocation_table, |
| | 7128 | .relocation_table_entry, |
| | 7129 | => assert(!coff.isImage()), |
| 2255 | .image_section => |si| { | 7130 | .image_section => |si| { |
| 2256 | const sym = si.get(coff); | 7131 | const sym = si.get(coff); |
| 2257 | const section_index = sym.section_number.toIndex(); | 7132 | const section_index = sym.section_number.toIndex(); |
| 2258 | const section = &coff.sectionTableSlice()[section_index]; | 7133 | const section = &coff.sectionTableSlice()[section_index]; |
| 2259 | coff.targetStore(&section.size_of_raw_data, @intCast(size)); | 7134 | coff.targetStore(&section.size_of_raw_data, @intCast(size)); |
| 2260 | if (size > coff.targetLoad(&section.virtual_size)) { | 7135 | if (coff.isImage() and size > coff.targetLoad(&section.virtual_size)) { |
| 2261 | const virtual_size = std.mem.alignForward( | 7136 | const virtual_size = std.mem.alignForward( |
| 2262 | u32, | 7137 | u32, |
| 2263 | @intCast(size * 4), | 7138 | @intCast(size * 4), |
| ... | @@ -2266,29 +7141,221 @@ fn flushResized(coff: *Coff, ni: MappedFile.Node.Index) !void { | ... | @@ -2266,29 +7141,221 @@ fn flushResized(coff: *Coff, ni: MappedFile.Node.Index) !void { |
| 2266 | coff.targetStore(&section.virtual_size, virtual_size); | 7141 | coff.targetStore(&section.virtual_size, virtual_size); |
| 2267 | try coff.virtualSlide(section_index + 1, sym.rva + virtual_size); | 7142 | try coff.virtualSlide(section_index + 1, sym.rva + virtual_size); |
| 2268 | } | 7143 | } |
| | 7144 | |
| | 7145 | if (!coff.isImage()) { |
| | 7146 | if (coff.symbolTableSectionAuxEntryPtr(si.sti(coff))) |aux_ptr| |
| | 7147 | coff.targetStore(&aux_ptr.length, @intCast(size)); |
| | 7148 | } |
| 2269 | }, | 7149 | }, |
| 2270 | .import_directory_table => coff.targetStore( | 7150 | .input_section => {}, |
| 2271 | &coff.dataDirectoryPtr(.IMPORT).size, | 7151 | .import_directory_table => { |
| 2272 | @intCast(size), | 7152 | const prev_size = coff.targetLoad(&coff.dataDirectoryPtr(.IMPORT).size); |
| 2273 | ), | 7153 | coff.targetStore( |
| 2274 | .import_lookup_table, .import_address_table, .import_hint_name_table => {}, | 7154 | &coff.dataDirectoryPtr(.IMPORT).size, |
| | 7155 | @intCast(size), |
| | 7156 | ); |
| | 7157 | if (prev_size == 0) try coff.flushMoved(ni); |
| | 7158 | }, |
| | 7159 | .import_lookup_table, |
| | 7160 | .import_address_table, |
| | 7161 | .import_hint_name_table, |
| | 7162 | => {}, |
| | 7163 | .export_directory_table => unreachable, |
| | 7164 | .export_address_table, |
| | 7165 | .export_name_pointer_table, |
| | 7166 | .export_ordinal_table, |
| | 7167 | .export_name_table, |
| | 7168 | => {}, |
| 2275 | inline .pseudo_section, | 7169 | inline .pseudo_section, |
| 2276 | .object_section, | 7170 | .object_section, |
| 2277 | => |smi| smi.symbol(coff).get(coff).size = @intCast(size), | 7171 | => |smi, tag| { |
| 2278 | .global, .nav, .uav, .lazy_code, .lazy_const_data => {}, | 7172 | if (tag == .pseudo_section and smi.name(coff) == .@".edata") { |
| | 7173 | coff.targetStore( |
| | 7174 | &coff.dataDirectoryPtr(.EXPORT).size, |
| | 7175 | @intCast(size), |
| | 7176 | ); |
| | 7177 | } |
| | 7178 | |
| | 7179 | var sym = smi.symbol(coff).get(coff); |
| | 7180 | while (sym.flags.extra_tag == .next_alias_si) |
| | 7181 | sym = sym.extra.next_alias_si.get(coff); |
| | 7182 | |
| | 7183 | sym.extra.size = @intCast(size); |
| | 7184 | }, |
| | 7185 | .import_thunk, |
| | 7186 | .nav, |
| | 7187 | .uav, |
| | 7188 | .lazy_code, |
| | 7189 | .lazy_const_data, |
| | 7190 | .builtin, |
| | 7191 | => {}, |
| | 7192 | .placeholder, |
| | 7193 | => unreachable, |
| | 7194 | } |
| | 7195 | } |
| | 7196 | |
| | 7197 | fn flushMember(coff: *Coff, mi: Member.Index) !void { |
| | 7198 | const member = mi.get(coff); |
| | 7199 | switch (member.kind) { |
| | 7200 | .first_linker, |
| | 7201 | .longnames, |
| | 7202 | .import, |
| | 7203 | => unreachable, |
| | 7204 | .second_linker => { |
| | 7205 | const Context = struct { |
| | 7206 | coff: *Coff, |
| | 7207 | indices: []u16, |
| | 7208 | strings: []String, |
| | 7209 | |
| | 7210 | pub fn lessThan(ctx: @This(), lhs: usize, rhs: usize) bool { |
| | 7211 | return std.mem.lessThan( |
| | 7212 | u8, |
| | 7213 | ctx.strings[lhs].toSlice(ctx.coff), |
| | 7214 | ctx.strings[rhs].toSlice(ctx.coff), |
| | 7215 | ); |
| | 7216 | } |
| | 7217 | |
| | 7218 | pub fn swap(ctx: @This(), lhs: usize, rhs: usize) void { |
| | 7219 | std.mem.swap(u16, &ctx.indices[lhs], &ctx.indices[rhs]); |
| | 7220 | std.mem.swap(String, &ctx.strings[lhs], &ctx.strings[rhs]); |
| | 7221 | } |
| | 7222 | }; |
| | 7223 | |
| | 7224 | // TODO: Does this sort need to also sort by linker input order (if names equal)? |
| | 7225 | std.sort.pdqContext(0, coff.lib_string_table.items.len, Context{ |
| | 7226 | .coff = coff, |
| | 7227 | .indices = coff.secondLinkerMemberIndicesSlice(), |
| | 7228 | .strings = coff.lib_string_table.items, |
| | 7229 | }); |
| | 7230 | |
| | 7231 | var offset: usize = 0; |
| | 7232 | var string_table = coff.secondLinkerMemberStringsSlice(); |
| | 7233 | for (coff.lib_string_table.items) |string| { |
| | 7234 | const str = string.toSlice(coff); |
| | 7235 | @memcpy(string_table[offset..][0..str.len], str); |
| | 7236 | string_table[offset + str.len] = 0; |
| | 7237 | offset += str.len + 1; |
| | 7238 | } |
| | 7239 | }, |
| | 7240 | .coff => { |
| | 7241 | const file_offset: u32 = @intCast(member.header_ni.fileLocation(&coff.mf, false).offset); |
| | 7242 | const first_linker_offsets = coff.firstLinkerMemberOffsetsSlice(); |
| | 7243 | for (member.first_linker_indices.values()) |mfli| |
| | 7244 | first_linker_offsets[@intFromEnum(mfli)] = std.mem.nativeTo(u32, file_offset, .big); |
| | 7245 | }, |
| | 7246 | } |
| | 7247 | } |
| | 7248 | |
| | 7249 | fn flushExportsSort(coff: *Coff) void { |
| | 7250 | const Context = struct { |
| | 7251 | coff: *Coff, |
| | 7252 | np: []std.coff.ExportNamePointerTableEntry, |
| | 7253 | ord: []std.coff.ExportOrdinalTableEntry, |
| | 7254 | entries: []ExportTable.Entry, |
| | 7255 | nt: []const u8, |
| | 7256 | |
| | 7257 | pub fn lessThan(ctx: *const @This(), lhs: usize, rhs: usize) bool { |
| | 7258 | const lhs_entry = &ctx.entries[ctx.coff.targetLoad(&ctx.ord[lhs].unbiased_ordinal)]; |
| | 7259 | const rhs_entry = &ctx.entries[ctx.coff.targetLoad(&ctx.ord[rhs].unbiased_ordinal)]; |
| | 7260 | return std.mem.lessThan( |
| | 7261 | u8, |
| | 7262 | ctx.nt[lhs_entry.name_index..][0..lhs_entry.name_len], |
| | 7263 | ctx.nt[rhs_entry.name_index..][0..rhs_entry.name_len], |
| | 7264 | ); |
| | 7265 | } |
| | 7266 | |
| | 7267 | pub fn swap(ctx: @This(), lhs: usize, rhs: usize) void { |
| | 7268 | std.mem.swap(std.coff.ExportNamePointerTableEntry, &ctx.np[lhs], &ctx.np[rhs]); |
| | 7269 | std.mem.swap(std.coff.ExportOrdinalTableEntry, &ctx.ord[lhs], &ctx.ord[rhs]); |
| | 7270 | } |
| | 7271 | }; |
| | 7272 | |
| | 7273 | std.sort.pdqContext(0, coff.export_table.entries.count(), &Context{ |
| | 7274 | .coff = coff, |
| | 7275 | .np = coff.exportNamePointerTableSlice(), |
| | 7276 | .ord = coff.exportOrdinalTableSlice(), |
| | 7277 | .entries = coff.export_table.entries.values(), |
| | 7278 | .nt = coff.export_table.name_table_ni.slice(&coff.mf), |
| | 7279 | }); |
| | 7280 | } |
| | 7281 | |
| | 7282 | fn flushSectionMerges(coff: *Coff) !void { |
| | 7283 | while (coff.section_merge_pending_index < coff.section_merges.count()) : (coff.section_merge_pending_index += 1) |
| | 7284 | try coff.flushSectionMerge(coff.section_merge_pending_index); |
| | 7285 | } |
| | 7286 | |
| | 7287 | fn flushSectionMerge(coff: *Coff, index: u32) !void { |
| | 7288 | assert(coff.isImage()); |
| | 7289 | const from = coff.section_merges.keys()[index]; |
| | 7290 | const to = coff.section_merges.values()[index]; |
| | 7291 | assert(from != to); |
| | 7292 | |
| | 7293 | log.debug("flushSectionMerge({s}->{s})", .{ from.toSlice(coff), to.toSlice(coff) }); |
| | 7294 | |
| | 7295 | const opt_to_sec = coff.section_table.getPtr(to); |
| | 7296 | if (coff.section_table.getPtr(from)) |from_sec| { |
| | 7297 | const from_sym = from_sec.si.get(coff); |
| | 7298 | if (opt_to_sec) |to_sec| { |
| | 7299 | const to_sym = to_sec.si.get(coff); |
| | 7300 | |
| | 7301 | // TODO: Create a pseudo-section named `from` in `to`, copy `from_sec` ni into that pseudo section |
| | 7302 | // TODO: Update .section_number for all contained syms |
| | 7303 | // TODO: Remove `from_sec` from section table (set size = 0 and can do it in flushResized?). |
| | 7304 | // This is non-trivial as we can't leave holes in the section table. |
| | 7305 | // TODO: Merge section flags |
| | 7306 | _ = to_sym; |
| | 7307 | return coff.base.comp.link_diags.fail("TODO implement section to section merge", .{}); |
| | 7308 | } else if (coff.pseudo_section_table.get(to)) |to_ps_si| { |
| | 7309 | const to_sym = to_ps_si.get(coff); |
| | 7310 | if (from_sym.section_number == to_sym.section_number) |
| | 7311 | return; |
| | 7312 | |
| | 7313 | // TODO: Same as above, except place `from` into a node in `to_psmi`'s parent |
| | 7314 | return coff.base.comp.link_diags.fail("TODO implement section to pseudosection merge", .{}); |
| | 7315 | } |
| | 7316 | |
| | 7317 | // If `to` doesn't exist, /MERGE is defined as renaming `from` to `to`. |
| | 7318 | // No other path will create image-level sections, so we can safely rename this now |
| | 7319 | const from_name = &from_sec.si.get(coff).section_number.header(coff).name; |
| | 7320 | const to_slice = to.toSlice(coff); |
| | 7321 | @memcpy(from_name[0..to_slice.len], to_slice); |
| | 7322 | @memset(from_name[to_slice.len..], 0); |
| | 7323 | } else if (coff.pseudo_section_table.getIndex(from)) |from_index| { |
| | 7324 | const from_psmi: Node.PseudoSectionMapIndex = @enumFromInt(from_index); |
| | 7325 | const from_sym = from_psmi.symbol(coff).get(coff); |
| | 7326 | if (opt_to_sec) |to_sec| { |
| | 7327 | const to_sym = to_sec.si.get(coff); |
| | 7328 | if (from_sym.section_number == to_sym.section_number) |
| | 7329 | return; |
| | 7330 | |
| | 7331 | // TODO: Move from_psmi's node into to_sec |
| | 7332 | // TODO: Update .section_number for all contained syms |
| | 7333 | // TODO: Merge section flags |
| | 7334 | return coff.base.comp.link_diags.fail("TODO implement pseudosection to section merge", .{}); |
| | 7335 | } else if (coff.pseudo_section_table.get(to)) |to_ps_si| { |
| | 7336 | const to_sym = to_ps_si.get(coff); |
| | 7337 | if (from_sym.section_number == to_sym.section_number) |
| | 7338 | return; |
| | 7339 | |
| | 7340 | // TODO: Same as above, but move from_psmi's node after to_psmi's node in its parent |
| | 7341 | return coff.base.comp.link_diags.fail("TODO implement pseudosection to pseudosection merge", .{}); |
| | 7342 | } |
| | 7343 | |
| | 7344 | // Renaming pseudo-sections have no effect on the output, so this is a no-op. |
| 2279 | } | 7345 | } |
| 2280 | } | 7346 | } |
| | 7347 | |
| 2281 | fn virtualSlide(coff: *Coff, start_section_index: usize, start_rva: u32) !void { | 7348 | fn virtualSlide(coff: *Coff, start_section_index: usize, start_rva: u32) !void { |
| 2282 | var rva = start_rva; | 7349 | var rva = start_rva; |
| 2283 | for ( | 7350 | for ( |
| 2284 | coff.image_section_table.items[start_section_index..], | 7351 | coff.section_table.values()[start_section_index..], |
| 2285 | coff.sectionTableSlice()[start_section_index..], | 7352 | coff.sectionTableSlice()[start_section_index..], |
| 2286 | ) |section_si, *section| { | 7353 | ) |*section, *header| { |
| 2287 | const section_sym = section_si.get(coff); | 7354 | const section_sym = section.si.get(coff); |
| 2288 | section_sym.rva = rva; | 7355 | section_sym.rva = rva; |
| 2289 | coff.targetStore(&section.virtual_address, rva); | 7356 | coff.targetStore(&header.virtual_address, rva); |
| 2290 | try section_sym.ni.childrenMoved(coff.base.comp.gpa, &coff.mf); | 7357 | try section_sym.ni.childrenMoved(coff.base.comp.gpa, &coff.mf); |
| 2291 | rva += coff.targetLoad(&section.virtual_size); | 7358 | rva += coff.targetLoad(&header.virtual_size); |
| 2292 | } | 7359 | } |
| 2293 | switch (coff.optionalHeaderPtr()) { | 7360 | switch (coff.optionalHeaderPtr()) { |
| 2294 | inline else => |optional_header| coff.targetStore( | 7361 | inline else => |optional_header| coff.targetStore( |
| ... | @@ -2303,19 +7370,27 @@ pub fn updateExports( | ... | @@ -2303,19 +7370,27 @@ pub fn updateExports( |
| 2303 | pt: Zcu.PerThread, | 7370 | pt: Zcu.PerThread, |
| 2304 | exported: Zcu.Exported, | 7371 | exported: Zcu.Exported, |
| 2305 | export_indices: []const Zcu.Export.Index, | 7372 | export_indices: []const Zcu.Export.Index, |
| | 7373 | ) link.Error!void { |
| | 7374 | const diags = &coff.base.comp.link_diags; |
| | 7375 | return coff.updateExportsInner(pt, exported, export_indices) catch |err| switch (err) { |
| | 7376 | error.MappedFileIo => return diags.fail( |
| | 7377 | "failed to write output file: {t}", |
| | 7378 | .{coff.mf.io_err.?}, |
| | 7379 | ), |
| | 7380 | else => |e| return e, |
| | 7381 | }; |
| | 7382 | } |
| | 7383 | fn updateExportsInner( |
| | 7384 | coff: *Coff, |
| | 7385 | pt: Zcu.PerThread, |
| | 7386 | exported: Zcu.Exported, |
| | 7387 | export_indices: []const Zcu.Export.Index, |
| 2306 | ) !void { | 7388 | ) !void { |
| 2307 | const zcu = pt.zcu; | 7389 | const zcu = pt.zcu; |
| 2308 | const gpa = zcu.gpa; | 7390 | const gpa = zcu.gpa; |
| 2309 | const ip = &zcu.intern_pool; | 7391 | const ip = &zcu.intern_pool; |
| 2310 | | 7392 | |
| 2311 | switch (exported) { | 7393 | try coff.symbols.ensureUnusedCapacity(gpa, export_indices.len); |
| 2312 | .nav => |nav| log.debug("updateExports({f})", .{ip.getNav(nav).fqn.fmt(ip)}), | | |
| 2313 | .uav => |uav| log.debug("updateExports(@as({f}, {f}))", .{ | | |
| 2314 | Type.fromInterned(ip.typeOf(uav)).fmt(pt), | | |
| 2315 | Value.fromInterned(uav).fmtValue(pt), | | |
| 2316 | }), | | |
| 2317 | } | | |
| 2318 | try coff.symbol_table.ensureUnusedCapacity(gpa, export_indices.len); | | |
| 2319 | const exported_si: Symbol.Index = switch (exported) { | 7394 | const exported_si: Symbol.Index = switch (exported) { |
| 2320 | .nav => |nav| try coff.navSymbol(zcu, nav), | 7395 | .nav => |nav| try coff.navSymbol(zcu, nav), |
| 2321 | .uav => |uav| @enumFromInt(@intFromEnum(try coff.lowerUav( | 7396 | .uav => |uav| @enumFromInt(@intFromEnum(try coff.lowerUav( |
| ... | @@ -2324,62 +7399,299 @@ pub fn updateExports( | ... | @@ -2324,62 +7399,299 @@ pub fn updateExports( |
| 2324 | Type.fromInterned(ip.typeOf(uav)).abiAlignment(zcu), | 7399 | Type.fromInterned(ip.typeOf(uav)).abiAlignment(zcu), |
| 2325 | ))), | 7400 | ))), |
| 2326 | }; | 7401 | }; |
| | 7402 | switch (exported) { |
| | 7403 | .nav => |nav| log.debug("updateExports({f}) = {d}", .{ ip.getNav(nav).fqn.fmt(ip), exported_si }), |
| | 7404 | .uav => |uav| log.debug("updateExports(@as({f}, {f})) = {d}", .{ |
| | 7405 | Type.fromInterned(ip.typeOf(uav)).fmt(pt), |
| | 7406 | Value.fromInterned(uav).fmtValue(pt), |
| | 7407 | exported_si, |
| | 7408 | }), |
| | 7409 | } |
| | 7410 | while (try coff.resolve(pt.tid)) {} |
| 2327 | while (try coff.idle(pt.tid)) {} | 7411 | while (try coff.idle(pt.tid)) {} |
| | 7412 | |
| | 7413 | const machine = coff.targetLoad(&coff.headerPtr().machine); |
| 2328 | const exported_ni = exported_si.node(coff); | 7414 | const exported_ni = exported_si.node(coff); |
| 2329 | const exported_sym = exported_si.get(coff); | 7415 | const exported_sym = exported_si.get(coff); |
| | 7416 | var prev_alias_si = exported_si; |
| | 7417 | |
| 2330 | for (export_indices) |export_index| { | 7418 | for (export_indices) |export_index| { |
| 2331 | const @"export" = export_index.ptr(zcu); | 7419 | const @"export" = export_index.ptr(zcu); |
| 2332 | const export_si = try coff.globalSymbol(@"export".opts.name.toSlice(ip), null); | 7420 | const name = @"export".opts.name.toSlice(ip); |
| | 7421 | |
| | 7422 | // TODO: add an errMsg if this conflicts with an existing symbol |
| | 7423 | const export_si = try coff.globalSymbol(.{ .name = name }); |
| 2333 | const export_sym = export_si.get(coff); | 7424 | const export_sym = export_si.get(coff); |
| 2334 | export_sym.ni = exported_ni; | 7425 | export_sym.ni = exported_ni; |
| 2335 | export_sym.rva = exported_sym.rva; | 7426 | export_sym.rva = exported_sym.rva; |
| 2336 | export_sym.size = exported_sym.size; | | |
| 2337 | export_sym.section_number = exported_sym.section_number; | 7427 | export_sym.section_number = exported_sym.section_number; |
| 2338 | export_si.applyTargetRelocs(coff); | 7428 | if (@"export".opts.linkage == .weak and !coff.isImage()) { |
| 2339 | if (@"export".opts.name.eqlSlice("wWinMainCRTStartup", ip)) { | 7429 | // exported_si needs to be ahead of export_si in the symbol table, |
| 2340 | coff.optionalHeaderStandardPtr().address_of_entry_point = exported_sym.rva; | 7430 | // so that its sti is known when creating the weak external aux entry |
| 2341 | } else if (@"export".opts.name.eqlSlice("_tls_used", ip)) { | 7431 | try coff.pendingSymbolTableEntry(exported_si); |
| 2342 | const tls_directory = coff.dataDirectoryPtr(.TLS); | 7432 | export_sym.flags.weak_external_strat = .alias; |
| 2343 | tls_directory.* = .{ .virtual_address = exported_sym.rva, .size = exported_sym.size }; | 7433 | export_sym.setValue(.{ .weak_alias_si = exported_si }); |
| 2344 | if (coff.targetEndian() != native_endian) | 7434 | } |
| 2345 | std.mem.byteSwapAllFields(std.coff.ImageDataDirectory, tls_directory); | 7435 | defer export_si.applyTargetRelocs(coff, .none) catch unreachable; |
| | 7436 | |
| | 7437 | // The last symbol in the alias list holds the size |
| | 7438 | const prev_alias_sym = prev_alias_si.get(coff); |
| | 7439 | switch (prev_alias_sym.flags.extra_tag) { |
| | 7440 | .size => export_sym.setExtra(.{ .size = prev_alias_sym.extra.size }), |
| | 7441 | // This export should have been deleted |
| | 7442 | .next_alias_si => assert(prev_alias_sym.extra.next_alias_si == export_si), |
| | 7443 | else => unreachable, |
| | 7444 | } |
| | 7445 | |
| | 7446 | prev_alias_sym.setExtra(.{ .next_alias_si = export_si }); |
| | 7447 | prev_alias_si = export_si; |
| | 7448 | |
| | 7449 | if (!coff.isImage()) continue; |
| | 7450 | |
| | 7451 | const entries_ctx = ExportTable.Adapter{ .coff = coff }; |
| | 7452 | const gop = try coff.export_table.entries.getOrPutAdapted( |
| | 7453 | gpa, |
| | 7454 | name, |
| | 7455 | entries_ctx, |
| | 7456 | ); |
| | 7457 | |
| | 7458 | if (!gop.found_existing) { |
| | 7459 | errdefer _ = coff.export_table.entries.pop(); |
| | 7460 | |
| | 7461 | const export_count = coff.export_table.entries.count(); |
| | 7462 | if (export_count > std.math.maxInt(@FieldType(std.coff.ExportDirectoryTable, "number_of_entries"))) |
| | 7463 | return coff.base.comp.link_diags.fail("exceeded maximum number of exports", .{}); |
| | 7464 | |
| | 7465 | const name_index: u32 = @intCast(coff.export_table.name_table_ni.location(&coff.mf).resolve(&coff.mf)[1]); |
| | 7466 | const new_name_table_size = name_index + name.len + 1; |
| | 7467 | if (new_name_table_size > std.math.maxInt(@FieldType(ExportTable.Entry, "name_index"))) |
| | 7468 | return coff.base.comp.link_diags.fail("exports name table limit reached", .{}); |
| | 7469 | |
| | 7470 | try coff.export_table.name_table_ni.resize(&coff.mf, gpa, new_name_table_size); |
| | 7471 | |
| | 7472 | const name_table_slice = coff.export_table.name_table_ni.slice(&coff.mf); |
| | 7473 | @memcpy(name_table_slice[name_index..][0 .. name.len + 1], name[0 .. name.len + 1]); |
| | 7474 | |
| | 7475 | // If the new name sorts after the current tail of the sorted list, we don't need to re-sort |
| | 7476 | { |
| | 7477 | const ordinal_table_slice = coff.exportOrdinalTableSlice(); |
| | 7478 | if (ordinal_table_slice.len > 0 and !coff.export_table.pending_sort) { |
| | 7479 | const tail_index: ExportTable.Ordinal = |
| | 7480 | @enumFromInt(ordinal_table_slice[ordinal_table_slice.len - 1].unbiased_ordinal); |
| | 7481 | const tail_entry = tail_index.get(coff); |
| | 7482 | const tail_name = name_table_slice[tail_entry.name_index..][0..tail_entry.name_len]; |
| | 7483 | coff.export_table.pending_sort = std.mem.lessThan(u8, name, tail_name); |
| | 7484 | } |
| | 7485 | } |
| | 7486 | |
| | 7487 | const edt = coff.exportDirectoryTable(); |
| | 7488 | coff.targetStore(&edt.number_of_names, @intCast(export_count)); |
| | 7489 | edt.number_of_entries = edt.number_of_names; |
| | 7490 | |
| | 7491 | // TODO: These should all be resized ahead of time to fit all exports |
| | 7492 | // after https://github.com/ziglang/zig/issues/23616 |
| | 7493 | try coff.export_table.export_address_table_si.node(coff).resize( |
| | 7494 | &coff.mf, |
| | 7495 | gpa, |
| | 7496 | export_count * @sizeOf(std.coff.ExportAddressTableEntry), |
| | 7497 | ); |
| | 7498 | |
| | 7499 | try coff.export_table.name_pointer_table_ni.resize( |
| | 7500 | &coff.mf, |
| | 7501 | gpa, |
| | 7502 | export_count * @sizeOf(std.coff.ExportNamePointerTableEntry), |
| | 7503 | ); |
| | 7504 | |
| | 7505 | try coff.export_table.ordinal_table_ni.resize( |
| | 7506 | &coff.mf, |
| | 7507 | gpa, |
| | 7508 | export_count * @sizeOf(std.coff.ExportOrdinalTableEntry), |
| | 7509 | ); |
| | 7510 | |
| | 7511 | coff.targetStore( |
| | 7512 | &coff.exportNamePointerTableSlice()[gop.index].name_rva, |
| | 7513 | @intCast(coff.computeNodeRva(coff.export_table.name_table_ni) + name_index), |
| | 7514 | ); |
| | 7515 | coff.targetStore( |
| | 7516 | &coff.exportOrdinalTableSlice()[gop.index].unbiased_ordinal, |
| | 7517 | @intCast(gop.index), |
| | 7518 | ); |
| | 7519 | |
| | 7520 | gop.value_ptr.* = .{ |
| | 7521 | .si = export_si, |
| | 7522 | .name_index = @intCast(name_index), |
| | 7523 | .name_len = @intCast(name.len), |
| | 7524 | .export_address_table_ri = @enumFromInt(coff.relocs.items.len), |
| | 7525 | }; |
| | 7526 | |
| | 7527 | try coff.addReloc( |
| | 7528 | coff.export_table.export_address_table_si, |
| | 7529 | @intCast(@sizeOf(std.coff.ExportAddressTableEntry) * gop.index), |
| | 7530 | export_si, |
| | 7531 | .{ .known = 0 }, |
| | 7532 | switch (machine) { |
| | 7533 | else => |tag| @panic(@tagName(tag)), |
| | 7534 | .AMD64 => .{ .AMD64 = .ADDR32NB }, |
| | 7535 | .I386 => .{ .I386 = .DIR32NB }, |
| | 7536 | }, |
| | 7537 | ); |
| | 7538 | } else { |
| | 7539 | gop.value_ptr.si = export_si; |
| | 7540 | const reloc = gop.value_ptr.*.export_address_table_ri.get(coff); |
| | 7541 | reloc.target = export_si; |
| 2346 | } | 7542 | } |
| 2347 | } | 7543 | } |
| 2348 | } | 7544 | } |
| 2349 | | 7545 | |
| 2350 | pub fn deleteExport(coff: *Coff, exported: Zcu.Exported, name: InternPool.NullTerminatedString) void { | 7546 | pub fn deleteExport( |
| 2351 | _ = coff; | 7547 | coff: *Coff, |
| 2352 | _ = exported; | 7548 | exported: Zcu.Exported, |
| 2353 | _ = name; | 7549 | name: InternPool.NullTerminatedString, |
| | 7550 | ) void { |
| | 7551 | const zcu = coff.base.comp.zcu.?; |
| | 7552 | const ip = &zcu.intern_pool; |
| | 7553 | |
| | 7554 | const exported_si: Symbol.Index = switch (exported) { |
| | 7555 | .nav => |nav| coff.navs.get(nav).?, |
| | 7556 | .uav => |uav| coff.uavs.get(uav).?, |
| | 7557 | }; |
| | 7558 | |
| | 7559 | const name_slice = name.toSlice(ip); |
| | 7560 | log.debug("deleteExport({s}, {d})", .{ name_slice, exported_si }); |
| | 7561 | |
| | 7562 | // TODO: Delete from first / second linker member table |
| | 7563 | // TODO: Delete from symbol table inside section |
| 2354 | } | 7564 | } |
| 2355 | | 7565 | |
| 2356 | pub fn dump(coff: *Coff, tid: Zcu.PerThread.Id) Io.Cancelable!void { | 7566 | fn dumpStderr(coff: *Coff, tid: Zcu.PerThread.Id) !void { |
| 2357 | const comp = coff.base.comp; | 7567 | const comp = coff.base.comp; |
| 2358 | const io = comp.io; | 7568 | const io = comp.io; |
| 2359 | var buffer: [512]u8 = undefined; | 7569 | var buffer: [512]u8 = undefined; |
| 2360 | const stderr = try io.lockStderr(&buffer, null); | 7570 | const stderr = try io.lockStderr(&buffer, null); |
| 2361 | defer io.unlockStderr(); | 7571 | defer io.unlockStderr(); |
| 2362 | const w = &stderr.file_writer.interface; | 7572 | const w = &stderr.file_writer.interface; |
| 2363 | coff.printNode(tid, w, .root, 0) catch |err| switch (err) { | 7573 | _ = try coff.dump(w, tid); |
| 2364 | error.WriteFailed => return stderr.err.?, | | |
| 2365 | }; | | |
| 2366 | } | 7574 | } |
| 2367 | | 7575 | |
| 2368 | pub fn printNode( | 7576 | pub fn dump(coff: *Coff, w: *Io.Writer, tid: Zcu.PerThread.Id) !link.File.DumpResult { |
| | 7577 | if (coff.options.enable_link_snapshots) { |
| | 7578 | try coff.printNode(tid, w, .root, 0); |
| | 7579 | try w.writeAll("Section table:\n"); |
| | 7580 | for (coff.section_table.keys(), coff.section_table.values()) |name, sec| |
| | 7581 | try coff.printSection(w, name, sec.si); |
| | 7582 | try w.writeAll("Symbol table:\n"); |
| | 7583 | for (1..coff.symbols.items.len) |si| |
| | 7584 | try coff.printSymbol(w, tid, @enumFromInt(si)); |
| | 7585 | |
| | 7586 | return .enabled; |
| | 7587 | } |
| | 7588 | return .disabled; |
| | 7589 | } |
| | 7590 | |
| | 7591 | fn printSection(coff: *Coff, w: *Io.Writer, name: String, si: Symbol.Index) !void { |
| | 7592 | const sym = si.get(coff); |
| | 7593 | try w.print("{d:0>6}@{d:0>2} {x:08} n{d:0>8} | {s}\n", .{ |
| | 7594 | si, |
| | 7595 | sym.section_number, |
| | 7596 | if (sym.flags.extra_tag == .size) sym.extra.size else 0, |
| | 7597 | sym.ni, |
| | 7598 | name.toSlice(coff), |
| | 7599 | }); |
| | 7600 | } |
| | 7601 | |
| | 7602 | fn printSymbol( |
| 2369 | coff: *Coff, | 7603 | coff: *Coff, |
| | 7604 | w: *Io.Writer, |
| 2370 | tid: Zcu.PerThread.Id, | 7605 | tid: Zcu.PerThread.Id, |
| | 7606 | si: Symbol.Index, |
| | 7607 | ) !void { |
| | 7608 | const sym = si.get(coff); |
| | 7609 | const node = coff.getNode(sym.ni); |
| | 7610 | try w.print("{d:0>6}@{d:0>2} {x:08} {s} {s} {s} n{d:0>8}+{x:08}:{t: <26} | {x:08} ", .{ |
| | 7611 | si, |
| | 7612 | sym.section_number, |
| | 7613 | if (sym.flags.extra_tag == .size) |
| | 7614 | @as(u64, sym.extra.size) |
| | 7615 | else if (sym.ni != .none) |
| | 7616 | sym.ni.location(&coff.mf).resolve(&coff.mf)[1] |
| | 7617 | else |
| | 7618 | 0, |
| | 7619 | switch (sym.flags.value_tag) { |
| | 7620 | .none => "xx", |
| | 7621 | .weak_alias_name => "an", |
| | 7622 | .weak_alias_si => "as", |
| | 7623 | .node_offset => "no", |
| | 7624 | }, |
| | 7625 | switch (sym.flags.extra_tag) { |
| | 7626 | .size => "sz", |
| | 7627 | .isli => "li", |
| | 7628 | .next_alias_si => "na", |
| | 7629 | }, |
| | 7630 | switch (sym.flags.type) { |
| | 7631 | .unknown => "u", |
| | 7632 | .code => "c", |
| | 7633 | .data => "d", |
| | 7634 | }, |
| | 7635 | sym.ni, |
| | 7636 | if (sym.flags.value_tag == .node_offset) sym.value.node_offset else 0, |
| | 7637 | node, |
| | 7638 | sym.rva, |
| | 7639 | }); |
| | 7640 | |
| | 7641 | if (sym.gmi != .none) { |
| | 7642 | try w.print("G {f}\n", .{fmtGlobalName(coff, sym.gmi)}); |
| | 7643 | } else { |
| | 7644 | try w.writeAll("| "); |
| | 7645 | try coff.printNodeName(w, tid, node); |
| | 7646 | if (sym.flags.extra_tag == .isli) |
| | 7647 | try w.print(" | {s}", .{sym.extra.isli.name(coff).toSlice(coff)}); |
| | 7648 | try w.writeByte('\n'); |
| | 7649 | } |
| | 7650 | } |
| | 7651 | |
| | 7652 | const FmtGlobalName = struct { coff: *Coff, gmi: Node.GlobalMapIndex }; |
| | 7653 | |
| | 7654 | fn fmtGlobalName(coff: *Coff, gmi: Node.GlobalMapIndex) std.fmt.Alt(FmtGlobalName, globalNameEscape) { |
| | 7655 | return .{ .data = .{ .coff = coff, .gmi = gmi } }; |
| | 7656 | } |
| | 7657 | |
| | 7658 | fn globalNameEscape(data: FmtGlobalName, w: *std.Io.Writer) std.Io.Writer.Error!void { |
| | 7659 | if (data.gmi == .none) return; |
| | 7660 | try w.writeAll(data.gmi.name(data.coff).toSlice(data.coff)); |
| | 7661 | if (data.gmi.libName(data.coff).unwrap()) |lib_name| |
| | 7662 | try w.print("({s})", .{lib_name.toSlice(data.coff)}); |
| | 7663 | } |
| | 7664 | |
| | 7665 | fn printNodeName( |
| | 7666 | coff: *Coff, |
| 2371 | w: *std.Io.Writer, | 7667 | w: *std.Io.Writer, |
| 2372 | ni: MappedFile.Node.Index, | 7668 | tid: Zcu.PerThread.Id, |
| 2373 | indent: usize, | 7669 | node: Node, |
| 2374 | ) !void { | 7670 | ) !void { |
| 2375 | const node = coff.getNode(ni); | | |
| 2376 | try w.splatByteAll(' ', indent); | | |
| 2377 | try w.writeAll(@tagName(node)); | | |
| 2378 | switch (node) { | 7671 | switch (node) { |
| 2379 | else => {}, | 7672 | else => {}, |
| 2380 | .image_section => |si| try w.print("({s})", .{ | 7673 | .image_section => |si| try w.print("({s})", .{ |
| 2381 | std.mem.sliceTo(&si.get(coff).section_number.header(coff).name, 0), | 7674 | std.mem.sliceTo(&si.get(coff).section_number.header(coff).name, 0), |
| 2382 | }), | 7675 | }), |
| | 7676 | .input_section => |isi| { |
| | 7677 | const ioi = isi.input(coff); |
| | 7678 | const is = isi.inputSection(coff); |
| | 7679 | try w.print("({f}{f}, {s}", .{ |
| | 7680 | ioi.path(coff).fmtEscapeString(), |
| | 7681 | fmtMemberNameString(ioi.memberName(coff)), |
| | 7682 | coff.getNode(is.si.node(coff).parent(&coff.mf)).object_section.name(coff).toSlice(coff), |
| | 7683 | }); |
| | 7684 | if (is.comdat_si != .null) { |
| | 7685 | const comdat_sym = is.comdat_si.get(coff); |
| | 7686 | const comdat_name = if (comdat_sym.gmi != .none) |
| | 7687 | comdat_sym.gmi.name(coff).toSlice(coff) |
| | 7688 | else |
| | 7689 | coff.input_symbols.items[@intFromEnum(comdat_sym.extra.isli)].name.toSlice(coff); |
| | 7690 | |
| | 7691 | try w.print("={s}", .{comdat_name}); |
| | 7692 | } |
| | 7693 | try w.writeAll(")"); |
| | 7694 | }, |
| 2383 | .import_lookup_table, | 7695 | .import_lookup_table, |
| 2384 | .import_address_table, | 7696 | .import_address_table, |
| 2385 | .import_hint_name_table, | 7697 | .import_hint_name_table, |
| ... | @@ -2389,18 +7701,18 @@ pub fn printNode( | ... | @@ -2389,18 +7701,18 @@ pub fn printNode( |
| 2389 | inline .pseudo_section, .object_section => |smi| try w.print("({s})", .{ | 7701 | inline .pseudo_section, .object_section => |smi| try w.print("({s})", .{ |
| 2390 | smi.name(coff).toSlice(coff), | 7702 | smi.name(coff).toSlice(coff), |
| 2391 | }), | 7703 | }), |
| 2392 | .global => |gmi| { | 7704 | .import_thunk, |
| 2393 | const gn = gmi.globalName(coff); | 7705 | => |gmi| { |
| 2394 | try w.writeByte('('); | 7706 | try w.writeByte('('); |
| 2395 | if (gn.lib_name.toSlice(coff)) |lib_name| try w.print("{s}.dll, ", .{lib_name}); | 7707 | if (gmi.libName(coff).toSlice(coff)) |lib_name| try w.print("{s}.dll, ", .{lib_name}); |
| 2396 | try w.print("{s})", .{gn.name.toSlice(coff)}); | 7708 | try w.print("{s})", .{gmi.name(coff).toSlice(coff)}); |
| 2397 | }, | 7709 | }, |
| 2398 | .nav => |nmi| { | 7710 | .nav => |nmi| { |
| 2399 | const zcu = coff.base.comp.zcu.?; | 7711 | const zcu = coff.base.comp.zcu.?; |
| 2400 | const ip = &zcu.intern_pool; | 7712 | const ip = &zcu.intern_pool; |
| 2401 | const nav = ip.getNav(nmi.navIndex(coff)); | 7713 | const nav = ip.getNav(nmi.navIndex(coff)); |
| 2402 | try w.print("({f}, {f})", .{ | 7714 | try w.print("({f}, {f})", .{ |
| 2403 | Type.fromInterned(nav.typeOf(ip)).fmt(.{ .zcu = zcu, .tid = tid }), | 7715 | Type.fromInterned(ip.typeOf(nav.resolved.?.value)).fmt(.{ .zcu = zcu, .tid = tid }), |
| 2404 | nav.fqn.fmt(ip), | 7716 | nav.fqn.fmt(ip), |
| 2405 | }); | 7717 | }); |
| 2406 | }, | 7718 | }, |
| ... | @@ -2418,7 +7730,28 @@ pub fn printNode( | ... | @@ -2418,7 +7730,28 @@ pub fn printNode( |
| 2418 | .tid = tid, | 7730 | .tid = tid, |
| 2419 | }), | 7731 | }), |
| 2420 | }), | 7732 | }), |
| | 7733 | .builtin => |si| { |
| | 7734 | const sym = si.get(coff); |
| | 7735 | if (sym.gmi != .none) { |
| | 7736 | try w.writeByte('('); |
| | 7737 | if (sym.gmi.libName(coff).toSlice(coff)) |lib_name| try w.print("{s}.dll, ", .{lib_name}); |
| | 7738 | try w.print("{s})", .{sym.gmi.name(coff).toSlice(coff)}); |
| | 7739 | } |
| | 7740 | }, |
| 2421 | } | 7741 | } |
| | 7742 | } |
| | 7743 | |
| | 7744 | pub fn printNode( |
| | 7745 | coff: *Coff, |
| | 7746 | tid: Zcu.PerThread.Id, |
| | 7747 | w: *Io.Writer, |
| | 7748 | ni: MappedFile.Node.Index, |
| | 7749 | indent: usize, |
| | 7750 | ) !void { |
| | 7751 | const node = coff.getNode(ni); |
| | 7752 | try w.splatByteAll(' ', indent); |
| | 7753 | try w.writeAll(@tagName(node)); |
| | 7754 | try coff.printNodeName(w, tid, node); |
| 2422 | { | 7755 | { |
| 2423 | const mf_node = &coff.mf.nodes.items[@intFromEnum(ni)]; | 7756 | const mf_node = &coff.mf.nodes.items[@intFromEnum(ni)]; |
| 2424 | const off, const size = mf_node.location().resolve(&coff.mf); | 7757 | const off, const size = mf_node.location().resolve(&coff.mf); |
| ... | @@ -2446,7 +7779,7 @@ pub fn printNode( | ... | @@ -2446,7 +7779,7 @@ pub fn printNode( |
| 2446 | const line_len = 0x10; | 7779 | const line_len = 0x10; |
| 2447 | var line_it = std.mem.window( | 7780 | var line_it = std.mem.window( |
| 2448 | u8, | 7781 | u8, |
| 2449 | coff.mf.contents[@intCast(file_loc.offset)..][0..@intCast(file_loc.size)], | 7782 | coff.mf.memory_map.memory[@intCast(file_loc.offset)..][0..@intCast(file_loc.size)], |
| 2450 | line_len, | 7783 | line_len, |
| 2451 | line_len, | 7784 | line_len, |
| 2452 | ); | 7785 | ); |