xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/getcwd/getcwd03.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
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)
10  * system call on a symbolic link.
11  *
12  * [Algorithm]
13  *
14  * 1. create a directory, and create a symbolic link to it at the
15  *    same directory level.
16  * 2. get the working directory of a directory, and its pathname.
17  * 3. get the working directory of a symbolic link, and its pathname,
18  *    and its readlink info.
19  * 4. compare the working directories and link information.
20  */
21 
22 #define _GNU_SOURCE 1
23 #include <errno.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <stdlib.h>
30 #include "tst_test.h"
31 
32 static char dir[BUFSIZ], dir_link[BUFSIZ];
33 
verify_getcwd(void)34 static void verify_getcwd(void)
35 {
36 	char link[BUFSIZ];
37 	char *res1 = NULL;
38 	char *res2 = NULL;
39 
40 	SAFE_CHDIR(dir);
41 
42 	res1 = getcwd(NULL, 0);
43 	if (!res1) {
44 		tst_res(TFAIL | TERRNO, "getcwd() failed to "
45 			"get working directory of a directory");
46 		goto end;
47 	}
48 
49 	SAFE_CHDIR("..");
50 	SAFE_CHDIR(dir_link);
51 
52 	res2 = getcwd(NULL, 0);
53 	if (!res2) {
54 		tst_res(TFAIL | TERRNO, "getcwd() failed to get "
55 			"working directory of a symbolic link");
56 		goto end;
57 	}
58 
59 	if (strcmp(res1, res2)) {
60 		tst_res(TFAIL,
61 			"getcwd() got mismatched working directories (%s, %s)",
62 			res1, res2);
63 		goto end;
64 	}
65 
66 	SAFE_CHDIR("..");
67 	SAFE_READLINK(dir_link, link, sizeof(link));
68 
69 	if (strcmp(link, SAFE_BASENAME(res1))) {
70 		tst_res(TFAIL,
71 			"link information didn't match the working directory");
72 		goto end;
73 	}
74 
75 	tst_res(TPASS, "getcwd() succeeded on a symbolic link");
76 
77 end:
78 	free(res1);
79 	free(res2);
80 }
81 
setup(void)82 static void setup(void)
83 {
84 	sprintf(dir, "getcwd1.%d", getpid());
85 	sprintf(dir_link, "getcwd2.%d", getpid());
86 	SAFE_MKDIR(dir, 0755);
87 	SAFE_SYMLINK(dir, dir_link);
88 }
89 
90 static struct tst_test test = {
91 	.needs_tmpdir = 1,
92 	.setup = setup,
93 	.test_all = verify_getcwd
94 };
95