realpath.c\misc\src - musl - musl - an implementation of the standard library for Linux-based systems

index : musl
musl - an implementation of the standard library for Linux-based systems
summary refs log tree commit diff
path: root/src/misc/realpath.c
blob: 183351462519b99912265da7a87a11489dd8f1b9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
char *realpath(const char *restrict filename, char *restrict resolved)
{
	int fd;
	ssize_t r;
	struct stat st1, st2;
	char buf[15+3*sizeof(int)];
	int alloc = 0;
	if (!filename) {
		errno = EINVAL;
		return 0;
	}
	fd = open(filename, O_RDONLY|O_NONBLOCK|O_CLOEXEC);
	if (fd < 0) return 0;
	snprintf(buf, sizeof buf, "/proc/self/fd/%d", fd);
	if (!resolved) {
		alloc = 1;
		resolved = malloc(PATH_MAX);
		if (!resolved) return 0;
	}
	r = readlink(buf, resolved, PATH_MAX-1);
	if (r < 0) goto err;
	resolved[r] = 0;
	fstat(fd, &st1);
	r = stat(resolved, &st2);
	if (r<0 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) {
		if (!r) errno = ELOOP;
		goto err;
	}
	close(fd);
	return resolved;
err:
	if (alloc) free(resolved);
	close(fd);
	return 0;
}
generated by cgit v1.2.1 (git 2.18.0) at 2025年09月09日 18:33:36 +0000

AltStyle によって変換されたページ (->オリジナル) /