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