Skip to content

Commit

Permalink
Merge pull request #3068 from tree-sitter/load-old-language-via-wasm-…
Browse files Browse the repository at this point in the history
…crash

Fix crash when attempting to load ancient languages via wasm
  • Loading branch information
maxbrunsfeld authored Feb 23, 2024
2 parents 1f751bb + 8dded3a commit 9301c1e
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/binding_rust/wasm_language.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ impl fmt::Display for WasmError {
WasmErrorKind::Instantiate => "Failed to instantiate wasm module",
WasmErrorKind::Other => "Unknown error",
};
write!(f, "{kind} {}", self.message)
write!(f, "{kind}: {}", self.message)
}
}

Expand Down
5 changes: 4 additions & 1 deletion lib/src/language.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ extern "C" {

#define ts_builtin_sym_error_repeat (ts_builtin_sym_error - 1)

#define LANGUAGE_VERSION_WITH_PRIMARY_STATES 14
#define LANGUAGE_VERSION_USABLE_VIA_WASM 13

typedef struct {
const TSParseAction *actions;
uint32_t action_count;
Expand Down Expand Up @@ -186,7 +189,7 @@ static inline bool ts_language_state_is_primary(
const TSLanguage *self,
TSStateId state
) {
if (self->version >= 14) {
if (self->version >= LANGUAGE_VERSION_WITH_PRIMARY_STATES) {
return state == self->primary_state_ids[state];
} else {
return true;
Expand Down
9 changes: 8 additions & 1 deletion lib/src/wasm.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "./alloc.h"
#include "./array.h"
#include "./atomic.h"
#include "./language.h"
#include "./lexer.h"
#include "./wasm.h"
#include "./wasm/wasm-stdlib.h"
Expand Down Expand Up @@ -1057,6 +1058,12 @@ const TSLanguage *ts_wasm_store_load_language(
const uint8_t *memory = wasmtime_memory_data(context, &self->memory);
memcpy(&wasm_language, &memory[language_address], sizeof(LanguageInWasmMemory));

if (wasm_language.version < LANGUAGE_VERSION_USABLE_VIA_WASM) {
wasm_error->kind = TSWasmErrorKindInstantiate;
format(&wasm_error->message, "language version %u is too old for wasm", wasm_language.version);
goto error;
}

int32_t addresses[] = {
wasm_language.alias_map,
wasm_language.alias_sequences,
Expand Down Expand Up @@ -1188,7 +1195,7 @@ const TSLanguage *ts_wasm_store_load_language(
);
}

if (language->version >= 14) {
if (language->version >= LANGUAGE_VERSION_WITH_PRIMARY_STATES) {
language->primary_state_ids = copy(
&memory[wasm_language.primary_state_ids],
wasm_language.state_count * sizeof(TSStateId)
Expand Down

0 comments on commit 9301c1e

Please sign in to comment.