tools: test: iconv: fix open_2 to not segfault

Record error condition when iconv_open() fails rather than leaving a
bogus iconv_t that iconv_close() can later choke on; this is one failure
mode.

If we opened MAX_LIMIT files with success, we need to rewind one so that
we don't iconv_close() one past the end of cd; this is the second
failure mode.

Sponsored by:	Klara, Inc.
This commit is contained in:
Kyle Evans 2022-01-11 17:41:10 -06:00
parent 7d72ff9057
commit 814bd1ed43

View file

@ -27,8 +27,8 @@
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <sys/param.h>
#include <sys/endian.h>
#include <sys/types.h>
#include <err.h>
#include <errno.h>
@ -66,18 +66,22 @@ static int
open_2(void)
{
iconv_t cd[MAX_LIMIT];
int i, ret;
size_t i;
int ret;
errno = 0;
ret = 1;
for (i = 0; i < MAX_LIMIT; i++) {
cd[i] = iconv_open("ASCII", "UTF8");
if (cd[i] == (iconv_t)-1)
if (cd[i] == (iconv_t)-1) {
if (errno == ENFILE || errno == EMFILE)
ret = 0;
cd[i] = NULL;
break;
}
}
ret = (cd[i] == (iconv_t)-1) && ((errno == ENFILE) ||
(errno == EMFILE)) ? 0 : 1;
for (; i > 0; i--)
for (i = MIN(i, nitems(cd) - 1); i > 0; i--)
iconv_close(cd[i]);
return (ret);
}