wasm-micro-runtime icon indicating copy to clipboard operation
wasm-micro-runtime copied to clipboard

[RFC] Run-time dynamic linking support

Open xujuntwt95329 opened this issue 3 years ago • 0 comments

Abstract

Currently WebAssembly doesn't support runtime dynamic linking (dlopen, dlsym, dlclose). #444

typedef int (*TestFunc)(int);

int main()
{
    int ret;
    void *handle;
    TestFunc test_func;

    handle = dlopen("app.wasm", 0);
    test_func = (TestFunc)dlsym(handle, "test_func");
    ret = (*test_func)(1);
}

The code ret = (*test_func)(1) will generate a call_indirect instruction, but the function is actually not in the current module instance, which will cause a runtime exception during execution.

possible approach

Add three native APIs in libc_builtin:

  • dlopen:
    • if module not opened, load and instantiate the module, assign an unique id(uint16) to this module, append this module to a list, and return this id
    • if the module has been opened (already exists in the list), return the associated id
  • dlsym(void handle, const char symbol) /* handle is the id returned from dlopen */:
    • get module_instance through handle, lookup the symbol from this instance, get function index
    • return module_id << 16 + function_index (aka tagged function index)
  • dlclose
    • destroy the corresponding module, remove it from the list and release its id

We also need some modification for call_indirect opcode:

  • call_indirect will check the tag bits (highest 16 bits) in the operand, if the tag bits are 0, then execute the original logic; if not, then call the function in the corresponding module instance.

limitations

  • This mechanism only support functions, globals are not supported (globals are actually some memory spaces in the linear memory, but we can't tag the memory offset because this will reduce the memory addressing range).
  • Only primitive types are supported for function parameters, buffers are not allowed. (The caller and callee come from different module instances, they occupies different memory instances)

xujuntwt95329 avatar Jan 13 '21 03:01 xujuntwt95329