[Tutorial] Run-time plugin feature detection

Started by Kalcor, SA:MP, Aug 08, 2023, 07:46 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Kalcor, SA:MP

[Tutorial] Run-time plugin feature detection

Plugins provide natives to do things.  This is great, but if you write a library sometimes you want to do one thing if the plugin exists and another thing if it doesn't.  Until now the best way was to include (or tryinclude) the plugin's include and use them, but this would cause issues if a user had the include but didn't load the plugin.  Simply calling the native won't work - all the natives are checked for existence prior to the script starting - hence all the famous runtime error 19s, and nativecheckers.  The goal has always been to be able to detect which natives exist at run-time, use them if they do, but not error out if they don't.  I finally figured out a way to do this based on an obscure AMX feature - you can use negative native indexes to not put them in the AMX header:




Code:

#define NATIVE_PrintAmxBacktrace (-5)

native PrintAmxBacktrace() = NATIVE_PrintAmxBacktrace;

main()
{
    if (QueryNative(NATIVE_PrintAmxBacktrace)) PrintAmxBacktrace();
}

There are at least two possible ways to write QueryNative while being backwards-compatible.



V1:




Code:

stock QueryNative(id)
{
    #emit LOAD.S.alt id
    #emit ZERO.pri
    #emit LCTRL 10
    #emit RETN
    return 0;
}

LCTRL 10 would be a new control register, somehow hooked by every plugin, that returns 1 if the specified native index exists.  This would require a lot of AMX_Exec hooking though.



V2:




Code:

#define QueryNative(%0) getproperty(.id = 0x504C5547, .value = (%0)) // !"PLUG"

This is simpler - just a hook of the getproperty native looking for a special domain (id) for plugin natives.



I've not worked out all the details of either yet, since every negative ID will need to be unique among plugins, and they should only respond to their own IDs, or pass along the chain otherwise.  This implies some sort of global registry, at least of ranges - allocated say 100 at once, so -500 – -599 = mysql, -600 – -699 = streamer, etc (-1 – -99 probably reserved for local testing and errors).

Source: [Tutorial] Run-time plugin feature detection