getcwd.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (C) 2000-2006 Erik Andersen <andersen@uclibc.org>
  3. *
  4. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  5. */
  6. /* These functions find the absolute path to the current working directory. */
  7. #include <stdlib.h>
  8. #include <errno.h>
  9. #include <sys/stat.h>
  10. #include <dirent.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <sys/param.h>
  14. #include <sys/syscall.h>
  15. # define __NR___syscall_getcwd __NR_getcwd
  16. static __always_inline
  17. _syscall2(int, __syscall_getcwd, char *, buf, unsigned long, size)
  18. char *getcwd(char *buf, size_t size)
  19. {
  20. int ret;
  21. char *path;
  22. size_t alloc_size = size;
  23. if (size == 0) {
  24. if (buf != NULL) {
  25. __set_errno(EINVAL);
  26. return NULL;
  27. }
  28. alloc_size = MAX (PATH_MAX, getpagesize ());
  29. }
  30. path=buf;
  31. if (buf == NULL) {
  32. path = malloc(alloc_size);
  33. if (path == NULL)
  34. return NULL;
  35. }
  36. ret = __syscall_getcwd(path, alloc_size);
  37. if (ret > 0 && path[0] == '/')
  38. {
  39. if (buf == NULL && size == 0)
  40. buf = realloc(path, ret);
  41. if (buf == NULL)
  42. buf = path;
  43. return buf;
  44. }
  45. if (buf == NULL)
  46. free (path);
  47. return NULL;
  48. }
  49. libc_hidden_def(getcwd)