xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/chmod/chmod01.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2001
4  *  07/2001 Ported by Wayne Boyer
5  */
6 
7 /*\
8  * [Description]
9  *
10  * Verify that chmod(2) succeeds when used to change the mode permissions
11  * of a file or directory.
12  */
13 
14 #include "tst_test.h"
15 
16 #define MODE	S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
17 #define TESTFILE	"testfile"
18 #define TESTDIR		"testdir_1"
19 
20 static int modes[] = {0, 07, 070, 0700, 0777, 02777, 04777, 06777};
21 
22 static char *test_dir;
23 static char *test_file;
24 
25 static struct variant {
26 	char **name;
27 	unsigned int mode_mask;
28 	char *desc;
29 } variants[] = {
30 	{&test_file, S_IFREG, "verify permissions of file"},
31 	{&test_dir, S_IFDIR, "verify permissions of directory"},
32 };
33 
verify_chmod(unsigned int n)34 static void verify_chmod(unsigned int n)
35 {
36 	struct stat stat_buf;
37 	int mode = modes[n];
38 	struct variant *tc = &variants[tst_variant];
39 
40 	TST_EXP_PASS(chmod(*tc->name, mode), "chmod(%s, %04o)",
41 	             *tc->name, mode);
42 
43 	if (!TST_PASS)
44 		return;
45 
46 	SAFE_STAT(*tc->name, &stat_buf);
47 	stat_buf.st_mode &= ~tc->mode_mask;
48 
49 	if (stat_buf.st_mode == (unsigned int)mode) {
50 		tst_res(TPASS, "stat(%s) mode=%04o",
51 				*tc->name, stat_buf.st_mode);
52 	} else {
53 		tst_res(TFAIL, "stat(%s) mode=%04o",
54 				*tc->name, stat_buf.st_mode);
55 	}
56 }
57 
setup(void)58 static void setup(void)
59 {
60 	tst_res(TINFO, "Testing variant: %s", variants[tst_variant].desc);
61 
62 	if (tst_variant)
63 		SAFE_MKDIR(*variants[tst_variant].name, MODE);
64 	else
65 		SAFE_TOUCH(*variants[tst_variant].name, MODE, NULL);
66 }
67 
68 static struct tst_test test = {
69 	.setup = setup,
70 	.test_variants = ARRAY_SIZE(variants),
71 	.tcnt = ARRAY_SIZE(modes),
72 	.test = verify_chmod,
73 	.needs_tmpdir = 1,
74 	.bufs = (struct tst_buffers []) {
75 		{&test_file, .str = TESTFILE},
76 		{&test_dir, .str = TESTDIR},
77 		{}
78 	}
79 };
80