Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [thread-next>] [day] [month] [year] [list]
Message-ID: <AC*ApgATLIDbScbGVCqN54qY.1.1795685934012.Hmail.2601110895@stu.pku.edu.cn>
Date: Thu, 26 Nov 2026 17:38:54 +0800 (GMT+08:00)
From: 吴尚哲 <wushangzhe26@....pku.edu.cn>
To: musl  <musl@...ts.openwall.com>
Subject: Bug in wordexp(): getword() leaks a buffer when getdelim() reaches EOF

Hello,

We found a memory leak in wordexp() in musl 1.2.5. getword() reads one
NUL-terminated word:
    static char *getword(FILE *f)
    {
        char *s = 0;
        return getdelim(&s, (size_t [1]){0}, 0, f) < 0 ? 0 : s;
    }
getdelim() can allocate a buffer and still return -1. With *n == 0 and
an empty read buffer it reaches getdelim.c:35 with i = 0, k = 0,
computes m = i+k+2 = 2, applies m += m/2 because z is NULL, getting 3,
and calls realloc(*s, 3); *s now holds that block. The following
getc_unlocked() returns EOF and, since !i, the call returns -1 at
getdelim.c:65-67.


The negative-return branch at wordexp.c:23 discards s without freeing
it. The buffer was never added to the word vector, so wordfree() cannot
release it either. Every successful wordexp() call ends with one such
failing getword(), because the loop runs until getword() returns 0, so
this happens per call rather than per error. Long-running processes that
call wordexp() repeatedly grow monotonically.


Measured on musl 1.2.5, counting requested sizes through a malloc
wrapper: 200 outstanding blocks totalling 600 bytes after 200 calls to
wordexp(), i.e. 3 bytes per call. A control that calls getdelim()
directly and frees the buffer on the -1 return leaves nothing
outstanding, so the difference is the missing free in getword().
Freeing s before returning NULL on a negative getdelim() result fixes
the leak:
    static char *getword(FILE *f)
    {
        char *s = 0;
        if (getdelim(&s, (size_t [1]){0}, 0, f) < 0) {
            free(s);
            return 0;
        }
        return s;
    }


Checking for EOF before growing the buffer inside getdelim() would also
work, but that changes a shared loop; the caller-side fix stays inside
wordexp().


Thanks,
Shangzhe







Content of type "text/html" skipped

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.