2011-02-12 00:22:29 -05:00
|
|
|
#include <stdlib.h>
|
2011-04-17 17:32:36 -04:00
|
|
|
#include <limits.h>
|
|
|
|
#include <sys/stat.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <errno.h>
|
|
|
|
#include <unistd.h>
|
2013-08-31 15:50:23 -04:00
|
|
|
#include <string.h>
|
2013-08-31 16:01:01 -04:00
|
|
|
#include "syscall.h"
|
2011-02-12 00:22:29 -05:00
|
|
|
|
2013-08-02 12:59:45 -04:00
|
|
|
void __procfdname(char *, unsigned);
|
|
|
|
|
2012-09-06 22:44:55 -04:00
|
|
|
char *realpath(const char *restrict filename, char *restrict resolved)
|
2011-02-12 00:22:29 -05:00
|
|
|
{
|
2011-04-17 17:32:36 -04:00
|
|
|
int fd;
|
|
|
|
ssize_t r;
|
|
|
|
struct stat st1, st2;
|
|
|
|
char buf[15+3*sizeof(int)];
|
2013-08-31 15:50:23 -04:00
|
|
|
char tmp[PATH_MAX];
|
2011-04-17 17:32:36 -04:00
|
|
|
|
|
|
|
if (!filename) {
|
|
|
|
errno = EINVAL;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2014-05-24 22:54:05 -04:00
|
|
|
fd = sys_open(filename, O_PATH|O_NONBLOCK|O_CLOEXEC);
|
2011-06-18 07:41:14 -04:00
|
|
|
if (fd < 0) return 0;
|
2013-08-02 12:59:45 -04:00
|
|
|
__procfdname(buf, fd);
|
2011-06-18 07:41:14 -04:00
|
|
|
|
2013-08-31 15:50:23 -04:00
|
|
|
r = readlink(buf, tmp, sizeof tmp - 1);
|
2011-04-17 17:32:36 -04:00
|
|
|
if (r < 0) goto err;
|
2013-08-31 15:50:23 -04:00
|
|
|
tmp[r] = 0;
|
2011-04-17 17:32:36 -04:00
|
|
|
|
|
|
|
fstat(fd, &st1);
|
2013-08-31 15:50:23 -04:00
|
|
|
r = stat(tmp, &st2);
|
2011-04-17 17:32:36 -04:00
|
|
|
if (r<0 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) {
|
|
|
|
if (!r) errno = ELOOP;
|
|
|
|
goto err;
|
|
|
|
}
|
|
|
|
|
2013-08-31 16:01:01 -04:00
|
|
|
__syscall(SYS_close, fd);
|
2013-08-31 15:50:23 -04:00
|
|
|
return resolved ? strcpy(resolved, tmp) : strdup(tmp);
|
2011-04-17 17:32:36 -04:00
|
|
|
err:
|
2013-08-31 16:01:01 -04:00
|
|
|
__syscall(SYS_close, fd);
|
2011-02-12 00:22:29 -05:00
|
|
|
return 0;
|
|
|
|
}
|