Odin
Odin copied to clipboard
Can't control allocator used in procs tagged with `@(init)` and globals
There is no way to make a proc tagged with @(init) use a custom allocator. For example, there are packages in core that use @(init) to allocate some memory.
Below is an example:
package allocator_issue
import "base:runtime"
my_arr: [dynamic]int
// Imagine this happens in some package that is out of my control.
@(init)
run_before_main :: proc() {
append(&my_arr, 5)
}
main :: proc() {
// There's no good way to make this apply to `run_before_main`
context.allocator = runtime.panic_allocator()
assert(my_arr[0] == 5)
}
Similarly, if you have a global written like so:
arr := make([dynamic]int)
then there is no way to make it use a custom context.allocator, since main hasn't been run yet.
Another example is global dynamic literals:
global_map := map[int]float {
5 = 3.2,
7 = 1.2,
}
It will initialized with the platform's default allocator. There is no good way to override which one it uses.
Suggested solutions
There have been multiple ways suggested to implement this, such as:
- Add a compiler command line flag that specifies a procedure to run before
@(init), i.e. you name a "pre-init" proc name. - Make it possible to provide a custom entry point procedure, so that you can do special things in there. I.e. look at
maininbase/runtime/entry_windows.odinetc, and figure out to inject a custom entry procedure. However, that would maybe be platform-dependent.