1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2001
4 */
5
6 /*\
7 * [Description]
8 *
9 * Testcase to check the basic functionality of the getcwd(2) system call.
10 *
11 * 1. getcwd(2) works fine if buf and size are valid.
12 * 2. getcwd(2) works fine if buf points to NULL and size is set to 0.
13 * 3. getcwd(2) works fine if buf points to NULL and size is greater than strlen(path).
14 */
15
16 #include <errno.h>
17 #include <unistd.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22
23 #include "tst_test.h"
24
25 static char exp_buf[PATH_MAX];
26 static char buffer[PATH_MAX];
27
28 static struct t_case {
29 char *buf;
30 size_t size;
31 } tcases[] = {
32 {buffer, sizeof(buffer)},
33 {NULL, 0},
34 {NULL, PATH_MAX}
35 };
36
dir_exists(const char * dirpath)37 static int dir_exists(const char *dirpath)
38 {
39 struct stat sb;
40
41 if (!stat(dirpath, &sb) && S_ISDIR(sb.st_mode))
42 return 1;
43
44 return 0;
45 }
46
verify_getcwd(unsigned int n)47 static void verify_getcwd(unsigned int n)
48 {
49 struct t_case *tc = &tcases[n];
50 char *res = NULL;
51
52 errno = 0;
53 res = getcwd(tc->buf, tc->size);
54 TST_ERR = errno;
55 if (!res) {
56 tst_res(TFAIL | TTERRNO, "getcwd() failed");
57 goto end;
58 }
59
60 if (strcmp(exp_buf, res)) {
61 tst_res(TFAIL, "getcwd() returned unexpected directory: %s, "
62 "expected: %s", res, exp_buf);
63 goto end;
64 }
65
66 tst_res(TPASS, "getcwd() returned expected directory: %s", res);
67
68 end:
69 if (!tc->buf)
70 free(res);
71 }
72
setup(void)73 static void setup(void)
74 {
75 const char *tmpdir = tst_get_tmpdir_root();
76
77 if (!dir_exists(tmpdir))
78 tst_brk(TBROK | TERRNO, "TMPDIR '%s' doesn't exist", tmpdir);
79
80 SAFE_CHDIR(tmpdir);
81
82 if (!realpath(tmpdir, exp_buf))
83 tst_brk(TBROK | TERRNO, "realpath() failed");
84
85 tst_res(TINFO, "Expected path '%s'", exp_buf);
86 }
87
88 static struct tst_test test = {
89 .setup = setup,
90 .tcnt = ARRAY_SIZE(tcases),
91 .test = verify_getcwd
92 };
93