Skip to content

Commit 9caa15e

Browse files
committed
Fix severe bug when branching with a negative offset
This bug is essentially due to a buffer overflow, in fact we were shifting a byte to the left by 8 bits.
1 parent f458537 commit 9caa15e

File tree

2 files changed

+6
-6
lines changed

2 files changed

+6
-6
lines changed

gork/zmachine.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -121,25 +121,25 @@ func (zm *ZMachine) Branch(conditionOk bool) {
121121
branchOnTrue := (info >> 7) != 0x00
122122

123123
// offset is relative to current PC and it can be negative
124-
var offset int16
124+
var offset int32
125125

126126
// if bit #6 is set than the offset is stored in the bottom
127127
// 6 bits
128128
if info&0x40 != 0x00 {
129-
offset = int16(info & 0x3F)
129+
offset = int32(info & 0x3F)
130130
} else {
131131
// if bit #6 is clear than the offset is store in a 14 bit signed
132132
// integer composed by the bottom 5 bits of info and 8 bits of an
133133
// additional byte
134-
firstPart := info & 0x3F
134+
firstPart := uint16(info & 0x3F)
135135

136136
// if sign bit(#6) is set then it's a negative number
137137
// in two complement form, so set the bits #6 and #7 too
138138
if firstPart&0x20 != 0x00 {
139139
firstPart |= 0x3 << 6
140140
}
141141

142-
offset = int16(firstPart<<8) | int16(zm.seq.ReadByte())
142+
offset = int32(int16(firstPart<<8) | int16(zm.seq.ReadByte()))
143143
}
144144

145145
// jump if conditionOk and branchOnTrue are both true or false
@@ -158,7 +158,7 @@ func (zm *ZMachine) Branch(conditionOk bool) {
158158
}
159159
}
160160

161-
func (zm *ZMachine) CalcJumpAddress(offset int16) uint32 {
161+
func (zm *ZMachine) CalcJumpAddress(offset int32) uint32 {
162162
// Address after branch data + Offset - 2
163163
return uint32(int64(zm.seq.pos) + int64(offset) - 2)
164164
}

gork/zoptable.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ func ZJump(zm *ZMachine, offset uint16) {
153153
// this is not a branch instruction
154154
// jumping to an instruction in a different routine is permitted,
155155
// but the standard consider it bad practice :)
156-
zm.seq.pos = zm.CalcJumpAddress(int16(offset))
156+
zm.seq.pos = zm.CalcJumpAddress(int32(int16(offset)))
157157
}
158158

159159
func ZPrint(zm *ZMachine) {

0 commit comments

Comments
 (0)