github.com/wasilibs/wazerox@v0.0.0-20240124024944-4923be63ab5f/internal/engine/wazevo/backend/isa/arm64/machine_relocation.go (about)

     1  package arm64
     2  
     3  import (
     4  	"github.com/wasilibs/wazerox/internal/engine/wazevo/backend"
     5  	"github.com/wasilibs/wazerox/internal/engine/wazevo/ssa"
     6  )
     7  
     8  // ResolveRelocations implements backend.Machine ResolveRelocations.
     9  //
    10  // TODO: unit test!
    11  func (m *machine) ResolveRelocations(refToBinaryOffset map[ssa.FuncRef]int, binary []byte, relocations []backend.RelocationInfo) {
    12  	for _, r := range relocations {
    13  		instrOffset := r.Offset
    14  		calleeFnOffset := refToBinaryOffset[r.FuncRef]
    15  		brInstr := binary[instrOffset : instrOffset+4]
    16  		diff := int64(calleeFnOffset) - (instrOffset)
    17  		// https://developer.arm.com/documentation/ddi0596/2020-12/Base-Instructions/BL--Branch-with-Link-
    18  		imm26 := diff / 4
    19  		brInstr[0] = byte(imm26)
    20  		brInstr[1] = byte(imm26 >> 8)
    21  		brInstr[2] = byte(imm26 >> 16)
    22  		if diff < 0 {
    23  			brInstr[3] = (byte(imm26 >> 24 & 0b000000_01)) | 0b100101_10 // Set sign bit.
    24  		} else {
    25  			brInstr[3] = (byte(imm26 >> 24 & 0b000000_01)) | 0b100101_00 // No sign bit.
    26  		}
    27  	}
    28  }