162306a36Sopenharmony_ci// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
262306a36Sopenharmony_ci/* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
362306a36Sopenharmony_ci#include <ctype.h>
462306a36Sopenharmony_ci#include <stdio.h>
562306a36Sopenharmony_ci#include <stdlib.h>
662306a36Sopenharmony_ci#include <string.h>
762306a36Sopenharmony_ci#include <libelf.h>
862306a36Sopenharmony_ci#include <gelf.h>
962306a36Sopenharmony_ci#include <unistd.h>
1062306a36Sopenharmony_ci#include <linux/ptrace.h>
1162306a36Sopenharmony_ci#include <linux/kernel.h>
1262306a36Sopenharmony_ci
1362306a36Sopenharmony_ci/* s8 will be marked as poison while it's a reg of riscv */
1462306a36Sopenharmony_ci#if defined(__riscv)
1562306a36Sopenharmony_ci#define rv_s8 s8
1662306a36Sopenharmony_ci#endif
1762306a36Sopenharmony_ci
1862306a36Sopenharmony_ci#include "bpf.h"
1962306a36Sopenharmony_ci#include "libbpf.h"
2062306a36Sopenharmony_ci#include "libbpf_common.h"
2162306a36Sopenharmony_ci#include "libbpf_internal.h"
2262306a36Sopenharmony_ci#include "hashmap.h"
2362306a36Sopenharmony_ci
2462306a36Sopenharmony_ci/* libbpf's USDT support consists of BPF-side state/code and user-space
2562306a36Sopenharmony_ci * state/code working together in concert. BPF-side parts are defined in
2662306a36Sopenharmony_ci * usdt.bpf.h header library. User-space state is encapsulated by struct
2762306a36Sopenharmony_ci * usdt_manager and all the supporting code centered around usdt_manager.
2862306a36Sopenharmony_ci *
2962306a36Sopenharmony_ci * usdt.bpf.h defines two BPF maps that usdt_manager expects: USDT spec map
3062306a36Sopenharmony_ci * and IP-to-spec-ID map, which is auxiliary map necessary for kernels that
3162306a36Sopenharmony_ci * don't support BPF cookie (see below). These two maps are implicitly
3262306a36Sopenharmony_ci * embedded into user's end BPF object file when user's code included
3362306a36Sopenharmony_ci * usdt.bpf.h. This means that libbpf doesn't do anything special to create
3462306a36Sopenharmony_ci * these USDT support maps. They are created by normal libbpf logic of
3562306a36Sopenharmony_ci * instantiating BPF maps when opening and loading BPF object.
3662306a36Sopenharmony_ci *
3762306a36Sopenharmony_ci * As such, libbpf is basically unaware of the need to do anything
3862306a36Sopenharmony_ci * USDT-related until the very first call to bpf_program__attach_usdt(), which
3962306a36Sopenharmony_ci * can be called by user explicitly or happen automatically during skeleton
4062306a36Sopenharmony_ci * attach (or, equivalently, through generic bpf_program__attach() call). At
4162306a36Sopenharmony_ci * this point, libbpf will instantiate and initialize struct usdt_manager and
4262306a36Sopenharmony_ci * store it in bpf_object. USDT manager is per-BPF object construct, as each
4362306a36Sopenharmony_ci * independent BPF object might or might not have USDT programs, and thus all
4462306a36Sopenharmony_ci * the expected USDT-related state. There is no coordination between two
4562306a36Sopenharmony_ci * bpf_object in parts of USDT attachment, they are oblivious of each other's
4662306a36Sopenharmony_ci * existence and libbpf is just oblivious, dealing with bpf_object-specific
4762306a36Sopenharmony_ci * USDT state.
4862306a36Sopenharmony_ci *
4962306a36Sopenharmony_ci * Quick crash course on USDTs.
5062306a36Sopenharmony_ci *
5162306a36Sopenharmony_ci * From user-space application's point of view, USDT is essentially just
5262306a36Sopenharmony_ci * a slightly special function call that normally has zero overhead, unless it
5362306a36Sopenharmony_ci * is being traced by some external entity (e.g, BPF-based tool). Here's how
5462306a36Sopenharmony_ci * a typical application can trigger USDT probe:
5562306a36Sopenharmony_ci *
5662306a36Sopenharmony_ci * #include <sys/sdt.h>  // provided by systemtap-sdt-devel package
5762306a36Sopenharmony_ci * // folly also provide similar functionality in folly/tracing/StaticTracepoint.h
5862306a36Sopenharmony_ci *
5962306a36Sopenharmony_ci * STAP_PROBE3(my_usdt_provider, my_usdt_probe_name, 123, x, &y);
6062306a36Sopenharmony_ci *
6162306a36Sopenharmony_ci * USDT is identified by it's <provider-name>:<probe-name> pair of names. Each
6262306a36Sopenharmony_ci * individual USDT has a fixed number of arguments (3 in the above example)
6362306a36Sopenharmony_ci * and specifies values of each argument as if it was a function call.
6462306a36Sopenharmony_ci *
6562306a36Sopenharmony_ci * USDT call is actually not a function call, but is instead replaced by
6662306a36Sopenharmony_ci * a single NOP instruction (thus zero overhead, effectively). But in addition
6762306a36Sopenharmony_ci * to that, those USDT macros generate special SHT_NOTE ELF records in
6862306a36Sopenharmony_ci * .note.stapsdt ELF section. Here's an example USDT definition as emitted by
6962306a36Sopenharmony_ci * `readelf -n <binary>`:
7062306a36Sopenharmony_ci *
7162306a36Sopenharmony_ci *   stapsdt              0x00000089       NT_STAPSDT (SystemTap probe descriptors)
7262306a36Sopenharmony_ci *   Provider: test
7362306a36Sopenharmony_ci *   Name: usdt12
7462306a36Sopenharmony_ci *   Location: 0x0000000000549df3, Base: 0x00000000008effa4, Semaphore: 0x0000000000a4606e
7562306a36Sopenharmony_ci *   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
7662306a36Sopenharmony_ci *
7762306a36Sopenharmony_ci * In this case we have USDT test:usdt12 with 12 arguments.
7862306a36Sopenharmony_ci *
7962306a36Sopenharmony_ci * Location and base are offsets used to calculate absolute IP address of that
8062306a36Sopenharmony_ci * NOP instruction that kernel can replace with an interrupt instruction to
8162306a36Sopenharmony_ci * trigger instrumentation code (BPF program for all that we care about).
8262306a36Sopenharmony_ci *
8362306a36Sopenharmony_ci * Semaphore above is and optional feature. It records an address of a 2-byte
8462306a36Sopenharmony_ci * refcount variable (normally in '.probes' ELF section) used for signaling if
8562306a36Sopenharmony_ci * there is anything that is attached to USDT. This is useful for user
8662306a36Sopenharmony_ci * applications if, for example, they need to prepare some arguments that are
8762306a36Sopenharmony_ci * passed only to USDTs and preparation is expensive. By checking if USDT is
8862306a36Sopenharmony_ci * "activated", an application can avoid paying those costs unnecessarily.
8962306a36Sopenharmony_ci * Recent enough kernel has built-in support for automatically managing this
9062306a36Sopenharmony_ci * refcount, which libbpf expects and relies on. If USDT is defined without
9162306a36Sopenharmony_ci * associated semaphore, this value will be zero. See selftests for semaphore
9262306a36Sopenharmony_ci * examples.
9362306a36Sopenharmony_ci *
9462306a36Sopenharmony_ci * Arguments is the most interesting part. This USDT specification string is
9562306a36Sopenharmony_ci * providing information about all the USDT arguments and their locations. The
9662306a36Sopenharmony_ci * part before @ sign defined byte size of the argument (1, 2, 4, or 8) and
9762306a36Sopenharmony_ci * whether the argument is signed or unsigned (negative size means signed).
9862306a36Sopenharmony_ci * The part after @ sign is assembly-like definition of argument location
9962306a36Sopenharmony_ci * (see [0] for more details). Technically, assembler can provide some pretty
10062306a36Sopenharmony_ci * advanced definitions, but libbpf is currently supporting three most common
10162306a36Sopenharmony_ci * cases:
10262306a36Sopenharmony_ci *   1) immediate constant, see 5th and 9th args above (-4@$5 and -4@-9);
10362306a36Sopenharmony_ci *   2) register value, e.g., 8@%rdx, which means "unsigned 8-byte integer
10462306a36Sopenharmony_ci *      whose value is in register %rdx";
10562306a36Sopenharmony_ci *   3) memory dereference addressed by register, e.g., -4@-1204(%rbp), which
10662306a36Sopenharmony_ci *      specifies signed 32-bit integer stored at offset -1204 bytes from
10762306a36Sopenharmony_ci *      memory address stored in %rbp.
10862306a36Sopenharmony_ci *
10962306a36Sopenharmony_ci *   [0] https://sourceware.org/systemtap/wiki/UserSpaceProbeImplementation
11062306a36Sopenharmony_ci *
11162306a36Sopenharmony_ci * During attachment, libbpf parses all the relevant USDT specifications and
11262306a36Sopenharmony_ci * prepares `struct usdt_spec` (USDT spec), which is then provided to BPF-side
11362306a36Sopenharmony_ci * code through spec map. This allows BPF applications to quickly fetch the
11462306a36Sopenharmony_ci * actual value at runtime using a simple BPF-side code.
11562306a36Sopenharmony_ci *
11662306a36Sopenharmony_ci * With basics out of the way, let's go over less immediately obvious aspects
11762306a36Sopenharmony_ci * of supporting USDTs.
11862306a36Sopenharmony_ci *
11962306a36Sopenharmony_ci * First, there is no special USDT BPF program type. It is actually just
12062306a36Sopenharmony_ci * a uprobe BPF program (which for kernel, at least currently, is just a kprobe
12162306a36Sopenharmony_ci * program, so BPF_PROG_TYPE_KPROBE program type). With the only difference
12262306a36Sopenharmony_ci * that uprobe is usually attached at the function entry, while USDT will
12362306a36Sopenharmony_ci * normally will be somewhere inside the function. But it should always be
12462306a36Sopenharmony_ci * pointing to NOP instruction, which makes such uprobes the fastest uprobe
12562306a36Sopenharmony_ci * kind.
12662306a36Sopenharmony_ci *
12762306a36Sopenharmony_ci * Second, it's important to realize that such STAP_PROBEn(provider, name, ...)
12862306a36Sopenharmony_ci * macro invocations can end up being inlined many-many times, depending on
12962306a36Sopenharmony_ci * specifics of each individual user application. So single conceptual USDT
13062306a36Sopenharmony_ci * (identified by provider:name pair of identifiers) is, generally speaking,
13162306a36Sopenharmony_ci * multiple uprobe locations (USDT call sites) in different places in user
13262306a36Sopenharmony_ci * application. Further, again due to inlining, each USDT call site might end
13362306a36Sopenharmony_ci * up having the same argument #N be located in a different place. In one call
13462306a36Sopenharmony_ci * site it could be a constant, in another will end up in a register, and in
13562306a36Sopenharmony_ci * yet another could be some other register or even somewhere on the stack.
13662306a36Sopenharmony_ci *
13762306a36Sopenharmony_ci * As such, "attaching to USDT" means (in general case) attaching the same
13862306a36Sopenharmony_ci * uprobe BPF program to multiple target locations in user application, each
13962306a36Sopenharmony_ci * potentially having a completely different USDT spec associated with it.
14062306a36Sopenharmony_ci * To wire all this up together libbpf allocates a unique integer spec ID for
14162306a36Sopenharmony_ci * each unique USDT spec. Spec IDs are allocated as sequential small integers
14262306a36Sopenharmony_ci * so that they can be used as keys in array BPF map (for performance reasons).
14362306a36Sopenharmony_ci * Spec ID allocation and accounting is big part of what usdt_manager is
14462306a36Sopenharmony_ci * about. This state has to be maintained per-BPF object and coordinate
14562306a36Sopenharmony_ci * between different USDT attachments within the same BPF object.
14662306a36Sopenharmony_ci *
14762306a36Sopenharmony_ci * Spec ID is the key in spec BPF map, value is the actual USDT spec layed out
14862306a36Sopenharmony_ci * as struct usdt_spec. Each invocation of BPF program at runtime needs to
14962306a36Sopenharmony_ci * know its associated spec ID. It gets it either through BPF cookie, which
15062306a36Sopenharmony_ci * libbpf sets to spec ID during attach time, or, if kernel is too old to
15162306a36Sopenharmony_ci * support BPF cookie, through IP-to-spec-ID map that libbpf maintains in such
15262306a36Sopenharmony_ci * case. The latter means that some modes of operation can't be supported
15362306a36Sopenharmony_ci * without BPF cookie. Such mode is attaching to shared library "generically",
15462306a36Sopenharmony_ci * without specifying target process. In such case, it's impossible to
15562306a36Sopenharmony_ci * calculate absolute IP addresses for IP-to-spec-ID map, and thus such mode
15662306a36Sopenharmony_ci * is not supported without BPF cookie support.
15762306a36Sopenharmony_ci *
15862306a36Sopenharmony_ci * Note that libbpf is using BPF cookie functionality for its own internal
15962306a36Sopenharmony_ci * needs, so user itself can't rely on BPF cookie feature. To that end, libbpf
16062306a36Sopenharmony_ci * provides conceptually equivalent USDT cookie support. It's still u64
16162306a36Sopenharmony_ci * user-provided value that can be associated with USDT attachment. Note that
16262306a36Sopenharmony_ci * this will be the same value for all USDT call sites within the same single
16362306a36Sopenharmony_ci * *logical* USDT attachment. This makes sense because to user attaching to
16462306a36Sopenharmony_ci * USDT is a single BPF program triggered for singular USDT probe. The fact
16562306a36Sopenharmony_ci * that this is done at multiple actual locations is a mostly hidden
16662306a36Sopenharmony_ci * implementation details. This USDT cookie value can be fetched with
16762306a36Sopenharmony_ci * bpf_usdt_cookie(ctx) API provided by usdt.bpf.h
16862306a36Sopenharmony_ci *
16962306a36Sopenharmony_ci * Lastly, while single USDT can have tons of USDT call sites, it doesn't
17062306a36Sopenharmony_ci * necessarily have that many different USDT specs. It very well might be
17162306a36Sopenharmony_ci * that 1000 USDT call sites only need 5 different USDT specs, because all the
17262306a36Sopenharmony_ci * arguments are typically contained in a small set of registers or stack
17362306a36Sopenharmony_ci * locations. As such, it's wasteful to allocate as many USDT spec IDs as
17462306a36Sopenharmony_ci * there are USDT call sites. So libbpf tries to be frugal and performs
17562306a36Sopenharmony_ci * on-the-fly deduplication during a single USDT attachment to only allocate
17662306a36Sopenharmony_ci * the minimal required amount of unique USDT specs (and thus spec IDs). This
17762306a36Sopenharmony_ci * is trivially achieved by using USDT spec string (Arguments string from USDT
17862306a36Sopenharmony_ci * note) as a lookup key in a hashmap. USDT spec string uniquely defines
17962306a36Sopenharmony_ci * everything about how to fetch USDT arguments, so two USDT call sites
18062306a36Sopenharmony_ci * sharing USDT spec string can safely share the same USDT spec and spec ID.
18162306a36Sopenharmony_ci * Note, this spec string deduplication is happening only during the same USDT
18262306a36Sopenharmony_ci * attachment, so each USDT spec shares the same USDT cookie value. This is
18362306a36Sopenharmony_ci * not generally true for other USDT attachments within the same BPF object,
18462306a36Sopenharmony_ci * as even if USDT spec string is the same, USDT cookie value can be
18562306a36Sopenharmony_ci * different. It was deemed excessive to try to deduplicate across independent
18662306a36Sopenharmony_ci * USDT attachments by taking into account USDT spec string *and* USDT cookie
18762306a36Sopenharmony_ci * value, which would complicated spec ID accounting significantly for little
18862306a36Sopenharmony_ci * gain.
18962306a36Sopenharmony_ci */
19062306a36Sopenharmony_ci
19162306a36Sopenharmony_ci#define USDT_BASE_SEC ".stapsdt.base"
19262306a36Sopenharmony_ci#define USDT_SEMA_SEC ".probes"
19362306a36Sopenharmony_ci#define USDT_NOTE_SEC  ".note.stapsdt"
19462306a36Sopenharmony_ci#define USDT_NOTE_TYPE 3
19562306a36Sopenharmony_ci#define USDT_NOTE_NAME "stapsdt"
19662306a36Sopenharmony_ci
19762306a36Sopenharmony_ci/* should match exactly enum __bpf_usdt_arg_type from usdt.bpf.h */
19862306a36Sopenharmony_cienum usdt_arg_type {
19962306a36Sopenharmony_ci	USDT_ARG_CONST,
20062306a36Sopenharmony_ci	USDT_ARG_REG,
20162306a36Sopenharmony_ci	USDT_ARG_REG_DEREF,
20262306a36Sopenharmony_ci};
20362306a36Sopenharmony_ci
20462306a36Sopenharmony_ci/* should match exactly struct __bpf_usdt_arg_spec from usdt.bpf.h */
20562306a36Sopenharmony_cistruct usdt_arg_spec {
20662306a36Sopenharmony_ci	__u64 val_off;
20762306a36Sopenharmony_ci	enum usdt_arg_type arg_type;
20862306a36Sopenharmony_ci	short reg_off;
20962306a36Sopenharmony_ci	bool arg_signed;
21062306a36Sopenharmony_ci	char arg_bitshift;
21162306a36Sopenharmony_ci};
21262306a36Sopenharmony_ci
21362306a36Sopenharmony_ci/* should match BPF_USDT_MAX_ARG_CNT in usdt.bpf.h */
21462306a36Sopenharmony_ci#define USDT_MAX_ARG_CNT 12
21562306a36Sopenharmony_ci
21662306a36Sopenharmony_ci/* should match struct __bpf_usdt_spec from usdt.bpf.h */
21762306a36Sopenharmony_cistruct usdt_spec {
21862306a36Sopenharmony_ci	struct usdt_arg_spec args[USDT_MAX_ARG_CNT];
21962306a36Sopenharmony_ci	__u64 usdt_cookie;
22062306a36Sopenharmony_ci	short arg_cnt;
22162306a36Sopenharmony_ci};
22262306a36Sopenharmony_ci
22362306a36Sopenharmony_cistruct usdt_note {
22462306a36Sopenharmony_ci	const char *provider;
22562306a36Sopenharmony_ci	const char *name;
22662306a36Sopenharmony_ci	/* USDT args specification string, e.g.:
22762306a36Sopenharmony_ci	 * "-4@%esi -4@-24(%rbp) -4@%ecx 2@%ax 8@%rdx"
22862306a36Sopenharmony_ci	 */
22962306a36Sopenharmony_ci	const char *args;
23062306a36Sopenharmony_ci	long loc_addr;
23162306a36Sopenharmony_ci	long base_addr;
23262306a36Sopenharmony_ci	long sema_addr;
23362306a36Sopenharmony_ci};
23462306a36Sopenharmony_ci
23562306a36Sopenharmony_cistruct usdt_target {
23662306a36Sopenharmony_ci	long abs_ip;
23762306a36Sopenharmony_ci	long rel_ip;
23862306a36Sopenharmony_ci	long sema_off;
23962306a36Sopenharmony_ci	struct usdt_spec spec;
24062306a36Sopenharmony_ci	const char *spec_str;
24162306a36Sopenharmony_ci};
24262306a36Sopenharmony_ci
24362306a36Sopenharmony_cistruct usdt_manager {
24462306a36Sopenharmony_ci	struct bpf_map *specs_map;
24562306a36Sopenharmony_ci	struct bpf_map *ip_to_spec_id_map;
24662306a36Sopenharmony_ci
24762306a36Sopenharmony_ci	int *free_spec_ids;
24862306a36Sopenharmony_ci	size_t free_spec_cnt;
24962306a36Sopenharmony_ci	size_t next_free_spec_id;
25062306a36Sopenharmony_ci
25162306a36Sopenharmony_ci	bool has_bpf_cookie;
25262306a36Sopenharmony_ci	bool has_sema_refcnt;
25362306a36Sopenharmony_ci	bool has_uprobe_multi;
25462306a36Sopenharmony_ci};
25562306a36Sopenharmony_ci
25662306a36Sopenharmony_cistruct usdt_manager *usdt_manager_new(struct bpf_object *obj)
25762306a36Sopenharmony_ci{
25862306a36Sopenharmony_ci	static const char *ref_ctr_sysfs_path = "/sys/bus/event_source/devices/uprobe/format/ref_ctr_offset";
25962306a36Sopenharmony_ci	struct usdt_manager *man;
26062306a36Sopenharmony_ci	struct bpf_map *specs_map, *ip_to_spec_id_map;
26162306a36Sopenharmony_ci
26262306a36Sopenharmony_ci	specs_map = bpf_object__find_map_by_name(obj, "__bpf_usdt_specs");
26362306a36Sopenharmony_ci	ip_to_spec_id_map = bpf_object__find_map_by_name(obj, "__bpf_usdt_ip_to_spec_id");
26462306a36Sopenharmony_ci	if (!specs_map || !ip_to_spec_id_map) {
26562306a36Sopenharmony_ci		pr_warn("usdt: failed to find USDT support BPF maps, did you forget to include bpf/usdt.bpf.h?\n");
26662306a36Sopenharmony_ci		return ERR_PTR(-ESRCH);
26762306a36Sopenharmony_ci	}
26862306a36Sopenharmony_ci
26962306a36Sopenharmony_ci	man = calloc(1, sizeof(*man));
27062306a36Sopenharmony_ci	if (!man)
27162306a36Sopenharmony_ci		return ERR_PTR(-ENOMEM);
27262306a36Sopenharmony_ci
27362306a36Sopenharmony_ci	man->specs_map = specs_map;
27462306a36Sopenharmony_ci	man->ip_to_spec_id_map = ip_to_spec_id_map;
27562306a36Sopenharmony_ci
27662306a36Sopenharmony_ci	/* Detect if BPF cookie is supported for kprobes.
27762306a36Sopenharmony_ci	 * We don't need IP-to-ID mapping if we can use BPF cookies.
27862306a36Sopenharmony_ci	 * Added in: 7adfc6c9b315 ("bpf: Add bpf_get_attach_cookie() BPF helper to access bpf_cookie value")
27962306a36Sopenharmony_ci	 */
28062306a36Sopenharmony_ci	man->has_bpf_cookie = kernel_supports(obj, FEAT_BPF_COOKIE);
28162306a36Sopenharmony_ci
28262306a36Sopenharmony_ci	/* Detect kernel support for automatic refcounting of USDT semaphore.
28362306a36Sopenharmony_ci	 * If this is not supported, USDTs with semaphores will not be supported.
28462306a36Sopenharmony_ci	 * Added in: a6ca88b241d5 ("trace_uprobe: support reference counter in fd-based uprobe")
28562306a36Sopenharmony_ci	 */
28662306a36Sopenharmony_ci	man->has_sema_refcnt = faccessat(AT_FDCWD, ref_ctr_sysfs_path, F_OK, AT_EACCESS) == 0;
28762306a36Sopenharmony_ci
28862306a36Sopenharmony_ci	/*
28962306a36Sopenharmony_ci	 * Detect kernel support for uprobe multi link to be used for attaching
29062306a36Sopenharmony_ci	 * usdt probes.
29162306a36Sopenharmony_ci	 */
29262306a36Sopenharmony_ci	man->has_uprobe_multi = kernel_supports(obj, FEAT_UPROBE_MULTI_LINK);
29362306a36Sopenharmony_ci	return man;
29462306a36Sopenharmony_ci}
29562306a36Sopenharmony_ci
29662306a36Sopenharmony_civoid usdt_manager_free(struct usdt_manager *man)
29762306a36Sopenharmony_ci{
29862306a36Sopenharmony_ci	if (IS_ERR_OR_NULL(man))
29962306a36Sopenharmony_ci		return;
30062306a36Sopenharmony_ci
30162306a36Sopenharmony_ci	free(man->free_spec_ids);
30262306a36Sopenharmony_ci	free(man);
30362306a36Sopenharmony_ci}
30462306a36Sopenharmony_ci
30562306a36Sopenharmony_cistatic int sanity_check_usdt_elf(Elf *elf, const char *path)
30662306a36Sopenharmony_ci{
30762306a36Sopenharmony_ci	GElf_Ehdr ehdr;
30862306a36Sopenharmony_ci	int endianness;
30962306a36Sopenharmony_ci
31062306a36Sopenharmony_ci	if (elf_kind(elf) != ELF_K_ELF) {
31162306a36Sopenharmony_ci		pr_warn("usdt: unrecognized ELF kind %d for '%s'\n", elf_kind(elf), path);
31262306a36Sopenharmony_ci		return -EBADF;
31362306a36Sopenharmony_ci	}
31462306a36Sopenharmony_ci
31562306a36Sopenharmony_ci	switch (gelf_getclass(elf)) {
31662306a36Sopenharmony_ci	case ELFCLASS64:
31762306a36Sopenharmony_ci		if (sizeof(void *) != 8) {
31862306a36Sopenharmony_ci			pr_warn("usdt: attaching to 64-bit ELF binary '%s' is not supported\n", path);
31962306a36Sopenharmony_ci			return -EBADF;
32062306a36Sopenharmony_ci		}
32162306a36Sopenharmony_ci		break;
32262306a36Sopenharmony_ci	case ELFCLASS32:
32362306a36Sopenharmony_ci		if (sizeof(void *) != 4) {
32462306a36Sopenharmony_ci			pr_warn("usdt: attaching to 32-bit ELF binary '%s' is not supported\n", path);
32562306a36Sopenharmony_ci			return -EBADF;
32662306a36Sopenharmony_ci		}
32762306a36Sopenharmony_ci		break;
32862306a36Sopenharmony_ci	default:
32962306a36Sopenharmony_ci		pr_warn("usdt: unsupported ELF class for '%s'\n", path);
33062306a36Sopenharmony_ci		return -EBADF;
33162306a36Sopenharmony_ci	}
33262306a36Sopenharmony_ci
33362306a36Sopenharmony_ci	if (!gelf_getehdr(elf, &ehdr))
33462306a36Sopenharmony_ci		return -EINVAL;
33562306a36Sopenharmony_ci
33662306a36Sopenharmony_ci	if (ehdr.e_type != ET_EXEC && ehdr.e_type != ET_DYN) {
33762306a36Sopenharmony_ci		pr_warn("usdt: unsupported type of ELF binary '%s' (%d), only ET_EXEC and ET_DYN are supported\n",
33862306a36Sopenharmony_ci			path, ehdr.e_type);
33962306a36Sopenharmony_ci		return -EBADF;
34062306a36Sopenharmony_ci	}
34162306a36Sopenharmony_ci
34262306a36Sopenharmony_ci#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
34362306a36Sopenharmony_ci	endianness = ELFDATA2LSB;
34462306a36Sopenharmony_ci#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
34562306a36Sopenharmony_ci	endianness = ELFDATA2MSB;
34662306a36Sopenharmony_ci#else
34762306a36Sopenharmony_ci# error "Unrecognized __BYTE_ORDER__"
34862306a36Sopenharmony_ci#endif
34962306a36Sopenharmony_ci	if (endianness != ehdr.e_ident[EI_DATA]) {
35062306a36Sopenharmony_ci		pr_warn("usdt: ELF endianness mismatch for '%s'\n", path);
35162306a36Sopenharmony_ci		return -EBADF;
35262306a36Sopenharmony_ci	}
35362306a36Sopenharmony_ci
35462306a36Sopenharmony_ci	return 0;
35562306a36Sopenharmony_ci}
35662306a36Sopenharmony_ci
35762306a36Sopenharmony_cistatic int find_elf_sec_by_name(Elf *elf, const char *sec_name, GElf_Shdr *shdr, Elf_Scn **scn)
35862306a36Sopenharmony_ci{
35962306a36Sopenharmony_ci	Elf_Scn *sec = NULL;
36062306a36Sopenharmony_ci	size_t shstrndx;
36162306a36Sopenharmony_ci
36262306a36Sopenharmony_ci	if (elf_getshdrstrndx(elf, &shstrndx))
36362306a36Sopenharmony_ci		return -EINVAL;
36462306a36Sopenharmony_ci
36562306a36Sopenharmony_ci	/* check if ELF is corrupted and avoid calling elf_strptr if yes */
36662306a36Sopenharmony_ci	if (!elf_rawdata(elf_getscn(elf, shstrndx), NULL))
36762306a36Sopenharmony_ci		return -EINVAL;
36862306a36Sopenharmony_ci
36962306a36Sopenharmony_ci	while ((sec = elf_nextscn(elf, sec)) != NULL) {
37062306a36Sopenharmony_ci		char *name;
37162306a36Sopenharmony_ci
37262306a36Sopenharmony_ci		if (!gelf_getshdr(sec, shdr))
37362306a36Sopenharmony_ci			return -EINVAL;
37462306a36Sopenharmony_ci
37562306a36Sopenharmony_ci		name = elf_strptr(elf, shstrndx, shdr->sh_name);
37662306a36Sopenharmony_ci		if (name && strcmp(sec_name, name) == 0) {
37762306a36Sopenharmony_ci			*scn = sec;
37862306a36Sopenharmony_ci			return 0;
37962306a36Sopenharmony_ci		}
38062306a36Sopenharmony_ci	}
38162306a36Sopenharmony_ci
38262306a36Sopenharmony_ci	return -ENOENT;
38362306a36Sopenharmony_ci}
38462306a36Sopenharmony_ci
38562306a36Sopenharmony_cistruct elf_seg {
38662306a36Sopenharmony_ci	long start;
38762306a36Sopenharmony_ci	long end;
38862306a36Sopenharmony_ci	long offset;
38962306a36Sopenharmony_ci	bool is_exec;
39062306a36Sopenharmony_ci};
39162306a36Sopenharmony_ci
39262306a36Sopenharmony_cistatic int cmp_elf_segs(const void *_a, const void *_b)
39362306a36Sopenharmony_ci{
39462306a36Sopenharmony_ci	const struct elf_seg *a = _a;
39562306a36Sopenharmony_ci	const struct elf_seg *b = _b;
39662306a36Sopenharmony_ci
39762306a36Sopenharmony_ci	return a->start < b->start ? -1 : 1;
39862306a36Sopenharmony_ci}
39962306a36Sopenharmony_ci
40062306a36Sopenharmony_cistatic int parse_elf_segs(Elf *elf, const char *path, struct elf_seg **segs, size_t *seg_cnt)
40162306a36Sopenharmony_ci{
40262306a36Sopenharmony_ci	GElf_Phdr phdr;
40362306a36Sopenharmony_ci	size_t n;
40462306a36Sopenharmony_ci	int i, err;
40562306a36Sopenharmony_ci	struct elf_seg *seg;
40662306a36Sopenharmony_ci	void *tmp;
40762306a36Sopenharmony_ci
40862306a36Sopenharmony_ci	*seg_cnt = 0;
40962306a36Sopenharmony_ci
41062306a36Sopenharmony_ci	if (elf_getphdrnum(elf, &n)) {
41162306a36Sopenharmony_ci		err = -errno;
41262306a36Sopenharmony_ci		return err;
41362306a36Sopenharmony_ci	}
41462306a36Sopenharmony_ci
41562306a36Sopenharmony_ci	for (i = 0; i < n; i++) {
41662306a36Sopenharmony_ci		if (!gelf_getphdr(elf, i, &phdr)) {
41762306a36Sopenharmony_ci			err = -errno;
41862306a36Sopenharmony_ci			return err;
41962306a36Sopenharmony_ci		}
42062306a36Sopenharmony_ci
42162306a36Sopenharmony_ci		pr_debug("usdt: discovered PHDR #%d in '%s': vaddr 0x%lx memsz 0x%lx offset 0x%lx type 0x%lx flags 0x%lx\n",
42262306a36Sopenharmony_ci			 i, path, (long)phdr.p_vaddr, (long)phdr.p_memsz, (long)phdr.p_offset,
42362306a36Sopenharmony_ci			 (long)phdr.p_type, (long)phdr.p_flags);
42462306a36Sopenharmony_ci		if (phdr.p_type != PT_LOAD)
42562306a36Sopenharmony_ci			continue;
42662306a36Sopenharmony_ci
42762306a36Sopenharmony_ci		tmp = libbpf_reallocarray(*segs, *seg_cnt + 1, sizeof(**segs));
42862306a36Sopenharmony_ci		if (!tmp)
42962306a36Sopenharmony_ci			return -ENOMEM;
43062306a36Sopenharmony_ci
43162306a36Sopenharmony_ci		*segs = tmp;
43262306a36Sopenharmony_ci		seg = *segs + *seg_cnt;
43362306a36Sopenharmony_ci		(*seg_cnt)++;
43462306a36Sopenharmony_ci
43562306a36Sopenharmony_ci		seg->start = phdr.p_vaddr;
43662306a36Sopenharmony_ci		seg->end = phdr.p_vaddr + phdr.p_memsz;
43762306a36Sopenharmony_ci		seg->offset = phdr.p_offset;
43862306a36Sopenharmony_ci		seg->is_exec = phdr.p_flags & PF_X;
43962306a36Sopenharmony_ci	}
44062306a36Sopenharmony_ci
44162306a36Sopenharmony_ci	if (*seg_cnt == 0) {
44262306a36Sopenharmony_ci		pr_warn("usdt: failed to find PT_LOAD program headers in '%s'\n", path);
44362306a36Sopenharmony_ci		return -ESRCH;
44462306a36Sopenharmony_ci	}
44562306a36Sopenharmony_ci
44662306a36Sopenharmony_ci	qsort(*segs, *seg_cnt, sizeof(**segs), cmp_elf_segs);
44762306a36Sopenharmony_ci	return 0;
44862306a36Sopenharmony_ci}
44962306a36Sopenharmony_ci
45062306a36Sopenharmony_cistatic int parse_vma_segs(int pid, const char *lib_path, struct elf_seg **segs, size_t *seg_cnt)
45162306a36Sopenharmony_ci{
45262306a36Sopenharmony_ci	char path[PATH_MAX], line[PATH_MAX], mode[16];
45362306a36Sopenharmony_ci	size_t seg_start, seg_end, seg_off;
45462306a36Sopenharmony_ci	struct elf_seg *seg;
45562306a36Sopenharmony_ci	int tmp_pid, i, err;
45662306a36Sopenharmony_ci	FILE *f;
45762306a36Sopenharmony_ci
45862306a36Sopenharmony_ci	*seg_cnt = 0;
45962306a36Sopenharmony_ci
46062306a36Sopenharmony_ci	/* Handle containerized binaries only accessible from
46162306a36Sopenharmony_ci	 * /proc/<pid>/root/<path>. They will be reported as just /<path> in
46262306a36Sopenharmony_ci	 * /proc/<pid>/maps.
46362306a36Sopenharmony_ci	 */
46462306a36Sopenharmony_ci	if (sscanf(lib_path, "/proc/%d/root%s", &tmp_pid, path) == 2 && pid == tmp_pid)
46562306a36Sopenharmony_ci		goto proceed;
46662306a36Sopenharmony_ci
46762306a36Sopenharmony_ci	if (!realpath(lib_path, path)) {
46862306a36Sopenharmony_ci		pr_warn("usdt: failed to get absolute path of '%s' (err %d), using path as is...\n",
46962306a36Sopenharmony_ci			lib_path, -errno);
47062306a36Sopenharmony_ci		libbpf_strlcpy(path, lib_path, sizeof(path));
47162306a36Sopenharmony_ci	}
47262306a36Sopenharmony_ci
47362306a36Sopenharmony_ciproceed:
47462306a36Sopenharmony_ci	sprintf(line, "/proc/%d/maps", pid);
47562306a36Sopenharmony_ci	f = fopen(line, "re");
47662306a36Sopenharmony_ci	if (!f) {
47762306a36Sopenharmony_ci		err = -errno;
47862306a36Sopenharmony_ci		pr_warn("usdt: failed to open '%s' to get base addr of '%s': %d\n",
47962306a36Sopenharmony_ci			line, lib_path, err);
48062306a36Sopenharmony_ci		return err;
48162306a36Sopenharmony_ci	}
48262306a36Sopenharmony_ci
48362306a36Sopenharmony_ci	/* We need to handle lines with no path at the end:
48462306a36Sopenharmony_ci	 *
48562306a36Sopenharmony_ci	 * 7f5c6f5d1000-7f5c6f5d3000 rw-p 001c7000 08:04 21238613      /usr/lib64/libc-2.17.so
48662306a36Sopenharmony_ci	 * 7f5c6f5d3000-7f5c6f5d8000 rw-p 00000000 00:00 0
48762306a36Sopenharmony_ci	 * 7f5c6f5d8000-7f5c6f5d9000 r-xp 00000000 103:01 362990598    /data/users/andriin/linux/tools/bpf/usdt/libhello_usdt.so
48862306a36Sopenharmony_ci	 */
48962306a36Sopenharmony_ci	while (fscanf(f, "%zx-%zx %s %zx %*s %*d%[^\n]\n",
49062306a36Sopenharmony_ci		      &seg_start, &seg_end, mode, &seg_off, line) == 5) {
49162306a36Sopenharmony_ci		void *tmp;
49262306a36Sopenharmony_ci
49362306a36Sopenharmony_ci		/* to handle no path case (see above) we need to capture line
49462306a36Sopenharmony_ci		 * without skipping any whitespaces. So we need to strip
49562306a36Sopenharmony_ci		 * leading whitespaces manually here
49662306a36Sopenharmony_ci		 */
49762306a36Sopenharmony_ci		i = 0;
49862306a36Sopenharmony_ci		while (isblank(line[i]))
49962306a36Sopenharmony_ci			i++;
50062306a36Sopenharmony_ci		if (strcmp(line + i, path) != 0)
50162306a36Sopenharmony_ci			continue;
50262306a36Sopenharmony_ci
50362306a36Sopenharmony_ci		pr_debug("usdt: discovered segment for lib '%s': addrs %zx-%zx mode %s offset %zx\n",
50462306a36Sopenharmony_ci			 path, seg_start, seg_end, mode, seg_off);
50562306a36Sopenharmony_ci
50662306a36Sopenharmony_ci		/* ignore non-executable sections for shared libs */
50762306a36Sopenharmony_ci		if (mode[2] != 'x')
50862306a36Sopenharmony_ci			continue;
50962306a36Sopenharmony_ci
51062306a36Sopenharmony_ci		tmp = libbpf_reallocarray(*segs, *seg_cnt + 1, sizeof(**segs));
51162306a36Sopenharmony_ci		if (!tmp) {
51262306a36Sopenharmony_ci			err = -ENOMEM;
51362306a36Sopenharmony_ci			goto err_out;
51462306a36Sopenharmony_ci		}
51562306a36Sopenharmony_ci
51662306a36Sopenharmony_ci		*segs = tmp;
51762306a36Sopenharmony_ci		seg = *segs + *seg_cnt;
51862306a36Sopenharmony_ci		*seg_cnt += 1;
51962306a36Sopenharmony_ci
52062306a36Sopenharmony_ci		seg->start = seg_start;
52162306a36Sopenharmony_ci		seg->end = seg_end;
52262306a36Sopenharmony_ci		seg->offset = seg_off;
52362306a36Sopenharmony_ci		seg->is_exec = true;
52462306a36Sopenharmony_ci	}
52562306a36Sopenharmony_ci
52662306a36Sopenharmony_ci	if (*seg_cnt == 0) {
52762306a36Sopenharmony_ci		pr_warn("usdt: failed to find '%s' (resolved to '%s') within PID %d memory mappings\n",
52862306a36Sopenharmony_ci			lib_path, path, pid);
52962306a36Sopenharmony_ci		err = -ESRCH;
53062306a36Sopenharmony_ci		goto err_out;
53162306a36Sopenharmony_ci	}
53262306a36Sopenharmony_ci
53362306a36Sopenharmony_ci	qsort(*segs, *seg_cnt, sizeof(**segs), cmp_elf_segs);
53462306a36Sopenharmony_ci	err = 0;
53562306a36Sopenharmony_cierr_out:
53662306a36Sopenharmony_ci	fclose(f);
53762306a36Sopenharmony_ci	return err;
53862306a36Sopenharmony_ci}
53962306a36Sopenharmony_ci
54062306a36Sopenharmony_cistatic struct elf_seg *find_elf_seg(struct elf_seg *segs, size_t seg_cnt, long virtaddr)
54162306a36Sopenharmony_ci{
54262306a36Sopenharmony_ci	struct elf_seg *seg;
54362306a36Sopenharmony_ci	int i;
54462306a36Sopenharmony_ci
54562306a36Sopenharmony_ci	/* for ELF binaries (both executables and shared libraries), we are
54662306a36Sopenharmony_ci	 * given virtual address (absolute for executables, relative for
54762306a36Sopenharmony_ci	 * libraries) which should match address range of [seg_start, seg_end)
54862306a36Sopenharmony_ci	 */
54962306a36Sopenharmony_ci	for (i = 0, seg = segs; i < seg_cnt; i++, seg++) {
55062306a36Sopenharmony_ci		if (seg->start <= virtaddr && virtaddr < seg->end)
55162306a36Sopenharmony_ci			return seg;
55262306a36Sopenharmony_ci	}
55362306a36Sopenharmony_ci	return NULL;
55462306a36Sopenharmony_ci}
55562306a36Sopenharmony_ci
55662306a36Sopenharmony_cistatic struct elf_seg *find_vma_seg(struct elf_seg *segs, size_t seg_cnt, long offset)
55762306a36Sopenharmony_ci{
55862306a36Sopenharmony_ci	struct elf_seg *seg;
55962306a36Sopenharmony_ci	int i;
56062306a36Sopenharmony_ci
56162306a36Sopenharmony_ci	/* for VMA segments from /proc/<pid>/maps file, provided "address" is
56262306a36Sopenharmony_ci	 * actually a file offset, so should be fall within logical
56362306a36Sopenharmony_ci	 * offset-based range of [offset_start, offset_end)
56462306a36Sopenharmony_ci	 */
56562306a36Sopenharmony_ci	for (i = 0, seg = segs; i < seg_cnt; i++, seg++) {
56662306a36Sopenharmony_ci		if (seg->offset <= offset && offset < seg->offset + (seg->end - seg->start))
56762306a36Sopenharmony_ci			return seg;
56862306a36Sopenharmony_ci	}
56962306a36Sopenharmony_ci	return NULL;
57062306a36Sopenharmony_ci}
57162306a36Sopenharmony_ci
57262306a36Sopenharmony_cistatic int parse_usdt_note(Elf *elf, const char *path, GElf_Nhdr *nhdr,
57362306a36Sopenharmony_ci			   const char *data, size_t name_off, size_t desc_off,
57462306a36Sopenharmony_ci			   struct usdt_note *usdt_note);
57562306a36Sopenharmony_ci
57662306a36Sopenharmony_cistatic int parse_usdt_spec(struct usdt_spec *spec, const struct usdt_note *note, __u64 usdt_cookie);
57762306a36Sopenharmony_ci
57862306a36Sopenharmony_cistatic int collect_usdt_targets(struct usdt_manager *man, Elf *elf, const char *path, pid_t pid,
57962306a36Sopenharmony_ci				const char *usdt_provider, const char *usdt_name, __u64 usdt_cookie,
58062306a36Sopenharmony_ci				struct usdt_target **out_targets, size_t *out_target_cnt)
58162306a36Sopenharmony_ci{
58262306a36Sopenharmony_ci	size_t off, name_off, desc_off, seg_cnt = 0, vma_seg_cnt = 0, target_cnt = 0;
58362306a36Sopenharmony_ci	struct elf_seg *segs = NULL, *vma_segs = NULL;
58462306a36Sopenharmony_ci	struct usdt_target *targets = NULL, *target;
58562306a36Sopenharmony_ci	long base_addr = 0;
58662306a36Sopenharmony_ci	Elf_Scn *notes_scn, *base_scn;
58762306a36Sopenharmony_ci	GElf_Shdr base_shdr, notes_shdr;
58862306a36Sopenharmony_ci	GElf_Ehdr ehdr;
58962306a36Sopenharmony_ci	GElf_Nhdr nhdr;
59062306a36Sopenharmony_ci	Elf_Data *data;
59162306a36Sopenharmony_ci	int err;
59262306a36Sopenharmony_ci
59362306a36Sopenharmony_ci	*out_targets = NULL;
59462306a36Sopenharmony_ci	*out_target_cnt = 0;
59562306a36Sopenharmony_ci
59662306a36Sopenharmony_ci	err = find_elf_sec_by_name(elf, USDT_NOTE_SEC, &notes_shdr, &notes_scn);
59762306a36Sopenharmony_ci	if (err) {
59862306a36Sopenharmony_ci		pr_warn("usdt: no USDT notes section (%s) found in '%s'\n", USDT_NOTE_SEC, path);
59962306a36Sopenharmony_ci		return err;
60062306a36Sopenharmony_ci	}
60162306a36Sopenharmony_ci
60262306a36Sopenharmony_ci	if (notes_shdr.sh_type != SHT_NOTE || !gelf_getehdr(elf, &ehdr)) {
60362306a36Sopenharmony_ci		pr_warn("usdt: invalid USDT notes section (%s) in '%s'\n", USDT_NOTE_SEC, path);
60462306a36Sopenharmony_ci		return -EINVAL;
60562306a36Sopenharmony_ci	}
60662306a36Sopenharmony_ci
60762306a36Sopenharmony_ci	err = parse_elf_segs(elf, path, &segs, &seg_cnt);
60862306a36Sopenharmony_ci	if (err) {
60962306a36Sopenharmony_ci		pr_warn("usdt: failed to process ELF program segments for '%s': %d\n", path, err);
61062306a36Sopenharmony_ci		goto err_out;
61162306a36Sopenharmony_ci	}
61262306a36Sopenharmony_ci
61362306a36Sopenharmony_ci	/* .stapsdt.base ELF section is optional, but is used for prelink
61462306a36Sopenharmony_ci	 * offset compensation (see a big comment further below)
61562306a36Sopenharmony_ci	 */
61662306a36Sopenharmony_ci	if (find_elf_sec_by_name(elf, USDT_BASE_SEC, &base_shdr, &base_scn) == 0)
61762306a36Sopenharmony_ci		base_addr = base_shdr.sh_addr;
61862306a36Sopenharmony_ci
61962306a36Sopenharmony_ci	data = elf_getdata(notes_scn, 0);
62062306a36Sopenharmony_ci	off = 0;
62162306a36Sopenharmony_ci	while ((off = gelf_getnote(data, off, &nhdr, &name_off, &desc_off)) > 0) {
62262306a36Sopenharmony_ci		long usdt_abs_ip, usdt_rel_ip, usdt_sema_off = 0;
62362306a36Sopenharmony_ci		struct usdt_note note;
62462306a36Sopenharmony_ci		struct elf_seg *seg = NULL;
62562306a36Sopenharmony_ci		void *tmp;
62662306a36Sopenharmony_ci
62762306a36Sopenharmony_ci		err = parse_usdt_note(elf, path, &nhdr, data->d_buf, name_off, desc_off, &note);
62862306a36Sopenharmony_ci		if (err)
62962306a36Sopenharmony_ci			goto err_out;
63062306a36Sopenharmony_ci
63162306a36Sopenharmony_ci		if (strcmp(note.provider, usdt_provider) != 0 || strcmp(note.name, usdt_name) != 0)
63262306a36Sopenharmony_ci			continue;
63362306a36Sopenharmony_ci
63462306a36Sopenharmony_ci		/* We need to compensate "prelink effect". See [0] for details,
63562306a36Sopenharmony_ci		 * relevant parts quoted here:
63662306a36Sopenharmony_ci		 *
63762306a36Sopenharmony_ci		 * Each SDT probe also expands into a non-allocated ELF note. You can
63862306a36Sopenharmony_ci		 * find this by looking at SHT_NOTE sections and decoding the format;
63962306a36Sopenharmony_ci		 * see below for details. Because the note is non-allocated, it means
64062306a36Sopenharmony_ci		 * there is no runtime cost, and also preserved in both stripped files
64162306a36Sopenharmony_ci		 * and .debug files.
64262306a36Sopenharmony_ci		 *
64362306a36Sopenharmony_ci		 * However, this means that prelink won't adjust the note's contents
64462306a36Sopenharmony_ci		 * for address offsets. Instead, this is done via the .stapsdt.base
64562306a36Sopenharmony_ci		 * section. This is a special section that is added to the text. We
64662306a36Sopenharmony_ci		 * will only ever have one of these sections in a final link and it
64762306a36Sopenharmony_ci		 * will only ever be one byte long. Nothing about this section itself
64862306a36Sopenharmony_ci		 * matters, we just use it as a marker to detect prelink address
64962306a36Sopenharmony_ci		 * adjustments.
65062306a36Sopenharmony_ci		 *
65162306a36Sopenharmony_ci		 * Each probe note records the link-time address of the .stapsdt.base
65262306a36Sopenharmony_ci		 * section alongside the probe PC address. The decoder compares the
65362306a36Sopenharmony_ci		 * base address stored in the note with the .stapsdt.base section's
65462306a36Sopenharmony_ci		 * sh_addr. Initially these are the same, but the section header will
65562306a36Sopenharmony_ci		 * be adjusted by prelink. So the decoder applies the difference to
65662306a36Sopenharmony_ci		 * the probe PC address to get the correct prelinked PC address; the
65762306a36Sopenharmony_ci		 * same adjustment is applied to the semaphore address, if any.
65862306a36Sopenharmony_ci		 *
65962306a36Sopenharmony_ci		 *   [0] https://sourceware.org/systemtap/wiki/UserSpaceProbeImplementation
66062306a36Sopenharmony_ci		 */
66162306a36Sopenharmony_ci		usdt_abs_ip = note.loc_addr;
66262306a36Sopenharmony_ci		if (base_addr)
66362306a36Sopenharmony_ci			usdt_abs_ip += base_addr - note.base_addr;
66462306a36Sopenharmony_ci
66562306a36Sopenharmony_ci		/* When attaching uprobes (which is what USDTs basically are)
66662306a36Sopenharmony_ci		 * kernel expects file offset to be specified, not a relative
66762306a36Sopenharmony_ci		 * virtual address, so we need to translate virtual address to
66862306a36Sopenharmony_ci		 * file offset, for both ET_EXEC and ET_DYN binaries.
66962306a36Sopenharmony_ci		 */
67062306a36Sopenharmony_ci		seg = find_elf_seg(segs, seg_cnt, usdt_abs_ip);
67162306a36Sopenharmony_ci		if (!seg) {
67262306a36Sopenharmony_ci			err = -ESRCH;
67362306a36Sopenharmony_ci			pr_warn("usdt: failed to find ELF program segment for '%s:%s' in '%s' at IP 0x%lx\n",
67462306a36Sopenharmony_ci				usdt_provider, usdt_name, path, usdt_abs_ip);
67562306a36Sopenharmony_ci			goto err_out;
67662306a36Sopenharmony_ci		}
67762306a36Sopenharmony_ci		if (!seg->is_exec) {
67862306a36Sopenharmony_ci			err = -ESRCH;
67962306a36Sopenharmony_ci			pr_warn("usdt: matched ELF binary '%s' segment [0x%lx, 0x%lx) for '%s:%s' at IP 0x%lx is not executable\n",
68062306a36Sopenharmony_ci				path, seg->start, seg->end, usdt_provider, usdt_name,
68162306a36Sopenharmony_ci				usdt_abs_ip);
68262306a36Sopenharmony_ci			goto err_out;
68362306a36Sopenharmony_ci		}
68462306a36Sopenharmony_ci		/* translate from virtual address to file offset */
68562306a36Sopenharmony_ci		usdt_rel_ip = usdt_abs_ip - seg->start + seg->offset;
68662306a36Sopenharmony_ci
68762306a36Sopenharmony_ci		if (ehdr.e_type == ET_DYN && !man->has_bpf_cookie) {
68862306a36Sopenharmony_ci			/* If we don't have BPF cookie support but need to
68962306a36Sopenharmony_ci			 * attach to a shared library, we'll need to know and
69062306a36Sopenharmony_ci			 * record absolute addresses of attach points due to
69162306a36Sopenharmony_ci			 * the need to lookup USDT spec by absolute IP of
69262306a36Sopenharmony_ci			 * triggered uprobe. Doing this resolution is only
69362306a36Sopenharmony_ci			 * possible when we have a specific PID of the process
69462306a36Sopenharmony_ci			 * that's using specified shared library. BPF cookie
69562306a36Sopenharmony_ci			 * removes the absolute address limitation as we don't
69662306a36Sopenharmony_ci			 * need to do this lookup (we just use BPF cookie as
69762306a36Sopenharmony_ci			 * an index of USDT spec), so for newer kernels with
69862306a36Sopenharmony_ci			 * BPF cookie support libbpf supports USDT attachment
69962306a36Sopenharmony_ci			 * to shared libraries with no PID filter.
70062306a36Sopenharmony_ci			 */
70162306a36Sopenharmony_ci			if (pid < 0) {
70262306a36Sopenharmony_ci				pr_warn("usdt: attaching to shared libraries without specific PID is not supported on current kernel\n");
70362306a36Sopenharmony_ci				err = -ENOTSUP;
70462306a36Sopenharmony_ci				goto err_out;
70562306a36Sopenharmony_ci			}
70662306a36Sopenharmony_ci
70762306a36Sopenharmony_ci			/* vma_segs are lazily initialized only if necessary */
70862306a36Sopenharmony_ci			if (vma_seg_cnt == 0) {
70962306a36Sopenharmony_ci				err = parse_vma_segs(pid, path, &vma_segs, &vma_seg_cnt);
71062306a36Sopenharmony_ci				if (err) {
71162306a36Sopenharmony_ci					pr_warn("usdt: failed to get memory segments in PID %d for shared library '%s': %d\n",
71262306a36Sopenharmony_ci						pid, path, err);
71362306a36Sopenharmony_ci					goto err_out;
71462306a36Sopenharmony_ci				}
71562306a36Sopenharmony_ci			}
71662306a36Sopenharmony_ci
71762306a36Sopenharmony_ci			seg = find_vma_seg(vma_segs, vma_seg_cnt, usdt_rel_ip);
71862306a36Sopenharmony_ci			if (!seg) {
71962306a36Sopenharmony_ci				err = -ESRCH;
72062306a36Sopenharmony_ci				pr_warn("usdt: failed to find shared lib memory segment for '%s:%s' in '%s' at relative IP 0x%lx\n",
72162306a36Sopenharmony_ci					usdt_provider, usdt_name, path, usdt_rel_ip);
72262306a36Sopenharmony_ci				goto err_out;
72362306a36Sopenharmony_ci			}
72462306a36Sopenharmony_ci
72562306a36Sopenharmony_ci			usdt_abs_ip = seg->start - seg->offset + usdt_rel_ip;
72662306a36Sopenharmony_ci		}
72762306a36Sopenharmony_ci
72862306a36Sopenharmony_ci		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",
72962306a36Sopenharmony_ci			 usdt_provider, usdt_name, ehdr.e_type == ET_EXEC ? "exec" : "lib ", path,
73062306a36Sopenharmony_ci			 note.loc_addr, note.base_addr, usdt_abs_ip, usdt_rel_ip, note.args,
73162306a36Sopenharmony_ci			 seg ? seg->start : 0, seg ? seg->end : 0, seg ? seg->offset : 0);
73262306a36Sopenharmony_ci
73362306a36Sopenharmony_ci		/* Adjust semaphore address to be a file offset */
73462306a36Sopenharmony_ci		if (note.sema_addr) {
73562306a36Sopenharmony_ci			if (!man->has_sema_refcnt) {
73662306a36Sopenharmony_ci				pr_warn("usdt: kernel doesn't support USDT semaphore refcounting for '%s:%s' in '%s'\n",
73762306a36Sopenharmony_ci					usdt_provider, usdt_name, path);
73862306a36Sopenharmony_ci				err = -ENOTSUP;
73962306a36Sopenharmony_ci				goto err_out;
74062306a36Sopenharmony_ci			}
74162306a36Sopenharmony_ci
74262306a36Sopenharmony_ci			seg = find_elf_seg(segs, seg_cnt, note.sema_addr);
74362306a36Sopenharmony_ci			if (!seg) {
74462306a36Sopenharmony_ci				err = -ESRCH;
74562306a36Sopenharmony_ci				pr_warn("usdt: failed to find ELF loadable segment with semaphore of '%s:%s' in '%s' at 0x%lx\n",
74662306a36Sopenharmony_ci					usdt_provider, usdt_name, path, note.sema_addr);
74762306a36Sopenharmony_ci				goto err_out;
74862306a36Sopenharmony_ci			}
74962306a36Sopenharmony_ci			if (seg->is_exec) {
75062306a36Sopenharmony_ci				err = -ESRCH;
75162306a36Sopenharmony_ci				pr_warn("usdt: matched ELF binary '%s' segment [0x%lx, 0x%lx] for semaphore of '%s:%s' at 0x%lx is executable\n",
75262306a36Sopenharmony_ci					path, seg->start, seg->end, usdt_provider, usdt_name,
75362306a36Sopenharmony_ci					note.sema_addr);
75462306a36Sopenharmony_ci				goto err_out;
75562306a36Sopenharmony_ci			}
75662306a36Sopenharmony_ci
75762306a36Sopenharmony_ci			usdt_sema_off = note.sema_addr - seg->start + seg->offset;
75862306a36Sopenharmony_ci
75962306a36Sopenharmony_ci			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",
76062306a36Sopenharmony_ci				 usdt_provider, usdt_name, ehdr.e_type == ET_EXEC ? "exec" : "lib ",
76162306a36Sopenharmony_ci				 path, note.sema_addr, note.base_addr, usdt_sema_off,
76262306a36Sopenharmony_ci				 seg->start, seg->end, seg->offset);
76362306a36Sopenharmony_ci		}
76462306a36Sopenharmony_ci
76562306a36Sopenharmony_ci		/* Record adjusted addresses and offsets and parse USDT spec */
76662306a36Sopenharmony_ci		tmp = libbpf_reallocarray(targets, target_cnt + 1, sizeof(*targets));
76762306a36Sopenharmony_ci		if (!tmp) {
76862306a36Sopenharmony_ci			err = -ENOMEM;
76962306a36Sopenharmony_ci			goto err_out;
77062306a36Sopenharmony_ci		}
77162306a36Sopenharmony_ci		targets = tmp;
77262306a36Sopenharmony_ci
77362306a36Sopenharmony_ci		target = &targets[target_cnt];
77462306a36Sopenharmony_ci		memset(target, 0, sizeof(*target));
77562306a36Sopenharmony_ci
77662306a36Sopenharmony_ci		target->abs_ip = usdt_abs_ip;
77762306a36Sopenharmony_ci		target->rel_ip = usdt_rel_ip;
77862306a36Sopenharmony_ci		target->sema_off = usdt_sema_off;
77962306a36Sopenharmony_ci
78062306a36Sopenharmony_ci		/* notes.args references strings from ELF itself, so they can
78162306a36Sopenharmony_ci		 * be referenced safely until elf_end() call
78262306a36Sopenharmony_ci		 */
78362306a36Sopenharmony_ci		target->spec_str = note.args;
78462306a36Sopenharmony_ci
78562306a36Sopenharmony_ci		err = parse_usdt_spec(&target->spec, &note, usdt_cookie);
78662306a36Sopenharmony_ci		if (err)
78762306a36Sopenharmony_ci			goto err_out;
78862306a36Sopenharmony_ci
78962306a36Sopenharmony_ci		target_cnt++;
79062306a36Sopenharmony_ci	}
79162306a36Sopenharmony_ci
79262306a36Sopenharmony_ci	*out_targets = targets;
79362306a36Sopenharmony_ci	*out_target_cnt = target_cnt;
79462306a36Sopenharmony_ci	err = target_cnt;
79562306a36Sopenharmony_ci
79662306a36Sopenharmony_cierr_out:
79762306a36Sopenharmony_ci	free(segs);
79862306a36Sopenharmony_ci	free(vma_segs);
79962306a36Sopenharmony_ci	if (err < 0)
80062306a36Sopenharmony_ci		free(targets);
80162306a36Sopenharmony_ci	return err;
80262306a36Sopenharmony_ci}
80362306a36Sopenharmony_ci
80462306a36Sopenharmony_cistruct bpf_link_usdt {
80562306a36Sopenharmony_ci	struct bpf_link link;
80662306a36Sopenharmony_ci
80762306a36Sopenharmony_ci	struct usdt_manager *usdt_man;
80862306a36Sopenharmony_ci
80962306a36Sopenharmony_ci	size_t spec_cnt;
81062306a36Sopenharmony_ci	int *spec_ids;
81162306a36Sopenharmony_ci
81262306a36Sopenharmony_ci	size_t uprobe_cnt;
81362306a36Sopenharmony_ci	struct {
81462306a36Sopenharmony_ci		long abs_ip;
81562306a36Sopenharmony_ci		struct bpf_link *link;
81662306a36Sopenharmony_ci	} *uprobes;
81762306a36Sopenharmony_ci
81862306a36Sopenharmony_ci	struct bpf_link *multi_link;
81962306a36Sopenharmony_ci};
82062306a36Sopenharmony_ci
82162306a36Sopenharmony_cistatic int bpf_link_usdt_detach(struct bpf_link *link)
82262306a36Sopenharmony_ci{
82362306a36Sopenharmony_ci	struct bpf_link_usdt *usdt_link = container_of(link, struct bpf_link_usdt, link);
82462306a36Sopenharmony_ci	struct usdt_manager *man = usdt_link->usdt_man;
82562306a36Sopenharmony_ci	int i;
82662306a36Sopenharmony_ci
82762306a36Sopenharmony_ci	bpf_link__destroy(usdt_link->multi_link);
82862306a36Sopenharmony_ci
82962306a36Sopenharmony_ci	/* When having multi_link, uprobe_cnt is 0 */
83062306a36Sopenharmony_ci	for (i = 0; i < usdt_link->uprobe_cnt; i++) {
83162306a36Sopenharmony_ci		/* detach underlying uprobe link */
83262306a36Sopenharmony_ci		bpf_link__destroy(usdt_link->uprobes[i].link);
83362306a36Sopenharmony_ci		/* there is no need to update specs map because it will be
83462306a36Sopenharmony_ci		 * unconditionally overwritten on subsequent USDT attaches,
83562306a36Sopenharmony_ci		 * but if BPF cookies are not used we need to remove entry
83662306a36Sopenharmony_ci		 * from ip_to_spec_id map, otherwise we'll run into false
83762306a36Sopenharmony_ci		 * conflicting IP errors
83862306a36Sopenharmony_ci		 */
83962306a36Sopenharmony_ci		if (!man->has_bpf_cookie) {
84062306a36Sopenharmony_ci			/* not much we can do about errors here */
84162306a36Sopenharmony_ci			(void)bpf_map_delete_elem(bpf_map__fd(man->ip_to_spec_id_map),
84262306a36Sopenharmony_ci						  &usdt_link->uprobes[i].abs_ip);
84362306a36Sopenharmony_ci		}
84462306a36Sopenharmony_ci	}
84562306a36Sopenharmony_ci
84662306a36Sopenharmony_ci	/* try to return the list of previously used spec IDs to usdt_manager
84762306a36Sopenharmony_ci	 * for future reuse for subsequent USDT attaches
84862306a36Sopenharmony_ci	 */
84962306a36Sopenharmony_ci	if (!man->free_spec_ids) {
85062306a36Sopenharmony_ci		/* if there were no free spec IDs yet, just transfer our IDs */
85162306a36Sopenharmony_ci		man->free_spec_ids = usdt_link->spec_ids;
85262306a36Sopenharmony_ci		man->free_spec_cnt = usdt_link->spec_cnt;
85362306a36Sopenharmony_ci		usdt_link->spec_ids = NULL;
85462306a36Sopenharmony_ci	} else {
85562306a36Sopenharmony_ci		/* otherwise concat IDs */
85662306a36Sopenharmony_ci		size_t new_cnt = man->free_spec_cnt + usdt_link->spec_cnt;
85762306a36Sopenharmony_ci		int *new_free_ids;
85862306a36Sopenharmony_ci
85962306a36Sopenharmony_ci		new_free_ids = libbpf_reallocarray(man->free_spec_ids, new_cnt,
86062306a36Sopenharmony_ci						   sizeof(*new_free_ids));
86162306a36Sopenharmony_ci		/* If we couldn't resize free_spec_ids, we'll just leak
86262306a36Sopenharmony_ci		 * a bunch of free IDs; this is very unlikely to happen and if
86362306a36Sopenharmony_ci		 * system is so exhausted on memory, it's the least of user's
86462306a36Sopenharmony_ci		 * concerns, probably.
86562306a36Sopenharmony_ci		 * So just do our best here to return those IDs to usdt_manager.
86662306a36Sopenharmony_ci		 * Another edge case when we can legitimately get NULL is when
86762306a36Sopenharmony_ci		 * new_cnt is zero, which can happen in some edge cases, so we
86862306a36Sopenharmony_ci		 * need to be careful about that.
86962306a36Sopenharmony_ci		 */
87062306a36Sopenharmony_ci		if (new_free_ids || new_cnt == 0) {
87162306a36Sopenharmony_ci			memcpy(new_free_ids + man->free_spec_cnt, usdt_link->spec_ids,
87262306a36Sopenharmony_ci			       usdt_link->spec_cnt * sizeof(*usdt_link->spec_ids));
87362306a36Sopenharmony_ci			man->free_spec_ids = new_free_ids;
87462306a36Sopenharmony_ci			man->free_spec_cnt = new_cnt;
87562306a36Sopenharmony_ci		}
87662306a36Sopenharmony_ci	}
87762306a36Sopenharmony_ci
87862306a36Sopenharmony_ci	return 0;
87962306a36Sopenharmony_ci}
88062306a36Sopenharmony_ci
88162306a36Sopenharmony_cistatic void bpf_link_usdt_dealloc(struct bpf_link *link)
88262306a36Sopenharmony_ci{
88362306a36Sopenharmony_ci	struct bpf_link_usdt *usdt_link = container_of(link, struct bpf_link_usdt, link);
88462306a36Sopenharmony_ci
88562306a36Sopenharmony_ci	free(usdt_link->spec_ids);
88662306a36Sopenharmony_ci	free(usdt_link->uprobes);
88762306a36Sopenharmony_ci	free(usdt_link);
88862306a36Sopenharmony_ci}
88962306a36Sopenharmony_ci
89062306a36Sopenharmony_cistatic size_t specs_hash_fn(long key, void *ctx)
89162306a36Sopenharmony_ci{
89262306a36Sopenharmony_ci	return str_hash((char *)key);
89362306a36Sopenharmony_ci}
89462306a36Sopenharmony_ci
89562306a36Sopenharmony_cistatic bool specs_equal_fn(long key1, long key2, void *ctx)
89662306a36Sopenharmony_ci{
89762306a36Sopenharmony_ci	return strcmp((char *)key1, (char *)key2) == 0;
89862306a36Sopenharmony_ci}
89962306a36Sopenharmony_ci
90062306a36Sopenharmony_cistatic int allocate_spec_id(struct usdt_manager *man, struct hashmap *specs_hash,
90162306a36Sopenharmony_ci			    struct bpf_link_usdt *link, struct usdt_target *target,
90262306a36Sopenharmony_ci			    int *spec_id, bool *is_new)
90362306a36Sopenharmony_ci{
90462306a36Sopenharmony_ci	long tmp;
90562306a36Sopenharmony_ci	void *new_ids;
90662306a36Sopenharmony_ci	int err;
90762306a36Sopenharmony_ci
90862306a36Sopenharmony_ci	/* check if we already allocated spec ID for this spec string */
90962306a36Sopenharmony_ci	if (hashmap__find(specs_hash, target->spec_str, &tmp)) {
91062306a36Sopenharmony_ci		*spec_id = tmp;
91162306a36Sopenharmony_ci		*is_new = false;
91262306a36Sopenharmony_ci		return 0;
91362306a36Sopenharmony_ci	}
91462306a36Sopenharmony_ci
91562306a36Sopenharmony_ci	/* otherwise it's a new ID that needs to be set up in specs map and
91662306a36Sopenharmony_ci	 * returned back to usdt_manager when USDT link is detached
91762306a36Sopenharmony_ci	 */
91862306a36Sopenharmony_ci	new_ids = libbpf_reallocarray(link->spec_ids, link->spec_cnt + 1, sizeof(*link->spec_ids));
91962306a36Sopenharmony_ci	if (!new_ids)
92062306a36Sopenharmony_ci		return -ENOMEM;
92162306a36Sopenharmony_ci	link->spec_ids = new_ids;
92262306a36Sopenharmony_ci
92362306a36Sopenharmony_ci	/* get next free spec ID, giving preference to free list, if not empty */
92462306a36Sopenharmony_ci	if (man->free_spec_cnt) {
92562306a36Sopenharmony_ci		*spec_id = man->free_spec_ids[man->free_spec_cnt - 1];
92662306a36Sopenharmony_ci
92762306a36Sopenharmony_ci		/* cache spec ID for current spec string for future lookups */
92862306a36Sopenharmony_ci		err = hashmap__add(specs_hash, target->spec_str, *spec_id);
92962306a36Sopenharmony_ci		if (err)
93062306a36Sopenharmony_ci			 return err;
93162306a36Sopenharmony_ci
93262306a36Sopenharmony_ci		man->free_spec_cnt--;
93362306a36Sopenharmony_ci	} else {
93462306a36Sopenharmony_ci		/* don't allocate spec ID bigger than what fits in specs map */
93562306a36Sopenharmony_ci		if (man->next_free_spec_id >= bpf_map__max_entries(man->specs_map))
93662306a36Sopenharmony_ci			return -E2BIG;
93762306a36Sopenharmony_ci
93862306a36Sopenharmony_ci		*spec_id = man->next_free_spec_id;
93962306a36Sopenharmony_ci
94062306a36Sopenharmony_ci		/* cache spec ID for current spec string for future lookups */
94162306a36Sopenharmony_ci		err = hashmap__add(specs_hash, target->spec_str, *spec_id);
94262306a36Sopenharmony_ci		if (err)
94362306a36Sopenharmony_ci			 return err;
94462306a36Sopenharmony_ci
94562306a36Sopenharmony_ci		man->next_free_spec_id++;
94662306a36Sopenharmony_ci	}
94762306a36Sopenharmony_ci
94862306a36Sopenharmony_ci	/* remember new spec ID in the link for later return back to free list on detach */
94962306a36Sopenharmony_ci	link->spec_ids[link->spec_cnt] = *spec_id;
95062306a36Sopenharmony_ci	link->spec_cnt++;
95162306a36Sopenharmony_ci	*is_new = true;
95262306a36Sopenharmony_ci	return 0;
95362306a36Sopenharmony_ci}
95462306a36Sopenharmony_ci
95562306a36Sopenharmony_cistruct bpf_link *usdt_manager_attach_usdt(struct usdt_manager *man, const struct bpf_program *prog,
95662306a36Sopenharmony_ci					  pid_t pid, const char *path,
95762306a36Sopenharmony_ci					  const char *usdt_provider, const char *usdt_name,
95862306a36Sopenharmony_ci					  __u64 usdt_cookie)
95962306a36Sopenharmony_ci{
96062306a36Sopenharmony_ci	unsigned long *offsets = NULL, *ref_ctr_offsets = NULL;
96162306a36Sopenharmony_ci	int i, err, spec_map_fd, ip_map_fd;
96262306a36Sopenharmony_ci	LIBBPF_OPTS(bpf_uprobe_opts, opts);
96362306a36Sopenharmony_ci	struct hashmap *specs_hash = NULL;
96462306a36Sopenharmony_ci	struct bpf_link_usdt *link = NULL;
96562306a36Sopenharmony_ci	struct usdt_target *targets = NULL;
96662306a36Sopenharmony_ci	__u64 *cookies = NULL;
96762306a36Sopenharmony_ci	struct elf_fd elf_fd;
96862306a36Sopenharmony_ci	size_t target_cnt;
96962306a36Sopenharmony_ci
97062306a36Sopenharmony_ci	spec_map_fd = bpf_map__fd(man->specs_map);
97162306a36Sopenharmony_ci	ip_map_fd = bpf_map__fd(man->ip_to_spec_id_map);
97262306a36Sopenharmony_ci
97362306a36Sopenharmony_ci	err = elf_open(path, &elf_fd);
97462306a36Sopenharmony_ci	if (err)
97562306a36Sopenharmony_ci		return libbpf_err_ptr(err);
97662306a36Sopenharmony_ci
97762306a36Sopenharmony_ci	err = sanity_check_usdt_elf(elf_fd.elf, path);
97862306a36Sopenharmony_ci	if (err)
97962306a36Sopenharmony_ci		goto err_out;
98062306a36Sopenharmony_ci
98162306a36Sopenharmony_ci	/* normalize PID filter */
98262306a36Sopenharmony_ci	if (pid < 0)
98362306a36Sopenharmony_ci		pid = -1;
98462306a36Sopenharmony_ci	else if (pid == 0)
98562306a36Sopenharmony_ci		pid = getpid();
98662306a36Sopenharmony_ci
98762306a36Sopenharmony_ci	/* discover USDT in given binary, optionally limiting
98862306a36Sopenharmony_ci	 * activations to a given PID, if pid > 0
98962306a36Sopenharmony_ci	 */
99062306a36Sopenharmony_ci	err = collect_usdt_targets(man, elf_fd.elf, path, pid, usdt_provider, usdt_name,
99162306a36Sopenharmony_ci				   usdt_cookie, &targets, &target_cnt);
99262306a36Sopenharmony_ci	if (err <= 0) {
99362306a36Sopenharmony_ci		err = (err == 0) ? -ENOENT : err;
99462306a36Sopenharmony_ci		goto err_out;
99562306a36Sopenharmony_ci	}
99662306a36Sopenharmony_ci
99762306a36Sopenharmony_ci	specs_hash = hashmap__new(specs_hash_fn, specs_equal_fn, NULL);
99862306a36Sopenharmony_ci	if (IS_ERR(specs_hash)) {
99962306a36Sopenharmony_ci		err = PTR_ERR(specs_hash);
100062306a36Sopenharmony_ci		goto err_out;
100162306a36Sopenharmony_ci	}
100262306a36Sopenharmony_ci
100362306a36Sopenharmony_ci	link = calloc(1, sizeof(*link));
100462306a36Sopenharmony_ci	if (!link) {
100562306a36Sopenharmony_ci		err = -ENOMEM;
100662306a36Sopenharmony_ci		goto err_out;
100762306a36Sopenharmony_ci	}
100862306a36Sopenharmony_ci
100962306a36Sopenharmony_ci	link->usdt_man = man;
101062306a36Sopenharmony_ci	link->link.detach = &bpf_link_usdt_detach;
101162306a36Sopenharmony_ci	link->link.dealloc = &bpf_link_usdt_dealloc;
101262306a36Sopenharmony_ci
101362306a36Sopenharmony_ci	if (man->has_uprobe_multi) {
101462306a36Sopenharmony_ci		offsets = calloc(target_cnt, sizeof(*offsets));
101562306a36Sopenharmony_ci		cookies = calloc(target_cnt, sizeof(*cookies));
101662306a36Sopenharmony_ci		ref_ctr_offsets = calloc(target_cnt, sizeof(*ref_ctr_offsets));
101762306a36Sopenharmony_ci
101862306a36Sopenharmony_ci		if (!offsets || !ref_ctr_offsets || !cookies) {
101962306a36Sopenharmony_ci			err = -ENOMEM;
102062306a36Sopenharmony_ci			goto err_out;
102162306a36Sopenharmony_ci		}
102262306a36Sopenharmony_ci	} else {
102362306a36Sopenharmony_ci		link->uprobes = calloc(target_cnt, sizeof(*link->uprobes));
102462306a36Sopenharmony_ci		if (!link->uprobes) {
102562306a36Sopenharmony_ci			err = -ENOMEM;
102662306a36Sopenharmony_ci			goto err_out;
102762306a36Sopenharmony_ci		}
102862306a36Sopenharmony_ci	}
102962306a36Sopenharmony_ci
103062306a36Sopenharmony_ci	for (i = 0; i < target_cnt; i++) {
103162306a36Sopenharmony_ci		struct usdt_target *target = &targets[i];
103262306a36Sopenharmony_ci		struct bpf_link *uprobe_link;
103362306a36Sopenharmony_ci		bool is_new;
103462306a36Sopenharmony_ci		int spec_id;
103562306a36Sopenharmony_ci
103662306a36Sopenharmony_ci		/* Spec ID can be either reused or newly allocated. If it is
103762306a36Sopenharmony_ci		 * newly allocated, we'll need to fill out spec map, otherwise
103862306a36Sopenharmony_ci		 * entire spec should be valid and can be just used by a new
103962306a36Sopenharmony_ci		 * uprobe. We reuse spec when USDT arg spec is identical. We
104062306a36Sopenharmony_ci		 * also never share specs between two different USDT
104162306a36Sopenharmony_ci		 * attachments ("links"), so all the reused specs already
104262306a36Sopenharmony_ci		 * share USDT cookie value implicitly.
104362306a36Sopenharmony_ci		 */
104462306a36Sopenharmony_ci		err = allocate_spec_id(man, specs_hash, link, target, &spec_id, &is_new);
104562306a36Sopenharmony_ci		if (err)
104662306a36Sopenharmony_ci			goto err_out;
104762306a36Sopenharmony_ci
104862306a36Sopenharmony_ci		if (is_new && bpf_map_update_elem(spec_map_fd, &spec_id, &target->spec, BPF_ANY)) {
104962306a36Sopenharmony_ci			err = -errno;
105062306a36Sopenharmony_ci			pr_warn("usdt: failed to set USDT spec #%d for '%s:%s' in '%s': %d\n",
105162306a36Sopenharmony_ci				spec_id, usdt_provider, usdt_name, path, err);
105262306a36Sopenharmony_ci			goto err_out;
105362306a36Sopenharmony_ci		}
105462306a36Sopenharmony_ci		if (!man->has_bpf_cookie &&
105562306a36Sopenharmony_ci		    bpf_map_update_elem(ip_map_fd, &target->abs_ip, &spec_id, BPF_NOEXIST)) {
105662306a36Sopenharmony_ci			err = -errno;
105762306a36Sopenharmony_ci			if (err == -EEXIST) {
105862306a36Sopenharmony_ci				pr_warn("usdt: IP collision detected for spec #%d for '%s:%s' in '%s'\n",
105962306a36Sopenharmony_ci				        spec_id, usdt_provider, usdt_name, path);
106062306a36Sopenharmony_ci			} else {
106162306a36Sopenharmony_ci				pr_warn("usdt: failed to map IP 0x%lx to spec #%d for '%s:%s' in '%s': %d\n",
106262306a36Sopenharmony_ci					target->abs_ip, spec_id, usdt_provider, usdt_name,
106362306a36Sopenharmony_ci					path, err);
106462306a36Sopenharmony_ci			}
106562306a36Sopenharmony_ci			goto err_out;
106662306a36Sopenharmony_ci		}
106762306a36Sopenharmony_ci
106862306a36Sopenharmony_ci		if (man->has_uprobe_multi) {
106962306a36Sopenharmony_ci			offsets[i] = target->rel_ip;
107062306a36Sopenharmony_ci			ref_ctr_offsets[i] = target->sema_off;
107162306a36Sopenharmony_ci			cookies[i] = spec_id;
107262306a36Sopenharmony_ci		} else {
107362306a36Sopenharmony_ci			opts.ref_ctr_offset = target->sema_off;
107462306a36Sopenharmony_ci			opts.bpf_cookie = man->has_bpf_cookie ? spec_id : 0;
107562306a36Sopenharmony_ci			uprobe_link = bpf_program__attach_uprobe_opts(prog, pid, path,
107662306a36Sopenharmony_ci								      target->rel_ip, &opts);
107762306a36Sopenharmony_ci			err = libbpf_get_error(uprobe_link);
107862306a36Sopenharmony_ci			if (err) {
107962306a36Sopenharmony_ci				pr_warn("usdt: failed to attach uprobe #%d for '%s:%s' in '%s': %d\n",
108062306a36Sopenharmony_ci					i, usdt_provider, usdt_name, path, err);
108162306a36Sopenharmony_ci				goto err_out;
108262306a36Sopenharmony_ci			}
108362306a36Sopenharmony_ci
108462306a36Sopenharmony_ci			link->uprobes[i].link = uprobe_link;
108562306a36Sopenharmony_ci			link->uprobes[i].abs_ip = target->abs_ip;
108662306a36Sopenharmony_ci			link->uprobe_cnt++;
108762306a36Sopenharmony_ci		}
108862306a36Sopenharmony_ci	}
108962306a36Sopenharmony_ci
109062306a36Sopenharmony_ci	if (man->has_uprobe_multi) {
109162306a36Sopenharmony_ci		LIBBPF_OPTS(bpf_uprobe_multi_opts, opts_multi,
109262306a36Sopenharmony_ci			.ref_ctr_offsets = ref_ctr_offsets,
109362306a36Sopenharmony_ci			.offsets = offsets,
109462306a36Sopenharmony_ci			.cookies = cookies,
109562306a36Sopenharmony_ci			.cnt = target_cnt,
109662306a36Sopenharmony_ci		);
109762306a36Sopenharmony_ci
109862306a36Sopenharmony_ci		link->multi_link = bpf_program__attach_uprobe_multi(prog, pid, path,
109962306a36Sopenharmony_ci								    NULL, &opts_multi);
110062306a36Sopenharmony_ci		if (!link->multi_link) {
110162306a36Sopenharmony_ci			err = -errno;
110262306a36Sopenharmony_ci			pr_warn("usdt: failed to attach uprobe multi for '%s:%s' in '%s': %d\n",
110362306a36Sopenharmony_ci				usdt_provider, usdt_name, path, err);
110462306a36Sopenharmony_ci			goto err_out;
110562306a36Sopenharmony_ci		}
110662306a36Sopenharmony_ci
110762306a36Sopenharmony_ci		free(offsets);
110862306a36Sopenharmony_ci		free(ref_ctr_offsets);
110962306a36Sopenharmony_ci		free(cookies);
111062306a36Sopenharmony_ci	}
111162306a36Sopenharmony_ci
111262306a36Sopenharmony_ci	free(targets);
111362306a36Sopenharmony_ci	hashmap__free(specs_hash);
111462306a36Sopenharmony_ci	elf_close(&elf_fd);
111562306a36Sopenharmony_ci	return &link->link;
111662306a36Sopenharmony_ci
111762306a36Sopenharmony_cierr_out:
111862306a36Sopenharmony_ci	free(offsets);
111962306a36Sopenharmony_ci	free(ref_ctr_offsets);
112062306a36Sopenharmony_ci	free(cookies);
112162306a36Sopenharmony_ci
112262306a36Sopenharmony_ci	if (link)
112362306a36Sopenharmony_ci		bpf_link__destroy(&link->link);
112462306a36Sopenharmony_ci	free(targets);
112562306a36Sopenharmony_ci	hashmap__free(specs_hash);
112662306a36Sopenharmony_ci	elf_close(&elf_fd);
112762306a36Sopenharmony_ci	return libbpf_err_ptr(err);
112862306a36Sopenharmony_ci}
112962306a36Sopenharmony_ci
113062306a36Sopenharmony_ci/* Parse out USDT ELF note from '.note.stapsdt' section.
113162306a36Sopenharmony_ci * Logic inspired by perf's code.
113262306a36Sopenharmony_ci */
113362306a36Sopenharmony_cistatic int parse_usdt_note(Elf *elf, const char *path, GElf_Nhdr *nhdr,
113462306a36Sopenharmony_ci			   const char *data, size_t name_off, size_t desc_off,
113562306a36Sopenharmony_ci			   struct usdt_note *note)
113662306a36Sopenharmony_ci{
113762306a36Sopenharmony_ci	const char *provider, *name, *args;
113862306a36Sopenharmony_ci	long addrs[3];
113962306a36Sopenharmony_ci	size_t len;
114062306a36Sopenharmony_ci
114162306a36Sopenharmony_ci	/* sanity check USDT note name and type first */
114262306a36Sopenharmony_ci	if (strncmp(data + name_off, USDT_NOTE_NAME, nhdr->n_namesz) != 0)
114362306a36Sopenharmony_ci		return -EINVAL;
114462306a36Sopenharmony_ci	if (nhdr->n_type != USDT_NOTE_TYPE)
114562306a36Sopenharmony_ci		return -EINVAL;
114662306a36Sopenharmony_ci
114762306a36Sopenharmony_ci	/* sanity check USDT note contents ("description" in ELF terminology) */
114862306a36Sopenharmony_ci	len = nhdr->n_descsz;
114962306a36Sopenharmony_ci	data = data + desc_off;
115062306a36Sopenharmony_ci
115162306a36Sopenharmony_ci	/* +3 is the very minimum required to store three empty strings */
115262306a36Sopenharmony_ci	if (len < sizeof(addrs) + 3)
115362306a36Sopenharmony_ci		return -EINVAL;
115462306a36Sopenharmony_ci
115562306a36Sopenharmony_ci	/* get location, base, and semaphore addrs */
115662306a36Sopenharmony_ci	memcpy(&addrs, data, sizeof(addrs));
115762306a36Sopenharmony_ci
115862306a36Sopenharmony_ci	/* parse string fields: provider, name, args */
115962306a36Sopenharmony_ci	provider = data + sizeof(addrs);
116062306a36Sopenharmony_ci
116162306a36Sopenharmony_ci	name = (const char *)memchr(provider, '\0', data + len - provider);
116262306a36Sopenharmony_ci	if (!name) /* non-zero-terminated provider */
116362306a36Sopenharmony_ci		return -EINVAL;
116462306a36Sopenharmony_ci	name++;
116562306a36Sopenharmony_ci	if (name >= data + len || *name == '\0') /* missing or empty name */
116662306a36Sopenharmony_ci		return -EINVAL;
116762306a36Sopenharmony_ci
116862306a36Sopenharmony_ci	args = memchr(name, '\0', data + len - name);
116962306a36Sopenharmony_ci	if (!args) /* non-zero-terminated name */
117062306a36Sopenharmony_ci		return -EINVAL;
117162306a36Sopenharmony_ci	++args;
117262306a36Sopenharmony_ci	if (args >= data + len) /* missing arguments spec */
117362306a36Sopenharmony_ci		return -EINVAL;
117462306a36Sopenharmony_ci
117562306a36Sopenharmony_ci	note->provider = provider;
117662306a36Sopenharmony_ci	note->name = name;
117762306a36Sopenharmony_ci	if (*args == '\0' || *args == ':')
117862306a36Sopenharmony_ci		note->args = "";
117962306a36Sopenharmony_ci	else
118062306a36Sopenharmony_ci		note->args = args;
118162306a36Sopenharmony_ci	note->loc_addr = addrs[0];
118262306a36Sopenharmony_ci	note->base_addr = addrs[1];
118362306a36Sopenharmony_ci	note->sema_addr = addrs[2];
118462306a36Sopenharmony_ci
118562306a36Sopenharmony_ci	return 0;
118662306a36Sopenharmony_ci}
118762306a36Sopenharmony_ci
118862306a36Sopenharmony_cistatic int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz);
118962306a36Sopenharmony_ci
119062306a36Sopenharmony_cistatic int parse_usdt_spec(struct usdt_spec *spec, const struct usdt_note *note, __u64 usdt_cookie)
119162306a36Sopenharmony_ci{
119262306a36Sopenharmony_ci	struct usdt_arg_spec *arg;
119362306a36Sopenharmony_ci	const char *s;
119462306a36Sopenharmony_ci	int arg_sz, len;
119562306a36Sopenharmony_ci
119662306a36Sopenharmony_ci	spec->usdt_cookie = usdt_cookie;
119762306a36Sopenharmony_ci	spec->arg_cnt = 0;
119862306a36Sopenharmony_ci
119962306a36Sopenharmony_ci	s = note->args;
120062306a36Sopenharmony_ci	while (s[0]) {
120162306a36Sopenharmony_ci		if (spec->arg_cnt >= USDT_MAX_ARG_CNT) {
120262306a36Sopenharmony_ci			pr_warn("usdt: too many USDT arguments (> %d) for '%s:%s' with args spec '%s'\n",
120362306a36Sopenharmony_ci				USDT_MAX_ARG_CNT, note->provider, note->name, note->args);
120462306a36Sopenharmony_ci			return -E2BIG;
120562306a36Sopenharmony_ci		}
120662306a36Sopenharmony_ci
120762306a36Sopenharmony_ci		arg = &spec->args[spec->arg_cnt];
120862306a36Sopenharmony_ci		len = parse_usdt_arg(s, spec->arg_cnt, arg, &arg_sz);
120962306a36Sopenharmony_ci		if (len < 0)
121062306a36Sopenharmony_ci			return len;
121162306a36Sopenharmony_ci
121262306a36Sopenharmony_ci		arg->arg_signed = arg_sz < 0;
121362306a36Sopenharmony_ci		if (arg_sz < 0)
121462306a36Sopenharmony_ci			arg_sz = -arg_sz;
121562306a36Sopenharmony_ci
121662306a36Sopenharmony_ci		switch (arg_sz) {
121762306a36Sopenharmony_ci		case 1: case 2: case 4: case 8:
121862306a36Sopenharmony_ci			arg->arg_bitshift = 64 - arg_sz * 8;
121962306a36Sopenharmony_ci			break;
122062306a36Sopenharmony_ci		default:
122162306a36Sopenharmony_ci			pr_warn("usdt: unsupported arg #%d (spec '%s') size: %d\n",
122262306a36Sopenharmony_ci				spec->arg_cnt, s, arg_sz);
122362306a36Sopenharmony_ci			return -EINVAL;
122462306a36Sopenharmony_ci		}
122562306a36Sopenharmony_ci
122662306a36Sopenharmony_ci		s += len;
122762306a36Sopenharmony_ci		spec->arg_cnt++;
122862306a36Sopenharmony_ci	}
122962306a36Sopenharmony_ci
123062306a36Sopenharmony_ci	return 0;
123162306a36Sopenharmony_ci}
123262306a36Sopenharmony_ci
123362306a36Sopenharmony_ci/* Architecture-specific logic for parsing USDT argument location specs */
123462306a36Sopenharmony_ci
123562306a36Sopenharmony_ci#if defined(__x86_64__) || defined(__i386__)
123662306a36Sopenharmony_ci
123762306a36Sopenharmony_cistatic int calc_pt_regs_off(const char *reg_name)
123862306a36Sopenharmony_ci{
123962306a36Sopenharmony_ci	static struct {
124062306a36Sopenharmony_ci		const char *names[4];
124162306a36Sopenharmony_ci		size_t pt_regs_off;
124262306a36Sopenharmony_ci	} reg_map[] = {
124362306a36Sopenharmony_ci#ifdef __x86_64__
124462306a36Sopenharmony_ci#define reg_off(reg64, reg32) offsetof(struct pt_regs, reg64)
124562306a36Sopenharmony_ci#else
124662306a36Sopenharmony_ci#define reg_off(reg64, reg32) offsetof(struct pt_regs, reg32)
124762306a36Sopenharmony_ci#endif
124862306a36Sopenharmony_ci		{ {"rip", "eip", "", ""}, reg_off(rip, eip) },
124962306a36Sopenharmony_ci		{ {"rax", "eax", "ax", "al"}, reg_off(rax, eax) },
125062306a36Sopenharmony_ci		{ {"rbx", "ebx", "bx", "bl"}, reg_off(rbx, ebx) },
125162306a36Sopenharmony_ci		{ {"rcx", "ecx", "cx", "cl"}, reg_off(rcx, ecx) },
125262306a36Sopenharmony_ci		{ {"rdx", "edx", "dx", "dl"}, reg_off(rdx, edx) },
125362306a36Sopenharmony_ci		{ {"rsi", "esi", "si", "sil"}, reg_off(rsi, esi) },
125462306a36Sopenharmony_ci		{ {"rdi", "edi", "di", "dil"}, reg_off(rdi, edi) },
125562306a36Sopenharmony_ci		{ {"rbp", "ebp", "bp", "bpl"}, reg_off(rbp, ebp) },
125662306a36Sopenharmony_ci		{ {"rsp", "esp", "sp", "spl"}, reg_off(rsp, esp) },
125762306a36Sopenharmony_ci#undef reg_off
125862306a36Sopenharmony_ci#ifdef __x86_64__
125962306a36Sopenharmony_ci		{ {"r8", "r8d", "r8w", "r8b"}, offsetof(struct pt_regs, r8) },
126062306a36Sopenharmony_ci		{ {"r9", "r9d", "r9w", "r9b"}, offsetof(struct pt_regs, r9) },
126162306a36Sopenharmony_ci		{ {"r10", "r10d", "r10w", "r10b"}, offsetof(struct pt_regs, r10) },
126262306a36Sopenharmony_ci		{ {"r11", "r11d", "r11w", "r11b"}, offsetof(struct pt_regs, r11) },
126362306a36Sopenharmony_ci		{ {"r12", "r12d", "r12w", "r12b"}, offsetof(struct pt_regs, r12) },
126462306a36Sopenharmony_ci		{ {"r13", "r13d", "r13w", "r13b"}, offsetof(struct pt_regs, r13) },
126562306a36Sopenharmony_ci		{ {"r14", "r14d", "r14w", "r14b"}, offsetof(struct pt_regs, r14) },
126662306a36Sopenharmony_ci		{ {"r15", "r15d", "r15w", "r15b"}, offsetof(struct pt_regs, r15) },
126762306a36Sopenharmony_ci#endif
126862306a36Sopenharmony_ci	};
126962306a36Sopenharmony_ci	int i, j;
127062306a36Sopenharmony_ci
127162306a36Sopenharmony_ci	for (i = 0; i < ARRAY_SIZE(reg_map); i++) {
127262306a36Sopenharmony_ci		for (j = 0; j < ARRAY_SIZE(reg_map[i].names); j++) {
127362306a36Sopenharmony_ci			if (strcmp(reg_name, reg_map[i].names[j]) == 0)
127462306a36Sopenharmony_ci				return reg_map[i].pt_regs_off;
127562306a36Sopenharmony_ci		}
127662306a36Sopenharmony_ci	}
127762306a36Sopenharmony_ci
127862306a36Sopenharmony_ci	pr_warn("usdt: unrecognized register '%s'\n", reg_name);
127962306a36Sopenharmony_ci	return -ENOENT;
128062306a36Sopenharmony_ci}
128162306a36Sopenharmony_ci
128262306a36Sopenharmony_cistatic int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
128362306a36Sopenharmony_ci{
128462306a36Sopenharmony_ci	char reg_name[16];
128562306a36Sopenharmony_ci	int len, reg_off;
128662306a36Sopenharmony_ci	long off;
128762306a36Sopenharmony_ci
128862306a36Sopenharmony_ci	if (sscanf(arg_str, " %d @ %ld ( %%%15[^)] ) %n", arg_sz, &off, reg_name, &len) == 3) {
128962306a36Sopenharmony_ci		/* Memory dereference case, e.g., -4@-20(%rbp) */
129062306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG_DEREF;
129162306a36Sopenharmony_ci		arg->val_off = off;
129262306a36Sopenharmony_ci		reg_off = calc_pt_regs_off(reg_name);
129362306a36Sopenharmony_ci		if (reg_off < 0)
129462306a36Sopenharmony_ci			return reg_off;
129562306a36Sopenharmony_ci		arg->reg_off = reg_off;
129662306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ ( %%%15[^)] ) %n", arg_sz, reg_name, &len) == 2) {
129762306a36Sopenharmony_ci		/* Memory dereference case without offset, e.g., 8@(%rsp) */
129862306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG_DEREF;
129962306a36Sopenharmony_ci		arg->val_off = 0;
130062306a36Sopenharmony_ci		reg_off = calc_pt_regs_off(reg_name);
130162306a36Sopenharmony_ci		if (reg_off < 0)
130262306a36Sopenharmony_ci			return reg_off;
130362306a36Sopenharmony_ci		arg->reg_off = reg_off;
130462306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ %%%15s %n", arg_sz, reg_name, &len) == 2) {
130562306a36Sopenharmony_ci		/* Register read case, e.g., -4@%eax */
130662306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG;
130762306a36Sopenharmony_ci		arg->val_off = 0;
130862306a36Sopenharmony_ci
130962306a36Sopenharmony_ci		reg_off = calc_pt_regs_off(reg_name);
131062306a36Sopenharmony_ci		if (reg_off < 0)
131162306a36Sopenharmony_ci			return reg_off;
131262306a36Sopenharmony_ci		arg->reg_off = reg_off;
131362306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ $%ld %n", arg_sz, &off, &len) == 2) {
131462306a36Sopenharmony_ci		/* Constant value case, e.g., 4@$71 */
131562306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_CONST;
131662306a36Sopenharmony_ci		arg->val_off = off;
131762306a36Sopenharmony_ci		arg->reg_off = 0;
131862306a36Sopenharmony_ci	} else {
131962306a36Sopenharmony_ci		pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
132062306a36Sopenharmony_ci		return -EINVAL;
132162306a36Sopenharmony_ci	}
132262306a36Sopenharmony_ci
132362306a36Sopenharmony_ci	return len;
132462306a36Sopenharmony_ci}
132562306a36Sopenharmony_ci
132662306a36Sopenharmony_ci#elif defined(__s390x__)
132762306a36Sopenharmony_ci
132862306a36Sopenharmony_ci/* Do not support __s390__ for now, since user_pt_regs is broken with -m31. */
132962306a36Sopenharmony_ci
133062306a36Sopenharmony_cistatic int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
133162306a36Sopenharmony_ci{
133262306a36Sopenharmony_ci	unsigned int reg;
133362306a36Sopenharmony_ci	int len;
133462306a36Sopenharmony_ci	long off;
133562306a36Sopenharmony_ci
133662306a36Sopenharmony_ci	if (sscanf(arg_str, " %d @ %ld ( %%r%u ) %n", arg_sz, &off, &reg, &len) == 3) {
133762306a36Sopenharmony_ci		/* Memory dereference case, e.g., -2@-28(%r15) */
133862306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG_DEREF;
133962306a36Sopenharmony_ci		arg->val_off = off;
134062306a36Sopenharmony_ci		if (reg > 15) {
134162306a36Sopenharmony_ci			pr_warn("usdt: unrecognized register '%%r%u'\n", reg);
134262306a36Sopenharmony_ci			return -EINVAL;
134362306a36Sopenharmony_ci		}
134462306a36Sopenharmony_ci		arg->reg_off = offsetof(user_pt_regs, gprs[reg]);
134562306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ %%r%u %n", arg_sz, &reg, &len) == 2) {
134662306a36Sopenharmony_ci		/* Register read case, e.g., -8@%r0 */
134762306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG;
134862306a36Sopenharmony_ci		arg->val_off = 0;
134962306a36Sopenharmony_ci		if (reg > 15) {
135062306a36Sopenharmony_ci			pr_warn("usdt: unrecognized register '%%r%u'\n", reg);
135162306a36Sopenharmony_ci			return -EINVAL;
135262306a36Sopenharmony_ci		}
135362306a36Sopenharmony_ci		arg->reg_off = offsetof(user_pt_regs, gprs[reg]);
135462306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ %ld %n", arg_sz, &off, &len) == 2) {
135562306a36Sopenharmony_ci		/* Constant value case, e.g., 4@71 */
135662306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_CONST;
135762306a36Sopenharmony_ci		arg->val_off = off;
135862306a36Sopenharmony_ci		arg->reg_off = 0;
135962306a36Sopenharmony_ci	} else {
136062306a36Sopenharmony_ci		pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
136162306a36Sopenharmony_ci		return -EINVAL;
136262306a36Sopenharmony_ci	}
136362306a36Sopenharmony_ci
136462306a36Sopenharmony_ci	return len;
136562306a36Sopenharmony_ci}
136662306a36Sopenharmony_ci
136762306a36Sopenharmony_ci#elif defined(__aarch64__)
136862306a36Sopenharmony_ci
136962306a36Sopenharmony_cistatic int calc_pt_regs_off(const char *reg_name)
137062306a36Sopenharmony_ci{
137162306a36Sopenharmony_ci	int reg_num;
137262306a36Sopenharmony_ci
137362306a36Sopenharmony_ci	if (sscanf(reg_name, "x%d", &reg_num) == 1) {
137462306a36Sopenharmony_ci		if (reg_num >= 0 && reg_num < 31)
137562306a36Sopenharmony_ci			return offsetof(struct user_pt_regs, regs[reg_num]);
137662306a36Sopenharmony_ci	} else if (strcmp(reg_name, "sp") == 0) {
137762306a36Sopenharmony_ci		return offsetof(struct user_pt_regs, sp);
137862306a36Sopenharmony_ci	}
137962306a36Sopenharmony_ci	pr_warn("usdt: unrecognized register '%s'\n", reg_name);
138062306a36Sopenharmony_ci	return -ENOENT;
138162306a36Sopenharmony_ci}
138262306a36Sopenharmony_ci
138362306a36Sopenharmony_cistatic int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
138462306a36Sopenharmony_ci{
138562306a36Sopenharmony_ci	char reg_name[16];
138662306a36Sopenharmony_ci	int len, reg_off;
138762306a36Sopenharmony_ci	long off;
138862306a36Sopenharmony_ci
138962306a36Sopenharmony_ci	if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] , %ld ] %n", arg_sz, reg_name, &off, &len) == 3) {
139062306a36Sopenharmony_ci		/* Memory dereference case, e.g., -4@[sp, 96] */
139162306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG_DEREF;
139262306a36Sopenharmony_ci		arg->val_off = off;
139362306a36Sopenharmony_ci		reg_off = calc_pt_regs_off(reg_name);
139462306a36Sopenharmony_ci		if (reg_off < 0)
139562306a36Sopenharmony_ci			return reg_off;
139662306a36Sopenharmony_ci		arg->reg_off = reg_off;
139762306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] ] %n", arg_sz, reg_name, &len) == 2) {
139862306a36Sopenharmony_ci		/* Memory dereference case, e.g., -4@[sp] */
139962306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG_DEREF;
140062306a36Sopenharmony_ci		arg->val_off = 0;
140162306a36Sopenharmony_ci		reg_off = calc_pt_regs_off(reg_name);
140262306a36Sopenharmony_ci		if (reg_off < 0)
140362306a36Sopenharmony_ci			return reg_off;
140462306a36Sopenharmony_ci		arg->reg_off = reg_off;
140562306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ %ld %n", arg_sz, &off, &len) == 2) {
140662306a36Sopenharmony_ci		/* Constant value case, e.g., 4@5 */
140762306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_CONST;
140862306a36Sopenharmony_ci		arg->val_off = off;
140962306a36Sopenharmony_ci		arg->reg_off = 0;
141062306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ %15[a-z0-9] %n", arg_sz, reg_name, &len) == 2) {
141162306a36Sopenharmony_ci		/* Register read case, e.g., -8@x4 */
141262306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG;
141362306a36Sopenharmony_ci		arg->val_off = 0;
141462306a36Sopenharmony_ci		reg_off = calc_pt_regs_off(reg_name);
141562306a36Sopenharmony_ci		if (reg_off < 0)
141662306a36Sopenharmony_ci			return reg_off;
141762306a36Sopenharmony_ci		arg->reg_off = reg_off;
141862306a36Sopenharmony_ci	} else {
141962306a36Sopenharmony_ci		pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
142062306a36Sopenharmony_ci		return -EINVAL;
142162306a36Sopenharmony_ci	}
142262306a36Sopenharmony_ci
142362306a36Sopenharmony_ci	return len;
142462306a36Sopenharmony_ci}
142562306a36Sopenharmony_ci
142662306a36Sopenharmony_ci#elif defined(__riscv)
142762306a36Sopenharmony_ci
142862306a36Sopenharmony_cistatic int calc_pt_regs_off(const char *reg_name)
142962306a36Sopenharmony_ci{
143062306a36Sopenharmony_ci	static struct {
143162306a36Sopenharmony_ci		const char *name;
143262306a36Sopenharmony_ci		size_t pt_regs_off;
143362306a36Sopenharmony_ci	} reg_map[] = {
143462306a36Sopenharmony_ci		{ "ra", offsetof(struct user_regs_struct, ra) },
143562306a36Sopenharmony_ci		{ "sp", offsetof(struct user_regs_struct, sp) },
143662306a36Sopenharmony_ci		{ "gp", offsetof(struct user_regs_struct, gp) },
143762306a36Sopenharmony_ci		{ "tp", offsetof(struct user_regs_struct, tp) },
143862306a36Sopenharmony_ci		{ "a0", offsetof(struct user_regs_struct, a0) },
143962306a36Sopenharmony_ci		{ "a1", offsetof(struct user_regs_struct, a1) },
144062306a36Sopenharmony_ci		{ "a2", offsetof(struct user_regs_struct, a2) },
144162306a36Sopenharmony_ci		{ "a3", offsetof(struct user_regs_struct, a3) },
144262306a36Sopenharmony_ci		{ "a4", offsetof(struct user_regs_struct, a4) },
144362306a36Sopenharmony_ci		{ "a5", offsetof(struct user_regs_struct, a5) },
144462306a36Sopenharmony_ci		{ "a6", offsetof(struct user_regs_struct, a6) },
144562306a36Sopenharmony_ci		{ "a7", offsetof(struct user_regs_struct, a7) },
144662306a36Sopenharmony_ci		{ "s0", offsetof(struct user_regs_struct, s0) },
144762306a36Sopenharmony_ci		{ "s1", offsetof(struct user_regs_struct, s1) },
144862306a36Sopenharmony_ci		{ "s2", offsetof(struct user_regs_struct, s2) },
144962306a36Sopenharmony_ci		{ "s3", offsetof(struct user_regs_struct, s3) },
145062306a36Sopenharmony_ci		{ "s4", offsetof(struct user_regs_struct, s4) },
145162306a36Sopenharmony_ci		{ "s5", offsetof(struct user_regs_struct, s5) },
145262306a36Sopenharmony_ci		{ "s6", offsetof(struct user_regs_struct, s6) },
145362306a36Sopenharmony_ci		{ "s7", offsetof(struct user_regs_struct, s7) },
145462306a36Sopenharmony_ci		{ "s8", offsetof(struct user_regs_struct, rv_s8) },
145562306a36Sopenharmony_ci		{ "s9", offsetof(struct user_regs_struct, s9) },
145662306a36Sopenharmony_ci		{ "s10", offsetof(struct user_regs_struct, s10) },
145762306a36Sopenharmony_ci		{ "s11", offsetof(struct user_regs_struct, s11) },
145862306a36Sopenharmony_ci		{ "t0", offsetof(struct user_regs_struct, t0) },
145962306a36Sopenharmony_ci		{ "t1", offsetof(struct user_regs_struct, t1) },
146062306a36Sopenharmony_ci		{ "t2", offsetof(struct user_regs_struct, t2) },
146162306a36Sopenharmony_ci		{ "t3", offsetof(struct user_regs_struct, t3) },
146262306a36Sopenharmony_ci		{ "t4", offsetof(struct user_regs_struct, t4) },
146362306a36Sopenharmony_ci		{ "t5", offsetof(struct user_regs_struct, t5) },
146462306a36Sopenharmony_ci		{ "t6", offsetof(struct user_regs_struct, t6) },
146562306a36Sopenharmony_ci	};
146662306a36Sopenharmony_ci	int i;
146762306a36Sopenharmony_ci
146862306a36Sopenharmony_ci	for (i = 0; i < ARRAY_SIZE(reg_map); i++) {
146962306a36Sopenharmony_ci		if (strcmp(reg_name, reg_map[i].name) == 0)
147062306a36Sopenharmony_ci			return reg_map[i].pt_regs_off;
147162306a36Sopenharmony_ci	}
147262306a36Sopenharmony_ci
147362306a36Sopenharmony_ci	pr_warn("usdt: unrecognized register '%s'\n", reg_name);
147462306a36Sopenharmony_ci	return -ENOENT;
147562306a36Sopenharmony_ci}
147662306a36Sopenharmony_ci
147762306a36Sopenharmony_cistatic int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
147862306a36Sopenharmony_ci{
147962306a36Sopenharmony_ci	char reg_name[16];
148062306a36Sopenharmony_ci	int len, reg_off;
148162306a36Sopenharmony_ci	long off;
148262306a36Sopenharmony_ci
148362306a36Sopenharmony_ci	if (sscanf(arg_str, " %d @ %ld ( %15[a-z0-9] ) %n", arg_sz, &off, reg_name, &len) == 3) {
148462306a36Sopenharmony_ci		/* Memory dereference case, e.g., -8@-88(s0) */
148562306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG_DEREF;
148662306a36Sopenharmony_ci		arg->val_off = off;
148762306a36Sopenharmony_ci		reg_off = calc_pt_regs_off(reg_name);
148862306a36Sopenharmony_ci		if (reg_off < 0)
148962306a36Sopenharmony_ci			return reg_off;
149062306a36Sopenharmony_ci		arg->reg_off = reg_off;
149162306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ %ld %n", arg_sz, &off, &len) == 2) {
149262306a36Sopenharmony_ci		/* Constant value case, e.g., 4@5 */
149362306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_CONST;
149462306a36Sopenharmony_ci		arg->val_off = off;
149562306a36Sopenharmony_ci		arg->reg_off = 0;
149662306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ %15[a-z0-9] %n", arg_sz, reg_name, &len) == 2) {
149762306a36Sopenharmony_ci		/* Register read case, e.g., -8@a1 */
149862306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG;
149962306a36Sopenharmony_ci		arg->val_off = 0;
150062306a36Sopenharmony_ci		reg_off = calc_pt_regs_off(reg_name);
150162306a36Sopenharmony_ci		if (reg_off < 0)
150262306a36Sopenharmony_ci			return reg_off;
150362306a36Sopenharmony_ci		arg->reg_off = reg_off;
150462306a36Sopenharmony_ci	} else {
150562306a36Sopenharmony_ci		pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
150662306a36Sopenharmony_ci		return -EINVAL;
150762306a36Sopenharmony_ci	}
150862306a36Sopenharmony_ci
150962306a36Sopenharmony_ci	return len;
151062306a36Sopenharmony_ci}
151162306a36Sopenharmony_ci
151262306a36Sopenharmony_ci#elif defined(__arm__)
151362306a36Sopenharmony_ci
151462306a36Sopenharmony_cistatic int calc_pt_regs_off(const char *reg_name)
151562306a36Sopenharmony_ci{
151662306a36Sopenharmony_ci	static struct {
151762306a36Sopenharmony_ci		const char *name;
151862306a36Sopenharmony_ci		size_t pt_regs_off;
151962306a36Sopenharmony_ci	} reg_map[] = {
152062306a36Sopenharmony_ci		{ "r0", offsetof(struct pt_regs, uregs[0]) },
152162306a36Sopenharmony_ci		{ "r1", offsetof(struct pt_regs, uregs[1]) },
152262306a36Sopenharmony_ci		{ "r2", offsetof(struct pt_regs, uregs[2]) },
152362306a36Sopenharmony_ci		{ "r3", offsetof(struct pt_regs, uregs[3]) },
152462306a36Sopenharmony_ci		{ "r4", offsetof(struct pt_regs, uregs[4]) },
152562306a36Sopenharmony_ci		{ "r5", offsetof(struct pt_regs, uregs[5]) },
152662306a36Sopenharmony_ci		{ "r6", offsetof(struct pt_regs, uregs[6]) },
152762306a36Sopenharmony_ci		{ "r7", offsetof(struct pt_regs, uregs[7]) },
152862306a36Sopenharmony_ci		{ "r8", offsetof(struct pt_regs, uregs[8]) },
152962306a36Sopenharmony_ci		{ "r9", offsetof(struct pt_regs, uregs[9]) },
153062306a36Sopenharmony_ci		{ "r10", offsetof(struct pt_regs, uregs[10]) },
153162306a36Sopenharmony_ci		{ "fp", offsetof(struct pt_regs, uregs[11]) },
153262306a36Sopenharmony_ci		{ "ip", offsetof(struct pt_regs, uregs[12]) },
153362306a36Sopenharmony_ci		{ "sp", offsetof(struct pt_regs, uregs[13]) },
153462306a36Sopenharmony_ci		{ "lr", offsetof(struct pt_regs, uregs[14]) },
153562306a36Sopenharmony_ci		{ "pc", offsetof(struct pt_regs, uregs[15]) },
153662306a36Sopenharmony_ci	};
153762306a36Sopenharmony_ci	int i;
153862306a36Sopenharmony_ci
153962306a36Sopenharmony_ci	for (i = 0; i < ARRAY_SIZE(reg_map); i++) {
154062306a36Sopenharmony_ci		if (strcmp(reg_name, reg_map[i].name) == 0)
154162306a36Sopenharmony_ci			return reg_map[i].pt_regs_off;
154262306a36Sopenharmony_ci	}
154362306a36Sopenharmony_ci
154462306a36Sopenharmony_ci	pr_warn("usdt: unrecognized register '%s'\n", reg_name);
154562306a36Sopenharmony_ci	return -ENOENT;
154662306a36Sopenharmony_ci}
154762306a36Sopenharmony_ci
154862306a36Sopenharmony_cistatic int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
154962306a36Sopenharmony_ci{
155062306a36Sopenharmony_ci	char reg_name[16];
155162306a36Sopenharmony_ci	int len, reg_off;
155262306a36Sopenharmony_ci	long off;
155362306a36Sopenharmony_ci
155462306a36Sopenharmony_ci	if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] , #%ld ] %n",
155562306a36Sopenharmony_ci		   arg_sz, reg_name, &off, &len) == 3) {
155662306a36Sopenharmony_ci		/* Memory dereference case, e.g., -4@[fp, #96] */
155762306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG_DEREF;
155862306a36Sopenharmony_ci		arg->val_off = off;
155962306a36Sopenharmony_ci		reg_off = calc_pt_regs_off(reg_name);
156062306a36Sopenharmony_ci		if (reg_off < 0)
156162306a36Sopenharmony_ci			return reg_off;
156262306a36Sopenharmony_ci		arg->reg_off = reg_off;
156362306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] ] %n", arg_sz, reg_name, &len) == 2) {
156462306a36Sopenharmony_ci		/* Memory dereference case, e.g., -4@[sp] */
156562306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG_DEREF;
156662306a36Sopenharmony_ci		arg->val_off = 0;
156762306a36Sopenharmony_ci		reg_off = calc_pt_regs_off(reg_name);
156862306a36Sopenharmony_ci		if (reg_off < 0)
156962306a36Sopenharmony_ci			return reg_off;
157062306a36Sopenharmony_ci		arg->reg_off = reg_off;
157162306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ #%ld %n", arg_sz, &off, &len) == 2) {
157262306a36Sopenharmony_ci		/* Constant value case, e.g., 4@#5 */
157362306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_CONST;
157462306a36Sopenharmony_ci		arg->val_off = off;
157562306a36Sopenharmony_ci		arg->reg_off = 0;
157662306a36Sopenharmony_ci	} else if (sscanf(arg_str, " %d @ %15[a-z0-9] %n", arg_sz, reg_name, &len) == 2) {
157762306a36Sopenharmony_ci		/* Register read case, e.g., -8@r4 */
157862306a36Sopenharmony_ci		arg->arg_type = USDT_ARG_REG;
157962306a36Sopenharmony_ci		arg->val_off = 0;
158062306a36Sopenharmony_ci		reg_off = calc_pt_regs_off(reg_name);
158162306a36Sopenharmony_ci		if (reg_off < 0)
158262306a36Sopenharmony_ci			return reg_off;
158362306a36Sopenharmony_ci		arg->reg_off = reg_off;
158462306a36Sopenharmony_ci	} else {
158562306a36Sopenharmony_ci		pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
158662306a36Sopenharmony_ci		return -EINVAL;
158762306a36Sopenharmony_ci	}
158862306a36Sopenharmony_ci
158962306a36Sopenharmony_ci	return len;
159062306a36Sopenharmony_ci}
159162306a36Sopenharmony_ci
159262306a36Sopenharmony_ci#else
159362306a36Sopenharmony_ci
159462306a36Sopenharmony_cistatic int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
159562306a36Sopenharmony_ci{
159662306a36Sopenharmony_ci	pr_warn("usdt: libbpf doesn't support USDTs on current architecture\n");
159762306a36Sopenharmony_ci	return -ENOTSUP;
159862306a36Sopenharmony_ci}
159962306a36Sopenharmony_ci
160062306a36Sopenharmony_ci#endif
1601