Skip to content

Commit afeac38

Browse files
committed
replace alloca with safe_emalloc in mb_guess_encoding_for_strings
1 parent 96be28c commit afeac38

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

ext/mbstring/mbstring.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3415,14 +3415,15 @@ MBSTRING_API const mbfl_encoding* mb_guess_encoding_for_strings(const unsigned c
34153415
}
34163416

34173417
/* Allocate on stack; when we return, this array is automatically freed */
3418-
struct candidate *array = alloca(elist_size * sizeof(struct candidate));
3418+
struct candidate *array = (struct candidate *) safe_emalloc(elist_size, sizeof(struct candidate), 0);
34193419
elist_size = init_candidate_array(array, elist_size, elist, strings, str_lengths, n, strict, order_significant);
34203420

34213421
while (n--) {
34223422
start_string(array, elist_size, strings[n], str_lengths[n]);
34233423
elist_size = count_demerits(array, elist_size, strict);
34243424
if (elist_size == 0) {
34253425
/* All candidates were eliminated */
3426+
efree(array);
34263427
return NULL;
34273428
}
34283429
}
@@ -3434,7 +3435,10 @@ MBSTRING_API const mbfl_encoding* mb_guess_encoding_for_strings(const unsigned c
34343435
best = i;
34353436
}
34363437
}
3437-
return array[best].enc;
3438+
3439+
const mbfl_encoding *result = array[best].enc;
3440+
efree(array);
3441+
return result;
34383442
}
34393443

34403444
/* When doing 'strict' detection, any string which is invalid in the candidate encoding

ext/mbstring/tests/gh21223.phpt

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
--TEST--
2+
GH-21223 (Stack overflow in mb_guess_encoding called via mb_detect_encoding)
3+
--EXTENSIONS--
4+
mbstring
5+
--FILE--
6+
<?php
7+
$str = "hello";
8+
9+
$list = [];
10+
for ($i = 0; $i < 500000; $i++) {
11+
$list[] = "UTF-8";
12+
}
13+
14+
var_dump(mb_detect_encoding($str, $list, false));
15+
echo "Done";
16+
?>
17+
--EXPECT--
18+
string(5) "UTF-8"
19+
Done

0 commit comments

Comments
 (0)