xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/listxattr/listxattr02.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2016 RT-RK Institute for Computer Based Systems
4  * Copyright (c) Linux Test Project, 2016-2024
5  * Author: Dejan Jovicevic <[email protected]>
6  */
7 
8 /*\
9  * [Description]
10  *
11  * Test for listxattr error.
12  *
13  * - ERANGE - the size of the list buffer is too small to hold the result.
14  * - ENOENT - path is an empty string.
15  * - EFAULT - attempted to read from a invalid address.
16  * - ENAMETOOLONG - path is longer than allowed.
17  */
18 
19 #include "config.h"
20 #include <errno.h>
21 #include <sys/types.h>
22 
23 #ifdef HAVE_SYS_XATTR_H
24 # include <sys/xattr.h>
25 #endif
26 
27 #include "tst_test.h"
28 
29 #ifdef HAVE_SYS_XATTR_H
30 
31 #define SECURITY_KEY	"security.ltptest"
32 #define VALUE	"test"
33 #define VALUE_SIZE	(sizeof(VALUE) - 1)
34 #define TESTFILE    "testfile"
35 
36 static char longpathname[PATH_MAX + 2];
37 
38 static struct test_case {
39 	const char *path;
40 	size_t size;
41 	int exp_err;
42 } tc[] = {
43 	{TESTFILE, 1, ERANGE},
44 	{"", 20, ENOENT},
45 	{(char *)-1, 20, EFAULT},
46 	{longpathname, 20, ENAMETOOLONG}
47 };
48 
verify_listxattr(unsigned int n)49 static void verify_listxattr(unsigned int n)
50 {
51 	struct test_case *t = tc + n;
52 	char buf[t->size];
53 
54 	TEST(listxattr(t->path, buf, sizeof(buf)));
55 	if (TST_RET != -1) {
56 		tst_res(TFAIL,
57 			"listxattr() succeeded unexpectedly (returned %ld)",
58 			TST_RET);
59 		return;
60 	}
61 
62 	if (t->exp_err != TST_ERR) {
63 		tst_res(TFAIL | TTERRNO, "listxattr() failed "
64 			 "unexpectedlly, expected %s",
65 			 tst_strerrno(t->exp_err));
66 	} else {
67 		tst_res(TPASS | TTERRNO,
68 			 "listxattr() failed as expected");
69 	}
70 }
71 
setup(void)72 static void setup(void)
73 {
74 	SAFE_TOUCH(TESTFILE, 0644, NULL);
75 
76 	SAFE_SETXATTR(TESTFILE, SECURITY_KEY, VALUE, VALUE_SIZE, XATTR_CREATE);
77 
78 	memset(&longpathname, 'a', sizeof(longpathname) - 1);
79 }
80 
81 static struct tst_test test = {
82 	.needs_tmpdir = 1,
83 	.needs_root = 1,
84 	.test = verify_listxattr,
85 	.tcnt = ARRAY_SIZE(tc),
86 	.setup = setup,
87 };
88 
89 #else /* HAVE_SYS_XATTR_H */
90 	TST_TEST_TCONF("<sys/xattr.h> does not exist.");
91 #endif
92