Skip to content

Commit ea6cef7

Browse files
authored
Fix malloc non-thread-safe usage in lib-wasi-threads test (#2022)
In the WASI thread test modified in this PR, malloc was used in multiple threads without a lock. But wasi-libc implementation of malloc is not thread-safe.
1 parent ff38877 commit ea6cef7

1 file changed

Lines changed: 9 additions & 0 deletions

File tree

core/iwasm/libraries/lib-wasi-threads/test/update_shared_data_and_alloc_heap.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include <stdio.h>
1212
#include <assert.h>
1313
#include <stdbool.h>
14+
#include <pthread.h>
1415

1516
#include "wasi_thread_start.h"
1617

@@ -29,6 +30,7 @@ typedef struct {
2930
int *pval;
3031
} shared_t;
3132

33+
pthread_mutex_t mutex;
3234
int *vals[NUM_THREADS];
3335

3436
void
@@ -39,7 +41,9 @@ __wasi_thread_start_C(int thread_id, int *start_arg)
3941
for (int i = 0; i < NUM_ITER; i++)
4042
__atomic_fetch_add(data->count, 1, __ATOMIC_SEQ_CST);
4143

44+
pthread_mutex_lock(&mutex); /* malloc is not thread-safe in wasi-libc */
4245
vals[data->iteration] = malloc(sizeof(int));
46+
pthread_mutex_unlock(&mutex);
4347
*vals[data->iteration] = data->iteration;
4448

4549
__atomic_store_n(&data->th_done, 1, __ATOMIC_SEQ_CST);
@@ -53,6 +57,9 @@ main(int argc, char **argv)
5357
int thread_ids[NUM_THREADS];
5458
int *count = calloc(1, sizeof(int));
5559

60+
assert(count != NULL && "Failed to call calloc");
61+
assert(pthread_mutex_init(&mutex, NULL) == 0 && "Failed to init mutex");
62+
5663
for (int i = 0; i < NUM_THREADS; i++) {
5764
assert(start_args_init(&data[i].base)
5865
&& "Stack allocation for thread failed");
@@ -82,5 +89,7 @@ main(int argc, char **argv)
8289
}
8390

8491
free(count);
92+
assert(pthread_mutex_destroy(&mutex) == 0 && "Failed to destroy mutex");
93+
8594
return EXIT_SUCCESS;
8695
}

0 commit comments

Comments
 (0)