- path_max = pathconf(name, _PC_PATH_MAX);
- if (path_max <= 0 || path_max >= 4096)
- path_max = 4096;
-#endif
- rpath = dss_malloc(path_max);
- rpath_limit = rpath + path_max;
-
- if (name[0] != '/') {
- if (!getcwd(rpath, path_max)) {
- ret = -ERRNO_TO_DSS_ERROR(errno);
- goto error;
- }
- dest = memchr(rpath, '\0', path_max);
- } else {
- rpath[0] = '/';
- dest = rpath + 1;
- }
-
- for (start = end = name; *start; start = end) {
- struct stat st;
- int n;
-
- /* Skip sequence of multiple path-separators. */
- while (*start == '/')
- ++start;
-
- /* Find end of path component. */
- for (end = start; *end && *end != '/'; ++end)
- /* Nothing. */ ;
-
- if (end - start == 0)
- break;
- else if (end - start == 1 && start[0] == '.')
- /* nothing */ ;
- else if (end - start == 2 && start[0] == '.' && start[1] == '.') {
- /* Back up to previous component, ignore if at root already. */
- if (dest > rpath + 1)
- while ((--dest)[-1] != '/') ;
- } else {
- size_t new_size;
-
- if (dest[-1] != '/')
- *dest++ = '/';
-
- if (dest + (end - start) >= rpath_limit) {
- ptrdiff_t dest_offset = dest - rpath;
-
- new_size = rpath_limit - rpath;
- if (end - start + 1 > path_max)
- new_size += end - start + 1;
- else
- new_size += path_max;
- rpath = dss_realloc(rpath, new_size);
- rpath_limit = rpath + new_size;
- dest = rpath + dest_offset;
- }
-
- memcpy(dest, start, end - start);
- dest += end - start;
- *dest = '\0';
-
- if (stat(rpath, &st) < 0) {
- ret = -ERRNO_TO_DSS_ERROR(errno);
- goto error;
- }
-
- if (S_ISLNK(st.st_mode)) {
- char *buf = alloca(path_max);
- size_t len;
-
- if (++num_links > MAXSYMLINKS) {
- ret = -ERRNO_TO_DSS_ERROR(ELOOP);
- goto error;
- }
-
- n = readlink(rpath, buf, path_max - 1);
- if (n < 0) {
- ret = -ERRNO_TO_DSS_ERROR(errno);
- goto error;
- }
- buf[n] = '\0';
-
- if (!extra_buf)
- extra_buf = alloca(path_max);
-
- len = strlen(end);
- if ((long int) (n + len) >= path_max) {
- ret = -ERRNO_TO_DSS_ERROR(ENAMETOOLONG);
- goto error;
- }
-
- /* Careful here, end may be a pointer into extra_buf... */
- memmove(&extra_buf[n], end, len + 1);
- name = end = memcpy(extra_buf, buf, n);
-
- if (buf[0] == '/') /* It's an absolute symlink */
- dest = rpath + 1;
- else /* Back up to previous component, ignore if at root already: */
- if (dest > rpath + 1)
- while ((--dest)[-1] != '/')
- ; /* nothing */
- } else if (!S_ISDIR(st.st_mode) && *end != '\0') {
- ret = -ERRNO_TO_DSS_ERROR(ENOTDIR);
- goto error;
- }
- }
- }
- if (dest > rpath + 1 && dest[-1] == '/')
- --dest;
- *dest = '\0';
- *resolved_path = rpath;
- return 1;
-error:
- free(rpath);
- *resolved_path = NULL;
- return ret;