Skip to content

Commit a26e243

Browse files
committed
Avoid invalid read in webgl1.c
Extract another helper function here which avoids the invalid read at address zero. Without this change a call to `emscripten_webgl_make_context_current(0)` would result in the second word of memory being compared to `pthread_self()`.
1 parent a55946d commit a26e243

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

system/lib/gl/webgl1.c

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* University of Illinois/NCSA Open Source License. Both these licenses can be
55
* found in the LICENSE file.
66
*/
7+
#include <assert.h>
78
#include <emscripten/threading.h>
89
#include <emscripten/console.h>
910
#include <string.h>
@@ -27,8 +28,20 @@ static void InitWebGLTls() {
2728
pthread_key_create(&currentThreadOwnsItsWebGLContext, NULL);
2829
}
2930

30-
static pthread_t GetCurrentTargetThread() {
31-
return *(void**)(pthread_getspecific(currentActiveWebGLContext) + 4);
31+
// When OFFSCREEN_FRAMEBUFFER is enabled the EMSCRIPTEN_WEBGL_CONTEXT_HANDLE
32+
// is a pointer to a struct with two fields. See registerContext in
33+
// library_webgl.js
34+
typedef struct WebGLContextHandle {
35+
uint32_t explicit_swap_control;
36+
pthread_t owning_thread;
37+
} WebGLContextHandle;
38+
39+
static inline pthread_t GetOwningThread(EMSCRIPTEN_WEBGL_CONTEXT_HANDLE handle) {
40+
return ((WebGLContextHandle*)handle)->owning_thread;
41+
}
42+
43+
static inline pthread_t GetCurrentTargetThread() {
44+
return GetOwningThread(emscripten_webgl_get_current_context());
3245
}
3346

3447
EMSCRIPTEN_WEBGL_CONTEXT_HANDLE emscripten_webgl_create_context(const char *target, const EmscriptenWebGLContextAttributes *attributes) {
@@ -54,8 +67,7 @@ EMSCRIPTEN_RESULT emscripten_webgl_make_context_current(EMSCRIPTEN_WEBGL_CONTEXT
5467
if (emscripten_webgl_get_current_context() == context)
5568
return EMSCRIPTEN_RESULT_SUCCESS;
5669

57-
void *owningThread = *(void**)(context + 4);
58-
if (owningThread == pthread_self()) {
70+
if (context && GetOwningThread(context) == pthread_self()) {
5971
EMSCRIPTEN_RESULT r = emscripten_webgl_make_context_current_calling_thread(context);
6072
if (r == EMSCRIPTEN_RESULT_SUCCESS) {
6173
pthread_setspecific(currentActiveWebGLContext, (void*)context);

0 commit comments

Comments
 (0)