Skip to content

Eliminate wasm_rt_register_func_type in wasm2c runtime API - #2120

Merged
keithw merged 1 commit into
mainfrom
w2c-elim-global-func-types
Jan 25, 2023
Merged

keithw merged 1 commit into
mainfrom
w2c-elim-global-func-types

Conversation

@keithw

@keithw keithw commented Jan 6, 2023 •

Copy link
Copy Markdown
Member

Kicked off by #2117, here is a PR that makes wasm2c serialize each function type, rather than registering function types at module-initialization time in a global registry maintained by the runtime. The serialized function type is the SHA-256 of the mangled param and result types, separated by a space.

At runtime in call_indirect, a known (immediate) function type is compared against the function type stored in a funcref structure. For call_indirects to functions local to the module, or for any call_indirect with a toolchain that merges string constants across compilation units (generally, GCC and clang), this is done by checking the equality of the pointers to each function type. Otherwise, the actual 32-byte values are compared.

The function type IDs can be looked up at runtime with Z_[modname]_get_func_type, which matches the API from wasm_rt_register_func_type (which goes away with this PR). I added a callback example to demo this.

I did a ton of microbenchmarking for a "foreign-module" call_indirect (https://gist.github.com/keithw/aaf17bf55165fe0de522c5c8dbfc6d4d) and the summary is that:

  • in the cases I tested, GCC/clang+ld were able to merge the identical string constants even across compilation units, which means that performance is essentially unchanged (we're just testing pointer equality instead of i32 equality). In every case I tested, it was within +/- 1 cycle of the current main branch.1
  • on MSVC, this doesn't seem to be possible (because a static const char * const can't be used in a static initializer, so the function types have to be static const char arrays). I didn't benchmark it on Windown, but on GCC or clang, there's generally a penalty of around 1 or 1.5 cycles from having to do the 256-bit compare. Again, this is only for call_indirects that cross modules; a "same-module" call_indirect is just the pointer comparison.

wasm2c does the SHA-256 either by using OpenSSL's libcrypto or, if not available or if requested with cmake -DUSE_INTERNAL_SHA256=ON, by using a vendored (header-only) PicoSHA2. (For something security-sensitive, it seemed like we should prefer to use a well-known SHA-256 implementation if possible.) There is no runtime dependency on SHA-256 in the wasm2c runtime or generated modules.

Footnotes

  1. On an AMD 4750U, the performance with clang actually improves over the main branch, from 6 cycles per iteration down to 5 cycles per iteration. GCC with PDO is unchanged, at around 5.25 cycles per iteration. GCC without PDO takes a hit from 5 cycles per iteration up to 6 cycles per iteration. On an Intel i7-9700T, the performance with GCC is unchanged (7 cycles per iteration either way), and clang takes a 1-cycle hit (from 6 cycles to 7 cycles per iteration).) ↩

@keithw
keithw requested review from sbc100 and shravanrn January 6, 2023 07:40
@keithw keithw closed this Jan 6, 2023
@keithw keithw reopened this Jan 7, 2023
@keithw
keithw marked this pull request as draft January 7, 2023 00:14
@keithw
keithw marked this pull request as ready for review January 7, 2023 05:11
@keithw keithw changed the title RFC: eliminate wasm_rt_register_func_type in wasm2c runtime API Eliminate wasm_rt_register_func_type in wasm2c runtime API Jan 7, 2023
@shravanrn

Copy link
Copy Markdown
Collaborator

@keithw The broad approach looks good to me. However, I think the one change that would be great is if we can pull the type serializer into its own separate file/library so I can pull this in for RLBox also. This would let me avoid re-implementing the type serializer in RLBox to dynamically construct a type index.

One point I had when I quickly look at the code is that the complexity of the type serializer makes me a bit nervous, however I don't know of a way to make this any simpler. I was hoping to do a closer code review, but I am traveling at the moment, so I may only be able to get to this in a few days.

@keithw

keithw commented Jan 11, 2023 •

Copy link
Copy Markdown
Member Author

However, I think the one change that would be great is if we can pull the type serializer into its own separate file/library so I can pull this in for RLBox also.

I think that would be quite doable, but there's a question about how you want to use it. E.g. are you able to link with libwabt to get it? That would be one easy way to make this happen without duplicating anything.

Other option would be to just duplicate the functionality in the wasm runtime and maybe have some tests to ensure the equality for at least any type in the testsuite.

@keithw

keithw commented Jan 13, 2023

Copy link
Copy Markdown
Member Author

Or... maybe the easiest approach here is for wasm2c to stick a bunch of #defines in the generated header file, giving a reasonable name for each type in the module, e.g.:

#ifndef Z_w2c_type_param_i32_i64_return_externref
#define Z_w2c_type_param_i32_i64_return_externref (wasm_rt_func_type_t){{.val = 260}, 8})
#endif

That way you could just use the type directly in your code (worst case the type doesn't exist in any module and the code fails to compile, which should be an error anyway since there's no way it can successfully be call_indirect'ed), and it doesn't seem like that big of a deal to pollute the global (preprocessor) namespace with these #define names.

Comment thread src/template/wasm2c.declarations.c Resolved
@keithw
keithw force-pushed the w2c-elim-global-func-types branch 14 times, most recently from d9546b2 to 8feeafc Compare January 17, 2023 02:42

@shravanrn shravanrn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Generally lgtm apart from the two comments.

Comment thread src/c-writer.cc Resolved
Comment thread CMakeLists.txt Resolved
@keithw
keithw force-pushed the w2c-elim-global-func-types branch 3 times, most recently from 02a2bcb to f2fe17e Compare January 19, 2023 22:21
@keithw

keithw commented Jan 21, 2023

Copy link
Copy Markdown
Member Author

OK @shravanrn, I thought about this a bunch and have a proposed approach that you might actually like. If RLBox is comfortable calling the current wasm_rt_register_func_type at runtime, how about if we make wasm2c generate basically the exact same API as part of the transpiled module, so you can call Z[modname]_get_func_type( 2, 1, WASM_RT_I32, WASM_RT_F32, WASM_RT_I64 ) at runtime and get back the corresponding wasm_rt_func_type_t (or NULL if it doesn't exist in the module). You wouldn't have to change the way RLBox does reflection you wouldn't ever have to do any SHA-256ing.

@keithw
keithw force-pushed the w2c-elim-global-func-types branch 2 times, most recently from 8fc5fab to a001816 Compare January 22, 2023 20:45
@keithw

keithw commented Jan 22, 2023 •

Copy link
Copy Markdown
Member Author

OK, done -- I hope this is what you were looking for. wasm2c now generates a Z_[modname]_get_func_type function whose API mirrors the wasm_rt_register_func_type call that RLBox is used to. My hope is that passing a callback dynamically to the module will now be largely unchanged for you. I added a callback demo that gives an example. If the module takes a callback at runtime, then here's what the host-side code to pass in the type-checked callback can look like. And, nobody ever has to compute a SHA-256 at runtime (not the wasm2c runtime, not the wasm2c generated output, and not the host).

@keithw
keithw force-pushed the w2c-elim-global-func-types branch from a001816 to 754a51a Compare January 22, 2023 21:07
This makes wasm2c serialize each function type, rather than registering
function types at module-initialization time. The serialized function
type is the SHA-256 of the mangled param and result types (with a space
between params and results).

At runtime in call_indirect, a known (immediate) function type is
compared against the function type stored in a funcref structure. For
call_indirects to functions local to the module, or for any
call_indirect when the toolchain merges string constants across
compilation units (generally, GCC and clang), this can be done by
comparing the pointers to each function type. Otherwise, the actual
32-byte values are compared.

The function type IDs can be looked up at runtime with
`Z_[modname]_get_func_type`, which matches the API from
`wasm_rt_register_func_type`. A new `callback` example demos this.

wasm2c does the SHA-256 either by linking against libcrypto or, if not
available or if requested via `cmake -DUSE_INTERNAL_SHA256=ON`, by using
a vendored (header-only) PicoSHA2. There is no runtime dependency on
SHA-256 in the wasm2c runtime or generated modules.

This eliminates the last of the per-module state, so this commit also removes
the [modname]_init_module() function and the s_module_initialized bool.
@keithw
keithw force-pushed the w2c-elim-global-func-types branch from 754a51a to f4f2533 Compare January 22, 2023 22:23
@shravanrn

Copy link
Copy Markdown
Collaborator

@keithw This option looks great! Thanks for all your work accommodating the RLBox use case as well. I think we can ship this!

@keithw

keithw commented Jan 24, 2023

Copy link
Copy Markdown
Member Author

Wonderful! Pleasure doing business with you -- I'm glad we were able to converge.

@sbc100 Do you want to weigh in on/review this before merger?

@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.

I don't love the extra dependency, but otherwise I guess the overall approach nicer in the longer term.

Comment thread wasm2c/examples/fac/fac.c
#define FUNC_TYPE_T(x) static const char* const x
#else
#define FUNC_TYPE_T(x) static const char x[]
#endif

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.

Can we not just use static const char* in both cases, avoiding the macro completely?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Unfortunately I couldn't figure out how -- on MSVC, a static const char* const doesn't seem to be a constant expression and can't be used in an initializer, which is how we represent elem segments. (On the other hand, I think C requires a static const char[] to have a distinct address so it can't be merged with another identical string constant.)

Comment thread wasm2c/examples/fac/fac.h
void Z_fac_init_module(void);
void Z_fac_instantiate(Z_fac_instance_t*);
void Z_fac_free(Z_fac_instance_t*);
wasm_rt_func_type_t Z_fac_get_func_type(uint32_t param_count, uint32_t result_count, ...);

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.

Does this need to be a public function?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think so -- the purpose is to help the host generate a funcref that can be passed to Wasm code (as in the new "callback" example). The function isn't called by any of the wasm2c-generated code.

Comment thread .gitmodules Resolved
@keithw

keithw commented Jan 25, 2023

Copy link
Copy Markdown
Member Author

Ok, merging soon barring further concerns/objections. If there is unexpected trouble I hope people will let us know and we can of course revisit. I'm going to email the Debian/Ubuntu and Fedora package maintainers to give a heads-up about the (optional) added libcrypto dependency.

@sbc100

sbc100 commented Jan 25, 2023

Copy link
Copy Markdown
Member

I wonder if SHA1 would be good enough (and slightly faster and less memory intensive at runtime)? It seems like if it good enough to avoid collisions it git it should be more than good enough for this purpose.

@keithw

keithw commented Jan 25, 2023

Copy link
Copy Markdown
Member Author

My understanding was that the security community has been sharply discouraging any "new" use of SHA-1 for a while now. (https://www.zdnet.com/article/its-the-end-of-sha-1-and-i-feel-fine/ is from six years ago.) Even Git has been working on a transition to SHA-256. I think it would raise some eyebrows if we picked SHA-1 in 2023. :-/

In terms of runtime cost, there's some added burden from holding 32 bytes in the binary instead of 20, but it seems nominal since I basically wasn't expecting those 32 bytes to ever get accessed. (If the wasm2c output is compiled via clang or GCC, call_indirect is generally just comparing the pointers without dereferencing them.)

@sbc100

sbc100 commented Jan 25, 2023

Copy link
Copy Markdown
Member

My understanding was that the security community has been sharply discouraging any "new" use of SHA-1 for a while now. (https://www.zdnet.com/article/its-the-end-of-sha-1-and-i-feel-fine/ is from six years ago.) Even Git has been working on a transition to SHA-256. I think it would raise some eyebrows if we picked SHA-1 in 2023. :-/

If this were some kind of crypto application I would agree. I don't really see this as having the same bar for unbreakability though. What is the threat model you are worried about? I guess building a collisions detection system is probably more work that just using SHA-256? .. so maybe you are right.

Part of me does wonder if this solution is a little too clever/complex for its own good.. on the other hand avoiding the central/global type registry is a really nice property.

This change lgtm though.. I think these concerns a minor.

@keithw

keithw commented Jan 25, 2023

Copy link
Copy Markdown
Member Author

All fair points. Re: threat model, I guess I see it as (aspirationally) the same as with a browser-based Wasm engine, in that the Wasm module might be trying really hard to escape the sandbox with a very clever (but invalid) call_indirect. I don't think we're there yet, but I see that as what we're aiming for. So would tend to favor the boring/safe choices.

Merging now, and let's hope this complexity doesn't become a recurring pain point. If so we can certainly revisit.

@keithw
keithw merged commit 777e651 into main Jan 25, 2023
@keithw
keithw deleted the w2c-elim-global-func-types branch January 25, 2023 18:28
@sbc100

sbc100 commented Jan 25, 2023

Copy link
Copy Markdown
Member

All fair points. Re: threat model, I guess I see it as (aspirationally) the same as with a browser-based Wasm engine, in that the Wasm module might be trying really hard to escape the sandbox with a very clever (but invalid) call_indirect.

But presumably no system would ever just trust the compiled/binaries produced by wasm2c. Any system using wasm2c would also be running wasm2c an not consuming the compiled code.. so it could put in place some kind of global collision detection system... but I guess that is what we had in the runtime before.

@sbc100

sbc100 commented Jan 25, 2023

Copy link
Copy Markdown
Member

I also think maybe if we enforced a sensible limit of the size of the types it could make collision forging impossible, but I'm not a hash algorithm expert so its probably best not to guess at this stuff.

dimitry- pushed a commit to AndroidWasm/wabt that referenced this pull request Jan 26, 2023
This makes wasm2c serialize each function type, rather than registering
function types at module-initialization time. The serialized function
type is the SHA-256 of the mangled param and result types (with a space
between params and results).

At runtime in call_indirect, a known (immediate) function type is
compared against the function type stored in a funcref structure. For
call_indirects to functions local to the module, or for any
call_indirect when the toolchain merges string constants across
compilation units (generally, GCC and clang), this can be done by
comparing the pointers to each function type. Otherwise, the actual
32-byte values are compared.

The function type IDs can be looked up at runtime with
`Z_[modname]_get_func_type`, which matches the API from
`wasm_rt_register_func_type`. A new `callback` example demos this.

wasm2c does the SHA-256 either by linking against libcrypto or, if not
available or if requested via `cmake -DUSE_INTERNAL_SHA256=ON`, by using
a vendored (header-only) PicoSHA2. There is no runtime dependency on
SHA-256 in the wasm2c runtime or generated modules.

This eliminates the last of the per-module state, so this commit also removes
the [modname]_init_module() function and the s_module_initialized bool.
@deian

deian commented Jan 27, 2023

Copy link
Copy Markdown

I don't think a sha1 pre-image attack is realistic here (I'd be more concerned about compiler bugs if an attacker that can pull of a pre-image attack is in your attacker model), but that's just my 2c

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.

5 participants