xref: /linux/tools/perf/util/cap.c (revision a3a02a52bcfcbcc4a637d4b68bf1bc391c9fad02)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Capability utilities
4  */
5 
6 #include "cap.h"
7 #include "debug.h"
8 #include <errno.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <linux/capability.h>
12 #include <sys/syscall.h>
13 
14 #ifndef SYS_capget
15 #define SYS_capget 90
16 #endif
17 
18 #define MAX_LINUX_CAPABILITY_U32S _LINUX_CAPABILITY_U32S_3
19 
20 bool perf_cap__capable(int cap, bool *used_root)
21 {
22 	struct __user_cap_header_struct header = {
23 		.version = _LINUX_CAPABILITY_VERSION_3,
24 		.pid = getpid(),
25 	};
26 	struct __user_cap_data_struct data[MAX_LINUX_CAPABILITY_U32S];
27 	__u32 cap_val;
28 
29 	*used_root = false;
30 	while (syscall(SYS_capget, &header, &data[0]) == -1) {
31 		/* Retry, first attempt has set the header.version correctly. */
32 		if (errno == EINVAL && header.version != _LINUX_CAPABILITY_VERSION_3 &&
33 		    header.version == _LINUX_CAPABILITY_VERSION_1)
34 			continue;
35 
36 		pr_debug2("capget syscall failed (%s - %d) fall back on root check\n",
37 			  strerror(errno), errno);
38 		*used_root = true;
39 		return geteuid() == 0;
40 	}
41 
42 	/* Extract the relevant capability bit. */
43 	if (cap >= 32) {
44 		if (header.version == _LINUX_CAPABILITY_VERSION_3) {
45 			cap_val = data[1].effective;
46 		} else {
47 			/* Capability beyond 32 is requested but only 32 are supported. */
48 			return false;
49 		}
50 	} else {
51 		cap_val = data[0].effective;
52 	}
53 	return (cap_val & (1 << (cap & 0x1f))) != 0;
54 }
55