This source file includes following definitions.
- areadlinkat_with_size
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 #include <config.h>
23
24 #include "areadlink.h"
25
26 #include <errno.h>
27 #include <limits.h>
28 #include <stdint.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32
33 #if HAVE_READLINKAT
34
35 # ifndef SSIZE_MAX
36 # define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
37 # endif
38
39
40
41
42 # ifndef SYMLINK_MAX
43 # define SYMLINK_MAX 1024
44 # endif
45
46 # define MAXSIZE (SIZE_MAX < SSIZE_MAX ? SIZE_MAX : SSIZE_MAX)
47
48
49
50
51
52
53
54
55
56
57 char *
58 areadlinkat_with_size (int fd, char const *file, size_t size)
59 {
60
61
62
63 size_t symlink_max = SYMLINK_MAX;
64 size_t INITIAL_LIMIT_BOUND = 8 * 1024;
65 size_t initial_limit = (symlink_max < INITIAL_LIMIT_BOUND
66 ? symlink_max + 1
67 : INITIAL_LIMIT_BOUND);
68
69 enum { stackbuf_size = 128 };
70
71
72 size_t buf_size = (size == 0 ? stackbuf_size
73 : size < initial_limit ? size + 1 : initial_limit);
74
75 while (1)
76 {
77 ssize_t r;
78 size_t link_length;
79 char stackbuf[stackbuf_size];
80 char *buf = stackbuf;
81 char *buffer = NULL;
82
83 if (! (size == 0 && buf_size == stackbuf_size))
84 {
85 buf = buffer = malloc (buf_size);
86 if (!buffer)
87
88
89 return NULL;
90 }
91
92 r = readlinkat (fd, file, buf, buf_size);
93 link_length = r;
94
95 if (r < 0)
96 {
97 free (buffer);
98 return NULL;
99 }
100
101 if (link_length < buf_size)
102 {
103 buf[link_length] = 0;
104 if (!buffer)
105 {
106 buffer = malloc (link_length + 1);
107 if (buffer)
108 return memcpy (buffer, buf, link_length + 1);
109 }
110 else if (link_length + 1 < buf_size)
111 {
112
113 char *shrinked_buffer = realloc (buffer, link_length + 1);
114 if (shrinked_buffer != NULL)
115 buffer = shrinked_buffer;
116 }
117 return buffer;
118 }
119
120 free (buffer);
121 if (buf_size <= MAXSIZE / 2)
122 buf_size *= 2;
123 else if (buf_size < MAXSIZE)
124 buf_size = MAXSIZE;
125 else
126 {
127 errno = ENOMEM;
128 return NULL;
129 }
130 }
131 }
132
133 #else
134
135
136
137
138
139
140 # define AT_FUNC_NAME areadlinkat_with_size
141 # define AT_FUNC_F1 areadlink_with_size
142 # define AT_FUNC_POST_FILE_PARAM_DECLS , size_t size
143 # define AT_FUNC_POST_FILE_ARGS , size
144 # define AT_FUNC_RESULT char *
145 # define AT_FUNC_FAIL NULL
146 # include "at-func.c"
147 # undef AT_FUNC_NAME
148 # undef AT_FUNC_F1
149 # undef AT_FUNC_POST_FILE_PARAM_DECLS
150 # undef AT_FUNC_POST_FILE_ARGS
151 # undef AT_FUNC_RESULT
152 # undef AT_FUNC_FAIL
153
154 #endif