123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176 |
- #include <config.h>
- #include "careadlinkat.h"
- #include <errno.h>
- #include <limits.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #ifndef SIZE_MAX
- # define SIZE_MAX ((size_t) -1)
- #endif
- #ifndef SSIZE_MAX
- # define SSIZE_MAX ((ssize_t) (SIZE_MAX / 2))
- #endif
- #include "allocator.h"
- ssize_t
- careadlinkatcwd (int fd, char const *filename, char *buffer,
- size_t buffer_size)
- {
-
- if (fd != AT_FDCWD)
- abort ();
- return readlink (filename, buffer, buffer_size);
- }
- char *
- careadlinkat (int fd, char const *filename,
- char *buffer, size_t buffer_size,
- struct allocator const *alloc,
- ssize_t (*preadlinkat) (int, char const *, char *, size_t))
- {
- char *buf;
- size_t buf_size;
- size_t buf_size_max =
- SSIZE_MAX < SIZE_MAX ? (size_t) SSIZE_MAX + 1 : SIZE_MAX;
- char stack_buf[1024];
- if (! alloc)
- alloc = &stdlib_allocator;
- if (! buffer_size)
- {
-
- buffer = stack_buf;
- buffer_size = sizeof stack_buf;
- }
- buf = buffer;
- buf_size = buffer_size;
- do
- {
-
- ssize_t link_length = preadlinkat (fd, filename, buf, buf_size);
- size_t link_size;
- if (link_length < 0)
- {
-
- int readlinkat_errno = errno;
- if (readlinkat_errno != ERANGE)
- {
- if (buf != buffer)
- {
- alloc->free (buf);
- errno = readlinkat_errno;
- }
- return NULL;
- }
- }
- link_size = link_length;
- if (link_size < buf_size)
- {
- buf[link_size++] = '\0';
- if (buf == stack_buf)
- {
- char *b = (char *) alloc->allocate (link_size);
- buf_size = link_size;
- if (! b)
- break;
- memcpy (b, buf, link_size);
- buf = b;
- }
- else if (link_size < buf_size && buf != buffer && alloc->reallocate)
- {
-
- char *b = (char *) alloc->reallocate (buf, link_size);
- if (b)
- buf = b;
- }
- return buf;
- }
- if (buf != buffer)
- alloc->free (buf);
- if (buf_size <= buf_size_max / 2)
- buf_size *= 2;
- else if (buf_size < buf_size_max)
- buf_size = buf_size_max;
- else if (buf_size_max < SIZE_MAX)
- {
- errno = ENAMETOOLONG;
- return NULL;
- }
- else
- break;
- buf = (char *) alloc->allocate (buf_size);
- }
- while (buf);
- if (alloc->die)
- alloc->die (buf_size);
- errno = ENOMEM;
- return NULL;
- }
|