Skip to content

Commit 360d367

Browse files
committed
Check relative branches for byte overflows
1 parent c68eb7d commit 360d367

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

cocoasm/statement.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,10 +326,18 @@ def fix_addresses(self, statements, this_index):
326326
length = 1
327327
for statement in statements[branch_index:this_index+1]:
328328
length += statement.code_pkg.size
329+
330+
# Check for overflow errors if this is a short relative operation
331+
if self.instruction.is_short_branch and length > 128:
332+
raise TranslationError(f"short relative branch cannot be less than -128 bytes", self)
329333
self.code_pkg.additional = NumericValue(base_value - length, size_hint=size_hint)
330334
else:
331335
for statement in statements[this_index+1:branch_index]:
332336
length += statement.code_pkg.size
337+
338+
# Check for overflow errors if this is a short relative operation
339+
if self.instruction.is_short_branch and length > 127:
340+
raise TranslationError(f"short relative branch cannot be more than 127 bytes", self)
333341
self.code_pkg.additional = NumericValue(length, size_hint=size_hint)
334342
return
335343

test/test_program.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,36 @@ def test_translation_error_raised_on_bad_label(self):
361361
program.statements = [statement]
362362
program.translate_statements()
363363

364+
def test_translation_error_raised_on_short_branch_too_large_backward_branch(self):
365+
statements = [
366+
" ORG $0600",
367+
"START LDA #$01",
368+
]
369+
for x in range(400):
370+
statements.append(" LDA #$01")
371+
statements.append(" BRA START")
372+
program = Program()
373+
with self.assertRaises(TranslationError) as context:
374+
program.process(statements)
375+
376+
the_exception = context.exception
377+
self.assertEqual("short relative branch cannot be less than -128 bytes", the_exception.value)
378+
379+
def test_translation_error_raised_on_short_branch_too_large_forward_branch(self):
380+
statements = [
381+
" ORG $0600",
382+
"START BRA THEEND",
383+
]
384+
for x in range(400):
385+
statements.append(" LDA #$01")
386+
statements.append("THEEND LDA #$01")
387+
program = Program()
388+
with self.assertRaises(TranslationError) as context:
389+
program.process(statements)
390+
391+
the_exception = context.exception
392+
self.assertEqual("short relative branch cannot be more than 127 bytes", the_exception.value)
393+
364394
def test_get_binary_array_empty_if_no_statements(self):
365395
program = Program()
366396
self.assertEqual([], program.get_binary_array())

0 commit comments

Comments
 (0)