-
Notifications
You must be signed in to change notification settings - Fork 124
/
wasm_store.c
1823 lines (1644 loc) · 57.4 KB
/
wasm_store.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "api.h"
#include "./parser.h"
#include <stdint.h>
#ifdef TREE_SITTER_FEATURE_WASM
#include <wasmtime.h>
#include <wasm.h>
#include <string.h>
#include "./alloc.h"
#include "./array.h"
#include "./atomic.h"
#include "./language.h"
#include "./lexer.h"
#include "./wasm_store.h"
#include "./wasm/wasm-stdlib.h"
#define array_len(a) (sizeof(a) / sizeof(a[0]))
// The following symbols from the C and C++ standard libraries are available
// for external scanners to use.
const char *STDLIB_SYMBOLS[] = {
#include "./stdlib-symbols.txt"
};
// The contents of the `dylink.0` custom section of a wasm module,
// as specified by the current WebAssembly dynamic linking ABI proposal.
typedef struct {
uint32_t memory_size;
uint32_t memory_align;
uint32_t table_size;
uint32_t table_align;
} WasmDylinkInfo;
// WasmLanguageId - A pointer used to identify a language. This language id is
// reference-counted, so that its ownership can be shared between the language
// itself and the instances of the language that are held in wasm stores.
typedef struct {
volatile uint32_t ref_count;
volatile uint32_t is_language_deleted;
} WasmLanguageId;
// LanguageWasmModule - Additional data associated with a wasm-backed
// `TSLanguage`. This data is read-only and does not reference a particular
// wasm store, so it can be shared by all users of a `TSLanguage`. A pointer to
// this is stored on the language itself.
typedef struct {
volatile uint32_t ref_count;
WasmLanguageId *language_id;
wasmtime_module_t *module;
const char *name;
char *symbol_name_buffer;
char *field_name_buffer;
WasmDylinkInfo dylink_info;
} LanguageWasmModule;
// LanguageWasmInstance - Additional data associated with an instantiation of
// a `TSLanguage` in a particular wasm store. The wasm store holds one of
// these structs for each language that it has instantiated.
typedef struct {
WasmLanguageId *language_id;
wasmtime_instance_t instance;
int32_t external_states_address;
int32_t lex_main_fn_index;
int32_t lex_keyword_fn_index;
int32_t scanner_create_fn_index;
int32_t scanner_destroy_fn_index;
int32_t scanner_serialize_fn_index;
int32_t scanner_deserialize_fn_index;
int32_t scanner_scan_fn_index;
} LanguageWasmInstance;
typedef struct {
uint32_t reset_heap;
uint32_t proc_exit;
uint32_t abort;
uint32_t assert_fail;
uint32_t notify_memory_growth;
uint32_t debug_message;
uint32_t at_exit;
uint32_t args_get;
uint32_t args_sizes_get;
} BuiltinFunctionIndices;
// TSWasmStore - A struct that allows a given `Parser` to use wasm-backed
// languages. This struct is mutable, and can only be used by one parser at a
// time.
struct TSWasmStore {
wasm_engine_t *engine;
wasmtime_store_t *store;
wasmtime_table_t function_table;
wasmtime_memory_t memory;
TSLexer *current_lexer;
LanguageWasmInstance *current_instance;
Array(LanguageWasmInstance) language_instances;
uint32_t current_memory_offset;
uint32_t current_function_table_offset;
uint32_t *stdlib_fn_indices;
BuiltinFunctionIndices builtin_fn_indices;
wasmtime_global_t stack_pointer_global;
wasm_globaltype_t *const_i32_type;
bool has_error;
uint32_t lexer_address;
uint32_t serialization_buffer_address;
};
typedef Array(char) StringData;
// LanguageInWasmMemory - The memory layout of a `TSLanguage` when compiled to
// wasm32. This is used to copy static language data out of the wasm memory.
typedef struct {
uint32_t version;
uint32_t symbol_count;
uint32_t alias_count;
uint32_t token_count;
uint32_t external_token_count;
uint32_t state_count;
uint32_t large_state_count;
uint32_t production_id_count;
uint32_t field_count;
uint16_t max_alias_sequence_length;
int32_t parse_table;
int32_t small_parse_table;
int32_t small_parse_table_map;
int32_t parse_actions;
int32_t symbol_names;
int32_t field_names;
int32_t field_map_slices;
int32_t field_map_entries;
int32_t symbol_metadata;
int32_t public_symbol_map;
int32_t alias_map;
int32_t alias_sequences;
int32_t lex_modes;
int32_t lex_fn;
int32_t keyword_lex_fn;
TSSymbol keyword_capture_token;
struct {
int32_t states;
int32_t symbol_map;
int32_t create;
int32_t destroy;
int32_t scan;
int32_t serialize;
int32_t deserialize;
} external_scanner;
int32_t primary_state_ids;
} LanguageInWasmMemory;
// LexerInWasmMemory - The memory layout of a `TSLexer` when compiled to wasm32.
// This is used to copy mutable lexing state in and out of the wasm memory.
typedef struct {
int32_t lookahead;
TSSymbol result_symbol;
int32_t advance;
int32_t mark_end;
int32_t get_column;
int32_t is_at_included_range_start;
int32_t eof;
} LexerInWasmMemory;
static volatile uint32_t NEXT_LANGUAGE_ID;
// Linear memory layout:
// [ <-- stack | stdlib statics | lexer | serialization_buffer | language statics --> | heap --> ]
#define MAX_MEMORY_SIZE (128 * 1024 * 1024 / MEMORY_PAGE_SIZE)
/************************
* WasmDylinkMemoryInfo
***********************/
static uint8_t read_u8(const uint8_t **p, const uint8_t *end) {
return *(*p)++;
}
static inline uint64_t read_uleb128(const uint8_t **p, const uint8_t *end) {
uint64_t value = 0;
unsigned shift = 0;
do {
if (*p == end) return UINT64_MAX;
value += (uint64_t)(**p & 0x7f) << shift;
shift += 7;
} while (*((*p)++) >= 128);
return value;
}
static bool wasm_dylink_info__parse(
const uint8_t *bytes,
size_t length,
WasmDylinkInfo *info
) {
const uint8_t WASM_MAGIC_NUMBER[4] = {0, 'a', 's', 'm'};
const uint8_t WASM_VERSION[4] = {1, 0, 0, 0};
const uint8_t WASM_CUSTOM_SECTION = 0x0;
const uint8_t WASM_DYLINK_MEM_INFO = 0x1;
const uint8_t *p = bytes;
const uint8_t *end = bytes + length;
if (length < 8) return false;
if (memcmp(p, WASM_MAGIC_NUMBER, 4) != 0) return false;
p += 4;
if (memcmp(p, WASM_VERSION, 4) != 0) return false;
p += 4;
while (p < end) {
uint8_t section_id = read_u8(&p, end);
uint32_t section_length = read_uleb128(&p, end);
const uint8_t *section_end = p + section_length;
if (section_end > end) return false;
if (section_id == WASM_CUSTOM_SECTION) {
uint32_t name_length = read_uleb128(&p, section_end);
const uint8_t *name_end = p + name_length;
if (name_end > section_end) return false;
if (name_length == 8 && memcmp(p, "dylink.0", 8) == 0) {
p = name_end;
while (p < section_end) {
uint8_t subsection_type = read_u8(&p, section_end);
uint32_t subsection_size = read_uleb128(&p, section_end);
const uint8_t *subsection_end = p + subsection_size;
if (subsection_end > section_end) return false;
if (subsection_type == WASM_DYLINK_MEM_INFO) {
info->memory_size = read_uleb128(&p, subsection_end);
info->memory_align = read_uleb128(&p, subsection_end);
info->table_size = read_uleb128(&p, subsection_end);
info->table_align = read_uleb128(&p, subsection_end);
return true;
}
p = subsection_end;
}
}
}
p = section_end;
}
return false;
}
/*******************************************
* Native callbacks exposed to wasm modules
*******************************************/
static wasm_trap_t *callback__abort(
void *env,
wasmtime_caller_t* caller,
wasmtime_val_raw_t *args_and_results,
size_t args_and_results_len
) {
return wasmtime_trap_new("wasm module called abort", 24);
}
static wasm_trap_t *callback__debug_message(
void *env,
wasmtime_caller_t* caller,
wasmtime_val_raw_t *args_and_results,
size_t args_and_results_len
) {
wasmtime_context_t *context = wasmtime_caller_context(caller);
TSWasmStore *store = env;
assert(args_and_results_len == 2);
uint32_t string_address = args_and_results[0].i32;
uint32_t value = args_and_results[1].i32;
uint8_t *memory = wasmtime_memory_data(context, &store->memory);
printf("DEBUG: %s %u\n", &memory[string_address], value);
return NULL;
}
static wasm_trap_t *callback__noop(
void *env,
wasmtime_caller_t* caller,
wasmtime_val_raw_t *args_and_results,
size_t args_and_results_len
) {
return NULL;
}
static wasm_trap_t *callback__lexer_advance(
void *env,
wasmtime_caller_t* caller,
wasmtime_val_raw_t *args_and_results,
size_t args_and_results_len
) {
wasmtime_context_t *context = wasmtime_caller_context(caller);
assert(args_and_results_len == 2);
TSWasmStore *store = env;
TSLexer *lexer = store->current_lexer;
bool skip = args_and_results[1].i32;
lexer->advance(lexer, skip);
uint8_t *memory = wasmtime_memory_data(context, &store->memory);
memcpy(&memory[store->lexer_address], &lexer->lookahead, sizeof(lexer->lookahead));
return NULL;
}
static wasm_trap_t *callback__lexer_mark_end(
void *env,
wasmtime_caller_t* caller,
wasmtime_val_raw_t *args_and_results,
size_t args_and_results_len
) {
TSWasmStore *store = env;
TSLexer *lexer = store->current_lexer;
lexer->mark_end(lexer);
return NULL;
}
static wasm_trap_t *callback__lexer_get_column(
void *env,
wasmtime_caller_t* caller,
wasmtime_val_raw_t *args_and_results,
size_t args_and_results_len
) {
TSWasmStore *store = env;
TSLexer *lexer = store->current_lexer;
uint32_t result = lexer->get_column(lexer);
args_and_results[0].i32 = result;
return NULL;
}
static wasm_trap_t *callback__lexer_is_at_included_range_start(
void *env,
wasmtime_caller_t* caller,
wasmtime_val_raw_t *args_and_results,
size_t args_and_results_len
) {
TSWasmStore *store = env;
TSLexer *lexer = store->current_lexer;
bool result = lexer->is_at_included_range_start(lexer);
args_and_results[0].i32 = result;
return NULL;
}
static wasm_trap_t *callback__lexer_eof(
void *env,
wasmtime_caller_t* caller,
wasmtime_val_raw_t *args_and_results,
size_t args_and_results_len
) {
TSWasmStore *store = env;
TSLexer *lexer = store->current_lexer;
bool result = lexer->eof(lexer);
args_and_results[0].i32 = result;
return NULL;
}
typedef struct {
uint32_t *storage_location;
wasmtime_func_unchecked_callback_t callback;
wasm_functype_t *type;
} FunctionDefinition;
static void *copy(const void *data, size_t size) {
void *result = ts_malloc(size);
memcpy(result, data, size);
return result;
}
static void *copy_unsized_static_array(
const uint8_t *data,
int32_t start_address,
const int32_t all_addresses[],
size_t address_count
) {
int32_t end_address = 0;
for (unsigned i = 0; i < address_count; i++) {
if (all_addresses[i] > start_address) {
if (!end_address || all_addresses[i] < end_address) {
end_address = all_addresses[i];
}
}
}
if (!end_address) return NULL;
size_t size = end_address - start_address;
void *result = ts_malloc(size);
memcpy(result, &data[start_address], size);
return result;
}
static void *copy_strings(
const uint8_t *data,
int32_t array_address,
size_t count,
StringData *string_data
) {
const char **result = ts_malloc(count * sizeof(char *));
for (unsigned i = 0; i < count; i++) {
int32_t address;
memcpy(&address, &data[array_address + i * sizeof(address)], sizeof(address));
if (address == 0) {
result[i] = (const char *)-1;
} else {
const uint8_t *string = &data[address];
uint32_t len = strlen((const char *)string);
result[i] = (const char *)(uintptr_t)string_data->size;
array_extend(string_data, len + 1, string);
}
}
for (unsigned i = 0; i < count; i++) {
if (result[i] == (const char *)-1) {
result[i] = NULL;
} else {
result[i] = string_data->contents + (uintptr_t)result[i];
}
}
return result;
}
static bool name_eq(const wasm_name_t *name, const char *string) {
return strncmp(string, name->data, name->size) == 0;
}
static inline wasm_functype_t* wasm_functype_new_4_0(
wasm_valtype_t* p1,
wasm_valtype_t* p2,
wasm_valtype_t* p3,
wasm_valtype_t* p4
) {
wasm_valtype_t* ps[4] = {p1, p2, p3, p4};
wasm_valtype_vec_t params, results;
wasm_valtype_vec_new(¶ms, 4, ps);
wasm_valtype_vec_new_empty(&results);
return wasm_functype_new(¶ms, &results);
}
#define format(output, ...) \
do { \
size_t message_length = snprintf((char *)NULL, 0, __VA_ARGS__); \
*output = ts_malloc(message_length + 1); \
snprintf(*output, message_length + 1, __VA_ARGS__); \
} while (0)
WasmLanguageId *language_id_new() {
WasmLanguageId *self = ts_malloc(sizeof(WasmLanguageId));
self->is_language_deleted = false;
self->ref_count = 1;
return self;
}
WasmLanguageId *language_id_clone(WasmLanguageId *self) {
atomic_inc(&self->ref_count);
return self;
}
void language_id_delete(WasmLanguageId *self) {
if (atomic_dec(&self->ref_count) == 0) {
ts_free(self);
}
}
static wasmtime_extern_t get_builtin_extern(
wasmtime_table_t *table,
unsigned index
) {
return (wasmtime_extern_t) {
.kind = WASMTIME_EXTERN_FUNC,
.of.func = (wasmtime_func_t) {
.store_id = table->store_id,
.index = index
}
};
}
static bool ts_wasm_store__provide_builtin_import(
TSWasmStore *self,
const wasm_name_t *import_name,
wasmtime_extern_t *import
) {
wasmtime_error_t *error = NULL;
wasmtime_context_t *context = wasmtime_store_context(self->store);
// Dynamic linking parameters
if (name_eq(import_name, "__memory_base")) {
wasmtime_val_t value = WASM_I32_VAL(self->current_memory_offset);
wasmtime_global_t global;
error = wasmtime_global_new(context, self->const_i32_type, &value, &global);
assert(!error);
*import = (wasmtime_extern_t) {.kind = WASMTIME_EXTERN_GLOBAL, .of.global = global};
} else if (name_eq(import_name, "__table_base")) {
wasmtime_val_t value = WASM_I32_VAL(self->current_function_table_offset);
wasmtime_global_t global;
error = wasmtime_global_new(context, self->const_i32_type, &value, &global);
assert(!error);
*import = (wasmtime_extern_t) {.kind = WASMTIME_EXTERN_GLOBAL, .of.global = global};
} else if (name_eq(import_name, "__stack_pointer")) {
*import = (wasmtime_extern_t) {.kind = WASMTIME_EXTERN_GLOBAL, .of.global = self->stack_pointer_global};
} else if (name_eq(import_name, "__indirect_function_table")) {
*import = (wasmtime_extern_t) {.kind = WASMTIME_EXTERN_TABLE, .of.table = self->function_table};
} else if (name_eq(import_name, "memory")) {
*import = (wasmtime_extern_t) {.kind = WASMTIME_EXTERN_MEMORY, .of.memory = self->memory};
}
// Builtin functions
else if (name_eq(import_name, "__assert_fail")) {
*import = get_builtin_extern(&self->function_table, self->builtin_fn_indices.assert_fail);
} else if (name_eq(import_name, "__cxa_atexit")) {
*import = get_builtin_extern(&self->function_table, self->builtin_fn_indices.at_exit);
} else if (name_eq(import_name, "args_get")) {
*import = get_builtin_extern(&self->function_table, self->builtin_fn_indices.args_get);
} else if (name_eq(import_name, "args_sizes_get")) {
*import = get_builtin_extern(&self->function_table, self->builtin_fn_indices.args_sizes_get);
} else if (name_eq(import_name, "abort")) {
*import = get_builtin_extern(&self->function_table, self->builtin_fn_indices.abort);
} else if (name_eq(import_name, "proc_exit")) {
*import = get_builtin_extern(&self->function_table, self->builtin_fn_indices.proc_exit);
} else if (name_eq(import_name, "emscripten_notify_memory_growth")) {
*import = get_builtin_extern(&self->function_table, self->builtin_fn_indices.notify_memory_growth);
} else if (name_eq(import_name, "tree_sitter_debug_message")) {
*import = get_builtin_extern(&self->function_table, self->builtin_fn_indices.debug_message);
} else {
return false;
}
return true;
}
static bool ts_wasm_store__call_module_initializer(
TSWasmStore *self,
const wasm_name_t *export_name,
wasmtime_extern_t *export,
wasm_trap_t **trap
) {
if (
name_eq(export_name, "_initialize") ||
name_eq(export_name, "__wasm_apply_data_relocs") ||
name_eq(export_name, "__wasm_call_ctors")
) {
wasmtime_context_t *context = wasmtime_store_context(self->store);
wasmtime_func_t initialization_func = export->of.func;
wasmtime_error_t *error = wasmtime_func_call(context, &initialization_func, NULL, 0, NULL, 0, trap);
assert(!error);
return true;
} else {
return false;
}
}
TSWasmStore *ts_wasm_store_new(TSWasmEngine *engine, TSWasmError *wasm_error) {
TSWasmStore *self = ts_calloc(1, sizeof(TSWasmStore));
wasmtime_store_t *store = wasmtime_store_new(engine, self, NULL);
wasmtime_context_t *context = wasmtime_store_context(store);
wasmtime_error_t *error = NULL;
wasm_trap_t *trap = NULL;
wasm_message_t message = WASM_EMPTY_VEC;
wasm_exporttype_vec_t export_types = WASM_EMPTY_VEC;
wasmtime_extern_t *imports = NULL;
wasmtime_module_t *stdlib_module = NULL;
wasm_memorytype_t *memory_type = NULL;
wasm_tabletype_t *table_type = NULL;
// Define functions called by scanners via function pointers on the lexer.
LexerInWasmMemory lexer = {
.lookahead = 0,
.result_symbol = 0,
};
FunctionDefinition lexer_definitions[] = {
{
(uint32_t *)&lexer.advance,
callback__lexer_advance,
wasm_functype_new_2_0(wasm_valtype_new_i32(), wasm_valtype_new_i32())
},
{
(uint32_t *)&lexer.mark_end,
callback__lexer_mark_end,
wasm_functype_new_1_0(wasm_valtype_new_i32())
},
{
(uint32_t *)&lexer.get_column,
callback__lexer_get_column,
wasm_functype_new_1_1(wasm_valtype_new_i32(), wasm_valtype_new_i32())
},
{
(uint32_t *)&lexer.is_at_included_range_start,
callback__lexer_is_at_included_range_start,
wasm_functype_new_1_1(wasm_valtype_new_i32(), wasm_valtype_new_i32())
},
{
(uint32_t *)&lexer.eof,
callback__lexer_eof,
wasm_functype_new_1_1(wasm_valtype_new_i32(), wasm_valtype_new_i32())
},
};
// Define builtin functions that can be imported by scanners.
BuiltinFunctionIndices builtin_fn_indices;
FunctionDefinition builtin_definitions[] = {
{
&builtin_fn_indices.proc_exit,
callback__abort,
wasm_functype_new_1_0(wasm_valtype_new_i32())
},
{
&builtin_fn_indices.abort,
callback__abort,
wasm_functype_new_0_0()
},
{
&builtin_fn_indices.assert_fail,
callback__abort,
wasm_functype_new_4_0(wasm_valtype_new_i32(), wasm_valtype_new_i32(), wasm_valtype_new_i32(), wasm_valtype_new_i32())
},
{
&builtin_fn_indices.notify_memory_growth,
callback__noop,
wasm_functype_new_1_0(wasm_valtype_new_i32())
},
{
&builtin_fn_indices.debug_message,
callback__debug_message,
wasm_functype_new_2_0(wasm_valtype_new_i32(), wasm_valtype_new_i32())
},
{
&builtin_fn_indices.at_exit,
callback__noop,
wasm_functype_new_3_1(wasm_valtype_new_i32(), wasm_valtype_new_i32(), wasm_valtype_new_i32(), wasm_valtype_new_i32())
},
{
&builtin_fn_indices.args_get,
callback__noop,
wasm_functype_new_2_1(wasm_valtype_new_i32(), wasm_valtype_new_i32(), wasm_valtype_new_i32())
},
{
&builtin_fn_indices.args_sizes_get,
callback__noop,
wasm_functype_new_2_1(wasm_valtype_new_i32(), wasm_valtype_new_i32(), wasm_valtype_new_i32())
},
};
// Create all of the wasm functions.
unsigned builtin_definitions_len = array_len(builtin_definitions);
unsigned lexer_definitions_len = array_len(lexer_definitions);
for (unsigned i = 0; i < builtin_definitions_len; i++) {
FunctionDefinition *definition = &builtin_definitions[i];
wasmtime_func_t func;
wasmtime_func_new_unchecked(context, definition->type, definition->callback, self, NULL, &func);
*definition->storage_location = func.index;
wasm_functype_delete(definition->type);
}
for (unsigned i = 0; i < lexer_definitions_len; i++) {
FunctionDefinition *definition = &lexer_definitions[i];
wasmtime_func_t func;
wasmtime_func_new_unchecked(context, definition->type, definition->callback, self, NULL, &func);
*definition->storage_location = func.index;
wasm_functype_delete(definition->type);
}
// Compile the stdlib module.
error = wasmtime_module_new(engine, STDLIB_WASM, STDLIB_WASM_LEN, &stdlib_module);
if (error) {
wasmtime_error_message(error, &message);
wasm_error->kind = TSWasmErrorKindCompile;
format(
&wasm_error->message,
"failed to compile wasm stdlib: %.*s",
(int)message.size, message.data
);
goto error;
}
// Retrieve the stdlib module's imports.
wasm_importtype_vec_t import_types = WASM_EMPTY_VEC;
wasmtime_module_imports(stdlib_module, &import_types);
// Find the initial number of memory pages needed by the stdlib.
const wasm_memorytype_t *stdlib_memory_type;
for (unsigned i = 0; i < import_types.size; i++) {
wasm_importtype_t *import_type = import_types.data[i];
const wasm_name_t *import_name = wasm_importtype_name(import_type);
if (name_eq(import_name, "memory")) {
const wasm_externtype_t *type = wasm_importtype_type(import_type);
stdlib_memory_type = wasm_externtype_as_memorytype_const(type);
}
}
if (!stdlib_memory_type) {
wasm_error->kind = TSWasmErrorKindCompile;
format(
&wasm_error->message,
"wasm stdlib is missing the 'memory' import"
);
goto error;
}
// Initialize store's memory
uint64_t initial_memory_pages = wasmtime_memorytype_minimum(stdlib_memory_type);
wasm_limits_t memory_limits = {.min = initial_memory_pages, .max = MAX_MEMORY_SIZE};
memory_type = wasm_memorytype_new(&memory_limits);
wasmtime_memory_t memory;
error = wasmtime_memory_new(context, memory_type, &memory);
if (error) {
wasmtime_error_message(error, &message);
wasm_error->kind = TSWasmErrorKindAllocate;
format(
&wasm_error->message,
"failed to allocate wasm memory: %.*s",
(int)message.size, message.data
);
goto error;
}
wasm_memorytype_delete(memory_type);
memory_type = NULL;
// Initialize store's function table
wasm_limits_t table_limits = {.min = 1, .max = wasm_limits_max_default};
table_type = wasm_tabletype_new(wasm_valtype_new(WASM_FUNCREF), &table_limits);
wasmtime_val_t initializer = {.kind = WASMTIME_FUNCREF};
wasmtime_table_t function_table;
error = wasmtime_table_new(context, table_type, &initializer, &function_table);
if (error) {
wasmtime_error_message(error, &message);
wasm_error->kind = TSWasmErrorKindAllocate;
format(
&wasm_error->message,
"failed to allocate wasm table: %.*s",
(int)message.size, message.data
);
goto error;
}
wasm_tabletype_delete(table_type);
table_type = NULL;
unsigned stdlib_symbols_len = array_len(STDLIB_SYMBOLS);
// Define globals for the stack and heap start addresses.
wasm_globaltype_t *const_i32_type = wasm_globaltype_new(wasm_valtype_new_i32(), WASM_CONST);
wasm_globaltype_t *var_i32_type = wasm_globaltype_new(wasm_valtype_new_i32(), WASM_VAR);
wasmtime_val_t stack_pointer_value = WASM_I32_VAL(0);
wasmtime_global_t stack_pointer_global;
error = wasmtime_global_new(context, var_i32_type, &stack_pointer_value, &stack_pointer_global);
assert(!error);
*self = (TSWasmStore) {
.engine = engine,
.store = store,
.memory = memory,
.function_table = function_table,
.language_instances = array_new(),
.stdlib_fn_indices = ts_calloc(stdlib_symbols_len, sizeof(uint32_t)),
.builtin_fn_indices = builtin_fn_indices,
.stack_pointer_global = stack_pointer_global,
.current_memory_offset = 0,
.current_function_table_offset = 0,
.const_i32_type = const_i32_type,
};
// Set up the imports for the stdlib module.
imports = ts_calloc(import_types.size, sizeof(wasmtime_extern_t));
for (unsigned i = 0; i < import_types.size; i++) {
wasm_importtype_t *type = import_types.data[i];
const wasm_name_t *import_name = wasm_importtype_name(type);
if (!ts_wasm_store__provide_builtin_import(self, import_name, &imports[i])) {
wasm_error->kind = TSWasmErrorKindInstantiate;
format(
&wasm_error->message,
"unexpected import in wasm stdlib: %.*s\n",
(int)import_name->size, import_name->data
);
goto error;
}
}
// Instantiate the stdlib module.
wasmtime_instance_t instance;
error = wasmtime_instance_new(context, stdlib_module, imports, import_types.size, &instance, &trap);
ts_free(imports);
imports = NULL;
if (error) {
wasmtime_error_message(error, &message);
wasm_error->kind = TSWasmErrorKindInstantiate;
format(
&wasm_error->message,
"failed to instantiate wasm stdlib module: %.*s",
(int)message.size, message.data
);
goto error;
}
if (trap) {
wasm_trap_message(trap, &message);
wasm_error->kind = TSWasmErrorKindInstantiate;
format(
&wasm_error->message,
"trapped when instantiating wasm stdlib module: %.*s",
(int)message.size, message.data
);
goto error;
}
wasm_importtype_vec_delete(&import_types);
// Process the stdlib module's exports.
for (unsigned i = 0; i < stdlib_symbols_len; i++) {
self->stdlib_fn_indices[i] = UINT32_MAX;
}
wasmtime_module_exports(stdlib_module, &export_types);
for (unsigned i = 0; i < export_types.size; i++) {
wasm_exporttype_t *export_type = export_types.data[i];
const wasm_name_t *name = wasm_exporttype_name(export_type);
char *export_name;
size_t name_len;
wasmtime_extern_t export = {.kind = WASM_EXTERN_GLOBAL};
bool exists = wasmtime_instance_export_nth(context, &instance, i, &export_name, &name_len, &export);
assert(exists);
if (export.kind == WASMTIME_EXTERN_GLOBAL) {
if (name_eq(name, "__stack_pointer")) {
self->stack_pointer_global = export.of.global;
}
}
if (export.kind == WASMTIME_EXTERN_FUNC) {
if (ts_wasm_store__call_module_initializer(self, name, &export, &trap)) {
if (trap) {
wasm_trap_message(trap, &message);
wasm_error->kind = TSWasmErrorKindInstantiate;
format(
&wasm_error->message,
"trap when calling stdlib relocation function: %.*s\n",
(int)message.size, message.data
);
goto error;
}
continue;
}
if (name_eq(name, "reset_heap")) {
self->builtin_fn_indices.reset_heap = export.of.func.index;
continue;
}
for (unsigned j = 0; j < stdlib_symbols_len; j++) {
if (name_eq(name, STDLIB_SYMBOLS[j])) {
self->stdlib_fn_indices[j] = export.of.func.index;
break;
}
}
}
}
if (self->builtin_fn_indices.reset_heap == UINT32_MAX) {
wasm_error->kind = TSWasmErrorKindInstantiate;
format(
&wasm_error->message,
"missing malloc reset function in wasm stdlib"
);
goto error;
}
for (unsigned i = 0; i < stdlib_symbols_len; i++) {
if (self->stdlib_fn_indices[i] == UINT32_MAX) {
wasm_error->kind = TSWasmErrorKindInstantiate;
format(
&wasm_error->message,
"missing exported symbol in wasm stdlib: %s",
STDLIB_SYMBOLS[i]
);
goto error;
}
}
wasm_exporttype_vec_delete(&export_types);
wasmtime_module_delete(stdlib_module);
// Add all of the lexer callback functions to the function table. Store their function table
// indices on the in-memory lexer.
uint32_t table_index;
error = wasmtime_table_grow(context, &function_table, lexer_definitions_len, &initializer, &table_index);
if (error) {
wasmtime_error_message(error, &message);
wasm_error->kind = TSWasmErrorKindAllocate;
format(
&wasm_error->message,
"failed to grow wasm table to initial size: %.*s",
(int)message.size, message.data
);
goto error;
}
for (unsigned i = 0; i < lexer_definitions_len; i++) {
FunctionDefinition *definition = &lexer_definitions[i];
wasmtime_func_t func = {function_table.store_id, *definition->storage_location};
wasmtime_val_t func_val = {.kind = WASMTIME_FUNCREF, .of.funcref = func};
error = wasmtime_table_set(context, &function_table, table_index, &func_val);
assert(!error);
*(int32_t *)(definition->storage_location) = table_index;
table_index++;
}
self->current_function_table_offset = table_index;
self->lexer_address = initial_memory_pages * MEMORY_PAGE_SIZE;
self->serialization_buffer_address = self->lexer_address + sizeof(LexerInWasmMemory);
self->current_memory_offset = self->serialization_buffer_address + TREE_SITTER_SERIALIZATION_BUFFER_SIZE;
// Grow the memory enough to hold the builtin lexer and serialization buffer.
uint32_t new_pages_needed = (self->current_memory_offset - self->lexer_address - 1) / MEMORY_PAGE_SIZE + 1;
uint64_t prev_memory_size;
wasmtime_memory_grow(context, &memory, new_pages_needed, &prev_memory_size);
uint8_t *memory_data = wasmtime_memory_data(context, &memory);
memcpy(&memory_data[self->lexer_address], &lexer, sizeof(lexer));
return self;
error:
ts_free(self);
if (stdlib_module) wasmtime_module_delete(stdlib_module);
if (store) wasmtime_store_delete(store);
if (import_types.size) wasm_importtype_vec_delete(&import_types);
if (memory_type) wasm_memorytype_delete(memory_type);
if (table_type) wasm_tabletype_delete(table_type);
if (trap) wasm_trap_delete(trap);
if (error) wasmtime_error_delete(error);
if (message.size) wasm_byte_vec_delete(&message);
if (export_types.size) wasm_exporttype_vec_delete(&export_types);
if (imports) ts_free(imports);
return NULL;
}
void ts_wasm_store_delete(TSWasmStore *self) {
if (!self) return;
ts_free(self->stdlib_fn_indices);
wasm_globaltype_delete(self->const_i32_type);
wasmtime_store_delete(self->store);
wasm_engine_delete(self->engine);
for (unsigned i = 0; i < self->language_instances.size; i++) {
LanguageWasmInstance *instance = &self->language_instances.contents[i];
language_id_delete(instance->language_id);
}
array_delete(&self->language_instances);
ts_free(self);
}
size_t ts_wasm_store_language_count(const TSWasmStore *self) {
size_t result = 0;
for (unsigned i = 0; i < self->language_instances.size; i++) {
const WasmLanguageId *id = self->language_instances.contents[i].language_id;
if (!id->is_language_deleted) {
result++;
}
}
return result;
}
static bool ts_wasm_store__instantiate(
TSWasmStore *self,
wasmtime_module_t *module,
const char *language_name,
const WasmDylinkInfo *dylink_info,
wasmtime_instance_t *result,
int32_t *language_address,
char **error_message
) {
wasmtime_error_t *error = NULL;
wasm_trap_t *trap = NULL;
wasm_message_t message = WASM_EMPTY_VEC;
char *language_function_name = NULL;
wasmtime_extern_t *imports = NULL;
wasmtime_context_t *context = wasmtime_store_context(self->store);
// Grow the function table to make room for the new functions.
wasmtime_val_t initializer = {.kind = WASMTIME_FUNCREF};
uint32_t prev_table_size;
error = wasmtime_table_grow(context, &self->function_table, dylink_info->table_size, &initializer, &prev_table_size);
if (error) {
format(error_message, "invalid function table size %u", dylink_info->table_size);
goto error;
}
// Grow the memory to make room for the new data.
uint32_t needed_memory_size = self->current_memory_offset + dylink_info->memory_size;
uint32_t current_memory_size = wasmtime_memory_data_size(context, &self->memory);
if (needed_memory_size > current_memory_size) {
uint32_t pages_to_grow = (
needed_memory_size - current_memory_size + MEMORY_PAGE_SIZE - 1) /
MEMORY_PAGE_SIZE;
uint64_t prev_memory_size;
error = wasmtime_memory_grow(context, &self->memory, pages_to_grow, &prev_memory_size);
if (error) {
format(error_message, "invalid memory size %u", dylink_info->memory_size);
goto error;
}
}
// Construct the language function name as string.
format(&language_function_name, "tree_sitter_%s", language_name);
const uint64_t store_id = self->function_table.store_id;
// Build the imports list for the module.
wasm_importtype_vec_t import_types = WASM_EMPTY_VEC;
wasmtime_module_imports(module, &import_types);
imports = ts_calloc(import_types.size, sizeof(wasmtime_extern_t));
for (unsigned i = 0; i < import_types.size; i++) {
const wasm_importtype_t *import_type = import_types.data[i];
const wasm_name_t *import_name = wasm_importtype_name(import_type);
if (import_name->size == 0) {
format(error_message, "empty import name");
goto error;
}