Skip to contentSkip to conversation

perf tools: Enhance namespace and chroot handling

PATCH New Namhyung Kim 2 participants 23 messages Nov 16 perf events

lore
Share & tools
lore

Namhyung Kim

author maintainer
#0 lore raw

v2 cover perf tools: Enhance namespace and chroot handling

Hello,

This series improves namespace and chroot handling when perf accesses files from /proc. It defers reading /proc until namespace info is actually needed, verifies thread liveness, matching boot IDs, and mount namespace inodes against PID/TID recycling, and avoids entering target mount namespaces for host-side files such as the build-id cache.

It's assisted by LLM.

v2 changes:

* Keep dso__filename_with_chroot() (guarded by nsinfo__check_proc()) instead of calling chroot() inside nsinfo__mountns_enter().
* Add a mutex lock to struct nsinfo and replace thread->nsinfo safely on exec/namespace events rather than mutating shared instances in place.
* Mark offline sessions explicitly, propagate exit on fork replacement and perf_event__exit_del_thread(), and guard sub-thread fallback in thread__e_machine_endian().
* Gate mount namespace entry for debuginfo/binary probing callers, include distro debuginfo types, and handle build-id lookups in symbol-minimal's dso__load_sym().
* Add unit and shell tests for namespace, nsinfo, chroot, and boot ID handling.

v1: https://lore.kernel.org/r/[email protected]

Thanks,
Namhyung

Namhyung Kim (11):
perf tools: Add HEADER_BOOT_ID feature
perf tools: Add perf_env__is_same_boot()
perf tools: Add nsinfo__new_thread() to track tid perf tools: Add lock to struct nsinfo
perf tools: Defer /proc lookup until nsinfo is used perf tools: Verify thread status and mount namespace inode perf tools: Check thread liveness when accessing /proc perf tools: Export filename__read_build_id_ns() perf tools: Only enter mount namespace if necessary perf tools: Scope mount namespace entry in dso__load() perf tests: Add namespace, nsinfo, and boot ID tests

 .../Documentation/perf.data-file-format.txt   |    5 +
 tools/perf/builtin-inject.c                   |   15 +-
 tools/perf/builtin-trace.c                    |    2 +-
 tools/perf/tests/Build                        |    1 +
 tools/perf/tests/builtin-test.c               |    1 +
 tools/perf/tests/namespaces.c                 | 1035 +++++++++++++++++
 tools/perf/tests/shell/header.sh              |    9 +
 tools/perf/tests/tests.h                      |    1 +
 tools/perf/util/build-id.c                    |   14 +-
 tools/perf/util/capstone.c                    |    8 +-
 tools/perf/util/debuginfo.c                   |   19 +-
 tools/perf/util/disasm.c                      |    8 +-
 tools/perf/util/dso.c                         |   59 +-
 tools/perf/util/dso.h                         |   34 +
 tools/perf/util/dsos.c                        |   17 +-
 tools/perf/util/env.c                         |   69 ++
 tools/perf/util/env.h                         |    4 +
 tools/perf/util/event.c                       |    1 +
 tools/perf/util/header.c                      |   28 +
 tools/perf/util/header.h                      |    1 +
 tools/perf/util/jitdump.c                     |    2 +-
 tools/perf/util/machine.c                     |   16 +-
 tools/perf/util/map.c                         |    2 +-
 tools/perf/util/namespaces.c                  |  273 ++++-
 tools/perf/util/namespaces.h                  |   10 +
 tools/perf/util/session.c                     |    1 +
 tools/perf/util/symbol-minimal.c              |    4 +-
 tools/perf/util/symbol.c                      |   45 +-
 tools/perf/util/symbol.h                      |    3 +
 tools/perf/util/thread.c                      |   95 +-
 tools/perf/util/thread.h                      |   13 +-
 31 files changed, 1651 insertions(+), 144 deletions(-)
 create mode 100644 tools/perf/tests/namespaces.c
Signature · 1 line
2.56.0.611.g1030f0b940-goog
author maintainer
#1 lore raw

PATCH v2 1/11 perf tools: Add HEADER_BOOT_ID feature

Save /proc/sys/kernel/random/boot_id in the perf.data header and struct perf_env so post-processing tools can identify if it's the same kernel boot on which the data was recorded.

---
 .../Documentation/perf.data-file-format.txt   |  5 +++
 tools/perf/builtin-inject.c                   |  1 +
 tools/perf/util/env.c                         | 44 +++++++++++++++++++
 tools/perf/util/env.h                         |  3 ++
 tools/perf/util/header.c                      | 28 ++++++++++++
 tools/perf/util/header.h                      |  1 +
 tools/perf/util/session.c                     |  1 +
 7 files changed, 83 insertions(+)
tools/perf/Documentation/perf.data-file-format.txt +5 -0
index 1f8e7d8e9ae21d73..359d6ef0c80aac26 100644
@@ -491,6 +491,11 @@ struct memory_range {
 	u8 remote_region_id;
 }; [nr_memory_ranges]
 
+	HEADER_BOOT_ID = 36,
+
+	A perf_header_string with the kernel boot ID read from
+	/proc/sys/kernel/random/boot_id.
+
 	other bits are reserved and should be ignored for now
 	HEADER_FEAT_BITS	= 256,
 
tools/perf/builtin-inject.c +1 -0
index 3f3108fd39811017..0e01b14fa51676ab 100644
@@ -2307,6 +2307,7 @@ static bool keep_feat(struct perf_inject *inject, int feat)
 	case HEADER_CPU_DOMAIN_INFO:
 	case HEADER_CLN_SIZE:
 	case HEADER_MEMORY_RANGES:
+	case HEADER_BOOT_ID:
 		return true;
 	/* Information that can be updated */
 	case HEADER_BUILD_ID:
tools/perf/util/env.c +44 -0

62 lines not on this page · raw message

tools/perf/util/env.h +3 -0
index 23d35425efe38b24..aafd213c7523c018 100644
@@ -81,6 +81,7 @@ struct perf_env {
 	char			*os_release;
 	char			*version;
 	char			*arch;
+	char			*boot_id;
 	/* e_machine expanded from 16 to 32-bits for alignment. */
 	u32			e_machine;
 	u32			e_flags;
@@ -154,6 +155,7 @@ struct perf_env {
 	/* For fast cpu to numa node lookup via perf_env__numa_node */
 	int			*numa_map;
 	int			 nr_numa_map;
+	bool			 offline;
 
 	/* For real clock time reference. */
 	struct {
@@ -187,6 +189,7 @@ void perf_env__exit(struct perf_env *env);
 int perf_env__kernel_is_64_bit(struct perf_env *env);
 bool perf_arch_is_big_endian(const char *arch);
 const char *perf_env__os_release(struct perf_env *env);
+const char *perf_env__boot_id(struct perf_env *env);
 
 int perf_env__set_cmdline(struct perf_env *env, int argc, const char *argv[]);
 
tools/perf/util/header.c +28 -0
index 9eec6deee190ff21..3e0b6fce55973dd1 100644
@@ -494,6 +494,27 @@ static int write_version(struct feat_fd *ff,
 	return do_write_string(ff, perf_version_string);
 }
 
+static int write_boot_id(struct feat_fd *ff, struct evlist *evlist)
+{
+	const char *boot_id = NULL;
+	char *buf = NULL;
+	size_t sz;
+	int ret;
+
+	if (evlist__session(evlist))
+		boot_id = perf_env__boot_id(perf_session__env(evlist__session(evlist)));
+
+	if (!boot_id) {
+		if (procfs__read_str("sys/kernel/random/boot_id", &buf, &sz) < 0)
+			return -1;
+		boot_id = strim(buf);
+	}
+
+	ret = do_write_string(ff, boot_id);
+	free(buf);
+	return ret;
+}
+
 static int __write_cpudesc(struct feat_fd *ff, const char *cpuinfo_proc)
 {
 	FILE *file;
@@ -2079,6 +2100,11 @@ static void print_version(struct feat_fd *ff, FILE *fp)
 	fprintf(fp, "# perf version : %s\n", ff->ph->env.version);
 }
 
+static void print_boot_id(struct feat_fd *ff, FILE *fp)
+{
+	fprintf(fp, "# boot id : %s\n", ff->ph->env.boot_id);
+}
+
 static void print_cmdline(struct feat_fd *ff, FILE *fp)
 {
 	int nr, i;
@@ -3022,6 +3048,7 @@ FEAT_PROCESS_STR_FUN(osrelease, os_release);
 FEAT_PROCESS_STR_FUN(version, version);
 FEAT_PROCESS_STR_FUN(cpudesc, cpu_desc);
 FEAT_PROCESS_STR_FUN(cpuid, cpuid);
+FEAT_PROCESS_STR_FUN(boot_id, boot_id);
 
 static int process_arch(struct feat_fd *ff, void *data __maybe_unused)
 {
@@ -4496,6 +4523,7 @@ const struct perf_header_feature_ops feat_ops[HEADER_LAST_FEATURE] = {
 	FEAT_OPR(E_MACHINE,	e_machine,	false),
 	FEAT_OPR(CLN_SIZE,	cln_size,	false),
 	FEAT_OPR(MEMORY_RANGES,	memory_ranges,	false),
+	FEAT_OPR(BOOT_ID,	boot_id,	false),
 };
 
 struct header_print_data {
tools/perf/util/header.h +1 -0
index 765037762758ca11..5bbf16342b4d26d8 100644
@@ -57,6 +57,7 @@ enum {
 	HEADER_E_MACHINE,
 	HEADER_CLN_SIZE,
 	HEADER_MEMORY_RANGES,
+	HEADER_BOOT_ID,
 	HEADER_LAST_FEATURE,
 	HEADER_FEAT_BITS	= 256,
 };
tools/perf/util/session.c +1 -0
index a58b4fe44b62e3bb..578abcb14de84a39 100644
@@ -179,6 +179,7 @@ struct perf_session *__perf_session__new(struct perf_data *data,
 		session->data = data;
 
 		if (perf_data__is_read(data)) {
+			session->header.env.offline = true;
 			ret = perf_session__open(session);
 			if (ret < 0)
 				goto out_delete;
Signature · 1 line
2.56.0.611.g1030f0b940-goog
#2 lore raw

Re: [PATCH v2 01/11] perf tools: Add HEADER_BOOT_ID feature

Sashiko has reviewed this patch and found no issues.
Quoted 5 lines

Save /proc/sys/kernel/random/boot_id in the perf.data header and struct perf_env so post-processing tools can identify if it's the same kernel boot on which the data was recorded.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#3 lore raw

PATCH v2 2/11 perf tools: Add perf_env__is_same_boot()

In reply to Namhyung Kim

Add perf_env__is_same_boot() to compare the recorded boot_id in struct perf_env against the running host's /proc/sys/kernel/random/boot_id. For live sessions where no offline header was populated, it falls back to reading the host boot_id and returns true.

---
 tools/perf/util/env.c | 25 +++++++++++++++++++++++++
 tools/perf/util/env.h |  1 +
 2 files changed, 26 insertions(+)
tools/perf/util/env.c +25 -0
index 24de685486af9bd5..91ab4ccaf5a9475c 100644
@@ -444,6 +444,31 @@ const char *perf_env__boot_id(struct perf_env *env)
 	return boot_id;
 }
 
+static char *host_boot_id;
+
+static void init_host_boot_id(void)
+{
+	host_boot_id = read_host_boot_id();
+}
+
+bool perf_env__is_same_boot(struct perf_env *env)
+{
+	const char *env_boot_id;
+
+	DO_ONCE(init_host_boot_id);
+	if (!host_boot_id)
+		return false;
+
+	if (!env)
+		return true;
+
+	env_boot_id = perf_env__boot_id(env);
+	if (!env_boot_id)
+		return false;
+
+	return !strcmp(env_boot_id, host_boot_id);
+}
+
 int perf_env__set_cmdline(struct perf_env *env, int argc, const char *argv[])
 {
 	int i;
tools/perf/util/env.h +1 -0
index aafd213c7523c018..856385624cee6adf 100644
@@ -190,6 +190,7 @@ int perf_env__kernel_is_64_bit(struct perf_env *env);
 bool perf_arch_is_big_endian(const char *arch);
 const char *perf_env__os_release(struct perf_env *env);
 const char *perf_env__boot_id(struct perf_env *env);
+bool perf_env__is_same_boot(struct perf_env *env);
 
 int perf_env__set_cmdline(struct perf_env *env, int argc, const char *argv[]);
 
Signature · 1 line
2.56.0.611.g1030f0b940-goog
#4 lore raw

Re: [PATCH v2 02/11] perf tools: Add perf_env__is_same_boot()

Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

Add perf_env__is_same_boot() to compare the recorded boot_id in struct perf_env against the running host's /proc/sys/kernel/random/boot_id. For live sessions where no offline header was populated, it falls back to reading the host boot_id and returns true.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author maintainer
#5 lore raw

PATCH v2 3/11 perf tools: Add nsinfo__new_thread() to track tid

In reply to Namhyung Kim

Record the thread ID (tid) in struct nsinfo via nsinfo__new_thread() and access /proc/<pid>/task/<tid>/ status and ns/mnt paths instead of only /proc/<pid>/. Also recreate thread->nsinfo when the pid of the thread is updated.

---
 tools/perf/util/machine.c    |  3 +++
 tools/perf/util/namespaces.c | 22 ++++++++++++++++++----
 tools/perf/util/namespaces.h |  3 +++
 tools/perf/util/thread.c     |  2 +-
 4 files changed, 25 insertions(+), 5 deletions(-)
tools/perf/util/machine.c +3 -0
index 5b4550e97172db54..ac857b395882f569 100644
@@ -19,6 +19,7 @@
 #include "branch.h"
 #include "mem-events.h"
 #include "mem-info.h"
+#include "namespaces.h"
 #include "path.h"
 #include "srcline.h"
 #include "symbol.h"
@@ -516,6 +517,8 @@ static void machine__update_thread_pid(struct machine *machine,
 		return;
 
 	thread__set_pid(th, pid);
+	nsinfo__zput(RC_CHK_ACCESS(th)->nsinfo);
+	RC_CHK_ACCESS(th)->nsinfo = nsinfo__new_thread(pid, thread__tid(th));
 
 	if (thread__pid(th) == thread__tid(th))
 		return;
tools/perf/util/namespaces.c +18 -4
index 01502570b32d02ab..f426eba04d6ef449 100644
@@ -106,7 +106,8 @@ int nsinfo__init(struct nsinfo *nsi)
 	if (snprintf(oldns, PATH_MAX, "/proc/self/ns/mnt") >= PATH_MAX)
 		return rv;
 
-	if (asprintf(&newns, "/proc/%d/ns/mnt", nsinfo__pid(nsi)) == -1)
+	if (asprintf(&newns, "/proc/%d/task/%d/ns/mnt",
+		     nsinfo__pid(nsi), nsinfo__tid(nsi)) == -1)
 		return rv;
 
 	if (stat(oldns, &old_stat) < 0)
@@ -127,7 +128,8 @@ int nsinfo__init(struct nsinfo *nsi)
 	/* If we're dealing with a process that is in a different PID namespace,
 	 * attempt to work out the innermost tgid for the process.
 	 */
-	if (snprintf(spath, PATH_MAX, "/proc/%d/status", nsinfo__pid(nsi)) >= PATH_MAX)
+	if (snprintf(spath, PATH_MAX, "/proc/%d/task/%d/status",
+		     nsinfo__pid(nsi), nsinfo__tid(nsi)) >= PATH_MAX)
 		goto out;
 
 	rv = nsinfo__get_nspid(&RC_CHK_ACCESS(nsi)->tgid, &RC_CHK_ACCESS(nsi)->nstgid,
@@ -150,11 +152,11 @@ static struct nsinfo *nsinfo__alloc(void)
 	return res;
 }
 
-struct nsinfo *nsinfo__new(pid_t pid)
+struct nsinfo *nsinfo__new_thread(pid_t pid, pid_t tid)
 {
 	struct nsinfo *nsi;
 
-	if (pid == 0)
+	if (pid <= 0 || tid <= 0)
 		return NULL;
 
 	nsi = nsinfo__alloc();
@@ -162,6 +164,7 @@ struct nsinfo *nsinfo__new(pid_t pid)
 		return NULL;
 
 	RC_CHK_ACCESS(nsi)->pid = pid;
+	RC_CHK_ACCESS(nsi)->tid = tid;
 	RC_CHK_ACCESS(nsi)->tgid = pid;
 	RC_CHK_ACCESS(nsi)->nstgid = pid;
 	nsinfo__clear_need_setns(nsi);
@@ -176,6 +179,11 @@ struct nsinfo *nsinfo__new(pid_t pid)
 	return nsi;
 }
 
+struct nsinfo *nsinfo__new(pid_t pid)
+{
+	return nsinfo__new_thread(pid, pid);
+}
+
 static const char *nsinfo__mntns_path(const struct nsinfo *nsi)
 {
 	return RC_CHK_ACCESS(nsi)->mntns_path;
@@ -193,6 +201,7 @@ struct nsinfo *nsinfo__copy(const struct nsinfo *nsi)
 		return NULL;
 
 	RC_CHK_ACCESS(nnsi)->pid = nsinfo__pid(nsi);
+	RC_CHK_ACCESS(nnsi)->tid = nsinfo__tid(nsi);
 	RC_CHK_ACCESS(nnsi)->tgid = nsinfo__tgid(nsi);
 	RC_CHK_ACCESS(nnsi)->nstgid = nsinfo__nstgid(nsi);
 	RC_CHK_ACCESS(nnsi)->need_setns = nsinfo__need_setns(nsi);
@@ -265,6 +274,11 @@ pid_t nsinfo__pid(const struct nsinfo  *nsi)
 	return RC_CHK_ACCESS(nsi)->pid;
 }
 
+pid_t nsinfo__tid(const struct nsinfo  *nsi)
+{
+	return RC_CHK_ACCESS(nsi)->tid;
+}
+
 bool nsinfo__in_pidns(const struct nsinfo *nsi)
 {
 	return RC_CHK_ACCESS(nsi)->in_pidns;
tools/perf/util/namespaces.h +3 -0
index e95c79b80e27c8fc..ea645954944de4be 100644
@@ -32,6 +32,7 @@ void namespaces__free(struct namespaces *namespaces);
 
 DECLARE_RC_STRUCT(nsinfo) {
 	pid_t			pid;
+	pid_t			tid;
 	pid_t			tgid;
 	pid_t			nstgid;
 	bool			need_setns;
@@ -48,6 +49,7 @@ struct nscookie {
 
 int nsinfo__init(struct nsinfo *nsi);
 struct nsinfo *nsinfo__new(pid_t pid);
+struct nsinfo *nsinfo__new_thread(pid_t pid, pid_t tid);
 struct nsinfo *nsinfo__copy(const struct nsinfo *nsi);
 
 struct nsinfo *nsinfo__get(struct nsinfo *nsi);
@@ -58,6 +60,7 @@ void nsinfo__clear_need_setns(struct nsinfo *nsi);
 pid_t nsinfo__tgid(const struct nsinfo  *nsi);
 pid_t nsinfo__nstgid(const struct nsinfo  *nsi);
 pid_t nsinfo__pid(const struct nsinfo  *nsi);
+pid_t nsinfo__tid(const struct nsinfo  *nsi);
 bool nsinfo__in_pidns(const struct nsinfo  *nsi);
 void nsinfo__set_in_pidns(struct nsinfo *nsi);
 
tools/perf/util/thread.c +1 -1
index 91118c301913b834..d12eb6bc63313b00 100644
@@ -71,7 +71,7 @@ struct thread *thread__new(pid_t pid, pid_t tid)
 		list_add(&comm->list, thread__comm_list(thread));
 		refcount_set(thread__refcnt(thread), 1);
 		/* Thread holds first ref to nsdata. */
-		RC_CHK_ACCESS(thread)->nsinfo = nsinfo__new(pid);
+		RC_CHK_ACCESS(thread)->nsinfo = nsinfo__new_thread(pid, tid);
 		srccode_state_init(thread__srccode_state(thread));
 	}
 
Signature · 1 line
2.56.0.611.g1030f0b940-goog
#6 lore raw

Re: [PATCH v2 03/11] perf tools: Add nsinfo__new_thread() to track tid

Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

Record the thread ID (tid) in struct nsinfo via nsinfo__new_thread() and access /proc/<pid>/task/<tid>/ status and ns/mnt paths instead of only /proc/<pid>/. Also recreate thread->nsinfo when the pid of the thread is updated.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author maintainer
#7 lore raw

PATCH v2 4/11 perf tools: Add lock to struct nsinfo

In reply to Namhyung Kim

A struct nsinfo instance can be shared across threads via thread->nsinfo and dso->nsinfo. Add a mutex lock inside struct nsinfo to synchronize access to its fields, initialization, copying, and mount namespace path duplication in nsinfo__mountns_enter().

---
 tools/perf/util/namespaces.c | 106 +++++++++++++++++++++++++++--------
 tools/perf/util/namespaces.h |   2 +
 2 files changed, 86 insertions(+), 22 deletions(-)
tools/perf/util/namespaces.c +84 -22
index f426eba04d6ef449..845a62045405c80a 100644
@@ -94,7 +94,7 @@ static int nsinfo__get_nspid(pid_t *tgid, pid_t *nstgid, bool *in_pidns, const c
 	return 0;
 }
 
-int nsinfo__init(struct nsinfo *nsi)
+static int nsinfo__init_locked(struct nsinfo *nsi)
 {
 	char oldns[PATH_MAX];
 	char spath[PATH_MAX];
@@ -140,14 +140,29 @@ int nsinfo__init(struct nsinfo *nsi)
 	return rv;
 }
 
+int nsinfo__init(struct nsinfo *nsi)
+{
+	int rv;
+
+	if (!nsi)
+		return -1;
+
+	mutex_lock(&RC_CHK_ACCESS(nsi)->lock);
+	rv = nsinfo__init_locked(nsi);
+	mutex_unlock(&RC_CHK_ACCESS(nsi)->lock);
+	return rv;
+}
+
 static struct nsinfo *nsinfo__alloc(void)
 {
 	struct nsinfo *res;
 	RC_STRUCT(nsinfo) *nsi;
 
 	nsi = calloc(1, sizeof(*nsi));
-	if (ADD_RC_CHK(res, nsi))
+	if (ADD_RC_CHK(res, nsi)) {
 		refcount_set(&nsi->refcnt, 1);
+		mutex_init(&nsi->lock);
+	}
 
 	return res;
 }
@@ -184,9 +199,9 @@ struct nsinfo *nsinfo__new(pid_t pid)
 	return nsinfo__new_thread(pid, pid);
 }
 
-static const char *nsinfo__mntns_path(const struct nsinfo *nsi)
+static struct mutex *nsinfo__lock(const struct nsinfo *nsi)
 {
-	return RC_CHK_ACCESS(nsi)->mntns_path;
+	return (struct mutex *)&RC_CHK_ACCESS(nsi)->lock;
 }
 
 struct nsinfo *nsinfo__copy(const struct nsinfo *nsi)
@@ -200,19 +215,22 @@ struct nsinfo *nsinfo__copy(const struct nsinfo *nsi)
 	if (!nnsi)
 		return NULL;
 
-	RC_CHK_ACCESS(nnsi)->pid = nsinfo__pid(nsi);
-	RC_CHK_ACCESS(nnsi)->tid = nsinfo__tid(nsi);
-	RC_CHK_ACCESS(nnsi)->tgid = nsinfo__tgid(nsi);
-	RC_CHK_ACCESS(nnsi)->nstgid = nsinfo__nstgid(nsi);
-	RC_CHK_ACCESS(nnsi)->need_setns = nsinfo__need_setns(nsi);
-	RC_CHK_ACCESS(nnsi)->in_pidns = nsinfo__in_pidns(nsi);
-	if (nsinfo__mntns_path(nsi)) {
-		RC_CHK_ACCESS(nnsi)->mntns_path = strdup(nsinfo__mntns_path(nsi));
+	mutex_lock(nsinfo__lock(nsi));
+	RC_CHK_ACCESS(nnsi)->pid = RC_CHK_ACCESS(nsi)->pid;
+	RC_CHK_ACCESS(nnsi)->tid = RC_CHK_ACCESS(nsi)->tid;
+	RC_CHK_ACCESS(nnsi)->tgid = RC_CHK_ACCESS(nsi)->tgid;
+	RC_CHK_ACCESS(nnsi)->nstgid = RC_CHK_ACCESS(nsi)->nstgid;
+	RC_CHK_ACCESS(nnsi)->need_setns = RC_CHK_ACCESS(nsi)->need_setns;
+	RC_CHK_ACCESS(nnsi)->in_pidns = RC_CHK_ACCESS(nsi)->in_pidns;
+	if (RC_CHK_ACCESS(nsi)->mntns_path) {
+		RC_CHK_ACCESS(nnsi)->mntns_path = strdup(RC_CHK_ACCESS(nsi)->mntns_path);
 		if (!RC_CHK_ACCESS(nnsi)->mntns_path) {
+			mutex_unlock(nsinfo__lock(nsi));
 			nsinfo__put(nnsi);
 			return NULL;
 		}
 	}
+	mutex_unlock(nsinfo__lock(nsi));
 
 	return nnsi;
 }
@@ -227,6 +245,7 @@ static void nsinfo__delete(struct nsinfo *nsi)
 	if (nsi) {
 		WARN_ONCE(refcount_read(nsinfo__refcnt(nsi)) != 0, "nsinfo refcnt unbalanced\n");
 		zfree(&RC_CHK_ACCESS(nsi)->mntns_path);
+		mutex_destroy(&RC_CHK_ACCESS(nsi)->lock);
 		RC_CHK_FREE(nsi);
 	}
 }
@@ -251,22 +270,46 @@ void nsinfo__put(struct nsinfo *nsi)
 
 bool nsinfo__need_setns(const struct nsinfo *nsi)
 {
-	return RC_CHK_ACCESS(nsi)->need_setns;
+	bool ret;
+
+	if (!nsi)
+		return false;
+
+	mutex_lock(nsinfo__lock(nsi));
+	ret = RC_CHK_ACCESS(nsi)->need_setns;
+	mutex_unlock(nsinfo__lock(nsi));
+	return ret;
 }
 
 void nsinfo__clear_need_setns(struct nsinfo *nsi)
 {
+	if (!nsi)
+		return;
+
+	mutex_lock(nsinfo__lock(nsi));
 	RC_CHK_ACCESS(nsi)->need_setns = false;
+	zfree(&RC_CHK_ACCESS(nsi)->mntns_path);
+	mutex_unlock(nsinfo__lock(nsi));
 }
 
-pid_t nsinfo__tgid(const struct nsinfo  *nsi)
+pid_t nsinfo__tgid(const struct nsinfo *nsi)
 {
-	return RC_CHK_ACCESS(nsi)->tgid;
+	pid_t ret;
+
+	mutex_lock(nsinfo__lock(nsi));
+	ret = RC_CHK_ACCESS(nsi)->tgid;
+	mutex_unlock(nsinfo__lock(nsi));
+	return ret;
 }
 
-pid_t nsinfo__nstgid(const struct nsinfo  *nsi)
+pid_t nsinfo__nstgid(const struct nsinfo *nsi)
 {
-	return RC_CHK_ACCESS(nsi)->nstgid;
+	pid_t ret;
+
+	mutex_lock(nsinfo__lock(nsi));
+	ret = RC_CHK_ACCESS(nsi)->nstgid;
+	mutex_unlock(nsinfo__lock(nsi));
+	return ret;
 }
 
 pid_t nsinfo__pid(const struct nsinfo  *nsi)
@@ -281,18 +324,26 @@ pid_t nsinfo__tid(const struct nsinfo  *nsi)
 
 bool nsinfo__in_pidns(const struct nsinfo *nsi)
 {
-	return RC_CHK_ACCESS(nsi)->in_pidns;
+	bool ret;
+
+	mutex_lock(nsinfo__lock(nsi));
+	ret = RC_CHK_ACCESS(nsi)->in_pidns;
+	mutex_unlock(nsinfo__lock(nsi));
+	return ret;
 }
 
 void nsinfo__set_in_pidns(struct nsinfo *nsi)
 {
+	mutex_lock(&RC_CHK_ACCESS(nsi)->lock);
 	RC_CHK_ACCESS(nsi)->in_pidns = true;
+	mutex_unlock(&RC_CHK_ACCESS(nsi)->lock);
 }
 
 void nsinfo__mountns_enter(struct nsinfo *nsi,
 				  struct nscookie *nc)
 {
 	char curpath[PATH_MAX];
+	char *mntns_path = NULL;
 	int oldns = -1;
 	int newns = -1;
 	char *oldcwd = NULL;
@@ -303,27 +354,36 @@ void nsinfo__mountns_enter(struct nsinfo *nsi,
 	nc->oldns = -1;
 	nc->newns = -1;
 
-	if (!nsi || !nsinfo__need_setns(nsi))
+	if (!nsi)
+		return;
+
+	mutex_lock(&RC_CHK_ACCESS(nsi)->lock);
+	if (RC_CHK_ACCESS(nsi)->need_setns && RC_CHK_ACCESS(nsi)->mntns_path)
+		mntns_path = strdup(RC_CHK_ACCESS(nsi)->mntns_path);
+	mutex_unlock(&RC_CHK_ACCESS(nsi)->lock);
+
+	if (!mntns_path)
 		return;
 
 	if (!getcwd(curpath, sizeof(curpath)))
-		return;
+		goto out;
 
 	oldcwd = strdup(curpath);
 	if (!oldcwd)
-		return;
+		goto out;
 
 	oldns = open("/proc/self/ns/mnt", O_RDONLY);
 	if (oldns < 0)
 		goto errout;
 
-	newns = open(nsinfo__mntns_path(nsi), O_RDONLY);
+	newns = open(mntns_path, O_RDONLY);
 	if (newns < 0)
 		goto errout;
 
 	if (setns(newns, CLONE_NEWNS) < 0)
 		goto errout;
 
+	free(mntns_path);
 	nc->oldcwd = oldcwd;
 	nc->oldns = oldns;
 	nc->newns = newns;
@@ -335,6 +395,8 @@ void nsinfo__mountns_enter(struct nsinfo *nsi,
 		close(oldns);
 	if (newns > -1)
 		close(newns);
+out:
+	free(mntns_path);
 }
 
 void nsinfo__mountns_exit(struct nscookie *nc)
tools/perf/util/namespaces.h +2 -0
index ea645954944de4be..bbb47a6f9e8323f2 100644
@@ -14,6 +14,7 @@
 #include <linux/refcount.h>
 #include <linux/types.h>
 #include <internal/rc_check.h>
+#include "mutex.h"
 
 #ifndef HAVE_SETNS_SUPPORT
 int setns(int fd, int nstype);
@@ -31,6 +32,7 @@ struct namespaces *namespaces__new(struct perf_record_namespaces *event);
 void namespaces__free(struct namespaces *namespaces);
 
 DECLARE_RC_STRUCT(nsinfo) {
+	struct mutex		lock;
 	pid_t			pid;
 	pid_t			tid;
 	pid_t			tgid;
Signature · 1 line
2.56.0.611.g1030f0b940-goog
#8 lore raw

Re: [PATCH v2 04/11] perf tools: Add lock to struct nsinfo

Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

A struct nsinfo instance can be shared across threads via thread->nsinfo and dso->nsinfo. Add a mutex lock inside struct nsinfo to synchronize access to its fields, initialization, copying, and mount namespace path duplication in nsinfo__mountns_enter().

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author maintainer
#9 lore raw

PATCH v2 5/11 perf tools: Defer /proc lookup until nsinfo is used

In reply to Namhyung Kim

Do not read /proc/<pid>/task/<tid>/ eagerly in nsinfo__new_thread(). Instead, initialize struct nsinfo on demand via nsinfo__ensure_init_locked() when namespace information is queried or entered, protected by nsinfo->lock.

Replace thread__nsinfo() with thread__get_nsinfo() and add thread__reset_nsinfo() to replace thread->nsinfo safely under thread->namespaces_lock on exec and PERF_RECORD_NAMESPACES events so namespace changes are picked up without racing existing readers.

---
 tools/perf/builtin-inject.c  |  2 +-
 tools/perf/util/jitdump.c    |  2 +-
 tools/perf/util/map.c        |  2 +-
 tools/perf/util/namespaces.c | 24 +++++++++++++++---------
 tools/perf/util/namespaces.h |  1 +
 tools/perf/util/thread.c     | 32 ++++++++++++++++++++++++++++++++
 tools/perf/util/thread.h     |  6 ++----
 7 files changed, 53 insertions(+), 16 deletions(-)
tools/perf/builtin-inject.c +1 -1
index 0e01b14fa51676ab..05bf1aae61778952 100644
@@ -626,7 +626,7 @@ static struct dso *findnew_dso(int pid, int tid, const char *filename,
 	}
 
 	vdso = is_vdso_map(filename);
-	nsi = nsinfo__get(thread__nsinfo(thread));
+	nsi = thread__get_nsinfo(thread);
 
 	if (vdso) {
 		/* The vdso maps are always on the host and not the
tools/perf/util/jitdump.c +1 -1
index 45a05316b3ca65b7..95a08ead1f380747 100644
@@ -985,7 +985,7 @@ jit_process(struct perf_session *session,
 		return 0;
 	}
 
-	nsi = nsinfo__get(thread__nsinfo(thread));
+	nsi = thread__get_nsinfo(thread);
 	thread__put(thread);
 
 	/*
tools/perf/util/map.c +1 -1
index d5319ffa88a7477c..91c1fbeff9d2446f 100644
@@ -139,7 +139,7 @@ struct map *map__new(struct machine *machine, u64 start, u64 len,
 		anon = is_anon_memory(filename) || flags & MAP_HUGETLB;
 		vdso = is_vdso_map(filename);
 		no_dso = is_no_dso_memory(filename);
-		nsi = nsinfo__get(thread__nsinfo(thread));
+		nsi = thread__get_nsinfo(thread);
 
 		if ((anon || no_dso) && nsi && (prot & PROT_EXEC)) {
 			snprintf(newfilename, sizeof(newfilename),
tools/perf/util/namespaces.c +15 -9
index 845a62045405c80a..afd8ad7f843ec09d 100644
@@ -103,6 +103,8 @@ static int nsinfo__init_locked(struct nsinfo *nsi)
 	struct stat new_stat;
 	int rv = -1;
 
+	RC_CHK_ACCESS(nsi)->inited = true;
+
 	if (snprintf(oldns, PATH_MAX, "/proc/self/ns/mnt") >= PATH_MAX)
 		return rv;
 
@@ -153,6 +155,12 @@ int nsinfo__init(struct nsinfo *nsi)
 	return rv;
 }
 
+static void nsinfo__ensure_init_locked(struct nsinfo *nsi)
+{
+	if (!RC_CHK_ACCESS(nsi)->inited)
+		nsinfo__init_locked(nsi);
+}
+
 static struct nsinfo *nsinfo__alloc(void)
 {
 	struct nsinfo *res;
@@ -182,15 +190,6 @@ struct nsinfo *nsinfo__new_thread(pid_t pid, pid_t tid)
 	RC_CHK_ACCESS(nsi)->tid = tid;
 	RC_CHK_ACCESS(nsi)->tgid = pid;
 	RC_CHK_ACCESS(nsi)->nstgid = pid;
-	nsinfo__clear_need_setns(nsi);
-	RC_CHK_ACCESS(nsi)->in_pidns = false;
-	/* Init may fail if the process exits while we're trying to look at its
-	 * proc information. In that case, save the pid but don't try to enter
-	 * the namespace.
-	 */
-	if (nsinfo__init(nsi) == -1)
-		nsinfo__clear_need_setns(nsi);
-
 	return nsi;
 }
 
@@ -220,6 +219,7 @@ struct nsinfo *nsinfo__copy(const struct nsinfo *nsi)
 	RC_CHK_ACCESS(nnsi)->tid = RC_CHK_ACCESS(nsi)->tid;
 	RC_CHK_ACCESS(nnsi)->tgid = RC_CHK_ACCESS(nsi)->tgid;
 	RC_CHK_ACCESS(nnsi)->nstgid = RC_CHK_ACCESS(nsi)->nstgid;
+	RC_CHK_ACCESS(nnsi)->inited = RC_CHK_ACCESS(nsi)->inited;
 	RC_CHK_ACCESS(nnsi)->need_setns = RC_CHK_ACCESS(nsi)->need_setns;
 	RC_CHK_ACCESS(nnsi)->in_pidns = RC_CHK_ACCESS(nsi)->in_pidns;
 	if (RC_CHK_ACCESS(nsi)->mntns_path) {
@@ -276,6 +276,7 @@ bool nsinfo__need_setns(const struct nsinfo *nsi)
 		return false;
 
 	mutex_lock(nsinfo__lock(nsi));
+	nsinfo__ensure_init_locked((struct nsinfo *)nsi);
 	ret = RC_CHK_ACCESS(nsi)->need_setns;
 	mutex_unlock(nsinfo__lock(nsi));
 	return ret;
@@ -287,6 +288,7 @@ void nsinfo__clear_need_setns(struct nsinfo *nsi)
 		return;
 
 	mutex_lock(nsinfo__lock(nsi));
+	RC_CHK_ACCESS(nsi)->inited = true;
 	RC_CHK_ACCESS(nsi)->need_setns = false;
 	zfree(&RC_CHK_ACCESS(nsi)->mntns_path);
 	mutex_unlock(nsinfo__lock(nsi));
@@ -297,6 +299,7 @@ pid_t nsinfo__tgid(const struct nsinfo *nsi)
 	pid_t ret;
 
 	mutex_lock(nsinfo__lock(nsi));
+	nsinfo__ensure_init_locked((struct nsinfo *)nsi);
 	ret = RC_CHK_ACCESS(nsi)->tgid;
 	mutex_unlock(nsinfo__lock(nsi));
 	return ret;
@@ -307,6 +310,7 @@ pid_t nsinfo__nstgid(const struct nsinfo *nsi)
 	pid_t ret;
 
 	mutex_lock(nsinfo__lock(nsi));
+	nsinfo__ensure_init_locked((struct nsinfo *)nsi);
 	ret = RC_CHK_ACCESS(nsi)->nstgid;
 	mutex_unlock(nsinfo__lock(nsi));
 	return ret;
@@ -327,6 +331,7 @@ bool nsinfo__in_pidns(const struct nsinfo *nsi)
 	bool ret;
 
 	mutex_lock(nsinfo__lock(nsi));
+	nsinfo__ensure_init_locked((struct nsinfo *)nsi);
 	ret = RC_CHK_ACCESS(nsi)->in_pidns;
 	mutex_unlock(nsinfo__lock(nsi));
 	return ret;
@@ -358,6 +363,7 @@ void nsinfo__mountns_enter(struct nsinfo *nsi,
 		return;
 
 	mutex_lock(&RC_CHK_ACCESS(nsi)->lock);
+	nsinfo__ensure_init_locked(nsi);
 	if (RC_CHK_ACCESS(nsi)->need_setns && RC_CHK_ACCESS(nsi)->mntns_path)
 		mntns_path = strdup(RC_CHK_ACCESS(nsi)->mntns_path);
 	mutex_unlock(&RC_CHK_ACCESS(nsi)->lock);
tools/perf/util/namespaces.h +1 -0
index bbb47a6f9e8323f2..42dcca13b002f153 100644
@@ -37,6 +37,7 @@ DECLARE_RC_STRUCT(nsinfo) {
 	pid_t			tid;
 	pid_t			tgid;
 	pid_t			nstgid;
+	bool			inited;
 	bool			need_setns;
 	bool			in_pidns;
 	char			*mntns_path;
tools/perf/util/thread.c +32 -0
index d12eb6bc63313b00..5d1c886add3e61eb 100644
@@ -191,6 +191,34 @@ static int __thread__set_namespaces(struct thread *thread, u64 timestamp,
 	return 0;
 }
 
+static void __thread__reset_nsinfo(struct thread *thread)
+	EXCLUSIVE_LOCKS_REQUIRED(thread__namespaces_lock(thread))
+{
+	nsinfo__zput(RC_CHK_ACCESS(thread)->nsinfo);
+	RC_CHK_ACCESS(thread)->nsinfo = nsinfo__new_thread(thread__pid(thread),
+							   thread__tid(thread));
+}
+
+void thread__reset_nsinfo(struct thread *thread)
+{
+	down_write(thread__namespaces_lock(thread));
+	__thread__reset_nsinfo(thread);
+	up_write(thread__namespaces_lock(thread));
+}
+
+struct nsinfo *thread__get_nsinfo(struct thread *thread)
+{
+	struct nsinfo *nsi;
+
+	if (!thread)
+		return NULL;
+
+	down_read(thread__namespaces_lock(thread));
+	nsi = nsinfo__get(RC_CHK_ACCESS(thread)->nsinfo);
+	up_read(thread__namespaces_lock(thread));
+	return nsi;
+}
+
 int thread__set_namespaces(struct thread *thread, u64 timestamp,
 			   struct perf_record_namespaces *event)
 {
@@ -198,6 +226,8 @@ int thread__set_namespaces(struct thread *thread, u64 timestamp,
 
 	down_write(thread__namespaces_lock(thread));
 	ret = __thread__set_namespaces(thread, timestamp, event);
+	if (!ret && event)
+		__thread__reset_nsinfo(thread);
 	up_write(thread__namespaces_lock(thread));
 	return ret;
 }
@@ -282,6 +312,8 @@ int __thread__set_comm(struct thread *thread, const char *str, u64 timestamp,
 	down_write(thread__comm_lock(thread));
 	ret = ____thread__set_comm(thread, str, timestamp, exec);
 	up_write(thread__comm_lock(thread));
+	if (!ret && exec)
+		thread__reset_nsinfo(thread);
 	return ret;
 }
 
tools/perf/util/thread.h +2 -4
index d82fce8173aefedc..36f2932422df8988 100644
@@ -286,10 +286,8 @@ static inline void thread__set_ts(struct thread *thread, struct thread_stack *ts
 	RC_CHK_ACCESS(thread)->ts = ts;
 }
 
-static inline struct nsinfo *thread__nsinfo(struct thread *thread)
-{
-	return RC_CHK_ACCESS(thread)->nsinfo;
-}
+struct nsinfo *thread__get_nsinfo(struct thread *thread);
+void thread__reset_nsinfo(struct thread *thread);
 
 static inline struct srccode_state *thread__srccode_state(struct thread *thread)
 {
Signature · 1 line
2.56.0.611.g1030f0b940-goog
#10 lore raw

Re: [PATCH v2 05/11] perf tools: Defer /proc lookup until nsinfo is used

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

Do not read /proc/<pid>/task/<tid>/ eagerly in nsinfo__new_thread(). Instead, initialize struct nsinfo on demand via nsinfo__ensure_init_locked() when namespace information is queried or entered, protected by nsinfo->lock.

Replace thread__nsinfo() with thread__get_nsinfo() and add thread__reset_nsinfo() to replace thread->nsinfo safely under thread->namespaces_lock on exec and PERF_RECORD_NAMESPACES events so namespace changes are picked up without racing existing readers.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
author maintainer
#11 lore raw

PATCH v2 6/11 perf tools: Verify thread status and mount namespace inode

In reply to Namhyung Kim

Verify /proc/<pid>/task/<tid>/status exists and has Tgid == pid before reading or entering a thread's namespaces to guard against PID/TID recycling.

Also record the mount namespace inode (mntns_ino) during initialization and verify via fstat() that the opened namespace file descriptor still refers to the same mount namespace.

---
 tools/perf/util/namespaces.c | 139 +++++++++++++++++++++++++++--------
 tools/perf/util/namespaces.h |   4 +
 2 files changed, 114 insertions(+), 29 deletions(-)
tools/perf/util/namespaces.c +110 -29
index afd8ad7f843ec09d..860b90e8384ed1f2 100644
@@ -65,6 +65,7 @@ static int nsinfo__get_nspid(pid_t *tgid, pid_t *nstgid, bool *in_pidns, const c
 	char *statln = NULL;
 	size_t linesz = 0;
 	char *nspid;
+	bool got_tgid = false;
 
 	f = fopen(path, "r");
 	if (f == NULL)
@@ -75,6 +76,7 @@ static int nsinfo__get_nspid(pid_t *tgid, pid_t *nstgid, bool *in_pidns, const c
 		if (strstr(statln, "Tgid:") != NULL) {
 			*tgid = (pid_t)strtol(strrchr(statln, '\t'), NULL, 10);
 			*nstgid = *tgid;
+			got_tgid = true;
 		}
 
 		if (strstr(statln, "NStgid:") != NULL) {
@@ -91,7 +93,20 @@ static int nsinfo__get_nspid(pid_t *tgid, pid_t *nstgid, bool *in_pidns, const c
 
 	fclose(f);
 	free(statln);
-	return 0;
+	return got_tgid ? 0 : -1;
+}
+
+static void nsinfo__clear_need_setns_locked(struct nsinfo *nsi)
+{
+	RC_CHK_ACCESS(nsi)->inited = true;
+	RC_CHK_ACCESS(nsi)->need_setns = false;
+	zfree(&RC_CHK_ACCESS(nsi)->mntns_path);
+}
+
+static void nsinfo__set_exited_locked(struct nsinfo *nsi)
+{
+	RC_CHK_ACCESS(nsi)->exited = true;
+	nsinfo__clear_need_setns_locked(nsi);
 }
 
 static int nsinfo__init_locked(struct nsinfo *nsi)
@@ -101,16 +116,41 @@ static int nsinfo__init_locked(struct nsinfo *nsi)
 	char *newns = NULL;
 	struct stat old_stat;
 	struct stat new_stat;
+	pid_t tgid = 0, nstgid = 0;
+	bool in_pidns = false;
 	int rv = -1;
 
+	if (RC_CHK_ACCESS(nsi)->exited)
+		return -1;
+
 	RC_CHK_ACCESS(nsi)->inited = true;
 
+	/*
+	 * Verify that the thread (pid, tid) still exists in /proc and its Tgid
+	 * matches pid (guarding against PID/TID recycling), while resolving the
+	 * innermost tgid if the process is in a different PID namespace.
+	 */
+	if (snprintf(spath, PATH_MAX, "/proc/%d/task/%d/status",
+		     nsinfo__pid(nsi), nsinfo__tid(nsi)) >= PATH_MAX)
+		goto out;
+
+	rv = nsinfo__get_nspid(&tgid, &nstgid, &in_pidns, spath);
+	if (rv < 0 || tgid != nsinfo__pid(nsi)) {
+		nsinfo__set_exited_locked(nsi);
+		rv = -1;
+		goto out;
+	}
+
+	RC_CHK_ACCESS(nsi)->tgid = tgid;
+	RC_CHK_ACCESS(nsi)->nstgid = nstgid;
+	RC_CHK_ACCESS(nsi)->in_pidns = in_pidns;
+
 	if (snprintf(oldns, PATH_MAX, "/proc/self/ns/mnt") >= PATH_MAX)
-		return rv;
+		return -1;
 
 	if (asprintf(&newns, "/proc/%d/task/%d/ns/mnt",
 		     nsinfo__pid(nsi), nsinfo__tid(nsi)) == -1)
-		return rv;
+		return -1;
 
 	if (stat(oldns, &old_stat) < 0)
 		goto out;
@@ -124,19 +164,10 @@ static int nsinfo__init_locked(struct nsinfo *nsi)
 	if (old_stat.st_ino != new_stat.st_ino) {
 		RC_CHK_ACCESS(nsi)->need_setns = true;
 		RC_CHK_ACCESS(nsi)->mntns_path = newns;
+		RC_CHK_ACCESS(nsi)->mntns_ino = new_stat.st_ino;
 		newns = NULL;
 	}
 
-	/* If we're dealing with a process that is in a different PID namespace,
-	 * attempt to work out the innermost tgid for the process.
-	 */
-	if (snprintf(spath, PATH_MAX, "/proc/%d/task/%d/status",
-		     nsinfo__pid(nsi), nsinfo__tid(nsi)) >= PATH_MAX)
-		goto out;
-
-	rv = nsinfo__get_nspid(&RC_CHK_ACCESS(nsi)->tgid, &RC_CHK_ACCESS(nsi)->nstgid,
-			       &RC_CHK_ACCESS(nsi)->in_pidns, spath);
-
 out:
 	free(newns);
 	return rv;
@@ -157,7 +188,7 @@ int nsinfo__init(struct nsinfo *nsi)
 
 static void nsinfo__ensure_init_locked(struct nsinfo *nsi)
 {
-	if (!RC_CHK_ACCESS(nsi)->inited)
+	if (!RC_CHK_ACCESS(nsi)->inited && !RC_CHK_ACCESS(nsi)->exited)
 		nsinfo__init_locked(nsi);
 }
 
@@ -219,7 +250,9 @@ struct nsinfo *nsinfo__copy(const struct nsinfo *nsi)
 	RC_CHK_ACCESS(nnsi)->tid = RC_CHK_ACCESS(nsi)->tid;
 	RC_CHK_ACCESS(nnsi)->tgid = RC_CHK_ACCESS(nsi)->tgid;
 	RC_CHK_ACCESS(nnsi)->nstgid = RC_CHK_ACCESS(nsi)->nstgid;
+	RC_CHK_ACCESS(nnsi)->mntns_ino = RC_CHK_ACCESS(nsi)->mntns_ino;
 	RC_CHK_ACCESS(nnsi)->inited = RC_CHK_ACCESS(nsi)->inited;
+	RC_CHK_ACCESS(nnsi)->exited = RC_CHK_ACCESS(nsi)->exited;
 	RC_CHK_ACCESS(nnsi)->need_setns = RC_CHK_ACCESS(nsi)->need_setns;
 	RC_CHK_ACCESS(nnsi)->in_pidns = RC_CHK_ACCESS(nsi)->in_pidns;
 	if (RC_CHK_ACCESS(nsi)->mntns_path) {
@@ -277,7 +310,7 @@ bool nsinfo__need_setns(const struct nsinfo *nsi)
 
 	mutex_lock(nsinfo__lock(nsi));
 	nsinfo__ensure_init_locked((struct nsinfo *)nsi);
-	ret = RC_CHK_ACCESS(nsi)->need_setns;
+	ret = !RC_CHK_ACCESS(nsi)->exited && RC_CHK_ACCESS(nsi)->need_setns;
 	mutex_unlock(nsinfo__lock(nsi));
 	return ret;
 }
@@ -288,12 +321,47 @@ void nsinfo__clear_need_setns(struct nsinfo *nsi)
 		return;
 
 	mutex_lock(nsinfo__lock(nsi));
-	RC_CHK_ACCESS(nsi)->inited = true;
-	RC_CHK_ACCESS(nsi)->need_setns = false;
-	zfree(&RC_CHK_ACCESS(nsi)->mntns_path);
+	nsinfo__clear_need_setns_locked(nsi);
+	mutex_unlock(nsinfo__lock(nsi));
+}
+
+void nsinfo__set_exited(struct nsinfo *nsi)
+{
+	if (!nsi)
+		return;
+
+	mutex_lock(nsinfo__lock(nsi));
+	nsinfo__set_exited_locked(nsi);
 	mutex_unlock(nsinfo__lock(nsi));
 }
 
+bool nsinfo__check_proc(struct nsinfo *nsi)
+{
+	char spath[64];
+	pid_t tgid = 0, nstgid = 0;
+	bool in_pidns = false;
+	bool exited;
+
+	if (!nsi)
+		return false;
+
+	mutex_lock(nsinfo__lock(nsi));
+	exited = RC_CHK_ACCESS(nsi)->exited;
+	mutex_unlock(nsinfo__lock(nsi));
+	if (exited)
+		return false;
+
+	scnprintf(spath, sizeof(spath), "/proc/%d/task/%d/status",
+		  nsinfo__pid(nsi), nsinfo__tid(nsi));
+	if (nsinfo__get_nspid(&tgid, &nstgid, &in_pidns, spath) < 0 ||
+	    tgid != nsinfo__pid(nsi)) {
+		nsinfo__set_exited(nsi);
+		return false;
+	}
+
+	return true;
+}
+
 pid_t nsinfo__tgid(const struct nsinfo *nsi)
 {
 	pid_t ret;
@@ -349,6 +417,8 @@ void nsinfo__mountns_enter(struct nsinfo *nsi,
 {
 	char curpath[PATH_MAX];
 	char *mntns_path = NULL;
+	ino_t mntns_ino = 0;
+	struct stat st;
 	int oldns = -1;
 	int newns = -1;
 	char *oldcwd = NULL;
@@ -358,19 +428,26 @@ void nsinfo__mountns_enter(struct nsinfo *nsi,
 
 	nc->oldns = -1;
 	nc->newns = -1;
+	nc->oldcwd = NULL;
 
 	if (!nsi)
 		return;
 
 	mutex_lock(&RC_CHK_ACCESS(nsi)->lock);
 	nsinfo__ensure_init_locked(nsi);
-	if (RC_CHK_ACCESS(nsi)->need_setns && RC_CHK_ACCESS(nsi)->mntns_path)
+	if (!RC_CHK_ACCESS(nsi)->exited && RC_CHK_ACCESS(nsi)->need_setns &&
+	    RC_CHK_ACCESS(nsi)->mntns_path) {
 		mntns_path = strdup(RC_CHK_ACCESS(nsi)->mntns_path);
+		mntns_ino = RC_CHK_ACCESS(nsi)->mntns_ino;
+	}
 	mutex_unlock(&RC_CHK_ACCESS(nsi)->lock);
 
 	if (!mntns_path)
 		return;
 
+	if (!nsinfo__check_proc(nsi))
+		goto out;
+
 	if (!getcwd(curpath, sizeof(curpath)))
 		goto out;
 
@@ -378,14 +455,19 @@ void nsinfo__mountns_enter(struct nsinfo *nsi,
 	if (!oldcwd)
 		goto out;
 
-	oldns = open("/proc/self/ns/mnt", O_RDONLY);
+	oldns = open("/proc/self/ns/mnt", O_RDONLY | O_CLOEXEC);
 	if (oldns < 0)
 		goto errout;
 
-	newns = open(mntns_path, O_RDONLY);
+	newns = open(mntns_path, O_RDONLY | O_CLOEXEC);
 	if (newns < 0)
 		goto errout;
 
+	if (fstat(newns, &st) < 0 || st.st_ino != mntns_ino) {
+		nsinfo__clear_need_setns(nsi);
+		goto errout;
+	}
+
 	if (setns(newns, CLONE_NEWNS) < 0)
 		goto errout;
 
@@ -407,17 +489,11 @@ void nsinfo__mountns_enter(struct nsinfo *nsi,
 
 void nsinfo__mountns_exit(struct nscookie *nc)
 {
-	if (nc == NULL || nc->oldns == -1 || nc->newns == -1 || !nc->oldcwd)
+	if (nc == NULL || !nc->oldcwd)
 		return;
 
-	setns(nc->oldns, CLONE_NEWNS);
-
-	if (nc->oldcwd) {
-		WARN_ON_ONCE(chdir(nc->oldcwd));
-		zfree(&nc->oldcwd);
-	}
-
 	if (nc->oldns > -1) {
+		setns(nc->oldns, CLONE_NEWNS);
 		close(nc->oldns);
 		nc->oldns = -1;
 	}
@@ -426,6 +502,11 @@ void nsinfo__mountns_exit(struct nscookie *nc)
 		close(nc->newns);
 		nc->newns = -1;
 	}
+
+	if (nc->oldcwd) {
+		WARN_ON_ONCE(chdir(nc->oldcwd));
+		zfree(&nc->oldcwd);
+	}
 }
 
 char *nsinfo__realpath(const char *path, struct nsinfo *nsi)
tools/perf/util/namespaces.h +4 -0
index 42dcca13b002f153..7bba217aa3fde3d7 100644
@@ -37,7 +37,9 @@ DECLARE_RC_STRUCT(nsinfo) {
 	pid_t			tid;
 	pid_t			tgid;
 	pid_t			nstgid;
+	ino_t			mntns_ino;
 	bool			inited;
+	bool			exited;
 	bool			need_setns;
 	bool			in_pidns;
 	char			*mntns_path;
@@ -60,6 +62,8 @@ void nsinfo__put(struct nsinfo *nsi);
 
 bool nsinfo__need_setns(const struct nsinfo *nsi);
 void nsinfo__clear_need_setns(struct nsinfo *nsi);
+void nsinfo__set_exited(struct nsinfo *nsi);
+bool nsinfo__check_proc(struct nsinfo *nsi);
 pid_t nsinfo__tgid(const struct nsinfo  *nsi);
 pid_t nsinfo__nstgid(const struct nsinfo  *nsi);
 pid_t nsinfo__pid(const struct nsinfo  *nsi);
Signature · 1 line
2.56.0.611.g1030f0b940-goog
#12 lore raw

Re: [PATCH v2 06/11] perf tools: Verify thread status and mount namespace inode

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] perf namespaces: nsinfo__init_locked() returns 0 when stat() fails --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] perf namespaces: nsinfo__init_locked() returns 0 when stat() fails
--

commit e6cbb7bd6fc00579ed776b5b31e5e5cfe0cc41a2
Author: Namhyung Kim <[email protected]>

perf tools: Verify thread status and mount namespace inode

This commit verifies that /proc/<pid>/task/<tid>/status exists with a matching Tgid and checks the mount namespace inode via fstat() before entering a thread's mount namespace.

Quoted 4 lines
tools/perf/util/namespaces.c +0 -0
index afd8ad7f843ec..860b90e8384ed 100644

[ ... ]

Quoted 55 lines
tools/perf/util/namespaces.c +28 -5
@@ -101,16 +116,41 @@ static int nsinfo__init_locked(struct nsinfo *nsi)
 	char *newns = NULL;
 	struct stat old_stat;
 	struct stat new_stat;
+	pid_t tgid = 0, nstgid = 0;
+	bool in_pidns = false;
 	int rv = -1;
 
+	if (RC_CHK_ACCESS(nsi)->exited)
+		return -1;
+
 	RC_CHK_ACCESS(nsi)->inited = true;
 
+	/*
+	 * Verify that the thread (pid, tid) still exists in /proc and its Tgid
+	 * matches pid (guarding against PID/TID recycling), while resolving the
+	 * innermost tgid if the process is in a different PID namespace.
+	 */
+	if (snprintf(spath, PATH_MAX, "/proc/%d/task/%d/status",
+		     nsinfo__pid(nsi), nsinfo__tid(nsi)) >= PATH_MAX)
+		goto out;
+
+	rv = nsinfo__get_nspid(&tgid, &nstgid, &in_pidns, spath);
+	if (rv < 0 || tgid != nsinfo__pid(nsi)) {
+		nsinfo__set_exited_locked(nsi);
+		rv = -1;
+		goto out;
+	}
+
+	RC_CHK_ACCESS(nsi)->tgid = tgid;
+	RC_CHK_ACCESS(nsi)->nstgid = nstgid;
+	RC_CHK_ACCESS(nsi)->in_pidns = in_pidns;
+
 	if (snprintf(oldns, PATH_MAX, "/proc/self/ns/mnt") >= PATH_MAX)
-		return rv;
+		return -1;
 
 	if (asprintf(&newns, "/proc/%d/task/%d/ns/mnt",
 		     nsinfo__pid(nsi), nsinfo__tid(nsi)) == -1)
-		return rv;
+		return -1;
 
 	if (stat(oldns, &old_stat) < 0)
 		goto out;
@@ -124,19 +164,10 @@ static int nsinfo__init_locked(struct nsinfo *nsi)
 	if (old_stat.st_ino != new_stat.st_ino) {
 		RC_CHK_ACCESS(nsi)->need_setns = true;
 		RC_CHK_ACCESS(nsi)->mntns_path = newns;
+		RC_CHK_ACCESS(nsi)->mntns_ino = new_stat.st_ino;
 		newns = NULL;
 	}
 
-	/* If we're dealing with a process that is in a different PID namespace,
-	 * attempt to work out the innermost tgid for the process.
-	 */

tools/perf/util/namespaces.c static int nsinfo__init_locked(struct nsinfo *nsi) · line 173

Quoted 10 lines
tools/perf/util/namespaces.c +0 -7
-	if (snprintf(spath, PATH_MAX, "/proc/%d/task/%d/status",
-		     nsinfo__pid(nsi), nsinfo__tid(nsi)) >= PATH_MAX)
-		goto out;
-
-	rv = nsinfo__get_nspid(&RC_CHK_ACCESS(nsi)->tgid, &RC_CHK_ACCESS(nsi)->nstgid,
-			       &RC_CHK_ACCESS(nsi)->in_pidns, spath);
-
 out:
 	free(newns);
 	return rv;

[Severity: Low]
Does nsinfo__init_locked() return 0 instead of -1 when stat() fails?

Moving nsinfo__get_nspid() ahead of the stat() checks sets rv to 0 on success. If stat(newns, &new_stat) then fails (for example with EACCES because /proc/<pid>/task/<tid>/ns/mnt requires PTRACE_MODE_READ_FSCREDS while status is world-readable), jumping to out returns 0 to callers of nsinfo__init().

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
author maintainer
#13 lore raw

PATCH v2 7/11 perf tools: Check thread liveness when accessing /proc

In reply to Namhyung Kim

Add thread__exited() and thread__is_alive(), and mark threads as exited on PERF_RECORD_EXIT, replaced parent and child threads on PERF_RECORD_FORK, and perf_event__exit_del_thread().

Propagate thread exit and boot ID mismatch to thread->nsinfo, guard /proc accesses with thread__is_alive() and nsinfo__check_proc() (for dso__filename_with_chroot()), and avoid synthesizing a live parent thread in thread__e_machine_endian() when a sub-thread is no longer alive.

---
 tools/perf/builtin-trace.c |  2 +-
 tools/perf/util/dso.c      |  7 +++-
 tools/perf/util/event.c    |  1 +
 tools/perf/util/machine.c  | 17 +++++++---
 tools/perf/util/thread.c   | 65 +++++++++++++++++++++++++++++++++++---
 tools/perf/util/thread.h   |  7 ++--
 6 files changed, 86 insertions(+), 13 deletions(-)
tools/perf/builtin-trace.c +1 -1
index 4094141461f91c32..a21bbf5926617633 100644
@@ -1858,7 +1858,7 @@ static const char *thread__fd_path(struct thread *thread, int fd,
 		return NULL;
 
 	if ((fd > ttrace->files.max || ttrace->files.table[fd].pathname == NULL)) {
-		if (!trace->live)
+		if (!trace->live || !thread__is_alive(thread))
 			return NULL;
 		++trace->stats.proc_getname;
 		if (thread__read_fd_path(thread, fd))
tools/perf/util/dso.c +6 -1
index e46cd614eb21184b..36e6c45dd0383073 100644
@@ -587,7 +587,12 @@ static int do_open(char *name) EXCLUSIVE_LOCKS_REQUIRED(_dso__data_open_lock)
 
 char *dso__filename_with_chroot(const struct dso *dso, const char *filename)
 {
-	return filename_with_chroot(nsinfo__pid(dso__nsinfo_const(dso)), filename);
+	struct nsinfo *nsi = (struct nsinfo *)dso__nsinfo_const(dso);
+
+	if (!nsinfo__check_proc(nsi))
+		return NULL;
+
+	return filename_with_chroot(nsinfo__pid(nsi), filename);
 }
 
 char *dso__get_filename(struct dso *dso, const char *root_dir, bool *decomp,
tools/perf/util/event.c +1 -0
index 2f80e364659fea71..ae0ebda42fa47e8c 100644
@@ -447,6 +447,7 @@ int perf_event__exit_del_thread(const struct perf_tool *tool __maybe_unused,
 		    event->fork.ppid, event->fork.ptid);
 
 	if (thread) {
+		thread__set_exited(thread, /*exited=*/true);
 		machine__remove_thread(machine, thread);
 		thread__put(thread);
 	}
tools/perf/util/machine.c +12 -5
index ac857b395882f569..53cda0046d24799c 100644
@@ -517,8 +517,14 @@ static void machine__update_thread_pid(struct machine *machine,
 		return;
 
 	thread__set_pid(th, pid);
-	nsinfo__zput(RC_CHK_ACCESS(th)->nsinfo);
-	RC_CHK_ACCESS(th)->nsinfo = nsinfo__new_thread(pid, thread__tid(th));
+	thread__reset_nsinfo(th);
+	if (thread__exited(th) || !machine__is_host(machine) ||
+	    !perf_env__is_same_boot(machine->env)) {
+		struct nsinfo *nsi = thread__get_nsinfo(th);
+
+		nsinfo__set_exited(nsi);
+		nsinfo__put(nsi);
+	}
 
 	if (thread__pid(th) == thread__tid(th))
 		return;
@@ -1975,6 +1981,7 @@ int machine__process_fork_event(struct machine *machine, union perf_event *event
 	    thread__pid(parent) != (pid_t)event->fork.ppid) {
 		dump_printf("removing erroneous parent thread %d/%d\n",
 			    thread__pid(parent), thread__tid(parent));
+		thread__set_exited(parent, /*exited=*/true);
 		machine__remove_thread(machine, parent);
 		thread__put(parent);
 		parent = machine__findnew_thread(machine, event->fork.ppid,
@@ -1983,6 +1990,7 @@ int machine__process_fork_event(struct machine *machine, union perf_event *event
 
 	/* if a thread currently exists for the thread id remove it */
 	if (thread != NULL) {
+		thread__set_exited(thread, /*exited=*/true);
 		machine__remove_thread(machine, thread);
 		thread__put(thread);
 	}
@@ -2030,9 +2038,8 @@ int machine__process_exit_event(struct machine *machine, union perf_event *event
 	/* There is no context switch out before exit, so we decrement here. */
 	machine->parallelism--;
 	if (thread != NULL) {
-		if (symbol_conf.keep_exited_threads)
-			thread__set_exited(thread, /*exited=*/true);
-		else
+		thread__set_exited(thread, /*exited=*/true);
+		if (!symbol_conf.keep_exited_threads)
 			machine__remove_thread(machine, thread);
 	}
 	thread__put(thread);
tools/perf/util/thread.c +61 -4

102 lines not on this page · raw message

tools/perf/util/thread.h +5 -2
index 36f2932422df8988..927b2ddccfc8433d 100644
@@ -205,11 +205,14 @@ static inline refcount_t *thread__refcnt(struct thread *thread)
 	return &RC_CHK_ACCESS(thread)->refcnt;
 }
 
-static inline void thread__set_exited(struct thread *thread, bool exited)
+static inline bool thread__exited(const struct thread *thread)
 {
-	RC_CHK_ACCESS(thread)->exited = exited;
+	return RC_CHK_ACCESS(thread)->exited;
 }
 
+void thread__set_exited(struct thread *thread, bool exited);
+bool thread__is_alive(struct thread *thread);
+
 static inline bool thread__comm_set(const struct thread *thread)
 {
 	return RC_CHK_ACCESS(thread)->comm_set;
Signature · 1 line
2.56.0.611.g1030f0b940-goog
#14 lore raw

Re: [PATCH v2 07/11] perf tools: Check thread liveness when accessing /proc

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] perf tools: nsinfo__check_proc() in dso__filename_with_chroot() inside mntns - [Medium] perf…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] perf tools: nsinfo__check_proc() in dso__filename_with_chroot() inside mntns
- [Medium] perf tools: thread__init_maps() marks pipe-mode threads exited in perf inject
--

commit e4d060b6fbe7a9b1256d33ec34cd9b157fb2e968
Author: Namhyung Kim <[email protected]>

perf tools: Check thread liveness when accessing /proc

This commit adds thread__exited() and thread__is_alive() to track thread liveness and propagates thread exit and boot ID mismatches to nsinfo so /proc accesses can be skipped for exited or offline threads.

Quoted 6 lines
tools/perf/util/dso.c +0 -0
index ce98613868e7d..0a3e40aeadbbb 100644
@@ -587,7 +587,12 @@ static int do_open(char *name) EXCLUSIVE_LOCKS_REQUIRED(_dso__data_open_lock)
 

tools/perf/util/dso.c static int do_open(char *name) EXCLUSIVE_LOCKS_REQUIRED(_dso__data_open_lock) · line 596

Quoted 10 lines
tools/perf/util/dso.c +6 -1
 char *dso__filename_with_chroot(const struct dso *dso, const char *filename)
 {
-	return filename_with_chroot(nsinfo__pid(dso__nsinfo_const(dso)), filename);
+	struct nsinfo *nsi = (struct nsinfo *)dso__nsinfo_const(dso);
+
+	if (!nsinfo__check_proc(nsi))
+		return NULL;
+
+	return filename_with_chroot(nsinfo__pid(nsi), filename);
 }

[Severity: Medium]
Can calling nsinfo__check_proc(nsi) here mark a live container thread's nsinfo as exited when dso__filename_with_chroot() runs inside the container's mount namespace?

dso__load() and dso__get_filename() call dso__filename_with_chroot() between nsinfo__mountns_enter() and nsinfo__mountns_exit(). When dso__load() probes distro debuginfo paths that do not exist before reaching DSO_BINARY_TYPE__SYSTEM_PATH_DSO, nsinfo__check_proc() looks up /proc/<host_pid>/task/<host_tid>/status inside the container's mount namespace. If the container has its own /proc mount for a PID namespace, that host PID lookup fails or matches a different task, so nsinfo__check_proc() calls nsinfo__set_exited(nsi). Because dso->nsinfo is shared with thread->nsinfo, this clears need_setns and breaks subsequent mount namespace entry and DSO loading for the live thread.

Quoted 10 lines
tools/perf/util/thread.c +2 -0
index 5d1c886add3e6..fda718ea5d7e6 100644
@@ -37,6 +37,16 @@ int thread__init_maps(struct thread *thread, struct machine *machine)
 		}
 	}
 
+	if (thread__pid(thread) != 0 || thread__tid(thread) != 0) {
+		if (!machine || !machine__is_host(machine) ||

tools/perf/util/thread.c int thread__init_maps(struct thread *thread, struct machine *machine) · line 51

Quoted 10 lines
tools/perf/util/thread.c +8 -0
+		    !perf_env__is_same_boot(machine->env)) {
+			struct nsinfo *nsi = thread__get_nsinfo(thread);
+
+			nsinfo__set_exited(nsi);
+			nsinfo__put(nsi);
+		}
+	}
+
 	return thread__maps(thread) ? 0 : -1;
 }

[Severity: Medium]
Does checking !perf_env__is_same_boot(machine->env) here (and in __thread__reset_nsinfo(), thread__is_alive(), and machine__update_thread_pid()) mark all threads as exited during live pipe-mode sessions such as "perf record -o - | perf inject -b"?

When __perf_session__new() opens a read-mode pipe, it sets session->header.env.offline = true and perf_session__read_header() returns before reading any feature records. In cmd_inject(), inject.tool.feature is set to perf_event__repipe_op2_synth rather than perf_event__process_feature(), so HEADER_BOOT_ID is never populated in machine->env->boot_id. perf_env__is_same_boot(machine->env) then returns false for every thread, disabling mount namespace entry, chroot resolution, and /proc lookups during pipe-mode build-id and JIT injection.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
author maintainer
#15 lore raw

PATCH v2 8/11 perf tools: Export filename__read_build_id_ns()

In reply to Namhyung Kim

Export filename__read_build_id_ns(), including a chroot fallback guarded by nsinfo__check_proc(), and use it in the dsos callback and perf-inject's dso__read_build_id() instead of open-coding nsinfo__mountns_enter() and dso__filename_with_chroot() fallbacks.

---
 tools/perf/builtin-inject.c | 12 +-----------
 tools/perf/util/build-id.c  | 14 +++++++++++---
 tools/perf/util/dsos.c      | 17 +++--------------
 tools/perf/util/symbol.h    |  3 +++
 4 files changed, 18 insertions(+), 28 deletions(-)
tools/perf/builtin-inject.c +1 -11
index 05bf1aae61778952..71ebb5b9ab84cbf7 100644
@@ -894,24 +894,14 @@ static int perf_event__repipe_tracing_data(const struct perf_tool *tool,
 
 static int dso__read_build_id(struct dso *dso)
 {
-	struct nscookie nsc;
 	struct build_id bid = { .size = 0, };
 
 	if (dso__has_build_id(dso))
 		return 0;
 
 	mutex_lock(dso__lock(dso));
-	nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
-	if (filename__read_build_id(dso__long_name(dso), &bid) > 0)
+	if (filename__read_build_id_ns(dso__long_name(dso), &bid, dso__nsinfo(dso)) > 0)
 		dso__set_build_id(dso, &bid);
-	else if (dso__nsinfo(dso)) {
-		char *new_name = dso__filename_with_chroot(dso, dso__long_name(dso));
-
-		if (new_name && filename__read_build_id(new_name, &bid) > 0)
-			dso__set_build_id(dso, &bid);
-		free(new_name);
-	}
-	nsinfo__mountns_exit(&nsc);
 	mutex_unlock(dso__lock(dso));
 
 	return dso__has_build_id(dso) ? 0 : -1;
tools/perf/util/build-id.c +11 -3
index 02233ef0eafff2c2..ff083a594b405208 100644
@@ -847,15 +847,23 @@ int build_id_cache__remove_s(const char *sbuild_id)
 	return err;
 }
 
-static int filename__read_build_id_ns(const char *filename,
-				      struct build_id *bid,
-				      struct nsinfo *nsi)
+int filename__read_build_id_ns(const char *filename,
+			       struct build_id *bid,
+			       struct nsinfo *nsi)
 {
 	struct nscookie nsc;
 	int ret;
 
 	nsinfo__mountns_enter(nsi, &nsc);
 	ret = filename__read_build_id(filename, bid);
+	if (ret < 0 && errno == ENOENT && nsinfo__check_proc(nsi)) {
+		char *new_name = filename_with_chroot(nsinfo__pid(nsi), filename);
+
+		if (new_name) {
+			ret = filename__read_build_id(new_name, bid);
+			free(new_name);
+		}
+	}
 	nsinfo__mountns_exit(&nsc);
 
 	return ret;
tools/perf/util/dsos.c +3 -14
index e927e707abace9c6..a97fed55286aefca 100644
@@ -4,11 +4,11 @@
 #include "dso.h"
 #include "util.h"
 #include "vdso.h"
-#include "namespaces.h"
 #include <errno.h>
+#include <linux/perf_event.h>
 #include <stdlib.h>
 #include <string.h>
-#include <symbol.h> // filename__read_build_id
+#include <symbol.h> // filename__read_build_id_ns
 #include <unistd.h>
 
 void dsos__init(struct dsos *dsos)
@@ -70,7 +70,6 @@ struct dsos__read_build_ids_cb_args {
 static int dsos__read_build_ids_cb(struct dso *dso, void *data)
 {
 	struct dsos__read_build_ids_cb_args *args = data;
-	struct nscookie nsc;
 	struct build_id bid = { .size = 0, };
 
 	if (args->with_hits && !dso__hit(dso) && !dso__is_vdso(dso))
@@ -79,20 +78,10 @@ static int dsos__read_build_ids_cb(struct dso *dso, void *data)
 		args->have_build_id = true;
 		return 0;
 	}
-	nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
-	if (filename__read_build_id(dso__long_name(dso), &bid) > 0) {
+	if (filename__read_build_id_ns(dso__long_name(dso), &bid, dso__nsinfo(dso)) > 0) {
 		dso__set_build_id(dso, &bid);
 		args->have_build_id = true;
-	} else if (errno == ENOENT && dso__nsinfo(dso)) {
-		char *new_name = dso__filename_with_chroot(dso, dso__long_name(dso));
-
-		if (new_name && filename__read_build_id(new_name, &bid) > 0) {
-			dso__set_build_id(dso, &bid);
-			args->have_build_id = true;
-		}
-		free(new_name);
 	}
-	nsinfo__mountns_exit(&nsc);
 	return 0;
 }
 
tools/perf/util/symbol.h +3 -0
index 6347bd218ad5eac4..7ac362b5d53530b0 100644
@@ -28,6 +28,7 @@
 struct dso;
 struct map;
 struct maps;
+struct nsinfo;
 struct option;
 struct build_id;
 struct perf_env;
@@ -211,6 +212,8 @@ struct symbol *dso__next_symbol(struct symbol *sym);
 enum dso_type dso__type_fd(int fd);
 
 int filename__read_build_id(const char *filename, struct build_id *id);
+int filename__read_build_id_ns(const char *filename, struct build_id *bid,
+			       struct nsinfo *nsi);
 int sysfs__read_build_id(const char *filename, struct build_id *bid);
 int modules__parse(const char *filename, void *arg,
 		   int (*process_module)(void *arg, const char *name,
Signature · 1 line
2.56.0.611.g1030f0b940-goog
#16 lore raw

Re: [PATCH v2 08/11] perf tools: Export filename__read_build_id_ns()

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] perf build-id: filename__read_build_id_ns() checks host /proc inside mountns --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] perf build-id: filename__read_build_id_ns() checks host /proc inside mountns
--

commit 32054987b7b4b030ff39e7d9b8a53cb7044261a7
Author: Namhyung Kim <[email protected]>

perf tools: Export filename__read_build_id_ns()

This commit exports filename__read_build_id_ns() with a chroot fallback and uses it in dsos__read_build_ids_cb() and perf-inject's dso__read_build_id().

Quoted 19 lines
tools/perf/util/build-id.c +3 -3
index 02233ef0eafff..ff083a594b405 100644
@@ -847,15 +847,23 @@ int build_id_cache__remove_s(const char *sbuild_id)
 	return err;
 }
 
-static int filename__read_build_id_ns(const char *filename,
-				      struct build_id *bid,
-				      struct nsinfo *nsi)
+int filename__read_build_id_ns(const char *filename,
+			       struct build_id *bid,
+			       struct nsinfo *nsi)
 {
 	struct nscookie nsc;
 	int ret;
 
 	nsinfo__mountns_enter(nsi, &nsc);

tools/perf/util/build-id.c int build_id_cache__remove_s(const char *sbuild_id) · line 867

Quoted 10 lines
tools/perf/util/build-id.c +8 -0
 	ret = filename__read_build_id(filename, bid);
+	if (ret < 0 && errno == ENOENT && nsinfo__check_proc(nsi)) {
+		char *new_name = filename_with_chroot(nsinfo__pid(nsi), filename);
+
+		if (new_name) {
+			ret = filename__read_build_id(new_name, bid);
+			free(new_name);
+		}
+	}
 	nsinfo__mountns_exit(&nsc);

[Severity: Medium]
Does calling nsinfo__check_proc() and filename_with_chroot() before nsinfo__mountns_exit() look up the host PID in the target mount namespace's /proc?

When profiling a container with its own PID namespace and /proc mount, any ENOENT from filename__read_build_id() (for example on [heap] or a deleted binary) causes nsinfo__check_proc() to inspect /proc/<host_pid>/task/<host_tid>/status inside the container's /proc:

tools/perf/util/namespaces.c:nsinfo__check_proc() {
    ...
	scnprintf(spath, sizeof(spath), "/proc/%d/task/%d/status",
		  nsinfo__pid(nsi), nsinfo__tid(nsi));
	if (nsinfo__get_nspid(&tgid, &nstgid, &in_pidns, spath) < 0 ||
	    tgid != nsinfo__pid(nsi)) {
		nsinfo__set_exited(nsi);
		return false;
	}
    ...
}

Because the host PID is absent or belongs to a different process there, nsinfo__check_proc() calls nsinfo__set_exited(nsi), clearing need_setns and freeing mntns_path on the shared struct nsinfo, which disables mount namespace entry for subsequent DSOs of that thread. Moving nsinfo__mountns_exit(&nsc) before the fallback (or resolving new_name in the host mount namespace) would avoid this.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
author maintainer
#17 lore raw

PATCH v2 9/11 perf tools: Only enter mount namespace if necessary

In reply to Namhyung Kim

Add dso_binary_type__needs_ns() to distinguish DSO binary and debuginfo types that reside inside the target process's mount namespace from host-side paths.

Gate mount namespace entry in open_dso(), dso__find_binary_type_locked(), dso__find_dbginfo_type(), __dso__read_symbol(), debuginfo__new(), symbol__disassemble(), and symbol__disassemble_capstone_powerpc() using dso_binary_type__needs_ns().

---
 tools/perf/util/capstone.c  |  8 ++++--
 tools/perf/util/debuginfo.c | 19 +++++++++-----
 tools/perf/util/disasm.c    |  8 +++++-
 tools/perf/util/dso.c       | 52 ++++++++++++++++++++++++++++++-------
 tools/perf/util/dso.h       | 34 ++++++++++++++++++++++++
 5 files changed, 102 insertions(+), 19 deletions(-)
tools/perf/util/capstone.c +6 -2
index 95881f15324aa614..e1de77879c5e5f97 100644
@@ -649,13 +649,17 @@ int symbol__disassemble_capstone_powerpc(const char *filename __maybe_unused,
 	bool disassembler_style = false;
 	uint16_t e_machine = EM_NONE;
 	bool is_big_endian = false;
+	bool nsenter;
 
 	if (args->options->objdump_path)
 		return -1;
 
-	nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
+	nsenter = dso_binary_type__needs_ns(dso__binary_type(dso));
+	if (nsenter)
+		nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
 	fd = open(filename, O_RDONLY);
-	nsinfo__mountns_exit(&nsc);
+	if (nsenter)
+		nsinfo__mountns_exit(&nsc);
 	if (fd < 0)
 		return -1;
 
tools/perf/util/debuginfo.c +13 -6
index db188c397d63880c..d339906c28b41425 100644
@@ -17,6 +17,7 @@
 #include "dso.h"
 #include "debug.h"
 #include "debuginfo.h"
+#include "namespaces.h"
 #include "symbol.h"
 
 #ifdef HAVE_DEBUGINFOD_SUPPORT
@@ -93,17 +94,23 @@ static struct debuginfo *__debuginfo__new(const char *path)
 
 struct debuginfo *debuginfo__new(struct dso *dso)
 {
-	struct debuginfo *dinfo;
+	struct debuginfo *dinfo = NULL;
+	struct nscookie nsc;
 	char *path;
 	bool decomp = false;
+	bool nsenter;
 
 	dso__find_dbginfo_type(dso);
+	nsenter = dso_binary_type__needs_ns(dso__dbginfo_type(dso));
+	if (nsenter)
+		nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
 	path = dso__get_filename(dso, "", &decomp, dso__dbginfo_type(dso));
-	if (path == NULL)
-		return NULL;
-
-	dinfo = __debuginfo__new(path);
-	dso__put_filename(dso, path, decomp);
+	if (path != NULL) {
+		dinfo = __debuginfo__new(path);
+		dso__put_filename(dso, path, decomp);
+	}
+	if (nsenter)
+		nsinfo__mountns_exit(&nsc);
 	return dinfo;
 }
 
tools/perf/util/disasm.c +7 -1
index ca478191813cf46f..5b9bc94be55ef088 100644
@@ -1499,7 +1499,8 @@ int symbol__disassemble(struct symbol *sym, struct annotate_args *args)
 	bool delete_extract = false;
 	struct kcore_extract kce;
 	enum dso_binary_type dbt;
-	bool decomp = false;
+	struct nscookie nsc;
+	bool decomp = false, nsenter;
 	int err;
 
 	dbt = dso__find_binary_type(dso);
@@ -1507,8 +1508,13 @@ int symbol__disassemble(struct symbol *sym, struct annotate_args *args)
 	if (dbt == DSO_BINARY_TYPE__KALLSYMS)
 		return SYMBOL_ANNOTATE_ERRNO__NO_VMLINUX;
 
+	nsenter = dso_binary_type__needs_ns(dbt);
 	mutex_lock(dso__lock(dso));
+	if (nsenter)
+		nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
 	symfs_filename = dso__get_filename(dso, "", &decomp, dbt);
+	if (nsenter)
+		nsinfo__mountns_exit(&nsc);
 	mutex_unlock(dso__lock(dso));
 
 	if (symfs_filename == NULL) {
tools/perf/util/dso.c +42 -10

124 lines not on this page · raw message

tools/perf/util/dso.h +34 -0
index d5f7382d4e13a371..7cac0960e1a6dd32 100644
@@ -141,6 +141,40 @@ enum dso_binary_type {
 	DSO_BINARY_TYPE__NOT_FOUND,
 };
 
+static inline bool dso_binary_type__needs_ns(enum dso_binary_type type)
+{
+	switch (type) {
+	case DSO_BINARY_TYPE__SYSTEM_PATH_DSO:
+	case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE:
+	case DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE_COMP:
+	case DSO_BINARY_TYPE__DEBUGLINK:
+	case DSO_BINARY_TYPE__GNU_DEBUGDATA:
+	case DSO_BINARY_TYPE__FEDORA_DEBUGINFO:
+	case DSO_BINARY_TYPE__UBUNTU_DEBUGINFO:
+	case DSO_BINARY_TYPE__MIXEDUP_UBUNTU_DEBUGINFO:
+	case DSO_BINARY_TYPE__BUILDID_DEBUGINFO:
+	case DSO_BINARY_TYPE__OPENEMBEDDED_DEBUGINFO:
+		return true;
+	case DSO_BINARY_TYPE__KALLSYMS:
+	case DSO_BINARY_TYPE__GUEST_KALLSYMS:
+	case DSO_BINARY_TYPE__VMLINUX:
+	case DSO_BINARY_TYPE__GUEST_VMLINUX:
+	case DSO_BINARY_TYPE__JAVA_JIT:
+	case DSO_BINARY_TYPE__BUILD_ID_CACHE:
+	case DSO_BINARY_TYPE__BUILD_ID_CACHE_DEBUGINFO:
+	case DSO_BINARY_TYPE__GUEST_KMODULE:
+	case DSO_BINARY_TYPE__GUEST_KMODULE_COMP:
+	case DSO_BINARY_TYPE__KCORE:
+	case DSO_BINARY_TYPE__GUEST_KCORE:
+	case DSO_BINARY_TYPE__BPF_PROG_INFO:
+	case DSO_BINARY_TYPE__BPF_IMAGE:
+	case DSO_BINARY_TYPE__OOL:
+	case DSO_BINARY_TYPE__NOT_FOUND:
+	default:
+		return false;
+	}
+}
+
 enum dso_space_type {
 	DSO_SPACE__USER = 0,
 	DSO_SPACE__KERNEL,
Signature · 1 line
2.56.0.611.g1030f0b940-goog
#18 lore raw

Re: [PATCH v2 09/11] perf tools: Only enter mount namespace if necessary

Sashiko has reviewed this patch and found no issues.
Quoted 10 lines

Add dso_binary_type__needs_ns() to distinguish DSO binary and debuginfo types that reside inside the target process's mount namespace from host-side paths.

Gate mount namespace entry in open_dso(), dso__find_binary_type_locked(), dso__find_dbginfo_type(), __dso__read_symbol(), debuginfo__new(), symbol__disassemble(), and symbol__disassemble_capstone_powerpc() using dso_binary_type__needs_ns().

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
author maintainer
#19 lore raw

PATCH v2 10/11 perf tools: Scope mount namespace entry in dso__load()

In reply to Namhyung Kim

Enter the target mount namespace only for the specific binary types that need it in dso__load(), and use filename__read_build_id_ns() for BUILDID_DEBUGINFO lookup and in symbol-minimal's dso__load_sym() so it does not read the wrong build-id from the host filesystem.

---
 tools/perf/util/symbol-minimal.c |  4 ++-
 tools/perf/util/symbol.c         | 45 +++++++++++++++-----------------
 2 files changed, 24 insertions(+), 25 deletions(-)
tools/perf/util/symbol-minimal.c +3 -1
index 0a71d146395271a6..5beb73fd508ad079 100644
@@ -342,7 +342,9 @@ int dso__load_sym(struct dso *dso, struct map *map __maybe_unused,
 	if (ret >= 0)
 		RC_CHK_ACCESS(dso)->is_64_bit = ret;
 
-	if (filename__read_build_id(ss->name, &bid) > 0)
+	if (filename__read_build_id_ns(ss->name, &bid,
+				       dso_binary_type__needs_ns(ss->type) ?
+				       dso__nsinfo(dso) : NULL) > 0)
 		dso__set_build_id(dso, &bid);
 	return 0;
 }
tools/perf/util/symbol.c +21 -24

95 lines not on this page · raw message

Signature · 1 line
2.56.0.611.g1030f0b940-goog
#20 lore raw

Re: [PATCH v2 10/11] perf tools: Scope mount namespace entry in dso__load()

Sashiko has reviewed this patch and found no issues.
Quoted 6 lines

Enter the target mount namespace only for the specific binary types that need it in dso__load(), and use filename__read_build_id_ns() for BUILDID_DEBUGINFO lookup and in symbol-minimal's dso__load_sym() so it does not read the wrong build-id from the host filesystem.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
author maintainer
#21 lore raw

PATCH v2 11/11 perf tests: Add namespace, nsinfo, and boot ID tests

In reply to Namhyung Kim

Add a "Namespace and nsinfo tests" suite covering HEADER_BOOT_ID, perf_env__is_same_boot(), deferred /proc lookup, raw nsinfo__copy(), PID/TID recycling detection, thread exit and fork liveness tracking, dso_binary_type__needs_ns(), and isolated mountns and chroot resolution.

Also verify the boot ID header matches /proc/sys/kernel/random/boot_id in the perf header shell test for both file and pipe modes.

---
 tools/perf/tests/Build           |    1 +
 tools/perf/tests/builtin-test.c  |    1 +
 tools/perf/tests/namespaces.c    | 1035 ++++++++++++++++++++++++++++++
 tools/perf/tests/shell/header.sh |    9 +
 tools/perf/tests/tests.h         |    1 +
 5 files changed, 1047 insertions(+)
 create mode 100644 tools/perf/tests/namespaces.c
tools/perf/tests/Build +1 -0
index 5eebb2ec5ddefcfd..7f2e926eb0bc7674 100644
@@ -74,6 +74,7 @@ perf-test-y += hwmon_pmu.o
 perf-test-y += tool_pmu.o
 perf-test-y += subcmd-help.o
 perf-test-y += kallsyms-split.o
+perf-test-y += namespaces.o
 
 ifeq ($(SRCARCH),$(filter $(SRCARCH),x86 arm arm64 powerpc riscv))
 perf-test-$(CONFIG_DWARF_UNWIND) += dwarf-unwind.o
tools/perf/tests/builtin-test.c +1 -0
index 327483f96401b580..f3c041ff1acf0289 100644
@@ -192,6 +192,7 @@ static struct test_suite *generic_tests[] = {
 	&suite__util,
 	&suite__subcmd_help,
 	&suite__kallsyms_split,
+	&suite__namespaces,
 	NULL,
 };
 
tools/perf/tests/namespaces.c new file +1035 -0

1,035 lines not on this page · raw message

tools/perf/tests/shell/header.sh +9 -0
index e1628ac0a61401a7..ae3cd2b50d1c3437 100755
@@ -37,6 +37,7 @@ check_header_output() {
     "sibling (cores|dies|threads)"
     "sibling threads"
     "total memory"
+    "boot id"
   )
   for i in "${fields[@]}"
   do
@@ -46,6 +47,14 @@ check_header_output() {
       err=1
     fi
   done
+
+  if [ -r /proc/sys/kernel/random/boot_id ]; then
+    host_boot_id=$(tr -d '\n' < /proc/sys/kernel/random/boot_id)
+    if ! grep -q "boot id : ${host_boot_id}" "${script_output}"; then
+      echo "Failed to find matching host boot id ${host_boot_id} in output"
+      err=1
+    fi
+  fi
 }
 
 test_file() {
tools/perf/tests/tests.h +1 -0
index af822885890dda73..b75fc1ef1c13bdd2 100644
@@ -203,6 +203,7 @@ DECLARE_SUITE(util);
 DECLARE_SUITE(uncore_event_sorting);
 DECLARE_SUITE(subcmd_help);
 DECLARE_SUITE(kallsyms_split);
+DECLARE_SUITE(namespaces);
 
 /*
  * PowerPC and S390 do not support creation of instruction breakpoints using the
Signature · 1 line
2.56.0.611.g1030f0b940-goog
#22 lore raw

Re: [PATCH v2 11/11] perf tests: Add namespace, nsinfo, and boot ID tests

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider: - [Medium] perf tests: unlinked DSO triggers assert in run_mountns_and_chroot_tests() - [Low] perf tests: raw…

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider:
- [Medium] perf tests: unlinked DSO triggers assert in run_mountns_and_chroot_tests()
- [Low] perf tests: raw nsinfo pointer comparison in test__nsinfo_thread_liveness()
- [Low] perf tests: missing signal.h include in namespaces.c
- [Low] perf tests: TEST_ASSERT_VAL() skips cleanup in test__nsinfo_boot_id()
- [Low] perf tests: leaked thread ref on failure in test__nsinfo_thread_liveness()
- [Low] perf tests: leaked chroot path string on failure in namespaces.c
- [Low] perf tests: unchecked allocations in run_mountns_and_chroot_tests()
--

commit c5ab486958138682ed6911ecda820dca7b29d74d
Author: Namhyung Kim <[email protected]>

perf tests: Add namespace, nsinfo, and boot ID tests

This commit adds a unit test suite for namespaces, nsinfo, and boot ID handling, and extends the perf header shell test to verify the boot ID.

Quoted 13 lines
tools/perf/tests/namespaces.c new file +7 -0
new file mode 100644
index 0000000000000..cfc654db48f92
@@ -0,0 +1,1035 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <pthread.h>
+#include <sched.h>
+#include <stdbool.h>

tools/perf/tests/namespaces.c line 17

Quoted 10 lines
tools/perf/tests/namespaces.c new file +10 -0
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>

[Severity: Low]
run_mountns_and_chroot_tests() calls kill() with SIGKILL, so signal.h should be included explicitly rather than relying on transitive headers.

[ ... ]

Quoted 11 lines
tools/perf/tests/namespaces.c new file +11 -0
+static int test__nsinfo_boot_id(struct test_suite *test __maybe_unused,
+				int subtest __maybe_unused)
+{
+	struct perf_env live_env, off_env;
+	char host_boot_id[64];
+	const char *bid;
+	int ret = TEST_FAIL;
+
+	if (read_host_boot_id_str(host_boot_id, sizeof(host_boot_id)) < 0) {
+		pr_debug("SKIP: cannot read host boot_id from procfs\n");
+		return TEST_SKIP;

tools/perf/tests/namespaces.c line 74

Quoted 10 lines
tools/perf/tests/namespaces.c new file +10 -0
+	}
+
+	perf_env__init(&live_env);
+	perf_env__init(&off_env);
+
+	TEST_ASSERT_VAL("NULL env should match current host boot",
+			perf_env__is_same_boot(NULL));
+
+	TEST_ASSERT_VAL("live env should match current host boot",
+			perf_env__is_same_boot(&live_env));

[Severity: Low]
Does TEST_ASSERT_VAL() return TEST_FAIL directly and skip perf_env__exit() at the out label if either check fails? Jumping to out instead avoids leaking live_env.boot_id and leaving the perf_env locks undestroyed.

[ ... ]

Quoted 33 lines
tools/perf/tests/namespaces.c new file +33 -0
+	thread__e_machine_endian(off_sub, off_m, NULL, NULL);
+	if (machine__find_thread(off_m, self_pid, self_pid) != NULL) {
+		pr_debug("thread__e_machine_endian() unexpectedly recreated exited leader\n");
+		goto out;
+	}
+	machine__remove_thread(off_m, off_sub);
+	thread__put(off_sub);
+	off_sub = NULL;
+
+	/* Live thread tracking, reset on exec/namespaces, and exit propagation. */
+	th = machine__findnew_thread(live_m, self_pid, self_pid);
+	if (!th || !thread__is_alive(th)) {
+		pr_debug("current live thread reported as dead\n");
+		goto out;
+	}
+
+	nsi1 = thread__get_nsinfo(th);
+	if (!nsi1)
+		goto out;
+
+	if (__thread__set_comm(th, "execed", 1000, /*exec=*/true) != 0)
+		goto out;
+	nsi2 = thread__get_nsinfo(th);
+	if (!nsi2 || nsi2 == nsi1) {
+		pr_debug("exec did not replace thread->nsinfo\n");
+		goto out;
+	}
+
+	ns_ev = calloc(1, sizeof(*ns_ev) + sizeof(ns_ev->link_info[0]));
+	if (!ns_ev)
+		goto out;
+	ns_ev->nr_namespaces = 1;
+	if (thread__set_namespaces(th, 2000, ns_ev) != 0) {

tools/perf/tests/namespaces.c line 455

Quoted 10 lines
tools/perf/tests/namespaces.c new file +10 -0
+		free(ns_ev);
+		goto out;
+	}
+	free(ns_ev);
+
+	nsi3 = thread__get_nsinfo(th);
+	if (!nsi3 || nsi3 == nsi2) {
+		pr_debug("PERF_RECORD_NAMESPACES did not replace thread->nsinfo\n");
+		goto out;
+	}

[Severity: Low]
Should nsi2 == nsi1 and nsi3 == nsi2 use RC_CHK_EQUAL() instead of raw pointer equality?

Because struct nsinfo is declared with DECLARE_RC_STRUCT(nsinfo), each thread__get_nsinfo() call allocates a distinct wrapper pointer when built with REFCNT_CHECKING, so raw pointer equality will always evaluate to false even if thread->nsinfo was not replaced.

[ ... ]

Quoted 4 lines
tools/perf/tests/namespaces.c new file +4 -0
+	memset(&ev, 0, sizeof(ev));
+	ev.fork.header.type = PERF_RECORD_EXIT;
+	ev.fork.header.size = sizeof(ev.fork);
+	ev.fork.pid = self_pid;

tools/perf/tests/namespaces.c line 516

Quoted 10 lines
tools/perf/tests/namespaces.c new file +10 -0
+	ev.fork.tid = self_pid;
+	ev.fork.ppid = 1;
+	ev.fork.ptid = 1;
+	if (perf_event__exit_del_thread(&tool, &ev, &sample, live_m) != 0)
+		goto out;
+	if (!RC_CHK_ACCESS(del_nsi)->exited || nsinfo__check_proc(del_nsi) ||
+	    machine__find_thread(live_m, self_pid, self_pid) != NULL) {
+		pr_debug("perf_event__exit_del_thread() did not mark nsinfo exited\n");
+		goto out;
+	}

[Severity: Low]
Does calling machine__find_thread() directly in the if condition here and after thread__e_machine_endian() above leak a thread reference if a thread is found? machine__find_thread() returns a refcounted struct thread * that must be released with thread__put().

[ ... ]

tools/perf/tests/namespaces.c line 601

Quoted 12 lines
tools/perf/tests/namespaces.c new file +12 -0
+	/* Guarded chroot/build-id lookups must bail out immediately when exited. */
+	dso = dso__new("/bin/sh");
+	nsi = nsinfo__new_thread(getpid(), getpid());
+	if (!dso || !nsi)
+		goto out;
+	nsinfo__set_exited(nsi);
+	dso__set_nsinfo(dso, nsinfo__get(nsi));
+
+	if (dso__filename_with_chroot(dso, "/bin/sh") != NULL) {
+		pr_debug("dso__filename_with_chroot() did not respect exited nsinfo\n");
+		goto out;
+	}

[Severity: Low]
Does this leak the heap string returned by dso__filename_with_chroot() if the check fails (as well as in the exited chroot check in run_mountns_and_chroot_tests() below)?

[ ... ]

tools/perf/tests/namespaces.c line 818

Quoted 13 lines
tools/perf/tests/namespaces.c new file +13 -0
+	dso = dso__new(target_bin);
+	if (!dso) {
+		machine__exit(&machine);
+		goto out_wait;
+	}
+	dso__set_nsinfo(dso, nsinfo__get(nsi));
+#ifndef HAVE_LIBELF_SUPPORT
+	/* Without libelf, filename__has_section() cannot auto-detect binary_type. */
+	dso__set_binary_type(dso, DSO_BINARY_TYPE__SYSTEM_PATH_DSO);
+	dso__set_bintype_searched(dso);
+#endif
+	if (dso__data_read_offset(dso, &machine, 0, magic, sizeof(magic)) != sizeof(magic) ||
+	    memcmp(magic, "\x7f" "ELF", 4) != 0) {

[Severity: Medium]
Does calling dso__data_read_offset() on a standalone dso without adding it via dsos__add(&machine.dsos, dso) trigger an assertion failure in DEBUG=1 builds?

dso__data_read_offset() -> data_read_write_offset() -> dso__data_file_size() -> file_size() -> try_to_open_dso() -> open_dso() calls dso__list_add(dso), which asserts that dso__dsos(dso) is non-NULL:

tools/perf/util/dso.c:dso__list_add() {
    ...
	/* Assume the dso is part of dsos, hence the optional reference count above. */
	assert(dso__dsos(dso));
}

[ ... ]

tools/perf/tests/namespaces.c line 915

Quoted 7 lines
tools/perf/tests/namespaces.c new file +7 -0
+			if (cpid > 0 && read(cpipe[0], &sig, 1) == 1 && sig == '1') {
+				struct nsinfo *cnsi = nsinfo__new_thread(cpid, cpid);
+				struct stat st1, st2;
+				char *resolved = NULL;
+
+				chroot_dso = dso__new("/chroot_elf");
+				if (chroot_dso && cnsi) {

[Severity: Low]
If either nsinfo__new_thread() or dso__new() returns NULL here, does the test silently skip the chroot checks and still set ret = TEST_OK?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11