From ba78f87bba031e322209899f1427b0c22c7b7031 Mon Sep 17 00:00:00 2001
From: Moritz Angermann <moritz.angermann@gmail.com>
Date: Tue, 22 Jun 2021 15:39:44 +0800
Subject: [PATCH] [aarch64-macho] Fix off-by-one error in the linker

We need to be careful about the sign bit for BR26 relocation
otherwise we end up encoding a large positive number and reading
back a large negative number.

(cherry picked from commit d6ab9c60288369ec991826b158d751dd4cb3319e)
---
 rts/linker/MachO.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/rts/linker/MachO.c b/rts/linker/MachO.c
index 0b7b7957f757..1505b2833526 100644
--- a/rts/linker/MachO.c
+++ b/rts/linker/MachO.c
@@ -552,7 +552,17 @@ relocateSectionAarch64(ObjectCode * oc, Section * section)
                 } else {
                     value = (uint64_t)symbol->addr;    // address of the symbol.
                 }
-                if((value - pc + addend) >> (2 + 26)) {
+                // We've got:
+                // + 2  bits, for alignment
+                // + 26 bits for for the relocation value
+                // - 1  bit for signage.
+                //
+                // Thus we can encode 26 bits for relocation, including the sign
+                // bit. However as branches need to be 4-byte aligned, we only
+                // need 26 bits to address a 28 bit range. Thus discarding the
+                // sign bit, we can encode a range of +/- 27bits.
+                //
+                if((value - pc + addend) >> (2 + 26 - 1)) {
                     /* we need a stub */
                     /* check if we already have that stub */
                     if(findStub(section, (void**)&value, 0)) {
-- 
GitLab