Skip to content

Commit d5ff87e

Browse files
committed
random: fix undefined behaviour
1 parent cd64077 commit d5ff87e

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

ext/random/random.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,14 +85,18 @@ static zend_object_handlers random_randomizer_object_handlers;
8585
static inline uint32_t rand_range32(const php_random_algo *algo, php_random_status *status, uint32_t umax)
8686
{
8787
uint32_t result, limit, r;
88-
size_t total_size = 0;
88+
size_t total_size = 0, shift_size = 0;
8989
uint32_t count = 0;
9090

9191
result = 0;
9292
total_size = 0;
9393
do {
9494
r = algo->generate(status);
95-
result = (result << (8 * status->last_generated_size)) | r;
95+
shift_size = (8 * status->last_generated_size);
96+
if ((8 * sizeof(uint32_t)) < shift_size) {
97+
shift_size = 0;
98+
}
99+
result = (result << shift_size) | r;
96100
total_size += status->last_generated_size;
97101
if (status->last_unsafe) {
98102
return 0;
@@ -127,7 +131,11 @@ static inline uint32_t rand_range32(const php_random_algo *algo, php_random_stat
127131
total_size = 0;
128132
do {
129133
r = algo->generate(status);
130-
result = (result << (8 * status->last_generated_size)) | r;
134+
shift_size = (8 * status->last_generated_size);
135+
if ((8 * sizeof(uint32_t)) < shift_size) {
136+
shift_size = 0;
137+
}
138+
result = (result << shift_size) | r;
131139
total_size += status->last_generated_size;
132140
if (status->last_unsafe) {
133141
return 0;

0 commit comments

Comments
 (0)