From 406c85f9ba056e10899feed18dae91e20942dc55 Mon Sep 17 00:00:00 2001 From: Jakub Konka Date: Sat, 22 Jan 2022 08:47:04 +0100 Subject: [PATCH] macho+elf: fix integer overflow in allocateAtom If there is a big atom available for re-use in the free list, and it's the last atom in section, it's ideal capacity might span the entire section in which case we do not want to calculate the actual end VM addr of the symbol since it may overflow. Instead, we just take the max capacity available as end VM addr estimate. In this case, the max capacity equals `std.math.maxInt(u64)`. --- src/link/Elf.zig | 2 +- src/link/MachO.zig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/link/Elf.zig b/src/link/Elf.zig index 63381d24a4..bfd472161a 100644 --- a/src/link/Elf.zig +++ b/src/link/Elf.zig @@ -2118,7 +2118,7 @@ fn allocateTextBlock(self: *Elf, block_list: *TextBlockList, text_block: *TextBl const sym = self.local_symbols.items[big_block.local_sym_index]; const capacity = big_block.capacity(self.*); const ideal_capacity = padToIdeal(capacity); - const ideal_capacity_end_vaddr = sym.st_value + ideal_capacity; + const ideal_capacity_end_vaddr = std.math.add(u64, sym.st_value, ideal_capacity) catch ideal_capacity; const capacity_end_vaddr = sym.st_value + capacity; const new_start_vaddr_unaligned = capacity_end_vaddr - new_block_ideal_capacity; const new_start_vaddr = mem.alignBackwardGeneric(u64, new_start_vaddr_unaligned, alignment); diff --git a/src/link/MachO.zig b/src/link/MachO.zig index 23ba1ee4b5..d7385f1f33 100644 --- a/src/link/MachO.zig +++ b/src/link/MachO.zig @@ -5064,7 +5064,7 @@ fn allocateAtom(self: *MachO, atom: *Atom, new_atom_size: u64, alignment: u64, m const sym = self.locals.items[big_atom.local_sym_index]; const capacity = big_atom.capacity(self.*); const ideal_capacity = if (needs_padding) padToIdeal(capacity) else capacity; - const ideal_capacity_end_vaddr = sym.n_value + ideal_capacity; + const ideal_capacity_end_vaddr = math.add(u64, sym.n_value, ideal_capacity) catch ideal_capacity; const capacity_end_vaddr = sym.n_value + capacity; const new_start_vaddr_unaligned = capacity_end_vaddr - new_atom_ideal_capacity; const new_start_vaddr = mem.alignBackwardGeneric(u64, new_start_vaddr_unaligned, alignment);