| ... | @@ -20,8 +20,11 @@ pub fn cmdObjCopy( | ... | @@ -20,8 +20,11 @@ pub fn cmdObjCopy( |
| 20 | var opt_out_fmt: ?std.Target.ObjectFormat = null; | 20 | var opt_out_fmt: ?std.Target.ObjectFormat = null; |
| 21 | var opt_input: ?[]const u8 = null; | 21 | var opt_input: ?[]const u8 = null; |
| 22 | var opt_output: ?[]const u8 = null; | 22 | var opt_output: ?[]const u8 = null; |
| | 23 | var opt_extract: ?[]const u8 = null; |
| 23 | var only_section: ?[]const u8 = null; | 24 | var only_section: ?[]const u8 = null; |
| 24 | var pad_to: ?u64 = null; | 25 | var pad_to: ?u64 = null; |
| | 26 | var strip_all: bool = false; |
| | 27 | var strip_only_debug: bool = false; |
| 25 | var listen = false; | 28 | var listen = false; |
| 26 | while (i < args.len) : (i += 1) { | 29 | while (i < args.len) : (i += 1) { |
| 27 | const arg = args[i]; | 30 | const arg = args[i]; |
| ... | @@ -67,6 +70,15 @@ pub fn cmdObjCopy( | ... | @@ -67,6 +70,15 @@ pub fn cmdObjCopy( |
| 67 | pad_to = std.fmt.parseInt(u64, args[i], 0) catch |err| { | 70 | pad_to = std.fmt.parseInt(u64, args[i], 0) catch |err| { |
| 68 | fatal("unable to parse: '{s}': {s}", .{ args[i], @errorName(err) }); | 71 | fatal("unable to parse: '{s}': {s}", .{ args[i], @errorName(err) }); |
| 69 | }; | 72 | }; |
| | 73 | } else if (mem.eql(u8, arg, "-g") or mem.eql(u8, arg, "--strip-debug")) { |
| | 74 | strip_only_debug = true; |
| | 75 | } else if (mem.eql(u8, arg, "-S") or mem.eql(u8, arg, "--strip-all")) { |
| | 76 | strip_only_debug = true; |
| | 77 | strip_all = true; |
| | 78 | } else if (mem.eql(u8, arg, "--extract-to")) { |
| | 79 | i += 1; |
| | 80 | if (i >= args.len) fatal("expected another argument after '{s}'", .{arg}); |
| | 81 | opt_extract = args[i]; |
| 70 | } else { | 82 | } else { |
| 71 | fatal("unrecognized argument: '{s}'", .{arg}); | 83 | fatal("unrecognized argument: '{s}'", .{arg}); |
| 72 | } | 84 | } |
| ... | @@ -101,13 +113,39 @@ pub fn cmdObjCopy( | ... | @@ -101,13 +113,39 @@ pub fn cmdObjCopy( |
| 101 | }; | 113 | }; |
| 102 | | 114 | |
| 103 | switch (out_fmt) { | 115 | switch (out_fmt) { |
| 104 | .hex, .raw, .elf => { | 116 | .hex, .raw => { |
| | 117 | if (strip_only_debug or strip_all) |
| | 118 | fatal("zig objcopy: ELF to RAW or HEX copying does not support --strip", .{}); |
| | 119 | if (opt_extract != null) |
| | 120 | fatal("zig objcopy: ELF to RAW or HEX copying does not support --extract-to", .{}); |
| | 121 | |
| 105 | try emitElf(arena, in_file, out_file, elf_hdr, .{ | 122 | try emitElf(arena, in_file, out_file, elf_hdr, .{ |
| 106 | .ofmt = out_fmt, | 123 | .ofmt = out_fmt, |
| 107 | .only_section = only_section, | 124 | .only_section = only_section, |
| 108 | .pad_to = pad_to, | 125 | .pad_to = pad_to, |
| 109 | }); | 126 | }); |
| 110 | }, | 127 | }, |
| | 128 | .elf => { |
| | 129 | if (elf_hdr.endian != @import("builtin").target.cpu.arch.endian()) |
| | 130 | fatal("zig objcopy: ELF to ELF copying only supports native endian", .{}); |
| | 131 | if (!elf_hdr.is_64) |
| | 132 | fatal("zig objcopy: ELF to ELF copying only supports 64-bit files", .{}); |
| | 133 | if (elf_hdr.phoff == 0) // no program header |
| | 134 | fatal("zig objcopy: ELF to ELF copying only supports programs", .{}); |
| | 135 | if (only_section) |_| |
| | 136 | fatal("zig objcopy: ELF to ELF copying does not support --only-section", .{}); |
| | 137 | if (pad_to) |_| |
| | 138 | fatal("zig objcopy: ELF to ELF copying does not support --pad-to", .{}); |
| | 139 | if (!strip_only_debug and !strip_all) |
| | 140 | fatal("zig objcopy: ELF to ELF copying only supports --strip", .{}); |
| | 141 | |
| | 142 | try stripElf(arena, in_file, out_file, elf_hdr, .{ |
| | 143 | .strip_only_debug = strip_only_debug, |
| | 144 | .strip_all = strip_all, |
| | 145 | .extract_to = opt_extract, |
| | 146 | }); |
| | 147 | return std.process.cleanExit(); |
| | 148 | }, |
| 111 | else => fatal("unsupported output object format: {s}", .{@tagName(out_fmt)}), | 149 | else => fatal("unsupported output object format: {s}", .{@tagName(out_fmt)}), |
| 112 | } | 150 | } |
| 113 | | 151 | |
| ... | @@ -158,7 +196,9 @@ const usage = | ... | @@ -158,7 +196,9 @@ const usage = |
| 158 | \\ --only-section=<section> Remove all but <section> | 196 | \\ --only-section=<section> Remove all but <section> |
| 159 | \\ -j <value> Alias for --only-section | 197 | \\ -j <value> Alias for --only-section |
| 160 | \\ --pad-to <addr> Pad the last section up to address <addr> | 198 | \\ --pad-to <addr> Pad the last section up to address <addr> |
| 161 | \\ | 199 | \\ --strip-debug, -g Remove all debug sections from the output.¶ |
| | 200 | \\ --strip-all, -S Remove all debug sections and symbol table from the output. |
| | 201 | \\ --extract-to <file> Extract the removed sections into <file>, and add a .gnu-debuglink section |
| 162 | ; | 202 | ; |
| 163 | | 203 | |
| 164 | pub const EmitRawElfOptions = struct { | 204 | pub const EmitRawElfOptions = struct { |
| ... | @@ -598,3 +638,516 @@ test "containsValidAddressRange" { | ... | @@ -598,3 +638,516 @@ test "containsValidAddressRange" { |
| 598 | segment.fileSize = 1; | 638 | segment.fileSize = 1; |
| 599 | try std.testing.expect(containsValidAddressRange(&buf)); | 639 | try std.testing.expect(containsValidAddressRange(&buf)); |
| 600 | } | 640 | } |
| | 641 | |
| | 642 | // ------------- |
| | 643 | // ELF to ELF stripping |
| | 644 | |
| | 645 | pub const StripElfOptions = struct { |
| | 646 | extract_to: ?[]const u8 = null, |
| | 647 | strip_all: bool = false, |
| | 648 | strip_only_debug: bool = false, |
| | 649 | }; |
| | 650 | |
| | 651 | fn stripElf( |
| | 652 | allocator: Allocator, |
| | 653 | in_file: File, |
| | 654 | out_file: File, |
| | 655 | elf_hdr: elf.Header, |
| | 656 | options: StripElfOptions, |
| | 657 | ) !void { |
| | 658 | std.debug.assert(options.strip_only_debug or options.strip_all); |
| | 659 | |
| | 660 | var elf_contents = try ElfContents.parse(allocator, in_file, elf_hdr); |
| | 661 | defer elf_contents.deinit(); |
| | 662 | |
| | 663 | if (options.extract_to) |filename| { |
| | 664 | const dbg_file = std.fs.cwd().createFile(filename, .{}) catch |err| { |
| | 665 | fatal("zig objcopy: unable to create '{s}': {s}", .{ filename, @errorName(err) }); |
| | 666 | }; |
| | 667 | defer dbg_file.close(); |
| | 668 | try elf_contents.emit(allocator, dbg_file, in_file, if (options.strip_only_debug) .debug else .debug_and_symbols, null); |
| | 669 | } |
| | 670 | |
| | 671 | const debuglink: ?ElfContents.DebugLink = blk: { |
| | 672 | if (options.extract_to) |filename| { |
| | 673 | const dbg_file = std.fs.cwd().openFile(filename, .{}) catch |err| { |
| | 674 | fatal("zig objcopy: could not read `{s}`: {s}\n", .{ filename, @errorName(err) }); |
| | 675 | }; |
| | 676 | defer dbg_file.close(); |
| | 677 | |
| | 678 | break :blk .{ .name = std.fs.path.basename(filename), .crc32 = try computeFileCrc(dbg_file) }; |
| | 679 | } else { |
| | 680 | break :blk null; |
| | 681 | } |
| | 682 | }; |
| | 683 | |
| | 684 | try elf_contents.emit(allocator, out_file, in_file, if (options.strip_only_debug) .program_and_symbols else .program, debuglink); |
| | 685 | } |
| | 686 | |
| | 687 | // note: this is "a minimal effort implementation" |
| | 688 | // It doesn't support all possibile elf files: some sections type may need fixups, the program header may need fix up, ... |
| | 689 | // it was written for a specific use case (strip debug info to a sperate file, for linux 64-bits executables built with `zig` or `zig c++` ) |
| | 690 | // It manupulates and reoders the sections as little as possible to avoid having to do fixups. |
| | 691 | // TODO: support 32-bit files |
| | 692 | // TODO: support non-native endianess |
| | 693 | |
| | 694 | const ElfContents = struct { |
| | 695 | raw_elf_header: elf.Elf64_Ehdr, |
| | 696 | program_segments: []const elf.Elf64_Phdr, |
| | 697 | sections: []const Section, |
| | 698 | arena: std.heap.ArenaAllocator, |
| | 699 | |
| | 700 | const section_memory_align = @alignOf(elf.Elf64_Sym); // most restrictive of what we may load in memory |
| | 701 | const Section = struct { |
| | 702 | section: elf.Elf64_Shdr, |
| | 703 | name: []const u8 = "", |
| | 704 | segment: ?*const elf.Elf64_Phdr = null, // if the section is used by a program segment (there can be more than one) |
| | 705 | payload: ?[]align(section_memory_align) const u8 = null, // if we need the data in memory |
| | 706 | usage: Usage = .none, // should the section be kept in the exe or stripped to the debug database, or both. |
| | 707 | |
| | 708 | const Usage = enum { common, exe, debug, symbols, none }; |
| | 709 | }; |
| | 710 | |
| | 711 | const Self = @This(); |
| | 712 | |
| | 713 | pub fn parse(gpa: Allocator, source: File, header: elf.Header) !Self { |
| | 714 | var arena = std.heap.ArenaAllocator.init(gpa); |
| | 715 | errdefer arena.deinit(); |
| | 716 | const allocator = arena.allocator(); |
| | 717 | |
| | 718 | var raw_header: elf.Elf64_Ehdr = undefined; |
| | 719 | try source.seekableStream().seekTo(0); |
| | 720 | try source.reader().readNoEof(std.mem.asBytes(&raw_header)); |
| | 721 | |
| | 722 | // program header: list of segments |
| | 723 | const program_segments = blk: { |
| | 724 | const program_header = try allocator.alloc(elf.Elf64_Phdr, header.phnum); |
| | 725 | var i: u32 = 0; |
| | 726 | var it = header.program_header_iterator(source); |
| | 727 | while (try it.next()) |hdr| { |
| | 728 | program_header[i] = hdr; |
| | 729 | i += 1; |
| | 730 | } |
| | 731 | break :blk @ptrCast([]const elf.Elf64_Phdr, program_header[0..i]); |
| | 732 | }; |
| | 733 | |
| | 734 | // section header |
| | 735 | const sections = blk: { |
| | 736 | const section_header = try allocator.alloc(Section, header.shnum); |
| | 737 | var it = header.section_header_iterator(source); |
| | 738 | var i: u32 = 0; |
| | 739 | while (try it.next()) |hdr| { |
| | 740 | section_header[i] = .{ .section = hdr }; |
| | 741 | i += 1; |
| | 742 | } |
| | 743 | break :blk section_header[0..i]; |
| | 744 | }; |
| | 745 | |
| | 746 | // load data to memory for some sections: |
| | 747 | // string tables for access |
| | 748 | // sections than need modifications when other sections move. |
| | 749 | for (sections, 0..) |*section, idx| { |
| | 750 | const need_data = switch (section.section.sh_type) { |
| | 751 | elf.DT_VERSYM => true, |
| | 752 | elf.SHT_SYMTAB, elf.SHT_DYNSYM => true, |
| | 753 | else => false, |
| | 754 | }; |
| | 755 | const need_strings = (idx == header.shstrndx); |
| | 756 | |
| | 757 | if (need_data or need_strings) { |
| | 758 | const buffer = try allocator.alignedAlloc(u8, section_memory_align, section.section.sh_size); |
| | 759 | const bytes_read = try source.preadAll(buffer, section.section.sh_offset); |
| | 760 | if (bytes_read != section.section.sh_size) return error.TRUNCATED_ELF; |
| | 761 | section.payload = buffer; |
| | 762 | } |
| | 763 | } |
| | 764 | |
| | 765 | // fill-in sections info: |
| | 766 | // resolve the name |
| | 767 | // find if a program segment uses the section |
| | 768 | // classify sections usage (used by program segments, debug datadase, common metadata, symbol table) |
| | 769 | for (sections) |*section| { |
| | 770 | section.segment = for (program_segments) |*seg| { |
| | 771 | if (sectionWithinSegment(section.section, seg.*)) break seg; |
| | 772 | } else null; |
| | 773 | |
| | 774 | if (section.section.sh_name != 0 and header.shstrndx != elf.SHN_UNDEF) |
| | 775 | section.name = std.mem.span(@ptrCast([*:0]const u8, &sections[header.shstrndx].payload.?[section.section.sh_name])); |
| | 776 | |
| | 777 | const usage_from_program: Section.Usage = if (section.segment != null) .exe else .debug; |
| | 778 | section.usage = switch (section.section.sh_type) { |
| | 779 | elf.SHT_NOTE => .common, |
| | 780 | elf.SHT_SYMTAB => .symbols, // "strip all" vs "strip only debug" |
| | 781 | elf.SHT_DYNSYM => .exe, |
| | 782 | elf.SHT_PROGBITS => usage: { |
| | 783 | if (std.mem.eql(u8, section.name, ".comment")) break :usage .exe; |
| | 784 | if (std.mem.eql(u8, section.name, ".gnu_debuglink")) break :usage .none; |
| | 785 | break :usage usage_from_program; |
| | 786 | }, |
| | 787 | elf.SHT_LOPROC...elf.SHT_HIPROC => .common, // don't strip unkonwn sections |
| | 788 | elf.SHT_LOUSER...elf.SHT_HIUSER => .common, // don't strip unkonwn sections |
| | 789 | else => usage_from_program, |
| | 790 | }; |
| | 791 | } |
| | 792 | |
| | 793 | sections[0].usage = .common; // mandatory null section |
| | 794 | if (header.shstrndx != elf.SHN_UNDEF) |
| | 795 | sections[header.shstrndx].usage = .common; // string table for the headers |
| | 796 | |
| | 797 | // recursive dependencies |
| | 798 | var dirty: u1 = 1; |
| | 799 | while (dirty != 0) { |
| | 800 | dirty = 0; |
| | 801 | |
| | 802 | const Local = struct { |
| | 803 | fn propagateUsage(cur: *Section.Usage, new: Section.Usage) u1 { |
| | 804 | const use: Section.Usage = switch (cur.*) { |
| | 805 | .none => new, |
| | 806 | .common => .common, |
| | 807 | .debug => switch (new) { |
| | 808 | .none, .debug => .debug, |
| | 809 | else => new, |
| | 810 | }, |
| | 811 | .exe => switch (new) { |
| | 812 | .common => .common, |
| | 813 | .none, .debug, .exe => .exe, |
| | 814 | .symbols => .exe, |
| | 815 | }, |
| | 816 | .symbols => switch (new) { |
| | 817 | .none, .common, .debug, .exe => unreachable, |
| | 818 | .symbols => .symbols, |
| | 819 | }, |
| | 820 | }; |
| | 821 | |
| | 822 | if (cur.* != use) { |
| | 823 | cur.* = use; |
| | 824 | return 1; |
| | 825 | } else { |
| | 826 | return 0; |
| | 827 | } |
| | 828 | } |
| | 829 | }; |
| | 830 | |
| | 831 | for (sections) |*section| { |
| | 832 | if (section.section.sh_link != elf.SHN_UNDEF) |
| | 833 | dirty |= Local.propagateUsage(&sections[section.section.sh_link].usage, section.usage); |
| | 834 | if ((section.section.sh_flags & elf.SHF_INFO_LINK) != 0 and section.section.sh_info != elf.SHN_UNDEF) |
| | 835 | dirty |= Local.propagateUsage(&sections[section.section.sh_info].usage, section.usage); |
| | 836 | |
| | 837 | if (section.payload) |data| { |
| | 838 | switch (section.section.sh_type) { |
| | 839 | elf.DT_VERSYM => { |
| | 840 | std.debug.assert(section.section.sh_entsize == @sizeOf(elf.Elf64_Verdef)); |
| | 841 | const defs = @ptrCast([*]const elf.Elf64_Verdef, data)[0 .. section.section.sh_size / @sizeOf(elf.Elf64_Verdef)]; |
| | 842 | for (defs) |def| { |
| | 843 | if (def.vd_ndx != elf.SHN_UNDEF) |
| | 844 | dirty |= Local.propagateUsage(&sections[def.vd_ndx].usage, section.usage); |
| | 845 | } |
| | 846 | }, |
| | 847 | elf.SHT_SYMTAB, elf.SHT_DYNSYM => { |
| | 848 | std.debug.assert(section.section.sh_entsize == @sizeOf(elf.Elf64_Sym)); |
| | 849 | const syms = @ptrCast([*]const elf.Elf64_Sym, data)[0 .. section.section.sh_size / @sizeOf(elf.Elf64_Sym)]; |
| | 850 | |
| | 851 | for (syms) |sym| { |
| | 852 | if (sym.st_shndx != elf.SHN_UNDEF and sym.st_shndx < elf.SHN_LORESERVE) |
| | 853 | dirty |= Local.propagateUsage(&sections[sym.st_shndx].usage, section.usage); |
| | 854 | } |
| | 855 | }, |
| | 856 | else => {}, |
| | 857 | } |
| | 858 | } |
| | 859 | } |
| | 860 | } |
| | 861 | |
| | 862 | return Self{ |
| | 863 | .arena = arena, |
| | 864 | .raw_elf_header = raw_header, |
| | 865 | .program_segments = program_segments, |
| | 866 | .sections = sections, |
| | 867 | }; |
| | 868 | } |
| | 869 | |
| | 870 | pub fn deinit(self: *Self) void { |
| | 871 | self.arena.deinit(); |
| | 872 | } |
| | 873 | |
| | 874 | const DebugLink = struct { name: []const u8, crc32: u32 }; |
| | 875 | const Filter = enum { program, debug, program_and_symbols, debug_and_symbols }; |
| | 876 | fn emit(self: *const Self, gpa: Allocator, output: File, source: File, filter: Filter, debuglink: ?DebugLink) !void { |
| | 877 | var arena = std.heap.ArenaAllocator.init(gpa); |
| | 878 | defer arena.deinit(); |
| | 879 | const allocator = arena.allocator(); |
| | 880 | |
| | 881 | // when emitting the stripped exe: |
| | 882 | // - unused sections are removed |
| | 883 | // when emitting the debug file: |
| | 884 | // - all sections are kept, but some are emptied and their types is changed to SHT_NOBITS |
| | 885 | // the program header is kept unchanged. (`strip` does update it, but `eu-strip` does not, and it still works) TODO: maybe it can be omitted altogether from debug? |
| | 886 | |
| | 887 | const Update = struct { |
| | 888 | action: enum { keep, strip, empty }, |
| | 889 | |
| | 890 | // remap the indexs after omitting the filtered sections |
| | 891 | remap_idx: u16, |
| | 892 | |
| | 893 | // optionally overrides the payload from the source file |
| | 894 | payload: ?[]align(section_memory_align) const u8, |
| | 895 | }; |
| | 896 | const sections_update = try allocator.alloc(Update, self.sections.len); |
| | 897 | const new_shnum = blk: { |
| | 898 | var next_idx: u16 = 0; |
| | 899 | for (self.sections, sections_update) |section, *update| { |
| | 900 | update.action = action: { |
| | 901 | if (section.usage == .none) break :action .strip; |
| | 902 | break :action switch (filter) { |
| | 903 | .program => switch (section.usage) { |
| | 904 | .common, .exe => .keep, |
| | 905 | else => .strip, |
| | 906 | }, |
| | 907 | .program_and_symbols => switch (section.usage) { |
| | 908 | .common, .exe, .symbols => .keep, |
| | 909 | else => .strip, |
| | 910 | }, |
| | 911 | .debug => switch (section.usage) { |
| | 912 | .exe, .symbols => .empty, |
| | 913 | else => .keep, |
| | 914 | }, |
| | 915 | .debug_and_symbols => switch (section.usage) { |
| | 916 | .exe => .empty, |
| | 917 | else => .keep, |
| | 918 | }, |
| | 919 | }; |
| | 920 | }; |
| | 921 | |
| | 922 | if (update.action == .strip) { |
| | 923 | update.remap_idx = elf.SHN_UNDEF; |
| | 924 | } else { |
| | 925 | update.remap_idx = next_idx; |
| | 926 | next_idx += 1; |
| | 927 | } |
| | 928 | |
| | 929 | update.payload = null; |
| | 930 | } |
| | 931 | |
| | 932 | if (debuglink != null) |
| | 933 | next_idx += 1; |
| | 934 | break :blk next_idx; |
| | 935 | }; |
| | 936 | |
| | 937 | const debuglink_name: elf.Elf64_Word = blk: { |
| | 938 | if (debuglink == null) break :blk elf.SHN_UNDEF; |
| | 939 | if (self.raw_elf_header.e_shstrndx == elf.SHN_UNDEF) |
| | 940 | fatal("zig objcopy: no strtab, cannot add the debuglink section", .{}); // TODO add the section if needed? |
| | 941 | |
| | 942 | const strtab = &self.sections[self.raw_elf_header.e_shstrndx]; |
| | 943 | const update = &sections_update[self.raw_elf_header.e_shstrndx]; |
| | 944 | |
| | 945 | const name: []const u8 = ".gnu_debuglink"; |
| | 946 | const new_offset = @intCast(u32, strtab.payload.?.len); |
| | 947 | const buf = try allocator.alignedAlloc(u8, section_memory_align, new_offset + name.len + 1); |
| | 948 | std.mem.copy(u8, buf[0..new_offset], strtab.payload.?); |
| | 949 | std.mem.copy(u8, buf[new_offset .. new_offset + name.len], name); |
| | 950 | buf[new_offset + name.len] = 0; |
| | 951 | |
| | 952 | std.debug.assert(update.action == .keep); |
| | 953 | update.payload = buf; |
| | 954 | |
| | 955 | break :blk new_offset; |
| | 956 | }; |
| | 957 | |
| | 958 | const WriteCmd = union(enum) { |
| | 959 | copy_range: struct { in_offset: u64, len: u64, out_offset: u64 }, |
| | 960 | write_data: struct { data: []const u8, out_offset: u64 }, |
| | 961 | }; |
| | 962 | var cmdbuf = std.ArrayList(WriteCmd).init(allocator); |
| | 963 | defer cmdbuf.deinit(); |
| | 964 | try cmdbuf.ensureUnusedCapacity(3 + new_shnum); |
| | 965 | var eof_offset: u64 = 0; // track the end of the data written so far. |
| | 966 | |
| | 967 | // build the updated headers |
| | 968 | // nb: updated_elf_header will be updated before the actual write |
| | 969 | var updated_elf_header = self.raw_elf_header; |
| | 970 | if (updated_elf_header.e_shstrndx != elf.SHN_UNDEF) |
| | 971 | updated_elf_header.e_shstrndx = sections_update[updated_elf_header.e_shstrndx].remap_idx; |
| | 972 | cmdbuf.appendAssumeCapacity(.{ .write_data = .{ .data = std.mem.asBytes(&updated_elf_header), .out_offset = 0 } }); |
| | 973 | eof_offset = @sizeOf(elf.Elf64_Ehdr); |
| | 974 | |
| | 975 | // program header as-is. |
| | 976 | { |
| | 977 | std.debug.assert(updated_elf_header.e_phoff == @sizeOf(elf.Elf64_Ehdr)); |
| | 978 | const data = std.mem.sliceAsBytes(self.program_segments); |
| | 979 | std.debug.assert(data.len == @as(usize, updated_elf_header.e_phentsize) * updated_elf_header.e_phnum); |
| | 980 | cmdbuf.appendAssumeCapacity(.{ .write_data = .{ .data = data, .out_offset = updated_elf_header.e_phoff } }); |
| | 981 | eof_offset = updated_elf_header.e_phoff + data.len; |
| | 982 | } |
| | 983 | |
| | 984 | // update sections and queue payload writes |
| | 985 | const updated_section_header = blk: { |
| | 986 | const dest_sections = try allocator.alloc(elf.Elf64_Shdr, new_shnum); |
| | 987 | |
| | 988 | { |
| | 989 | // the ELF format doesn't specify the order for all sections. |
| | 990 | // this code only supports when they are in increasing file order. |
| | 991 | var offset: u64 = eof_offset; |
| | 992 | for (self.sections[1..]) |section| { |
| | 993 | if (section.section.sh_offset < offset) { |
| | 994 | fatal("zig objcopy: unsuported ELF file", .{}); |
| | 995 | } |
| | 996 | offset = section.section.sh_offset; |
| | 997 | } |
| | 998 | } |
| | 999 | |
| | 1000 | dest_sections[0] = self.sections[0].section; |
| | 1001 | |
| | 1002 | var dest_section_idx: u32 = 1; |
| | 1003 | for (self.sections[1..], sections_update[1..]) |section, update| { |
| | 1004 | if (update.action == .strip) continue; |
| | 1005 | std.debug.assert(update.remap_idx == dest_section_idx); |
| | 1006 | |
| | 1007 | const src = &section.section; |
| | 1008 | const dest = &dest_sections[dest_section_idx]; |
| | 1009 | dest_section_idx += 1; |
| | 1010 | |
| | 1011 | dest.* = src.*; |
| | 1012 | |
| | 1013 | if (src.sh_link != elf.SHN_UNDEF) |
| | 1014 | dest.sh_link = sections_update[src.sh_link].remap_idx; |
| | 1015 | if ((src.sh_flags & elf.SHF_INFO_LINK) != 0 and src.sh_info != elf.SHN_UNDEF) |
| | 1016 | dest.sh_info = sections_update[src.sh_info].remap_idx; |
| | 1017 | |
| | 1018 | const payload = if (update.payload) |data| data else section.payload; |
| | 1019 | if (payload) |data| |
| | 1020 | dest.sh_size = data.len; |
| | 1021 | |
| | 1022 | const addralign = if (src.sh_addralign == 0 or dest.sh_type == elf.SHT_NOBITS) 1 else src.sh_addralign; |
| | 1023 | dest.sh_offset = std.mem.alignForward(eof_offset, addralign); |
| | 1024 | if (src.sh_offset != dest.sh_offset and section.segment != null and update.action != .empty and dest.sh_type != elf.SHT_NOTE) { |
| | 1025 | if (src.sh_offset > dest.sh_offset) { |
| | 1026 | dest.sh_offset = src.sh_offset; // add padding to avoid modifing the program segments |
| | 1027 | } else { |
| | 1028 | fatal("zig objcopy: cannot adjust program segments", .{}); |
| | 1029 | } |
| | 1030 | } |
| | 1031 | std.debug.assert(dest.sh_addr % addralign == dest.sh_offset % addralign); |
| | 1032 | |
| | 1033 | if (update.action == .empty) |
| | 1034 | dest.sh_type = elf.SHT_NOBITS; |
| | 1035 | |
| | 1036 | if (dest.sh_type != elf.SHT_NOBITS) { |
| | 1037 | if (payload) |src_data| { |
| | 1038 | // update sections payload and write |
| | 1039 | const data = try allocator.alignedAlloc(u8, section_memory_align, src_data.len); |
| | 1040 | std.mem.copy(u8, data, src_data); |
| | 1041 | |
| | 1042 | switch (src.sh_type) { |
| | 1043 | elf.DT_VERSYM => { |
| | 1044 | const defs = @ptrCast([*]elf.Elf64_Verdef, data)[0 .. src.sh_size / @sizeOf(elf.Elf64_Verdef)]; |
| | 1045 | for (defs) |*def| { |
| | 1046 | if (def.vd_ndx != elf.SHN_UNDEF) |
| | 1047 | def.vd_ndx = sections_update[src.sh_info].remap_idx; |
| | 1048 | } |
| | 1049 | }, |
| | 1050 | elf.SHT_SYMTAB, elf.SHT_DYNSYM => { |
| | 1051 | const syms = @ptrCast([*]elf.Elf64_Sym, data)[0 .. src.sh_size / @sizeOf(elf.Elf64_Sym)]; |
| | 1052 | for (syms) |*sym| { |
| | 1053 | if (sym.st_shndx != elf.SHN_UNDEF and sym.st_shndx < elf.SHN_LORESERVE) |
| | 1054 | sym.st_shndx = sections_update[sym.st_shndx].remap_idx; |
| | 1055 | } |
| | 1056 | }, |
| | 1057 | else => {}, |
| | 1058 | } |
| | 1059 | |
| | 1060 | std.debug.assert(data.len == dest.sh_size); |
| | 1061 | cmdbuf.appendAssumeCapacity(.{ .write_data = .{ .data = data, .out_offset = dest.sh_offset } }); |
| | 1062 | eof_offset = dest.sh_offset + dest.sh_size; |
| | 1063 | } else { |
| | 1064 | // direct contents copy |
| | 1065 | cmdbuf.appendAssumeCapacity(.{ .copy_range = .{ .in_offset = src.sh_offset, .len = dest.sh_size, .out_offset = dest.sh_offset } }); |
| | 1066 | eof_offset = dest.sh_offset + dest.sh_size; |
| | 1067 | } |
| | 1068 | } else { |
| | 1069 | // account for alignment padding even in empty sections to keep logical section order |
| | 1070 | eof_offset = dest.sh_offset; |
| | 1071 | } |
| | 1072 | } |
| | 1073 | |
| | 1074 | // add a ".gnu_debuglink" section |
| | 1075 | if (debuglink) |link| { |
| | 1076 | const payload = payload: { |
| | 1077 | const crc_offset = std.mem.alignForward(link.name.len + 1, 4); |
| | 1078 | const buf = try allocator.alignedAlloc(u8, 4, crc_offset + 4); |
| | 1079 | std.mem.copy(u8, buf[0..link.name.len], link.name); |
| | 1080 | std.mem.set(u8, buf[link.name.len..crc_offset], 0); |
| | 1081 | std.mem.copy(u8, buf[crc_offset..], std.mem.asBytes(&link.crc32)); |
| | 1082 | break :payload buf; |
| | 1083 | }; |
| | 1084 | |
| | 1085 | dest_sections[dest_section_idx] = elf.Elf64_Shdr{ |
| | 1086 | .sh_name = debuglink_name, |
| | 1087 | .sh_type = elf.SHT_PROGBITS, |
| | 1088 | .sh_flags = 0, |
| | 1089 | .sh_addr = 0, |
| | 1090 | .sh_offset = eof_offset, |
| | 1091 | .sh_size = payload.len, |
| | 1092 | .sh_link = elf.SHN_UNDEF, |
| | 1093 | .sh_info = elf.SHN_UNDEF, |
| | 1094 | .sh_addralign = 4, |
| | 1095 | .sh_entsize = 0, |
| | 1096 | }; |
| | 1097 | dest_section_idx += 1; |
| | 1098 | |
| | 1099 | cmdbuf.appendAssumeCapacity(.{ .write_data = .{ .data = payload, .out_offset = eof_offset } }); |
| | 1100 | eof_offset += payload.len; |
| | 1101 | } |
| | 1102 | |
| | 1103 | std.debug.assert(dest_section_idx == new_shnum); |
| | 1104 | break :blk dest_sections; |
| | 1105 | }; |
| | 1106 | |
| | 1107 | // write the section header at the tail |
| | 1108 | { |
| | 1109 | const offset = std.mem.alignForward(eof_offset, @alignOf(elf.Elf64_Shdr)); |
| | 1110 | |
| | 1111 | const data = std.mem.sliceAsBytes(updated_section_header); |
| | 1112 | std.debug.assert(data.len == @as(usize, updated_elf_header.e_shentsize) * new_shnum); |
| | 1113 | updated_elf_header.e_shoff = offset; |
| | 1114 | updated_elf_header.e_shnum = new_shnum; |
| | 1115 | |
| | 1116 | cmdbuf.appendAssumeCapacity(.{ .write_data = .{ .data = data, .out_offset = updated_elf_header.e_shoff } }); |
| | 1117 | } |
| | 1118 | |
| | 1119 | // write the target files |
| | 1120 | // TODO: pack together contiguous copies (cmdbuf if ordered by construction) |
| | 1121 | // TODO: fill the paddings with zero or copy from source file |
| | 1122 | for (cmdbuf.items) |cmd| { |
| | 1123 | switch (cmd) { |
| | 1124 | .write_data => |data| { |
| | 1125 | var iovec = [_]std.os.iovec_const{.{ .iov_base = data.data.ptr, .iov_len = data.data.len }}; |
| | 1126 | try output.pwritevAll(&iovec, data.out_offset); |
| | 1127 | }, |
| | 1128 | .copy_range => |range| { |
| | 1129 | const copied_bytes = try source.copyRangeAll(range.in_offset, output, range.out_offset, range.len); |
| | 1130 | if (copied_bytes < range.len) return error.TRUNCATED_ELF; |
| | 1131 | }, |
| | 1132 | } |
| | 1133 | } |
| | 1134 | } |
| | 1135 | |
| | 1136 | fn sectionWithinSegment(section: elf.Elf64_Shdr, segment: elf.Elf64_Phdr) bool { |
| | 1137 | const file_size = if (section.sh_type == elf.SHT_NOBITS) 0 else section.sh_size; |
| | 1138 | return segment.p_offset <= section.sh_offset and (segment.p_offset + segment.p_filesz) >= (section.sh_offset + file_size); |
| | 1139 | } |
| | 1140 | }; |
| | 1141 | |
| | 1142 | fn computeFileCrc(file: File) !u32 { |
| | 1143 | var buf: [8000]u8 = undefined; |
| | 1144 | |
| | 1145 | try file.seekTo(0); |
| | 1146 | var hasher = std.hash.Crc32.init(); |
| | 1147 | while (true) { |
| | 1148 | const bytes_read = try file.read(&buf); |
| | 1149 | if (bytes_read == 0) break; |
| | 1150 | hasher.update(buf[0..bytes_read]); |
| | 1151 | } |
| | 1152 | return hasher.final(); |
| | 1153 | } |