Fixed jump address calculation

This commit is contained in:
Eduard Urbach 2024-07-26 19:33:51 +02:00
parent bf80551a15
commit d001e4e55f
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
3 changed files with 53 additions and 24 deletions

View File

@ -57,23 +57,25 @@ func (a Assembler) Finalize() ([]byte, []byte) {
code = x64.Call(code, 0x00_00_00_00)
size := 4
label := x.Data.(*Label)
nextInstructionAddress := Address(len(code))
pointers = append(pointers, &Pointer{
pointer := &Pointer{
Position: Address(len(code) - size),
OpSize: 1,
Size: uint8(size),
Resolve: func() Address {
destination, exists := labels[label.Name]
}
if !exists {
panic("unknown call label")
}
pointer.Resolve = func() Address {
destination, exists := labels[label.Name]
distance := destination - nextInstructionAddress
return Address(distance)
},
})
if !exists {
panic("unknown jump label")
}
distance := destination - (pointer.Position + Address(pointer.Size))
return Address(distance)
}
pointers = append(pointers, pointer)
case COMMENT:
continue
@ -106,23 +108,25 @@ func (a Assembler) Finalize() ([]byte, []byte) {
size := 1
label := x.Data.(*Label)
nextInstructionAddress := Address(len(code))
pointers = append(pointers, &Pointer{
pointer := &Pointer{
Position: Address(len(code) - size),
OpSize: 1,
Size: uint8(size),
Resolve: func() Address {
destination, exists := labels[label.Name]
}
if !exists {
panic("unknown jump label")
}
pointer.Resolve = func() Address {
destination, exists := labels[label.Name]
distance := destination - nextInstructionAddress
return Address(distance)
},
})
if !exists {
panic("unknown jump label")
}
distance := destination - (pointer.Position + Address(pointer.Size))
return Address(distance)
}
pointers = append(pointers, pointer)
case LABEL:
labels[x.Data.(*Label).Name] = Address(len(code))
@ -269,8 +273,16 @@ restart:
following.Position += offset
}
code = append(left, jump...)
code = append(code, right...)
for key, address := range labels {
if address > pointer.Position {
labels[key] += offset
}
}
code = make([]byte, len(left)+len(jump)+len(right))
copy(code, left)
copy(code[len(left):], jump)
copy(code[len(left)+len(jump):], right)
goto restart
}

View File

@ -0,0 +1,16 @@
main() {
f(1, 2, 3, 4, 5, 6)
}
f(a, b, c, d, e, f) {
return g(f, e, d, c, b, a)
}
g(a, b, c, d, e, f) {
assert a == 6
assert b == 5
assert c == 4
assert d == 3
assert e == 2
assert f == 1
}

View File

@ -25,6 +25,7 @@ var programs = []struct {
{"nested-calls", "", "", 4},
{"param", "", "", 3},
{"param-multi", "", "", 21},
{"param-order", "", "", 0},
{"reuse", "", "", 3},
{"return", "", "", 6},
{"reassign", "", "", 2},