From d2dfb3d37f2f880fe4bd2a8efbf30ca8ca0b1959 Mon Sep 17 00:00:00 2001 From: Aleksei Bavshin Date: Thu, 12 Jun 2025 10:36:30 -0700 Subject: [PATCH] Core: invalidated shared memory addresses after unmapping. As we unmap the unused shared zones before destroying the cycle pool, it was possible to access already unmapped address from a cleanup handler. The change gives such handlers a way to determine that the memory is unavailable and any processing should be skipped. --- src/os/unix/ngx_shmem.c | 13 +++++++++++-- src/os/win32/ngx_shmem.c | 2 ++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/os/unix/ngx_shmem.c b/src/os/unix/ngx_shmem.c index 3ec7cbf1f..e5dd6ad88 100644 --- a/src/os/unix/ngx_shmem.c +++ b/src/os/unix/ngx_shmem.c @@ -19,6 +19,7 @@ ngx_shm_alloc(ngx_shm_t *shm) MAP_ANON|MAP_SHARED, -1, 0); if (shm->addr == MAP_FAILED) { + shm->addr = NULL; ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno, "mmap(MAP_ANON|MAP_SHARED, %uz) failed", shm->size); return NGX_ERROR; @@ -35,6 +36,8 @@ ngx_shm_free(ngx_shm_t *shm) ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno, "munmap(%p, %uz) failed", shm->addr, shm->size); } + + shm->addr = NULL; } #elif (NGX_HAVE_MAP_DEVZERO) @@ -56,6 +59,7 @@ ngx_shm_alloc(ngx_shm_t *shm) MAP_SHARED, fd, 0); if (shm->addr == MAP_FAILED) { + shm->addr = NULL; ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno, "mmap(/dev/zero, MAP_SHARED, %uz) failed", shm->size); } @@ -65,7 +69,7 @@ ngx_shm_alloc(ngx_shm_t *shm) "close(\"/dev/zero\") failed"); } - return (shm->addr == MAP_FAILED) ? NGX_ERROR : NGX_OK; + return (shm->addr == NULL) ? NGX_ERROR : NGX_OK; } @@ -76,6 +80,8 @@ ngx_shm_free(ngx_shm_t *shm) ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno, "munmap(%p, %uz) failed", shm->addr, shm->size); } + + shm->addr = NULL; } #elif (NGX_HAVE_SYSVSHM) @@ -102,6 +108,7 @@ ngx_shm_alloc(ngx_shm_t *shm) shm->addr = shmat(id, NULL, 0); if (shm->addr == (void *) -1) { + shm->addr = NULL; ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno, "shmat() failed"); } @@ -110,7 +117,7 @@ ngx_shm_alloc(ngx_shm_t *shm) "shmctl(IPC_RMID) failed"); } - return (shm->addr == (void *) -1) ? NGX_ERROR : NGX_OK; + return (shm->addr == NULL) ? NGX_ERROR : NGX_OK; } @@ -121,6 +128,8 @@ ngx_shm_free(ngx_shm_t *shm) ngx_log_error(NGX_LOG_ALERT, shm->log, ngx_errno, "shmdt(%p) failed", shm->addr); } + + shm->addr = NULL; } #endif diff --git a/src/os/win32/ngx_shmem.c b/src/os/win32/ngx_shmem.c index c3ed699f7..df1166ee6 100644 --- a/src/os/win32/ngx_shmem.c +++ b/src/os/win32/ngx_shmem.c @@ -158,4 +158,6 @@ ngx_shm_free(ngx_shm_t *shm) "CloseHandle() of file mapping \"%V\" failed", &shm->name); } + + shm->addr = NULL; }