Skip to content

Commit

Permalink
Fix macro generation
Browse files Browse the repository at this point in the history
1) We need to add ULL modifier to all values to fix some issues with `set_field` and `get_field` OpenOCD macros (for example, when `mask` = 1 << 31, it leads to UB becuase of signed overflow)
  • Loading branch information
kr-sc committed Oct 23, 2023
1 parent 393715e commit 44b8d86
Showing 1 changed file with 7 additions and 16 deletions.
23 changes: 7 additions & 16 deletions registers.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,26 +386,17 @@ def prototype(self):
def body(self):
return self.expression

def sympy_to_c(expression, sym_to_c = lambda s: "(" + str(s) + ")"):
def sympy_to_c(expression, sym_to_c = lambda s: f"({s})", unsigned=True):
"""Implement our own string function, so we can replace 2** with 1<<."""
stc = lambda x : sympy_to_c(x, sym_to_c)
stc = lambda x : sympy_to_c(x, sym_to_c, unsigned)
if isinstance(expression, str):
return expression
if isinstance(expression, sympy.Number):
if (expression >= 2**32):
return "0x%xULL" % expression
elif (expression >= 2**31):
return "0x%xU" % expression
elif (expression >= 10):
return "0x%x" % expression
elif (expression > -10):
return "%d" % expression
elif (expression > -2**31):
return "-0x%x" % -expression
elif (expression > -2**32):
return "-0x%xU" % -expression
suffix = "ULL" if unsigned else ""
if (expression < 10 and expression > -10):
return "%d%s" % (expression, suffix)
else:
return "-0x%xULL" % -expression
return "%#0x%s" % (expression, suffix)
elif isinstance(expression, sympy.Symbol):
return sym_to_c(expression)
elif isinstance(expression, sympy.Add):
Expand Down Expand Up @@ -502,7 +493,7 @@ def print_cgetters( registers_list, fd_h, fd_c):
fd_h.write(Register.c_field_list_type())
fd_h.write(Register.c_info_type())

to_c = lambda string: sympy_to_c(sympy.simplify(string), lambda s: f"context.{s}.value")
to_c = lambda string: sympy_to_c(sympy.simplify(string), lambda s: f"context.{s}.value", False)
is_valid = lambda s: f"context.{s}.is_set"

for r in all_regs:
Expand Down

0 comments on commit 44b8d86

Please sign in to comment.