#Is there a way to have several functions at ascending addresses?

1 messages · Page 1 of 1 (latest)

dire osprey
#

I have about 40 functions and I want to know if a given pointer is one of those function. Ideally I'd check if the address in question was >= the address of the first of the functions and <= the last. But when I have the functions defined in sequence the addresses are not in that order... Obviously there are other, slower ways to check (hash table/set, or binary search on a sorted array), but the ordered comparison is the best way.

I had defined them in a top-level const struct, but I could define them at the top level in a file if that would produce a reliable ordering. Are they maybe on alphabetical order? It's probably irrelevant, but all 40 functions have the same type signature.

Thanks, in advance!

cinder matrix
#

I imagine that'd be dependent on the linker script you use

#

Only thing that really comes to mind is to export them and specify their linksection, which you'd then use in your linker script to ensure they are linked as ordered

#

You could also just switch on them

#

Ie

inline fn isFunc(ptr: *const anyopaque) bool {
    return switch (ptr) {
        &func1,
        &func2,
        // ...
        &funcn,
        => true,
        else => false,
    };
}
#

Won't necessarily be faster than the range check

#

But probably will compile down to the range check anyways if their addresses happen to be packed together

#

Will point out though, even with the range check, it doesn't necessarily tell you if it's a valid function pointer - it could be a pointer to executable code just slightly offset from one of the function pointers

#

Though I guess you could just mask the value against function alignment and ensure it would be

dire osprey
#

Thanks @cinder matrix What if I defined them in a struct would they all be together in some arbitrary order? Because then, at runtime, I could find the lowest address and the highest address, then use those. This really does need to be fast, because it has to happen on every major garbage collection and there are 10s of thousands of them to test. All the addresses will be one of these functions or other unrelated functions, so I don't need to worry about in-between addresses.

cinder matrix
#

I just tried that out, doesn't seem to work as you'dve hoped

#

and just in case you mean as declarations: where functions are defined in a namespace needn't have any meaningful impact on the end result

#

zig has no ABI, and thus doesn't guarantee anything regarding that

#

if you really need to go that route, using a specific linker script alongside specifying the linksection of the functions is probably your best bet

dire osprey
#

can you provide a reference to linker scripts and linksection? The documentation says: "TODO add documentation for linksection"

cinder matrix
#

Then in the linker script you'd have to define that section, and put the function there