Skip to content

wasm2c: lock func indexes as they are shared across wasm instances - #2117

Closed
shravanrn wants to merge 1 commit into
WebAssembly:mainfrom
PLSysSec:globals-mutex
Closed

shravanrn wants to merge 1 commit into
WebAssembly:mainfrom
PLSysSec:globals-mutex

Conversation

@shravanrn

Copy link
Copy Markdown
Collaborator

For the Firefox use case, we will be creating multiple wasm instances dynamically on concurrent threads. Currently, the creation of the instances is racy when querying/updating the function type indexes, as this is data shared across wasm instances. This PR fixes this by locking any query/update of the function indexes.

This PR follows a discussion at #2046

@sbc100 sbc100 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm % comments

Comment thread wasm2c/wasm-rt-impl.c Resolved
Comment thread wasm2c/wasm-rt-impl.c Resolved
Comment thread wasm2c/wasm-rt-impl.c Resolved
Comment thread wasm2c/wasm-rt-impl.c Resolved
Comment thread wasm2c/wasm-rt-impl.c Resolved
Comment thread wasm2c/wasm-rt-impl.c Resolved
Comment thread wasm2c/wasm-rt-impl.c Resolved
@keithw

keithw commented Jan 4, 2023 •

Copy link
Copy Markdown
Member

Thanks for looping me in. I guess my view hasn't really changed from the last discussion; briefly:

  • I see the runtime implementation included in the WABT repo as basically just an example. It's far from production-grade in many respects. For the limited purposes it's used for, I don't think this is a big problem1, and I think it's better to err towards keeping it simple if possible. There's no single answer to what it means to "transform wasm to C," so it seems like it's better for wasm2c to plan for flexibility in the embedder's runtime implementation (and let us debate what the API should be), rather than try to maintain a runtime that meets the needs of a mega-app like Chrome or Firefox. It's going to be hard enough to do that in the actual wasm2c transpiler, which to me is the real shared ground here.

  • If Firefox needs module initialization (and trap catching and exception handling) to be thread-safe, it totally makes sense that they would need more sophistication in their runtime. If the proposal is that we should make WABT's own runtime implementation fully re-entrant and bear that burden upstream, that seems like the big decision to make, rather than this individual PR. Because it seems to lead down a path where we're adding locks, thread_locals, and the multi-platform equivalents in various places, and then perhaps also trying to test/fuzz the new thread-safety properties we're adding.

  • I'm not super into that because I think WABT is a small project that's currently somewhat underwater in terms of complexity, fuzz failures, etc., and I'm wary of biting off more unless we think the change is of global benefit. But if we do decide to do that, as before my suggestion would be to start a second runtime implementation, rather than adding this complexity piecemeal to the "example" runtime and pushing the maintenance burden on everybody. And ideally some Mozilla people will show up to contribute to its maintenance and provide healthy discussion about what the API boundary should be. (Although if I were Firefox... wouldn't I want to use C++ to represent some of these runtime data structures?)

  • For the particular use-case in the PR (RLBox in a Firefox-like app), it seems like there may be a nicer approach anyway, for two reasons:

    • The output of wasm_rt_register_func_type only has to be unique within the context of "a module and the modules it transitively imports funcrefs and funcref tables from." For RLBox, I assume this is just "the module," which means the "func_types" structure only needs to be per-module, and it's only used at module initialization time. So for the RLBox use case, it might be enough to make this structure thread-local.
    • Or, if you know all the modules upfront, wasm_rt_register_func_type could be implemented as a pure function with no side effects, e.g. consult a precomputed/immutable mapping from functypes to unique integers and return the correct value. This might be cleaner than mutating anything at module initialization time.

Footnotes

  1. Lots of ISO C and POSIX functions can't be implemented re-entrantly at all afaik, e.g. localtime, getpwnam, seed48, etc. Not saying this is great, but at least the wasm2c runtime functions can be implemented reentrantly if you need to! ↩

@sbc100

sbc100 commented Jan 4, 2023

Copy link
Copy Markdown
Member

Thanks for looping me in. I guess my view hasn't really changed from the last discussion; briefly:

  • I see the runtime implementation included in the WABT repo as basically just an example. It's far from production-grade in many respects. For the limited purposes it's used for, I don't think this is a big problem1, and I think it's better to err towards keeping it simple if possible. There's no single answer to what it means to "transform wasm to C," so it seems like it's better for wasm2c to plan for flexibility in the embedder's runtime implementation (and let us debate what the API should be), rather than try to maintain a runtime that meets the needs of a mega-app like Chrome or Firefox. It's going to be hard enough to do that in the actual wasm2c transpiler, which to me is the real shared ground here.
  • If Firefox needs module initialization (and trap catching and exception handling) to be thread-safe, it totally makes sense that they would need more sophistication in their runtime. If the proposal is that we should make WABT's own runtime implementation fully re-entrant and bear that burden upstream, that seems like the big decision to make, rather than this individual PR. Because it seems to lead down a path where we're adding locks, thread_locals, and the multi-platform equivalents in various places, and then perhaps also trying to test/fuzz the new thread-safety properties we're adding.
  • I'm not super into that because I think WABT is a small project that's currently somewhat underwater in terms of complexity, fuzz failures, etc., and I'm wary of biting off more unless we think the change is of global benefit. But if we do decide to do that, as before my suggestion would be to start a second runtime implementation, rather than adding this complexity piecemeal to the "example" runtime and pushing the maintenance burden on everybody. And ideally some Mozilla people will show up to contribute to its maintenance and provide healthy discussion about what the API boundary should be. (Although if I were Firefox... wouldn't I want to use C++ to represent some of these runtime data structures?)

Attempting to answer these points together. I agree that the wasm-rt implementation that ships with wasm2c can most likely never achieve the goal of being all things to all people but think we can and should strive to make it is as complete and robust as possible, within reason. I don't think I agree (at least not at this point in time) with idea that it should be considered just "example code", but even that were true, its not a reason to avoid all complexity. I think we should see it more as a "reference implementation", and strive for production quality where we can.

Obviously, there is a line we will be walking in terms of how much complexity we want to deal with, and how much we want to resist complexity that seems implementation specific.

Perhaps this upstreaming will be futile because there will be some core wasm-rt feature from rlbox that we really don't want upstream and they will ultimately be stuck on a fork anyway. But the smaller the fork needs to be the better our reference implementation is IMHO.

I think multi-threading is going to widely used/useful and implementing the wasm threads proposal is something we will want to do. I can imagine perhaps also implementing the new wasi-threads proposal so that we can run the tests coming or of that project.

I suppose I can imagine forking the runtime, as you suggest, into runtime-simple, and runtime-complex, but that has some major downsides in terms of our testing matrix. I don't think this kind of PR pushes us over the limit where we would want to take on that burden.

  • For the particular use-case in the PR (RLBox in a Firefox-like app), it seems like there may be a nicer approach anyway, for two reasons:

    • The output of wasm_rt_register_func_type only has to be unique within the context of "a module and the modules it transitively imports funcrefs and funcref tables from." For RLBox, I assume this is just "the module," which means the "func_types" structure only needs to be per-module, and it's only used at module initialization time. So for the RLBox use case, it might be enough to make this structure thread-local.
    • Or, if you know all the modules upfront, wasm_rt_register_func_type could be implemented as a pure function with no side effects, e.g. consult a precomputed/immutable mapping from functypes to unique integers and return the correct value. This might be cleaner than mutating anything at module initialization time.

Footnotes

  1. Lots of ISO C and POSIX functions can't be implemented re-entrantly at all afaik, e.g. localtime, getpwnam, seed48, etc. Not saying this is great, but at least the wasm2c runtime functions can be implemented reentrantly if you need to! leftwards_arrow_with_hook

@keithw

keithw commented Jan 4, 2023 •

Copy link
Copy Markdown
Member

If the consensus is to stick with one runtime, and we want that runtime to become fully re-entrant, I think it may be possible to solve some of the root problems a little more definitively vs. adding locks incrementally.

Let me try to summarize my understanding: The purpose of g_func_types is to maintain a mapping from each unique functype to a unique identifier. The identifier is compared at runtime in CALL_INDIRECT to check equality of types. The mapping from functypes to identifiers needs to be consistent across any scope of "a module and its transitive imports," which is why g_func_types is a global right now. But that makes it inconvenient to add new functype->identifier mappings in parallel.

I think we could move to a world where:

  • we eliminate the wasm_rt_register_func_type runtime API endpoint, and the g_func_types data structure, completely
  • instead, wasm2c generates a deterministic identifier for the function type at "transpile-time" instead of module-initialization time

What if wasm2c serializes the param and result types to an opaque string in the module's .c file, and the func_types identifier becomes a pointer to this string? We can do nice things like always zero-pad to the nearest 2/4/8/16 bytes (which makes a memcmp quite fast, especially given that only one side of a CALL_INDIRECT needs to deref the pointer -- the other side is always a known string). This might let us get out of the whole business entirely.

Godbolt example: https://godbolt.org/z/GvTYTrfE7

@sbc100

sbc100 commented Jan 4, 2023

Copy link
Copy Markdown
Member

If the consensus is to stick with one runtime, and we want that runtime become fully re-entrant, I think it may be possible to solve some of the root problems a little more definitively vs. adding locks incrementally.

Let me try to summarize my understanding: The purpose of g_func_types is to maintain a mapping from each unique functype to a unique identifier. The identifier is compared at runtime in CALL_INDIRECT to check equality of types. The mapping from functypes to identifiers needs to be consistent across any scope of "a module and its transitive imports," which is why g_func_types is a global right now. But that makes it inconvenient to add new functype->identifier mappings in parallel.

I think we could move to a world where:

  • we eliminate the wasm_rt_register_func_type runtime API endpoint, and the g_func_types data structure, completely
  • instead, wasm2c generate a deterministic identifier for the function type at "transpile-time" instead of module-initialization time

What if wasm2c serializes the param and result types to an opaque string in the module's .c file, and the func_types identifier becomes a pointer to this string? We can do nice things like always zero-pad to the nearest 2/4/8/16 bytes (which makes a memcmp quite fast, especially given that only one side of a CALL_INDIRECT needs to deref the pointer -- the other side is always a known string). This might let us get out of the whole business entirely.

I like the idea of avoiding the whole registration system. With this proposal make type checking during call_indirect into a memcpy? I guess that downside there is that the cost of checking the sig would be O(number of arg)?

Given that each thread has it own instance of each module, do you think that making the mapping thread-local might be simpler for now? Its not possible to call_indirect from one thread to another so it should be fine for each thread to have its own mapping.

Godbolt example: https://godbolt.org/z/GvTYTrfE7

@keithw

keithw commented Jan 4, 2023 •

Copy link
Copy Markdown
Member

I like the idea of avoiding the whole registration system. With this proposal make type checking during call_indirect into a memcpy?

Well, a memcmp, but I think in the common case it would actually be faster than today. Right now the type checking during call_indirect has to fetch two i32s from memory (both of which are opaque identifiers that came from wasm_rt_register_func_type at module-initialization time) and then execute a cmp instruction to compare them.

In this proposal, for a function with fewer than ~12 params and results, I think wasm2c would be able to cram everything into 4 bytes. So now the type checking would involve executing a cmp instruction between an immediate i32 (because now the serialized type is known at compile-time) and a single i32 fetched from memory.

I guess that downside there is that the cost of checking the sig would be O(number of arg)?

Yes in the asymptote, but in practice it will compile to a single cmp QWORD instruction up to ~24 params and results, and I suspect (hope) the overhead of the memcmp is dwarfed by the overhead of the actual indirect function call for any reasonable number of args.

Beyond 64 bits, maybe we should just put the param and result types into SHA-256. That would make the comparison asymptotically O(1). :-)

Given that each thread has it own instance of each module, do you think that making the mapping thread-local might be simpler for now? Its not possible to call_indirect from one thread to another so it should be fine for each thread to have its own mapping.

Hmm, I'm not totally sure I follow here. Having g_func_types be lockless and thread_local seems like it would work fine for RLBox because I don't think RLBox cares about modules that import tables/funcrefs from other modules anyway.

But in general, what if the embedder has a module ModA that imports a table from module ModB, and the embedder chooses to run Z_ModA_init_module() on one thread while running Z_ModB_init_module() on a second thread in parallel? If we want our runtime to be re-entrant, I think that would mean supporting this. The problem arises before any module instances are instantiated.

@sbc100

sbc100 commented Jan 4, 2023

Copy link
Copy Markdown
Member

But in general, what if the embedder has a module ModA that imports a table from module ModB, and the embedder chooses to run Z_ModA_init_module() on one thread while running Z_ModB_init_module() on a second thread in parallel? If we want our runtime to be re-entrant, I think that would mean supporting this.

Ah I see yes, even though instances can't be shared between threads (in the current instance-per-thread model), this type table/data is module-specific rather than instance-specific? so i can/should be shareable.

@shravanrn

shravanrn commented Jan 5, 2023 •

Copy link
Copy Markdown
Collaborator Author

@sbc100 Sorry for the delay in responding. I just read through the thread. Please correct me if I am wrong, but the conclusions here are

  • TLS won't work for func indexes
  • Ideally, we probably want a static signature to index scheme in place of a locked counter

These make sense to me.

Do we land the mutex approach in the interrim or is there a strong preference to start with the signature scheme? (Personally, I prefer to land mutex approach temporarily as so we can unblock wasm2c use in Firefox). let me know your thoughts!

@keithw

keithw commented Jan 5, 2023 •

Copy link
Copy Markdown
Member
TLS won't work for func indexes

I think the conclusion was that TLS would work well for g_func_types for RLBox. This data structure is global is to support modules importing funcref tables or funcrefs from other modules, which (AIUI) RLBox modules don't do; they only import functions/memories and only from the host, right?

Edit: I went ahead and tried implementing the signature approach today (#2120) and it works with seemingly minimal performance impact and lets us eliminate the functype registry completely, but... it's also pretty complicated. There is some merit in keeping this 100% the runtime's problem. I don't love just adding locks (I don't think they're the right answer for us, or for RLBox/Firefox as discussed above), but I think I might prefer that to making wasm2c much more complicated...

I'm starting to think maybe the cleanest way to make everybody happy is for wasm_rt_init() to allocate the functype registry (and tag count) on the heap, and return an opaque scope pointer that has to be passed back to every module's modname_init_module() function. (And then wasm_rt_free() takes the pointer back and frees everything.) That, plus making the jump buffers thread_local, I think is enough to make the runtime thread-safe even with simultaneous initialization of modules [that don't need to link with one another]. The key assumption is that nobody needs to initialize modules in parallel and then have one of those modules import funcrefs or tags from the other (or a third module import from both of them), which... seems reasonable?

@shravanrn

shravanrn commented Jan 6, 2023 •

Copy link
Copy Markdown
Collaborator Author

RLBox doesn't really use interactions across multiple modules, but passes in callbacks from the host which has the same requirements. Callbacks may not be created in the same thread as they are invoked, so TLS wouldn't work in the RLBox setting.

Here is a simple example

Wasm rlbox module code

typedef int(*int_int_func_t)(int); 

int w2c_func(Z_rlbox_instance_t* wasm_instance, u32 /* int_int_func_t */ f, int param) {
  int_int_func_t fn = (int_int_func_t) wasm_instance.w2c_T0.data[f];
  return fn(wasm_instance, param);
}

Firefox code

Z_rlbox_instance_t* wasm_instance = nullptr;
wasm_rt_funcref_t func_val;

int host_func(Z_rlbox_instance_t* wasm_instance, int a) {
  return a + 1;
}

// Firefox thread 1: create the instance and the callback

Z_rlbox_init_module();
wasm_instance = Z_rlbox_instantiate();

wasm_rt_funcref_t func_val;
func_val.func_type = wasm_rt_register_func_type( /* args */ 2, WASM_RT_I32, WASM_RT_I32, /* return */ 1, WASM_RT_I32);
func_val.func = reinterpret_cast<wasm_rt_function_ptr_t>(host_func);
func_val.module_instance = &wasm_instance;

// Firefox thread 2: set the callback and invoke functions

uint32_t free_index = /* unused index in wasm_instance.w2c_T0.data */;
wasm_instance.w2c_T0.data[free_index] = func_val;

uint32_t result = w2c_func(wasm_instance, free_index, 5);
assert(result == 6);

(responding to the other questions in a new post)

@shravanrn

shravanrn commented Jan 6, 2023 •

Copy link
Copy Markdown
Collaborator Author

@keithw Re locks vs signature scheme vs passing in the func_index context --- I think in the long run, no strong preferences and either solution sounds fine to me (with a slight preference for the signature scheme --- i may have a simpler way to implement this than the approach in the closed PR).

@keithw @sbc100 However, in the short term, given that the signature prototype proved complicated to build, I think we should probably land the locks in the interrim. I am wary of blocking Firefox's move to upstream wasm2c while we figure out how to design/implement either option above, especially when Firefox does not really depend on this. For the Firefox use case, the only extra thing we need right now is security --- we can't ship code with race conditions. Initialization and callbacks are not on the critical path and so locks would be fine for this. From the wasm2c perspective, having a runtime where APIs like wasm_rt_register_func_type are secure by default seems like the right design --- leaving things as is would mean that callers have to remember to lock calls to this func, and also understand that the same lock should be placed before calls to *_init_module to avoid race conditions, which seems unnecessarily complex.

@keithw

keithw commented Jan 7, 2023

Copy link
Copy Markdown
Member

Ok, if you just want to get this in the upstream runtime with the understanding that things will probably change again soon, fine with me I guess.

@shravanrn

shravanrn commented Jan 7, 2023 •

Copy link
Copy Markdown
Collaborator Author

sounds good!
@sbc100 @keithw any chance one of you could sign-off on this PR?

@shravanrn

Copy link
Copy Markdown
Collaborator Author

Sorry for the delay, back from travel. I won't land this just yet, given that #2120 has some momentum.

My plan: If #2120 pending concerns get resolved and we are able to land it, I'll close this PR. If not, I'll land this PR as an interim measure.

@shravanrn shravanrn closed this Apr 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants