xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/stat/stat03.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Copyright (c) International Business Machines  Corp., 2001
3  *	07/2001 John George
4  *		-Ported
5  * Copyright (c) Linux Test Project, 2002-2022
6  */
7 
8 /*\
9  * [Description]
10  *
11  * check stat() with various error conditions that should produce
12  * EACCES, EFAULT, ENAMETOOLONG,  ENOENT, ENOTDIR, ELOOP
13  */
14 
15 #include <pwd.h>
16 #include "tst_test.h"
17 
18 #define TST_EACCES_DIR   "tst_eaccesdir"
19 #define TST_EACCES_FILE  "tst_eaccesdir/tst"
20 #define TST_ENOENT       "tst_enoent/tst"
21 #define TST_ENOTDIR_DIR  "tst_enotdir/tst"
22 #define TST_ENOTDIR_FILE "tst_enotdir"
23 
24 #define MODE_RW	        0666
25 #define DIR_MODE        0755
26 
27 static struct passwd *ltpuser;
28 
29 static char long_dir[PATH_MAX + 2] = {[0 ... PATH_MAX + 1] = 'a'};
30 static char loop_dir[PATH_MAX] = ".";
31 
32 static struct tcase{
33 	char *pathname;
34 	int exp_errno;
35 } TC[] = {
36 	{TST_EACCES_FILE, EACCES},
37 	{NULL, EFAULT},
38 	{long_dir, ENAMETOOLONG},
39 	{TST_ENOENT, ENOENT},
40 	{TST_ENOTDIR_DIR, ENOTDIR},
41 	{loop_dir, ELOOP}
42 };
43 
verify_stat(unsigned int n)44 static void verify_stat(unsigned int n)
45 {
46 	struct tcase *tc = TC + n;
47 	struct stat stat_buf;
48 
49 	TST_EXP_FAIL(stat(tc->pathname, &stat_buf), tc->exp_errno);
50 }
51 
setup(void)52 static void setup(void)
53 {
54 	unsigned int i;
55 
56 	ltpuser = SAFE_GETPWNAM("nobody");
57 	SAFE_SETUID(ltpuser->pw_uid);
58 
59 	SAFE_MKDIR(TST_EACCES_DIR, DIR_MODE);
60 	SAFE_TOUCH(TST_EACCES_FILE, DIR_MODE, NULL);
61 	SAFE_CHMOD(TST_EACCES_DIR, MODE_RW);
62 
63 	for (i = 0; i < ARRAY_SIZE(TC); i++) {
64 		if (TC[i].exp_errno == EFAULT)
65 			TC[i].pathname = tst_get_bad_addr(NULL);
66 	}
67 
68 	SAFE_TOUCH(TST_ENOTDIR_FILE, DIR_MODE, NULL);
69 
70 	SAFE_MKDIR("test_eloop", DIR_MODE);
71 	SAFE_SYMLINK("../test_eloop", "test_eloop/test_eloop");
72 	for (i = 0; i < 43; i++)
73 		strcat(loop_dir, "/test_eloop");
74 }
75 
76 static struct tst_test test = {
77 	.tcnt = ARRAY_SIZE(TC),
78 	.needs_tmpdir = 1,
79 	.needs_root = 1,
80 	.setup = setup,
81 	.test = verify_stat,
82 };
83