From 66052f7c4c68ab5dab9292ad04f35b07352c9e74 Mon Sep 17 00:00:00 2001 From: YAMAMOTO Takashi Date: Tue, 16 Jun 2020 17:21:28 +0900 Subject: [PATCH] mkstemp: Only look at the trailing Xs As it's stated in the standards. The original code look at the first Xs. It can end up with an unexpected behavior, if a template contains multiple series of Xs. E.g. /tmp/XXXXXX/XXXXXX --- libs/libc/stdlib/lib_mkstemp.c | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/libs/libc/stdlib/lib_mkstemp.c b/libs/libc/stdlib/lib_mkstemp.c index feb95d8631..9fcc2dfc3c 100644 --- a/libs/libc/stdlib/lib_mkstemp.c +++ b/libs/libc/stdlib/lib_mkstemp.c @@ -198,29 +198,28 @@ int mkstemp(FAR char *path_template) uint8_t base62[MAX_XS]; uint32_t retries; FAR char *xptr; - FAR char *ptr; int xlen; int fd; int i; /* Count the number of X's at the end of the template */ - xptr = strchr(path_template, 'X'); - if (!xptr) + xptr = &path_template[strlen(path_template)]; + for (xlen = 0; xlen < MAX_XS && path_template < xptr && *(xptr - 1) == 'X'; + xlen++, xptr--); + + if (xlen == 0) { /* No Xs? There should always really be 6 */ return open(path_template, O_RDWR | O_CREAT | O_EXCL, 0666); } - /* There is at least one.. count all of them */ - - for (xlen = 0, ptr = xptr; xlen < MAX_XS && *ptr == 'X'; xlen++, ptr++); - /* Ignore any X's after the sixth */ if (xlen > MAX_XS) { + xptr += xlen - MAX_XS; xlen = MAX_XS; }