Skip to content

Commit

Permalink
Fix incorrect check in fpm_shm_free() (#13797)
Browse files Browse the repository at this point in the history
`if (fpm_shm_size - size > 0)` will be rewritten by the compiler as this: `if (fpm_shm_size != size)`, which is undesirable. The reason this happens is that both variables are size_t, so subtracting them cannot be negative. The only way it can be not > 0, is if they're equal because the result will then be 0. This means that the else branch won't work properly. E.g. if `fpm_shm_size == 50` and `size == 51`, then `fpm_shm_size` will wraparound instead of becoming zero.

To showcase that the compiler actually does this, take a look at this
isolated case: https://godbolt.org/z/azobdWcrY. Here we can see the
usage of the compare instruction + cmove, so the "then" branch
is only done if the variables are equal.
  • Loading branch information
nielsdos committed Mar 24, 2024
1 parent 6f11cc4 commit dd3aa18
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion sapi/fpm/fpm/fpm_shm.c
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ int fpm_shm_free(void *mem, size_t size) /* {{{ */
return 0;
}

if (fpm_shm_size - size > 0) {
if (fpm_shm_size > size) {
fpm_shm_size -= size;
} else {
fpm_shm_size = 0;
Expand Down

0 comments on commit dd3aa18

Please sign in to comment.