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 
7 /* These functions find the absolute path to the current working directory.  */
8 
9 #include <stdlib.h>
10 #include <errno.h>
11 #include <sys/stat.h>
12 #include <dirent.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <sys/param.h>
16 #include <sys/syscall.h>
17 
18 
19 # define __NR___syscall_getcwd __NR_getcwd
20 static __always_inline
_syscall2(int,__syscall_getcwd,char *,buf,unsigned long,size)21 _syscall2(int, __syscall_getcwd, char *, buf, unsigned long, size)
22 
23 char *getcwd(char *buf, size_t size)
24 {
25     int ret;
26     char *path;
27     size_t alloc_size = size;
28 
29     if (size == 0) {
30 	if (buf != NULL) {
31 	    __set_errno(EINVAL);
32 	    return NULL;
33 	}
34 	alloc_size = MAX (PATH_MAX, getpagesize ());
35     }
36     path=buf;
37     if (buf == NULL) {
38 	path = malloc(alloc_size);
39 	if (path == NULL)
40 	    return NULL;
41     }
42     ret = __syscall_getcwd(path, alloc_size);
43     if (ret > 0 && path[0] == '/')
44     {
45 	if (buf == NULL && size == 0)
46 	    buf = realloc(path, ret);
47 	if (buf == NULL)
48 	    buf = path;
49 	return buf;
50     }
51     if (buf == NULL)
52 	free (path);
53     return NULL;
54 }
55 libc_hidden_def(getcwd)
56