Skip to content

Commit

Permalink
Enable file locking in musl stdio
Browse files Browse the repository at this point in the history
This is a slightly modified version of
d5d5f69

The change to __lockfile.c means we always compile in the locking code
but atomics will get lowered away in single threaded builds and the
wait/wake functions are no-ops in this mode too, so it should not effect
code size in release builds.

Because __lockfile.c is not compiled into a multi-thread-aware library
(its not part of an MTLibrary) it was never actually being built with
`__EMSCRIPTEN_PTHREADS__`.

Fixes: #13194
  • Loading branch information
sbc100 committed Sep 17, 2021
1 parent 558b9f6 commit f53df1a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
4 changes: 0 additions & 4 deletions system/lib/libc/musl/src/stdio/__lockfile.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,16 @@

int __lockfile(FILE *f)
{
#if defined(__EMSCRIPTEN_PTHREADS__)
int owner, tid = __pthread_self()->tid;
if (f->lock == tid)
return 0;
while ((owner = a_cas(&f->lock, 0, tid)))
__wait(&f->lock, &f->waiters, owner, 1);
#endif
return 1;
}

void __unlockfile(FILE *f)
{
#if defined(__EMSCRIPTEN_PTHREADS__)
a_store(&f->lock, 0);

/* The following read is technically invalid under situations
Expand All @@ -28,5 +25,4 @@ void __unlockfile(FILE *f)
* malloc changes, this assumption needs revisiting. */

if (f->waiters) __wake(&f->lock, 1, 1);
#endif
}
21 changes: 21 additions & 0 deletions system/lib/pthread/pthread_create.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

#define _GNU_SOURCE
#include "pthread_impl.h"
#include "stdio_impl.h"
#include "assert.h"
#include <pthread.h>
#include <stdbool.h>
Expand Down Expand Up @@ -53,6 +54,15 @@ void __do_cleanup_pop(struct __ptcb *cb) {
__pthread_self()->cancelbuf = cb->__next;
}

static FILE *volatile dummy_file = 0;
weak_alias(dummy_file, __stdin_used);
weak_alias(dummy_file, __stdout_used);
weak_alias(dummy_file, __stderr_used);

static void init_file_lock(FILE *f) {
if (f && f->lock<0) f->lock = 0;
}

int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict attrp, void *(*entry)(void *), void *restrict arg) {
// Note on LSAN: lsan intercepts/wraps calls to pthread_create so any
// allocation we we do here should be considered leaks.
Expand All @@ -61,6 +71,17 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att
return EINVAL;
}

pthread_t self = __pthread_self();
if (!libc.threaded) {
for (FILE *f=*__ofl_lock(); f; f=f->next)
init_file_lock(f);
__ofl_unlock();
init_file_lock(__stdin_used);
init_file_lock(__stdout_used);
init_file_lock(__stderr_used);
libc.threaded = 1;
}

// Allocate thread block (pthread_t structure).
struct pthread *new = malloc(sizeof(struct pthread));
// zero-initialize thread structure.
Expand Down

0 comments on commit f53df1a

Please sign in to comment.