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