From a912ea844e9bd0185c68e7983292b4c043c079f6 Mon Sep 17 00:00:00 2001 From: Edoardo Vacchi Date: Thu, 4 May 2023 01:37:13 +0200 Subject: [PATCH] compiler: update RATIONALE.md for native check (#1432) Signed-off-by: Edoardo Vacchi --- internal/engine/compiler/RATIONALE.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/internal/engine/compiler/RATIONALE.md b/internal/engine/compiler/RATIONALE.md index 0fcea3a7..2db59e72 100644 --- a/internal/engine/compiler/RATIONALE.md +++ b/internal/engine/compiler/RATIONALE.md @@ -75,3 +75,19 @@ and as of Go 1.20, these assembler functions are considered as _unsafe_ for asyn From the Go runtime point of view, the execution of runtime-generated machine codes is considered as a part of that trampoline function. Therefore, runtime-generated machine code is also correctly considered unsafe for async preemption. + +## Why context cancellation is handled in Go code rather than native code + +Since [wazero v1.0.0-pre.9](https://github.com/tetratelabs/wazero/releases/tag/v1.0.0-pre.9), the runtime +supports integration with Go contexts to interrupt execution after a timeout, or in response to explicit cancellation. +This support is internally implemented as a special opcode `builtinFunctionCheckExitCode` that triggers the execution of +a Go function (`ModuleInstance.FailIfClosed`) that atomically checks a sentinel value at strategic points in the code +(e.g. [within loops][checkexitcode_loop]). + +[It _is indeed_ possible to check the sentinel value directly, without leaving the native world][native_check], thus sparing some cycles; +however, because native code never preempts (see section above), this may lead to a state where the other goroutines +never get the chance to run, and thus never get the chance to set the sentinel value; effectively preventing +cancellation from taking place. + +[checkexitcode_loop]: https://github.com/tetratelabs/wazero/blob/86444c67a37dbf9e693ae5b365901f64968d9025/internal/wazeroir/compiler.go#L467-L476 +[native_check]: https://github.com/tetratelabs/wazero/issues/1409