usdt.c 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649
  1. // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
  2. /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
  3. #include <ctype.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <libelf.h>
  8. #include <gelf.h>
  9. #include <unistd.h>
  10. #include <linux/ptrace.h>
  11. #include <linux/kernel.h>
  12. /* s8 will be marked as poison while it's a reg of riscv */
  13. #if defined(__riscv)
  14. #define rv_s8 s8
  15. #endif
  16. #include "bpf.h"
  17. #include "libbpf.h"
  18. #include "libbpf_common.h"
  19. #include "libbpf_internal.h"
  20. #include "hashmap.h"
  21. /* libbpf's USDT support consists of BPF-side state/code and user-space
  22. * state/code working together in concert. BPF-side parts are defined in
  23. * usdt.bpf.h header library. User-space state is encapsulated by struct
  24. * usdt_manager and all the supporting code centered around usdt_manager.
  25. *
  26. * usdt.bpf.h defines two BPF maps that usdt_manager expects: USDT spec map
  27. * and IP-to-spec-ID map, which is auxiliary map necessary for kernels that
  28. * don't support BPF cookie (see below). These two maps are implicitly
  29. * embedded into user's end BPF object file when user's code included
  30. * usdt.bpf.h. This means that libbpf doesn't do anything special to create
  31. * these USDT support maps. They are created by normal libbpf logic of
  32. * instantiating BPF maps when opening and loading BPF object.
  33. *
  34. * As such, libbpf is basically unaware of the need to do anything
  35. * USDT-related until the very first call to bpf_program__attach_usdt(), which
  36. * can be called by user explicitly or happen automatically during skeleton
  37. * attach (or, equivalently, through generic bpf_program__attach() call). At
  38. * this point, libbpf will instantiate and initialize struct usdt_manager and
  39. * store it in bpf_object. USDT manager is per-BPF object construct, as each
  40. * independent BPF object might or might not have USDT programs, and thus all
  41. * the expected USDT-related state. There is no coordination between two
  42. * bpf_object in parts of USDT attachment, they are oblivious of each other's
  43. * existence and libbpf is just oblivious, dealing with bpf_object-specific
  44. * USDT state.
  45. *
  46. * Quick crash course on USDTs.
  47. *
  48. * From user-space application's point of view, USDT is essentially just
  49. * a slightly special function call that normally has zero overhead, unless it
  50. * is being traced by some external entity (e.g, BPF-based tool). Here's how
  51. * a typical application can trigger USDT probe:
  52. *
  53. * #include <sys/sdt.h> // provided by systemtap-sdt-devel package
  54. * // folly also provide similar functionality in folly/tracing/StaticTracepoint.h
  55. *
  56. * STAP_PROBE3(my_usdt_provider, my_usdt_probe_name, 123, x, &y);
  57. *
  58. * USDT is identified by its <provider-name>:<probe-name> pair of names. Each
  59. * individual USDT has a fixed number of arguments (3 in the above example)
  60. * and specifies values of each argument as if it was a function call.
  61. *
  62. * USDT call is actually not a function call, but is instead replaced by
  63. * a single NOP instruction (thus zero overhead, effectively). But in addition
  64. * to that, those USDT macros generate special SHT_NOTE ELF records in
  65. * .note.stapsdt ELF section. Here's an example USDT definition as emitted by
  66. * `readelf -n <binary>`:
  67. *
  68. * stapsdt 0x00000089 NT_STAPSDT (SystemTap probe descriptors)
  69. * Provider: test
  70. * Name: usdt12
  71. * Location: 0x0000000000549df3, Base: 0x00000000008effa4, Semaphore: 0x0000000000a4606e
  72. * 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
  73. *
  74. * In this case we have USDT test:usdt12 with 12 arguments.
  75. *
  76. * Location and base are offsets used to calculate absolute IP address of that
  77. * NOP instruction that kernel can replace with an interrupt instruction to
  78. * trigger instrumentation code (BPF program for all that we care about).
  79. *
  80. * Semaphore above is an optional feature. It records an address of a 2-byte
  81. * refcount variable (normally in '.probes' ELF section) used for signaling if
  82. * there is anything that is attached to USDT. This is useful for user
  83. * applications if, for example, they need to prepare some arguments that are
  84. * passed only to USDTs and preparation is expensive. By checking if USDT is
  85. * "activated", an application can avoid paying those costs unnecessarily.
  86. * Recent enough kernel has built-in support for automatically managing this
  87. * refcount, which libbpf expects and relies on. If USDT is defined without
  88. * associated semaphore, this value will be zero. See selftests for semaphore
  89. * examples.
  90. *
  91. * Arguments is the most interesting part. This USDT specification string is
  92. * providing information about all the USDT arguments and their locations. The
  93. * part before @ sign defined byte size of the argument (1, 2, 4, or 8) and
  94. * whether the argument is signed or unsigned (negative size means signed).
  95. * The part after @ sign is assembly-like definition of argument location
  96. * (see [0] for more details). Technically, assembler can provide some pretty
  97. * advanced definitions, but libbpf is currently supporting three most common
  98. * cases:
  99. * 1) immediate constant, see 5th and 9th args above (-4@$5 and -4@-9);
  100. * 2) register value, e.g., 8@%rdx, which means "unsigned 8-byte integer
  101. * whose value is in register %rdx";
  102. * 3) memory dereference addressed by register, e.g., -4@-1204(%rbp), which
  103. * specifies signed 32-bit integer stored at offset -1204 bytes from
  104. * memory address stored in %rbp.
  105. *
  106. * [0] https://sourceware.org/systemtap/wiki/UserSpaceProbeImplementation
  107. *
  108. * During attachment, libbpf parses all the relevant USDT specifications and
  109. * prepares `struct usdt_spec` (USDT spec), which is then provided to BPF-side
  110. * code through spec map. This allows BPF applications to quickly fetch the
  111. * actual value at runtime using a simple BPF-side code.
  112. *
  113. * With basics out of the way, let's go over less immediately obvious aspects
  114. * of supporting USDTs.
  115. *
  116. * First, there is no special USDT BPF program type. It is actually just
  117. * a uprobe BPF program (which for kernel, at least currently, is just a kprobe
  118. * program, so BPF_PROG_TYPE_KPROBE program type). With the only difference
  119. * that uprobe is usually attached at the function entry, while USDT will
  120. * normally be somewhere inside the function. But it should always be
  121. * pointing to NOP instruction, which makes such uprobes the fastest uprobe
  122. * kind.
  123. *
  124. * Second, it's important to realize that such STAP_PROBEn(provider, name, ...)
  125. * macro invocations can end up being inlined many-many times, depending on
  126. * specifics of each individual user application. So single conceptual USDT
  127. * (identified by provider:name pair of identifiers) is, generally speaking,
  128. * multiple uprobe locations (USDT call sites) in different places in user
  129. * application. Further, again due to inlining, each USDT call site might end
  130. * up having the same argument #N be located in a different place. In one call
  131. * site it could be a constant, in another will end up in a register, and in
  132. * yet another could be some other register or even somewhere on the stack.
  133. *
  134. * As such, "attaching to USDT" means (in general case) attaching the same
  135. * uprobe BPF program to multiple target locations in user application, each
  136. * potentially having a completely different USDT spec associated with it.
  137. * To wire all this up together libbpf allocates a unique integer spec ID for
  138. * each unique USDT spec. Spec IDs are allocated as sequential small integers
  139. * so that they can be used as keys in array BPF map (for performance reasons).
  140. * Spec ID allocation and accounting is big part of what usdt_manager is
  141. * about. This state has to be maintained per-BPF object and coordinate
  142. * between different USDT attachments within the same BPF object.
  143. *
  144. * Spec ID is the key in spec BPF map, value is the actual USDT spec layed out
  145. * as struct usdt_spec. Each invocation of BPF program at runtime needs to
  146. * know its associated spec ID. It gets it either through BPF cookie, which
  147. * libbpf sets to spec ID during attach time, or, if kernel is too old to
  148. * support BPF cookie, through IP-to-spec-ID map that libbpf maintains in such
  149. * case. The latter means that some modes of operation can't be supported
  150. * without BPF cookie. Such a mode is attaching to shared library "generically",
  151. * without specifying target process. In such case, it's impossible to
  152. * calculate absolute IP addresses for IP-to-spec-ID map, and thus such mode
  153. * is not supported without BPF cookie support.
  154. *
  155. * Note that libbpf is using BPF cookie functionality for its own internal
  156. * needs, so user itself can't rely on BPF cookie feature. To that end, libbpf
  157. * provides conceptually equivalent USDT cookie support. It's still u64
  158. * user-provided value that can be associated with USDT attachment. Note that
  159. * this will be the same value for all USDT call sites within the same single
  160. * *logical* USDT attachment. This makes sense because to user attaching to
  161. * USDT is a single BPF program triggered for singular USDT probe. The fact
  162. * that this is done at multiple actual locations is a mostly hidden
  163. * implementation details. This USDT cookie value can be fetched with
  164. * bpf_usdt_cookie(ctx) API provided by usdt.bpf.h
  165. *
  166. * Lastly, while single USDT can have tons of USDT call sites, it doesn't
  167. * necessarily have that many different USDT specs. It very well might be
  168. * that 1000 USDT call sites only need 5 different USDT specs, because all the
  169. * arguments are typically contained in a small set of registers or stack
  170. * locations. As such, it's wasteful to allocate as many USDT spec IDs as
  171. * there are USDT call sites. So libbpf tries to be frugal and performs
  172. * on-the-fly deduplication during a single USDT attachment to only allocate
  173. * the minimal required amount of unique USDT specs (and thus spec IDs). This
  174. * is trivially achieved by using USDT spec string (Arguments string from USDT
  175. * note) as a lookup key in a hashmap. USDT spec string uniquely defines
  176. * everything about how to fetch USDT arguments, so two USDT call sites
  177. * sharing USDT spec string can safely share the same USDT spec and spec ID.
  178. * Note, this spec string deduplication is happening only during the same USDT
  179. * attachment, so each USDT spec shares the same USDT cookie value. This is
  180. * not generally true for other USDT attachments within the same BPF object,
  181. * as even if USDT spec string is the same, USDT cookie value can be
  182. * different. It was deemed excessive to try to deduplicate across independent
  183. * USDT attachments by taking into account USDT spec string *and* USDT cookie
  184. * value, which would complicate spec ID accounting significantly for little
  185. * gain.
  186. */
  187. #define USDT_BASE_SEC ".stapsdt.base"
  188. #define USDT_SEMA_SEC ".probes"
  189. #define USDT_NOTE_SEC ".note.stapsdt"
  190. #define USDT_NOTE_TYPE 3
  191. #define USDT_NOTE_NAME "stapsdt"
  192. /* should match exactly enum __bpf_usdt_arg_type from usdt.bpf.h */
  193. enum usdt_arg_type {
  194. USDT_ARG_CONST,
  195. USDT_ARG_REG,
  196. USDT_ARG_REG_DEREF,
  197. USDT_ARG_SIB,
  198. };
  199. /* should match exactly struct __bpf_usdt_arg_spec from usdt.bpf.h */
  200. struct usdt_arg_spec {
  201. __u64 val_off;
  202. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  203. enum usdt_arg_type arg_type: 8;
  204. __u16 idx_reg_off: 12;
  205. __u16 scale_bitshift: 4;
  206. __u8 __reserved: 8; /* keep reg_off offset stable */
  207. #else
  208. __u8 __reserved: 8; /* keep reg_off offset stable */
  209. __u16 idx_reg_off: 12;
  210. __u16 scale_bitshift: 4;
  211. enum usdt_arg_type arg_type: 8;
  212. #endif
  213. short reg_off;
  214. bool arg_signed;
  215. char arg_bitshift;
  216. };
  217. /* should match BPF_USDT_MAX_ARG_CNT in usdt.bpf.h */
  218. #define USDT_MAX_ARG_CNT 12
  219. /* should match struct __bpf_usdt_spec from usdt.bpf.h */
  220. struct usdt_spec {
  221. struct usdt_arg_spec args[USDT_MAX_ARG_CNT];
  222. __u64 usdt_cookie;
  223. short arg_cnt;
  224. };
  225. struct usdt_note {
  226. const char *provider;
  227. const char *name;
  228. /* USDT args specification string, e.g.:
  229. * "-4@%esi -4@-24(%rbp) -4@%ecx 2@%ax 8@%rdx"
  230. */
  231. const char *args;
  232. long loc_addr;
  233. long base_addr;
  234. long sema_addr;
  235. };
  236. struct usdt_target {
  237. long abs_ip;
  238. long rel_ip;
  239. long sema_off;
  240. struct usdt_spec spec;
  241. const char *spec_str;
  242. };
  243. struct usdt_manager {
  244. struct bpf_map *specs_map;
  245. struct bpf_map *ip_to_spec_id_map;
  246. int *free_spec_ids;
  247. size_t free_spec_cnt;
  248. size_t next_free_spec_id;
  249. bool has_bpf_cookie;
  250. bool has_sema_refcnt;
  251. bool has_uprobe_multi;
  252. };
  253. struct usdt_manager *usdt_manager_new(struct bpf_object *obj)
  254. {
  255. static const char *ref_ctr_sysfs_path = "/sys/bus/event_source/devices/uprobe/format/ref_ctr_offset";
  256. struct usdt_manager *man;
  257. struct bpf_map *specs_map, *ip_to_spec_id_map;
  258. specs_map = bpf_object__find_map_by_name(obj, "__bpf_usdt_specs");
  259. ip_to_spec_id_map = bpf_object__find_map_by_name(obj, "__bpf_usdt_ip_to_spec_id");
  260. if (!specs_map || !ip_to_spec_id_map) {
  261. pr_warn("usdt: failed to find USDT support BPF maps, did you forget to include bpf/usdt.bpf.h?\n");
  262. return ERR_PTR(-ESRCH);
  263. }
  264. man = calloc(1, sizeof(*man));
  265. if (!man)
  266. return ERR_PTR(-ENOMEM);
  267. man->specs_map = specs_map;
  268. man->ip_to_spec_id_map = ip_to_spec_id_map;
  269. /* Detect if BPF cookie is supported for kprobes.
  270. * We don't need IP-to-ID mapping if we can use BPF cookies.
  271. * Added in: 7adfc6c9b315 ("bpf: Add bpf_get_attach_cookie() BPF helper to access bpf_cookie value")
  272. */
  273. man->has_bpf_cookie = kernel_supports(obj, FEAT_BPF_COOKIE);
  274. /* Detect kernel support for automatic refcounting of USDT semaphore.
  275. * If this is not supported, USDTs with semaphores will not be supported.
  276. * Added in: a6ca88b241d5 ("trace_uprobe: support reference counter in fd-based uprobe")
  277. */
  278. man->has_sema_refcnt = faccessat(AT_FDCWD, ref_ctr_sysfs_path, F_OK, AT_EACCESS) == 0;
  279. /*
  280. * Detect kernel support for uprobe multi link to be used for attaching
  281. * usdt probes.
  282. */
  283. man->has_uprobe_multi = kernel_supports(obj, FEAT_UPROBE_MULTI_LINK);
  284. return man;
  285. }
  286. void usdt_manager_free(struct usdt_manager *man)
  287. {
  288. if (IS_ERR_OR_NULL(man))
  289. return;
  290. free(man->free_spec_ids);
  291. free(man);
  292. }
  293. static int sanity_check_usdt_elf(Elf *elf, const char *path)
  294. {
  295. GElf_Ehdr ehdr;
  296. int endianness;
  297. if (elf_kind(elf) != ELF_K_ELF) {
  298. pr_warn("usdt: unrecognized ELF kind %d for '%s'\n", elf_kind(elf), path);
  299. return -EBADF;
  300. }
  301. switch (gelf_getclass(elf)) {
  302. case ELFCLASS64:
  303. if (sizeof(void *) != 8) {
  304. pr_warn("usdt: attaching to 64-bit ELF binary '%s' is not supported\n", path);
  305. return -EBADF;
  306. }
  307. break;
  308. case ELFCLASS32:
  309. if (sizeof(void *) != 4) {
  310. pr_warn("usdt: attaching to 32-bit ELF binary '%s' is not supported\n", path);
  311. return -EBADF;
  312. }
  313. break;
  314. default:
  315. pr_warn("usdt: unsupported ELF class for '%s'\n", path);
  316. return -EBADF;
  317. }
  318. if (!gelf_getehdr(elf, &ehdr))
  319. return -EINVAL;
  320. if (ehdr.e_type != ET_EXEC && ehdr.e_type != ET_DYN) {
  321. pr_warn("usdt: unsupported type of ELF binary '%s' (%d), only ET_EXEC and ET_DYN are supported\n",
  322. path, ehdr.e_type);
  323. return -EBADF;
  324. }
  325. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  326. endianness = ELFDATA2LSB;
  327. #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  328. endianness = ELFDATA2MSB;
  329. #else
  330. # error "Unrecognized __BYTE_ORDER__"
  331. #endif
  332. if (endianness != ehdr.e_ident[EI_DATA]) {
  333. pr_warn("usdt: ELF endianness mismatch for '%s'\n", path);
  334. return -EBADF;
  335. }
  336. return 0;
  337. }
  338. static int find_elf_sec_by_name(Elf *elf, const char *sec_name, GElf_Shdr *shdr, Elf_Scn **scn)
  339. {
  340. Elf_Scn *sec = NULL;
  341. size_t shstrndx;
  342. if (elf_getshdrstrndx(elf, &shstrndx))
  343. return -EINVAL;
  344. /* check if ELF is corrupted and avoid calling elf_strptr if yes */
  345. if (!elf_rawdata(elf_getscn(elf, shstrndx), NULL))
  346. return -EINVAL;
  347. while ((sec = elf_nextscn(elf, sec)) != NULL) {
  348. char *name;
  349. if (!gelf_getshdr(sec, shdr))
  350. return -EINVAL;
  351. name = elf_strptr(elf, shstrndx, shdr->sh_name);
  352. if (name && strcmp(sec_name, name) == 0) {
  353. *scn = sec;
  354. return 0;
  355. }
  356. }
  357. return -ENOENT;
  358. }
  359. struct elf_seg {
  360. long start;
  361. long end;
  362. long offset;
  363. bool is_exec;
  364. };
  365. static int cmp_elf_segs(const void *_a, const void *_b)
  366. {
  367. const struct elf_seg *a = _a;
  368. const struct elf_seg *b = _b;
  369. return a->start < b->start ? -1 : 1;
  370. }
  371. static int parse_elf_segs(Elf *elf, const char *path, struct elf_seg **segs, size_t *seg_cnt)
  372. {
  373. GElf_Phdr phdr;
  374. size_t n;
  375. int i, err;
  376. struct elf_seg *seg;
  377. void *tmp;
  378. *seg_cnt = 0;
  379. if (elf_getphdrnum(elf, &n)) {
  380. err = -errno;
  381. return err;
  382. }
  383. for (i = 0; i < n; i++) {
  384. if (!gelf_getphdr(elf, i, &phdr)) {
  385. err = -errno;
  386. return err;
  387. }
  388. pr_debug("usdt: discovered PHDR #%d in '%s': vaddr 0x%lx memsz 0x%lx offset 0x%lx type 0x%lx flags 0x%lx\n",
  389. i, path, (long)phdr.p_vaddr, (long)phdr.p_memsz, (long)phdr.p_offset,
  390. (long)phdr.p_type, (long)phdr.p_flags);
  391. if (phdr.p_type != PT_LOAD)
  392. continue;
  393. tmp = libbpf_reallocarray(*segs, *seg_cnt + 1, sizeof(**segs));
  394. if (!tmp)
  395. return -ENOMEM;
  396. *segs = tmp;
  397. seg = *segs + *seg_cnt;
  398. (*seg_cnt)++;
  399. seg->start = phdr.p_vaddr;
  400. seg->end = phdr.p_vaddr + phdr.p_memsz;
  401. seg->offset = phdr.p_offset;
  402. seg->is_exec = phdr.p_flags & PF_X;
  403. }
  404. if (*seg_cnt == 0) {
  405. pr_warn("usdt: failed to find PT_LOAD program headers in '%s'\n", path);
  406. return -ESRCH;
  407. }
  408. qsort(*segs, *seg_cnt, sizeof(**segs), cmp_elf_segs);
  409. return 0;
  410. }
  411. static int parse_vma_segs(int pid, const char *lib_path, struct elf_seg **segs, size_t *seg_cnt)
  412. {
  413. char path[PATH_MAX], line[PATH_MAX], mode[16];
  414. size_t seg_start, seg_end, seg_off;
  415. struct elf_seg *seg;
  416. int tmp_pid, i, err;
  417. FILE *f;
  418. *seg_cnt = 0;
  419. /* Handle containerized binaries only accessible from
  420. * /proc/<pid>/root/<path>. They will be reported as just /<path> in
  421. * /proc/<pid>/maps.
  422. */
  423. if (sscanf(lib_path, "/proc/%d/root%s", &tmp_pid, path) == 2 && pid == tmp_pid)
  424. goto proceed;
  425. if (!realpath(lib_path, path)) {
  426. pr_warn("usdt: failed to get absolute path of '%s' (err %s), using path as is...\n",
  427. lib_path, errstr(-errno));
  428. libbpf_strlcpy(path, lib_path, sizeof(path));
  429. }
  430. proceed:
  431. sprintf(line, "/proc/%d/maps", pid);
  432. f = fopen(line, "re");
  433. if (!f) {
  434. err = -errno;
  435. pr_warn("usdt: failed to open '%s' to get base addr of '%s': %s\n",
  436. line, lib_path, errstr(err));
  437. return err;
  438. }
  439. /* We need to handle lines with no path at the end:
  440. *
  441. * 7f5c6f5d1000-7f5c6f5d3000 rw-p 001c7000 08:04 21238613 /usr/lib64/libc-2.17.so
  442. * 7f5c6f5d3000-7f5c6f5d8000 rw-p 00000000 00:00 0
  443. * 7f5c6f5d8000-7f5c6f5d9000 r-xp 00000000 103:01 362990598 /data/users/andriin/linux/tools/bpf/usdt/libhello_usdt.so
  444. */
  445. while (fscanf(f, "%zx-%zx %s %zx %*s %*d%[^\n]\n",
  446. &seg_start, &seg_end, mode, &seg_off, line) == 5) {
  447. void *tmp;
  448. /* to handle no path case (see above) we need to capture line
  449. * without skipping any whitespaces. So we need to strip
  450. * leading whitespaces manually here
  451. */
  452. i = 0;
  453. while (isblank(line[i]))
  454. i++;
  455. if (strcmp(line + i, path) != 0)
  456. continue;
  457. pr_debug("usdt: discovered segment for lib '%s': addrs %zx-%zx mode %s offset %zx\n",
  458. path, seg_start, seg_end, mode, seg_off);
  459. /* ignore non-executable sections for shared libs */
  460. if (mode[2] != 'x')
  461. continue;
  462. tmp = libbpf_reallocarray(*segs, *seg_cnt + 1, sizeof(**segs));
  463. if (!tmp) {
  464. err = -ENOMEM;
  465. goto err_out;
  466. }
  467. *segs = tmp;
  468. seg = *segs + *seg_cnt;
  469. *seg_cnt += 1;
  470. seg->start = seg_start;
  471. seg->end = seg_end;
  472. seg->offset = seg_off;
  473. seg->is_exec = true;
  474. }
  475. if (*seg_cnt == 0) {
  476. pr_warn("usdt: failed to find '%s' (resolved to '%s') within PID %d memory mappings\n",
  477. lib_path, path, pid);
  478. err = -ESRCH;
  479. goto err_out;
  480. }
  481. qsort(*segs, *seg_cnt, sizeof(**segs), cmp_elf_segs);
  482. err = 0;
  483. err_out:
  484. fclose(f);
  485. return err;
  486. }
  487. static struct elf_seg *find_elf_seg(struct elf_seg *segs, size_t seg_cnt, long virtaddr)
  488. {
  489. struct elf_seg *seg;
  490. int i;
  491. /* for ELF binaries (both executables and shared libraries), we are
  492. * given virtual address (absolute for executables, relative for
  493. * libraries) which should match address range of [seg_start, seg_end)
  494. */
  495. for (i = 0, seg = segs; i < seg_cnt; i++, seg++) {
  496. if (seg->start <= virtaddr && virtaddr < seg->end)
  497. return seg;
  498. }
  499. return NULL;
  500. }
  501. static struct elf_seg *find_vma_seg(struct elf_seg *segs, size_t seg_cnt, long offset)
  502. {
  503. struct elf_seg *seg;
  504. int i;
  505. /* for VMA segments from /proc/<pid>/maps file, provided "address" is
  506. * actually a file offset, so should be fall within logical
  507. * offset-based range of [offset_start, offset_end)
  508. */
  509. for (i = 0, seg = segs; i < seg_cnt; i++, seg++) {
  510. if (seg->offset <= offset && offset < seg->offset + (seg->end - seg->start))
  511. return seg;
  512. }
  513. return NULL;
  514. }
  515. static int parse_usdt_note(GElf_Nhdr *nhdr, const char *data, size_t name_off,
  516. size_t desc_off, struct usdt_note *usdt_note);
  517. static int parse_usdt_spec(struct usdt_spec *spec, const struct usdt_note *note, __u64 usdt_cookie);
  518. static int collect_usdt_targets(struct usdt_manager *man, Elf *elf, const char *path, pid_t pid,
  519. const char *usdt_provider, const char *usdt_name, __u64 usdt_cookie,
  520. struct usdt_target **out_targets, size_t *out_target_cnt)
  521. {
  522. size_t off, name_off, desc_off, seg_cnt = 0, vma_seg_cnt = 0, target_cnt = 0;
  523. struct elf_seg *segs = NULL, *vma_segs = NULL;
  524. struct usdt_target *targets = NULL, *target;
  525. long base_addr = 0;
  526. Elf_Scn *notes_scn, *base_scn;
  527. GElf_Shdr base_shdr, notes_shdr;
  528. GElf_Ehdr ehdr;
  529. GElf_Nhdr nhdr;
  530. Elf_Data *data;
  531. int err;
  532. *out_targets = NULL;
  533. *out_target_cnt = 0;
  534. err = find_elf_sec_by_name(elf, USDT_NOTE_SEC, &notes_shdr, &notes_scn);
  535. if (err) {
  536. pr_warn("usdt: no USDT notes section (%s) found in '%s'\n", USDT_NOTE_SEC, path);
  537. return err;
  538. }
  539. if (notes_shdr.sh_type != SHT_NOTE || !gelf_getehdr(elf, &ehdr)) {
  540. pr_warn("usdt: invalid USDT notes section (%s) in '%s'\n", USDT_NOTE_SEC, path);
  541. return -EINVAL;
  542. }
  543. err = parse_elf_segs(elf, path, &segs, &seg_cnt);
  544. if (err) {
  545. pr_warn("usdt: failed to process ELF program segments for '%s': %s\n",
  546. path, errstr(err));
  547. goto err_out;
  548. }
  549. /* .stapsdt.base ELF section is optional, but is used for prelink
  550. * offset compensation (see a big comment further below)
  551. */
  552. if (find_elf_sec_by_name(elf, USDT_BASE_SEC, &base_shdr, &base_scn) == 0)
  553. base_addr = base_shdr.sh_addr;
  554. data = elf_getdata(notes_scn, 0);
  555. off = 0;
  556. while ((off = gelf_getnote(data, off, &nhdr, &name_off, &desc_off)) > 0) {
  557. long usdt_abs_ip, usdt_rel_ip, usdt_sema_off = 0;
  558. struct usdt_note note;
  559. struct elf_seg *seg = NULL;
  560. void *tmp;
  561. err = parse_usdt_note(&nhdr, data->d_buf, name_off, desc_off, &note);
  562. if (err)
  563. goto err_out;
  564. if (strcmp(note.provider, usdt_provider) != 0 || strcmp(note.name, usdt_name) != 0)
  565. continue;
  566. /* We need to compensate "prelink effect". See [0] for details,
  567. * relevant parts quoted here:
  568. *
  569. * Each SDT probe also expands into a non-allocated ELF note. You can
  570. * find this by looking at SHT_NOTE sections and decoding the format;
  571. * see below for details. Because the note is non-allocated, it means
  572. * there is no runtime cost, and also preserved in both stripped files
  573. * and .debug files.
  574. *
  575. * However, this means that prelink won't adjust the note's contents
  576. * for address offsets. Instead, this is done via the .stapsdt.base
  577. * section. This is a special section that is added to the text. We
  578. * will only ever have one of these sections in a final link and it
  579. * will only ever be one byte long. Nothing about this section itself
  580. * matters, we just use it as a marker to detect prelink address
  581. * adjustments.
  582. *
  583. * Each probe note records the link-time address of the .stapsdt.base
  584. * section alongside the probe PC address. The decoder compares the
  585. * base address stored in the note with the .stapsdt.base section's
  586. * sh_addr. Initially these are the same, but the section header will
  587. * be adjusted by prelink. So the decoder applies the difference to
  588. * the probe PC address to get the correct prelinked PC address; the
  589. * same adjustment is applied to the semaphore address, if any.
  590. *
  591. * [0] https://sourceware.org/systemtap/wiki/UserSpaceProbeImplementation
  592. */
  593. usdt_abs_ip = note.loc_addr;
  594. if (base_addr && note.base_addr)
  595. usdt_abs_ip += base_addr - note.base_addr;
  596. /* When attaching uprobes (which is what USDTs basically are)
  597. * kernel expects file offset to be specified, not a relative
  598. * virtual address, so we need to translate virtual address to
  599. * file offset, for both ET_EXEC and ET_DYN binaries.
  600. */
  601. seg = find_elf_seg(segs, seg_cnt, usdt_abs_ip);
  602. if (!seg) {
  603. err = -ESRCH;
  604. pr_warn("usdt: failed to find ELF program segment for '%s:%s' in '%s' at IP 0x%lx\n",
  605. usdt_provider, usdt_name, path, usdt_abs_ip);
  606. goto err_out;
  607. }
  608. if (!seg->is_exec) {
  609. err = -ESRCH;
  610. pr_warn("usdt: matched ELF binary '%s' segment [0x%lx, 0x%lx) for '%s:%s' at IP 0x%lx is not executable\n",
  611. path, seg->start, seg->end, usdt_provider, usdt_name,
  612. usdt_abs_ip);
  613. goto err_out;
  614. }
  615. /* translate from virtual address to file offset */
  616. usdt_rel_ip = usdt_abs_ip - seg->start + seg->offset;
  617. if (ehdr.e_type == ET_DYN && !man->has_bpf_cookie) {
  618. /* If we don't have BPF cookie support but need to
  619. * attach to a shared library, we'll need to know and
  620. * record absolute addresses of attach points due to
  621. * the need to lookup USDT spec by absolute IP of
  622. * triggered uprobe. Doing this resolution is only
  623. * possible when we have a specific PID of the process
  624. * that's using specified shared library. BPF cookie
  625. * removes the absolute address limitation as we don't
  626. * need to do this lookup (we just use BPF cookie as
  627. * an index of USDT spec), so for newer kernels with
  628. * BPF cookie support libbpf supports USDT attachment
  629. * to shared libraries with no PID filter.
  630. */
  631. if (pid < 0) {
  632. pr_warn("usdt: attaching to shared libraries without specific PID is not supported on current kernel\n");
  633. err = -ENOTSUP;
  634. goto err_out;
  635. }
  636. /* vma_segs are lazily initialized only if necessary */
  637. if (vma_seg_cnt == 0) {
  638. err = parse_vma_segs(pid, path, &vma_segs, &vma_seg_cnt);
  639. if (err) {
  640. pr_warn("usdt: failed to get memory segments in PID %d for shared library '%s': %s\n",
  641. pid, path, errstr(err));
  642. goto err_out;
  643. }
  644. }
  645. seg = find_vma_seg(vma_segs, vma_seg_cnt, usdt_rel_ip);
  646. if (!seg) {
  647. err = -ESRCH;
  648. pr_warn("usdt: failed to find shared lib memory segment for '%s:%s' in '%s' at relative IP 0x%lx\n",
  649. usdt_provider, usdt_name, path, usdt_rel_ip);
  650. goto err_out;
  651. }
  652. usdt_abs_ip = seg->start - seg->offset + usdt_rel_ip;
  653. }
  654. 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",
  655. usdt_provider, usdt_name, ehdr.e_type == ET_EXEC ? "exec" : "lib ", path,
  656. note.loc_addr, note.base_addr, usdt_abs_ip, usdt_rel_ip, note.args,
  657. seg ? seg->start : 0, seg ? seg->end : 0, seg ? seg->offset : 0);
  658. /* Adjust semaphore address to be a file offset */
  659. if (note.sema_addr) {
  660. if (!man->has_sema_refcnt) {
  661. pr_warn("usdt: kernel doesn't support USDT semaphore refcounting for '%s:%s' in '%s'\n",
  662. usdt_provider, usdt_name, path);
  663. err = -ENOTSUP;
  664. goto err_out;
  665. }
  666. seg = find_elf_seg(segs, seg_cnt, note.sema_addr);
  667. if (!seg) {
  668. err = -ESRCH;
  669. pr_warn("usdt: failed to find ELF loadable segment with semaphore of '%s:%s' in '%s' at 0x%lx\n",
  670. usdt_provider, usdt_name, path, note.sema_addr);
  671. goto err_out;
  672. }
  673. if (seg->is_exec) {
  674. err = -ESRCH;
  675. pr_warn("usdt: matched ELF binary '%s' segment [0x%lx, 0x%lx] for semaphore of '%s:%s' at 0x%lx is executable\n",
  676. path, seg->start, seg->end, usdt_provider, usdt_name,
  677. note.sema_addr);
  678. goto err_out;
  679. }
  680. usdt_sema_off = note.sema_addr - seg->start + seg->offset;
  681. 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",
  682. usdt_provider, usdt_name, ehdr.e_type == ET_EXEC ? "exec" : "lib ",
  683. path, note.sema_addr, note.base_addr, usdt_sema_off,
  684. seg->start, seg->end, seg->offset);
  685. }
  686. /* Record adjusted addresses and offsets and parse USDT spec */
  687. tmp = libbpf_reallocarray(targets, target_cnt + 1, sizeof(*targets));
  688. if (!tmp) {
  689. err = -ENOMEM;
  690. goto err_out;
  691. }
  692. targets = tmp;
  693. target = &targets[target_cnt];
  694. memset(target, 0, sizeof(*target));
  695. target->abs_ip = usdt_abs_ip;
  696. target->rel_ip = usdt_rel_ip;
  697. target->sema_off = usdt_sema_off;
  698. /* notes.args references strings from ELF itself, so they can
  699. * be referenced safely until elf_end() call
  700. */
  701. target->spec_str = note.args;
  702. err = parse_usdt_spec(&target->spec, &note, usdt_cookie);
  703. if (err)
  704. goto err_out;
  705. target_cnt++;
  706. }
  707. *out_targets = targets;
  708. *out_target_cnt = target_cnt;
  709. err = target_cnt;
  710. err_out:
  711. free(segs);
  712. free(vma_segs);
  713. if (err < 0)
  714. free(targets);
  715. return err;
  716. }
  717. struct bpf_link_usdt {
  718. struct bpf_link link;
  719. struct usdt_manager *usdt_man;
  720. size_t spec_cnt;
  721. int *spec_ids;
  722. size_t uprobe_cnt;
  723. struct {
  724. long abs_ip;
  725. struct bpf_link *link;
  726. } *uprobes;
  727. struct bpf_link *multi_link;
  728. };
  729. static int bpf_link_usdt_detach(struct bpf_link *link)
  730. {
  731. struct bpf_link_usdt *usdt_link = container_of(link, struct bpf_link_usdt, link);
  732. struct usdt_manager *man = usdt_link->usdt_man;
  733. int i;
  734. bpf_link__destroy(usdt_link->multi_link);
  735. /* When having multi_link, uprobe_cnt is 0 */
  736. for (i = 0; i < usdt_link->uprobe_cnt; i++) {
  737. /* detach underlying uprobe link */
  738. bpf_link__destroy(usdt_link->uprobes[i].link);
  739. /* there is no need to update specs map because it will be
  740. * unconditionally overwritten on subsequent USDT attaches,
  741. * but if BPF cookies are not used we need to remove entry
  742. * from ip_to_spec_id map, otherwise we'll run into false
  743. * conflicting IP errors
  744. */
  745. if (!man->has_bpf_cookie) {
  746. /* not much we can do about errors here */
  747. (void)bpf_map_delete_elem(bpf_map__fd(man->ip_to_spec_id_map),
  748. &usdt_link->uprobes[i].abs_ip);
  749. }
  750. }
  751. /* try to return the list of previously used spec IDs to usdt_manager
  752. * for future reuse for subsequent USDT attaches
  753. */
  754. if (!man->free_spec_ids) {
  755. /* if there were no free spec IDs yet, just transfer our IDs */
  756. man->free_spec_ids = usdt_link->spec_ids;
  757. man->free_spec_cnt = usdt_link->spec_cnt;
  758. usdt_link->spec_ids = NULL;
  759. } else {
  760. /* otherwise concat IDs */
  761. size_t new_cnt = man->free_spec_cnt + usdt_link->spec_cnt;
  762. int *new_free_ids;
  763. new_free_ids = libbpf_reallocarray(man->free_spec_ids, new_cnt,
  764. sizeof(*new_free_ids));
  765. /* If we couldn't resize free_spec_ids, we'll just leak
  766. * a bunch of free IDs; this is very unlikely to happen and if
  767. * system is so exhausted on memory, it's the least of user's
  768. * concerns, probably.
  769. * So just do our best here to return those IDs to usdt_manager.
  770. * Another edge case when we can legitimately get NULL is when
  771. * new_cnt is zero, which can happen in some edge cases, so we
  772. * need to be careful about that.
  773. */
  774. if (new_free_ids || new_cnt == 0) {
  775. memcpy(new_free_ids + man->free_spec_cnt, usdt_link->spec_ids,
  776. usdt_link->spec_cnt * sizeof(*usdt_link->spec_ids));
  777. man->free_spec_ids = new_free_ids;
  778. man->free_spec_cnt = new_cnt;
  779. }
  780. }
  781. return 0;
  782. }
  783. static void bpf_link_usdt_dealloc(struct bpf_link *link)
  784. {
  785. struct bpf_link_usdt *usdt_link = container_of(link, struct bpf_link_usdt, link);
  786. free(usdt_link->spec_ids);
  787. free(usdt_link->uprobes);
  788. free(usdt_link);
  789. }
  790. static size_t specs_hash_fn(long key, void *ctx)
  791. {
  792. return str_hash((char *)key);
  793. }
  794. static bool specs_equal_fn(long key1, long key2, void *ctx)
  795. {
  796. return strcmp((char *)key1, (char *)key2) == 0;
  797. }
  798. static int allocate_spec_id(struct usdt_manager *man, struct hashmap *specs_hash,
  799. struct bpf_link_usdt *link, struct usdt_target *target,
  800. int *spec_id, bool *is_new)
  801. {
  802. long tmp;
  803. void *new_ids;
  804. int err;
  805. /* check if we already allocated spec ID for this spec string */
  806. if (hashmap__find(specs_hash, target->spec_str, &tmp)) {
  807. *spec_id = tmp;
  808. *is_new = false;
  809. return 0;
  810. }
  811. /* otherwise it's a new ID that needs to be set up in specs map and
  812. * returned back to usdt_manager when USDT link is detached
  813. */
  814. new_ids = libbpf_reallocarray(link->spec_ids, link->spec_cnt + 1, sizeof(*link->spec_ids));
  815. if (!new_ids)
  816. return -ENOMEM;
  817. link->spec_ids = new_ids;
  818. /* get next free spec ID, giving preference to free list, if not empty */
  819. if (man->free_spec_cnt) {
  820. *spec_id = man->free_spec_ids[man->free_spec_cnt - 1];
  821. /* cache spec ID for current spec string for future lookups */
  822. err = hashmap__add(specs_hash, target->spec_str, *spec_id);
  823. if (err)
  824. return err;
  825. man->free_spec_cnt--;
  826. } else {
  827. /* don't allocate spec ID bigger than what fits in specs map */
  828. if (man->next_free_spec_id >= bpf_map__max_entries(man->specs_map))
  829. return -E2BIG;
  830. *spec_id = man->next_free_spec_id;
  831. /* cache spec ID for current spec string for future lookups */
  832. err = hashmap__add(specs_hash, target->spec_str, *spec_id);
  833. if (err)
  834. return err;
  835. man->next_free_spec_id++;
  836. }
  837. /* remember new spec ID in the link for later return back to free list on detach */
  838. link->spec_ids[link->spec_cnt] = *spec_id;
  839. link->spec_cnt++;
  840. *is_new = true;
  841. return 0;
  842. }
  843. struct bpf_link *usdt_manager_attach_usdt(struct usdt_manager *man, const struct bpf_program *prog,
  844. pid_t pid, const char *path,
  845. const char *usdt_provider, const char *usdt_name,
  846. __u64 usdt_cookie)
  847. {
  848. unsigned long *offsets = NULL, *ref_ctr_offsets = NULL;
  849. int i, err, spec_map_fd, ip_map_fd;
  850. LIBBPF_OPTS(bpf_uprobe_opts, opts);
  851. struct hashmap *specs_hash = NULL;
  852. struct bpf_link_usdt *link = NULL;
  853. struct usdt_target *targets = NULL;
  854. __u64 *cookies = NULL;
  855. struct elf_fd elf_fd;
  856. size_t target_cnt;
  857. spec_map_fd = bpf_map__fd(man->specs_map);
  858. ip_map_fd = bpf_map__fd(man->ip_to_spec_id_map);
  859. err = elf_open(path, &elf_fd);
  860. if (err)
  861. return libbpf_err_ptr(err);
  862. err = sanity_check_usdt_elf(elf_fd.elf, path);
  863. if (err)
  864. goto err_out;
  865. /* normalize PID filter */
  866. if (pid < 0)
  867. pid = -1;
  868. else if (pid == 0)
  869. pid = getpid();
  870. /* discover USDT in given binary, optionally limiting
  871. * activations to a given PID, if pid > 0
  872. */
  873. err = collect_usdt_targets(man, elf_fd.elf, path, pid, usdt_provider, usdt_name,
  874. usdt_cookie, &targets, &target_cnt);
  875. if (err <= 0) {
  876. err = (err == 0) ? -ENOENT : err;
  877. goto err_out;
  878. }
  879. specs_hash = hashmap__new(specs_hash_fn, specs_equal_fn, NULL);
  880. if (IS_ERR(specs_hash)) {
  881. err = PTR_ERR(specs_hash);
  882. goto err_out;
  883. }
  884. link = calloc(1, sizeof(*link));
  885. if (!link) {
  886. err = -ENOMEM;
  887. goto err_out;
  888. }
  889. link->usdt_man = man;
  890. link->link.detach = &bpf_link_usdt_detach;
  891. link->link.dealloc = &bpf_link_usdt_dealloc;
  892. if (man->has_uprobe_multi) {
  893. offsets = calloc(target_cnt, sizeof(*offsets));
  894. cookies = calloc(target_cnt, sizeof(*cookies));
  895. ref_ctr_offsets = calloc(target_cnt, sizeof(*ref_ctr_offsets));
  896. if (!offsets || !ref_ctr_offsets || !cookies) {
  897. err = -ENOMEM;
  898. goto err_out;
  899. }
  900. } else {
  901. link->uprobes = calloc(target_cnt, sizeof(*link->uprobes));
  902. if (!link->uprobes) {
  903. err = -ENOMEM;
  904. goto err_out;
  905. }
  906. }
  907. for (i = 0; i < target_cnt; i++) {
  908. struct usdt_target *target = &targets[i];
  909. struct bpf_link *uprobe_link;
  910. bool is_new;
  911. int spec_id;
  912. /* Spec ID can be either reused or newly allocated. If it is
  913. * newly allocated, we'll need to fill out spec map, otherwise
  914. * entire spec should be valid and can be just used by a new
  915. * uprobe. We reuse spec when USDT arg spec is identical. We
  916. * also never share specs between two different USDT
  917. * attachments ("links"), so all the reused specs already
  918. * share USDT cookie value implicitly.
  919. */
  920. err = allocate_spec_id(man, specs_hash, link, target, &spec_id, &is_new);
  921. if (err)
  922. goto err_out;
  923. if (is_new && bpf_map_update_elem(spec_map_fd, &spec_id, &target->spec, BPF_ANY)) {
  924. err = -errno;
  925. pr_warn("usdt: failed to set USDT spec #%d for '%s:%s' in '%s': %s\n",
  926. spec_id, usdt_provider, usdt_name, path, errstr(err));
  927. goto err_out;
  928. }
  929. if (!man->has_bpf_cookie &&
  930. bpf_map_update_elem(ip_map_fd, &target->abs_ip, &spec_id, BPF_NOEXIST)) {
  931. err = -errno;
  932. if (err == -EEXIST) {
  933. pr_warn("usdt: IP collision detected for spec #%d for '%s:%s' in '%s'\n",
  934. spec_id, usdt_provider, usdt_name, path);
  935. } else {
  936. pr_warn("usdt: failed to map IP 0x%lx to spec #%d for '%s:%s' in '%s': %s\n",
  937. target->abs_ip, spec_id, usdt_provider, usdt_name,
  938. path, errstr(err));
  939. }
  940. goto err_out;
  941. }
  942. if (man->has_uprobe_multi) {
  943. offsets[i] = target->rel_ip;
  944. ref_ctr_offsets[i] = target->sema_off;
  945. cookies[i] = spec_id;
  946. } else {
  947. opts.ref_ctr_offset = target->sema_off;
  948. opts.bpf_cookie = man->has_bpf_cookie ? spec_id : 0;
  949. uprobe_link = bpf_program__attach_uprobe_opts(prog, pid, path,
  950. target->rel_ip, &opts);
  951. err = libbpf_get_error(uprobe_link);
  952. if (err) {
  953. pr_warn("usdt: failed to attach uprobe #%d for '%s:%s' in '%s': %s\n",
  954. i, usdt_provider, usdt_name, path, errstr(err));
  955. goto err_out;
  956. }
  957. link->uprobes[i].link = uprobe_link;
  958. link->uprobes[i].abs_ip = target->abs_ip;
  959. link->uprobe_cnt++;
  960. }
  961. }
  962. if (man->has_uprobe_multi) {
  963. LIBBPF_OPTS(bpf_uprobe_multi_opts, opts_multi,
  964. .ref_ctr_offsets = ref_ctr_offsets,
  965. .offsets = offsets,
  966. .cookies = cookies,
  967. .cnt = target_cnt,
  968. );
  969. link->multi_link = bpf_program__attach_uprobe_multi(prog, pid, path,
  970. NULL, &opts_multi);
  971. if (!link->multi_link) {
  972. err = -errno;
  973. pr_warn("usdt: failed to attach uprobe multi for '%s:%s' in '%s': %s\n",
  974. usdt_provider, usdt_name, path, errstr(err));
  975. goto err_out;
  976. }
  977. free(offsets);
  978. free(ref_ctr_offsets);
  979. free(cookies);
  980. }
  981. free(targets);
  982. hashmap__free(specs_hash);
  983. elf_close(&elf_fd);
  984. return &link->link;
  985. err_out:
  986. free(offsets);
  987. free(ref_ctr_offsets);
  988. free(cookies);
  989. if (link)
  990. bpf_link__destroy(&link->link);
  991. free(targets);
  992. hashmap__free(specs_hash);
  993. elf_close(&elf_fd);
  994. return libbpf_err_ptr(err);
  995. }
  996. /* Parse out USDT ELF note from '.note.stapsdt' section.
  997. * Logic inspired by perf's code.
  998. */
  999. static int parse_usdt_note(GElf_Nhdr *nhdr, const char *data, size_t name_off, size_t desc_off,
  1000. struct usdt_note *note)
  1001. {
  1002. const char *provider, *name, *args;
  1003. long addrs[3];
  1004. size_t len;
  1005. /* sanity check USDT note name and type first */
  1006. if (strncmp(data + name_off, USDT_NOTE_NAME, nhdr->n_namesz) != 0)
  1007. return -EINVAL;
  1008. if (nhdr->n_type != USDT_NOTE_TYPE)
  1009. return -EINVAL;
  1010. /* sanity check USDT note contents ("description" in ELF terminology) */
  1011. len = nhdr->n_descsz;
  1012. data = data + desc_off;
  1013. /* +3 is the very minimum required to store three empty strings */
  1014. if (len < sizeof(addrs) + 3)
  1015. return -EINVAL;
  1016. /* get location, base, and semaphore addrs */
  1017. memcpy(&addrs, data, sizeof(addrs));
  1018. /* parse string fields: provider, name, args */
  1019. provider = data + sizeof(addrs);
  1020. name = (const char *)memchr(provider, '\0', data + len - provider);
  1021. if (!name) /* non-zero-terminated provider */
  1022. return -EINVAL;
  1023. name++;
  1024. if (name >= data + len || *name == '\0') /* missing or empty name */
  1025. return -EINVAL;
  1026. args = memchr(name, '\0', data + len - name);
  1027. if (!args) /* non-zero-terminated name */
  1028. return -EINVAL;
  1029. ++args;
  1030. if (args >= data + len) /* missing arguments spec */
  1031. return -EINVAL;
  1032. note->provider = provider;
  1033. note->name = name;
  1034. if (*args == '\0' || *args == ':')
  1035. note->args = "";
  1036. else
  1037. note->args = args;
  1038. note->loc_addr = addrs[0];
  1039. note->base_addr = addrs[1];
  1040. note->sema_addr = addrs[2];
  1041. return 0;
  1042. }
  1043. static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz);
  1044. static int parse_usdt_spec(struct usdt_spec *spec, const struct usdt_note *note, __u64 usdt_cookie)
  1045. {
  1046. struct usdt_arg_spec *arg;
  1047. const char *s;
  1048. int arg_sz, len;
  1049. spec->usdt_cookie = usdt_cookie;
  1050. spec->arg_cnt = 0;
  1051. s = note->args;
  1052. while (s[0]) {
  1053. if (spec->arg_cnt >= USDT_MAX_ARG_CNT) {
  1054. pr_warn("usdt: too many USDT arguments (> %d) for '%s:%s' with args spec '%s'\n",
  1055. USDT_MAX_ARG_CNT, note->provider, note->name, note->args);
  1056. return -E2BIG;
  1057. }
  1058. arg = &spec->args[spec->arg_cnt];
  1059. len = parse_usdt_arg(s, spec->arg_cnt, arg, &arg_sz);
  1060. if (len < 0)
  1061. return len;
  1062. arg->arg_signed = arg_sz < 0;
  1063. if (arg_sz < 0)
  1064. arg_sz = -arg_sz;
  1065. switch (arg_sz) {
  1066. case 1: case 2: case 4: case 8:
  1067. arg->arg_bitshift = 64 - arg_sz * 8;
  1068. break;
  1069. default:
  1070. pr_warn("usdt: unsupported arg #%d (spec '%s') size: %d\n",
  1071. spec->arg_cnt, s, arg_sz);
  1072. return -EINVAL;
  1073. }
  1074. s += len;
  1075. spec->arg_cnt++;
  1076. }
  1077. return 0;
  1078. }
  1079. /* Architecture-specific logic for parsing USDT argument location specs */
  1080. #if defined(__x86_64__) || defined(__i386__)
  1081. static int calc_pt_regs_off(const char *reg_name)
  1082. {
  1083. static struct {
  1084. const char *names[4];
  1085. size_t pt_regs_off;
  1086. } reg_map[] = {
  1087. #ifdef __x86_64__
  1088. #define reg_off(reg64, reg32) offsetof(struct pt_regs, reg64)
  1089. #else
  1090. #define reg_off(reg64, reg32) offsetof(struct pt_regs, reg32)
  1091. #endif
  1092. { {"rip", "eip", "", ""}, reg_off(rip, eip) },
  1093. { {"rax", "eax", "ax", "al"}, reg_off(rax, eax) },
  1094. { {"rbx", "ebx", "bx", "bl"}, reg_off(rbx, ebx) },
  1095. { {"rcx", "ecx", "cx", "cl"}, reg_off(rcx, ecx) },
  1096. { {"rdx", "edx", "dx", "dl"}, reg_off(rdx, edx) },
  1097. { {"rsi", "esi", "si", "sil"}, reg_off(rsi, esi) },
  1098. { {"rdi", "edi", "di", "dil"}, reg_off(rdi, edi) },
  1099. { {"rbp", "ebp", "bp", "bpl"}, reg_off(rbp, ebp) },
  1100. { {"rsp", "esp", "sp", "spl"}, reg_off(rsp, esp) },
  1101. #undef reg_off
  1102. #ifdef __x86_64__
  1103. { {"r8", "r8d", "r8w", "r8b"}, offsetof(struct pt_regs, r8) },
  1104. { {"r9", "r9d", "r9w", "r9b"}, offsetof(struct pt_regs, r9) },
  1105. { {"r10", "r10d", "r10w", "r10b"}, offsetof(struct pt_regs, r10) },
  1106. { {"r11", "r11d", "r11w", "r11b"}, offsetof(struct pt_regs, r11) },
  1107. { {"r12", "r12d", "r12w", "r12b"}, offsetof(struct pt_regs, r12) },
  1108. { {"r13", "r13d", "r13w", "r13b"}, offsetof(struct pt_regs, r13) },
  1109. { {"r14", "r14d", "r14w", "r14b"}, offsetof(struct pt_regs, r14) },
  1110. { {"r15", "r15d", "r15w", "r15b"}, offsetof(struct pt_regs, r15) },
  1111. #endif
  1112. };
  1113. int i, j;
  1114. for (i = 0; i < ARRAY_SIZE(reg_map); i++) {
  1115. for (j = 0; j < ARRAY_SIZE(reg_map[i].names); j++) {
  1116. if (strcmp(reg_name, reg_map[i].names[j]) == 0)
  1117. return reg_map[i].pt_regs_off;
  1118. }
  1119. }
  1120. pr_warn("usdt: unrecognized register '%s'\n", reg_name);
  1121. return -ENOENT;
  1122. }
  1123. static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
  1124. {
  1125. char reg_name[16] = {0}, idx_reg_name[16] = {0};
  1126. int len, reg_off, idx_reg_off, scale = 1;
  1127. long off = 0;
  1128. if (sscanf(arg_str, " %d @ %ld ( %%%15[^,] , %%%15[^,] , %d ) %n",
  1129. arg_sz, &off, reg_name, idx_reg_name, &scale, &len) == 5 ||
  1130. sscanf(arg_str, " %d @ ( %%%15[^,] , %%%15[^,] , %d ) %n",
  1131. arg_sz, reg_name, idx_reg_name, &scale, &len) == 4 ||
  1132. sscanf(arg_str, " %d @ %ld ( %%%15[^,] , %%%15[^)] ) %n",
  1133. arg_sz, &off, reg_name, idx_reg_name, &len) == 4 ||
  1134. sscanf(arg_str, " %d @ ( %%%15[^,] , %%%15[^)] ) %n",
  1135. arg_sz, reg_name, idx_reg_name, &len) == 3
  1136. ) {
  1137. /*
  1138. * Scale Index Base case:
  1139. * 1@-96(%rbp,%rax,8)
  1140. * 1@(%rbp,%rax,8)
  1141. * 1@-96(%rbp,%rax)
  1142. * 1@(%rbp,%rax)
  1143. */
  1144. arg->arg_type = USDT_ARG_SIB;
  1145. arg->val_off = off;
  1146. reg_off = calc_pt_regs_off(reg_name);
  1147. if (reg_off < 0)
  1148. return reg_off;
  1149. arg->reg_off = reg_off;
  1150. idx_reg_off = calc_pt_regs_off(idx_reg_name);
  1151. if (idx_reg_off < 0)
  1152. return idx_reg_off;
  1153. arg->idx_reg_off = idx_reg_off;
  1154. /* validate scale factor and set fields directly */
  1155. switch (scale) {
  1156. case 1: arg->scale_bitshift = 0; break;
  1157. case 2: arg->scale_bitshift = 1; break;
  1158. case 4: arg->scale_bitshift = 2; break;
  1159. case 8: arg->scale_bitshift = 3; break;
  1160. default:
  1161. pr_warn("usdt: invalid SIB scale %d, expected 1, 2, 4, 8\n", scale);
  1162. return -EINVAL;
  1163. }
  1164. } else if (sscanf(arg_str, " %d @ %ld ( %%%15[^)] ) %n",
  1165. arg_sz, &off, reg_name, &len) == 3) {
  1166. /* Memory dereference case, e.g., -4@-20(%rbp) */
  1167. arg->arg_type = USDT_ARG_REG_DEREF;
  1168. arg->val_off = off;
  1169. reg_off = calc_pt_regs_off(reg_name);
  1170. if (reg_off < 0)
  1171. return reg_off;
  1172. arg->reg_off = reg_off;
  1173. } else if (sscanf(arg_str, " %d @ ( %%%15[^)] ) %n", arg_sz, reg_name, &len) == 2) {
  1174. /* Memory dereference case without offset, e.g., 8@(%rsp) */
  1175. arg->arg_type = USDT_ARG_REG_DEREF;
  1176. arg->val_off = 0;
  1177. reg_off = calc_pt_regs_off(reg_name);
  1178. if (reg_off < 0)
  1179. return reg_off;
  1180. arg->reg_off = reg_off;
  1181. } else if (sscanf(arg_str, " %d @ %%%15s %n", arg_sz, reg_name, &len) == 2) {
  1182. /* Register read case, e.g., -4@%eax */
  1183. arg->arg_type = USDT_ARG_REG;
  1184. /* register read has no memory offset */
  1185. arg->val_off = 0;
  1186. reg_off = calc_pt_regs_off(reg_name);
  1187. if (reg_off < 0)
  1188. return reg_off;
  1189. arg->reg_off = reg_off;
  1190. } else if (sscanf(arg_str, " %d @ $%ld %n", arg_sz, &off, &len) == 2) {
  1191. /* Constant value case, e.g., 4@$71 */
  1192. arg->arg_type = USDT_ARG_CONST;
  1193. arg->val_off = off;
  1194. arg->reg_off = 0;
  1195. } else {
  1196. pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
  1197. return -EINVAL;
  1198. }
  1199. return len;
  1200. }
  1201. #elif defined(__s390x__)
  1202. static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
  1203. {
  1204. unsigned int reg;
  1205. int len;
  1206. long off;
  1207. if (sscanf(arg_str, " %d @ %ld ( %%r%u ) %n", arg_sz, &off, &reg, &len) == 3) {
  1208. /* Memory dereference case, e.g., -2@-28(%r15) */
  1209. arg->arg_type = USDT_ARG_REG_DEREF;
  1210. arg->val_off = off;
  1211. if (reg > 15) {
  1212. pr_warn("usdt: unrecognized register '%%r%u'\n", reg);
  1213. return -EINVAL;
  1214. }
  1215. arg->reg_off = offsetof(user_pt_regs, gprs[reg]);
  1216. } else if (sscanf(arg_str, " %d @ %%r%u %n", arg_sz, &reg, &len) == 2) {
  1217. /* Register read case, e.g., -8@%r0 */
  1218. arg->arg_type = USDT_ARG_REG;
  1219. arg->val_off = 0;
  1220. if (reg > 15) {
  1221. pr_warn("usdt: unrecognized register '%%r%u'\n", reg);
  1222. return -EINVAL;
  1223. }
  1224. arg->reg_off = offsetof(user_pt_regs, gprs[reg]);
  1225. } else if (sscanf(arg_str, " %d @ %ld %n", arg_sz, &off, &len) == 2) {
  1226. /* Constant value case, e.g., 4@71 */
  1227. arg->arg_type = USDT_ARG_CONST;
  1228. arg->val_off = off;
  1229. arg->reg_off = 0;
  1230. } else {
  1231. pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
  1232. return -EINVAL;
  1233. }
  1234. return len;
  1235. }
  1236. #elif defined(__aarch64__)
  1237. static int calc_pt_regs_off(const char *reg_name)
  1238. {
  1239. int reg_num;
  1240. if (sscanf(reg_name, "x%d", &reg_num) == 1) {
  1241. if (reg_num >= 0 && reg_num < 31)
  1242. return offsetof(struct user_pt_regs, regs[reg_num]);
  1243. } else if (strcmp(reg_name, "sp") == 0) {
  1244. return offsetof(struct user_pt_regs, sp);
  1245. }
  1246. pr_warn("usdt: unrecognized register '%s'\n", reg_name);
  1247. return -ENOENT;
  1248. }
  1249. static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
  1250. {
  1251. char reg_name[16];
  1252. int len, reg_off;
  1253. long off;
  1254. if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] , %ld ] %n", arg_sz, reg_name, &off, &len) == 3) {
  1255. /* Memory dereference case, e.g., -4@[sp, 96] */
  1256. arg->arg_type = USDT_ARG_REG_DEREF;
  1257. arg->val_off = off;
  1258. reg_off = calc_pt_regs_off(reg_name);
  1259. if (reg_off < 0)
  1260. return reg_off;
  1261. arg->reg_off = reg_off;
  1262. } else if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] ] %n", arg_sz, reg_name, &len) == 2) {
  1263. /* Memory dereference case, e.g., -4@[sp] */
  1264. arg->arg_type = USDT_ARG_REG_DEREF;
  1265. arg->val_off = 0;
  1266. reg_off = calc_pt_regs_off(reg_name);
  1267. if (reg_off < 0)
  1268. return reg_off;
  1269. arg->reg_off = reg_off;
  1270. } else if (sscanf(arg_str, " %d @ %ld %n", arg_sz, &off, &len) == 2) {
  1271. /* Constant value case, e.g., 4@5 */
  1272. arg->arg_type = USDT_ARG_CONST;
  1273. arg->val_off = off;
  1274. arg->reg_off = 0;
  1275. } else if (sscanf(arg_str, " %d @ %15[a-z0-9] %n", arg_sz, reg_name, &len) == 2) {
  1276. /* Register read case, e.g., -8@x4 */
  1277. arg->arg_type = USDT_ARG_REG;
  1278. arg->val_off = 0;
  1279. reg_off = calc_pt_regs_off(reg_name);
  1280. if (reg_off < 0)
  1281. return reg_off;
  1282. arg->reg_off = reg_off;
  1283. } else {
  1284. pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
  1285. return -EINVAL;
  1286. }
  1287. return len;
  1288. }
  1289. #elif defined(__riscv)
  1290. static int calc_pt_regs_off(const char *reg_name)
  1291. {
  1292. static struct {
  1293. const char *name;
  1294. size_t pt_regs_off;
  1295. } reg_map[] = {
  1296. { "ra", offsetof(struct user_regs_struct, ra) },
  1297. { "sp", offsetof(struct user_regs_struct, sp) },
  1298. { "gp", offsetof(struct user_regs_struct, gp) },
  1299. { "tp", offsetof(struct user_regs_struct, tp) },
  1300. { "a0", offsetof(struct user_regs_struct, a0) },
  1301. { "a1", offsetof(struct user_regs_struct, a1) },
  1302. { "a2", offsetof(struct user_regs_struct, a2) },
  1303. { "a3", offsetof(struct user_regs_struct, a3) },
  1304. { "a4", offsetof(struct user_regs_struct, a4) },
  1305. { "a5", offsetof(struct user_regs_struct, a5) },
  1306. { "a6", offsetof(struct user_regs_struct, a6) },
  1307. { "a7", offsetof(struct user_regs_struct, a7) },
  1308. { "s0", offsetof(struct user_regs_struct, s0) },
  1309. { "s1", offsetof(struct user_regs_struct, s1) },
  1310. { "s2", offsetof(struct user_regs_struct, s2) },
  1311. { "s3", offsetof(struct user_regs_struct, s3) },
  1312. { "s4", offsetof(struct user_regs_struct, s4) },
  1313. { "s5", offsetof(struct user_regs_struct, s5) },
  1314. { "s6", offsetof(struct user_regs_struct, s6) },
  1315. { "s7", offsetof(struct user_regs_struct, s7) },
  1316. { "s8", offsetof(struct user_regs_struct, rv_s8) },
  1317. { "s9", offsetof(struct user_regs_struct, s9) },
  1318. { "s10", offsetof(struct user_regs_struct, s10) },
  1319. { "s11", offsetof(struct user_regs_struct, s11) },
  1320. { "t0", offsetof(struct user_regs_struct, t0) },
  1321. { "t1", offsetof(struct user_regs_struct, t1) },
  1322. { "t2", offsetof(struct user_regs_struct, t2) },
  1323. { "t3", offsetof(struct user_regs_struct, t3) },
  1324. { "t4", offsetof(struct user_regs_struct, t4) },
  1325. { "t5", offsetof(struct user_regs_struct, t5) },
  1326. { "t6", offsetof(struct user_regs_struct, t6) },
  1327. };
  1328. int i;
  1329. for (i = 0; i < ARRAY_SIZE(reg_map); i++) {
  1330. if (strcmp(reg_name, reg_map[i].name) == 0)
  1331. return reg_map[i].pt_regs_off;
  1332. }
  1333. pr_warn("usdt: unrecognized register '%s'\n", reg_name);
  1334. return -ENOENT;
  1335. }
  1336. static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
  1337. {
  1338. char reg_name[16];
  1339. int len, reg_off;
  1340. long off;
  1341. if (sscanf(arg_str, " %d @ %ld ( %15[a-z0-9] ) %n", arg_sz, &off, reg_name, &len) == 3) {
  1342. /* Memory dereference case, e.g., -8@-88(s0) */
  1343. arg->arg_type = USDT_ARG_REG_DEREF;
  1344. arg->val_off = off;
  1345. reg_off = calc_pt_regs_off(reg_name);
  1346. if (reg_off < 0)
  1347. return reg_off;
  1348. arg->reg_off = reg_off;
  1349. } else if (sscanf(arg_str, " %d @ %ld %n", arg_sz, &off, &len) == 2) {
  1350. /* Constant value case, e.g., 4@5 */
  1351. arg->arg_type = USDT_ARG_CONST;
  1352. arg->val_off = off;
  1353. arg->reg_off = 0;
  1354. } else if (sscanf(arg_str, " %d @ %15[a-z0-9] %n", arg_sz, reg_name, &len) == 2) {
  1355. /* Register read case, e.g., -8@a1 */
  1356. arg->arg_type = USDT_ARG_REG;
  1357. arg->val_off = 0;
  1358. reg_off = calc_pt_regs_off(reg_name);
  1359. if (reg_off < 0)
  1360. return reg_off;
  1361. arg->reg_off = reg_off;
  1362. } else {
  1363. pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
  1364. return -EINVAL;
  1365. }
  1366. return len;
  1367. }
  1368. #elif defined(__arm__)
  1369. static int calc_pt_regs_off(const char *reg_name)
  1370. {
  1371. static struct {
  1372. const char *name;
  1373. size_t pt_regs_off;
  1374. } reg_map[] = {
  1375. { "r0", offsetof(struct pt_regs, uregs[0]) },
  1376. { "r1", offsetof(struct pt_regs, uregs[1]) },
  1377. { "r2", offsetof(struct pt_regs, uregs[2]) },
  1378. { "r3", offsetof(struct pt_regs, uregs[3]) },
  1379. { "r4", offsetof(struct pt_regs, uregs[4]) },
  1380. { "r5", offsetof(struct pt_regs, uregs[5]) },
  1381. { "r6", offsetof(struct pt_regs, uregs[6]) },
  1382. { "r7", offsetof(struct pt_regs, uregs[7]) },
  1383. { "r8", offsetof(struct pt_regs, uregs[8]) },
  1384. { "r9", offsetof(struct pt_regs, uregs[9]) },
  1385. { "r10", offsetof(struct pt_regs, uregs[10]) },
  1386. { "fp", offsetof(struct pt_regs, uregs[11]) },
  1387. { "ip", offsetof(struct pt_regs, uregs[12]) },
  1388. { "sp", offsetof(struct pt_regs, uregs[13]) },
  1389. { "lr", offsetof(struct pt_regs, uregs[14]) },
  1390. { "pc", offsetof(struct pt_regs, uregs[15]) },
  1391. };
  1392. int i;
  1393. for (i = 0; i < ARRAY_SIZE(reg_map); i++) {
  1394. if (strcmp(reg_name, reg_map[i].name) == 0)
  1395. return reg_map[i].pt_regs_off;
  1396. }
  1397. pr_warn("usdt: unrecognized register '%s'\n", reg_name);
  1398. return -ENOENT;
  1399. }
  1400. static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
  1401. {
  1402. char reg_name[16];
  1403. int len, reg_off;
  1404. long off;
  1405. if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] , #%ld ] %n",
  1406. arg_sz, reg_name, &off, &len) == 3) {
  1407. /* Memory dereference case, e.g., -4@[fp, #96] */
  1408. arg->arg_type = USDT_ARG_REG_DEREF;
  1409. arg->val_off = off;
  1410. reg_off = calc_pt_regs_off(reg_name);
  1411. if (reg_off < 0)
  1412. return reg_off;
  1413. arg->reg_off = reg_off;
  1414. } else if (sscanf(arg_str, " %d @ \[ %15[a-z0-9] ] %n", arg_sz, reg_name, &len) == 2) {
  1415. /* Memory dereference case, e.g., -4@[sp] */
  1416. arg->arg_type = USDT_ARG_REG_DEREF;
  1417. arg->val_off = 0;
  1418. reg_off = calc_pt_regs_off(reg_name);
  1419. if (reg_off < 0)
  1420. return reg_off;
  1421. arg->reg_off = reg_off;
  1422. } else if (sscanf(arg_str, " %d @ #%ld %n", arg_sz, &off, &len) == 2) {
  1423. /* Constant value case, e.g., 4@#5 */
  1424. arg->arg_type = USDT_ARG_CONST;
  1425. arg->val_off = off;
  1426. arg->reg_off = 0;
  1427. } else if (sscanf(arg_str, " %d @ %15[a-z0-9] %n", arg_sz, reg_name, &len) == 2) {
  1428. /* Register read case, e.g., -8@r4 */
  1429. arg->arg_type = USDT_ARG_REG;
  1430. arg->val_off = 0;
  1431. reg_off = calc_pt_regs_off(reg_name);
  1432. if (reg_off < 0)
  1433. return reg_off;
  1434. arg->reg_off = reg_off;
  1435. } else {
  1436. pr_warn("usdt: unrecognized arg #%d spec '%s'\n", arg_num, arg_str);
  1437. return -EINVAL;
  1438. }
  1439. return len;
  1440. }
  1441. #else
  1442. static int parse_usdt_arg(const char *arg_str, int arg_num, struct usdt_arg_spec *arg, int *arg_sz)
  1443. {
  1444. pr_warn("usdt: libbpf doesn't support USDTs on current architecture\n");
  1445. return -ENOTSUP;
  1446. }
  1447. #endif