From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.198 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796346315; b=jcWESTmJTuew9Jvt0Ih5QXwGbJmRWyx61U7Iggeizx6udOxhYsxw2Zk4IeIkhVtzSCuc 2AUNkcXXaIV6zFNofRylcdUiDDO5Bkr6bPGvBUQPo9zt3hzJm1LReDB79gh1T0ZKCMlJS OO9QxwlZQWDSUo8YrWquirOUngnrn/ma80Kp6j41wLWgnfPO+it7zw9myKUzlm4FSpl1P 3+YyBa987nERN6cz0vWYV2qBdTbOSJMLbt4DMTNS9JLfFi2qKzwzauPDbq1qHCkTvFeGg Dh9NLLINPT/mpD7vQP7+IUO0Ampjdxrk9vmQ2BiIuh4LPDP78yLO8jnc99ktjdyPhEg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796346315; 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=JINBzwI6XxStUYHZtw43pse4uohg9+iYZVFrdJsAQ28=; b=VMcOsKdT9qCcE5WaVRLDzrL/4ZF0f9DQimZY223182TdO3D7c2hvTA+bFQfn7WIms51m sCEr5/sp9NERN/EEQW7eXaNew69tFbcw5Ar+XD3NqCrn6sNVVYYIF4XpaSgbRdT8VhNSy XyulV8xne1kEzzkdvDkpBiTEAev8c5yJKyNe+1Gl1rgkoATNtqQT4NKdX6VhQ94tZgAjj Z+VpqBTG5IZqE/SR+UKuPlKHVWGm72smT5r5C91Tr9zEgf3CijUnt7I6IZd4VIxhP+yL0 cOl8+8m678hyDfRovuiNlecSgUMfXgZYTls4MuHjL/YR8YEJ0AEvpPrlw9d8sLQ91pw== 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=Hlq553+j; arc=none smtp.remote-ip=74.125.82.198 Received: from mail-dy1-f198.google.com (mail-dy1-f198.google.com [74.125.82.198]) (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 D3CA6606A683 for ; Fri, 4 Dec 2026 01:05:14 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org D3CA6606A683 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=Hlq553+j Received: by mail-dy1-f198.google.com with SMTP id 5a478bee46e88-38751f8cc15so672011eec.1 for ; Thu, 03 Dec 2026 17:05:14 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1796346314; x=1796951114; 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=JINBzwI6XxStUYHZtw43pse4uohg9+iYZVFrdJsAQ28=; b=Hlq553+jQIhZ2TfNelrC4AyqAfrGfKUWwsVh09RR2i1WDZeS9e8LNfbJhVeulYqSDZ d+lb3FwnUTBC79TbE0e1R0a9o5GQeGkHIQZ91BvxcSkjyhhBup2HZGfQ4sg6/GtmROh3 epRH5OujUaja+zf7HwEOthmtgmZ5uF+FzqEBxT8mc/SDvxkgqMybMUZ7YOu4kxzUvJhh XDLoCo5akwFnSlLJvkkspwzkdaF6fl6UuW3BPLbuI+AYCdefRAeFpHEIapn4bRb+zVB9 pXQgWTiwmADYVnRc3Qr6KvnDMWj41ATsWCLSERqluoy5MKpncWMjguGxFosAn+AmFn27 b+ng== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796346314; x=1796951114; 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=JINBzwI6XxStUYHZtw43pse4uohg9+iYZVFrdJsAQ28=; b=vxTctEjkWbcZAaZ58oQblulfu7TxlGwXSohWAn+9VCJ19SWC1BuLZz063GaDfcMaM/ 4sgwoRjSXxousup7DcqU4RieA0ereh8zJMXveQ80wBvXC3cB6YcbgElsupfVFbBU8T9f FdhW11npTdcNxBOwncdcSccMb10XQM3otIgtrQIHhVdCUyvLENcZXW8osstbS6fmPYyi 2C4MgD/riG+J5p2h+iUp+Ts54GDRJ8G7eshNTGy7gBetLkKKSPyo7EvVzvUXeNXFwY6p HoYmqsf48cWE+Bzxl9+NEpQqMsk+9qOLHsG/kkEJtE1fKzqH2PN8aK+ZNqJlYaDEIt1z HZ4g== X-Gm-Message-State: APuU4Z8r8tQoUB6Gl9Ex3eR3jR3nGBd9aDcFvXJZwTzU8xfOR/js5iNI xuwVnb+EW4uLIpd0r1thhw56Ff2T4w7oR3OCdJX+n0XnhojMIUOTerPIWzH+hfp6wiAmK3BAmis J6eT3kxJ3shI+rwwHnM4mPHri61yhH68gPbNUaYy4QLAsyaYGiBLof1ym0BxRftch8k1YVgCPwV VarNYj+CngGpzpzAQpq9LDwi1DGaV0UL2pk8SsA5+kMSZPQEZsreLiH6I= X-Received: from dykg3.prod.google.com ([2002:a05:7300:5783:b0:387:48d8:26c]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7301:9e48:b0:386:98bf:c6c1 with SMTP id 5a478bee46e88-387521d242dmr712332eec.26.1796346313321; Thu, 03 Dec 2026 17:05:13 -0800 (PST) Date: Thu, 3 Dec 2026 17:04:49 -0800 In-Reply-To: <20261204010452.1937224-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: <20261204010452.1937224-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.915.g69d5ec7298-goog Message-ID: <20261204010452.1937224-5-irogers@google.com> Subject: [PATCH 4/6] perf synthetic-events: Use PROCMAP_QUERY to synthesize mmap events From: Ian Rogers To: linux-perf-users@vger.kernel.org, acme@kernel.org, namhyung@kernel.org Cc: linux-kernel@vger.kernel.org, peterz@infradead.org, mingo@redhat.com, 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 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. Names too long for the event become "//toolong" as with the text parser. The text parser remains as a fallback for kernels 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. The tools/include copy of linux/fs.h provides PROCMAP_QUERY when the system headers lack it. Using 'perf bench internals synthesize' on an Intel Core i7-14700 with a 7.1 kernel, pinned to a 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 249.2 / 258.8 172.2 / 177.2 with data mmaps 1458.3 / 1621.8 1631.5 / 1726.2 With data mmaps every readable VMA needs an ioctl and, with a warm DSO cache, this is about 6% 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 32,000 events, unprivileged, min / median of 3 runs) shows the benefit of not opening ELF files: Threads /proc/pid/maps text PROCMAP_QUERY 1 301943 / 302766 161624 / 164009 2 184631 / 187061 112002 / 115959 3 240013 / 240291 136163 / 215740 4 133571 / 139586 92270 / 95234 The 3 thread PROCMAP_QUERY median is skewed by two noisy runs. Link: https://lore.kernel.org/lkml/20261202124341.GA677025@noisy.programming.kicks-ass.net/ Suggested-by: Peter Zijlstra Signed-off-by: Ian Rogers --- Notes: This change was developed with the help of an AI coding assistant (Gemini in Jetski), which wrote the initial code, tests and changelog; it was reviewed, built and tested by the author. tools/perf/util/synthetic-events.c | 528 +++++++++++++++++++++++------ 1 file changed, 428 insertions(+), 100 deletions(-) diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c index 445199d7bbd4..3ad482f9115a 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, from tools/include/uapi if not in system headers */ #include #include #include @@ -34,12 +37,14 @@ #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 @@ -436,9 +441,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 +478,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 +523,435 @@ 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)); +/* Does the running kernel support PROCMAP_QUERY? Set by procmap_query__probe(). */ +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, + }; + int fd = open("/proc/self/maps", O_RDONLY); - /* - * 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 (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; +} + +/* + * 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; + } + + 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; - 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; + /* 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; + } + + 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; + } - event->header.misc |= PERF_RECORD_MISC_MMAP_DATA; + /* 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)) { + addr = q.vma_end; + continue; + } + if (!want_name) { + /* A wanted VMA, query it again to get its name. */ + want_name = true; + 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] == '/' && + ((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); - if (truncation) - break; + addr = q.vma_end; + + ret = synth_mmap2_state__process_vma(state, &vma); + dso__put(vma.dso); + if (ret) + return -1; + + if (state->truncation) + return 0; } +} - 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 +1140,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 +1628,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