summaryrefslogtreecommitdiff
path: root/python
diff options
context:
space:
mode:
authorRusty Wagner <rusty.wagner@gmail.com>2025-10-20 20:11:20 -0400
committerRusty Wagner <rusty.wagner@gmail.com>2025-10-21 13:52:40 -0400
commit314d2cac1c12d0e20266fc7671689c376b13a26f (patch)
tree56b95e92af601db6b19ca30c12b82ebbf52fee3b /python
parentf080d1cd1c11ddf2476fa9d9f113dd45ee2a5e45 (diff)
Add an example for using constant renderers to render unusual floating point constant encodings directly in the decompilation
Diffstat (limited to 'python')
-rw-r--r--python/examples/bid64_constant.py42
1 files changed, 42 insertions, 0 deletions
diff --git a/python/examples/bid64_constant.py b/python/examples/bid64_constant.py
new file mode 100644
index 00000000..d5f49ccd
--- /dev/null
+++ b/python/examples/bid64_constant.py
@@ -0,0 +1,42 @@
+# This plugin renders 64-bit binary integer decimal floating point constants directly in the
+# decompilation. See the sample binary at `examples/bid64_constant/sample_binary` for an
+# example of a binary that uses this unusual format.
+
+from binaryninja import (ConstantRenderer, InstructionTextToken, InstructionTextTokenType, IntegerType)
+from decimal import Decimal
+
+
+class Bid64ConstantRenderer(ConstantRenderer):
+ renderer_name = "bid64_constant"
+
+ def render_constant(self, instr, type, val, tokens, settings, precedence):
+ # Typedefs have the final type, so make sure it is a 64 bit integer. The registered name
+ # should be the typedef "BID_UINT64".
+ if not isinstance(type, IntegerType):
+ return False
+ if type.width != 8:
+ return False
+ if type.registered_name is None or type.registered_name.name != 'BID_UINT64':
+ return False
+
+ sign = (val & (1 << 63)) != 0
+ raw_exponent = (val >> 53) & 0x3ff
+ if raw_exponent >= 0x300:
+ # Don't try and render NaN or infinity
+ return False
+
+ bias = 398
+ exponent = raw_exponent - bias
+ magnitude = val & ((1 << 53) - 1)
+
+ if magnitude == 0:
+ exponent = 0
+
+ value = Decimal(magnitude) * Decimal(10.0) ** Decimal(exponent)
+ if sign:
+ value = -value
+ tokens.append(InstructionTextToken(InstructionTextTokenType.FloatingPointToken, str(value) + "_bid"))
+ return True
+
+
+Bid64ConstantRenderer().register()