From nobody Mon May 25 03:33:06 2026 Received: from mail-dy1-f201.google.com (mail-dy1-f201.google.com [74.125.82.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 122573E008F for ; Tue, 19 May 2026 08:08:29 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=74.125.82.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779178111; cv=none; b=uM1xWpMu9kxzQ8JAyhLfg+dkQ3wy1HmqsjJdWx0SPZIVqggipNJPdZMijJ1s+VH+EcDj9FyfTHHLa7ZcV3v6Eb+TkIIp31GVMQ6N2ChHFsnfKE6O5oB05MZ3hmFdFosdfdCKtFwlVud19PGolUXpOoTn1zvkOkxyZG8bHFJ/Uxw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779178111; c=relaxed/simple; bh=ep7COZZ9+dYsiSZc2LCfDflxg3XnWPqDjplcDPy/7jQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=R8c2YmijHFd4AxxmvPSOIj74wtRGNm9pja8X2+8a9L6vLMQly1CFQ06b5bbpYq5DPq70W7z3YRLMRYBkkXhIE6XHFcyQqL6Sh64jm4jpGhZVT+WMMTCbKkStcaU+OgZ9jYRleOnG85WsG3Z/33pIkn6EON/7ZYo8txLdlbHN+KQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=M7mCBH6u; arc=none smtp.client-ip=74.125.82.201 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.b="M7mCBH6u" Received: by mail-dy1-f201.google.com with SMTP id 5a478bee46e88-2f485961555so16280706eec.1 for ; Tue, 19 May 2026 01:08:29 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20251104; t=1779178109; x=1779782909; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=PDL9MwqmDNfF2Jy2SVEWelU+Z3ZeBcjmLtu8epKj4/4=; b=M7mCBH6uL+6oZrOwKmG7EhEWAUoeFaob+4EyjVROTwcDUaBfh0yywmaQt/aSDVEF3s kz345tNpqzKtrbStEvsym0PEkWXzQ1gZ8koAe07dXSH6b30J5pWizN0e5glYd6CHzDKX HyZFmpO1xkrtaS0qx/kNq2Y9KvsbQX0Yzr5TqfV8b2zmcoY7hYr5evUSNlgkkRjKWW0N XQ1v7NRxFU3GxmRglXqLhIH93cQfLmk/tvxp/rluTITJ42wwemDsY1Z44LHpD3SYHBYY SH0vAjAKnEmnKgawZQhfqYdNfOmWK9Om7RDii8ZFxNm8J2ac5+RlIyxx9k5uTv4xMDnJ BhHg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1779178109; x=1779782909; h=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; bh=PDL9MwqmDNfF2Jy2SVEWelU+Z3ZeBcjmLtu8epKj4/4=; b=UTdaipnLRCmGlSgpg6QBRvH+GDjoUDeSQF62R181EHHEk7TC7LDASot5uKUyrJHXOc UJRb12b4hD6RxVGDO5x5BeKZMokp9JxUMf4slmdfPJDSlLZ9ZLk6WbktpbWcI9mTNTTO H42d+Y47pEiKjL9fuEhuIGf8xDdMJaT26bfgrqo0s5eosl8+ygXGPGv6uAhHfaDfmzbo +0Zt39EaXLKQaYJRUuclb0HNg3czNa+ovOegtJiAswjFR+fFyRsAz6AkCN/aisBdTB0b l4FRkCr7RlwrLrn7v25RwSvpgT07pyF3iJaj9XBj4iUe1B4qfp5G3/dEBqTb6eWcA+l+ 7OQg== X-Forwarded-Encrypted: i=1; AFNElJ8cZWgDieB7IjHcbnkoJNcRQGpznlED3Uuy8sRg41B1CDQ1SXzKIyye4qwkJTsGPg0Ub8EJnjfQ6dl5ZvM=@vger.kernel.org X-Gm-Message-State: AOJu0YyDeyLzpkbOYcrkmal7c+ndvmNpGcnGN+ONVp90Wx6lPMmKSInu Eo0k33OSlmQ2mW67oZNadQvY2APncNlDgCejVMQjcRrmMhcu/eA+V13g4cAEZt+nRCtqEUxIaRy KerQFc3eGwg== X-Received: from dycop8.prod.google.com ([2002:a05:7301:9bc8:b0:304:bc:3817]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7300:be17:b0:2d8:7302:d21 with SMTP id 5a478bee46e88-303986010e1mr7935832eec.16.1779178108864; Tue, 19 May 2026 01:08:28 -0700 (PDT) Date: Tue, 19 May 2026 01:08:21 -0700 In-Reply-To: <20260519080824.3329601-1-irogers@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20260508082726.2795191-1-irogers@google.com> <20260519080824.3329601-1-irogers@google.com> X-Mailer: git-send-email 2.54.0.631.ge1b05301d1-goog Message-ID: <20260519080824.3329601-2-irogers@google.com> Subject: [PATCH v7 1/4] perf maps: Add maps__mutate_mapping From: Ian Rogers To: irogers@google.com, acme@kernel.org, james.clark@linaro.org, namhyung@kernel.org Cc: adrian.hunter@intel.com, gmx@google.com, jolsa@kernel.org, linux-kernel@vger.kernel.org, linux-perf-users@vger.kernel.org, mingo@redhat.com, peterz@infradead.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" During kernel ELF symbol parsing (dso__process_kernel_symbol), proc kallsyms image loading (dso__load_kernel_sym, dso__load_guest_kernel_sym), and dynamic kernel memory map alignment updates (machine__update_kernel_mmap), the loader directly modifies live virtual address boundary keys fields on map objects. If these boundaries are mutated while the map pointer actively resides inside the parent maps cache array list (kmaps) outside of any lock closure, an unsafe concurrent window is exposed where parallel worker lookup threads (e.g., inside perf top) can mistakenly assume the cache remains sorted based on stale parameters, executing binary search queries (bsearch) across an unsorted range and triggering lookups failure. Fix this by introducing a thread-safe, atomic transactional framework routine maps__mutate_mapping() that explicitly acquires the parent maps write semaphore lock, executes an incoming mutation callback block to perform the field updates under full lock protection, and invalidates the sorted tracking flags prior to releasing the write lock. This guarantees absolute atomic synchronization invariants, completely closing the concurrent lookup race window. The adjacent module alignment pass inside machine__create_kernel_maps() is safely preserved as a high-performance lockless pass, as its invocation lifecycle bounds remain strictly single-threaded by contract during session initialization construction. To safely support this unconditional down_write write lock mutator without recursive read-to-write self-deadlock upgrades during lazy symbol loading, we introduce a public maps__load_maps() API. It copies map pointers under a brief read lock and force-loads all modules locklessly outside the lock. Callers (such as perf inject) must pre-load all kernel symbol maps up front at startup using maps__load_maps(), completely bypassing dynamic runtime mutations. Fixes: 39b12f781271 ("perf tools: Make it possible to read object code from= vmlinux") Signed-off-by: Ian Rogers --- tools/perf/util/machine.c | 32 +++++++++++++-------- tools/perf/util/maps.c | 55 ++++++++++++++++++++++++++++++++++++ tools/perf/util/maps.h | 3 ++ tools/perf/util/symbol-elf.c | 41 +++++++++++++++++---------- tools/perf/util/symbol.c | 17 ++++++++--- 5 files changed, 117 insertions(+), 31 deletions(-) diff --git a/tools/perf/util/machine.c b/tools/perf/util/machine.c index e76f8c86e62a..ea918f75e3ad 100644 --- a/tools/perf/util/machine.c +++ b/tools/perf/util/machine.c @@ -1522,22 +1522,30 @@ static void machine__set_kernel_mmap(struct machine= *machine, map__set_end(machine->vmlinux_map, ~0ULL); } =20 -static int machine__update_kernel_mmap(struct machine *machine, - u64 start, u64 end) +struct kernel_mmap_mutation_ctx { + u64 start; + u64 end; +}; + +static int kernel_mmap_mutate_cb(struct map *map, void *data) { - struct map *orig, *updated; - int err; + struct kernel_mmap_mutation_ctx *ctx =3D data; =20 - orig =3D machine->vmlinux_map; - updated =3D map__get(orig); + map__set_start(map, ctx->start); + map__set_end(map, ctx->end); + if (ctx->start =3D=3D 0 && ctx->end =3D=3D 0) + map__set_end(map, ~0ULL); + return 0; +} =20 - machine->vmlinux_map =3D updated; - maps__remove(machine__kernel_maps(machine), orig); - machine__set_kernel_mmap(machine, start, end); - err =3D maps__insert(machine__kernel_maps(machine), updated); - map__put(orig); +static int machine__update_kernel_mmap(struct machine *machine, + u64 start, u64 end) +{ + struct kernel_mmap_mutation_ctx ctx =3D { .start =3D start, .end =3D end = }; =20 - return err; + return maps__mutate_mapping(machine__kernel_maps(machine), + machine->vmlinux_map, + kernel_mmap_mutate_cb, &ctx); } =20 int machine__create_kernel_maps(struct machine *machine) diff --git a/tools/perf/util/maps.c b/tools/perf/util/maps.c index 923935ee21b6..f9d5dc7f673f 100644 --- a/tools/perf/util/maps.c +++ b/tools/perf/util/maps.c @@ -576,6 +576,32 @@ void maps__remove(struct maps *maps, struct map *map) #endif } =20 +int maps__mutate_mapping(struct maps *maps, struct map *map, + int (*mutate_cb)(struct map *map, void *data), void *data) +{ + int err =3D 0; + + if (maps) + down_write(maps__lock(maps)); + + err =3D mutate_cb(map, data); + + if (maps) { + RC_CHK_ACCESS(maps)->maps_by_address_sorted =3D false; + RC_CHK_ACCESS(maps)->maps_by_name_sorted =3D false; + } + + if (maps) + up_write(maps__lock(maps)); + +#ifdef HAVE_LIBDW_SUPPORT + if (maps) + libdw__invalidate_dwfl(maps, maps__libdw_addr_space_dwfl(maps)); +#endif + + return err; +} + bool maps__empty(struct maps *maps) { bool res; @@ -626,6 +652,35 @@ int maps__for_each_map(struct maps *maps, int (*cb)(st= ruct map *map, void *data) return ret; } =20 +int maps__load_maps(struct maps *maps) +{ + struct map **maps_copy; + unsigned int nr_maps; + int err =3D 0; + + if (!maps) + return 0; + + down_read(maps__lock(maps)); + nr_maps =3D maps__nr_maps(maps); + maps_copy =3D calloc(nr_maps, sizeof(*maps_copy)); + if (!maps_copy) { + up_read(maps__lock(maps)); + return -ENOMEM; + } + for (unsigned int i =3D 0; i < nr_maps; i++) + maps_copy[i] =3D map__get(maps__maps_by_address(maps)[i]); + up_read(maps__lock(maps)); + + for (unsigned int i =3D 0; i < nr_maps; i++) { + if (map__load(maps_copy[i]) < 0) + err =3D -1; + map__put(maps_copy[i]); + } + free(maps_copy); + return err; +} + void maps__remove_maps(struct maps *maps, bool (*cb)(struct map *map, void= *data), void *data) { struct map **maps_by_address; diff --git a/tools/perf/util/maps.h b/tools/perf/util/maps.h index 5b80b199685e..4ec9b7453a3b 100644 --- a/tools/perf/util/maps.h +++ b/tools/perf/util/maps.h @@ -59,8 +59,11 @@ void maps__set_libdw_addr_space_dwfl(struct maps *maps, = void *dwfl); =20 size_t maps__fprintf(struct maps *maps, FILE *fp); =20 +int maps__load_maps(struct maps *maps); int maps__insert(struct maps *maps, struct map *map); void maps__remove(struct maps *maps, struct map *map); +int maps__mutate_mapping(struct maps *maps, struct map *map, + int (*mutate_cb)(struct map *map, void *data), void *data); =20 struct map *maps__find(struct maps *maps, u64 addr); struct symbol *maps__find_symbol(struct maps *maps, u64 addr, struct map *= *mapp); diff --git a/tools/perf/util/symbol-elf.c b/tools/perf/util/symbol-elf.c index 7afa8a117139..dc4ab58857b3 100644 --- a/tools/perf/util/symbol-elf.c +++ b/tools/perf/util/symbol-elf.c @@ -1341,6 +1341,24 @@ static u64 ref_reloc(struct kmap *kmap) void __weak arch__sym_update(struct symbol *s __maybe_unused, GElf_Sym *sym __maybe_unused) { } =20 +struct remap_kernel_ctx { + u64 sh_addr; + u64 sh_size; + u64 sh_offset; + struct kmap *kmap; +}; + +static int remap_kernel_cb(struct map *map, void *data) +{ + struct remap_kernel_ctx *ctx =3D data; + + map__set_start(map, ctx->sh_addr + ref_reloc(ctx->kmap)); + map__set_end(map, map__start(map) + ctx->sh_size); + map__set_pgoff(map, ctx->sh_offset); + map__set_mapping_type(map, MAPPING_TYPE__DSO); + return 0; +} + static int dso__process_kernel_symbol(struct dso *dso, struct map *map, GElf_Sym *sym, GElf_Shdr *shdr, struct maps *kmaps, struct kmap *kmap, @@ -1371,22 +1389,15 @@ static int dso__process_kernel_symbol(struct dso *d= so, struct map *map, * map to the kernel dso. */ if (*remap_kernel && dso__kernel(dso) && !kmodule) { + struct remap_kernel_ctx ctx =3D { + .sh_addr =3D shdr->sh_addr, + .sh_size =3D shdr->sh_size, + .sh_offset =3D shdr->sh_offset, + .kmap =3D kmap + }; + *remap_kernel =3D false; - map__set_start(map, shdr->sh_addr + ref_reloc(kmap)); - map__set_end(map, map__start(map) + shdr->sh_size); - map__set_pgoff(map, shdr->sh_offset); - map__set_mapping_type(map, MAPPING_TYPE__DSO); - /* Ensure maps are correctly ordered */ - if (kmaps) { - int err; - struct map *tmp =3D map__get(map); - - maps__remove(kmaps, map); - err =3D maps__insert(kmaps, map); - map__put(tmp); - if (err) - return err; - } + maps__mutate_mapping(kmaps, map, remap_kernel_cb, &ctx); } =20 /* diff --git a/tools/perf/util/symbol.c b/tools/perf/util/symbol.c index fcaeeddbbb6b..09b93e844887 100644 --- a/tools/perf/util/symbol.c +++ b/tools/perf/util/symbol.c @@ -48,6 +48,13 @@ #include #include =20 +static int map_fixup_cb(struct map *map, void *data __maybe_unused) +{ + map__fixup_start(map); + map__fixup_end(map); + return 0; +} + static int dso__load_kernel_sym(struct dso *dso, struct map *map); static int dso__load_guest_kernel_sym(struct dso *dso, struct map *map); static bool symbol__is_idle(const char *name); @@ -2121,10 +2128,11 @@ static int dso__load_kernel_sym(struct dso *dso, st= ruct map *map) free(kallsyms_allocated_filename); =20 if (err > 0 && !dso__is_kcore(dso)) { + struct maps *kmaps =3D map__kmaps(map); + dso__set_binary_type(dso, DSO_BINARY_TYPE__KALLSYMS); dso__set_long_name(dso, DSO__NAME_KALLSYMS, false); - map__fixup_start(map); - map__fixup_end(map); + maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL); } =20 return err; @@ -2164,10 +2172,11 @@ static int dso__load_guest_kernel_sym(struct dso *d= so, struct map *map) if (err > 0) pr_debug("Using %s for symbols\n", kallsyms_filename); if (err > 0 && !dso__is_kcore(dso)) { + struct maps *kmaps =3D map__kmaps(map); + dso__set_binary_type(dso, DSO_BINARY_TYPE__GUEST_KALLSYMS); dso__set_long_name(dso, machine->mmap_name, false); - map__fixup_start(map); - map__fixup_end(map); + maps__mutate_mapping(kmaps, map, map_fixup_cb, NULL); } =20 return err; --=20 2.54.0.631.ge1b05301d1-goog From nobody Mon May 25 03:33:06 2026 Received: from mail-dl1-f74.google.com (mail-dl1-f74.google.com [74.125.82.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 326633E121F for ; Tue, 19 May 2026 08:08:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=74.125.82.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779178115; cv=none; b=g/j/ZiIOh7Od6YtMbaBeix2BQLdEv/3gEU1eWj0b6S8PBbWcc5ezljAVtIsiNuS15+AUPvMTZS2sFhDJIRQoAoGF8sO4iVtuU4r/+jHzu33Yx4qCf5ZPsf/Gu6wekUOLhfEW8BWrQW7WCtBzJUBtmZa2Ti/G43yEoaZknWnEgak= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779178115; c=relaxed/simple; bh=QigLO/1EyHwr9Mxfp46/kSMXPi7B0QHURuOUWyF5YvQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=FzN+UZp3L9AW6MZPU6Y8Vv6vzDRu5ag1il9XTi7E7adLGPx4jawBK+p0QgWs5DmCb8lGqYHfhsimGks1z37XzVfuwB2mW5wvUcyUWP8Rc+JVckONqjrKr01OFW3JbRBr1hUsrcCQ+VmvEJLRlyNWXWM6GkiyjyZFXpYP0BFKeEk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=slwGdTUl; arc=none smtp.client-ip=74.125.82.74 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.b="slwGdTUl" Received: by mail-dl1-f74.google.com with SMTP id a92af1059eb24-130aab78a09so3394175c88.0 for ; Tue, 19 May 2026 01:08:32 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20251104; t=1779178111; x=1779782911; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=dBVLUSZerE4X9RplXfEJUHJ/rzarqIPtz5S5pRBKPWc=; b=slwGdTUlBRryYb9sqpu0iFkyIQiH3se8dEBc/5JageUIi+a2VgoplN7uYiQUCTb6rW UeWgPxZi1/SmVYRMTZzzPjvv6APPxIw5hy2/CZsOorT3z4llDkLZinQiSsu43Q153PQt rzStzZxjYXiPYwcCJ/xNpKRRNbzvMugSzVvvJOKWRPUTd6AIIvjZUpasy5Euxi8uB4nL Swo0uDjXz4dNASUoxmAHYeWLEaJmZbIaaOb98i3vo5V74LpeOcZouf2JdjUcdT+mCtTl k8gvh2bZnXuUh0TTx6GphOnn95SOaTY5zRIaSxuj2COh5UKL/wiw6GUcM39EkrsVPFZ0 5a9Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1779178111; x=1779782911; h=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; bh=dBVLUSZerE4X9RplXfEJUHJ/rzarqIPtz5S5pRBKPWc=; b=cqx65p0Vd9oDdsqQCZ0sGsdpVRT1lVRz8jVgz0dYtAqLWpSvtXpoQOaTPnmK0kpEX/ n4u5YfinGnn8OT6L0LC0z2yJftJQmgaYaVB1CVAynct0WR33Rdqe1jVdqzCvYsm2gxLD 9fDVjD8q4G+n/Lubug14R/e0TivRMA3QToS8KFL1c7xPgW16bM9kteu74wHB+pscjeNA HIY1nI2CBv6VE3zpRkjDAhSazaTlJT/gTAgqlhA3jTpnDXaDEp2RVIPSSXYK0QYt4bs6 kVc+TqgHdtqjaL8VA+hdaT28zuPm67Tebm1Wc77iye226SHMbAvxupUvr3+LaafUJKpL wYrg== X-Forwarded-Encrypted: i=1; AFNElJ+/BDkxPvHRaNRCdmuWlT2EXaVnwyJXHyHzsKEgVDljDg9+l7zy7GbNkIdzbztwuPeUtQYrt01r/9AYOGY=@vger.kernel.org X-Gm-Message-State: AOJu0Yw4N95XNiuBs2pg/S6G7ys4tO2mMOQEYZqZsbC5vqJlMO1dGQ2w lJ7b3D8PzLl91AMdUyHdTppS7DYT0sjHEIdWAZpt+YlxVm9rbhOvUL+gJqANn2aHa+f9VLeDN2S untVEcSXLPg== X-Received: from dlboy15.prod.google.com ([2002:a05:7022:128f:b0:132:8d92:4d6c]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7022:928:b0:130:5c90:5a22 with SMTP id a92af1059eb24-13504a50480mr7181114c88.42.1779178110973; Tue, 19 May 2026 01:08:30 -0700 (PDT) Date: Tue, 19 May 2026 01:08:22 -0700 In-Reply-To: <20260519080824.3329601-1-irogers@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20260508082726.2795191-1-irogers@google.com> <20260519080824.3329601-1-irogers@google.com> X-Mailer: git-send-email 2.54.0.631.ge1b05301d1-goog Message-ID: <20260519080824.3329601-3-irogers@google.com> Subject: [PATCH v7 2/4] perf inject/aslr: Add aslr tool to remap/obfuscate virtual addresses From: Ian Rogers To: irogers@google.com, acme@kernel.org, james.clark@linaro.org, namhyung@kernel.org Cc: adrian.hunter@intel.com, gmx@google.com, jolsa@kernel.org, linux-kernel@vger.kernel.org, linux-perf-users@vger.kernel.org, mingo@redhat.com, peterz@infradead.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" If perf.data files are taken from one machine to another they may leak virtual addresses and so weaken ASLR on the machine they are coming from. Add an aslr option for perf inject that remaps all virtual addresses, or drops data/events, so that the virtual address information isn't leaked. Events carrying virtual memory layouts are conservatively remap-processed or dropped, while zero-address-risk lifecycle metadata records (such as namespaces, cgroups, and BPF program info) are intentionally delegated to preserve comprehensive downstream trace tool analysis compatibility. The ASLR tracking tool virtualizes process and machine namespaces using 'struct machines' to safely isolate host mappings from unprivileged KVM guest address spaces. Memory space layouts are tracked globally per process context to ensure linear, continuous space allocations across successive mapping runs. To remain strictly conservative and guarantee security, the tool scrubs breakpoint addresses (bp_addr) from all synthesized stream headers, completely drops PERF_RECORD_TEXT_POKE events to prevent absolute immediate pointer operands leaks, and drops unsupported complex payloads (such as user register stacks, raw tracepoints, and hardware AUX tracing frames). To permanently eliminate lazy-loading deadlock risks during runtime event processing, the inject tool force-loads all host and guest kernel and module maps up front at session startup under a clean single-threaded context using the new maps__load_maps() API. Guest kernel namespace isolation is secured by tracking guest kernels under kernel_pid (-1) and allocating guest kernel mappings inside kernel_space_start ranges. Unsupported or unrecognized UAPI sample flags are cleanly stripped from attributes up front using ASLR_SUPPORTED_SAMPLE_TYPE bitmask to prevent downstream parser misalignment crashes. Assisted-by: Gemini-CLI:Google Gemini 3 Signed-off-by: Ian Rogers Co-developed-by: Gabriel Marin Signed-off-by: Gabriel Marin --- tools/perf/builtin-inject.c | 93 ++- tools/perf/util/Build | 1 + tools/perf/util/aslr.c | 1106 +++++++++++++++++++++++++++++++++++ tools/perf/util/aslr.h | 37 ++ 4 files changed, 1236 insertions(+), 1 deletion(-) create mode 100644 tools/perf/util/aslr.c create mode 100644 tools/perf/util/aslr.h diff --git a/tools/perf/builtin-inject.c b/tools/perf/builtin-inject.c index a2493f1097df..8fe924e730a1 100644 --- a/tools/perf/builtin-inject.c +++ b/tools/perf/builtin-inject.c @@ -8,6 +8,7 @@ */ #include "builtin.h" =20 +#include "util/aslr.h" #include "util/color.h" #include "util/dso.h" #include "util/vdso.h" @@ -124,6 +125,7 @@ struct perf_inject { bool in_place_update_dry_run; bool copy_kcore_dir; bool convert_callchain; + bool aslr; const char *input_name; struct perf_data output; u64 bytes_written; @@ -2267,6 +2269,56 @@ static int output_fd(struct perf_inject *inject) return inject->in_place_update ? -1 : perf_data__fd(&inject->output); } =20 +/* + * To prevent recursive read-to-write lock upgrades self-deadlocks and con= current + * reader data corruptions, we must completely avoid mutating map boundari= es + * during runtime event processing. Since maps__mutate_mapping() requires = the + * write lock to safely protect concurrent searches in other threads, we f= orce-load + * all host and guest kernel and module maps up-front at session startup u= nder + * a clean single-threaded context, permanently bypassing lazy dynamic loa= ding. + */ +static int machine__load_kernel_maps(struct machine *machine) +{ + struct maps *kmaps =3D machine__kernel_maps(machine); + int err; + + if (!kmaps) + return 0; + + err =3D maps__load_maps(kmaps); + if (!err) { + pr_debug("ASLR: Loaded %u kernel/module maps up front for machine pid %d= :\n", + maps__nr_maps(kmaps), machine->pid); + if (verbose > 0) + maps__fprintf(kmaps, stderr); + } + return err; +} + +/* + * Scans and force-loads all registered host and guest machine kernel and + * module maps up front before event processing starts. + */ +static int perf_inject__load_kernel_maps(struct perf_inject *inject) +{ + struct machine *machine; + struct rb_node *nd; + int err =3D 0; + + /* Load host kernel maps up front */ + if (machine__load_kernel_maps(&inject->session->machines.host) < 0) + err =3D -1; + + /* Load all guest machines kernel maps up front */ + for (nd =3D rb_first_cached(&inject->session->machines.guests); nd; nd = =3D rb_next(nd)) { + machine =3D rb_entry(nd, struct machine, rb_node); + if (machine__load_kernel_maps(machine) < 0) + err =3D -1; + } + + return err; +} + static int __cmd_inject(struct perf_inject *inject) { int ret =3D -EINVAL; @@ -2399,6 +2451,13 @@ static int __cmd_inject(struct perf_inject *inject) if (!inject->output.is_pipe && !inject->in_place_update) lseek(fd, output_data_offset, SEEK_SET); =20 + if (inject->aslr) { + if (perf_inject__load_kernel_maps(inject) < 0) { + pr_err("Failed to load host or guest kernel maps up front\n"); + return -EINVAL; + } + } + ret =3D perf_session__process_events(session); if (ret) return ret; @@ -2460,6 +2519,8 @@ static int __cmd_inject(struct perf_inject *inject) } } =20 + + session->header.data_offset =3D output_data_offset; session->header.data_size =3D inject->bytes_written; perf_session__inject_header(session, session->evlist, fd, &inj_fc.fc, @@ -2569,6 +2630,8 @@ int cmd_inject(int argc, const char **argv) unwind__option), OPT_BOOLEAN(0, "convert-callchain", &inject.convert_callchain, "Generate callchains using DWARF and drop register/stack data"), + OPT_BOOLEAN(0, "aslr", &inject.aslr, + "Remap virtual memory addresses similar to ASLR"), OPT_END() }; const char * const inject_usage[] =3D { @@ -2576,6 +2639,7 @@ int cmd_inject(int argc, const char **argv) NULL }; bool ordered_events; + struct perf_tool *tool =3D &inject.tool; =20 if (!inject.itrace_synth_opts.set) { /* Disable eager loading of kernel symbols that adds overhead to perf in= ject. */ @@ -2596,6 +2660,11 @@ int cmd_inject(int argc, const char **argv) if (argc) usage_with_options(inject_usage, options); =20 + if (inject.aslr && inject.convert_callchain) { + pr_err("Error: --aslr and --convert-callchain are mutually exclusive fea= tures.\n"); + return -EINVAL; + } + if (inject.strip && !inject.itrace_synth_opts.set) { pr_err("--strip option requires --itrace option\n"); return -1; @@ -2689,18 +2758,38 @@ int cmd_inject(int argc, const char **argv) inject.tool.schedstat_domain =3D perf_event__repipe_op2_synth; inject.tool.dont_split_sample_group =3D true; inject.tool.merge_deferred_callchains =3D false; - inject.session =3D __perf_session__new(&data, &inject.tool, + if (inject.aslr) { + tool =3D aslr_tool__new(&inject.tool); + if (!tool) { + ret =3D -ENOMEM; + goto out_close_output; + } + } + inject.session =3D __perf_session__new(&data, tool, /*trace_event_repipe=3D*/inject.output.is_pipe, /*host_env=3D*/NULL); =20 if (IS_ERR(inject.session)) { ret =3D PTR_ERR(inject.session); + if (inject.aslr) + aslr_tool__delete(tool); goto out_close_output; } =20 if (zstd_init(&(inject.session->zstd_data), 0) < 0) pr_warning("Decompression initialization failed.\n"); =20 + if (inject.aslr) { + struct evsel *evsel; + + evlist__for_each_entry(inject.session->evlist, evsel) { + evsel->core.attr.sample_type &=3D ASLR_SUPPORTED_SAMPLE_TYPE; + + if (evsel->core.attr.type =3D=3D PERF_TYPE_BREAKPOINT) + evsel->core.attr.bp_addr =3D 0; + } + } + /* Save original section info before feature bits change */ ret =3D save_section_info(&inject); if (ret) @@ -2794,6 +2883,8 @@ int cmd_inject(int argc, const char **argv) strlist__delete(inject.known_build_ids); zstd_fini(&(inject.session->zstd_data)); perf_session__delete(inject.session); + if (inject.aslr) + aslr_tool__delete(tool); out_close_output: if (!inject.in_place_update) perf_data__close(&inject.output); diff --git a/tools/perf/util/Build b/tools/perf/util/Build index 2bb60f50f62d..98da4e263c6d 100644 --- a/tools/perf/util/Build +++ b/tools/perf/util/Build @@ -6,6 +6,7 @@ perf-util-y +=3D arm64-frame-pointer-unwind-support.o perf-util-y +=3D addr2line.o perf-util-y +=3D addr_location.o perf-util-y +=3D annotate.o +perf-util-y +=3D aslr.o perf-util-y +=3D blake2s.o perf-util-y +=3D block-info.o perf-util-y +=3D block-range.o diff --git a/tools/perf/util/aslr.c b/tools/perf/util/aslr.c new file mode 100644 index 000000000000..d0b1b33377fd --- /dev/null +++ b/tools/perf/util/aslr.c @@ -0,0 +1,1106 @@ +// SPDX-License-Identifier: GPL-2.0 +#include "aslr.h" + +#include "addr_location.h" +#include "debug.h" +#include "event.h" +#include "evsel.h" +#include "machine.h" +#include "map.h" +#include "thread.h" +#include "tool.h" +#include "session.h" +#include "data.h" +#include "dso.h" + +#include /* page_size */ +#include +#include +#include +#include + +#define ASLR_SUPPORTED_SAMPLE_TYPE ( \ + PERF_SAMPLE_IDENTIFIER | \ + PERF_SAMPLE_IP | \ + PERF_SAMPLE_TID | \ + PERF_SAMPLE_TIME | \ + PERF_SAMPLE_ADDR | \ + PERF_SAMPLE_ID | \ + PERF_SAMPLE_STREAM_ID | \ + PERF_SAMPLE_CPU | \ + PERF_SAMPLE_PERIOD | \ + PERF_SAMPLE_READ | \ + PERF_SAMPLE_CALLCHAIN | \ + PERF_SAMPLE_RAW | \ + PERF_SAMPLE_BRANCH_STACK | \ + PERF_SAMPLE_STACK_USER | \ + PERF_SAMPLE_WEIGHT_TYPE | \ + PERF_SAMPLE_DATA_SRC | \ + PERF_SAMPLE_TRANSACTION | \ + PERF_SAMPLE_PHYS_ADDR | \ + PERF_SAMPLE_CGROUP | \ + PERF_SAMPLE_DATA_PAGE_SIZE | \ + PERF_SAMPLE_CODE_PAGE_SIZE | \ + PERF_SAMPLE_AUX) + +/** + * struct remap_addresses_key - Key for mapping original addresses to rema= pped ones. + * @dso: Pointer to the DSO (Dynamic Shared Object) associated with the ma= pping. + * @invariant: Unique offset invariant within the VMA (Virtual Memory Area= ). + * Calculated as `start - pgoff`. This value remains constant = when + * perf's internal `maps__fixup_overlap_and_insert` splits a m= ap into + * fragmented VMA pieces due to overlapping events, allowing u= s to + * resolve split maps consistently back to the original VMA. + * @pid: Process ID associated with the mapping. + */ +struct remap_addresses_key { + struct machine *machine; + struct dso *dso; + u64 invariant; + pid_t pid; +}; + +struct aslr_mapping { + struct list_head node; + u64 orig_start; + u64 len; + u64 remap_start; +}; + +struct aslr_tool { + /** @tool: The tool implemented here and a pointer to a delegate to proce= ss the data. */ + struct delegate_tool tool; + /** @machines: The machines with the input, not remapped, virtual address= layout. */ + struct machines machines; + /** @event_copy: Buffer used to create an event to pass to the delegate. = */ + char event_copy[PERF_SAMPLE_MAX_SIZE] __aligned(8); + /** @remap_addresses: mapping from remap_addresses_key to remapped addres= s. */ + struct hashmap remap_addresses; + /** @top_addresses: mapping from process to max remapped address. */ + struct hashmap top_addresses; +}; + +static const pid_t kernel_pid =3D -1; + +/* Start remapping user processes from a small non-zero offset. */ +static const u64 user_space_start =3D 0x200000; +static const u64 kernel_space_start =3D 0xffff800010000000; + +static size_t remap_addresses__hash(long _key, void *ctx __maybe_unused) +{ + struct remap_addresses_key *key =3D (struct remap_addresses_key *)_key; + + return (size_t)key->machine ^ (size_t)key->dso ^ key->invariant ^ key->pi= d; +} + +static bool remap_addresses__equal(long _key1, long _key2, void *ctx __may= be_unused) +{ + struct remap_addresses_key *key1 =3D (struct remap_addresses_key *)_key1; + struct remap_addresses_key *key2 =3D (struct remap_addresses_key *)_key2; + + return key1->machine =3D=3D key2->machine && + RC_CHK_EQUAL(key1->dso, key2->dso) && + key1->invariant =3D=3D key2->invariant && + key1->pid =3D=3D key2->pid; +} + +struct top_addresses_key { + struct machine *machine; + pid_t pid; +}; + +static size_t top_addresses__hash(long _key, void *ctx __maybe_unused) +{ + struct top_addresses_key *key =3D (struct top_addresses_key *)_key; + + return (size_t)key->machine ^ key->pid; +} + +static bool top_addresses__equal(long _key1, long _key2, void *ctx __maybe= _unused) +{ + struct top_addresses_key *key1 =3D (struct top_addresses_key *)_key1; + struct top_addresses_key *key2 =3D (struct top_addresses_key *)_key2; + + return key1->machine =3D=3D key2->machine && key1->pid =3D=3D key2->pid; +} + +static u64 round_up_to_page_size(u64 addr) +{ + return (addr + page_size - 1) & ~((u64)page_size - 1); +} + +static u64 aslr_tool__remap_address(struct aslr_tool *aslr, + struct thread *aslr_thread, + u8 cpumode, + u64 addr) +{ + struct addr_location al; + struct remap_addresses_key key; + u64 *remapped_invariant_ptr =3D NULL; + u64 remap_addr =3D 0; + u8 effective_cpumode =3D cpumode; + + if (!aslr_thread) + return 0; /* No thread. */ + + addr_location__init(&al); + if (!thread__find_map(aslr_thread, cpumode, addr, &al)) { + /* + * If lookup fails with specified cpumode, try fallback to the other spa= ce + * to be robust against bad cpumode in samples. + */ + if (cpumode =3D=3D PERF_RECORD_MISC_KERNEL) + effective_cpumode =3D PERF_RECORD_MISC_USER; + else if (cpumode =3D=3D PERF_RECORD_MISC_USER) + effective_cpumode =3D PERF_RECORD_MISC_KERNEL; + else if (cpumode =3D=3D PERF_RECORD_MISC_GUEST_KERNEL) + effective_cpumode =3D PERF_RECORD_MISC_GUEST_USER; + else if (cpumode =3D=3D PERF_RECORD_MISC_GUEST_USER) + effective_cpumode =3D PERF_RECORD_MISC_GUEST_KERNEL; + + if (!thread__find_map(aslr_thread, effective_cpumode, addr, &al)) { + addr_location__exit(&al); + return 0; /* No mmap. */ + } + } + + key.machine =3D maps__machine(aslr_thread->maps); + key.dso =3D map__dso(al.map); + key.invariant =3D map__start(al.map) - map__pgoff(al.map); + key.pid =3D (effective_cpumode =3D=3D PERF_RECORD_MISC_KERNEL || + effective_cpumode =3D=3D PERF_RECORD_MISC_GUEST_KERNEL) ? + kernel_pid : aslr_thread->pid_; + + if (hashmap__find(&aslr->remap_addresses, &key, &remapped_invariant_ptr))= { + remap_addr =3D *remapped_invariant_ptr + map__pgoff(al.map) + + (addr - map__start(al.map)); + } else { + pr_debug("Cannot find a remapped entry for address %lx in mapping %lx(%l= x) for pid=3D%d\n", + addr, map__start(al.map), map__size(al.map), key.pid); + } + + addr_location__exit(&al); + return remap_addr; +} + +static u64 aslr_tool__findnew_mapping(struct aslr_tool *aslr, + struct thread *aslr_thread, + u8 cpumode, u64 start, + u64 len, u64 pgoff) +{ + /* Address location for dso lookup. */ + struct addr_location al; + /* Original ASLR address based key for the remap table. */ + struct remap_addresses_key remap_key; + /* The address in the ASLR sanitized address space less pg_off. */ + u64 *remapped_invariant_ptr; + /* Key for the maximum address in a process. */ + struct top_addresses_key top_addr_key; + /* Value in top address table. */ + u64 *pmax =3D NULL; + /* Address in ASLR sanitized address space. */ + u64 remap_addr; + /* Potentially allocated remap table key. */ + struct remap_addresses_key *new_remap_key =3D NULL; + /* + * Potentially allocated remap table key. + * TODO: Avoid allocation necessary for perf 32-bit binary support. + */ + u64 *new_remap_val =3D NULL; + int err; + + if (!aslr_thread) + return 0; + + /* The key to look up an incoming address to the outgoing value. */ + addr_location__init(&al); + remap_key.machine =3D maps__machine(aslr_thread->maps); + remap_key.pid =3D (cpumode =3D=3D PERF_RECORD_MISC_KERNEL || + cpumode =3D=3D PERF_RECORD_MISC_GUEST_KERNEL) ? + kernel_pid : aslr_thread->pid_; + if (thread__find_map(aslr_thread, cpumode, start, &al)) { + remap_key.dso =3D map__dso(al.map); + remap_key.invariant =3D map__start(al.map) - map__pgoff(al.map); + } else { + remap_key.dso =3D NULL; + remap_key.invariant =3D start - pgoff; + } + + /* The key to look up top allocated address. */ + top_addr_key.machine =3D remap_key.machine; + top_addr_key.pid =3D remap_key.pid; + + if (hashmap__find(&aslr->remap_addresses, &remap_key, &remapped_invariant= _ptr)) { + /* Mmap already exists. */ + u64 calculated_max; + + remap_addr =3D *remapped_invariant_ptr + (al.map ? map__pgoff(al.map) : = pgoff); + calculated_max =3D remap_addr + len; + + /* See if top mapping was expanded. */ + if (hashmap__find(&aslr->top_addresses, &top_addr_key, &pmax)) { + if (calculated_max > *pmax) + *pmax =3D calculated_max; + } + addr_location__exit(&al); + return remap_addr; + } + /* No mmap, create an entry from the top address. */ + if (hashmap__find(&aslr->top_addresses, &top_addr_key, &pmax)) { + /* Current max allocated mmap address within the process. */ + remap_addr =3D *pmax; + + /* Give 1 page gap from current max page. */ + remap_addr =3D round_up_to_page_size(remap_addr); + remap_addr +=3D page_size; + if (remap_addr + len > *pmax) + *pmax =3D remap_addr + len; + } else { + /* First address of the process, allocate key and first top address. */ + struct top_addresses_key *tk; + + remap_addr =3D (cpumode =3D=3D PERF_RECORD_MISC_KERNEL || + cpumode =3D=3D PERF_RECORD_MISC_GUEST_KERNEL) ? + kernel_space_start : user_space_start; + remap_addr =3D round_up_to_page_size(remap_addr); + + tk =3D malloc(sizeof(*tk)); + pmax =3D malloc(sizeof(u64)); + if (!tk || !pmax) { + err =3D -ENOMEM; + } else { + *tk =3D top_addr_key; + *pmax =3D remap_addr + len; + err =3D hashmap__insert(&aslr->top_addresses, tk, pmax, + HASHMAP_ADD, NULL, NULL); + } + if (err) { + errno =3D -err; + pr_err("Failure to add ASLR process top address %m\n"); + free(tk); + free(pmax); + addr_location__exit(&al); + return 0; + } + } + /* Create rmeapping entry. */ + new_remap_key =3D malloc(sizeof(*new_remap_key)); + new_remap_val =3D malloc(sizeof(u64)); + if (!new_remap_key || !new_remap_val) { + err =3D -ENOMEM; + } else { + *new_remap_key =3D remap_key; + new_remap_key->dso =3D dso__get(remap_key.dso); + if (cpumode =3D=3D PERF_RECORD_MISC_KERNEL || + cpumode =3D=3D PERF_RECORD_MISC_GUEST_KERNEL) { + if (al.map) { + *new_remap_val =3D remap_addr - + (start - map__start(al.map)) - + map__pgoff(al.map); + } else { + *new_remap_val =3D remap_addr; + } + } else { + *new_remap_val =3D remap_addr - (al.map ? map__pgoff(al.map) : pgoff); + } + err =3D hashmap__add(&aslr->remap_addresses, new_remap_key, new_remap_va= l); + if (err) + dso__put(new_remap_key->dso); + } + if (err) { + errno =3D -err; + pr_err("Failure to add ASLR remapping %m\n"); + free(new_remap_key); + free(new_remap_val); + addr_location__exit(&al); + return 0; + } + addr_location__exit(&al); + return remap_addr; +} + +static int aslr_tool__process_mmap(const struct perf_tool *tool, + union perf_event *event, + struct perf_sample *sample, + struct machine *machine) +{ + struct delegate_tool *del_tool; + struct aslr_tool *aslr; + struct perf_tool *delegate; + union perf_event *new_event; + u8 cpumode; + struct thread *thread; + struct machine *aslr_machine; + int err; + + del_tool =3D container_of(tool, struct delegate_tool, tool); + aslr =3D container_of(del_tool, struct aslr_tool, tool); + delegate =3D aslr->tool.delegate; + new_event =3D (union perf_event *)aslr->event_copy; + cpumode =3D event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK; + + aslr_machine =3D machines__findnew(&aslr->machines, machine->pid); + if (!aslr_machine) + return -ENOMEM; + + /* Create the thread, map, etc. in the ASLR before virtual address space.= */ + err =3D perf_event__process_mmap(tool, event, sample, aslr_machine); + if (err) + return err; + + thread =3D machine__findnew_thread(aslr_machine, event->mmap.pid, event->= mmap.tid); + if (!thread) + return -ENOMEM; + memcpy(&new_event->mmap, &event->mmap, event->mmap.header.size); + /* Remaps the mmap.start. */ + new_event->mmap.start =3D aslr_tool__findnew_mapping(aslr, thread, cpumod= e, + event->mmap.start, + event->mmap.len, + event->mmap.pgoff); + if (cpumode =3D=3D PERF_RECORD_MISC_KERNEL || cpumode =3D=3D PERF_RECORD_= MISC_GUEST_KERNEL) + new_event->mmap.pgoff =3D new_event->mmap.start; + err =3D delegate->mmap(delegate, new_event, sample, machine); + thread__put(thread); + return err; +} + +static int aslr_tool__process_mmap2(const struct perf_tool *tool, + union perf_event *event, + struct perf_sample *sample, + struct machine *machine) +{ + struct delegate_tool *del_tool; + struct aslr_tool *aslr; + struct perf_tool *delegate; + union perf_event *new_event; + u8 cpumode; + struct thread *thread; + struct machine *aslr_machine; + int err; + + del_tool =3D container_of(tool, struct delegate_tool, tool); + aslr =3D container_of(del_tool, struct aslr_tool, tool); + delegate =3D aslr->tool.delegate; + new_event =3D (union perf_event *)aslr->event_copy; + cpumode =3D event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK; + + aslr_machine =3D machines__findnew(&aslr->machines, machine->pid); + if (!aslr_machine) + return -ENOMEM; + + /* Create the thread, map, etc. in the ASLR before virtual address space.= */ + err =3D perf_event__process_mmap2(tool, event, sample, aslr_machine); + if (err) + return err; + + thread =3D machine__findnew_thread(aslr_machine, event->mmap2.pid, event-= >mmap2.tid); + if (!thread) + return -ENOMEM; + memcpy(&new_event->mmap2, &event->mmap2, event->mmap2.header.size); + /* Remaps the mmap.start. */ + new_event->mmap2.start =3D aslr_tool__findnew_mapping(aslr, thread, cpumo= de, + event->mmap2.start, + event->mmap2.len, + event->mmap2.pgoff); + if (cpumode =3D=3D PERF_RECORD_MISC_KERNEL || cpumode =3D=3D PERF_RECORD_= MISC_GUEST_KERNEL) + new_event->mmap2.pgoff =3D new_event->mmap2.start; + err =3D delegate->mmap2(delegate, new_event, sample, machine); + thread__put(thread); + return err; +} + +static int aslr_tool__process_comm(const struct perf_tool *tool, + union perf_event *event, + struct perf_sample *sample, + struct machine *machine) +{ + struct delegate_tool *del_tool; + struct aslr_tool *aslr; + struct perf_tool *delegate; + struct machine *aslr_machine; + int err; + + del_tool =3D container_of(tool, struct delegate_tool, tool); + aslr =3D container_of(del_tool, struct aslr_tool, tool); + delegate =3D aslr->tool.delegate; + + aslr_machine =3D machines__findnew(&aslr->machines, machine->pid); + if (!aslr_machine) + return -ENOMEM; + + /* Create the thread, map, etc. in the ASLR before virtual address space.= */ + err =3D perf_event__process_comm(tool, event, sample, aslr_machine); + if (err) + return err; + + return delegate->comm(delegate, event, sample, machine); +} + +static int aslr_tool__process_fork(const struct perf_tool *tool, + union perf_event *event, + struct perf_sample *sample, + struct machine *machine) +{ + struct delegate_tool *del_tool; + struct aslr_tool *aslr; + struct perf_tool *delegate; + struct machine *aslr_machine; + int err; + + del_tool =3D container_of(tool, struct delegate_tool, tool); + aslr =3D container_of(del_tool, struct aslr_tool, tool); + delegate =3D aslr->tool.delegate; + + aslr_machine =3D machines__findnew(&aslr->machines, machine->pid); + if (!aslr_machine) + return -ENOMEM; + + /* Create the thread, map, etc. in the ASLR before virtual address space.= */ + err =3D perf_event__process_fork(tool, event, sample, aslr_machine); + if (err) + return err; + + return delegate->fork(delegate, event, sample, machine); +} + +static int aslr_tool__process_exit(const struct perf_tool *tool, + union perf_event *event, + struct perf_sample *sample, + struct machine *machine) +{ + struct delegate_tool *del_tool; + struct aslr_tool *aslr; + struct perf_tool *delegate; + struct machine *aslr_machine; + int err; + + del_tool =3D container_of(tool, struct delegate_tool, tool); + aslr =3D container_of(del_tool, struct aslr_tool, tool); + delegate =3D aslr->tool.delegate; + + aslr_machine =3D machines__findnew(&aslr->machines, machine->pid); + if (!aslr_machine) + return -ENOMEM; + + /* Create the thread, map, etc. in the ASLR before virtual address space.= */ + err =3D perf_event__process_exit(tool, event, sample, aslr_machine); + if (err) + return err; + + return delegate->exit(delegate, event, sample, machine); +} + +static int aslr_tool__process_text_poke(const struct perf_tool *tool __may= be_unused, + union perf_event *event __maybe_unused, + struct perf_sample *sample __maybe_unused, + struct machine *machine __maybe_unused) +{ + /* Drop in case the instruction encodes an ASLR revealing address. */ + return 0; +} + +static int aslr_tool__process_ksymbol(const struct perf_tool *tool, + union perf_event *event, + struct perf_sample *sample, + struct machine *machine) +{ + struct delegate_tool *del_tool; + struct aslr_tool *aslr; + struct perf_tool *delegate; + union perf_event *new_event; + struct thread *thread; + struct machine *aslr_machine; + int err; + + del_tool =3D container_of(tool, struct delegate_tool, tool); + aslr =3D container_of(del_tool, struct aslr_tool, tool); + delegate =3D aslr->tool.delegate; + new_event =3D (union perf_event *)aslr->event_copy; + + aslr_machine =3D machines__findnew(&aslr->machines, machine->pid); + if (!aslr_machine) + return -ENOMEM; + + err =3D perf_event__process_ksymbol(tool, event, sample, aslr_machine); + if (err) + return err; + + thread =3D machine__findnew_thread(aslr_machine, kernel_pid, 0); + if (!thread) + return -ENOMEM; + memcpy(&new_event->ksymbol, &event->ksymbol, event->ksymbol.header.size); + /* Remaps the ksymbol.start */ + new_event->ksymbol.addr =3D aslr_tool__findnew_mapping(aslr, thread, + PERF_RECORD_MISC_KERNEL, + event->ksymbol.addr, + event->ksymbol.len, + /*pgoff=3D*/0); + + err =3D delegate->ksymbol(delegate, new_event, sample, machine); + thread__put(thread); + return err; +} + +static int aslr_tool__process_sample(const struct perf_tool *tool, + union perf_event *event, + struct perf_sample *sample, + struct evsel *evsel, + struct machine *machine) +{ + struct delegate_tool *del_tool; + struct aslr_tool *aslr; + struct perf_tool *delegate; + int ret; + u64 sample_type; + struct thread *thread; + struct machine *aslr_machine; + __u64 max_i; + __u64 max_j; + union perf_event *new_event; + struct perf_sample new_sample; + __u64 *in_array, *out_array; + u8 cpumode; + u64 addr; + size_t i; + size_t j; + + del_tool =3D container_of(tool, struct delegate_tool, tool); + aslr =3D container_of(del_tool, struct aslr_tool, tool); + delegate =3D aslr->tool.delegate; + ret =3D -EFAULT; + sample_type =3D evsel->core.attr.sample_type; + max_i =3D (event->header.size - sizeof(struct perf_event_header)) / sizeo= f(__u64); + max_j =3D (PERF_SAMPLE_MAX_SIZE - sizeof(struct perf_event_header)) / siz= eof(__u64); + new_event =3D (union perf_event *)aslr->event_copy; + cpumode =3D sample->cpumode; + i =3D 0; + j =3D 0; + + aslr_machine =3D machines__findnew(&aslr->machines, machine->pid); + if (!aslr_machine) + return -ENOMEM; + + thread =3D machine__findnew_thread(aslr_machine, sample->pid, sample->tid= ); + + if (!thread) + return -ENOMEM; + + if (max_i > PERF_SAMPLE_MAX_SIZE / sizeof(u64)) + goto out_put; + + new_event->sample.header =3D event->sample.header; + + in_array =3D &event->sample.array[0]; + out_array =3D &new_event->sample.array[0]; + +#define CHECK_BOUNDS(required_i, required_j) \ + (i + (required_i) > max_i || j + (required_j) > max_j) + +#define COPY_U64() \ + do { \ + if (CHECK_BOUNDS(1, 1)) { \ + ret =3D -EFAULT; \ + goto out_put; \ + } \ + out_array[j++] =3D in_array[i++]; \ + } while (0) + +#define REMAP_U64(addr_field) \ + do { \ + if (CHECK_BOUNDS(1, 1)) { \ + ret =3D -EFAULT; \ + goto out_put; \ + } \ + out_array[j++] =3D aslr_tool__remap_address(aslr, thread, cpumode, addr_= field); \ + i++; \ + } while (0) + + if (sample_type & PERF_SAMPLE_IDENTIFIER) + COPY_U64(); /* id */ + if (sample_type & PERF_SAMPLE_IP) + REMAP_U64(sample->ip); + if (sample_type & PERF_SAMPLE_TID) + COPY_U64(); /* pid, tid */ + if (sample_type & PERF_SAMPLE_TIME) + COPY_U64(); /* time */ + if (sample_type & PERF_SAMPLE_ADDR) + REMAP_U64(sample->addr); + if (sample_type & PERF_SAMPLE_ID) + COPY_U64(); /* id */ + if (sample_type & PERF_SAMPLE_STREAM_ID) + COPY_U64(); /* stream_id */ + if (sample_type & PERF_SAMPLE_CPU) + COPY_U64(); /* cpu, res */ + if (sample_type & PERF_SAMPLE_PERIOD) + COPY_U64(); /* period */ + if (sample_type & PERF_SAMPLE_READ) { + if ((evsel->core.attr.read_format & PERF_FORMAT_GROUP) =3D=3D 0) { + COPY_U64(); /* value */ + if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) + COPY_U64(); /* time_enabled */ + if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) + COPY_U64(); /* time_running */ + if (evsel->core.attr.read_format & PERF_FORMAT_ID) + COPY_U64(); /* id */ + if (evsel->core.attr.read_format & PERF_FORMAT_LOST) + COPY_U64(); /* lost */ + } else { + u64 nr; + + if (CHECK_BOUNDS(1, 1)) { + ret =3D -EFAULT; + goto out_put; + } + out_array[j] =3D in_array[i]; + nr =3D out_array[j++]; + i++; + if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) + COPY_U64(); /* time_enabled */ + if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) + COPY_U64(); /* time_running */ + for (u64 cntr =3D 0; cntr < nr; cntr++) { + COPY_U64(); /* value */ + if (evsel->core.attr.read_format & PERF_FORMAT_ID) + COPY_U64(); /* id */ + if (evsel->core.attr.read_format & PERF_FORMAT_LOST) + COPY_U64(); /* lost */ + } + } + } + if (sample_type & PERF_SAMPLE_CALLCHAIN) { + u64 nr; + + if (CHECK_BOUNDS(1, 1)) { + ret =3D -EFAULT; + goto out_put; + } + out_array[j] =3D in_array[i]; + nr =3D out_array[j++]; + i++; + + for (u64 cntr =3D 0; cntr < nr; cntr++) { + if (CHECK_BOUNDS(1, 1)) { + ret =3D -EFAULT; + goto out_put; + } + addr =3D in_array[i++]; + if (addr >=3D PERF_CONTEXT_MAX) { + out_array[j++] =3D addr; + switch (addr) { + case PERF_CONTEXT_HV: + cpumode =3D PERF_RECORD_MISC_HYPERVISOR; + break; + case PERF_CONTEXT_KERNEL: + cpumode =3D PERF_RECORD_MISC_KERNEL; + break; + case PERF_CONTEXT_USER: + cpumode =3D PERF_RECORD_MISC_USER; + break; + case PERF_CONTEXT_GUEST: + cpumode =3D PERF_RECORD_MISC_GUEST_KERNEL; + break; + case PERF_CONTEXT_GUEST_KERNEL: + cpumode =3D PERF_RECORD_MISC_GUEST_KERNEL; + break; + case PERF_CONTEXT_GUEST_USER: + cpumode =3D PERF_RECORD_MISC_GUEST_USER; + break; + case PERF_CONTEXT_USER_DEFERRED: + if (cntr + 1 >=3D nr) { + pr_debug("Truncated callchain deferred cookie context\n"); + ret =3D 0; + goto out_put; + } + /* + * Immediately followed by a 64-bit + * stitching cookie. Skip/Copy it! + */ + if (CHECK_BOUNDS(1, 1)) { + ret =3D -EFAULT; + goto out_put; + } + out_array[j++] =3D in_array[i++]; + cntr++; + cpumode =3D PERF_RECORD_MISC_USER; + break; + default: + pr_debug("invalid callchain context: %"PRIx64"\n", addr); + ret =3D 0; + goto out_put; + } + continue; + } + out_array[j++] =3D aslr_tool__remap_address(aslr, thread, cpumode, addr= ); + } + } + if (sample_type & PERF_SAMPLE_RAW) { + size_t bytes =3D sizeof(u32) + sample->raw_size; + size_t u64_words =3D (bytes + 7) / 8; + + if (i + u64_words > max_i || j + u64_words > max_j) { + ret =3D -EFAULT; + goto out_put; + } + memcpy(&out_array[j], &in_array[i], bytes); + i +=3D u64_words; + j +=3D u64_words; + /* + * TODO: certain raw samples can be remapped, such as + * tracepoints by examining their fields. + */ + pr_debug("Dropping raw samples as possible ASLR leak\n"); + ret =3D 0; + goto out_put; + } + if (sample_type & PERF_SAMPLE_BRANCH_STACK) { + u64 nr; + + if (CHECK_BOUNDS(1, 1)) { + ret =3D -EFAULT; + goto out_put; + } + out_array[j] =3D in_array[i]; + nr =3D out_array[j++]; + i++; + + if (evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX) + COPY_U64(); /* hw_idx */ + + if (nr > (ULLONG_MAX / 3)) { + ret =3D -EFAULT; + goto out_put; + } + if (nr * 3 > max_i - i || nr * 3 > max_j - j) { + ret =3D -EFAULT; + goto out_put; + } + for (u64 cntr =3D 0; cntr < nr; cntr++) { + out_array[j++] =3D aslr_tool__remap_address(aslr, thread, + sample->cpumode, + in_array[i++]); /* from */ + out_array[j++] =3D aslr_tool__remap_address(aslr, thread, + sample->cpumode, + in_array[i++]); /* to */ + out_array[j++] =3D in_array[i++]; /* flags */ + } + if (evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS) { + if (nr > max_i - i || nr > max_j - j) { + ret =3D -EFAULT; + goto out_put; + } + memcpy(&out_array[j], &in_array[i], nr * sizeof(u64)); + i +=3D nr; + j +=3D nr; + /* TODO: confirm branch counters don't leak ASLR information. */ + pr_debug("Dropping sample branch counters as possible ASLR leak\n"); + ret =3D 0; + goto out_put; + } + } + if (sample_type & PERF_SAMPLE_REGS_USER) { + u64 abi; + + if (CHECK_BOUNDS(1, 0)) { + ret =3D -EFAULT; + goto out_put; + } + abi =3D in_array[i++]; + if (abi !=3D PERF_SAMPLE_REGS_ABI_NONE) { + u64 nr =3D hweight64(evsel->core.attr.sample_regs_user); + + if (nr > max_i - i || nr > max_j - j) { + ret =3D -EFAULT; + goto out_put; + } + memcpy(&out_array[j], &in_array[i], nr * sizeof(u64)); + i +=3D nr; + j +=3D nr; + } + /* TODO: can this be less conservative? */ + pr_debug("Dropping regs user sample as possible ASLR leak\n"); + ret =3D 0; + goto out_put; + } + if (sample_type & PERF_SAMPLE_STACK_USER) { + u64 size; + + if (CHECK_BOUNDS(1, 1)) { + ret =3D -EFAULT; + goto out_put; + } + out_array[j] =3D in_array[i]; + size =3D out_array[j++]; + i++; + if (size > 0) { + size_t u64_words =3D size / 8 + (size % 8 ? 1 : 0); + + if (u64_words > max_i - i || u64_words > max_j - j) { + ret =3D -EFAULT; + goto out_put; + } + memcpy(&out_array[j], &in_array[i], size); + if (size % 8) { + size_t pad =3D 8 - (size % 8); + + memset(((char *)&out_array[j]) + size, 0, pad); + } + i +=3D u64_words; + j +=3D u64_words; + + COPY_U64(); /* dyn_size */ + } + /* TODO: can this be less conservative? */ + pr_debug("Dropping stack user sample as possible ASLR leak\n"); + ret =3D 0; + goto out_put; + } + if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) + COPY_U64(); /* perf_sample_weight */ + if (sample_type & PERF_SAMPLE_DATA_SRC) + COPY_U64(); /* data_src */ + if (sample_type & PERF_SAMPLE_TRANSACTION) + COPY_U64(); /* transaction */ + if (sample_type & PERF_SAMPLE_REGS_INTR) { + u64 abi; + + if (CHECK_BOUNDS(1, 0)) { + ret =3D -EFAULT; + goto out_put; + } + abi =3D in_array[i++]; + if (abi !=3D PERF_SAMPLE_REGS_ABI_NONE) { + u64 nr =3D hweight64(evsel->core.attr.sample_regs_intr); + + if (nr > max_i - i || nr > max_j - j) { + ret =3D -EFAULT; + goto out_put; + } + memcpy(&out_array[j], &in_array[i], nr * sizeof(u64)); + i +=3D nr; + j +=3D nr; + } + /* TODO: can this be less conservative? */ + pr_debug("Dropping interrupt register sample as possible ASLR leak\n"); + ret =3D 0; + goto out_put; + } + if (sample_type & PERF_SAMPLE_PHYS_ADDR) { + COPY_U64(); /* phys_addr */ + /* TODO: can this be less conservative? */ + pr_debug("Dropping physical address sample as possible ASLR leak\n"); + ret =3D 0; + goto out_put; + } + if (sample_type & PERF_SAMPLE_CGROUP) + COPY_U64(); /* cgroup */ + if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) + COPY_U64(); /* data_page_size */ + if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) + COPY_U64(); /* code_page_size */ + + if (sample_type & PERF_SAMPLE_AUX) { + u64 size; + + if (CHECK_BOUNDS(1, 1)) { + ret =3D -EFAULT; + goto out_put; + } + out_array[j] =3D in_array[i]; + size =3D out_array[j++]; + i++; + if (size > 0) { + size_t u64_words =3D size / 8 + (size % 8 ? 1 : 0); + + if (u64_words > max_i - i || u64_words > max_j - j) { + ret =3D -EFAULT; + goto out_put; + } + memcpy(&out_array[j], &in_array[i], size); + if (size % 8) { + size_t pad =3D 8 - (size % 8); + + memset(((char *)&out_array[j]) + size, 0, pad); + } + i +=3D u64_words; + j +=3D u64_words; + } + /* TODO: can this be less conservative? */ + pr_debug("Dropping aux sample as possible ASLR leak\n"); + ret =3D 0; + goto out_put; + } + + if (evsel__is_offcpu_event(evsel)) { + /* TODO: can this be less conservative? */ + pr_debug("Dropping off-CPU sample as possible ASLR leak\n"); + ret =3D 0; + goto out_put; + } + + new_event->sample.header.size =3D sizeof(struct perf_event_header) + j * = sizeof(u64); + + perf_sample__init(&new_sample, /*all=3D*/ true); + ret =3D evsel__parse_sample(evsel, new_event, &new_sample); + if (ret) { + perf_sample__exit(&new_sample); + goto out_put; + } + + ret =3D delegate->sample(delegate, new_event, &new_sample, evsel, machine= ); + perf_sample__exit(&new_sample); + +out_put: + thread__put(thread); + return ret; +} + +#undef CHECK_BOUNDS +#undef COPY_U64 +#undef REMAP_U64 + +static int aslr_tool__process_attr(const struct perf_tool *tool, + union perf_event *event, + struct evlist **pevlist) +{ + struct delegate_tool *del_tool; + struct aslr_tool *aslr; + struct perf_tool *delegate; + union perf_event *new_event; + + del_tool =3D container_of(tool, struct delegate_tool, tool); + aslr =3D container_of(del_tool, struct aslr_tool, tool); + delegate =3D aslr->tool.delegate; + new_event =3D (union perf_event *)aslr->event_copy; + + memcpy(&new_event->attr, &event->attr, event->attr.header.size); + if (new_event->attr.attr.type =3D=3D PERF_TYPE_BREAKPOINT) + new_event->attr.attr.bp_addr =3D 0; /* Conservatively remove addresses.= */ + + new_event->attr.attr.sample_type &=3D ASLR_SUPPORTED_SAMPLE_TYPE; + + return delegate->attr(delegate, new_event, pevlist); +} + +static int skipn(int fd, off_t n) +{ + char buf[4096]; + ssize_t ret; + + while (n > 0) { + ret =3D read(fd, buf, min_t(off_t, n, (off_t)sizeof(buf))); + if (ret <=3D 0) + return ret; + n -=3D ret; + } + + return 0; +} + +static s64 aslr_tool__process_auxtrace(const struct perf_tool *tool __mayb= e_unused, + struct perf_session *session, + union perf_event *event) +{ + if (perf_data__is_pipe(session->data)) { + /* Copy behavior of the stub by reading all pipe data. */ + int err =3D skipn(perf_data__fd(session->data), event->auxtrace.size); + + if (err < 0) + return err; + } + return event->auxtrace.size; +} + +static int aslr_tool__process_auxtrace_info(const struct perf_tool *tool _= _maybe_unused, + struct perf_session *session __maybe_unused, + union perf_event *event __maybe_unused) +{ + return 0; +} + +static int aslr_tool__process_auxtrace_error(const struct perf_tool *tool = __maybe_unused, + struct perf_session *session __maybe_unused, + union perf_event *event __maybe_unused) +{ + return 0; +} + +static void aslr_tool__init(struct aslr_tool *aslr, struct perf_tool *dele= gate) +{ + delegate_tool__init(&aslr->tool, delegate); + aslr->tool.tool.ordered_events =3D true; + + machines__init(&aslr->machines); + + hashmap__init(&aslr->remap_addresses, + remap_addresses__hash, remap_addresses__equal, + /*ctx=3D*/NULL); + hashmap__init(&aslr->top_addresses, + top_addresses__hash, top_addresses__equal, + /*ctx=3D*/NULL); + + aslr->tool.tool.sample =3D aslr_tool__process_sample; + /* read - reads a counter, okay to delegate. */ + aslr->tool.tool.mmap =3D aslr_tool__process_mmap; + aslr->tool.tool.mmap2 =3D aslr_tool__process_mmap2; + aslr->tool.tool.comm =3D aslr_tool__process_comm; + aslr->tool.tool.fork =3D aslr_tool__process_fork; + aslr->tool.tool.exit =3D aslr_tool__process_exit; + /* namesspaces, cgroup, lost, lost_sample, aux, */ + /* itrace_start, aux_output_hw_id, context_switch, throttle, unthrottle */ + /* - no virtual addresses. */ + aslr->tool.tool.ksymbol =3D aslr_tool__process_ksymbol; + /* bpf - no virtual address. */ + aslr->tool.tool.text_poke =3D aslr_tool__process_text_poke; + aslr->tool.tool.attr =3D aslr_tool__process_attr; + /* event_update, tracing_data, finished_round, build_id, id_index, */ + /* auxtrace_info, auxtrace_error, time_conv, thread_map, cpu_map, */ + /* stat_config, stat, feature, finished_init, bpf_metadata, compressed, */ + /* auxtrace - no virtual addresses. */ + aslr->tool.tool.auxtrace =3D aslr_tool__process_auxtrace; + aslr->tool.tool.auxtrace_info =3D aslr_tool__process_auxtrace_info; + aslr->tool.tool.auxtrace_error =3D aslr_tool__process_auxtrace_error; +} + +struct perf_tool *aslr_tool__new(struct perf_tool *delegate) +{ + struct aslr_tool *aslr =3D zalloc(sizeof(*aslr)); + + if (!aslr) + return NULL; + + aslr_tool__init(aslr, delegate); + return &aslr->tool.tool; +} + +void aslr_tool__delete(struct perf_tool *tool) +{ + struct delegate_tool *del_tool; + struct aslr_tool *aslr; + struct hashmap_entry *cur; + size_t bkt; + + if (!tool) + return; + + del_tool =3D container_of(tool, struct delegate_tool, tool); + aslr =3D container_of(del_tool, struct aslr_tool, tool); + + hashmap__for_each_entry(&aslr->remap_addresses, cur, bkt) { + struct remap_addresses_key *key =3D (struct remap_addresses_key *)cur->p= key; + + if (key) + dso__put(key->dso); + zfree(&cur->pkey); + zfree(&cur->pvalue); + } + hashmap__for_each_entry(&aslr->top_addresses, cur, bkt) { + zfree(&cur->pkey); + zfree(&cur->pvalue); + } + + hashmap__clear(&aslr->remap_addresses); + hashmap__clear(&aslr->top_addresses); + machines__destroy_kernel_maps(&aslr->machines); + machines__exit(&aslr->machines); + free(aslr); +} diff --git a/tools/perf/util/aslr.h b/tools/perf/util/aslr.h new file mode 100644 index 000000000000..a9b90bf29540 --- /dev/null +++ b/tools/perf/util/aslr.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef __PERF_ASLR_H +#define __PERF_ASLR_H + +#include + +#define ASLR_SUPPORTED_SAMPLE_TYPE ( \ + PERF_SAMPLE_IDENTIFIER | \ + PERF_SAMPLE_IP | \ + PERF_SAMPLE_TID | \ + PERF_SAMPLE_TIME | \ + PERF_SAMPLE_ADDR | \ + PERF_SAMPLE_ID | \ + PERF_SAMPLE_STREAM_ID | \ + PERF_SAMPLE_CPU | \ + PERF_SAMPLE_PERIOD | \ + PERF_SAMPLE_READ | \ + PERF_SAMPLE_CALLCHAIN | \ + PERF_SAMPLE_RAW | \ + PERF_SAMPLE_BRANCH_STACK | \ + PERF_SAMPLE_STACK_USER | \ + PERF_SAMPLE_WEIGHT_TYPE | \ + PERF_SAMPLE_DATA_SRC | \ + PERF_SAMPLE_TRANSACTION | \ + PERF_SAMPLE_PHYS_ADDR | \ + PERF_SAMPLE_CGROUP | \ + PERF_SAMPLE_DATA_PAGE_SIZE | \ + PERF_SAMPLE_CODE_PAGE_SIZE | \ + PERF_SAMPLE_AUX) + +struct perf_tool; +struct evsel; + +struct perf_tool *aslr_tool__new(struct perf_tool *delegate); +void aslr_tool__delete(struct perf_tool *aslr); + +#endif /* __PERF_ASLR_H */ --=20 2.54.0.631.ge1b05301d1-goog From nobody Mon May 25 03:33:06 2026 Received: from mail-dl1-f74.google.com (mail-dl1-f74.google.com [74.125.82.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 413003E00A2 for ; Tue, 19 May 2026 08:08:34 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=74.125.82.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779178116; cv=none; b=DQQVtgVlSU4PMCESicouism82VNzovuERwHYXO7hcRkJBwos/8wvs+0dG++zS7the+V+Srm0Tx+SbwMfkb8rsipGbQTFQhfHtJFytaMMUMmE84C2ytSeOUOY9sYdi3AazMik4HN9Wrpu9TGIfKtmu1ojSJ0cqoHUzPjCYKlImrY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779178116; c=relaxed/simple; bh=61nrk/GJ5sxd9VvTrzc1upScwhp45oKuFWfqmbV0FQA=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=LfFv0/5VZrmjdlgC8Jut41jKXnGcXxMrzc7zSMc6GBqsik4uCvWas1xPLClZZABend6Zu50zjvu1zApqhuJoMmqO8j7k1Wz4KVRfHZIfWTDDTvAZ0qmgffwHhaUbxnyav0JBqMS0YPQ8C3VZw5sfp8S1AaI8j61GqPksm6Omwok= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=YtmewVjp; arc=none smtp.client-ip=74.125.82.74 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.b="YtmewVjp" Received: by mail-dl1-f74.google.com with SMTP id a92af1059eb24-134cf343c58so6371131c88.1 for ; Tue, 19 May 2026 01:08:34 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20251104; t=1779178113; x=1779782913; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=XKHew9UrvbQMLagkmoEpaHtjeG3J0SZwwR9NyEROc7k=; b=YtmewVjpSXGB1soxD/Yu5bSqkBGyuG+ganfqXChyXRvBHkfIoaZUxTGbSFqKU6be9+ u/L0K0ouUIj71LtQg+tDyHo7wB5MI7/kjPZcjdALOnNOf/e2E4GXb17zNzrBecT0mxf1 drOSh35f9NpKxZGzkfaRKP/b8PVQWJrKyGkQaXVw9QUNvCuG9j8iDT/+YVB2yl+Xmz+/ bhPYpYwzP/MRGE4sw6hVQdWeRWsXRGlNWwmzZlr4ZjW3Ne8b4iOhLxxpd4shj/oF1p0x geSKnRdGCIMoCf6nSZZGkm85IFaVD7/ncUi325StsEqtHkEs+MXzzByDehOuDiNorKKS Eolw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1779178113; x=1779782913; h=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; bh=XKHew9UrvbQMLagkmoEpaHtjeG3J0SZwwR9NyEROc7k=; b=ih1so7e3ru4HJoC4EXFOtBDDDFIWDYfQsXqydV5qaMzO7asxicAjSdeVNqM2UWxD+T nZUD4D+QDBtZnCYuoDQZ+DH3KpDp5s37s4SbWCy2qnFC6SeSinWFUZgakC3c8eDjLo2T wfrE0V76oj583rpc/oE4i3gW/F0D3fLufZpxGRLq92oIvc3f3vhBFVbSJaCa1zYcwk09 JbOr1tD97M2syT6c+5ymR9npy6gxKkafPXOdnC+nOrr1MNkw/ifIQGhIJwRd/AmjZUrJ V+dGScAQHSNCb4N2MFgySMTdxyGPj4PrIaWt7/Gt8pNL5ckxiKFq8Js0EVDkYabrJX18 oShw== X-Forwarded-Encrypted: i=1; AFNElJ9UcWYJvWqX6S+RbecYL8F36ZfKH8Fk2H1qOYxlql+eF0Or1P+/UvMdpljUXfHcEQgv5411O8JX5r4t17o=@vger.kernel.org X-Gm-Message-State: AOJu0YzPFZkCkh1rWaBlojkogIGrt8Q82uH5FBKbdexGwU843DApd4Yw mIyw2G4oUIMLA4tutb2nZW4iWz8IaXUtRmn/S5eQPOYUtD1X5UQJm5mnX6Ac4DlPt3y8Ynx84Za bUTjlbcEYCQ== X-Received: from dlbcj24.prod.google.com ([2002:a05:7022:6998:b0:12c:20df:7530]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7022:fa1:b0:134:7497:2153 with SMTP id a92af1059eb24-13504744813mr8113016c88.20.1779178113069; Tue, 19 May 2026 01:08:33 -0700 (PDT) Date: Tue, 19 May 2026 01:08:23 -0700 In-Reply-To: <20260519080824.3329601-1-irogers@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20260508082726.2795191-1-irogers@google.com> <20260519080824.3329601-1-irogers@google.com> X-Mailer: git-send-email 2.54.0.631.ge1b05301d1-goog Message-ID: <20260519080824.3329601-4-irogers@google.com> Subject: [PATCH v7 3/4] perf test: Add inject ASLR test From: Ian Rogers To: irogers@google.com, acme@kernel.org, james.clark@linaro.org, namhyung@kernel.org Cc: adrian.hunter@intel.com, gmx@google.com, jolsa@kernel.org, linux-kernel@vger.kernel.org, linux-perf-users@vger.kernel.org, mingo@redhat.com, peterz@infradead.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add a new shell test `inject_aslr.sh` to verify the `perf inject --aslr` feature. The test covers: - Basic address remapping for user space samples. - Pipe mode coverage for `perf record` piped into `perf inject --aslr`. - Callchain address remapping. - Consistency of `perf report` output before and after injection. - Pipe mode report consistency. - Dropping of samples that leak ASLR info (physical addresses). - Kernel address remapping (utilizing a dedicated kernel-intensive VFS dd workload to guarantee continuous timer interrupts sampling flow inside kernel privilege states). - Kernel report consistency with address normalization. The test suite is hardened with global 'set -o pipefail' assertions to catch pipeline failures, stream-consuming awk processors to handle SIGPIPE signals, and a dedicated pipe output scenario validating raw 'perf inject -o -' stdout streams. Assisted-by: Gemini-CLI:Google Gemini 3 Signed-off-by: Ian Rogers --- tools/perf/tests/shell/inject_aslr.sh | 458 ++++++++++++++++++++++++++ 1 file changed, 458 insertions(+) create mode 100755 tools/perf/tests/shell/inject_aslr.sh diff --git a/tools/perf/tests/shell/inject_aslr.sh b/tools/perf/tests/shell= /inject_aslr.sh new file mode 100755 index 000000000000..098bf1db1245 --- /dev/null +++ b/tools/perf/tests/shell/inject_aslr.sh @@ -0,0 +1,458 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 +# perf inject --aslr test + +set -e +set -o pipefail + +shelldir=3D$(dirname "$0") +# shellcheck source=3Dlib/perf_has_symbol.sh +. "${shelldir}"/lib/perf_has_symbol.sh + +sym=3D"noploop" + +skip_test_missing_symbol ${sym} + +# Create global temp directory +temp_dir=3D$(mktemp -d /tmp/perf-test-aslr.XXXXXXXXXX) + +prog=3D"perf test -w noploop" +[ "$(uname -m)" =3D "s390x" ] && prog=3D"$prog 3" +err=3D0 +kprog=3D"dd if=3D/dev/zero of=3D/dev/null bs=3D1M count=3D500" + +cleanup() { + # Check if temp_dir is set and looks sane before removing + if [[ "${temp_dir}" =3D~ ^/tmp/perf-test-aslr\. ]]; then + rm -rf "${temp_dir}" + fi +} + +trap_cleanup() { + cleanup + exit 1 +} + +trap cleanup EXIT +trap trap_cleanup TERM INT + +get_noploop_addr() { + local file=3D$1 + perf script -i "$file" | awk ' + BEGIN { found=3D0 } + { + for (i=3D1; i<=3DNF; i++) { + if ($i ~ /noploop\+/) { + if (!found) { + print $(i-1) + found=3D1 + } + } + } + }' +} + +test_basic_aslr() { + echo "Test basic ASLR remapping" + local data + data=3D$(mktemp "${temp_dir}/perf.data.basic.XXXXXX") + local data2 + data2=3D$(mktemp "${temp_dir}/perf.data2.basic.XXXXXX") + + perf record -e task-clock:u -o "${data}" ${prog} + perf inject -v --aslr -i "${data}" -o "${data2}" + + orig_addr=3D$(get_noploop_addr "${data}") + new_addr=3D$(get_noploop_addr "${data2}") + + echo "Basic ASLR: orig_addr=3D$orig_addr, new_addr=3D$new_addr" + + if [ -z "$orig_addr" ]; then + echo "Basic ASLR test [Failed - no noploop samples in original file]" + err=3D1 + elif [ -z "$new_addr" ]; then + echo "Basic ASLR test [Failed - could not find remapped address]" + err=3D1 + elif [ "$orig_addr" =3D "$new_addr" ]; then + echo "Basic ASLR test [Failed - addresses are not remapped]" + err=3D1 + else + echo "Basic ASLR test [Success]" + fi +} + +test_pipe_aslr() { + echo "Test pipe mode ASLR remapping" + local data + data=3D$(mktemp "${temp_dir}/perf.data.pipe.XXXXXX") + local data2 + data2=3D$(mktemp "${temp_dir}/perf.data2.pipe.XXXXXX") + + # Use tee to save the original pipe data for comparison + perf record -e task-clock:u -o - ${prog} | tee "${data}" | perf inject -= -aslr -o "${data2}" + + orig_addr=3D$(get_noploop_addr "${data}") + new_addr=3D$(get_noploop_addr "${data2}") + + echo "Pipe ASLR: orig_addr=3D$orig_addr, new_addr=3D$new_addr" + + if [ -z "$orig_addr" ]; then + echo "Pipe ASLR test [Failed - no noploop samples in original file]" + err=3D1 + elif [ -z "$new_addr" ]; then + echo "Pipe ASLR test [Failed - could not find remapped address]" + err=3D1 + elif [ "$orig_addr" =3D "$new_addr" ]; then + echo "Pipe ASLR test [Failed - addresses are not remapped]" + err=3D1 + else + echo "Pipe ASLR test [Success]" + fi +} + +test_callchain_aslr() { + echo "Test Callchain ASLR remapping" + local data + data=3D$(mktemp "${temp_dir}/perf.data.callchain.XXXXXX") + local data2 + data2=3D$(mktemp "${temp_dir}/perf.data2.callchain.XXXXXX") + + perf record -g -e task-clock:u -o "${data}" ${prog} + perf inject --aslr -i "${data}" -o "${data2}" + + orig_addr=3D$(get_noploop_addr "${data}") + new_addr=3D$(get_noploop_addr "${data2}") + + echo "Callchain ASLR: orig_addr=3D$orig_addr, new_addr=3D$new_addr" + + if [ -z "$orig_addr" ]; then + echo "Callchain ASLR test [Failed - no noploop samples in original fil= e]" + err=3D1 + elif [ -z "$new_addr" ]; then + echo "Callchain ASLR test [Failed - could not find remapped address]" + err=3D1 + elif [ "$orig_addr" =3D "$new_addr" ]; then + echo "Callchain ASLR test [Failed - addresses are not remapped]" + err=3D1 + else + # Extract callchain addresses (indented lines starting with hex addres= ses) + orig_callchain=3D$(perf script -i "${data}" | awk '/^[[:space:]]+[0-9a= -f]+/ {print $1}') + new_callchain=3D$(perf script -i "${data2}" | awk '/^[[:space:]]+[0-9a= -f]+/ {print $1}') + + if [ -z "$orig_callchain" ]; then + echo "Callchain ASLR test [Failed - no callchain samples in original= file]" + err=3D1 + elif [ -z "$new_callchain" ]; then + echo "Callchain ASLR test [Failed - callchain data was dropped]" + err=3D1 + elif [ "$orig_callchain" =3D "$new_callchain" ]; then + echo "Callchain ASLR test [Failed - callchain addresses were not rem= apped]" + err=3D1 + else + echo "Callchain ASLR test [Success]" + fi + fi +} + +test_report_aslr() { + echo "Test perf report consistency" + local data + data=3D$(mktemp "${temp_dir}/perf.data.report.XXXXXX") + local data2 + data2=3D$(mktemp "${temp_dir}/perf.data2.report.XXXXXX") + local data_clean + data_clean=3D$(mktemp "${temp_dir}/perf.data.clean.XXXXXX") + + perf record -e task-clock:u -o "${data}" ${prog} + # Use -b to inject build-ids and force ordered events processing in both + perf inject -b -i "${data}" -o "${data_clean}" + perf inject -v -b --aslr -i "${data}" -o "${data2}" + + local report1=3D"${temp_dir}/report1" + local report2=3D"${temp_dir}/report2" + local report1_clean=3D"${temp_dir}/report1.clean" + local report2_clean=3D"${temp_dir}/report2.clean" + local diff_file=3D"${temp_dir}/diff" + + perf report -i "${data_clean}" --stdio > "${report1}" + perf report -i "${data2}" --stdio > "${report2}" + + # Strip headers and compare lines with percentages + grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true + grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true + + diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true + + if [ ! -s "${report1_clean}" ]; then + echo "Report ASLR test [Failed - no samples captured]" + err=3D1 + elif [ -s "${diff_file}" ]; then + echo "Report ASLR test [Failed - reports differ]" + echo "Showing first 20 lines of diff:" + head -n 20 "${diff_file}" + err=3D1 + else + echo "Report ASLR test [Success]" + fi +} + +test_pipe_report_aslr() { + echo "Test pipe mode perf report consistency" + local data + data=3D$(mktemp "${temp_dir}/perf.data.pipe_report.XXXXXX") + local data2 + data2=3D$(mktemp "${temp_dir}/perf.data2.pipe_report.XXXXXX") + local data_clean + data_clean=3D$(mktemp "${temp_dir}/perf.data.clean.XXXXXX") + + # Use tee to save the original pipe data, then process it with inject -b + perf record -e task-clock:u -o - ${prog} | \ + tee "${data}" | \ + perf inject -b --aslr -o "${data2}" + perf inject -b -i "${data}" -o "${data_clean}" + + local report1=3D"${temp_dir}/report1" + local report2=3D"${temp_dir}/report2" + local report1_clean=3D"${temp_dir}/report1.clean" + local report2_clean=3D"${temp_dir}/report2.clean" + local diff_file=3D"${temp_dir}/diff" + + perf report -i "${data_clean}" --stdio > "${report1}" + perf report -i "${data2}" --stdio > "${report2}" + + # Strip headers and compare lines with percentages + grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true + grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true + + diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true + + if [ ! -s "${report1_clean}" ]; then + echo "Pipe Report ASLR test [Failed - no samples captured]" + err=3D1 + elif [ -s "${diff_file}" ]; then + echo "Pipe Report ASLR test [Failed - reports differ]" + echo "Showing first 20 lines of diff:" + head -n 20 "${diff_file}" + err=3D1 + else + echo "Pipe Report ASLR test [Success]" + fi +} + +test_pipe_out_report_aslr() { + echo "Test pipe output mode perf report consistency" + local data + data=3D$(mktemp "${temp_dir}/perf.data.pipe_out_report.XXXXXX") + local data_clean + data_clean=3D$(mktemp "${temp_dir}/perf.data.clean.XXXXXX") + + perf record -e task-clock:u -o "${data}" ${prog} + perf inject -b -i "${data}" -o "${data_clean}" + + local report1=3D"${temp_dir}/report1" + local report2=3D"${temp_dir}/report2" + local report1_clean=3D"${temp_dir}/report1.clean" + local report2_clean=3D"${temp_dir}/report2.clean" + local diff_file=3D"${temp_dir}/diff" + + perf report -i "${data_clean}" --stdio > "${report1}" + perf inject -b --aslr -i "${data}" -o - | perf report -i - --stdio > "${= report2}" + + # Strip headers and compare lines with percentages + grep '%' "${report1}" | grep -v '^#' | sort > "${report1_clean}" || true + grep '%' "${report2}" | grep -v '^#' | sort > "${report2_clean}" || true + + diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true + + if [ ! -s "${report1_clean}" ]; then + echo "Pipe Output Report ASLR test [Failed - no samples captured]" + err=3D1 + elif [ -s "${diff_file}" ]; then + echo "Pipe Output Report ASLR test [Failed - reports differ]" + echo "Showing first 20 lines of diff:" + head -n 20 "${diff_file}" + err=3D1 + else + echo "Pipe Output Report ASLR test [Success]" + fi +} + +test_dropped_samples() { + echo "Test dropped samples (phys-data)" + local data + data=3D$(mktemp "${temp_dir}/perf.data.dropped.XXXXXX") + local data2 + data2=3D$(mktemp "${temp_dir}/perf.data2.dropped.XXXXXX") + + # Check if --phys-data is supported by recording a short run + if ! perf record -e task-clock:u --phys-data -o "${data}" -- sleep 0.1 >= /dev/null 2>&1; then + echo "Skipping dropped samples test as --phys-data is not supported" + return + fi + + perf record -e task-clock:u --phys-data -o "${data}" ${prog} + perf inject --aslr -i "${data}" -o "${data2}" + + # Verify that the original file actually contained samples! + orig_samples=3D$(perf script -i "${data}" | wc -l) + if [ "$orig_samples" -eq 0 ]; then + echo "Dropped samples test [Failed - no samples in original file]" + err=3D1 + else + # Verify that samples are dropped. + samples_count=3D$(perf script -i "${data2}" | wc -l) + + if [ "$samples_count" -gt 0 ]; then + echo "Dropped samples test [Failed - samples were not dropped]" + err=3D1 + else + echo "Dropped samples test [Success]" + fi + fi +} + +test_kernel_aslr() { + echo "Test kernel ASLR remapping" + local kdata + kdata=3D$(mktemp "${temp_dir}/perf.data.kernel.XXXXXX") + local kdata2 + kdata2=3D$(mktemp "${temp_dir}/perf.data2.kernel.XXXXXX") + local log_file + log_file=3D$(mktemp "${temp_dir}/kernel_record.log.XXXXXX") + + # Try to record kernel samples + if ! perf record -e task-clock:k -o "${kdata}" ${kprog} > "${log_file}" = 2>&1; then + echo "Skipping kernel ASLR test as recording failed (maybe no permissi= ons)" + return + fi + + # Check for warning about kernel map restriction + if grep -q "Couldn't record kernel reference relocation symbol" "${log_f= ile}"; then + echo "Skipping kernel ASLR test as kernel map could not be recorded (p= ermissions restricted)" + return + fi + + perf inject -v --aslr -i "${kdata}" -o "${kdata2}" + + # Check if kernel addresses are remapped. + # Find the field that ends with :k: (the event name) and take the next f= ield! + orig_addr=3D$(perf script -i "${kdata}" | awk ' + BEGIN { found=3D0 } + { + for (i=3D1; i "${log_file}" = 2>&1; then + echo "Skipping kernel report test as recording failed (maybe no permis= sions)" + return + fi + + # Check for warning about kernel map restriction + if grep -q "Couldn't record kernel reference relocation symbol" "${log_f= ile}"; then + echo "Skipping kernel report test as kernel map could not be recorded = (permissions restricted)" + return + fi + + # Use -b to inject build-ids and force ordered events processing in both + perf inject -b -i "${kdata}" -o "${data_clean}" + perf inject -v -b --aslr -i "${kdata}" -o "${kdata2}" + + local report1=3D"${temp_dir}/report_kernel1" + local report2=3D"${temp_dir}/report_kernel2" + local report1_clean=3D"${temp_dir}/report_kernel1.clean" + local report2_clean=3D"${temp_dir}/report_kernel2.clean" + + perf report -i "${data_clean}" --stdio > "${report1}" + perf report -i "${kdata2}" --stdio > "${report2}" + + # Strip headers and compare lines with percentages + grep '%' "${report1}" | grep -v '^#' > "${report1_clean}" || true + grep '%' "${report2}" | grep -v '^#' > "${report2_clean}" || true + + # Normalize kernel DSOs and addresses in clean reports + # This allows kernel modules to be either a module or kernel.kallsyms + local report1_norm=3D"${temp_dir}/report_kernel1.norm" + local report2_norm=3D"${temp_dir}/report_kernel2.norm" + local diff_file=3D"${temp_dir}/diff_kernel" + + grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report1_clean}" | \ + awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0)= ; print}' | \ + sort > "${report1_norm}" || true + grep -v -E '0x[0-9a-f]{8,}|0000000000000000' "${report2_clean}" | \ + awk '{gsub(/\[[a-zA-Z0-9_.-]{2,}\](\.[a-zA-Z0-9_]+)?/, "[kernel]", $0)= ; print}' | \ + sort > "${report2_norm}" || true + + diff -u -w "${report1_norm}" "${report2_norm}" > "${diff_file}" || true + + if [ ! -s "${report1_norm}" ]; then + echo "Kernel Report ASLR test [Failed - no samples captured]" + err=3D1 + elif [ -s "${diff_file}" ]; then + echo "Kernel Report ASLR test [Failed - reports differ]" + echo "Showing first 20 lines of diff:" + head -n 20 "${diff_file}" + err=3D1 + else + echo "Kernel Report ASLR test [Success]" + fi +} + +test_basic_aslr +test_pipe_aslr +test_callchain_aslr +test_report_aslr +test_pipe_report_aslr +test_pipe_out_report_aslr +test_dropped_samples +test_kernel_aslr +test_kernel_report_aslr + +cleanup +exit $err --=20 2.54.0.631.ge1b05301d1-goog From nobody Mon May 25 03:33:06 2026 Received: from mail-dy1-f202.google.com (mail-dy1-f202.google.com [74.125.82.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2A2663E0097 for ; Tue, 19 May 2026 08:08:36 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=74.125.82.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779178118; cv=none; b=DykSxF0khScaIl9scFKWuKzwMXOuNcfT7Mb1W0AncwbE5/UyoBSHLpR16uj9IvQBSHFpEychzqikSwHYwHKXDsG0osMt8sg/wpGAvb/YMNtk8totI7r5bzPnYyLxy1WYjHgyXQmrrUOhNIenpUmZXmq2XhYFv9Fnm8o/5pWk/Is= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779178118; c=relaxed/simple; bh=iuBO1W5K99TPH2DMEHxqdI89QCvm04PL4wcFZcMZXCk=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=W0FHOrRZOI3iZeG67bvWxAY4xFrrVcuSmPLNbgrnILXiSfuCSjGrSm8pWnsV2fBWhu+JtV7KJl+I2CABipOEhEVtZBEYM7iDi1+2IKntWjsZKO45F5AX/7TosSlBLM5Rnwh0ZiNAulKr8VBQTqL8GQXJo5BakoRF0FEvse5dEPI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=j0Wv3fiK; arc=none smtp.client-ip=74.125.82.202 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.b="j0Wv3fiK" Received: by mail-dy1-f202.google.com with SMTP id 5a478bee46e88-2ef37c3f773so3403182eec.1 for ; Tue, 19 May 2026 01:08:36 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20251104; t=1779178115; x=1779782915; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=R42dg19QrNU0bBzdrKMwJQ0jZEa1UyOaXYgiIqa/eiQ=; b=j0Wv3fiKwiFbb//BaI61m2LBOE+7rv9V37cUDYfmh0A0u6Uol51MWzs93IVzenYiZx /kpOIhGtAxqLfQqAADfz5kBwrfzBPbAjsy7UUUPLrs932n3mTKiqyS5uqOh4B8z+HZA8 ZxHqwUWmScGo0YQCO88Jt+FFmP8CSDqJcg8UXHOdV6ak1vdJugpQ0z3jduIY6SsYfRFa N1jFZsDLpPQu6aWKfGZ02gUtRxHJvB12Yj47oAVTgBNIa9kETYzYskPN4/KN7DTSh3jh 3PjPoSObLptbPOhmtiZkmyE8ni6tzK86QZV/5feHAXi0R83en83J3uDj2BIDbA0eEt0q q37Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1779178115; x=1779782915; h=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; bh=R42dg19QrNU0bBzdrKMwJQ0jZEa1UyOaXYgiIqa/eiQ=; b=QuhaWJY5EW88u32loUNc+DsDHOeRSnxuyKD94NiguxygGQIpkOTKkQ9fnIjN2Nk9ju WgWsqYcWC2rAd15A5Ld/CHmy7Oqi5VD9lB8r87rEVGHIhQjHc/CNGTtzmTM3YoLIHNNl n8MekF692CxsOjTX0eLH0siJWaxHtm2WeMHrIfADt0aPX0NRYb5LxN05EFZRkUVjVju6 tf+ipfKTvIDS5qOzk4lQLUiIJASCqmYNArHeN4iVediEPIvANJfg1OX9lB8QoBV4qbKO ND1D84gznPeDMEOtea3gwzDg6WiShckJwhdE9LTAbHtY1DrDXvLMcBctE4XRfAiJFUi1 6ALA== X-Forwarded-Encrypted: i=1; AFNElJ9MkoUahjbPhkx0ZMbeKEP7tN0dVJrV0JoJJ/3Qj1As7q8mz6uP5ePWRxq+8yqe8dOsymWe/Ha98M4KdFE=@vger.kernel.org X-Gm-Message-State: AOJu0YzN6tXRw/mBIMBSh1rO+5LDq8GWPDD0MfW4ecXVJanDI/DimMQJ a1NvE4WTNW9BexSnYBHrwFu4k508P9bccfLhZx/8KdCGR1N6r89Cn2zVQEo5MagKw9kAWaGvUjV 8XmpA4uFV0g== X-Received: from dycok12.prod.google.com ([2002:a05:7301:db0c:b0:302:5b3d:5b37]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7300:a907:b0:2c5:220c:5670 with SMTP id 5a478bee46e88-3039818eec3mr7313767eec.2.1779178115053; Tue, 19 May 2026 01:08:35 -0700 (PDT) Date: Tue, 19 May 2026 01:08:24 -0700 In-Reply-To: <20260519080824.3329601-1-irogers@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20260508082726.2795191-1-irogers@google.com> <20260519080824.3329601-1-irogers@google.com> X-Mailer: git-send-email 2.54.0.631.ge1b05301d1-goog Message-ID: <20260519080824.3329601-5-irogers@google.com> Subject: [PATCH v7 4/4] perf aslr: Strip sample registers From: Ian Rogers To: irogers@google.com, acme@kernel.org, james.clark@linaro.org, namhyung@kernel.org Cc: adrian.hunter@intel.com, gmx@google.com, jolsa@kernel.org, linux-kernel@vger.kernel.org, linux-perf-users@vger.kernel.org, mingo@redhat.com, peterz@infradead.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" When the ASLR tracking tool encounters sample events containing user or interrupt register dumps (PERF_SAMPLE_REGS_USER / PERF_SAMPLE_REGS_INTR), it previously dropped the entire sample event conservatively to prevent absolute virtual memory pointers leakage embedded inside raw register frames. If a trace session was recorded with register collection flags enabled, this resulted in 100% sample drop rates, and this happened by default for ARM64. Refactor the ASLR tool to strip out only the register dump payload words from PERF_RECORD_SAMPLE event streams, automatically shrinking the output sample header size. Incoming PERF_RECORD_ATTR events are scrubbed up front to clear the register dump bit selection flags and masks, and output sample ABI words are safely overwritten to PERF_SAMPLE_REGS_ABI_NONE. This keeps downstream evsel parsers perfectly synchronized while retaining full, comprehensive sample profiles completely clear of secret register data frames. Verification parity is established inside inject_aslr.sh via a dedicated sorted report diff comparison validation case proving zero starvation and absolute secrecy. Assisted-by: Gemini-CLI:Google Gemini 3 Signed-off-by: Ian Rogers --- tools/perf/builtin-inject.c | 22 +++ tools/perf/tests/shell/inject_aslr.sh | 55 ++++++++ tools/perf/util/aslr.c | 185 ++++++++++++++++---------- tools/perf/util/aslr.h | 1 + 4 files changed, 195 insertions(+), 68 deletions(-) diff --git a/tools/perf/builtin-inject.c b/tools/perf/builtin-inject.c index 8fe924e730a1..4bafccf7dae4 100644 --- a/tools/perf/builtin-inject.c +++ b/tools/perf/builtin-inject.c @@ -2519,6 +2519,17 @@ static int __cmd_inject(struct perf_inject *inject) } } =20 + if (inject->aslr) { + struct evsel *evsel; + + evlist__for_each_entry(session->evlist, evsel) { + evsel__reset_sample_bit(evsel, REGS_USER); + evsel__reset_sample_bit(evsel, REGS_INTR); + evsel->core.attr.sample_regs_user =3D 0; + evsel->core.attr.sample_regs_intr =3D 0; + } + } + =20 =20 session->header.data_offset =3D output_data_offset; @@ -2783,7 +2794,18 @@ int cmd_inject(int argc, const char **argv) struct evsel *evsel; =20 evlist__for_each_entry(inject.session->evlist, evsel) { + ret =3D aslr_tool__cache_orig_attrs(tool, evsel); + if (ret) { + pr_err("Failed to cache original attributes: %d\n", ret); + goto out_delete; + } + + /* Strip the registers and unknown flags natively inside memory! */ evsel->core.attr.sample_type &=3D ASLR_SUPPORTED_SAMPLE_TYPE; + evsel__reset_sample_bit(evsel, REGS_USER); + evsel__reset_sample_bit(evsel, REGS_INTR); + evsel->core.attr.sample_regs_user =3D 0; + evsel->core.attr.sample_regs_intr =3D 0; =20 if (evsel->core.attr.type =3D=3D PERF_TYPE_BREAKPOINT) evsel->core.attr.bp_addr =3D 0; diff --git a/tools/perf/tests/shell/inject_aslr.sh b/tools/perf/tests/shell= /inject_aslr.sh index 098bf1db1245..cd60e1b7d840 100755 --- a/tools/perf/tests/shell/inject_aslr.sh +++ b/tools/perf/tests/shell/inject_aslr.sh @@ -444,6 +444,60 @@ test_kernel_report_aslr() { fi } =20 +test_regs_stripping() { + echo "Test user register stripping" + local rdata=3D"${temp_dir}/perf.data.regs" + local rdata2=3D"${temp_dir}/perf.data.regs.injected" + local rdata_clean=3D"${temp_dir}/perf.data.regs.clean" + + if ! perf record --user-regs -o "${rdata}" ${prog} > /dev/null 2>&1; then + echo "Skipping user registers test as recording failed (unsupported fl= ag/platform)" + return + fi + + perf inject -b -i "${rdata}" -o "${rdata_clean}" + perf inject -v -b --aslr -i "${rdata}" -o "${rdata2}" + + local report1=3D"${temp_dir}/report_regs1" + local report2=3D"${temp_dir}/report_regs2" + local report1_clean=3D"${temp_dir}/report_regs1.clean" + local report2_clean=3D"${temp_dir}/report_regs2.clean" + local diff_file=3D"${temp_dir}/diff_regs" + + perf report -i "${rdata_clean}" --stdio > "${report1}" 2>/dev/null || tr= ue + perf report -i "${rdata2}" --stdio > "${report2}" 2>/dev/null || true + + grep '%' "${report1}" | grep -v '^#' | \ + grep -v -E '0x[0-9a-f]{8,}|0000000000000000' | \ + sort > "${report1_clean}" || true + grep '%' "${report2}" | grep -v '^#' | \ + grep -v -E '0x[0-9a-f]{8,}|0000000000000000' | \ + sort > "${report2_clean}" || true + + diff -u -w "${report1_clean}" "${report2_clean}" > "${diff_file}" || true + + if [ ! -s "${report1_clean}" ]; then + echo "User registers stripping test [Failed - profile trace starved/em= pty]" + err=3D1 + return + elif [ -s "${diff_file}" ]; then + echo "User registers stripping test [Failed - report parsing differs]" + echo "Showing first 20 lines of diff:" + head -n 20 "${diff_file}" + err=3D1 + return + fi + + local script_dump=3D"${temp_dir}/script_regs_dump" + perf script -D -i "${rdata2}" > "${script_dump}" 2>/dev/null || true + if grep -q "PERF_SAMPLE_REGS_USER" "${script_dump}"; then + echo "User registers stripping test [Failed - register dumps still pre= sent]" + err=3D1 + else + echo "User registers stripping test [Success]" + fi +} + test_basic_aslr test_pipe_aslr test_callchain_aslr @@ -453,6 +507,7 @@ test_pipe_out_report_aslr test_dropped_samples test_kernel_aslr test_kernel_report_aslr +test_regs_stripping =20 cleanup exit $err diff --git a/tools/perf/util/aslr.c b/tools/perf/util/aslr.c index d0b1b33377fd..ef6ba6fa5ff4 100644 --- a/tools/perf/util/aslr.c +++ b/tools/perf/util/aslr.c @@ -5,6 +5,7 @@ #include "debug.h" #include "event.h" #include "evsel.h" +#include "evlist.h" #include "machine.h" #include "map.h" #include "thread.h" @@ -16,33 +17,10 @@ #include /* page_size */ #include #include +#include #include #include =20 -#define ASLR_SUPPORTED_SAMPLE_TYPE ( \ - PERF_SAMPLE_IDENTIFIER | \ - PERF_SAMPLE_IP | \ - PERF_SAMPLE_TID | \ - PERF_SAMPLE_TIME | \ - PERF_SAMPLE_ADDR | \ - PERF_SAMPLE_ID | \ - PERF_SAMPLE_STREAM_ID | \ - PERF_SAMPLE_CPU | \ - PERF_SAMPLE_PERIOD | \ - PERF_SAMPLE_READ | \ - PERF_SAMPLE_CALLCHAIN | \ - PERF_SAMPLE_RAW | \ - PERF_SAMPLE_BRANCH_STACK | \ - PERF_SAMPLE_STACK_USER | \ - PERF_SAMPLE_WEIGHT_TYPE | \ - PERF_SAMPLE_DATA_SRC | \ - PERF_SAMPLE_TRANSACTION | \ - PERF_SAMPLE_PHYS_ADDR | \ - PERF_SAMPLE_CGROUP | \ - PERF_SAMPLE_DATA_PAGE_SIZE | \ - PERF_SAMPLE_CODE_PAGE_SIZE | \ - PERF_SAMPLE_AUX) - /** * struct remap_addresses_key - Key for mapping original addresses to rema= pped ones. * @dso: Pointer to the DSO (Dynamic Shared Object) associated with the ma= pping. @@ -67,6 +45,22 @@ struct aslr_mapping { u64 remap_start; }; =20 +struct aslr_evsel_priv { + u64 orig_sample_type; + u64 orig_sample_regs_user; + u64 orig_sample_regs_intr; +}; + +static size_t evsel_hash(long key, void *ctx __maybe_unused) +{ + return (size_t)key; +} + +static bool evsel_equal(long key1, long key2, void *ctx __maybe_unused) +{ + return key1 =3D=3D key2; +} + struct aslr_tool { /** @tool: The tool implemented here and a pointer to a delegate to proce= ss the data. */ struct delegate_tool tool; @@ -78,6 +72,11 @@ struct aslr_tool { struct hashmap remap_addresses; /** @top_addresses: mapping from process to max remapped address. */ struct hashmap top_addresses; + /** + * @evsel_orig_attrs: mapping from evsel pointer to its original + * unstripped sample_type and registers bitmasks. + */ + struct hashmap evsel_orig_attrs; }; =20 static const pid_t kernel_pid =3D -1; @@ -167,9 +166,7 @@ static u64 aslr_tool__remap_address(struct aslr_tool *a= slr, key.machine =3D maps__machine(aslr_thread->maps); key.dso =3D map__dso(al.map); key.invariant =3D map__start(al.map) - map__pgoff(al.map); - key.pid =3D (effective_cpumode =3D=3D PERF_RECORD_MISC_KERNEL || - effective_cpumode =3D=3D PERF_RECORD_MISC_GUEST_KERNEL) ? - kernel_pid : aslr_thread->pid_; + key.pid =3D effective_cpumode =3D=3D PERF_RECORD_MISC_KERNEL ? kernel_pid= : aslr_thread->pid_; =20 if (hashmap__find(&aslr->remap_addresses, &key, &remapped_invariant_ptr))= { remap_addr =3D *remapped_invariant_ptr + map__pgoff(al.map) + @@ -563,12 +560,25 @@ static int aslr_tool__process_sample(const struct per= f_tool *tool, u64 addr; size_t i; size_t j; + struct aslr_evsel_priv *priv =3D NULL; + u64 orig_sample_type; + u64 orig_regs_user; + u64 orig_regs_intr; =20 del_tool =3D container_of(tool, struct delegate_tool, tool); aslr =3D container_of(del_tool, struct aslr_tool, tool); delegate =3D aslr->tool.delegate; ret =3D -EFAULT; sample_type =3D evsel->core.attr.sample_type; + orig_sample_type =3D sample_type; + orig_regs_user =3D evsel->core.attr.sample_regs_user; + orig_regs_intr =3D evsel->core.attr.sample_regs_intr; + + if (hashmap__find(&aslr->evsel_orig_attrs, evsel, &priv)) { + orig_sample_type =3D priv->orig_sample_type; + orig_regs_user =3D priv->orig_sample_regs_user; + orig_regs_intr =3D priv->orig_sample_regs_intr; + } max_i =3D (event->header.size - sizeof(struct perf_event_header)) / sizeo= f(__u64); max_j =3D (PERF_SAMPLE_MAX_SIZE - sizeof(struct perf_event_header)) / siz= eof(__u64); new_event =3D (union perf_event *)aslr->event_copy; @@ -615,25 +625,25 @@ static int aslr_tool__process_sample(const struct per= f_tool *tool, i++; \ } while (0) =20 - if (sample_type & PERF_SAMPLE_IDENTIFIER) + if (orig_sample_type & PERF_SAMPLE_IDENTIFIER) COPY_U64(); /* id */ - if (sample_type & PERF_SAMPLE_IP) + if (orig_sample_type & PERF_SAMPLE_IP) REMAP_U64(sample->ip); - if (sample_type & PERF_SAMPLE_TID) + if (orig_sample_type & PERF_SAMPLE_TID) COPY_U64(); /* pid, tid */ - if (sample_type & PERF_SAMPLE_TIME) + if (orig_sample_type & PERF_SAMPLE_TIME) COPY_U64(); /* time */ - if (sample_type & PERF_SAMPLE_ADDR) + if (orig_sample_type & PERF_SAMPLE_ADDR) REMAP_U64(sample->addr); - if (sample_type & PERF_SAMPLE_ID) + if (orig_sample_type & PERF_SAMPLE_ID) COPY_U64(); /* id */ - if (sample_type & PERF_SAMPLE_STREAM_ID) + if (orig_sample_type & PERF_SAMPLE_STREAM_ID) COPY_U64(); /* stream_id */ - if (sample_type & PERF_SAMPLE_CPU) + if (orig_sample_type & PERF_SAMPLE_CPU) COPY_U64(); /* cpu, res */ - if (sample_type & PERF_SAMPLE_PERIOD) + if (orig_sample_type & PERF_SAMPLE_PERIOD) COPY_U64(); /* period */ - if (sample_type & PERF_SAMPLE_READ) { + if (orig_sample_type & PERF_SAMPLE_READ) { if ((evsel->core.attr.read_format & PERF_FORMAT_GROUP) =3D=3D 0) { COPY_U64(); /* value */ if (evsel->core.attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) @@ -667,7 +677,7 @@ static int aslr_tool__process_sample(const struct perf_= tool *tool, } } } - if (sample_type & PERF_SAMPLE_CALLCHAIN) { + if (orig_sample_type & PERF_SAMPLE_CALLCHAIN) { u64 nr; =20 if (CHECK_BOUNDS(1, 1)) { @@ -733,7 +743,7 @@ static int aslr_tool__process_sample(const struct perf_= tool *tool, out_array[j++] =3D aslr_tool__remap_address(aslr, thread, cpumode, addr= ); } } - if (sample_type & PERF_SAMPLE_RAW) { + if (orig_sample_type & PERF_SAMPLE_RAW) { size_t bytes =3D sizeof(u32) + sample->raw_size; size_t u64_words =3D (bytes + 7) / 8; =20 @@ -752,7 +762,7 @@ static int aslr_tool__process_sample(const struct perf_= tool *tool, ret =3D 0; goto out_put; } - if (sample_type & PERF_SAMPLE_BRANCH_STACK) { + if (orig_sample_type & PERF_SAMPLE_BRANCH_STACK) { u64 nr; =20 if (CHECK_BOUNDS(1, 1)) { @@ -797,7 +807,7 @@ static int aslr_tool__process_sample(const struct perf_= tool *tool, goto out_put; } } - if (sample_type & PERF_SAMPLE_REGS_USER) { + if (orig_sample_type & PERF_SAMPLE_REGS_USER) { u64 abi; =20 if (CHECK_BOUNDS(1, 0)) { @@ -806,22 +816,16 @@ static int aslr_tool__process_sample(const struct per= f_tool *tool, } abi =3D in_array[i++]; if (abi !=3D PERF_SAMPLE_REGS_ABI_NONE) { - u64 nr =3D hweight64(evsel->core.attr.sample_regs_user); + u64 nr =3D hweight64(orig_regs_user); =20 - if (nr > max_i - i || nr > max_j - j) { + if (nr > max_i - i) { ret =3D -EFAULT; goto out_put; } - memcpy(&out_array[j], &in_array[i], nr * sizeof(u64)); i +=3D nr; - j +=3D nr; } - /* TODO: can this be less conservative? */ - pr_debug("Dropping regs user sample as possible ASLR leak\n"); - ret =3D 0; - goto out_put; } - if (sample_type & PERF_SAMPLE_STACK_USER) { + if (orig_sample_type & PERF_SAMPLE_STACK_USER) { u64 size; =20 if (CHECK_BOUNDS(1, 1)) { @@ -854,13 +858,13 @@ static int aslr_tool__process_sample(const struct per= f_tool *tool, ret =3D 0; goto out_put; } - if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) + if (orig_sample_type & PERF_SAMPLE_WEIGHT_TYPE) COPY_U64(); /* perf_sample_weight */ - if (sample_type & PERF_SAMPLE_DATA_SRC) + if (orig_sample_type & PERF_SAMPLE_DATA_SRC) COPY_U64(); /* data_src */ - if (sample_type & PERF_SAMPLE_TRANSACTION) + if (orig_sample_type & PERF_SAMPLE_TRANSACTION) COPY_U64(); /* transaction */ - if (sample_type & PERF_SAMPLE_REGS_INTR) { + if (orig_sample_type & PERF_SAMPLE_REGS_INTR) { u64 abi; =20 if (CHECK_BOUNDS(1, 0)) { @@ -869,36 +873,30 @@ static int aslr_tool__process_sample(const struct per= f_tool *tool, } abi =3D in_array[i++]; if (abi !=3D PERF_SAMPLE_REGS_ABI_NONE) { - u64 nr =3D hweight64(evsel->core.attr.sample_regs_intr); + u64 nr =3D hweight64(orig_regs_intr); =20 - if (nr > max_i - i || nr > max_j - j) { + if (nr > max_i - i) { ret =3D -EFAULT; goto out_put; } - memcpy(&out_array[j], &in_array[i], nr * sizeof(u64)); i +=3D nr; - j +=3D nr; } - /* TODO: can this be less conservative? */ - pr_debug("Dropping interrupt register sample as possible ASLR leak\n"); - ret =3D 0; - goto out_put; } - if (sample_type & PERF_SAMPLE_PHYS_ADDR) { + if (orig_sample_type & PERF_SAMPLE_PHYS_ADDR) { COPY_U64(); /* phys_addr */ /* TODO: can this be less conservative? */ pr_debug("Dropping physical address sample as possible ASLR leak\n"); ret =3D 0; goto out_put; } - if (sample_type & PERF_SAMPLE_CGROUP) + if (orig_sample_type & PERF_SAMPLE_CGROUP) COPY_U64(); /* cgroup */ - if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) + if (orig_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) COPY_U64(); /* data_page_size */ - if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) + if (orig_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) COPY_U64(); /* code_page_size */ =20 - if (sample_type & PERF_SAMPLE_AUX) { + if (orig_sample_type & PERF_SAMPLE_AUX) { u64 size; =20 if (CHECK_BOUNDS(1, 1)) { @@ -966,6 +964,7 @@ static int aslr_tool__process_attr(const struct perf_to= ol *tool, struct aslr_tool *aslr; struct perf_tool *delegate; union perf_event *new_event; + int err; =20 del_tool =3D container_of(tool, struct delegate_tool, tool); aslr =3D container_of(del_tool, struct aslr_tool, tool); @@ -976,9 +975,32 @@ static int aslr_tool__process_attr(const struct perf_t= ool *tool, if (new_event->attr.attr.type =3D=3D PERF_TYPE_BREAKPOINT) new_event->attr.attr.bp_addr =3D 0; /* Conservatively remove addresses.= */ =20 + if (new_event->attr.attr.sample_type & PERF_SAMPLE_REGS_USER) { + new_event->attr.attr.sample_type &=3D ~PERF_SAMPLE_REGS_USER; + new_event->attr.attr.sample_regs_user =3D 0; + } + if (new_event->attr.attr.sample_type & PERF_SAMPLE_REGS_INTR) { + new_event->attr.attr.sample_type &=3D ~PERF_SAMPLE_REGS_INTR; + new_event->attr.attr.sample_regs_intr =3D 0; + } + new_event->attr.attr.sample_type &=3D ASLR_SUPPORTED_SAMPLE_TYPE; =20 - return delegate->attr(delegate, new_event, pevlist); + err =3D delegate->attr(delegate, new_event, pevlist); + if (!err && pevlist && *pevlist) { + struct evsel *evsel =3D evlist__last(*pevlist); + struct aslr_evsel_priv *priv =3D zalloc(sizeof(*priv)); + + if (priv) { + priv->orig_sample_type =3D event->attr.attr.sample_type; + priv->orig_sample_regs_user =3D event->attr.attr.sample_regs_user; + priv->orig_sample_regs_intr =3D event->attr.attr.sample_regs_intr; + if (hashmap__add(&aslr->evsel_orig_attrs, evsel, priv) !=3D 0) + free(priv); + } + } + + return err; } =20 static int skipn(int fd, off_t n) @@ -1037,6 +1059,9 @@ static void aslr_tool__init(struct aslr_tool *aslr, s= truct perf_tool *delegate) hashmap__init(&aslr->top_addresses, top_addresses__hash, top_addresses__equal, /*ctx=3D*/NULL); + hashmap__init(&aslr->evsel_orig_attrs, + evsel_hash, evsel_equal, + /*ctx=3D*/NULL); =20 aslr->tool.tool.sample =3D aslr_tool__process_sample; /* read - reads a counter, okay to delegate. */ @@ -1097,10 +1122,34 @@ void aslr_tool__delete(struct perf_tool *tool) zfree(&cur->pkey); zfree(&cur->pvalue); } + hashmap__for_each_entry(&aslr->evsel_orig_attrs, cur, bkt) { + zfree(&cur->pvalue); + } =20 hashmap__clear(&aslr->remap_addresses); hashmap__clear(&aslr->top_addresses); + hashmap__clear(&aslr->evsel_orig_attrs); machines__destroy_kernel_maps(&aslr->machines); machines__exit(&aslr->machines); free(aslr); } + +int aslr_tool__cache_orig_attrs(struct perf_tool *tool, struct evsel *evse= l) +{ + struct delegate_tool *del_tool =3D container_of(tool, struct delegate_too= l, tool); + struct aslr_tool *aslr =3D container_of(del_tool, struct aslr_tool, tool); + struct aslr_evsel_priv *priv =3D zalloc(sizeof(*priv)); + + if (!priv) + return -ENOMEM; + + priv->orig_sample_type =3D evsel->core.attr.sample_type; + priv->orig_sample_regs_user =3D evsel->core.attr.sample_regs_user; + priv->orig_sample_regs_intr =3D evsel->core.attr.sample_regs_intr; + + if (hashmap__add(&aslr->evsel_orig_attrs, evsel, priv) !=3D 0) { + free(priv); + return -EEXIST; + } + return 0; +} diff --git a/tools/perf/util/aslr.h b/tools/perf/util/aslr.h index a9b90bf29540..e4cdb337a66f 100644 --- a/tools/perf/util/aslr.h +++ b/tools/perf/util/aslr.h @@ -33,5 +33,6 @@ struct evsel; =20 struct perf_tool *aslr_tool__new(struct perf_tool *delegate); void aslr_tool__delete(struct perf_tool *aslr); +int aslr_tool__cache_orig_attrs(struct perf_tool *tool, struct evsel *evse= l); =20 #endif /* __PERF_ASLR_H */ --=20 2.54.0.631.ge1b05301d1-goog