authorgravatar for kubkon@jakubkonka.comJakub Konka <kubkon@jakubkonka.com> 2022-11-06 00:36:27+01:00
committergravatar for kubkon@jakubkonka.comJakub Konka <kubkon@jakubkonka.com> 2022-11-06 00:36:27+01:00
log76fb3e062161e84554e0665444135281f7bcaf74
tree95ba509db81c7e25678dad4debde931de93b91b1
parentaaaa7df15264edd38d755eb77253d54073e9f192

macho: do not zero-out file if there are no nonzerofill sects

If the `__DATA` segment comprises of only zerofill sections, do not accidentally zero out all of file.

1 files changed, 7 insertions(+), 10 deletions(-)

src/link/MachO/zld.zig+7-10
...@@ -4305,24 +4305,21 @@ pub fn linkWithZld(macho_file: *MachO, comp: *Compilation, prog_node: *std.Progr...@@ -4305,24 +4305,21 @@ pub fn linkWithZld(macho_file: *MachO, comp: *Compilation, prog_node: *std.Progr
4305 // segment and the beginning of __LINKEDIT segment is zerofilled as the loader will4305 // segment and the beginning of __LINKEDIT segment is zerofilled as the loader will
4306 // copy-paste this space into memory for quicker zerofill operation.4306 // copy-paste this space into memory for quicker zerofill operation.
4307 if (zld.getSegmentByName("__DATA")) |data_seg_id| blk: {4307 if (zld.getSegmentByName("__DATA")) |data_seg_id| blk: {
4308 var physical_zerofill_start: u64 = 0;4308 var physical_zerofill_start: ?u64 = null;
4309 const section_indexes = zld.getSectionIndexes(data_seg_id);4309 const section_indexes = zld.getSectionIndexes(data_seg_id);
4310 for (zld.sections.items(.header)[section_indexes.start..section_indexes.end]) |header| {4310 for (zld.sections.items(.header)[section_indexes.start..section_indexes.end]) |header| {
4311 if (header.isZerofill() and header.size > 0) break;4311 if (header.isZerofill() and header.size > 0) break;
4312 physical_zerofill_start = header.offset + header.size;4312 physical_zerofill_start = header.offset + header.size;
4313 } else break :blk;4313 } else break :blk;
4314 const start = physical_zerofill_start orelse break :blk;
4314 const linkedit = zld.getLinkeditSegmentPtr();4315 const linkedit = zld.getLinkeditSegmentPtr();
4315 const physical_zerofill_size = math.cast(usize, linkedit.fileoff - physical_zerofill_start) orelse4316 const size = math.cast(usize, linkedit.fileoff - start) orelse return error.Overflow;
4316 return error.Overflow;4317 if (size > 0) {
4317 if (physical_zerofill_size > 0) {4318 log.debug("zeroing out zerofill area of length {x} at {x}", .{ size, start });
4318 log.debug("zeroing out zerofill area of length {x} at {x}", .{4319 var padding = try zld.gpa.alloc(u8, size);
4319 physical_zerofill_size,
4320 physical_zerofill_start,
4321 });
4322 var padding = try zld.gpa.alloc(u8, physical_zerofill_size);
4323 defer zld.gpa.free(padding);4320 defer zld.gpa.free(padding);
4324 mem.set(u8, padding, 0);4321 mem.set(u8, padding, 0);
4325 try zld.file.pwriteAll(padding, physical_zerofill_start);4322 try zld.file.pwriteAll(padding, start);
4326 }4323 }
4327 }4324 }
43284325