From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.210.71 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796417955; b=aX+0M+5jYgBBUnT8xB1tkQFpBlgmJiZp/BMPx9qDWwaPTweTwLUFLza7+7PQtpiPJXTZ yL640NyrAAgrPcc8IcvIWKXN4xMbzOig+L472CJ1MN4ywegTq7ima2T+IFbeJjtZDPIAb 4QP+gx6435L2pOZBVcUa1e0IBzWGABRFauGrp4m/9C3qFTf91OpUQecxlRY/BOq6tFIpd Jt+8BcMAeMqf50QkpHtGBDfeObTtDpzX3CnIxwWKwxWLkwR+ghS/yj5/t0k1UT5lztbkl 98bGkKSzmuJz+k5fRF1v6fr3+uRVPP8uUZIPv1wgPZ8UWIdMIvaR9JjJ2U6dsuSS5nA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796417955; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Gm-Message-State:X-Received:Date:In-Reply-To:Mime-Version: References:X-Mailer:Message-ID:Subject:From:To:Cc:Content-Type; bh=8LCw4c8VA7om9OrtlNmoWUA0BA06z23OO92jP59AhNA=; b=sZIAJd4B7PGg7NjudVG2l0+6BVP50G4BK7PeNs9l46Uy0rARAtodnRoaAblw6pDb6cvr lhYjQJ3rmLrX25mUXVXv8YlGNKPxfKsF2sO/L4TcNFxJE9DmuR7rAjdZkdXvSyTGvkj2K GTKI859aSYHjkMlkKMtCg7DLj/bmWACIIpeRxBFWJpdQYIL3MB6UL1iU4YQqulSvb/wlb iJ29Pv7wBwaUe17n3OTFjAyYh5PJurqhdzQ84kM3849VcntNwRS1W1qpW6kufNP+2X7CS ECdgZDkgEM9YQe9nIhTuP/XwNo5zrxsaVh52WjFp49zuo8QIOHxS8//tocgiLoGdKog== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=ZZzKFs+V; arc=none smtp.remote-ip=209.85.210.71 Received: from mail-ot1-f71.google.com (mail-ot1-f71.google.com [209.85.210.71]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 668ED606A6A3 for ; Fri, 4 Dec 2026 20:59:14 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 668ED606A6A3 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=ZZzKFs+V Received: by mail-ot1-f71.google.com with SMTP id 46e09a7af769-8628955a085so1474877a34.3 for ; Fri, 04 Dec 2026 12:59:14 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1796417953; x=1797022753; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=8LCw4c8VA7om9OrtlNmoWUA0BA06z23OO92jP59AhNA=; b=ZZzKFs+VG9pE677f7ZuMGb8Tm+uTLpuOhe8JudRk1W4H0xrjs3jHkdLnu+B14mCEFZ Pfi62mNPkkqbCktzgmRCnBGQNndzs95A2dC+4e/127PekIH8fyzurKmD5icwctV+Dtrq puP5EfeN7hg5Om1E23Q742ImqFeFWiil19dyuDVFTPnbWiW3yaqLXnZ+wzJea1BrZcbA n+VFW80rKDHcCixmKbsRKgQrdbLNNrPKqIytvf0591MSw+YQT9lS2hDS8AWUGe7vVxbg OpluQX1tdqvBkJMIDcZj+f+GjXha6SU5sExm9m5JBFWcBP2jpxrB1LWCINZJBaKxc+AZ KByQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796417953; x=1797022753; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=8LCw4c8VA7om9OrtlNmoWUA0BA06z23OO92jP59AhNA=; b=aspBIoZj2cVmcLW5WRyBd6NqqJKJi0HDsXTyQ8NmZeQEdvXN1mwnWeQC+B8K09uehf 0I3IzANbXv72Q+04EnveiW/aqNq/xOdAkqkJPMlYPrqFWdQeSBB2gIIzCxvtP8wep0xd b+bP6uelivJF0H3hycm2zPJzTeKvO2EvobIfNKU4HsOH0M+9dnnqIarG7Sx9rsJxA6JU 3DizN2Boat3byeTHPNGr2SCxfymuvC64/jWmLHWdLr5XmU7BipF/cf0d60hDm51NiXNy OvbA3Y6zgiddx4jLhWfN+AtRKUTzGMlMiSyn5wxUAAWXud12O6ZwToD6VfTMmWHc0vjc zI0Q== X-Gm-Message-State: APuU4Z/kNY33FhSGtkthS1tJ4uO0cjdsSOAOzM37EpnCS70ufR/vNrFo 3PvJip1JMyyiYAt2YFUGPrKjzB7/PjKBMvUV0oANOfeFZoMXzHKHivnMtN+3ps3tCyFwA2pUY8Y gqv3RObaOS4Q3oV+wQf/aEAuwR6qZNonUkfsDggHYM5xCY1nzjGPSUYjMaRBPdULxIqyJugWRJ5 m/wpkspDBKr1eGPVZrrSpvjvdF40MY9YN2afj2yPfou/VMZ0vsIhCm5o0= X-Received: from otfi4-n1.prod.google.com ([2002:a05:6830:84c4:10b0:861:5cc0:bf30]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6830:90b:b0:822:978:f7bd with SMTP id 46e09a7af769-863f89e357cmr3593870a34.28.1796417952970; Fri, 04 Dec 2026 12:59:12 -0800 (PST) Date: Fri, 4 Dec 2026 12:58:51 -0800 In-Reply-To: <20261204205854.3973609-1-irogers@google.com> X-Mailing-List: linux-perf-users@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261204205854.3973609-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.915.g69d5ec7298-goog Message-ID: <20261204205854.3973609-6-irogers@google.com> Subject: [PATCH v4 5/7] perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events From: Ian Rogers To: linux-perf-users@vger.kernel.org Cc: linux-kernel@vger.kernel.org, peterz@infradead.org, mingo@redhat.com, acme@kernel.org, namhyung@kernel.org, jolsa@kernel.org, adrian.hunter@intel.com, james.clark@linaro.org, dsahern@gmail.com, andrii@kernel.org, Ian Rogers Content-Type: text/plain; charset="UTF-8" When synthesizing MMAP2 events for existing processes perf parses the text of /proc//task//maps and then, for each file backed mapping not already in the DSO cache, opens and parses the ELF file, within the process' mount namespace, to find its build ID. Since Linux 6.11 the PROCMAP_QUERY ioctl on the maps file returns the details of a VMA in binary form and can return the build ID of the backing file, read by the kernel from the mapped file. As suggested by Peter Zijlstra, use it on Linux 6.19+ to synthesize the mmap events: - The kernel skips unwanted VMAs, rather than perf parsing and discarding them. - Build IDs come from the kernel, avoiding perf opening ELF files and switching mount namespace. - Build IDs are found for files perf can't open by path, such as deleted binaries or those in other mount namespaces. Without data mmaps a single pass asks the kernel for executable VMAs. Data mmaps want VMAs that are readable or executable, but query flags can only require permissions, so a first pass gets the readable VMAs, skipping inaccessible ones like guard pages, and a second pass gets the executable VMAs that aren't readable, such as execute-only memory. The second pass only requests the name of the VMAs it emits. The events for execute-only VMAs therefore follow the others rather than being in address order. The DSO cache is still checked first, keyed by device and inode as before, with the build ID copied during the lookup, and the kernel is only asked to read the build ID on a miss, so the build ID of a file is read once. If the kernel can't provide the build ID then the file is read as before. As before, files without a build ID aren't remembered, so each mapping of them misses the cache, costing an extra query to the kernel before the file is read. PROCMAP_QUERY synthesis is gated on Linux 6.19+ (checked via uname() in the one-time probe): 6.18 added per-VMA locks to PROCMAP_QUERY via commit d9d1c2d81797 ("fs/proc/task_mmu: execute PROCMAP_QUERY ioctl under per-vma locks"), matching text /proc//maps from 6.17 via commit 5631da56c9a8 ("fs/proc/task_mmu: read proc/pid/maps under per-vma lock"), and 6.19 fixed a kernel NULL pointer dereference in filemap_read_folio() for build ID queries on mappings without ->read_folio (such as tmpfs, shmem, hugetlbfs, dma-buf, or devices) via commit 777a8560fd29 ("lib/buildid: use __kernel_read() for sleepable context"). Device nodes, kernel pseudo-filesystems/paths, and other visible non-regular files are also skipped before asking the kernel for a build ID. Names too long for the event become "//toolong" as with the text parser. The text parser remains as a fallback for kernels older than 6.19 or lacking PROCMAP_QUERY, which is probed once on /proc/self/maps using pthread_once(), and for other errors on the first query. The VMA handling shared by both paths is moved into a helper so both produce identical events. A difference is that the gate VMA, [vsyscall] on x86-64 and [vectors] on 32-bit ARM, isn't in the VMA tree and so isn't reported by PROCMAP_QUERY, while it is shown in the maps file. The kernel never emits an MMAP2 event for it either, so processes started while recording already lack it, and as it has no backing file no symbols were resolved for it. PROCMAP_QUERY is provided by tools/include/uapi/linux/fs.h. Using 'perf bench internals synthesize' on an Intel Core i7-14700 with a 7.1 kernel, pinned to a P-core CPU, with the DSO cache warm after the first iteration (usec, min / median of 10 interleaved runs): /proc/pid/maps text PROCMAP_QUERY exec mmaps only 254.1 / 256.9 171.1 / 173.5 with data mmaps 1513.4 / 1618.1 1667.8 / 1749.1 With data mmaps every readable VMA needs an ioctl and, with a warm DSO cache, this is about 8% slower than reading the text. With a cold DSO cache, as at the start of 'perf record -a', the system wide benchmark ('-t -m 1 -M 4', about 24,000 events, unprivileged, min / median of 5 interleaved runs) shows the benefit of not opening ELF files: Threads /proc/pid/maps text PROCMAP_QUERY 1 243754 / 246155 124929 / 126336 2 139272 / 143913 79233 / 80165 3 207429 / 209567 93290 / 94799 4 123863 / 123989 59701 / 62360 Link: https://lore.kernel.org/lkml/20261202124341.GA677025@noisy.programming.kicks-ass.net/ Suggested-by: Peter Zijlstra Signed-off-by: Ian Rogers --- tools/perf/util/synthetic-events.c | 599 ++++++++++++++++++++++++----- 1 file changed, 499 insertions(+), 100 deletions(-) diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c index 445199d7bbd4..4152d0ae5270 100644 --- a/tools/perf/util/synthetic-events.c +++ b/tools/perf/util/synthetic-events.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only #include "util/cgroup.h" +#include "util/build-id.h" #include "util/data.h" #include "util/debug.h" #include "util/dso.h" @@ -20,6 +21,8 @@ #include "util/target.h" #include "util/time-utils.h" #include +#include +#include /* PROCMAP_QUERY */ #include #include #include @@ -34,14 +37,17 @@ #include #include #include +#include #include #include #include /* To get things like MAP_HUGETLB even on older libc headers */ #include #include #include +#include #include #include +#include #include #include @@ -436,9 +442,19 @@ static bool read_proc_maps_line(struct io *io, __u64 *start, __u64 *end, return true; } +/* + * Add a build ID to the MMAP2 event. If the build ID is already known, for + * example because the PROCMAP_QUERY ioctl returned it, it is passed as + * known_bid and the file isn't read. Otherwise the build ID comes from the DSO + * cache or by reading the file within the process' mount namespace. If the + * DSO for the event's filename and device/inode was already found it may be + * passed to avoid looking it up again. + */ static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event, struct machine *machine, - bool is_kernel) + bool is_kernel, + struct dso *known_dso, + const struct build_id *known_bid) { struct build_id bid = { .size = 0, }; struct nsinfo *nsi; @@ -463,7 +479,17 @@ static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event, dso_id.mmap2_ino_generation_valid = true; } - dso = dsos__findnew_id_build_id(&machine->dsos, event->filename, &dso_id, &bid); + if (known_bid && known_bid->size) { + /* Set the build ID in the known DSO, if there is one, below. */ + dso = known_dso ? dso__get(known_dso) : NULL; + bid = *known_bid; + rc = 0; + goto out; + } + if (known_dso) + dso = dso__get(known_dso); + else + dso = dsos__findnew_id_build_id(&machine->dsos, event->filename, &dso_id, &bid); if (dso && bid.size) { /* The DSO already has the build ID, don't set it again. */ dso__zput(dso); @@ -498,134 +524,505 @@ static void perf_record_mmap2__read_build_id(struct perf_record_mmap2 *event, dso__put(dso); } -int perf_event__synthesize_mmap_events(const struct perf_tool *tool, - union perf_event *event, - pid_t pid, pid_t tgid, - perf_event__handler_t process, - struct machine *machine, - bool mmap_data) -{ +/* A VMA read from /proc//maps or with the PROCMAP_QUERY ioctl. */ +struct synth_mmap2_vma { + __u64 start, end, pgoff, ino; + u32 prot, flags, maj, min; + /* The build ID if provided by the kernel, otherwise size is 0. */ + struct build_id bid; + /* Optional DSO, holding a reference, already found for the VMA. */ + struct dso *dso; +}; + +/* State when synthesizing the MMAP2 events of a process. */ +struct synth_mmap2_state { + const struct perf_tool *tool; + union perf_event *event; + perf_event__handler_t process; + struct machine *machine; + const char *hugetlbfs_mnt; + size_t hugetlbfs_mnt_len; unsigned long long t; - char bf[BUFSIZ]; - struct io io; - bool truncation = false; - unsigned long long timeout = proc_map_timeout * 1000000ULL; - int rc = 0; - const char *hugetlbfs_mnt = hugetlbfs__mountpoint(); - int hugetlbfs_mnt_len = hugetlbfs_mnt ? strlen(hugetlbfs_mnt) : 0; + unsigned long long timeout; + pid_t pid; + pid_t tgid; + bool mmap_data; + /* Set when the timeout is exceeded, no more events should follow. */ + bool truncation; +}; - if (machine__is_default_guest(machine)) - return 0; +/* + * Complete and process the MMAP2 event for a VMA whose name has already been + * written to event->mmap2.filename. Unwanted VMAs are skipped. Returns 0 on + * success, or -1 if processing the event failed. + */ +static int synth_mmap2_state__process_vma(struct synth_mmap2_state *state, + struct synth_mmap2_vma *vma) +{ + static const char anonstr[] = "//anon"; + union perf_event *event = state->event; + struct machine *machine = state->machine; + size_t size, aligned_size; - snprintf(bf, sizeof(bf), "%s/proc/%d/task/%d/maps", - machine->root_dir, pid, pid); + if (!strcmp(event->mmap2.filename, "")) + strcpy(event->mmap2.filename, anonstr); - io.fd = open(bf, O_RDONLY, 0); - if (io.fd < 0) { - /* - * We raced with a task exiting - just return: - */ - pr_debug("couldn't open %s\n", bf); - return -1; + if (state->hugetlbfs_mnt_len && + !strncmp(event->mmap2.filename, state->hugetlbfs_mnt, state->hugetlbfs_mnt_len)) { + strcpy(event->mmap2.filename, anonstr); + vma->flags |= MAP_HUGETLB; + /* No build ID for "//anon", as when reading the file. */ + vma->bid.size = 0; + dso__zput(vma->dso); } - io__init(&io, io.fd, bf, sizeof(bf)); - event->header.type = PERF_RECORD_MMAP2; - t = rdclock(); + size = strlen(event->mmap2.filename) + 1; + aligned_size = PERF_ALIGN(size, sizeof(u64)); + + event->mmap2.header.type = PERF_RECORD_MMAP2; + + /* + * Just like the kernel, see perf_misc_flags() in + * kernel/events/core.c + */ + if (machine__is_host(machine)) + event->header.misc = PERF_RECORD_MISC_USER; + else + event->header.misc = PERF_RECORD_MISC_GUEST_USER; + + if ((rdclock() - state->t) > state->timeout) { + pr_warning("Reading %s/proc/%d/task/%d/maps time out. You may want to increase the time limit by --proc-map-timeout\n", + machine->root_dir, state->pid, state->pid); + state->truncation = true; + goto out; + } + + if ((vma->prot & PROT_EXEC) == 0) { + if (!state->mmap_data || (vma->prot & PROT_READ) == 0) + return 0; + + event->header.misc |= PERF_RECORD_MISC_MMAP_DATA; + } + +out: + if (state->truncation) + event->header.misc |= PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT; + + event->mmap2.header.size = + offsetof(struct perf_record_mmap2, filename) + + aligned_size; + + /* Zero the padding and ID header trailer safely! */ + memset((char *)event + offsetof(struct perf_record_mmap2, filename) + size, 0, + (aligned_size - size) + machine->id_hdr_size); + + event->mmap2.header.size += machine->id_hdr_size; + event->mmap2.start = vma->start; + event->mmap2.len = vma->end - vma->start; + event->mmap2.pgoff = vma->pgoff; + event->mmap2.maj = vma->maj; + event->mmap2.min = vma->min; + event->mmap2.ino = vma->ino; + event->mmap2.ino_generation = 0; + event->mmap2.pid = state->tgid; + event->mmap2.tid = state->pid; + event->mmap2.prot = vma->prot; + event->mmap2.flags = vma->flags; + + if (!symbol_conf.no_buildid_mmap2) + perf_record_mmap2__read_build_id(&event->mmap2, machine, false, + vma->dso, &vma->bid); + + if (perf_tool__process_synth_event(state->tool, event, machine, state->process) != 0) + return -1; + + return 0; +} + +/* Synthesize MMAP2 events by parsing the text of the maps file. */ +static int synth_mmap2_state__read_maps_text(struct synth_mmap2_state *state, int fd, + char *bf, size_t bf_size) +{ + union perf_event *event = state->event; + const size_t name_size = sizeof(event->mmap2.filename) - state->machine->id_hdr_size; + struct io io; + + io__init(&io, fd, bf, bf_size); while (!io.eof) { - static const char anonstr[] = "//anon"; - size_t size, aligned_size; - __u64 start, end, pgoff, ino; - u32 prot, flags, maj, min; + struct synth_mmap2_vma vma = { .bid = { .size = 0, }, }; /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */ /* Read directly into event->mmap2.filename, clamping for id_hdr_size! */ - if (!read_proc_maps_line(&io, &start, &end, - &prot, &flags, &pgoff, - &maj, &min, &ino, - sizeof(event->mmap2.filename) - machine->id_hdr_size, - event->mmap2.filename)) { + if (!read_proc_maps_line(&io, &vma.start, &vma.end, + &vma.prot, &vma.flags, &vma.pgoff, + &vma.maj, &vma.min, &vma.ino, + name_size, event->mmap2.filename)) { if (io.eof) break; continue; } - if (!strcmp(event->mmap2.filename, "")) - strcpy(event->mmap2.filename, anonstr); + if (synth_mmap2_state__process_vma(state, &vma)) + return -1; - if (hugetlbfs_mnt_len && - !strncmp(event->mmap2.filename, hugetlbfs_mnt, hugetlbfs_mnt_len)) { - strcpy(event->mmap2.filename, anonstr); - flags |= MAP_HUGETLB; - } + if (state->truncation) + break; + } + return 0; +} - size = strlen(event->mmap2.filename) + 1; - aligned_size = PERF_ALIGN(size, sizeof(u64)); +/* + * Set once by procmap_query__probe(): whether the running kernel is Linux + * 6.19+ and supports the PROCMAP_QUERY ioctl. + */ +static bool procmap_query_supported; - event->mmap2.header.type = PERF_RECORD_MMAP2; +static void procmap_query__probe(void) +{ + struct procmap_query q = { + .size = sizeof(q), + .query_flags = PROCMAP_QUERY_COVERING_OR_NEXT_VMA, + }; + struct utsname uts; + unsigned int major, minor; + int fd; - /* - * Just like the kernel, see perf_misc_flags() in - * kernel/events/core.c - */ - if (machine__is_host(machine)) - event->header.misc = PERF_RECORD_MISC_USER; - else - event->header.misc = PERF_RECORD_MISC_GUEST_USER; + /* + * Require Linux 6.19+ for PROCMAP_QUERY synthesis: + * - 6.18 (commit d9d1c2d81797 "fs/proc/task_mmu: execute + * PROCMAP_QUERY ioctl under per-vma locks") added per-VMA locking, + * matching text /proc//maps from 6.17 (commit 5631da56c9a8). + * - 6.19 (commit 777a8560fd29 "lib/buildid: use __kernel_read() for + * sleepable context") fixed a NULL pointer dereference in + * filemap_read_folio() when querying build IDs on mappings backed + * by filesystems without ->read_folio (such as tmpfs, shmem, + * hugetlbfs, dma-buf, or device files). + */ + if (uname(&uts) != 0 || + sscanf(uts.release, "%u.%u", &major, &minor) != 2 || + major < 6 || (major == 6 && minor < 19)) { + pr_debug("PROCMAP_QUERY disabled on kernel < 6.19, reading maps files as text\n"); + return; + } + + fd = open("/proc/self/maps", O_RDONLY); + if (fd < 0) + return; + + procmap_query_supported = ioctl(fd, PROCMAP_QUERY, &q) == 0 || errno == ENOENT; + close(fd); + if (!procmap_query_supported) + pr_debug("PROCMAP_QUERY not supported, reading maps files as text\n"); +} + +static bool procmap_query__supported(void) +{ + static pthread_once_t once = PTHREAD_ONCE_INIT; + + pthread_once(&once, procmap_query__probe); + return procmap_query_supported; +} + +static bool procmap_query__skip_build_id(struct machine *machine, const char *name) +{ + struct stat st; - if ((rdclock() - t) > timeout) { - pr_warning("Reading %s/proc/%d/task/%d/maps time out. You may want to increase the time limit by --proc-map-timeout\n", - machine->root_dir, pid, pid); - truncation = true; - goto out; + /* + * Skip device nodes and kernel pseudo-filesystems/paths before asking + * the kernel for a build ID: do_procmap_query() passes vma->vm_file + * straight to build_id_parse_file() -> __kernel_read(), which warns on + * device files without ->read_iter and wastes a query on non-ELF + * pseudo-paths. + */ + if (strstarts(name, "/dev/") || strstarts(name, "/sys/") || + strstarts(name, "/proc/") || strstarts(name, "/memfd:") || + strstarts(name, "/dmabuf:") || strstarts(name, "/anon_hugepage") || + strstarts(name, "/SYSV") || strstarts(name, "/[")) + return true; + + /* + * Skip any other non-regular file visible in this mount namespace. + * If stat() fails (e.g. a deleted binary or a file only in the + * target's mount namespace), still let the kernel try. + */ + if (machine__is_host(machine) && stat(name, &st) == 0 && !S_ISREG(st.st_mode)) + return true; + + return false; +} + +/* + * Find the DSO and build ID of the file backing a VMA found by PROCMAP_QUERY. + * The DSO cache is checked first, so that the kernel only reads the build ID + * once per file. On a hit the cached build ID is used and the DSO isn't kept. + * On a miss the DSO is kept, so the build ID can be added to it, and the VMA + * is queried again asking the kernel for the build ID. If the kernel can't + * provide it, the build ID is left empty and perf_record_mmap2__read_build_id() + * will try to read it from the file. + */ +static void synth_mmap2_state__vma_build_id(struct synth_mmap2_state *state, int fd, + const struct procmap_query *found, + const char *name, struct synth_mmap2_vma *vma) +{ + struct dso_id dso_id = dso_id_empty; + struct procmap_query q = { + .size = sizeof(q), + .query_addr = found->vma_start, + }; + u8 build_id[BUILD_ID_SIZE]; + + dso_id.maj = found->dev_major; + dso_id.min = found->dev_minor; + dso_id.ino = found->inode; + dso_id.ino_generation = 0; + dso_id.mmap2_valid = true; + dso_id.mmap2_ino_generation_valid = true; + + vma->dso = dsos__findnew_id_build_id(&state->machine->dsos, name, &dso_id, &vma->bid); + if (vma->bid.size) { + dso__zput(vma->dso); + return; + } + if (procmap_query__skip_build_id(state->machine, name)) + return; + + q.build_id_addr = (uintptr_t)build_id; + q.build_id_size = sizeof(build_id); + if (ioctl(fd, PROCMAP_QUERY, &q) < 0 || q.build_id_size == 0) + return; + + /* Ignore the build ID if the VMA was changed. */ + if (q.vma_start != found->vma_start || q.inode != found->inode || + q.dev_major != found->dev_major || q.dev_minor != found->dev_minor) + return; + + build_id__init(&vma->bid, build_id, q.build_id_size); +} + +/* + * Synthesize MMAP2 events for the VMAs found by PROCMAP_QUERY with the given + * query flags. When skip_readable is true readable VMAs are skipped, as an + * earlier pass handled them, and their names aren't requested. first is true + * until a query succeeds and is shared by passes. Returns 0 on success, -1 if + * processing an event failed or 1 if the first query failed and the maps file + * should be read as text instead. + */ +static int synth_mmap2_state__procmap_query_pass(struct synth_mmap2_state *state, int fd, + __u64 query_flags, bool skip_readable, + bool *first) +{ + union perf_event *event = state->event; + char *name = event->mmap2.filename; + const u32 name_size = sizeof(event->mmap2.filename) - state->machine->id_hdr_size; + __u64 addr = 0; + + while (true) { + struct synth_mmap2_vma vma = { .bid = { .size = 0, }, }; + struct procmap_query q; + bool want_name = !skip_readable; + bool name_too_long = false; + int ret; +retry: + q = (struct procmap_query){ + .size = sizeof(q), + .query_flags = query_flags, + .query_addr = addr, + }; + if (want_name) { + q.vma_name_addr = (uintptr_t)name; + q.vma_name_size = name_size; } - if ((prot & PROT_EXEC) == 0) { - if (!mmap_data || (prot & PROT_READ) == 0) + while (ioctl(fd, PROCMAP_QUERY, &q) < 0) { + int err = errno; + + /* No more VMAs. */ + if (err == ENOENT) + return 0; + + /* The name doesn't fit, retry without it. */ + if (err == ENAMETOOLONG && q.vma_name_size) { + name_too_long = true; + q.vma_name_addr = 0; + q.vma_name_size = 0; continue; + } - event->header.misc |= PERF_RECORD_MISC_MMAP_DATA; + if (*first) { + /* + * Read the text for just this process, for + * example if its maps file is in another + * machine's root_dir without PROCMAP_QUERY. + */ + pr_debug("PROCMAP_QUERY failed for pid %d (errno %d), reading maps file\n", + state->pid, err); + return 1; + } + + /* Likely the process exited, stop as reading text would. */ + pr_debug("PROCMAP_QUERY failed for pid %d at %#llx (errno %d)\n", + state->pid, (unsigned long long)addr, err); + return 0; } + *first = false; -out: - if (truncation) - event->header.misc |= PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT; + if (skip_readable && (q.vma_flags & PROCMAP_QUERY_VMA_READABLE)) { + if ((rdclock() - state->t) <= state->timeout) { + if (q.vma_end <= addr) + return 0; + addr = q.vma_end; + continue; + } + /* + * Timed out while skipping readable VMAs. Proceed to + * want_name to fetch the VMA's name so that + * synth_mmap2_state__process_vma() warns and emits the + * real VMA with PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT. + */ + } + if (!want_name) { + /* + * A wanted VMA (or a timeout), query it again to get + * its name without moving addr backwards (a covering + * VMA can start below addr, and moving backwards could + * loop if a concurrent mprotect() flips its prefix). + */ + want_name = true; + if (q.vma_start > addr) + addr = q.vma_start; + goto retry; + } - event->mmap2.header.size = - offsetof(struct perf_record_mmap2, filename) + - aligned_size; + vma.start = q.vma_start; + vma.end = q.vma_end; + vma.pgoff = q.vma_offset; + vma.maj = q.dev_major; + vma.min = q.dev_minor; + vma.ino = q.inode; + vma.prot = 0; + if (q.vma_flags & PROCMAP_QUERY_VMA_READABLE) + vma.prot |= PROT_READ; + if (q.vma_flags & PROCMAP_QUERY_VMA_WRITABLE) + vma.prot |= PROT_WRITE; + if (q.vma_flags & PROCMAP_QUERY_VMA_EXECUTABLE) + vma.prot |= PROT_EXEC; + vma.flags = (q.vma_flags & PROCMAP_QUERY_VMA_SHARED) ? MAP_SHARED : MAP_PRIVATE; + + if (name_too_long) + strlcpy(name, "//toolong", name_size); + else if (q.vma_name_size == 0) + name[0] = '\0'; - /* Zero the padding and ID header trailer safely! */ - memset((char *)event + offsetof(struct perf_record_mmap2, filename) + size, 0, - (aligned_size - size) + machine->id_hdr_size); - - event->mmap2.header.size += machine->id_hdr_size; - event->mmap2.start = start; - event->mmap2.len = end - start; - event->mmap2.pgoff = pgoff; - event->mmap2.maj = maj; - event->mmap2.min = min; - event->mmap2.ino = ino; - event->mmap2.ino_generation = 0; - event->mmap2.pid = tgid; - event->mmap2.tid = pid; - event->mmap2.prot = prot; - event->mmap2.flags = flags; - - if (!symbol_conf.no_buildid_mmap2) - perf_record_mmap2__read_build_id(&event->mmap2, machine, false); - - if (perf_tool__process_synth_event(tool, event, machine, process) != 0) { - rc = -1; - break; - } + /* + * Get the build ID of wanted file backed VMAs. Other VMAs + * have no build ID, or are unwanted and skipped. + */ + if (!symbol_conf.no_buildid_mmap2 && + q.inode && name[0] == '/' && name[1] != '/' && + ((vma.prot & PROT_EXEC) || (state->mmap_data && (vma.prot & PROT_READ))) && + (!state->hugetlbfs_mnt_len || + strncmp(name, state->hugetlbfs_mnt, state->hugetlbfs_mnt_len))) + synth_mmap2_state__vma_build_id(state, fd, &q, name, &vma); + + ret = synth_mmap2_state__process_vma(state, &vma); + dso__put(vma.dso); + if (ret) + return -1; - if (truncation) - break; + if (state->truncation || q.vma_end <= addr) + return 0; + addr = q.vma_end; } +} - close(io.fd); +/* + * Synthesize MMAP2 events using the PROCMAP_QUERY ioctl on the maps file. The + * kernel skips unwanted VMAs and provides the build ID, avoiding perf opening + * the ELF file within the process' mount namespace. Returns 0 on success, -1 + * if processing an event failed or 1 if the maps file should be read as text + * instead. + */ +static int synth_mmap2_state__procmap_query(struct synth_mmap2_state *state, int fd) +{ + bool first = true; + int ret; + + /* Without data mmaps only executable VMAs are wanted. */ + if (!state->mmap_data) { + return synth_mmap2_state__procmap_query_pass(state, fd, + PROCMAP_QUERY_COVERING_OR_NEXT_VMA | + PROCMAP_QUERY_VMA_EXECUTABLE, + /*skip_readable=*/false, &first); + } + + /* + * Data mmaps want VMAs that are readable or executable, but query + * flags can only require permissions. First get the readable VMAs, + * skipping inaccessible ones like guard pages, then the executable + * VMAs that aren't readable, such as execute-only memory. + */ + ret = synth_mmap2_state__procmap_query_pass(state, fd, + PROCMAP_QUERY_COVERING_OR_NEXT_VMA | + PROCMAP_QUERY_VMA_READABLE, + /*skip_readable=*/false, &first); + if (ret || state->truncation) + return ret; + + return synth_mmap2_state__procmap_query_pass(state, fd, + PROCMAP_QUERY_COVERING_OR_NEXT_VMA | + PROCMAP_QUERY_VMA_EXECUTABLE, + /*skip_readable=*/true, &first); +} + +int perf_event__synthesize_mmap_events(const struct perf_tool *tool, + union perf_event *event, + pid_t pid, pid_t tgid, + perf_event__handler_t process, + struct machine *machine, + bool mmap_data) +{ + char bf[BUFSIZ]; + const char *hugetlbfs_mnt = hugetlbfs__mountpoint(); + struct synth_mmap2_state state = { + .tool = tool, + .event = event, + .process = process, + .machine = machine, + .hugetlbfs_mnt = hugetlbfs_mnt, + .hugetlbfs_mnt_len = hugetlbfs_mnt ? strlen(hugetlbfs_mnt) : 0, + .timeout = proc_map_timeout * 1000000ULL, + .pid = pid, + .tgid = tgid, + .mmap_data = mmap_data, + }; + int fd, rc = 1; + + if (machine__is_default_guest(machine)) + return 0; + + snprintf(bf, sizeof(bf), "%s/proc/%d/task/%d/maps", + machine->root_dir, pid, pid); + + fd = open(bf, O_RDONLY, 0); + if (fd < 0) { + /* + * We raced with a task exiting - just return: + */ + pr_debug("couldn't open %s\n", bf); + return -1; + } + + event->header.type = PERF_RECORD_MMAP2; + state.t = rdclock(); + + if (procmap_query__supported()) + rc = synth_mmap2_state__procmap_query(&state, fd); + + if (rc > 0) + rc = synth_mmap2_state__read_maps_text(&state, fd, bf, sizeof(bf)); + + close(fd); return rc; } @@ -814,7 +1211,8 @@ static int perf_event__synthesize_modules_maps_cb(struct map *map, void *data) event->mmap2.__reserved_1 = 0; event->mmap2.__reserved_2 = 0; - perf_record_mmap2__read_build_id(&event->mmap2, args->machine, false); + perf_record_mmap2__read_build_id(&event->mmap2, args->machine, false, + /*known_dso=*/NULL, /*known_bid=*/NULL); } else { const char *long_name = dso__long_name(dso); @@ -1301,7 +1699,8 @@ static int __perf_event__synthesize_kernel_mmap(const struct perf_tool *tool, event->mmap2.len = map__end(map) - event->mmap.start; event->mmap2.pid = machine->pid; - perf_record_mmap2__read_build_id(&event->mmap2, machine, true); + perf_record_mmap2__read_build_id(&event->mmap2, machine, true, + /*known_dso=*/NULL, /*known_bid=*/NULL); } else { size = snprintf(event->mmap.filename, sizeof(event->mmap.filename), "%s%s", machine->mmap_name, kmap->ref_reloc_sym->name) + 1; -- 2.56.1.915.g69d5ec7298-goog