Skip to content

Commit

Permalink
libc/realpath: allocate link buffer of pseudofs to save stack
Browse files Browse the repository at this point in the history
The link buffer of pseudofs will occupy too much of stack, allocate from
the heap to save the stack usage.

Signed-off-by: chao an <[email protected]>
  • Loading branch information
anchao authored and xiaoxiang781216 committed Nov 7, 2023
1 parent 4d65d99 commit d410a6e
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions libs/libc/stdlib/lib_realpath.c
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@
FAR char *realpath(FAR const char *path, FAR char *resolved)
{
#ifdef CONFIG_PSEUDOFS_SOFTLINKS
char wbuf[2][PATH_MAX];
FAR char *wbuf[2] =
{
};

int nlnk = 0;
int idx = 0;
ssize_t n;
Expand Down Expand Up @@ -117,6 +120,14 @@ FAR char *realpath(FAR const char *path, FAR char *resolved)
}

*p = '\0';

#ifdef CONFIG_PSEUDOFS_SOFTLINKS
if (wbuf[0] != NULL)
{
lib_free(wbuf[0]);
}
#endif

return resolved;
}

Expand Down Expand Up @@ -186,7 +197,19 @@ FAR char *realpath(FAR const char *path, FAR char *resolved)
goto out;
}

n = readlink(resolved, wbuf[idx], sizeof(wbuf[0]) - 1);
if (wbuf[0] == NULL)
{
wbuf[0] = lib_calloc(2, PATH_MAX);
if (wbuf[0] == NULL)
{
set_errno(ENOMEM);
goto out;
}

wbuf[1] = wbuf[0] + PATH_MAX;
}

n = readlink(resolved, wbuf[idx], PATH_MAX - 1);
if (n <= 0)
{
if (n == 0)
Expand All @@ -199,7 +222,7 @@ FAR char *realpath(FAR const char *path, FAR char *resolved)

/* Append unresolved path to link target and switch to it. */

if (n + (len = strlen(q)) + 1 > sizeof(wbuf[0]))
if (n + (len = strlen(q)) + 1 > PATH_MAX)
{
set_errno(ENAMETOOLONG);
goto out;
Expand Down Expand Up @@ -234,5 +257,12 @@ FAR char *realpath(FAR const char *path, FAR char *resolved)

out:
lib_free(fres);
#ifdef CONFIG_PSEUDOFS_SOFTLINKS
if (wbuf[0] != NULL)
{
lib_free(wbuf[0]);
}
#endif

return NULL;
}

0 comments on commit d410a6e

Please sign in to comment.