1.9 KiB
Use Rhai in Dynamic Libraries
{{#include ../links.md}}
Sometimes functions registered into a Rhai [Engine
] come from dynamic libraries (a.k.a. shared
libraries in Linux or DLL's in Windows), which are compiled separately from the main binary, not
statically linked but loaded dynamically at runtime.
The project [`rhai-dylib`] demonstrates an API for creating dynamically-loadable libraries
for use with a Rhai [`Engine`].
Problem Symptom
The symptom is usually Function Not Found errors even though the relevant functions (within the
dynamic library) have already been registered into the [Engine
].
This usually happens when a mutable reference to the [Engine
] is passed into an entry-point
function exposed by the dynamic library and the [Engine
]'s function registration API is called
inside the dynamic library.
Problem Cause
To counter [DOS] attacks, the hasher used by Rhai, [ahash
], automatically generates a different
seed for hashing during each compilation and execution run.
This means that hash values generated by the hasher will not be stable – they change during each compile, and during each run.
This creates hash mismatches between the main binary and the loaded dynamic library because, as they are not linked together at compile time, two independent copies of the hasher reside in them, resulting in different hashes for even the same function signature.
Solution
Use [static hashing] for force predictable hashes.
Static hashing allows dynamic libraries with Rhai code to be loaded and used with
an [`Engine`] in the main binary.
However, a fixed seed enlarges the attack surface of Rhai to malicious intent
(e.g. [DOS] attacks).
This safety trade-off should be carefully considered.