From 98403eccb000bd7e8f3f6d6a42f5cb198ace0896 Mon Sep 17 00:00:00 2001 From: Gunnar Beutner Date: Wed, 14 Apr 2021 22:45:21 +0200 Subject: [PATCH] LibPthread: Ensure we're not overflowing the semaphore's value --- Userland/Libraries/LibPthread/semaphore.cpp | 17 +++++++++++++++-- Userland/Libraries/LibPthread/semaphore.h | 3 +++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/Userland/Libraries/LibPthread/semaphore.cpp b/Userland/Libraries/LibPthread/semaphore.cpp index 37361b4471..8b5f0862bd 100644 --- a/Userland/Libraries/LibPthread/semaphore.cpp +++ b/Userland/Libraries/LibPthread/semaphore.cpp @@ -48,8 +48,15 @@ int sem_getvalue(sem_t*, int*) int sem_init(sem_t* sem, int shared, unsigned int value) { - if (shared) - return ENOSYS; + if (shared) { + errno = ENOSYS; + return -1; + } + + if (value > SEM_VALUE_MAX) { + errno = EINVAL; + return -1; + } if (pthread_mutex_init(&sem->mtx, nullptr) != 0) return -1; @@ -70,6 +77,12 @@ sem_t* sem_open(const char*, int, ...) int sem_post(sem_t* sem) { + if (sem->value == SEM_VALUE_MAX) { + pthread_mutex_unlock(&sem->mtx); + errno = EOVERFLOW; + return -1; + } + sem->value++; pthread_cond_signal(&sem->cv); diff --git a/Userland/Libraries/LibPthread/semaphore.h b/Userland/Libraries/LibPthread/semaphore.h index 9371e51215..230c24c73a 100644 --- a/Userland/Libraries/LibPthread/semaphore.h +++ b/Userland/Libraries/LibPthread/semaphore.h @@ -26,6 +26,7 @@ #pragma once +#include #include #include #include @@ -48,4 +49,6 @@ int sem_trywait(sem_t*); int sem_unlink(const char*); int sem_wait(sem_t*); +#define SEM_VALUE_MAX INT_MAX + __END_DECLS