Skip to content

Commit 9604e4d

Browse files
committed
Fix GH-17399: iconv memory leak with large line-length
Move the buf allocation in _php_iconv_mime_encode() before the iconv_open() calls. When max_line_len is excessively large (e.g. PHP_INT_MAX), safe_emalloc triggers an OOM bailout that skips cleanup, leaking the iconv handles allocated via system malloc. By allocating buf first, a bailout happens before any iconv handles exist. Closes GH-17399
1 parent b97dd33 commit 9604e4d

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

ext/iconv/iconv.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -942,6 +942,8 @@ static php_iconv_err_t _php_iconv_mime_encode(smart_str *pretval, const char *fn
942942
goto out;
943943
}
944944

945+
buf = safe_emalloc(1, max_line_len, 5);
946+
945947
cd_pl = iconv_open(ICONV_ASCII_ENCODING, enc);
946948
if (cd_pl == (iconv_t)(-1)) {
947949
if (errno == EINVAL) {
@@ -962,8 +964,6 @@ static php_iconv_err_t _php_iconv_mime_encode(smart_str *pretval, const char *fn
962964
goto out;
963965
}
964966

965-
buf = safe_emalloc(1, max_line_len, 5);
966-
967967
char_cnt = max_line_len;
968968

969969
_php_iconv_appendl(pretval, fname, fname_nbytes, cd_pl);

ext/iconv/tests/gh17399.phpt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
--TEST--
2+
GH-17399 (iconv memory leak with large line-length in iconv_mime_encode)
3+
--EXTENSIONS--
4+
iconv
5+
--FILE--
6+
<?php
7+
$options = array(
8+
'line-length' => PHP_INT_MAX,
9+
);
10+
iconv_mime_encode('Subject', 'test', $options);
11+
?>
12+
--EXPECTF--
13+
Fatal error: Allowed memory size of %d bytes exhausted %s in %s on line %d

0 commit comments

Comments
 (0)