xref: /openbmc/linux/tools/lib/bpf/usdt.c (revision 060f35a317ef09101b128f399dce7ed13d019461)
12e4913e0SAndrii Nakryiko // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
22e4913e0SAndrii Nakryiko /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
32e4913e0SAndrii Nakryiko #include <ctype.h>
42e4913e0SAndrii Nakryiko #include <stdio.h>
52e4913e0SAndrii Nakryiko #include <stdlib.h>
62e4913e0SAndrii Nakryiko #include <string.h>
72e4913e0SAndrii Nakryiko #include <libelf.h>
82e4913e0SAndrii Nakryiko #include <gelf.h>
92e4913e0SAndrii Nakryiko #include <unistd.h>
102e4913e0SAndrii Nakryiko #include <linux/ptrace.h>
112e4913e0SAndrii Nakryiko #include <linux/kernel.h>
122e4913e0SAndrii Nakryiko 
1358ca8b05SPu Lehui /* s8 will be marked as poison while it's a reg of riscv */
1458ca8b05SPu Lehui #if defined(__riscv)
1558ca8b05SPu Lehui #define rv_s8 s8
1658ca8b05SPu Lehui #endif
1758ca8b05SPu Lehui 
182e4913e0SAndrii Nakryiko #include "bpf.h"
192e4913e0SAndrii Nakryiko #include "libbpf.h"
202e4913e0SAndrii Nakryiko #include "libbpf_common.h"
212e4913e0SAndrii Nakryiko #include "libbpf_internal.h"
222e4913e0SAndrii Nakryiko #include "hashmap.h"
232e4913e0SAndrii Nakryiko 
242e4913e0SAndrii Nakryiko /* libbpf's USDT support consists of BPF-side state/code and user-space
252e4913e0SAndrii Nakryiko  * state/code working together in concert. BPF-side parts are defined in
262e4913e0SAndrii Nakryiko  * usdt.bpf.h header library. User-space state is encapsulated by struct
272e4913e0SAndrii Nakryiko  * usdt_manager and all the supporting code centered around usdt_manager.
282e4913e0SAndrii Nakryiko  *
292e4913e0SAndrii Nakryiko  * usdt.bpf.h defines two BPF maps that usdt_manager expects: USDT spec map
302e4913e0SAndrii Nakryiko  * and IP-to-spec-ID map, which is auxiliary map necessary for kernels that
312e4913e0SAndrii Nakryiko  * don't support BPF cookie (see below). These two maps are implicitly
322e4913e0SAndrii Nakryiko  * embedded into user's end BPF object file when user's code included
332e4913e0SAndrii Nakryiko  * usdt.bpf.h. This means that libbpf doesn't do anything special to create
342e4913e0SAndrii Nakryiko  * these USDT support maps. They are created by normal libbpf logic of
352e4913e0SAndrii Nakryiko  * instantiating BPF maps when opening and loading BPF object.
362e4913e0SAndrii Nakryiko  *
372e4913e0SAndrii Nakryiko  * As such, libbpf is basically unaware of the need to do anything
382e4913e0SAndrii Nakryiko  * USDT-related until the very first call to bpf_program__attach_usdt(), which
392e4913e0SAndrii Nakryiko  * can be called by user explicitly or happen automatically during skeleton
402e4913e0SAndrii Nakryiko  * attach (or, equivalently, through generic bpf_program__attach() call). At
412e4913e0SAndrii Nakryiko  * this point, libbpf will instantiate and initialize struct usdt_manager and
422e4913e0SAndrii Nakryiko  * store it in bpf_object. USDT manager is per-BPF object construct, as each
432e4913e0SAndrii Nakryiko  * independent BPF object might or might not have USDT programs, and thus all
442e4913e0SAndrii Nakryiko  * the expected USDT-related state. There is no coordination between two
452e4913e0SAndrii Nakryiko  * bpf_object in parts of USDT attachment, they are oblivious of each other's
462e4913e0SAndrii Nakryiko  * existence and libbpf is just oblivious, dealing with bpf_object-specific
472e4913e0SAndrii Nakryiko  * USDT state.
482e4913e0SAndrii Nakryiko  *
492e4913e0SAndrii Nakryiko  * Quick crash course on USDTs.
502e4913e0SAndrii Nakryiko  *
512e4913e0SAndrii Nakryiko  * From user-space application's point of view, USDT is essentially just
522e4913e0SAndrii Nakryiko  * a slightly special function call that normally has zero overhead, unless it
532e4913e0SAndrii Nakryiko  * is being traced by some external entity (e.g, BPF-based tool). Here's how
542e4913e0SAndrii Nakryiko  * a typical application can trigger USDT probe:
552e4913e0SAndrii Nakryiko  *
562e4913e0SAndrii Nakryiko  * #include <sys/sdt.h>  // provided by systemtap-sdt-devel package
572e4913e0SAndrii Nakryiko  * // folly also provide similar functionality in folly/tracing/StaticTracepoint.h
582e4913e0SAndrii Nakryiko  *
592e4913e0SAndrii Nakryiko  * STAP_PROBE3(my_usdt_provider, my_usdt_probe_name, 123, x, &y);
602e4913e0SAndrii Nakryiko  *
612e4913e0SAndrii Nakryiko  * USDT is identified by it's <provider-name>:<probe-name> pair of names. Each
622e4913e0SAndrii Nakryiko  * individual USDT has a fixed number of arguments (3 in the above example)
632e4913e0SAndrii Nakryiko  * and specifies values of each argument as if it was a function call.
642e4913e0SAndrii Nakryiko  *
652e4913e0SAndrii Nakryiko  * USDT call is actually not a function call, but is instead replaced by
662e4913e0SAndrii Nakryiko  * a single NOP instruction (thus zero overhead, effectively). But in addition
672e4913e0SAndrii Nakryiko  * to that, those USDT macros generate special SHT_NOTE ELF records in
682e4913e0SAndrii Nakryiko  * .note.stapsdt ELF section. Here's an example USDT definition as emitted by
692e4913e0SAndrii Nakryiko  * `readelf -n <binary>`:
702e4913e0SAndrii Nakryiko  *
712e4913e0SAndrii Nakryiko  *   stapsdt              0x00000089       NT_STAPSDT (SystemTap probe descriptors)
722e4913e0SAndrii Nakryiko  *   Provider: test
732e4913e0SAndrii Nakryiko  *   Name: usdt12
742e4913e0SAndrii Nakryiko  *   Location: 0x0000000000549df3, Base: 0x00000000008effa4, Semaphore: 0x0000000000a4606e
752e4913e0SAndrii Nakryiko  *   Arguments: -4@-1204(%rbp) -4@%edi -8@-1216(%rbp) -8@%r8 -4@$5 -8@%r9 8@%rdx 8@%r10 -4@$-9 -2@%cx -2@%ax -1@%sil
762e4913e0SAndrii Nakryiko  *
772e4913e0SAndrii Nakryiko  * In this case we have USDT test:usdt12 with 12 arguments.
782e4913e0SAndrii Nakryiko  *
792e4913e0SAndrii Nakryiko  * Location and base are offsets used to calculate absolute IP address of that
802e4913e0SAndrii Nakryiko  * NOP instruction that kernel can replace with an interrupt instruction to
812e4913e0SAndrii Nakryiko  * trigger instrumentation code (BPF program for all that we care about).
822e4913e0SAndrii Nakryiko  *
832e4913e0SAndrii Nakryiko  * Semaphore above is and optional feature. It records an address of a 2-byte
842e4913e0SAndrii Nakryiko  * refcount variable (normally in '.probes' ELF section) used for signaling if
852e4913e0SAndrii Nakryiko  * there is anything that is attached to USDT. This is useful for user
862e4913e0SAndrii Nakryiko  * applications if, for example, they need to prepare some arguments that are
872e4913e0SAndrii Nakryiko  * passed only to USDTs and preparation is expensive. By checking if USDT is
882e4913e0SAndrii Nakryiko  * "activated", an application can avoid paying those costs unnecessarily.
892e4913e0SAndrii Nakryiko  * Recent enough kernel has built-in support for automatically managing this
902e4913e0SAndrii Nakryiko  * refcount, which libbpf expects and relies on. If USDT is defined without
912e4913e0SAndrii Nakryiko  * associated semaphore, this value will be zero. See selftests for semaphore
922e4913e0SAndrii Nakryiko  * examples.
932e4913e0SAndrii Nakryiko  *
942e4913e0SAndrii Nakryiko  * Arguments is the most interesting part. This USDT specification string is
952e4913e0SAndrii Nakryiko  * providing information about all the USDT arguments and their locations. The
962e4913e0SAndrii Nakryiko  * part before @ sign defined byte size of the argument (1, 2, 4, or 8) and
972e4913e0SAndrii Nakryiko  * whether the argument is signed or unsigned (negative size means signed).
982e4913e0SAndrii Nakryiko  * The part after @ sign is assembly-like definition of argument location
992e4913e0SAndrii Nakryiko  * (see [0] for more details). Technically, assembler can provide some pretty
1002e4913e0SAndrii Nakryiko  * advanced definitions, but libbpf is currently supporting three most common
1012e4913e0SAndrii Nakryiko  * cases:
1022e4913e0SAndrii Nakryiko  *   1) immediate constant, see 5th and 9th args above (-4@$5 and -4@-9);
1032e4913e0SAndrii Nakryiko  *   2) register value, e.g., 8@%rdx, which means "unsigned 8-byte integer
1042e4913e0SAndrii Nakryiko  *      whose value is in register %rdx";
1052e4913e0SAndrii Nakryiko  *   3) memory dereference addressed by register, e.g., -4@-1204(%rbp), which
1062e4913e0SAndrii Nakryiko  *      specifies signed 32-bit integer stored at offset -1204 bytes from
1072e4913e0SAndrii Nakryiko  *      memory address stored in %rbp.
1082e4913e0SAndrii Nakryiko  *
1092e4913e0SAndrii Nakryiko  *   [0] https://sourceware.org/systemtap/wiki/UserSpaceProbeImplementation
1102e4913e0SAndrii Nakryiko  *
1112e4913e0SAndrii Nakryiko  * During attachment, libbpf parses all the relevant USDT specifications and
1122e4913e0SAndrii Nakryiko  * prepares `struct usdt_spec` (USDT spec), which is then provided to BPF-side
1132e4913e0SAndrii Nakryiko  * code through spec map. This allows BPF applications to quickly fetch the
1142e4913e0SAndrii Nakryiko  * actual value at runtime using a simple BPF-side code.
1152e4913e0SAndrii Nakryiko  *
116e1b6df59SIlya Leoshkevich  * With basics out of the way, let's go over less immediately obvious aspects
1172e4913e0SAndrii Nakryiko  * of supporting USDTs.
1182e4913e0SAndrii Nakryiko  *
1192e4913e0SAndrii Nakryiko  * First, there is no special USDT BPF program type. It is actually just
1202e4913e0SAndrii Nakryiko  * a uprobe BPF program (which for kernel, at least currently, is just a kprobe
1212e4913e0SAndrii Nakryiko  * program, so BPF_PROG_TYPE_KPROBE program type). With the only difference
1222e4913e0SAndrii Nakryiko  * that uprobe is usually attached at the function entry, while USDT will
1232e4913e0SAndrii Nakryiko  * normally will be somewhere inside the function. But it should always be
1242e4913e0SAndrii Nakryiko  * pointing to NOP instruction, which makes such uprobes the fastest uprobe
1252e4913e0SAndrii Nakryiko  * kind.
1262e4913e0SAndrii Nakryiko  *
1272e4913e0SAndrii Nakryiko  * Second, it's important to realize that such STAP_PROBEn(provider, name, ...)
1282e4913e0SAndrii Nakryiko  * macro invocations can end up being inlined many-many times, depending on
1292e4913e0SAndrii Nakryiko  * specifics of each individual user application. So single conceptual USDT
1302e4913e0SAndrii Nakryiko  * (identified by provider:name pair of identifiers) is, generally speaking,
1312e4913e0SAndrii Nakryiko  * multiple uprobe locations (USDT call sites) in different places in user
1322e4913e0SAndrii Nakryiko  * application. Further, again due to inlining, each USDT call site might end
1332e4913e0SAndrii Nakryiko  * up having the same argument #N be located in a different place. In one call
1342e4913e0SAndrii Nakryiko  * site it could be a constant, in another will end up in a register, and in
1352e4913e0SAndrii Nakryiko  * yet another could be some other register or even somewhere on the stack.
1362e4913e0SAndrii Nakryiko  *
1372e4913e0SAndrii Nakryiko  * As such, "attaching to USDT" means (in general case) attaching the same
1382e4913e0SAndrii Nakryiko  * uprobe BPF program to multiple target locations in user application, each
1392e4913e0SAndrii Nakryiko  * potentially having a completely different USDT spec associated with it.
1402e4913e0SAndrii Nakryiko  * To wire all this up together libbpf allocates a unique integer spec ID for
1412e4913e0SAndrii Nakryiko  * each unique USDT spec. Spec IDs are allocated as sequential small integers
1422e4913e0SAndrii Nakryiko  * so that they can be used as keys in array BPF map (for performance reasons).
1432e4913e0SAndrii Nakryiko  * Spec ID allocation and accounting is big part of what usdt_manager is
1442e4913e0SAndrii Nakryiko  * about. This state has to be maintained per-BPF object and coordinate
1452e4913e0SAndrii Nakryiko  * between different USDT attachments within the same BPF object.
1462e4913e0SAndrii Nakryiko  *
1472e4913e0SAndrii Nakryiko  * Spec ID is the key in spec BPF map, value is the actual USDT spec layed out
1482e4913e0SAndrii Nakryiko  * as struct usdt_spec. Each invocation of BPF program at runtime needs to
1492e4913e0SAndrii Nakryiko  * know its associated spec ID. It gets it either through BPF cookie, which
1502e4913e0SAndrii Nakryiko  * libbpf sets to spec ID during attach time, or, if kernel is too old to
1512e4913e0SAndrii Nakryiko  * support BPF cookie, through IP-to-spec-ID map that libbpf maintains in such
1522e4913e0SAndrii Nakryiko  * case. The latter means that some modes of operation can't be supported
1532e4913e0SAndrii Nakryiko  * without BPF cookie. Such mode is attaching to shared library "generically",
1542e4913e0SAndrii Nakryiko  * without specifying target process. In such case, it's impossible to
1552e4913e0SAndrii Nakryiko  * calculate absolute IP addresses for IP-to-spec-ID map, and thus such mode
1562e4913e0SAndrii Nakryiko  * is not supported without BPF cookie support.
1572e4913e0SAndrii Nakryiko  *
1582e4913e0SAndrii Nakryiko  * Note that libbpf is using BPF cookie functionality for its own internal
1592e4913e0SAndrii Nakryiko  * needs, so user itself can't rely on BPF cookie feature. To that end, libbpf
1602e4913e0SAndrii Nakryiko  * provides conceptually equivalent USDT cookie support. It's still u64
1612e4913e0SAndrii Nakryiko  * user-provided value that can be associated with USDT attachment. Note that
1622e4913e0SAndrii Nakryiko  * this will be the same value for all USDT call sites within the same single
1632e4913e0SAndrii Nakryiko  * *logical* USDT attachment. This makes sense because to user attaching to
1642e4913e0SAndrii Nakryiko  * USDT is a single BPF program triggered for singular USDT probe. The fact
1652e4913e0SAndrii Nakryiko  * that this is done at multiple actual locations is a mostly hidden
1662e4913e0SAndrii Nakryiko  * implementation details. This USDT cookie value can be fetched with
1672e4913e0SAndrii Nakryiko  * bpf_usdt_cookie(ctx) API provided by usdt.bpf.h
1682e4913e0SAndrii Nakryiko  *
1692e4913e0SAndrii Nakryiko  * Lastly, while single USDT can have tons of USDT call sites, it doesn't
1702e4913e0SAndrii Nakryiko  * necessarily have that many different USDT specs. It very well might be
1712e4913e0SAndrii Nakryiko  * that 1000 USDT call sites only need 5 different USDT specs, because all the
1722e4913e0SAndrii Nakryiko  * arguments are typically contained in a small set of registers or stack
1732e4913e0SAndrii Nakryiko  * locations. As such, it's wasteful to allocate as many USDT spec IDs as
1742e4913e0SAndrii Nakryiko  * there are USDT call sites. So libbpf tries to be frugal and performs
1752e4913e0SAndrii Nakryiko  * on-the-fly deduplication during a single USDT attachment to only allocate
1762e4913e0SAndrii Nakryiko  * the minimal required amount of unique USDT specs (and thus spec IDs). This
1772e4913e0SAndrii Nakryiko  * is trivially achieved by using USDT spec string (Arguments string from USDT
1782e4913e0SAndrii Nakryiko  * note) as a lookup key in a hashmap. USDT spec string uniquely defines
1792e4913e0SAndrii Nakryiko  * everything about how to fetch USDT arguments, so two USDT call sites
1802e4913e0SAndrii Nakryiko  * sharing USDT spec string can safely share the same USDT spec and spec ID.
1812e4913e0SAndrii Nakryiko  * Note, this spec string deduplication is happening only during the same USDT
1822e4913e0SAndrii Nakryiko  * attachment, so each USDT spec shares the same USDT cookie value. This is
1832e4913e0SAndrii Nakryiko  * not generally true for other USDT attachments within the same BPF object,
1842e4913e0SAndrii Nakryiko  * as even if USDT spec string is the same, USDT cookie value can be
1852e4913e0SAndrii Nakryiko  * different. It was deemed excessive to try to deduplicate across independent
1862e4913e0SAndrii Nakryiko  * USDT attachments by taking into account USDT spec string *and* USDT cookie
1872e4913e0SAndrii Nakryiko  * value, which would complicated spec ID accounting significantly for little
1882e4913e0SAndrii Nakryiko  * gain.
1892e4913e0SAndrii Nakryiko  */
1902e4913e0SAndrii Nakryiko 
19174cc6311SAndrii Nakryiko #define USDT_BASE_SEC ".stapsdt.base"
19274cc6311SAndrii Nakryiko #define USDT_SEMA_SEC ".probes"
19374cc6311SAndrii Nakryiko #define USDT_NOTE_SEC  ".note.stapsdt"
19474cc6311SAndrii Nakryiko #define USDT_NOTE_TYPE 3
19574cc6311SAndrii Nakryiko #define USDT_NOTE_NAME "stapsdt"
19674cc6311SAndrii Nakryiko 
197e1b6df59SIlya Leoshkevich /* should match exactly enum __bpf_usdt_arg_type from usdt.bpf.h */
19874cc6311SAndrii Nakryiko enum usdt_arg_type {
19974cc6311SAndrii Nakryiko 	USDT_ARG_CONST,
20074cc6311SAndrii Nakryiko 	USDT_ARG_REG,
20174cc6311SAndrii Nakryiko 	USDT_ARG_REG_DEREF,
20274cc6311SAndrii Nakryiko };
20374cc6311SAndrii Nakryiko 
204e1b6df59SIlya Leoshkevich /* should match exactly struct __bpf_usdt_arg_spec from usdt.bpf.h */
20574cc6311SAndrii Nakryiko struct usdt_arg_spec {
20674cc6311SAndrii Nakryiko 	__u64 val_off;
20774cc6311SAndrii Nakryiko 	enum usdt_arg_type arg_type;
20874cc6311SAndrii Nakryiko 	short reg_off;
20974cc6311SAndrii Nakryiko 	bool arg_signed;
21074cc6311SAndrii Nakryiko 	char arg_bitshift;
21174cc6311SAndrii Nakryiko };
21274cc6311SAndrii Nakryiko 
21374cc6311SAndrii Nakryiko /* should match BPF_USDT_MAX_ARG_CNT in usdt.bpf.h */
21474cc6311SAndrii Nakryiko #define USDT_MAX_ARG_CNT 12
21574cc6311SAndrii Nakryiko 
21674cc6311SAndrii Nakryiko /* should match struct __bpf_usdt_spec from usdt.bpf.h */
21774cc6311SAndrii Nakryiko struct usdt_spec {
21874cc6311SAndrii Nakryiko 	struct usdt_arg_spec args[USDT_MAX_ARG_CNT];
21974cc6311SAndrii Nakryiko 	__u64 usdt_cookie;
22074cc6311SAndrii Nakryiko 	short arg_cnt;
22174cc6311SAndrii Nakryiko };
22274cc6311SAndrii Nakryiko 
22374cc6311SAndrii Nakryiko struct usdt_note {
22474cc6311SAndrii Nakryiko 	const char *provider;
22574cc6311SAndrii Nakryiko 	const char *name;
22674cc6311SAndrii Nakryiko 	/* USDT args specification string, e.g.:
22774cc6311SAndrii Nakryiko 	 * "-4@%esi -4@-24(%rbp) -4@%ecx 2@%ax 8@%rdx"
22874cc6311SAndrii Nakryiko 	 */
22974cc6311SAndrii Nakryiko 	const char *args;
23074cc6311SAndrii Nakryiko 	long loc_addr;
23174cc6311SAndrii Nakryiko 	long base_addr;
23274cc6311SAndrii Nakryiko 	long sema_addr;
23374cc6311SAndrii Nakryiko };
23474cc6311SAndrii Nakryiko 
2352e4913e0SAndrii Nakryiko struct usdt_target {
2362e4913e0SAndrii Nakryiko 	long abs_ip;
2372e4913e0SAndrii Nakryiko 	long rel_ip;
2382e4913e0SAndrii Nakryiko 	long sema_off;
23974cc6311SAndrii Nakryiko 	struct usdt_spec spec;
24074cc6311SAndrii Nakryiko 	const char *spec_str;
2412e4913e0SAndrii Nakryiko };
2422e4913e0SAndrii Nakryiko 
2432e4913e0SAndrii Nakryiko struct usdt_manager {
2442e4913e0SAndrii Nakryiko 	struct bpf_map *specs_map;
2452e4913e0SAndrii Nakryiko 	struct bpf_map *ip_to_spec_id_map;
2462e4913e0SAndrii Nakryiko 
247999783c8SAndrii Nakryiko 	int *free_spec_ids;
248999783c8SAndrii Nakryiko 	size_t free_spec_cnt;
249999783c8SAndrii Nakryiko 	size_t next_free_spec_id;
250999783c8SAndrii Nakryiko 
2512e4913e0SAndrii Nakryiko 	bool has_bpf_cookie;
2522e4913e0SAndrii Nakryiko 	bool has_sema_refcnt;
2535902da6dSJiri Olsa 	bool has_uprobe_multi;
2542e4913e0SAndrii Nakryiko };
2552e4913e0SAndrii Nakryiko 
usdt_manager_new(struct bpf_object * obj)2562e4913e0SAndrii Nakryiko struct usdt_manager *usdt_manager_new(struct bpf_object *obj)
2572e4913e0SAndrii Nakryiko {
2582e4913e0SAndrii Nakryiko 	static const char *ref_ctr_sysfs_path = "/sys/bus/event_source/devices/uprobe/format/ref_ctr_offset";
2592e4913e0SAndrii Nakryiko 	struct usdt_manager *man;
2602e4913e0SAndrii Nakryiko 	struct bpf_map *specs_map, *ip_to_spec_id_map;
2612e4913e0SAndrii Nakryiko 
2622e4913e0SAndrii Nakryiko 	specs_map = bpf_object__find_map_by_name(obj, "__bpf_usdt_specs");
2632e4913e0SAndrii Nakryiko 	ip_to_spec_id_map = bpf_object__find_map_by_name(obj, "__bpf_usdt_ip_to_spec_id");
2642e4913e0SAndrii Nakryiko 	if (!specs_map || !ip_to_spec_id_map) {
2652e4913e0SAndrii Nakryiko 		pr_warn("usdt: failed to find USDT support BPF maps, did you forget to include bpf/usdt.bpf.h?\n");
2662e4913e0SAndrii Nakryiko 		return ERR_PTR(-ESRCH);
2672e4913e0SAndrii Nakryiko 	}
2682e4913e0SAndrii Nakryiko 
2692e4913e0SAndrii Nakryiko 	man = calloc(1, sizeof(*man));
2702e4913e0SAndrii Nakryiko 	if (!man)
2712e4913e0SAndrii Nakryiko 		return ERR_PTR(-ENOMEM);
2722e4913e0SAndrii Nakryiko 
2732e4913e0SAndrii Nakryiko 	man->specs_map = specs_map;
2742e4913e0SAndrii Nakryiko 	man->ip_to_spec_id_map = ip_to_spec_id_map;
2752e4913e0SAndrii Nakryiko 
2762e4913e0SAndrii Nakryiko 	/* Detect if BPF cookie is supported for kprobes.
2772e4913e0SAndrii Nakryiko 	 * We don't need IP-to-ID mapping if we can use BPF cookies.
2782e4913e0SAndrii Nakryiko 	 * Added in: 7adfc6c9b315 ("bpf: Add bpf_get_attach_cookie() BPF helper to access bpf_cookie value")
2792e4913e0SAndrii Nakryiko 	 */
2802e4913e0SAndrii Nakryiko 	man->has_bpf_cookie = kernel_supports(obj, FEAT_BPF_COOKIE);
2812e4913e0SAndrii Nakryiko 
2822e4913e0SAndrii Nakryiko 	/* Detect kernel support for automatic refcounting of USDT semaphore.
2832e4913e0SAndrii Nakryiko 	 * If this is not supported, USDTs with semaphores will not be supported.
2842e4913e0SAndrii Nakryiko 	 * Added in: a6ca88b241d5 ("trace_uprobe: support reference counter in fd-based uprobe")
2852e4913e0SAndrii Nakryiko 	 */
2866a4ab886SJon Doron 	man->has_sema_refcnt = faccessat(AT_FDCWD, ref_ctr_sysfs_path, F_OK, AT_EACCESS) == 0;
2872e4913e0SAndrii Nakryiko 
2885902da6dSJiri Olsa 	/*
2895902da6dSJiri Olsa 	 * Detect kernel support for uprobe multi link to be used for attaching
2905902da6dSJiri Olsa 	 * usdt probes.
2915902da6dSJiri Olsa 	 */
2925902da6dSJiri Olsa 	man->has_uprobe_multi = kernel_supports(obj, FEAT_UPROBE_MULTI_LINK);
2932e4913e0SAndrii Nakryiko 	return man;
2942e4913e0SAndrii Nakryiko }
2952e4913e0SAndrii Nakryiko 
usdt_manager_free(struct usdt_manager * man)2962e4913e0SAndrii Nakryiko void usdt_manager_free(struct usdt_manager *man)
2972e4913e0SAndrii Nakryiko {
2982e4913e0SAndrii Nakryiko 	if (IS_ERR_OR_NULL(man))
2992e4913e0SAndrii Nakryiko 		return;
3002e4913e0SAndrii Nakryiko 
301999783c8SAndrii Nakryiko 	free(man->free_spec_ids);
3022e4913e0SAndrii Nakryiko 	free(man);
3032e4913e0SAndrii Nakryiko }
3042e4913e0SAndrii Nakryiko 
sanity_check_usdt_elf(Elf * elf,const char * path)3052e4913e0SAndrii Nakryiko static int sanity_check_usdt_elf(Elf *elf, const char *path)
3062e4913e0SAndrii Nakryiko {
3072e4913e0SAndrii Nakryiko 	GElf_Ehdr ehdr;
3082e4913e0SAndrii Nakryiko 	int endianness;
3092e4913e0SAndrii Nakryiko 
3102e4913e0SAndrii Nakryiko 	if (elf_kind(elf) != ELF_K_ELF) {
3112e4913e0SAndrii Nakryiko 		pr_warn("usdt: unrecognized ELF kind %d for '%s'\n", elf_kind(elf), path);
3122e4913e0SAndrii Nakryiko 		return -EBADF;
3132e4913e0SAndrii Nakryiko 	}
3142e4913e0SAndrii Nakryiko 
3152e4913e0SAndrii Nakryiko 	switch (gelf_getclass(elf)) {
3162e4913e0SAndrii Nakryiko 	case ELFCLASS64:
3172e4913e0SAndrii Nakryiko 		if (sizeof(void *) != 8) {
3182e4913e0SAndrii Nakryiko 			pr_warn("usdt: attaching to 64-bit ELF binary '%s' is not supported\n", path);
3192e4913e0SAndrii Nakryiko 			return -EBADF;
3202e4913e0SAndrii Nakryiko 		}
3212e4913e0SAndrii Nakryiko 		break;
3222e4913e0SAndrii Nakryiko 	case ELFCLASS32:
3232e4913e0SAndrii Nakryiko 		if (sizeof(void *) != 4) {
3242e4913e0SAndrii Nakryiko 			pr_warn("usdt: attaching to 32-bit ELF binary '%s' is not supported\n", path);
3252e4913e0SAndrii Nakryiko 			return -EBADF;
3262e4913e0SAndrii Nakryiko 		}
3272e4913e0SAndrii Nakryiko 		break;
3282e4913e0SAndrii Nakryiko 	default:
3292e4913e0SAndrii Nakryiko 		pr_warn("usdt: unsupported ELF class for '%s'\n", path);
3302e4913e0SAndrii Nakryiko 		return -EBADF;
3312e4913e0SAndrii Nakryiko 	}
3322e4913e0SAndrii Nakryiko 
3332e4913e0SAndrii Nakryiko 	if (!gelf_getehdr(elf, &ehdr))
3342e4913e0SAndrii Nakryiko 		return -EINVAL;
3352e4913e0SAndrii Nakryiko 
3362e4913e0SAndrii Nakryiko 	if (ehdr.e_type != ET_EXEC && ehdr.e_type != ET_DYN) {
3372e4913e0SAndrii Nakryiko 		pr_warn("usdt: unsupported type of ELF binary '%s' (%d), only ET_EXEC and ET_DYN are supported\n",
3382e4913e0SAndrii Nakryiko 			path, ehdr.e_type);
3392e4913e0SAndrii Nakryiko 		return -EBADF;
3402e4913e0SAndrii Nakryiko 	}
3412e4913e0SAndrii Nakryiko 
342e1b6df59SIlya Leoshkevich #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
3432e4913e0SAndrii Nakryiko 	endianness = ELFDATA2LSB;
344e1b6df59SIlya Leoshkevich #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
3452e4913e0SAndrii Nakryiko 	endianness = ELFDATA2MSB;
3462e4913e0SAndrii Nakryiko #else
3472e4913e0SAndrii Nakryiko # error "Unrecognized __BYTE_ORDER__"
3482e4913e0SAndrii Nakryiko #endif
3492e4913e0SAndrii Nakryiko 	if (endianness != ehdr.e_ident[EI_DATA]) {
3502e4913e0SAndrii Nakryiko 		pr_warn("usdt: ELF endianness mismatch for '%s'\n", path);
3512e4913e0SAndrii Nakryiko 		return -EBADF;
3522e4913e0SAndrii Nakryiko 	}
3532e4913e0SAndrii Nakryiko 
3542e4913e0SAndrii Nakryiko 	return 0;
3552e4913e0SAndrii Nakryiko }
3562e4913e0SAndrii Nakryiko 
find_elf_sec_by_name(Elf * elf,const char * sec_name,GElf_Shdr * shdr,Elf_Scn ** scn)35774cc6311SAndrii Nakryiko static int find_elf_sec_by_name(Elf *elf, const char *sec_name, GElf_Shdr *shdr, Elf_Scn **scn)
35874cc6311SAndrii Nakryiko {
35974cc6311SAndrii Nakryiko 	Elf_Scn *sec = NULL;
36074cc6311SAndrii Nakryiko 	size_t shstrndx;
36174cc6311SAndrii Nakryiko 
36274cc6311SAndrii Nakryiko 	if (elf_getshdrstrndx(elf, &shstrndx))
36374cc6311SAndrii Nakryiko 		return -EINVAL;
36474cc6311SAndrii Nakryiko 
36574cc6311SAndrii Nakryiko 	/* check if ELF is corrupted and avoid calling elf_strptr if yes */
36674cc6311SAndrii Nakryiko 	if (!elf_rawdata(elf_getscn(elf, shstrndx), NULL))
36774cc6311SAndrii Nakryiko 		return -EINVAL;
36874cc6311SAndrii Nakryiko 
36974cc6311SAndrii Nakryiko 	while ((sec = elf_nextscn(elf, sec)) != NULL) {
37074cc6311SAndrii Nakryiko 		char *name;
37174cc6311SAndrii Nakryiko 
37274cc6311SAndrii Nakryiko 		if (!gelf_getshdr(sec, shdr))
37374cc6311SAndrii Nakryiko 			return -EINVAL;
37474cc6311SAndrii Nakryiko 
37574cc6311SAndrii Nakryiko 		name = elf_strptr(elf, shstrndx, shdr->sh_name);
37674cc6311SAndrii Nakryiko 		if (name && strcmp(sec_name, name) == 0) {
37774cc6311SAndrii Nakryiko 			*scn = sec;
37874cc6311SAndrii Nakryiko 			return 0;
37974cc6311SAndrii Nakryiko 		}
38074cc6311SAndrii Nakryiko 	}
38174cc6311SAndrii Nakryiko 
38274cc6311SAndrii Nakryiko 	return -ENOENT;
38374cc6311SAndrii Nakryiko }
38474cc6311SAndrii Nakryiko 
38574cc6311SAndrii Nakryiko struct elf_seg {
38674cc6311SAndrii Nakryiko 	long start;
38774cc6311SAndrii Nakryiko 	long end;
38874cc6311SAndrii Nakryiko 	long offset;
38974cc6311SAndrii Nakryiko 	bool is_exec;
39074cc6311SAndrii Nakryiko };
39174cc6311SAndrii Nakryiko 
cmp_elf_segs(const void * _a,const void * _b)39274cc6311SAndrii Nakryiko static int cmp_elf_segs(const void *_a, const void *_b)
39374cc6311SAndrii Nakryiko {
39474cc6311SAndrii Nakryiko 	const struct elf_seg *a = _a;
39574cc6311SAndrii Nakryiko 	const struct elf_seg *b = _b;
39674cc6311SAndrii Nakryiko 
39774cc6311SAndrii Nakryiko 	return a->start < b->start ? -1 : 1;
39874cc6311SAndrii Nakryiko }
39974cc6311SAndrii Nakryiko 
parse_elf_segs(Elf * elf,const char * path,struct elf_seg ** segs,size_t * seg_cnt)40074cc6311SAndrii Nakryiko static int parse_elf_segs(Elf *elf, const char *path, struct elf_seg **segs, size_t *seg_cnt)
40174cc6311SAndrii Nakryiko {
40274cc6311SAndrii Nakryiko 	GElf_Phdr phdr;
40374cc6311SAndrii Nakryiko 	size_t n;
40474cc6311SAndrii Nakryiko 	int i, err;
40574cc6311SAndrii Nakryiko 	struct elf_seg *seg;
40674cc6311SAndrii Nakryiko 	void *tmp;
40774cc6311SAndrii Nakryiko 
40874cc6311SAndrii Nakryiko 	*seg_cnt = 0;
40974cc6311SAndrii Nakryiko 
41074cc6311SAndrii Nakryiko 	if (elf_getphdrnum(elf, &n)) {
41174cc6311SAndrii Nakryiko 		err = -errno;
41274cc6311SAndrii Nakryiko 		return err;
41374cc6311SAndrii Nakryiko 	}
41474cc6311SAndrii Nakryiko 
41574cc6311SAndrii Nakryiko 	for (i = 0; i < n; i++) {
41674cc6311SAndrii Nakryiko 		if (!gelf_getphdr(elf, i, &phdr)) {
41774cc6311SAndrii Nakryiko 			err = -errno;
41874cc6311SAndrii Nakryiko 			return err;
41974cc6311SAndrii Nakryiko 		}
42074cc6311SAndrii Nakryiko 
42174cc6311SAndrii Nakryiko 		pr_debug("usdt: discovered PHDR #%d in '%s': vaddr 0x%lx memsz 0x%lx offset 0x%lx type 0x%lx flags 0x%lx\n",
42274cc6311SAndrii Nakryiko 			 i, path, (long)phdr.p_vaddr, (long)phdr.p_memsz, (long)phdr.p_offset,
42374cc6311SAndrii Nakryiko 			 (long)phdr.p_type, (long)phdr.p_flags);
42474cc6311SAndrii Nakryiko 		if (phdr.p_type != PT_LOAD)
42574cc6311SAndrii Nakryiko 			continue;
42674cc6311SAndrii Nakryiko 
42774cc6311SAndrii Nakryiko 		tmp = libbpf_reallocarray(*segs, *seg_cnt + 1, sizeof(**segs));
42874cc6311SAndrii Nakryiko 		if (!tmp)
42974cc6311SAndrii Nakryiko 			return -ENOMEM;
43074cc6311SAndrii Nakryiko 
43174cc6311SAndrii Nakryiko 		*segs = tmp;
43274cc6311SAndrii Nakryiko 		seg = *segs + *seg_cnt;
43374cc6311SAndrii Nakryiko 		(*seg_cnt)++;
43474cc6311SAndrii Nakryiko 
43574cc6311SAndrii Nakryiko 		seg->start = phdr.p_vaddr;
43674cc6311SAndrii Nakryiko 		seg->end = phdr.p_vaddr + phdr.p_memsz;
43774cc6311SAndrii Nakryiko 		seg->offset = phdr.p_offset;
43874cc6311SAndrii Nakryiko 		seg->is_exec = phdr.p_flags & PF_X;
43974cc6311SAndrii Nakryiko 	}
44074cc6311SAndrii Nakryiko 
44174cc6311SAndrii Nakryiko 	if (*seg_cnt == 0) {
44274cc6311SAndrii Nakryiko 		pr_warn("usdt: failed to find PT_LOAD program headers in '%s'\n", path);
44374cc6311SAndrii Nakryiko 		return -ESRCH;
44474cc6311SAndrii Nakryiko 	}
44574cc6311SAndrii Nakryiko 
44674cc6311SAndrii Nakryiko 	qsort(*segs, *seg_cnt, sizeof(**segs), cmp_elf_segs);
44774cc6311SAndrii Nakryiko 	return 0;
44874cc6311SAndrii Nakryiko }
44974cc6311SAndrii Nakryiko 
parse_vma_segs(int pid,const char * lib_path,struct elf_seg ** segs,size_t * seg_cnt)4503e6fe5ceSAndrii Nakryiko static int parse_vma_segs(int pid, const char *lib_path, struct elf_seg **segs, size_t *seg_cnt)
45174cc6311SAndrii Nakryiko {
45274cc6311SAndrii Nakryiko 	char path[PATH_MAX], line[PATH_MAX], mode[16];
45374cc6311SAndrii Nakryiko 	size_t seg_start, seg_end, seg_off;
45474cc6311SAndrii Nakryiko 	struct elf_seg *seg;
45574cc6311SAndrii Nakryiko 	int tmp_pid, i, err;
45674cc6311SAndrii Nakryiko 	FILE *f;
45774cc6311SAndrii Nakryiko 
45874cc6311SAndrii Nakryiko 	*seg_cnt = 0;
45974cc6311SAndrii Nakryiko 
46074cc6311SAndrii Nakryiko 	/* Handle containerized binaries only accessible from
46174cc6311SAndrii Nakryiko 	 * /proc/<pid>/root/<path>. They will be reported as just /<path> in
46274cc6311SAndrii Nakryiko 	 * /proc/<pid>/maps.
46374cc6311SAndrii Nakryiko 	 */
46474cc6311SAndrii Nakryiko 	if (sscanf(lib_path, "/proc/%d/root%s", &tmp_pid, path) == 2 && pid == tmp_pid)
46574cc6311SAndrii Nakryiko 		goto proceed;
46674cc6311SAndrii Nakryiko 
46774cc6311SAndrii Nakryiko 	if (!realpath(lib_path, path)) {
46874cc6311SAndrii Nakryiko 		pr_warn("usdt: failed to get absolute path of '%s' (err %d), using path as is...\n",
46974cc6311SAndrii Nakryiko 			lib_path, -errno);
4703c0dfe6eSAndrii Nakryiko 		libbpf_strlcpy(path, lib_path, sizeof(path));
47174cc6311SAndrii Nakryiko 	}
47274cc6311SAndrii Nakryiko 
47374cc6311SAndrii Nakryiko proceed:
47474cc6311SAndrii Nakryiko 	sprintf(line, "/proc/%d/maps", pid);
47559842c54SAndrii Nakryiko 	f = fopen(line, "re");
47674cc6311SAndrii Nakryiko 	if (!f) {
47774cc6311SAndrii Nakryiko 		err = -errno;
47874cc6311SAndrii Nakryiko 		pr_warn("usdt: failed to open '%s' to get base addr of '%s': %d\n",
47974cc6311SAndrii Nakryiko 			line, lib_path, err);
48074cc6311SAndrii Nakryiko 		return err;
48174cc6311SAndrii Nakryiko 	}
48274cc6311SAndrii Nakryiko 
48374cc6311SAndrii Nakryiko 	/* We need to handle lines with no path at the end:
48474cc6311SAndrii Nakryiko 	 *
48574cc6311SAndrii Nakryiko 	 * 7f5c6f5d1000-7f5c6f5d3000 rw-p 001c7000 08:04 21238613      /usr/lib64/libc-2.17.so
48674cc6311SAndrii Nakryiko 	 * 7f5c6f5d3000-7f5c6f5d8000 rw-p 00000000 00:00 0
48774cc6311SAndrii Nakryiko 	 * 7f5c6f5d8000-7f5c6f5d9000 r-xp 00000000 103:01 362990598    /data/users/andriin/linux/tools/bpf/usdt/libhello_usdt.so
48874cc6311SAndrii Nakryiko 	 */
48974cc6311SAndrii Nakryiko 	while (fscanf(f, "%zx-%zx %s %zx %*s %*d%[^\n]\n",
49074cc6311SAndrii Nakryiko 		      &seg_start, &seg_end, mode, &seg_off, line) == 5) {
49174cc6311SAndrii Nakryiko 		void *tmp;
49274cc6311SAndrii Nakryiko 
49374cc6311SAndrii Nakryiko 		/* to handle no path case (see above) we need to capture line
49474cc6311SAndrii Nakryiko 		 * without skipping any whitespaces. So we need to strip
49574cc6311SAndrii Nakryiko 		 * leading whitespaces manually here
49674cc6311SAndrii Nakryiko 		 */
49774cc6311SAndrii Nakryiko 		i = 0;
49874cc6311SAndrii Nakryiko 		while (isblank(line[i]))
49974cc6311SAndrii Nakryiko 			i++;
50074cc6311SAndrii Nakryiko 		if (strcmp(line + i, path) != 0)
50174cc6311SAndrii Nakryiko 			continue;
50274cc6311SAndrii Nakryiko 
50374cc6311SAndrii Nakryiko 		pr_debug("usdt: discovered segment for lib '%s': addrs %zx-%zx mode %s offset %zx\n",
50474cc6311SAndrii Nakryiko 			 path, seg_start, seg_end, mode, seg_off);
50574cc6311SAndrii Nakryiko 
50674cc6311SAndrii Nakryiko 		/* ignore non-executable sections for shared libs */
50774cc6311SAndrii Nakryiko 		if (mode[2] != 'x')
50874cc6311SAndrii Nakryiko 			continue;
50974cc6311SAndrii Nakryiko 
51074cc6311SAndrii Nakryiko 		tmp = libbpf_reallocarray(*segs, *seg_cnt + 1, sizeof(**segs));
51174cc6311SAndrii Nakryiko 		if (!tmp) {
51274cc6311SAndrii Nakryiko 			err = -ENOMEM;
51374cc6311SAndrii Nakryiko 			goto err_out;
51474cc6311SAndrii Nakryiko 		}
51574cc6311SAndrii Nakryiko 
51674cc6311SAndrii Nakryiko 		*segs = tmp;
51774cc6311SAndrii Nakryiko 		seg = *segs + *seg_cnt;
51874cc6311SAndrii Nakryiko 		*seg_cnt += 1;
51974cc6311SAndrii Nakryiko 
52074cc6311SAndrii Nakryiko 		seg->start = seg_start;
52174cc6311SAndrii Nakryiko 		seg->end = seg_end;
52274cc6311SAndrii Nakryiko 		seg->offset = seg_off;
52374cc6311SAndrii Nakryiko 		seg->is_exec = true;
52474cc6311SAndrii Nakryiko 	}
52574cc6311SAndrii Nakryiko 
52674cc6311SAndrii Nakryiko 	if (*seg_cnt == 0) {
52774cc6311SAndrii Nakryiko 		pr_warn("usdt: failed to find '%s' (resolved to '%s') within PID %d memory mappings\n",
52874cc6311SAndrii Nakryiko 			lib_path, path, pid);
52974cc6311SAndrii Nakryiko 		err = -ESRCH;
53074cc6311SAndrii Nakryiko 		goto err_out;
53174cc6311SAndrii Nakryiko 	}
53274cc6311SAndrii Nakryiko 
53374cc6311SAndrii Nakryiko 	qsort(*segs, *seg_cnt, sizeof(**segs), cmp_elf_segs);
53474cc6311SAndrii Nakryiko 	err = 0;
53574cc6311SAndrii Nakryiko err_out:
53674cc6311SAndrii Nakryiko 	fclose(f);
53774cc6311SAndrii Nakryiko 	return err;
53874cc6311SAndrii Nakryiko }
53974cc6311SAndrii Nakryiko 
find_elf_seg(struct elf_seg * segs,size_t seg_cnt,long virtaddr)5403e6fe5ceSAndrii Nakryiko static struct elf_seg *find_elf_seg(struct elf_seg *segs, size_t seg_cnt, long virtaddr)
54174cc6311SAndrii Nakryiko {
54274cc6311SAndrii Nakryiko 	struct elf_seg *seg;
54374cc6311SAndrii Nakryiko 	int i;
54474cc6311SAndrii Nakryiko 
5453e6fe5ceSAndrii Nakryiko 	/* for ELF binaries (both executables and shared libraries), we are
5463e6fe5ceSAndrii Nakryiko 	 * given virtual address (absolute for executables, relative for
5473e6fe5ceSAndrii Nakryiko 	 * libraries) which should match address range of [seg_start, seg_end)
54874cc6311SAndrii Nakryiko 	 */
54974cc6311SAndrii Nakryiko 	for (i = 0, seg = segs; i < seg_cnt; i++, seg++) {
5503e6fe5ceSAndrii Nakryiko 		if (seg->start <= virtaddr && virtaddr < seg->end)
55174cc6311SAndrii Nakryiko 			return seg;
55274cc6311SAndrii Nakryiko 	}
55374cc6311SAndrii Nakryiko 	return NULL;
55474cc6311SAndrii Nakryiko }
55574cc6311SAndrii Nakryiko 
find_vma_seg(struct elf_seg * segs,size_t seg_cnt,long offset)5563e6fe5ceSAndrii Nakryiko static struct elf_seg *find_vma_seg(struct elf_seg *segs, size_t seg_cnt, long offset)
5573e6fe5ceSAndrii Nakryiko {
5583e6fe5ceSAndrii Nakryiko 	struct elf_seg *seg;
5593e6fe5ceSAndrii Nakryiko 	int i;
5603e6fe5ceSAndrii Nakryiko 
5613e6fe5ceSAndrii Nakryiko 	/* for VMA segments from /proc/<pid>/maps file, provided "address" is
5623e6fe5ceSAndrii Nakryiko 	 * actually a file offset, so should be fall within logical
5633e6fe5ceSAndrii Nakryiko 	 * offset-based range of [offset_start, offset_end)
5643e6fe5ceSAndrii Nakryiko 	 */
5653e6fe5ceSAndrii Nakryiko 	for (i = 0, seg = segs; i < seg_cnt; i++, seg++) {
5663e6fe5ceSAndrii Nakryiko 		if (seg->offset <= offset && offset < seg->offset + (seg->end - seg->start))
5673e6fe5ceSAndrii Nakryiko 			return seg;
5683e6fe5ceSAndrii Nakryiko 	}
5693e6fe5ceSAndrii Nakryiko 	return NULL;
5703e6fe5ceSAndrii Nakryiko }
5713e6fe5ceSAndrii Nakryiko 
5723e6fe5ceSAndrii Nakryiko static int parse_usdt_note(Elf *elf, const char *path, GElf_Nhdr *nhdr,
5733e6fe5ceSAndrii Nakryiko 			   const char *data, size_t name_off, size_t desc_off,
57474cc6311SAndrii Nakryiko 			   struct usdt_note *usdt_note);
57574cc6311SAndrii Nakryiko 
5765af25a41SPu Lehui static int parse_usdt_spec(struct usdt_spec *spec, const struct usdt_note *note, __u64 usdt_cookie);
57774cc6311SAndrii Nakryiko 
collect_usdt_targets(struct usdt_manager * man,Elf * elf,const char * path,pid_t pid,const char * usdt_provider,const char * usdt_name,__u64 usdt_cookie,struct usdt_target ** out_targets,size_t * out_target_cnt)5782e4913e0SAndrii Nakryiko static int collect_usdt_targets(struct usdt_manager *man, Elf *elf, const char *path, pid_t pid,
5795af25a41SPu Lehui 				const char *usdt_provider, const char *usdt_name, __u64 usdt_cookie,
5802e4913e0SAndrii Nakryiko 				struct usdt_target **out_targets, size_t *out_target_cnt)
5812e4913e0SAndrii Nakryiko {
5823e6fe5ceSAndrii Nakryiko 	size_t off, name_off, desc_off, seg_cnt = 0, vma_seg_cnt = 0, target_cnt = 0;
5833e6fe5ceSAndrii Nakryiko 	struct elf_seg *segs = NULL, *vma_segs = NULL;
58474cc6311SAndrii Nakryiko 	struct usdt_target *targets = NULL, *target;
58574cc6311SAndrii Nakryiko 	long base_addr = 0;
58674cc6311SAndrii Nakryiko 	Elf_Scn *notes_scn, *base_scn;
58774cc6311SAndrii Nakryiko 	GElf_Shdr base_shdr, notes_shdr;
58874cc6311SAndrii Nakryiko 	GElf_Ehdr ehdr;
58974cc6311SAndrii Nakryiko 	GElf_Nhdr nhdr;
59074cc6311SAndrii Nakryiko 	Elf_Data *data;
59174cc6311SAndrii Nakryiko 	int err;
59274cc6311SAndrii Nakryiko 
59374cc6311SAndrii Nakryiko 	*out_targets = NULL;
59474cc6311SAndrii Nakryiko 	*out_target_cnt = 0;
59574cc6311SAndrii Nakryiko 
59674cc6311SAndrii Nakryiko 	err = find_elf_sec_by_name(elf, USDT_NOTE_SEC, &notes_shdr, &notes_scn);
59774cc6311SAndrii Nakryiko 	if (err) {
59874cc6311SAndrii Nakryiko 		pr_warn("usdt: no USDT notes section (%s) found in '%s'\n", USDT_NOTE_SEC, path);
59974cc6311SAndrii Nakryiko 		return err;
60074cc6311SAndrii Nakryiko 	}
60174cc6311SAndrii Nakryiko 
60274cc6311SAndrii Nakryiko 	if (notes_shdr.sh_type != SHT_NOTE || !gelf_getehdr(elf, &ehdr)) {
60374cc6311SAndrii Nakryiko 		pr_warn("usdt: invalid USDT notes section (%s) in '%s'\n", USDT_NOTE_SEC, path);
60474cc6311SAndrii Nakryiko 		return -EINVAL;
60574cc6311SAndrii Nakryiko 	}
60674cc6311SAndrii Nakryiko 
60774cc6311SAndrii Nakryiko 	err = parse_elf_segs(elf, path, &segs, &seg_cnt);
60874cc6311SAndrii Nakryiko 	if (err) {
60974cc6311SAndrii Nakryiko 		pr_warn("usdt: failed to process ELF program segments for '%s': %d\n", path, err);
61074cc6311SAndrii Nakryiko 		goto err_out;
61174cc6311SAndrii Nakryiko 	}
61274cc6311SAndrii Nakryiko 
61374cc6311SAndrii Nakryiko 	/* .stapsdt.base ELF section is optional, but is used for prelink
61474cc6311SAndrii Nakryiko 	 * offset compensation (see a big comment further below)
61574cc6311SAndrii Nakryiko 	 */
61674cc6311SAndrii Nakryiko 	if (find_elf_sec_by_name(elf, USDT_BASE_SEC, &base_shdr, &base_scn) == 0)
61774cc6311SAndrii Nakryiko 		base_addr = base_shdr.sh_addr;
61874cc6311SAndrii Nakryiko 
61974cc6311SAndrii Nakryiko 	data = elf_getdata(notes_scn, 0);
62074cc6311SAndrii Nakryiko 	off = 0;
62174cc6311SAndrii Nakryiko 	while ((off = gelf_getnote(data, off, &nhdr, &name_off, &desc_off)) > 0) {
62274cc6311SAndrii Nakryiko 		long usdt_abs_ip, usdt_rel_ip, usdt_sema_off = 0;
62374cc6311SAndrii Nakryiko 		struct usdt_note note;
62474cc6311SAndrii Nakryiko 		struct elf_seg *seg = NULL;
62574cc6311SAndrii Nakryiko 		void *tmp;
62674cc6311SAndrii Nakryiko 
6273e6fe5ceSAndrii Nakryiko 		err = parse_usdt_note(elf, path, &nhdr, data->d_buf, name_off, desc_off, &note);
62874cc6311SAndrii Nakryiko 		if (err)
62974cc6311SAndrii Nakryiko 			goto err_out;
63074cc6311SAndrii Nakryiko 
63174cc6311SAndrii Nakryiko 		if (strcmp(note.provider, usdt_provider) != 0 || strcmp(note.name, usdt_name) != 0)
63274cc6311SAndrii Nakryiko 			continue;
63374cc6311SAndrii Nakryiko 
63474cc6311SAndrii Nakryiko 		/* We need to compensate "prelink effect". See [0] for details,
63574cc6311SAndrii Nakryiko 		 * relevant parts quoted here:
63674cc6311SAndrii Nakryiko 		 *
63774cc6311SAndrii Nakryiko 		 * Each SDT probe also expands into a non-allocated ELF note. You can
63874cc6311SAndrii Nakryiko 		 * find this by looking at SHT_NOTE sections and decoding the format;
63974cc6311SAndrii Nakryiko 		 * see below for details. Because the note is non-allocated, it means
64074cc6311SAndrii Nakryiko 		 * there is no runtime cost, and also preserved in both stripped files
64174cc6311SAndrii Nakryiko 		 * and .debug files.
64274cc6311SAndrii Nakryiko 		 *
64374cc6311SAndrii Nakryiko 		 * However, this means that prelink won't adjust the note's contents
64474cc6311SAndrii Nakryiko 		 * for address offsets. Instead, this is done via the .stapsdt.base
64574cc6311SAndrii Nakryiko 		 * section. This is a special section that is added to the text. We
64674cc6311SAndrii Nakryiko 		 * will only ever have one of these sections in a final link and it
64774cc6311SAndrii Nakryiko 		 * will only ever be one byte long. Nothing about this section itself
64874cc6311SAndrii Nakryiko 		 * matters, we just use it as a marker to detect prelink address
64974cc6311SAndrii Nakryiko 		 * adjustments.
65074cc6311SAndrii Nakryiko 		 *
65174cc6311SAndrii Nakryiko 		 * Each probe note records the link-time address of the .stapsdt.base
65274cc6311SAndrii Nakryiko 		 * section alongside the probe PC address. The decoder compares the
65374cc6311SAndrii Nakryiko 		 * base address stored in the note with the .stapsdt.base section's
65474cc6311SAndrii Nakryiko 		 * sh_addr. Initially these are the same, but the section header will
65574cc6311SAndrii Nakryiko 		 * be adjusted by prelink. So the decoder applies the difference to
65674cc6311SAndrii Nakryiko 		 * the probe PC address to get the correct prelinked PC address; the
65774cc6311SAndrii Nakryiko 		 * same adjustment is applied to the semaphore address, if any.
65874cc6311SAndrii Nakryiko 		 *
65974cc6311SAndrii Nakryiko 		 *   [0] https://sourceware.org/systemtap/wiki/UserSpaceProbeImplementation
66074cc6311SAndrii Nakryiko 		 */
6617c8121afSAndrii Nakryiko 		usdt_abs_ip = note.loc_addr;
662*3676e574SAndrii Nakryiko 		if (base_addr && note.base_addr)
66374cc6311SAndrii Nakryiko 			usdt_abs_ip += base_addr - note.base_addr;
66474cc6311SAndrii Nakryiko 
6653e6fe5ceSAndrii Nakryiko 		/* When attaching uprobes (which is what USDTs basically are)
6663e6fe5ceSAndrii Nakryiko 		 * kernel expects file offset to be specified, not a relative
6673e6fe5ceSAndrii Nakryiko 		 * virtual address, so we need to translate virtual address to
6683e6fe5ceSAndrii Nakryiko 		 * file offset, for both ET_EXEC and ET_DYN binaries.
66974cc6311SAndrii Nakryiko 		 */
6703e6fe5ceSAndrii Nakryiko 		seg = find_elf_seg(segs, seg_cnt, usdt_abs_ip);
67174cc6311SAndrii Nakryiko 		if (!seg) {
67274cc6311SAndrii Nakryiko 			err = -ESRCH;
67374cc6311SAndrii Nakryiko 			pr_warn("usdt: failed to find ELF program segment for '%s:%s' in '%s' at IP 0x%lx\n",
67474cc6311SAndrii Nakryiko 				usdt_provider, usdt_name, path, usdt_abs_ip);
67574cc6311SAndrii Nakryiko 			goto err_out;
67674cc6311SAndrii Nakryiko 		}
67774cc6311SAndrii Nakryiko 		if (!seg->is_exec) {
67874cc6311SAndrii Nakryiko 			err = -ESRCH;
67974cc6311SAndrii Nakryiko 			pr_warn("usdt: matched ELF binary '%s' segment [0x%lx, 0x%lx) for '%s:%s' at IP 0x%lx is not executable\n",
68074cc6311SAndrii Nakryiko 				path, seg->start, seg->end, usdt_provider, usdt_name,
68174cc6311SAndrii Nakryiko 				usdt_abs_ip);
68274cc6311SAndrii Nakryiko 			goto err_out;
68374cc6311SAndrii Nakryiko 		}
6843e6fe5ceSAndrii Nakryiko 		/* translate from virtual address to file offset */
6853e6fe5ceSAndrii Nakryiko 		usdt_rel_ip = usdt_abs_ip - seg->start + seg->offset;
68674cc6311SAndrii Nakryiko 
6873e6fe5ceSAndrii Nakryiko 		if (ehdr.e_type == ET_DYN && !man->has_bpf_cookie) {
68874cc6311SAndrii Nakryiko 			/* If we don't have BPF cookie support but need to
68974cc6311SAndrii Nakryiko 			 * attach to a shared library, we'll need to know and
69074cc6311SAndrii Nakryiko 			 * record absolute addresses of attach points due to
69174cc6311SAndrii Nakryiko 			 * the need to lookup USDT spec by absolute IP of
69274cc6311SAndrii Nakryiko 			 * triggered uprobe. Doing this resolution is only
69374cc6311SAndrii Nakryiko 			 * possible when we have a specific PID of the process
69474cc6311SAndrii Nakryiko 			 * that's using specified shared library. BPF cookie
69574cc6311SAndrii Nakryiko 			 * removes the absolute address limitation as we don't
69674cc6311SAndrii Nakryiko 			 * need to do this lookup (we just use BPF cookie as
69774cc6311SAndrii Nakryiko 			 * an index of USDT spec), so for newer kernels with
69874cc6311SAndrii Nakryiko 			 * BPF cookie support libbpf supports USDT attachment
69974cc6311SAndrii Nakryiko 			 * to shared libraries with no PID filter.
70074cc6311SAndrii Nakryiko 			 */
70174cc6311SAndrii Nakryiko 			if (pid < 0) {
702a8d600f6SColin Ian King 				pr_warn("usdt: attaching to shared libraries without specific PID is not supported on current kernel\n");
70374cc6311SAndrii Nakryiko 				err = -ENOTSUP;
70474cc6311SAndrii Nakryiko 				goto err_out;
70574cc6311SAndrii Nakryiko 			}
70674cc6311SAndrii Nakryiko 
7073e6fe5ceSAndrii Nakryiko 			/* vma_segs are lazily initialized only if necessary */
7083e6fe5ceSAndrii Nakryiko 			if (vma_seg_cnt == 0) {
7093e6fe5ceSAndrii Nakryiko 				err = parse_vma_segs(pid, path, &vma_segs, &vma_seg_cnt);
71074cc6311SAndrii Nakryiko 				if (err) {
71174cc6311SAndrii Nakryiko 					pr_warn("usdt: failed to get memory segments in PID %d for shared library '%s': %d\n",
71274cc6311SAndrii Nakryiko 						pid, path, err);
71374cc6311SAndrii Nakryiko 					goto err_out;
71474cc6311SAndrii Nakryiko 				}
71574cc6311SAndrii Nakryiko 			}
71674cc6311SAndrii Nakryiko 
7173e6fe5ceSAndrii Nakryiko 			seg = find_vma_seg(vma_segs, vma_seg_cnt, usdt_rel_ip);
71874cc6311SAndrii Nakryiko 			if (!seg) {
71974cc6311SAndrii Nakryiko 				err = -ESRCH;
72074cc6311SAndrii Nakryiko 				pr_warn("usdt: failed to find shared lib memory segment for '%s:%s' in '%s' at relative IP 0x%lx\n",
72174cc6311SAndrii Nakryiko 					usdt_provider, usdt_name, path, usdt_rel_ip);
72274cc6311SAndrii Nakryiko 				goto err_out;
72374cc6311SAndrii Nakryiko 			}
72474cc6311SAndrii Nakryiko 
7253e6fe5ceSAndrii Nakryiko 			usdt_abs_ip = seg->start - seg->offset + usdt_rel_ip;
72674cc6311SAndrii Nakryiko 		}
72774cc6311SAndrii Nakryiko 
72874cc6311SAndrii Nakryiko 		pr_debug("usdt: probe for '%s:%s' in %s '%s': addr 0x%lx base 0x%lx (resolved abs_ip 0x%lx rel_ip 0x%lx) args '%s' in segment [0x%lx, 0x%lx) at offset 0x%lx\n",
72974cc6311SAndrii Nakryiko 			 usdt_provider, usdt_name, ehdr.e_type == ET_EXEC ? "exec" : "lib ", path,
73074cc6311SAndrii Nakryiko 			 note.loc_addr, note.base_addr, usdt_abs_ip, usdt_rel_ip, note.args,
73174cc6311SAndrii Nakryiko 			 seg ? seg->start : 0, seg ? seg->end : 0, seg ? seg->offset : 0);
73274cc6311SAndrii Nakryiko 
7333e6fe5ceSAndrii Nakryiko 		/* Adjust semaphore address to be a file offset */
73474cc6311SAndrii Nakryiko 		if (note.sema_addr) {
73574cc6311SAndrii Nakryiko 			if (!man->has_sema_refcnt) {
73674cc6311SAndrii Nakryiko 				pr_warn("usdt: kernel doesn't support USDT semaphore refcounting for '%s:%s' in '%s'\n",
73774cc6311SAndrii Nakryiko 					usdt_provider, usdt_name, path);
73874cc6311SAndrii Nakryiko 				err = -ENOTSUP;
73974cc6311SAndrii Nakryiko 				goto err_out;
74074cc6311SAndrii Nakryiko 			}
74174cc6311SAndrii Nakryiko 
7423e6fe5ceSAndrii Nakryiko 			seg = find_elf_seg(segs, seg_cnt, note.sema_addr);
74374cc6311SAndrii Nakryiko 			if (!seg) {
74474cc6311SAndrii Nakryiko 				err = -ESRCH;
74574cc6311SAndrii Nakryiko 				pr_warn("usdt: failed to find ELF loadable segment with semaphore of '%s:%s' in '%s' at 0x%lx\n",
74674cc6311SAndrii Nakryiko 					usdt_provider, usdt_name, path, note.sema_addr);
74774cc6311SAndrii Nakryiko 				goto err_out;
74874cc6311SAndrii Nakryiko 			}
74974cc6311SAndrii Nakryiko 			if (seg->is_exec) {
75074cc6311SAndrii Nakryiko 				err = -ESRCH;
75174cc6311SAndrii Nakryiko 				pr_warn("usdt: matched ELF binary '%s' segment [0x%lx, 0x%lx] for semaphore of '%s:%s' at 0x%lx is executable\n",
75274cc6311SAndrii Nakryiko 					path, seg->start, seg->end, usdt_provider, usdt_name,
75374cc6311SAndrii Nakryiko 					note.sema_addr);
75474cc6311SAndrii Nakryiko 				goto err_out;
75574cc6311SAndrii Nakryiko 			}
75674cc6311SAndrii Nakryiko 
7573e6fe5ceSAndrii Nakryiko 			usdt_sema_off = note.sema_addr - seg->start + seg->offset;
75874cc6311SAndrii Nakryiko 
75974cc6311SAndrii Nakryiko 			pr_debug("usdt: sema  for '%s:%s' in %s '%s': addr 0x%lx base 0x%lx (resolved 0x%lx) in segment [0x%lx, 0x%lx] at offset 0x%lx\n",
76074cc6311SAndrii Nakryiko 				 usdt_provider, usdt_name, ehdr.e_type == ET_EXEC ? "exec" : "lib ",
76174cc6311SAndrii Nakryiko 				 path, note.sema_addr, note.base_addr, usdt_sema_off,
76274cc6311SAndrii Nakryiko 				 seg->start, seg->end, seg->offset);
76374cc6311SAndrii Nakryiko 		}
76474cc6311SAndrii Nakryiko 
76574cc6311SAndrii Nakryiko 		/* Record adjusted addresses and offsets and parse USDT spec */
76674cc6311SAndrii Nakryiko 		tmp = libbpf_reallocarray(targets, target_cnt + 1, sizeof(*targets));
76774cc6311SAndrii Nakryiko 		if (!tmp) {
76874cc6311SAndrii Nakryiko 			err = -ENOMEM;
76974cc6311SAndrii Nakryiko 			goto err_out;
77074cc6311SAndrii Nakryiko 		}
77174cc6311SAndrii Nakryiko 		targets = tmp;
77274cc6311SAndrii Nakryiko 
77374cc6311SAndrii Nakryiko 		target = &targets[target_cnt];
77474cc6311SAndrii Nakryiko 		memset(target, 0, sizeof(*target));
77574cc6311SAndrii Nakryiko 
77674cc6311SAndrii Nakryiko 		target->abs_ip = usdt_abs_ip;
77774cc6311SAndrii Nakryiko 		target->rel_ip = usdt_rel_ip;
77874cc6311SAndrii Nakryiko 		target->sema_off = usdt_sema_off;
77974cc6311SAndrii Nakryiko 
78070e79866SAlexey Dobriyan 		/* notes.args references strings from ELF itself, so they can
78174cc6311SAndrii Nakryiko 		 * be referenced safely until elf_end() call
78274cc6311SAndrii Nakryiko 		 */
78374cc6311SAndrii Nakryiko 		target->spec_str = note.args;
78474cc6311SAndrii Nakryiko 
78574cc6311SAndrii Nakryiko 		err = parse_usdt_spec(&target->spec, &note, usdt_cookie);
78674cc6311SAndrii Nakryiko 		if (err)
78774cc6311SAndrii Nakryiko 			goto err_out;
78874cc6311SAndrii Nakryiko 
78974cc6311SAndrii Nakryiko 		target_cnt++;
79074cc6311SAndrii Nakryiko 	}
79174cc6311SAndrii Nakryiko 
79274cc6311SAndrii Nakryiko 	*out_targets = targets;
79374cc6311SAndrii Nakryiko 	*out_target_cnt = target_cnt;
79474cc6311SAndrii Nakryiko 	err = target_cnt;
79574cc6311SAndrii Nakryiko 
79674cc6311SAndrii Nakryiko err_out:
79774cc6311SAndrii Nakryiko 	free(segs);
7983e6fe5ceSAndrii Nakryiko 	free(vma_segs);
79974cc6311SAndrii Nakryiko 	if (err < 0)
80074cc6311SAndrii Nakryiko 		free(targets);
80174cc6311SAndrii Nakryiko 	return err;
8022e4913e0SAndrii Nakryiko }
8032e4913e0SAndrii Nakryiko 
8042e4913e0SAndrii Nakryiko struct bpf_link_usdt {
8052e4913e0SAndrii Nakryiko 	struct bpf_link link;
8062e4913e0SAndrii Nakryiko 
8072e4913e0SAndrii Nakryiko 	struct usdt_manager *usdt_man;
8082e4913e0SAndrii Nakryiko 
809999783c8SAndrii Nakryiko 	size_t spec_cnt;
810999783c8SAndrii Nakryiko 	int *spec_ids;
811999783c8SAndrii Nakryiko 
8122e4913e0SAndrii Nakryiko 	size_t uprobe_cnt;
8132e4913e0SAndrii Nakryiko 	struct {
8142e4913e0SAndrii Nakryiko 		long abs_ip;
8152e4913e0SAndrii Nakryiko 		struct bpf_link *link;
8162e4913e0SAndrii Nakryiko 	} *uprobes;
8175902da6dSJiri Olsa 
8185902da6dSJiri Olsa 	struct bpf_link *multi_link;
8192e4913e0SAndrii Nakryiko };
8202e4913e0SAndrii Nakryiko 
bpf_link_usdt_detach(struct bpf_link * link)8212e4913e0SAndrii Nakryiko static int bpf_link_usdt_detach(struct bpf_link *link)
8222e4913e0SAndrii Nakryiko {
8232e4913e0SAndrii Nakryiko 	struct bpf_link_usdt *usdt_link = container_of(link, struct bpf_link_usdt, link);
824999783c8SAndrii Nakryiko 	struct usdt_manager *man = usdt_link->usdt_man;
8252e4913e0SAndrii Nakryiko 	int i;
8262e4913e0SAndrii Nakryiko 
8275902da6dSJiri Olsa 	bpf_link__destroy(usdt_link->multi_link);
8285902da6dSJiri Olsa 
8295902da6dSJiri Olsa 	/* When having multi_link, uprobe_cnt is 0 */
8302e4913e0SAndrii Nakryiko 	for (i = 0; i < usdt_link->uprobe_cnt; i++) {
8312e4913e0SAndrii Nakryiko 		/* detach underlying uprobe link */
8322e4913e0SAndrii Nakryiko 		bpf_link__destroy(usdt_link->uprobes[i].link);
833999783c8SAndrii Nakryiko 		/* there is no need to update specs map because it will be
834999783c8SAndrii Nakryiko 		 * unconditionally overwritten on subsequent USDT attaches,
835999783c8SAndrii Nakryiko 		 * but if BPF cookies are not used we need to remove entry
836999783c8SAndrii Nakryiko 		 * from ip_to_spec_id map, otherwise we'll run into false
837999783c8SAndrii Nakryiko 		 * conflicting IP errors
838999783c8SAndrii Nakryiko 		 */
839999783c8SAndrii Nakryiko 		if (!man->has_bpf_cookie) {
840999783c8SAndrii Nakryiko 			/* not much we can do about errors here */
841999783c8SAndrii Nakryiko 			(void)bpf_map_delete_elem(bpf_map__fd(man->ip_to_spec_id_map),
842999783c8SAndrii Nakryiko 						  &usdt_link->uprobes[i].abs_ip);
843999783c8SAndrii Nakryiko 		}
844999783c8SAndrii Nakryiko 	}
845999783c8SAndrii Nakryiko 
846999783c8SAndrii Nakryiko 	/* try to return the list of previously used spec IDs to usdt_manager
847999783c8SAndrii Nakryiko 	 * for future reuse for subsequent USDT attaches
848999783c8SAndrii Nakryiko 	 */
849999783c8SAndrii Nakryiko 	if (!man->free_spec_ids) {
850999783c8SAndrii Nakryiko 		/* if there were no free spec IDs yet, just transfer our IDs */
851999783c8SAndrii Nakryiko 		man->free_spec_ids = usdt_link->spec_ids;
852999783c8SAndrii Nakryiko 		man->free_spec_cnt = usdt_link->spec_cnt;
853999783c8SAndrii Nakryiko 		usdt_link->spec_ids = NULL;
854999783c8SAndrii Nakryiko 	} else {
855999783c8SAndrii Nakryiko 		/* otherwise concat IDs */
856999783c8SAndrii Nakryiko 		size_t new_cnt = man->free_spec_cnt + usdt_link->spec_cnt;
857999783c8SAndrii Nakryiko 		int *new_free_ids;
858999783c8SAndrii Nakryiko 
859999783c8SAndrii Nakryiko 		new_free_ids = libbpf_reallocarray(man->free_spec_ids, new_cnt,
860999783c8SAndrii Nakryiko 						   sizeof(*new_free_ids));
861999783c8SAndrii Nakryiko 		/* If we couldn't resize free_spec_ids, we'll just leak
862999783c8SAndrii Nakryiko 		 * a bunch of free IDs; this is very unlikely to happen and if
863e1b6df59SIlya Leoshkevich 		 * system is so exhausted on memory, it's the least of user's
864999783c8SAndrii Nakryiko 		 * concerns, probably.
865999783c8SAndrii Nakryiko 		 * So just do our best here to return those IDs to usdt_manager.
8668a0260dbSAndrii Nakryiko 		 * Another edge case when we can legitimately get NULL is when
8678a0260dbSAndrii Nakryiko 		 * new_cnt is zero, which can happen in some edge cases, so we
8688a0260dbSAndrii Nakryiko 		 * need to be careful about that.
869999783c8SAndrii Nakryiko 		 */
8708a0260dbSAndrii Nakryiko 		if (new_free_ids || new_cnt == 0) {
871999783c8SAndrii Nakryiko 			memcpy(new_free_ids + man->free_spec_cnt, usdt_link->spec_ids,
872999783c8SAndrii Nakryiko 			       usdt_link->spec_cnt * sizeof(*usdt_link->spec_ids));
873999783c8SAndrii Nakryiko 			man->free_spec_ids = new_free_ids;
874999783c8SAndrii Nakryiko 			man->free_spec_cnt = new_cnt;
875999783c8SAndrii Nakryiko 		}
8762e4913e0SAndrii Nakryiko 	}
8772e4913e0SAndrii Nakryiko 
8782e4913e0SAndrii Nakryiko 	return 0;
8792e4913e0SAndrii Nakryiko }
8802e4913e0SAndrii Nakryiko 
bpf_link_usdt_dealloc(struct bpf_link * link)8812e4913e0SAndrii Nakryiko static void bpf_link_usdt_dealloc(struct bpf_link *link)
8822e4913e0SAndrii Nakryiko {
8832e4913e0SAndrii Nakryiko 	struct bpf_link_usdt *usdt_link = container_of(link, struct bpf_link_usdt, link);
8842e4913e0SAndrii Nakryiko 
885999783c8SAndrii Nakryiko 	free(usdt_link->spec_ids);
8862e4913e0SAndrii Nakryiko 	free(usdt_link->uprobes);
8872e4913e0SAndrii Nakryiko 	free(usdt_link);
8882e4913e0SAndrii Nakryiko }
8892e4913e0SAndrii Nakryiko 
specs_hash_fn(long key,void * ctx)890c302378bSEduard Zingerman static size_t specs_hash_fn(long key, void *ctx)
891999783c8SAndrii Nakryiko {
892c302378bSEduard Zingerman 	return str_hash((char *)key);
893999783c8SAndrii Nakryiko }
894999783c8SAndrii Nakryiko 
specs_equal_fn(long key1,long key2,void * ctx)895c302378bSEduard Zingerman static bool specs_equal_fn(long key1, long key2, void *ctx)
896999783c8SAndrii Nakryiko {
897c302378bSEduard Zingerman 	return strcmp((char *)key1, (char *)key2) == 0;
898999783c8SAndrii Nakryiko }
899999783c8SAndrii Nakryiko 
allocate_spec_id(struct usdt_manager * man,struct hashmap * specs_hash,struct bpf_link_usdt * link,struct usdt_target * target,int * spec_id,bool * is_new)900999783c8SAndrii Nakryiko static int allocate_spec_id(struct usdt_manager *man, struct hashmap *specs_hash,
901999783c8SAndrii Nakryiko 			    struct bpf_link_usdt *link, struct usdt_target *target,
902999783c8SAndrii Nakryiko 			    int *spec_id, bool *is_new)
903999783c8SAndrii Nakryiko {
904c302378bSEduard Zingerman 	long tmp;
905c302378bSEduard Zingerman 	void *new_ids;
906999783c8SAndrii Nakryiko 	int err;
907999783c8SAndrii Nakryiko 
908999783c8SAndrii Nakryiko 	/* check if we already allocated spec ID for this spec string */
909999783c8SAndrii Nakryiko 	if (hashmap__find(specs_hash, target->spec_str, &tmp)) {
910c302378bSEduard Zingerman 		*spec_id = tmp;
911999783c8SAndrii Nakryiko 		*is_new = false;
912999783c8SAndrii Nakryiko 		return 0;
913999783c8SAndrii Nakryiko 	}
914999783c8SAndrii Nakryiko 
915999783c8SAndrii Nakryiko 	/* otherwise it's a new ID that needs to be set up in specs map and
916999783c8SAndrii Nakryiko 	 * returned back to usdt_manager when USDT link is detached
917999783c8SAndrii Nakryiko 	 */
918c302378bSEduard Zingerman 	new_ids = libbpf_reallocarray(link->spec_ids, link->spec_cnt + 1, sizeof(*link->spec_ids));
919c302378bSEduard Zingerman 	if (!new_ids)
920999783c8SAndrii Nakryiko 		return -ENOMEM;
921c302378bSEduard Zingerman 	link->spec_ids = new_ids;
922999783c8SAndrii Nakryiko 
923999783c8SAndrii Nakryiko 	/* get next free spec ID, giving preference to free list, if not empty */
924999783c8SAndrii Nakryiko 	if (man->free_spec_cnt) {
925999783c8SAndrii Nakryiko 		*spec_id = man->free_spec_ids[man->free_spec_cnt - 1];
926999783c8SAndrii Nakryiko 
927999783c8SAndrii Nakryiko 		/* cache spec ID for current spec string for future lookups */
928c302378bSEduard Zingerman 		err = hashmap__add(specs_hash, target->spec_str, *spec_id);
929999783c8SAndrii Nakryiko 		if (err)
930999783c8SAndrii Nakryiko 			 return err;
931999783c8SAndrii Nakryiko 
932999783c8SAndrii Nakryiko 		man->free_spec_cnt--;
933999783c8SAndrii Nakryiko 	} else {
934999783c8SAndrii Nakryiko 		/* don't allocate spec ID bigger than what fits in specs map */
935999783c8SAndrii Nakryiko 		if (man->next_free_spec_id >= bpf_map__max_entries(man->specs_map))
936999783c8SAndrii Nakryiko 			return -E2BIG;
937999783c8SAndrii Nakryiko 
938999783c8SAndrii Nakryiko 		*spec_id = man->next_free_spec_id;
939999783c8SAndrii Nakryiko 
940999783c8SAndrii Nakryiko 		/* cache spec ID for current spec string for future lookups */
941c302378bSEduard Zingerman 		err = hashmap__add(specs_hash, target->spec_str, *spec_id);
942999783c8SAndrii Nakryiko 		if (err)
943999783c8SAndrii Nakryiko 			 return err;
944999783c8SAndrii Nakryiko 
945999783c8SAndrii Nakryiko 		man->next_free_spec_id++;
946999783c8SAndrii Nakryiko 	}
947999783c8SAndrii Nakryiko 
948999783c8SAndrii Nakryiko 	/* remember new spec ID in the link for later return back to free list on detach */
949999783c8SAndrii Nakryiko 	link->spec_ids[link->spec_cnt] = *spec_id;
950999783c8SAndrii Nakryiko 	link->spec_cnt++;
951999783c8SAndrii Nakryiko 	*is_new = true;
952999783c8SAndrii Nakryiko 	return 0;
953999783c8SAndrii Nakryiko }
954999783c8SAndrii Nakryiko 
usdt_manager_attach_usdt(struct usdt_manager * man,const struct bpf_program * prog,pid_t pid,const char * path,const char * usdt_provider,const char * usdt_name,__u64 usdt_cookie)9552e4913e0SAndrii Nakryiko struct bpf_link *usdt_manager_attach_usdt(struct usdt_manager *man, const struct bpf_program *prog,
9562e4913e0SAndrii Nakryiko 					  pid_t pid, const char *path,
9572e4913e0SAndrii Nakryiko 					  const char *usdt_provider, const char *usdt_name,
9585af25a41SPu Lehui 					  __u64 usdt_cookie)
9592e4913e0SAndrii Nakryiko {
9605902da6dSJiri Olsa 	unsigned long *offsets = NULL, *ref_ctr_offsets = NULL;
961f90eb70dSJiri Olsa 	int i, err, spec_map_fd, ip_map_fd;
9622e4913e0SAndrii Nakryiko 	LIBBPF_OPTS(bpf_uprobe_opts, opts);
963999783c8SAndrii Nakryiko 	struct hashmap *specs_hash = NULL;
9642e4913e0SAndrii Nakryiko 	struct bpf_link_usdt *link = NULL;
9652e4913e0SAndrii Nakryiko 	struct usdt_target *targets = NULL;
9665902da6dSJiri Olsa 	__u64 *cookies = NULL;
967f90eb70dSJiri Olsa 	struct elf_fd elf_fd;
9682e4913e0SAndrii Nakryiko 	size_t target_cnt;
9692e4913e0SAndrii Nakryiko 
970999783c8SAndrii Nakryiko 	spec_map_fd = bpf_map__fd(man->specs_map);
971999783c8SAndrii Nakryiko 	ip_map_fd = bpf_map__fd(man->ip_to_spec_id_map);
972999783c8SAndrii Nakryiko 
973f90eb70dSJiri Olsa 	err = elf_open(path, &elf_fd);
974f90eb70dSJiri Olsa 	if (err)
9752e4913e0SAndrii Nakryiko 		return libbpf_err_ptr(err);
9762e4913e0SAndrii Nakryiko 
977f90eb70dSJiri Olsa 	err = sanity_check_usdt_elf(elf_fd.elf, path);
9782e4913e0SAndrii Nakryiko 	if (err)
9792e4913e0SAndrii Nakryiko 		goto err_out;
9802e4913e0SAndrii Nakryiko 
9812e4913e0SAndrii Nakryiko 	/* normalize PID filter */
9822e4913e0SAndrii Nakryiko 	if (pid < 0)
9832e4913e0SAndrii Nakryiko 		pid = -1;
9842e4913e0SAndrii Nakryiko 	else if (pid == 0)
9852e4913e0SAndrii Nakryiko 		pid = getpid();
9862e4913e0SAndrii Nakryiko 
9872e4913e0SAndrii Nakryiko 	/* discover USDT in given binary, optionally limiting
9882e4913e0SAndrii Nakryiko 	 * activations to a given PID, if pid > 0
9892e4913e0SAndrii Nakryiko 	 */
990f90eb70dSJiri Olsa 	err = collect_usdt_targets(man, elf_fd.elf, path, pid, usdt_provider, usdt_name,
9912e4913e0SAndrii Nakryiko 				   usdt_cookie, &targets, &target_cnt);
9922e4913e0SAndrii Nakryiko 	if (err <= 0) {
9932e4913e0SAndrii Nakryiko 		err = (err == 0) ? -ENOENT : err;
9942e4913e0SAndrii Nakryiko 		goto err_out;
9952e4913e0SAndrii Nakryiko 	}
9962e4913e0SAndrii Nakryiko 
997999783c8SAndrii Nakryiko 	specs_hash = hashmap__new(specs_hash_fn, specs_equal_fn, NULL);
998999783c8SAndrii Nakryiko 	if (IS_ERR(specs_hash)) {
999999783c8SAndrii Nakryiko 		err = PTR_ERR(specs_hash);
1000999783c8SAndrii Nakryiko 		goto err_out;
1001999783c8SAndrii Nakryiko 	}
1002999783c8SAndrii Nakryiko 
10032e4913e0SAndrii Nakryiko 	link = calloc(1, sizeof(*link));
10042e4913e0SAndrii Nakryiko 	if (!link) {
10052e4913e0SAndrii Nakryiko 		err = -ENOMEM;
10062e4913e0SAndrii Nakryiko 		goto err_out;
10072e4913e0SAndrii Nakryiko 	}
10082e4913e0SAndrii Nakryiko 
10092e4913e0SAndrii Nakryiko 	link->usdt_man = man;
10102e4913e0SAndrii Nakryiko 	link->link.detach = &bpf_link_usdt_detach;
10112e4913e0SAndrii Nakryiko 	link->link.dealloc = &bpf_link_usdt_dealloc;
10122e4913e0SAndrii Nakryiko 
10135902da6dSJiri Olsa 	if (man->has_uprobe_multi) {
10145902da6dSJiri Olsa 		offsets = calloc(target_cnt, sizeof(*offsets));
10155902da6dSJiri Olsa 		cookies = calloc(target_cnt, sizeof(*cookies));
10165902da6dSJiri Olsa 		ref_ctr_offsets = calloc(target_cnt, sizeof(*ref_ctr_offsets));
10175902da6dSJiri Olsa 
10185902da6dSJiri Olsa 		if (!offsets || !ref_ctr_offsets || !cookies) {
10195902da6dSJiri Olsa 			err = -ENOMEM;
10205902da6dSJiri Olsa 			goto err_out;
10215902da6dSJiri Olsa 		}
10225902da6dSJiri Olsa 	} else {
10232e4913e0SAndrii Nakryiko 		link->uprobes = calloc(target_cnt, sizeof(*link->uprobes));
10242e4913e0SAndrii Nakryiko 		if (!link->uprobes) {
10252e4913e0SAndrii Nakryiko 			err = -ENOMEM;
10262e4913e0SAndrii Nakryiko 			goto err_out;
10272e4913e0SAndrii Nakryiko 		}
10285902da6dSJiri Olsa 	}
10292e4913e0SAndrii Nakryiko 
10302e4913e0SAndrii Nakryiko 	for (i = 0; i < target_cnt; i++) {
10312e4913e0SAndrii Nakryiko 		struct usdt_target *target = &targets[i];
10322e4913e0SAndrii Nakryiko 		struct bpf_link *uprobe_link;
1033999783c8SAndrii Nakryiko 		bool is_new;
1034999783c8SAndrii Nakryiko 		int spec_id;
1035999783c8SAndrii Nakryiko 
1036999783c8SAndrii Nakryiko 		/* Spec ID can be either reused or newly allocated. If it is
1037999783c8SAndrii Nakryiko 		 * newly allocated, we'll need to fill out spec map, otherwise
1038999783c8SAndrii Nakryiko 		 * entire spec should be valid and can be just used by a new
1039999783c8SAndrii Nakryiko 		 * uprobe. We reuse spec when USDT arg spec is identical. We
1040999783c8SAndrii Nakryiko 		 * also never share specs between two different USDT
1041999783c8SAndrii Nakryiko 		 * attachments ("links"), so all the reused specs already
1042999783c8SAndrii Nakryiko 		 * share USDT cookie value implicitly.
1043999783c8SAndrii Nakryiko 		 */
1044999783c8SAndrii Nakryiko 		err = allocate_spec_id(man, specs_hash, link, target, &spec_id, &is_new);
1045999783c8SAndrii Nakryiko 		if (err)
1046999783c8SAndrii Nakryiko 			goto err_out;
1047999783c8SAndrii Nakryiko 
1048999783c8SAndrii Nakryiko 		if (is_new && bpf_map_update_elem(spec_map_fd, &spec_id, &target->spec, BPF_ANY)) {
1049999783c8SAndrii Nakryiko 			err = -errno;
1050999783c8SAndrii Nakryiko 			pr_warn("usdt: failed to set USDT spec #%d for '%s:%s' in '%s': %d\n",
1051999783c8SAndrii Nakryiko 				spec_id, usdt_provider, usdt_name, path, err);
1052999783c8SAndrii Nakryiko 			goto err_out;
1053999783c8SAndrii Nakryiko 		}
1054999783c8SAndrii Nakryiko 		if (!man->has_bpf_cookie &&
1055999783c8SAndrii Nakryiko 		    bpf_map_update_elem(ip_map_fd, &target->abs_ip, &spec_id, BPF_NOEXIST)) {
1056999783c8SAndrii Nakryiko 			err = -errno;
1057999783c8SAndrii Nakryiko 			if (err == -EEXIST) {
1058999783c8SAndrii Nakryiko 				pr_warn("usdt: IP collision detected for spec #%d for '%s:%s' in '%s'\n",
1059999783c8SAndrii Nakryiko 				        spec_id, usdt_provider, usdt_name, path);
1060999783c8SAndrii Nakryiko 			} else {
1061999783c8SAndrii Nakryiko 				pr_warn("usdt: failed to map IP 0x%lx to spec #%d for '%s:%s' in '%s': %d\n",
1062999783c8SAndrii Nakryiko 					target->abs_ip, spec_id, usdt_provider, usdt_name,
1063999783c8SAndrii Nakryiko 					path, err);
1064999783c8SAndrii Nakryiko 			}
1065999783c8SAndrii Nakryiko 			goto err_out;
1066999783c8SAndrii Nakryiko 		}
10672e4913e0SAndrii Nakryiko 
10685902da6dSJiri Olsa 		if (man->has_uprobe_multi) {
10695902da6dSJiri Olsa 			offsets[i] = target->rel_ip;
10705902da6dSJiri Olsa 			ref_ctr_offsets[i] = target->sema_off;
10715902da6dSJiri Olsa 			cookies[i] = spec_id;
10725902da6dSJiri Olsa 		} else {
10732e4913e0SAndrii Nakryiko 			opts.ref_ctr_offset = target->sema_off;
1074999783c8SAndrii Nakryiko 			opts.bpf_cookie = man->has_bpf_cookie ? spec_id : 0;
10752e4913e0SAndrii Nakryiko 			uprobe_link = bpf_program__attach_uprobe_opts(prog, pid, path,
10762e4913e0SAndrii Nakryiko 								      target->rel_ip, &opts);
10772e4913e0SAndrii Nakryiko 			err = libbpf_get_error(uprobe_link);
10782e4913e0SAndrii Nakryiko 			if (err) {
10792e4913e0SAndrii Nakryiko 				pr_warn("usdt: failed to attach uprobe #%d for '%s:%s' in '%s': %d\n",
10802e4913e0SAndrii Nakryiko 					i, usdt_provider, usdt_name, path, err);
10812e4913e0SAndrii Nakryiko 				goto err_out;
10822e4913e0SAndrii Nakryiko 			}
10832e4913e0SAndrii Nakryiko 
10842e4913e0SAndrii Nakryiko 			link->uprobes[i].link = uprobe_link;
10852e4913e0SAndrii Nakryiko 			link->uprobes[i].abs_ip = target->abs_ip;
10862e4913e0SAndrii Nakryiko 			link->uprobe_cnt++;
10872e4913e0SAndrii Nakryiko 		}
10885902da6dSJiri Olsa 	}
10895902da6dSJiri Olsa 
10905902da6dSJiri Olsa 	if (man->has_uprobe_multi) {
10915902da6dSJiri Olsa 		LIBBPF_OPTS(bpf_uprobe_multi_opts, opts_multi,
10925902da6dSJiri Olsa 			.ref_ctr_offsets = ref_ctr_offsets,
10935902da6dSJiri Olsa 			.offsets = offsets,
10945902da6dSJiri Olsa 			.cookies = cookies,
10955902da6dSJiri Olsa 			.cnt = target_cnt,
10965902da6dSJiri Olsa 		);
10975902da6dSJiri Olsa 
10985902da6dSJiri Olsa 		link->multi_link = bpf_program__attach_uprobe_multi(prog, pid, path,
10995902da6dSJiri Olsa 								    NULL, &opts_multi);
11005902da6dSJiri Olsa 		if (!link->multi_link) {
11015902da6dSJiri Olsa 			err = -errno;
11025902da6dSJiri Olsa 			pr_warn("usdt: failed to attach uprobe multi for '%s:%s' in '%s': %d\n",
11035902da6dSJiri Olsa 				usdt_provider, usdt_name, path, err);
11045902da6dSJiri Olsa 			goto err_out;
11055902da6dSJiri Olsa 		}
11065902da6dSJiri Olsa 
11075902da6dSJiri Olsa 		free(offsets);
11085902da6dSJiri Olsa 		free(ref_ctr_offsets);
11095902da6dSJiri Olsa 		free(cookies);
11105902da6dSJiri Olsa 	}
11112e4913e0SAndrii Nakryiko 
111274cc6311SAndrii Nakryiko 	free(targets);
1113999783c8SAndrii Nakryiko 	hashmap__free(specs_hash);
1114f90eb70dSJiri Olsa 	elf_close(&elf_fd);
11152e4913e0SAndrii Nakryiko 	return &link->link;
11162e4913e0SAndrii Nakryiko 
11172e4913e0SAndrii Nakryiko err_out:
11185902da6dSJiri Olsa 	free(offsets);
11195902da6dSJiri Olsa 	free(ref_ctr_offsets);
11205902da6dSJiri Olsa 	free(cookies);
11215902da6dSJiri Olsa 
1122e58c5c97SHaowen Bai 	if (link)
11232e4913e0SAndrii Nakryiko 		bpf_link__destroy(&link->link);
112474cc6311SAndrii Nakryiko 	free(targets);
1125999783c8SAndrii Nakryiko 	hashmap__free(specs_hash);
1126f90eb70dSJiri Olsa 	elf_close(&elf_fd);
11272e4913e0SAndrii Nakryiko 	return libbpf_err_ptr(err);
11282e4913e0SAndrii Nakryiko }
112974cc6311SAndrii Nakryiko 
113074cc6311SAndrii Nakryiko /* Parse out USDT ELF note from '.note.stapsdt' section.
113174cc6311SAndrii Nakryiko  * Logic inspired by perf's code.
113274cc6311SAndrii Nakryiko  */
parse_usdt_note(Elf * elf,const char * path,GElf_Nhdr * nhdr,const char * data,size_t name_off,size_t desc_off,struct usdt_note * note)11333e6fe5ceSAndrii Nakryiko static int parse_usdt_note(Elf *elf, const char *path, GElf_Nhdr *nhdr,
11343e6fe5ceSAndrii Nakryiko 			   const char *data, size_t name_off, size_t desc_off,
113574cc6311SAndrii Nakryiko 			   struct usdt_note *note)
113674cc6311SAndrii Nakryiko {
113774cc6311SAndrii Nakryiko 	const char *provider, *name, *args;
113874cc6311SAndrii Nakryiko 	long addrs[3];
113974cc6311SAndrii Nakryiko 	size_t len;
114074cc6311SAndrii Nakryiko 
114174cc6311SAndrii Nakryiko 	/* sanity check USDT note name and type first */
114274cc6311SAndrii Nakryiko 	if (strncmp(data + name_off, USDT_NOTE_NAME, nhdr->n_namesz) != 0)
114374cc6311SAndrii Nakryiko 		return -EINVAL;
114474cc6311SAndrii Nakryiko 	if (nhdr->n_type != USDT_NOTE_TYPE)
114574cc6311SAndrii Nakryiko 		return -EINVAL;
114674cc6311SAndrii Nakryiko 
114774cc6311SAndrii Nakryiko 	/* sanity check USDT note contents ("description" in ELF terminology) */
114874cc6311SAndrii Nakryiko 	len = nhdr->n_descsz;
114974cc6311SAndrii Nakryiko 	data = data + desc_off;
115074cc6311SAndrii Nakryiko 
115174cc6311SAndrii Nakryiko 	/* +3 is the very minimum required to store three empty strings */
115274cc6311SAndrii Nakryiko 	if (len < sizeof(addrs) + 3)
115374cc6311SAndrii Nakryiko 		return -EINVAL;
115474cc6311SAndrii Nakryiko 
115574cc6311SAndrii Nakryiko 	/* get location, base, and semaphore addrs */
115674cc6311SAndrii Nakryiko 	memcpy(&addrs, data, sizeof(addrs));
115774cc6311SAndrii Nakryiko 
115874cc6311SAndrii Nakryiko 	/* parse string fields: provider, name, args */
115974cc6311SAndrii Nakryiko 	provider = data + sizeof(addrs);
116074cc6311SAndrii Nakryiko 
116174cc6311SAndrii Nakryiko 	name = (const char *)memchr(provider, '\0', data + len - provider);
116274cc6311SAndrii Nakryiko 	if (!name) /* non-zero-terminated provider */
116374cc6311SAndrii Nakryiko 		return -EINVAL;
116474cc6311SAndrii Nakryiko 	name++;
116574cc6311SAndrii Nakryiko 	if (name >= data + len || *name == '\0') /* missing or empty name */
116674cc6311SAndrii Nakryiko 		return -EINVAL;
116774cc6311SAndrii Nakryiko 
116874cc6311SAndrii Nakryiko 	args = memchr(name, '\0', data + len - name);
116974cc6311SAndrii Nakryiko 	if (!args) /* non-zero-terminated name */
117074cc6311SAndrii Nakryiko 		return -EINVAL;
117174cc6311SAndrii Nakryiko 	++args;
117274cc6311SAndrii Nakryiko 	if (args >= data + len) /* missing arguments spec */
117374cc6311SAndrii Nakryiko 		return -EINVAL;
117474cc6311SAndrii Nakryiko 
117574cc6311SAndrii Nakryiko 	note->provider = provider;
117674cc6311SAndrii Nakryiko 	note->name = name;
117774cc6311SAndrii Nakryiko 	if (*args == '\0' || *args == ':')
117874cc6311SAndrii Nakryiko 		note->args = "";
117974cc6311SAndrii Nakryiko 	else
118074cc6311SAndrii Nakryiko 		note->args = args;
118174cc6311SAndrii Nakryiko 	note->loc_addr = addrs[0];
118274cc6311SAndrii Nakryiko 	note->base_addr = addrs[1];
118374cc6311SAndrii Nakryiko 	note->sema_addr = addrs[2];
118474cc6311SAndrii Nakryiko 
118574cc6311SAndrii Nakryiko 	return 0;
118674cc6311SAndrii Nakryiko }
118774cc6311SAndrii Nakryiko 
118898e678e9SPuranjay Mohan static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz);
118974cc6311SAndrii Nakryiko 
parse_usdt_spec(struct usdt_spec * spec,const struct usdt_note * note,__u64 usdt_cookie)11905af25a41SPu Lehui static int parse_usdt_spec(struct usdt_spec *spec, const struct usdt_note *note, __u64 usdt_cookie)
119174cc6311SAndrii Nakryiko {
119298e678e9SPuranjay Mohan 	struct usdt_arg_spec *arg;
119374cc6311SAndrii Nakryiko 	const char *s;
119498e678e9SPuranjay Mohan 	int arg_sz, len;
119574cc6311SAndrii Nakryiko 
119674cc6311SAndrii Nakryiko 	spec->usdt_cookie = usdt_cookie;
119774cc6311SAndrii Nakryiko 	spec->arg_cnt = 0;
119874cc6311SAndrii Nakryiko 
119974cc6311SAndrii Nakryiko 	s = note->args;
120074cc6311SAndrii Nakryiko 	while (s[0]) {
120174cc6311SAndrii Nakryiko 		if (spec->arg_cnt >= USDT_MAX_ARG_CNT) {
120274cc6311SAndrii Nakryiko 			pr_warn("usdt: too many USDT arguments (> %d) for '%s:%s' with args spec '%s'\n",
120374cc6311SAndrii Nakryiko 				USDT_MAX_ARG_CNT, note->provider, note->name, note->args);
120474cc6311SAndrii Nakryiko 			return -E2BIG;
120574cc6311SAndrii Nakryiko 		}
120674cc6311SAndrii Nakryiko 
120798e678e9SPuranjay Mohan 		arg = &spec->args[spec->arg_cnt];
120898e678e9SPuranjay Mohan 		len = parse_usdt_arg(s, spec->arg_cnt, arg, &arg_sz);
120974cc6311SAndrii Nakryiko 		if (len < 0)
121074cc6311SAndrii Nakryiko 			return len;
121174cc6311SAndrii Nakryiko 
121298e678e9SPuranjay Mohan 		arg->arg_signed = arg_sz < 0;
121398e678e9SPuranjay Mohan 		if (arg_sz < 0)
121498e678e9SPuranjay Mohan 			arg_sz = -arg_sz;
121598e678e9SPuranjay Mohan 
121698e678e9SPuranjay Mohan 		switch (arg_sz) {
121798e678e9SPuranjay Mohan 		case 1: case 2: case 4: case 8:
121898e678e9SPuranjay Mohan 			arg->arg_bitshift = 64 - arg_sz * 8;
121998e678e9SPuranjay Mohan 			break;
122098e678e9SPuranjay Mohan 		default:
122198e678e9SPuranjay Mohan 			pr_warn("usdt: unsupported arg #%d (spec '%s') size: %d\n",
122298e678e9SPuranjay Mohan 				spec->arg_cnt, s, arg_sz);
122398e678e9SPuranjay Mohan 			return -EINVAL;
122498e678e9SPuranjay Mohan 		}
122598e678e9SPuranjay Mohan 
122674cc6311SAndrii Nakryiko 		s += len;
122774cc6311SAndrii Nakryiko 		spec->arg_cnt++;
122874cc6311SAndrii Nakryiko 	}
122974cc6311SAndrii Nakryiko 
123074cc6311SAndrii Nakryiko 	return 0;
123174cc6311SAndrii Nakryiko }
123274cc6311SAndrii Nakryiko 
12334c59e584SAndrii Nakryiko /* Architecture-specific logic for parsing USDT argument location specs */
12344c59e584SAndrii Nakryiko 
12354c59e584SAndrii Nakryiko #if defined(__x86_64__) || defined(__i386__)
12364c59e584SAndrii Nakryiko 
calc_pt_regs_off(const char * reg_name)12374c59e584SAndrii Nakryiko static int calc_pt_regs_off(const char *reg_name)
12384c59e584SAndrii Nakryiko {
12394c59e584SAndrii Nakryiko 	static struct {
12404c59e584SAndrii Nakryiko 		const char *names[4];
12414c59e584SAndrii Nakryiko 		size_t pt_regs_off;
12424c59e584SAndrii Nakryiko 	} reg_map[] = {
1243ded6dffaSAndrii Nakryiko #ifdef __x86_64__
12444c59e584SAndrii Nakryiko #define reg_off(reg64, reg32) offsetof(struct pt_regs, reg64)
12454c59e584SAndrii Nakryiko #else
12464c59e584SAndrii Nakryiko #define reg_off(reg64, reg32) offsetof(struct pt_regs, reg32)
12474c59e584SAndrii Nakryiko #endif
12484c59e584SAndrii Nakryiko 		{ {"rip", "eip", "", ""}, reg_off(rip, eip) },
12494c59e584SAndrii Nakryiko 		{ {"rax", "eax", "ax", "al"}, reg_off(rax, eax) },
12504c59e584SAndrii Nakryiko 		{ {"rbx", "ebx", "bx", "bl"}, reg_off(rbx, ebx) },
12514c59e584SAndrii Nakryiko 		{ {"rcx", "ecx", "cx", "cl"}, reg_off(rcx, ecx) },
12524c59e584SAndrii Nakryiko 		{ {"rdx", "edx", "dx", "dl"}, reg_off(rdx, edx) },
12534c59e584SAndrii Nakryiko 		{ {"rsi", "esi", "si", "sil"}, reg_off(rsi, esi) },
12544c59e584SAndrii Nakryiko 		{ {"rdi", "edi", "di", "dil"}, reg_off(rdi, edi) },
12554c59e584SAndrii Nakryiko 		{ {"rbp", "ebp", "bp", "bpl"}, reg_off(rbp, ebp) },
12564c59e584SAndrii Nakryiko 		{ {"rsp", "esp", "sp", "spl"}, reg_off(rsp, esp) },
12574c59e584SAndrii Nakryiko #undef reg_off
1258ded6dffaSAndrii Nakryiko #ifdef __x86_64__
12594c59e584SAndrii Nakryiko 		{ {"r8", "r8d", "r8w", "r8b"}, offsetof(struct pt_regs, r8) },
12604c59e584SAndrii Nakryiko 		{ {"r9", "r9d", "r9w", "r9b"}, offsetof(struct pt_regs, r9) },
12614c59e584SAndrii Nakryiko 		{ {"r10", "r10d", "r10w", "r10b"}, offsetof(struct pt_regs, r10) },
12624c59e584SAndrii Nakryiko 		{ {"r11", "r11d", "r11w", "r11b"}, offsetof(struct pt_regs, r11) },
12634c59e584SAndrii Nakryiko 		{ {"r12", "r12d", "r12w", "r12b"}, offsetof(struct pt_regs, r12) },
12644c59e584SAndrii Nakryiko 		{ {"r13", "r13d", "r13w", "r13b"}, offsetof(struct pt_regs, r13) },
12654c59e584SAndrii Nakryiko 		{ {"r14", "r14d", "r14w", "r14b"}, offsetof(struct pt_regs, r14) },
12664c59e584SAndrii Nakryiko 		{ {"r15", "r15d", "r15w", "r15b"}, offsetof(struct pt_regs, r15) },
12674c59e584SAndrii Nakryiko #endif
12684c59e584SAndrii Nakryiko 	};
12694c59e584SAndrii Nakryiko 	int i, j;
12704c59e584SAndrii Nakryiko 
12714c59e584SAndrii Nakryiko 	for (i = 0; i < ARRAY_SIZE(reg_map); i++) {
12724c59e584SAndrii Nakryiko 		for (j = 0; j < ARRAY_SIZE(reg_map[i].names); j++) {
12734c59e584SAndrii Nakryiko 			if (strcmp(reg_name, reg_map[i].names[j]) == 0)
12744c59e584SAndrii Nakryiko 				return reg_map[i].pt_regs_off;
12754c59e584SAndrii Nakryiko 		}
12764c59e584SAndrii Nakryiko 	}
12774c59e584SAndrii Nakryiko 
12784c59e584SAndrii Nakryiko 	pr_warn("usdt: unrecognized register '%s'\n", reg_name);
12794c59e584SAndrii Nakryiko 	return -ENOENT;
12804c59e584SAndrii Nakryiko }
12814c59e584SAndrii Nakryiko 
parse_usdt_arg(const char * arg_str,int arg_num,struct usdt_arg_spec * arg,int * arg_sz)128298e678e9SPuranjay Mohan static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
12834c59e584SAndrii Nakryiko {
1284d9740535SXu Kuohai 	char reg_name[16];
128598e678e9SPuranjay Mohan 	int len, reg_off;
12864c59e584SAndrii Nakryiko 	long off;
12874c59e584SAndrii Nakryiko 
128898e678e9SPuranjay Mohan 	if (sscanf(arg_str, " %d @ %ld ( %%%15[^)] ) %n", arg_sz, &off, reg_name, &len) == 3) {
12894c59e584SAndrii Nakryiko 		/* Memory dereference case, e.g., -4@-20(%rbp) */
12904c59e584SAndrii Nakryiko 		arg->arg_type = USDT_ARG_REG_DEREF;
12914c59e584SAndrii Nakryiko 		arg->val_off = off;
12924c59e584SAndrii Nakryiko 		reg_off = calc_pt_regs_off(reg_name);
12934c59e584SAndrii Nakryiko 		if (reg_off < 0)
12944c59e584SAndrii Nakryiko 			return reg_off;
12954c59e584SAndrii Nakryiko 		arg->reg_off = reg_off;
129698e678e9SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ ( %%%15[^)] ) %n", arg_sz, reg_name, &len) == 2) {
1297c21dc529STimo Hunziker 		/* Memory dereference case without offset, e.g., 8@(%rsp) */
1298c21dc529STimo Hunziker 		arg->arg_type = USDT_ARG_REG_DEREF;
1299c21dc529STimo Hunziker 		arg->val_off = 0;
1300c21dc529STimo Hunziker 		reg_off = calc_pt_regs_off(reg_name);
1301c21dc529STimo Hunziker 		if (reg_off < 0)
1302c21dc529STimo Hunziker 			return reg_off;
1303c21dc529STimo Hunziker 		arg->reg_off = reg_off;
130498e678e9SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ %%%15s %n", arg_sz, reg_name, &len) == 2) {
13054c59e584SAndrii Nakryiko 		/* Register read case, e.g., -4@%eax */
13064c59e584SAndrii Nakryiko 		arg->arg_type = USDT_ARG_REG;
13074c59e584SAndrii Nakryiko 		arg->val_off = 0;
13084c59e584SAndrii Nakryiko 
13094c59e584SAndrii Nakryiko 		reg_off = calc_pt_regs_off(reg_name);
13104c59e584SAndrii Nakryiko 		if (reg_off < 0)
13114c59e584SAndrii Nakryiko 			return reg_off;
13124c59e584SAndrii Nakryiko 		arg->reg_off = reg_off;
131398e678e9SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ $%ld %n", arg_sz, &off, &len) == 2) {
13144c59e584SAndrii Nakryiko 		/* Constant value case, e.g., 4@$71 */
13154c59e584SAndrii Nakryiko 		arg->arg_type = USDT_ARG_CONST;
13164c59e584SAndrii Nakryiko 		arg->val_off = off;
13174c59e584SAndrii Nakryiko 		arg->reg_off = 0;
13184c59e584SAndrii Nakryiko 	} else {
13194c59e584SAndrii Nakryiko 		pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
13204c59e584SAndrii Nakryiko 		return -EINVAL;
13214c59e584SAndrii Nakryiko 	}
13224c59e584SAndrii Nakryiko 
13234c59e584SAndrii Nakryiko 	return len;
13244c59e584SAndrii Nakryiko }
13254c59e584SAndrii Nakryiko 
1326bd022685SIlya Leoshkevich #elif defined(__s390x__)
1327bd022685SIlya Leoshkevich 
1328bd022685SIlya Leoshkevich /* Do not support __s390__ for now, since user_pt_regs is broken with -m31. */
1329bd022685SIlya Leoshkevich 
parse_usdt_arg(const char * arg_str,int arg_num,struct usdt_arg_spec * arg,int * arg_sz)133098e678e9SPuranjay Mohan static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
1331bd022685SIlya Leoshkevich {
1332bd022685SIlya Leoshkevich 	unsigned int reg;
133398e678e9SPuranjay Mohan 	int len;
1334bd022685SIlya Leoshkevich 	long off;
1335bd022685SIlya Leoshkevich 
133698e678e9SPuranjay Mohan 	if (sscanf(arg_str, " %d @ %ld ( %%r%u ) %n", arg_sz, &off, &reg, &len) == 3) {
1337bd022685SIlya Leoshkevich 		/* Memory dereference case, e.g., -2@-28(%r15) */
1338bd022685SIlya Leoshkevich 		arg->arg_type = USDT_ARG_REG_DEREF;
1339bd022685SIlya Leoshkevich 		arg->val_off = off;
1340bd022685SIlya Leoshkevich 		if (reg > 15) {
1341bd022685SIlya Leoshkevich 			pr_warn("usdt: unrecognized register '%%r%u'\n", reg);
1342bd022685SIlya Leoshkevich 			return -EINVAL;
1343bd022685SIlya Leoshkevich 		}
1344bd022685SIlya Leoshkevich 		arg->reg_off = offsetof(user_pt_regs, gprs[reg]);
134598e678e9SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ %%r%u %n", arg_sz, &reg, &len) == 2) {
1346bd022685SIlya Leoshkevich 		/* Register read case, e.g., -8@%r0 */
1347bd022685SIlya Leoshkevich 		arg->arg_type = USDT_ARG_REG;
1348bd022685SIlya Leoshkevich 		arg->val_off = 0;
1349bd022685SIlya Leoshkevich 		if (reg > 15) {
1350bd022685SIlya Leoshkevich 			pr_warn("usdt: unrecognized register '%%r%u'\n", reg);
1351bd022685SIlya Leoshkevich 			return -EINVAL;
1352bd022685SIlya Leoshkevich 		}
1353bd022685SIlya Leoshkevich 		arg->reg_off = offsetof(user_pt_regs, gprs[reg]);
135498e678e9SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ %ld %n", arg_sz, &off, &len) == 2) {
1355bd022685SIlya Leoshkevich 		/* Constant value case, e.g., 4@71 */
1356bd022685SIlya Leoshkevich 		arg->arg_type = USDT_ARG_CONST;
1357bd022685SIlya Leoshkevich 		arg->val_off = off;
1358bd022685SIlya Leoshkevich 		arg->reg_off = 0;
1359bd022685SIlya Leoshkevich 	} else {
1360bd022685SIlya Leoshkevich 		pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
1361bd022685SIlya Leoshkevich 		return -EINVAL;
1362bd022685SIlya Leoshkevich 	}
1363bd022685SIlya Leoshkevich 
1364bd022685SIlya Leoshkevich 	return len;
1365bd022685SIlya Leoshkevich }
1366bd022685SIlya Leoshkevich 
13670f861992SAlan Maguire #elif defined(__aarch64__)
13680f861992SAlan Maguire 
calc_pt_regs_off(const char * reg_name)13690f861992SAlan Maguire static int calc_pt_regs_off(const char *reg_name)
13700f861992SAlan Maguire {
13710f861992SAlan Maguire 	int reg_num;
13720f861992SAlan Maguire 
13730f861992SAlan Maguire 	if (sscanf(reg_name, "x%d", &reg_num) == 1) {
13740f861992SAlan Maguire 		if (reg_num >= 0 && reg_num < 31)
13750f861992SAlan Maguire 			return offsetof(struct user_pt_regs, regs[reg_num]);
13760f861992SAlan Maguire 	} else if (strcmp(reg_name, "sp") == 0) {
13770f861992SAlan Maguire 		return offsetof(struct user_pt_regs, sp);
13780f861992SAlan Maguire 	}
13790f861992SAlan Maguire 	pr_warn("usdt: unrecognized register '%s'\n", reg_name);
13800f861992SAlan Maguire 	return -ENOENT;
13810f861992SAlan Maguire }
13820f861992SAlan Maguire 
parse_usdt_arg(const char * arg_str,int arg_num,struct usdt_arg_spec * arg,int * arg_sz)138398e678e9SPuranjay Mohan static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
13840f861992SAlan Maguire {
13850dc9254eSXu Kuohai 	char reg_name[16];
138698e678e9SPuranjay Mohan 	int len, reg_off;
13870f861992SAlan Maguire 	long off;
13880f861992SAlan Maguire 
138998e678e9SPuranjay Mohan 	if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] , %ld ] %n", arg_sz, reg_name, &off, &len) == 3) {
13900f861992SAlan Maguire 		/* Memory dereference case, e.g., -4@[sp, 96] */
13910f861992SAlan Maguire 		arg->arg_type = USDT_ARG_REG_DEREF;
13920f861992SAlan Maguire 		arg->val_off = off;
13930f861992SAlan Maguire 		reg_off = calc_pt_regs_off(reg_name);
13940f861992SAlan Maguire 		if (reg_off < 0)
13950f861992SAlan Maguire 			return reg_off;
13960f861992SAlan Maguire 		arg->reg_off = reg_off;
139798e678e9SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] ] %n", arg_sz, reg_name, &len) == 2) {
13980f861992SAlan Maguire 		/* Memory dereference case, e.g., -4@[sp] */
13990f861992SAlan Maguire 		arg->arg_type = USDT_ARG_REG_DEREF;
14000f861992SAlan Maguire 		arg->val_off = 0;
14010f861992SAlan Maguire 		reg_off = calc_pt_regs_off(reg_name);
14020f861992SAlan Maguire 		if (reg_off < 0)
14030f861992SAlan Maguire 			return reg_off;
14040f861992SAlan Maguire 		arg->reg_off = reg_off;
140598e678e9SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ %ld %n", arg_sz, &off, &len) == 2) {
14060f861992SAlan Maguire 		/* Constant value case, e.g., 4@5 */
14070f861992SAlan Maguire 		arg->arg_type = USDT_ARG_CONST;
14080f861992SAlan Maguire 		arg->val_off = off;
14090f861992SAlan Maguire 		arg->reg_off = 0;
141098e678e9SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ %15[a-z0-9] %n", arg_sz, reg_name, &len) == 2) {
14110f861992SAlan Maguire 		/* Register read case, e.g., -8@x4 */
14120f861992SAlan Maguire 		arg->arg_type = USDT_ARG_REG;
14130f861992SAlan Maguire 		arg->val_off = 0;
14140f861992SAlan Maguire 		reg_off = calc_pt_regs_off(reg_name);
14150f861992SAlan Maguire 		if (reg_off < 0)
14160f861992SAlan Maguire 			return reg_off;
14170f861992SAlan Maguire 		arg->reg_off = reg_off;
14180f861992SAlan Maguire 	} else {
14190f861992SAlan Maguire 		pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
14200f861992SAlan Maguire 		return -EINVAL;
14210f861992SAlan Maguire 	}
14220f861992SAlan Maguire 
14230f861992SAlan Maguire 	return len;
14240f861992SAlan Maguire }
14250f861992SAlan Maguire 
142658ca8b05SPu Lehui #elif defined(__riscv)
142758ca8b05SPu Lehui 
calc_pt_regs_off(const char * reg_name)142858ca8b05SPu Lehui static int calc_pt_regs_off(const char *reg_name)
142958ca8b05SPu Lehui {
143058ca8b05SPu Lehui 	static struct {
143158ca8b05SPu Lehui 		const char *name;
143258ca8b05SPu Lehui 		size_t pt_regs_off;
143358ca8b05SPu Lehui 	} reg_map[] = {
143458ca8b05SPu Lehui 		{ "ra", offsetof(struct user_regs_struct, ra) },
143558ca8b05SPu Lehui 		{ "sp", offsetof(struct user_regs_struct, sp) },
143658ca8b05SPu Lehui 		{ "gp", offsetof(struct user_regs_struct, gp) },
143758ca8b05SPu Lehui 		{ "tp", offsetof(struct user_regs_struct, tp) },
143858ca8b05SPu Lehui 		{ "a0", offsetof(struct user_regs_struct, a0) },
143958ca8b05SPu Lehui 		{ "a1", offsetof(struct user_regs_struct, a1) },
144058ca8b05SPu Lehui 		{ "a2", offsetof(struct user_regs_struct, a2) },
144158ca8b05SPu Lehui 		{ "a3", offsetof(struct user_regs_struct, a3) },
144258ca8b05SPu Lehui 		{ "a4", offsetof(struct user_regs_struct, a4) },
144358ca8b05SPu Lehui 		{ "a5", offsetof(struct user_regs_struct, a5) },
144458ca8b05SPu Lehui 		{ "a6", offsetof(struct user_regs_struct, a6) },
144558ca8b05SPu Lehui 		{ "a7", offsetof(struct user_regs_struct, a7) },
144658ca8b05SPu Lehui 		{ "s0", offsetof(struct user_regs_struct, s0) },
144758ca8b05SPu Lehui 		{ "s1", offsetof(struct user_regs_struct, s1) },
144858ca8b05SPu Lehui 		{ "s2", offsetof(struct user_regs_struct, s2) },
144958ca8b05SPu Lehui 		{ "s3", offsetof(struct user_regs_struct, s3) },
145058ca8b05SPu Lehui 		{ "s4", offsetof(struct user_regs_struct, s4) },
145158ca8b05SPu Lehui 		{ "s5", offsetof(struct user_regs_struct, s5) },
145258ca8b05SPu Lehui 		{ "s6", offsetof(struct user_regs_struct, s6) },
145358ca8b05SPu Lehui 		{ "s7", offsetof(struct user_regs_struct, s7) },
145458ca8b05SPu Lehui 		{ "s8", offsetof(struct user_regs_struct, rv_s8) },
145558ca8b05SPu Lehui 		{ "s9", offsetof(struct user_regs_struct, s9) },
145658ca8b05SPu Lehui 		{ "s10", offsetof(struct user_regs_struct, s10) },
145758ca8b05SPu Lehui 		{ "s11", offsetof(struct user_regs_struct, s11) },
145858ca8b05SPu Lehui 		{ "t0", offsetof(struct user_regs_struct, t0) },
145958ca8b05SPu Lehui 		{ "t1", offsetof(struct user_regs_struct, t1) },
146058ca8b05SPu Lehui 		{ "t2", offsetof(struct user_regs_struct, t2) },
146158ca8b05SPu Lehui 		{ "t3", offsetof(struct user_regs_struct, t3) },
146258ca8b05SPu Lehui 		{ "t4", offsetof(struct user_regs_struct, t4) },
146358ca8b05SPu Lehui 		{ "t5", offsetof(struct user_regs_struct, t5) },
146458ca8b05SPu Lehui 		{ "t6", offsetof(struct user_regs_struct, t6) },
146558ca8b05SPu Lehui 	};
146658ca8b05SPu Lehui 	int i;
146758ca8b05SPu Lehui 
146858ca8b05SPu Lehui 	for (i = 0; i < ARRAY_SIZE(reg_map); i++) {
146958ca8b05SPu Lehui 		if (strcmp(reg_name, reg_map[i].name) == 0)
147058ca8b05SPu Lehui 			return reg_map[i].pt_regs_off;
147158ca8b05SPu Lehui 	}
147258ca8b05SPu Lehui 
147358ca8b05SPu Lehui 	pr_warn("usdt: unrecognized register '%s'\n", reg_name);
147458ca8b05SPu Lehui 	return -ENOENT;
147558ca8b05SPu Lehui }
147658ca8b05SPu Lehui 
parse_usdt_arg(const char * arg_str,int arg_num,struct usdt_arg_spec * arg,int * arg_sz)147798e678e9SPuranjay Mohan static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
147858ca8b05SPu Lehui {
1479d9740535SXu Kuohai 	char reg_name[16];
148098e678e9SPuranjay Mohan 	int len, reg_off;
148158ca8b05SPu Lehui 	long off;
148258ca8b05SPu Lehui 
148398e678e9SPuranjay Mohan 	if (sscanf(arg_str, " %d @ %ld ( %15[a-z0-9] ) %n", arg_sz, &off, reg_name, &len) == 3) {
148458ca8b05SPu Lehui 		/* Memory dereference case, e.g., -8@-88(s0) */
148558ca8b05SPu Lehui 		arg->arg_type = USDT_ARG_REG_DEREF;
148658ca8b05SPu Lehui 		arg->val_off = off;
148758ca8b05SPu Lehui 		reg_off = calc_pt_regs_off(reg_name);
148858ca8b05SPu Lehui 		if (reg_off < 0)
148958ca8b05SPu Lehui 			return reg_off;
149058ca8b05SPu Lehui 		arg->reg_off = reg_off;
149198e678e9SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ %ld %n", arg_sz, &off, &len) == 2) {
149258ca8b05SPu Lehui 		/* Constant value case, e.g., 4@5 */
149358ca8b05SPu Lehui 		arg->arg_type = USDT_ARG_CONST;
149458ca8b05SPu Lehui 		arg->val_off = off;
149558ca8b05SPu Lehui 		arg->reg_off = 0;
149698e678e9SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ %15[a-z0-9] %n", arg_sz, reg_name, &len) == 2) {
149758ca8b05SPu Lehui 		/* Register read case, e.g., -8@a1 */
149858ca8b05SPu Lehui 		arg->arg_type = USDT_ARG_REG;
149958ca8b05SPu Lehui 		arg->val_off = 0;
150058ca8b05SPu Lehui 		reg_off = calc_pt_regs_off(reg_name);
150158ca8b05SPu Lehui 		if (reg_off < 0)
150258ca8b05SPu Lehui 			return reg_off;
150358ca8b05SPu Lehui 		arg->reg_off = reg_off;
150458ca8b05SPu Lehui 	} else {
150558ca8b05SPu Lehui 		pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
150658ca8b05SPu Lehui 		return -EINVAL;
150758ca8b05SPu Lehui 	}
150858ca8b05SPu Lehui 
150958ca8b05SPu Lehui 	return len;
151058ca8b05SPu Lehui }
151158ca8b05SPu Lehui 
1512720d93b6SPuranjay Mohan #elif defined(__arm__)
1513720d93b6SPuranjay Mohan 
calc_pt_regs_off(const char * reg_name)1514720d93b6SPuranjay Mohan static int calc_pt_regs_off(const char *reg_name)
1515720d93b6SPuranjay Mohan {
1516720d93b6SPuranjay Mohan 	static struct {
1517720d93b6SPuranjay Mohan 		const char *name;
1518720d93b6SPuranjay Mohan 		size_t pt_regs_off;
1519720d93b6SPuranjay Mohan 	} reg_map[] = {
1520720d93b6SPuranjay Mohan 		{ "r0", offsetof(struct pt_regs, uregs[0]) },
1521720d93b6SPuranjay Mohan 		{ "r1", offsetof(struct pt_regs, uregs[1]) },
1522720d93b6SPuranjay Mohan 		{ "r2", offsetof(struct pt_regs, uregs[2]) },
1523720d93b6SPuranjay Mohan 		{ "r3", offsetof(struct pt_regs, uregs[3]) },
1524720d93b6SPuranjay Mohan 		{ "r4", offsetof(struct pt_regs, uregs[4]) },
1525720d93b6SPuranjay Mohan 		{ "r5", offsetof(struct pt_regs, uregs[5]) },
1526720d93b6SPuranjay Mohan 		{ "r6", offsetof(struct pt_regs, uregs[6]) },
1527720d93b6SPuranjay Mohan 		{ "r7", offsetof(struct pt_regs, uregs[7]) },
1528720d93b6SPuranjay Mohan 		{ "r8", offsetof(struct pt_regs, uregs[8]) },
1529720d93b6SPuranjay Mohan 		{ "r9", offsetof(struct pt_regs, uregs[9]) },
1530720d93b6SPuranjay Mohan 		{ "r10", offsetof(struct pt_regs, uregs[10]) },
1531720d93b6SPuranjay Mohan 		{ "fp", offsetof(struct pt_regs, uregs[11]) },
1532720d93b6SPuranjay Mohan 		{ "ip", offsetof(struct pt_regs, uregs[12]) },
1533720d93b6SPuranjay Mohan 		{ "sp", offsetof(struct pt_regs, uregs[13]) },
1534720d93b6SPuranjay Mohan 		{ "lr", offsetof(struct pt_regs, uregs[14]) },
1535720d93b6SPuranjay Mohan 		{ "pc", offsetof(struct pt_regs, uregs[15]) },
1536720d93b6SPuranjay Mohan 	};
1537720d93b6SPuranjay Mohan 	int i;
1538720d93b6SPuranjay Mohan 
1539720d93b6SPuranjay Mohan 	for (i = 0; i < ARRAY_SIZE(reg_map); i++) {
1540720d93b6SPuranjay Mohan 		if (strcmp(reg_name, reg_map[i].name) == 0)
1541720d93b6SPuranjay Mohan 			return reg_map[i].pt_regs_off;
1542720d93b6SPuranjay Mohan 	}
1543720d93b6SPuranjay Mohan 
1544720d93b6SPuranjay Mohan 	pr_warn("usdt: unrecognized register '%s'\n", reg_name);
1545720d93b6SPuranjay Mohan 	return -ENOENT;
1546720d93b6SPuranjay Mohan }
1547720d93b6SPuranjay Mohan 
parse_usdt_arg(const char * arg_str,int arg_num,struct usdt_arg_spec * arg,int * arg_sz)1548720d93b6SPuranjay Mohan static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
1549720d93b6SPuranjay Mohan {
1550720d93b6SPuranjay Mohan 	char reg_name[16];
1551720d93b6SPuranjay Mohan 	int len, reg_off;
1552720d93b6SPuranjay Mohan 	long off;
1553720d93b6SPuranjay Mohan 
1554720d93b6SPuranjay Mohan 	if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] , #%ld ] %n",
1555720d93b6SPuranjay Mohan 		   arg_sz, reg_name, &off, &len) == 3) {
1556720d93b6SPuranjay Mohan 		/* Memory dereference case, e.g., -4@[fp, #96] */
1557720d93b6SPuranjay Mohan 		arg->arg_type = USDT_ARG_REG_DEREF;
1558720d93b6SPuranjay Mohan 		arg->val_off = off;
1559720d93b6SPuranjay Mohan 		reg_off = calc_pt_regs_off(reg_name);
1560720d93b6SPuranjay Mohan 		if (reg_off < 0)
1561720d93b6SPuranjay Mohan 			return reg_off;
1562720d93b6SPuranjay Mohan 		arg->reg_off = reg_off;
1563720d93b6SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] ] %n", arg_sz, reg_name, &len) == 2) {
1564720d93b6SPuranjay Mohan 		/* Memory dereference case, e.g., -4@[sp] */
1565720d93b6SPuranjay Mohan 		arg->arg_type = USDT_ARG_REG_DEREF;
1566720d93b6SPuranjay Mohan 		arg->val_off = 0;
1567720d93b6SPuranjay Mohan 		reg_off = calc_pt_regs_off(reg_name);
1568720d93b6SPuranjay Mohan 		if (reg_off < 0)
1569720d93b6SPuranjay Mohan 			return reg_off;
1570720d93b6SPuranjay Mohan 		arg->reg_off = reg_off;
1571720d93b6SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ #%ld %n", arg_sz, &off, &len) == 2) {
1572720d93b6SPuranjay Mohan 		/* Constant value case, e.g., 4@#5 */
1573720d93b6SPuranjay Mohan 		arg->arg_type = USDT_ARG_CONST;
1574720d93b6SPuranjay Mohan 		arg->val_off = off;
1575720d93b6SPuranjay Mohan 		arg->reg_off = 0;
1576720d93b6SPuranjay Mohan 	} else if (sscanf(arg_str, " %d @ %15[a-z0-9] %n", arg_sz, reg_name, &len) == 2) {
1577720d93b6SPuranjay Mohan 		/* Register read case, e.g., -8@r4 */
1578720d93b6SPuranjay Mohan 		arg->arg_type = USDT_ARG_REG;
1579720d93b6SPuranjay Mohan 		arg->val_off = 0;
1580720d93b6SPuranjay Mohan 		reg_off = calc_pt_regs_off(reg_name);
1581720d93b6SPuranjay Mohan 		if (reg_off < 0)
1582720d93b6SPuranjay Mohan 			return reg_off;
1583720d93b6SPuranjay Mohan 		arg->reg_off = reg_off;
1584720d93b6SPuranjay Mohan 	} else {
1585720d93b6SPuranjay Mohan 		pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
1586720d93b6SPuranjay Mohan 		return -EINVAL;
1587720d93b6SPuranjay Mohan 	}
1588720d93b6SPuranjay Mohan 
1589720d93b6SPuranjay Mohan 	return len;
1590720d93b6SPuranjay Mohan }
1591720d93b6SPuranjay Mohan 
15924c59e584SAndrii Nakryiko #else
15934c59e584SAndrii Nakryiko 
parse_usdt_arg(const char * arg_str,int arg_num,struct usdt_arg_spec * arg,int * arg_sz)159498e678e9SPuranjay Mohan static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
159574cc6311SAndrii Nakryiko {
159674cc6311SAndrii Nakryiko 	pr_warn("usdt: libbpf doesn't support USDTs on current architecture\n");
159774cc6311SAndrii Nakryiko 	return -ENOTSUP;
159874cc6311SAndrii Nakryiko }
15994c59e584SAndrii Nakryiko 
16004c59e584SAndrii Nakryiko #endif
1601