musl/src/misc/realpath.c
Rich Felker 594c827a22 support kernels with no SYS_open syscall, only SYS_openat
open is handled specially because it is used from so many places, in
so many variants (2 or 3 arguments, setting errno or not, and
cancellable or not). trying to do it as a function would not only
increase bloat, but would also risk subtle breakage.

this is the first step towards supporting "new" archs where linux
lacks "old" syscalls.
2014-05-24 22:54:05 -04:00

46 lines
877 B
C

#include <stdlib.h>
#include <limits.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include "syscall.h"
void __procfdname(char *, unsigned);
char *realpath(const char *restrict filename, char *restrict resolved)
{
int fd;
ssize_t r;
struct stat st1, st2;
char buf[15+3*sizeof(int)];
char tmp[PATH_MAX];
if (!filename) {
errno = EINVAL;
return 0;
}
fd = sys_open(filename, O_PATH|O_NONBLOCK|O_CLOEXEC);
if (fd < 0) return 0;
__procfdname(buf, fd);
r = readlink(buf, tmp, sizeof tmp - 1);
if (r < 0) goto err;
tmp[r] = 0;
fstat(fd, &st1);
r = stat(tmp, &st2);
if (r<0 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) {
if (!r) errno = ELOOP;
goto err;
}
__syscall(SYS_close, fd);
return resolved ? strcpy(resolved, tmp) : strdup(tmp);
err:
__syscall(SYS_close, fd);
return 0;
}