xref: /linux/tools/perf/util/thread.c (revision 390d5ea26622f794c2d29cefd5a01ef116b4fe1d)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <elf.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <linux/kernel.h>
9 #include <linux/zalloc.h>
10 #include "dso.h"
11 #include "session.h"
12 #include "thread.h"
13 #include "thread-stack.h"
14 #include "debug.h"
15 #include "namespaces.h"
16 #include "comm.h"
17 #include "map.h"
18 #include "symbol.h"
19 #include "unwind.h"
20 #include "callchain.h"
21 #include "dwarf-regs.h"
22 
23 #include <api/fs/fs.h>
24 
25 int thread__init_maps(struct thread *thread, struct machine *machine)
26 {
27 	pid_t pid = thread__pid(thread);
28 
29 	if (pid == thread__tid(thread) || pid == -1) {
30 		thread__set_maps(thread, maps__new(machine));
31 	} else {
32 		struct thread *leader = machine__findnew_thread(machine, pid, pid);
33 
34 		if (leader) {
35 			thread__set_maps(thread, maps__get(thread__maps(leader)));
36 			thread__put(leader);
37 		}
38 	}
39 
40 	return thread__maps(thread) ? 0 : -1;
41 }
42 
43 struct thread *thread__new(pid_t pid, pid_t tid)
44 	NO_THREAD_SAFETY_ANALYSIS /* Allocation/creation is inherently single threaded. */
45 {
46 	RC_STRUCT(thread) *_thread = zalloc(sizeof(*_thread));
47 	struct thread *thread;
48 
49 	if (ADD_RC_CHK(thread, _thread) != NULL) {
50 		struct comm *comm;
51 		char comm_str[32];
52 
53 		thread__set_pid(thread, pid);
54 		thread__set_tid(thread, tid);
55 		thread__set_ppid(thread, -1);
56 		thread__set_cpu(thread, -1);
57 		thread__set_guest_cpu(thread, -1);
58 		thread__set_e_machine(thread, EM_NONE);
59 		thread__set_lbr_stitch_enable(thread, false);
60 		INIT_LIST_HEAD(thread__namespaces_list(thread));
61 		INIT_LIST_HEAD(thread__comm_list(thread));
62 		init_rwsem(thread__namespaces_lock(thread));
63 		init_rwsem(thread__comm_lock(thread));
64 
65 		snprintf(comm_str, sizeof(comm_str), ":%d", tid);
66 		comm = comm__new(comm_str, 0, false);
67 		if (!comm)
68 			goto err_thread;
69 
70 		list_add(&comm->list, thread__comm_list(thread));
71 		refcount_set(thread__refcnt(thread), 1);
72 		/* Thread holds first ref to nsdata. */
73 		RC_CHK_ACCESS(thread)->nsinfo = nsinfo__new(pid);
74 		srccode_state_init(thread__srccode_state(thread));
75 	}
76 
77 	return thread;
78 
79 err_thread:
80 	thread__delete(thread);
81 	return NULL;
82 }
83 
84 static void (*thread__priv_destructor)(void *priv);
85 
86 void thread__set_priv_destructor(void (*destructor)(void *priv))
87 {
88 	assert(thread__priv_destructor == NULL);
89 
90 	thread__priv_destructor = destructor;
91 }
92 
93 void thread__delete(struct thread *thread)
94 {
95 	struct namespaces *namespaces, *tmp_namespaces;
96 	struct comm *comm, *tmp_comm;
97 
98 	thread_stack__free(thread);
99 
100 	if (thread__maps(thread)) {
101 		maps__put(thread__maps(thread));
102 		thread__set_maps(thread, NULL);
103 	}
104 	down_write(thread__namespaces_lock(thread));
105 	list_for_each_entry_safe(namespaces, tmp_namespaces,
106 				 thread__namespaces_list(thread), list) {
107 		list_del_init(&namespaces->list);
108 		namespaces__free(namespaces);
109 	}
110 	up_write(thread__namespaces_lock(thread));
111 
112 	down_write(thread__comm_lock(thread));
113 	list_for_each_entry_safe(comm, tmp_comm, thread__comm_list(thread), list) {
114 		list_del_init(&comm->list);
115 		comm__free(comm);
116 	}
117 	up_write(thread__comm_lock(thread));
118 
119 	nsinfo__zput(RC_CHK_ACCESS(thread)->nsinfo);
120 	srccode_state_free(thread__srccode_state(thread));
121 
122 	exit_rwsem(thread__namespaces_lock(thread));
123 	exit_rwsem(thread__comm_lock(thread));
124 	thread__free_stitch_list(thread);
125 
126 	if (thread__priv_destructor)
127 		thread__priv_destructor(thread__priv(thread));
128 
129 	RC_CHK_FREE(thread);
130 }
131 
132 struct thread *thread__get(struct thread *thread)
133 {
134 	struct thread *result;
135 
136 	if (RC_CHK_GET(result, thread))
137 		refcount_inc(thread__refcnt(thread));
138 
139 	return result;
140 }
141 
142 void thread__put(struct thread *thread)
143 {
144 	if (thread && refcount_dec_and_test(thread__refcnt(thread)))
145 		thread__delete(thread);
146 	else
147 		RC_CHK_PUT(thread);
148 }
149 
150 static struct namespaces *__thread__namespaces(struct thread *thread)
151 {
152 	if (list_empty(thread__namespaces_list(thread)))
153 		return NULL;
154 
155 	return list_first_entry(thread__namespaces_list(thread), struct namespaces, list);
156 }
157 
158 struct namespaces *thread__namespaces(struct thread *thread)
159 {
160 	struct namespaces *ns;
161 
162 	down_read(thread__namespaces_lock(thread));
163 	ns = __thread__namespaces(thread);
164 	up_read(thread__namespaces_lock(thread));
165 
166 	return ns;
167 }
168 
169 static int __thread__set_namespaces(struct thread *thread, u64 timestamp,
170 				    struct perf_record_namespaces *event)
171 {
172 	struct namespaces *new, *curr = __thread__namespaces(thread);
173 
174 	new = namespaces__new(event);
175 	if (!new)
176 		return -ENOMEM;
177 
178 	list_add(&new->list, thread__namespaces_list(thread));
179 
180 	if (timestamp && curr) {
181 		/*
182 		 * setns syscall must have changed few or all the namespaces
183 		 * of this thread. Update end time for the namespaces
184 		 * previously used.
185 		 */
186 		curr = list_next_entry(new, list);
187 		curr->end_time = timestamp;
188 	}
189 
190 	return 0;
191 }
192 
193 int thread__set_namespaces(struct thread *thread, u64 timestamp,
194 			   struct perf_record_namespaces *event)
195 {
196 	int ret;
197 
198 	down_write(thread__namespaces_lock(thread));
199 	ret = __thread__set_namespaces(thread, timestamp, event);
200 	up_write(thread__namespaces_lock(thread));
201 	return ret;
202 }
203 
204 static struct comm *__thread__comm(struct thread *thread)
205 	SHARED_LOCKS_REQUIRED(thread__comm_lock(thread))
206 {
207 	if (list_empty(thread__comm_list(thread)))
208 		return NULL;
209 
210 	return list_first_entry(thread__comm_list(thread), struct comm, list);
211 }
212 
213 struct comm *thread__comm(struct thread *thread)
214 {
215 	struct comm *res = NULL;
216 
217 	down_read(thread__comm_lock(thread));
218 	res = __thread__comm(thread);
219 	up_read(thread__comm_lock(thread));
220 	return res;
221 }
222 
223 struct comm *thread__exec_comm(struct thread *thread)
224 {
225 	struct comm *comm, *last = NULL, *second_last = NULL;
226 
227 	down_read(thread__comm_lock(thread));
228 	list_for_each_entry(comm, thread__comm_list(thread), list) {
229 		if (comm->exec) {
230 			up_read(thread__comm_lock(thread));
231 			return comm;
232 		}
233 		second_last = last;
234 		last = comm;
235 	}
236 	up_read(thread__comm_lock(thread));
237 
238 	/*
239 	 * 'last' with no start time might be the parent's comm of a synthesized
240 	 * thread (created by processing a synthesized fork event). For a main
241 	 * thread, that is very probably wrong. Prefer a later comm to avoid
242 	 * that case.
243 	 */
244 	if (second_last && !last->start && thread__pid(thread) == thread__tid(thread))
245 		return second_last;
246 
247 	return last;
248 }
249 
250 static int ____thread__set_comm(struct thread *thread, const char *str,
251 				u64 timestamp, bool exec)
252 	EXCLUSIVE_LOCKS_REQUIRED(thread__comm_lock(thread))
253 {
254 	struct comm *new, *curr = __thread__comm(thread);
255 
256 	/* Override the default :tid entry */
257 	if (!thread__comm_set(thread)) {
258 		int err = comm__override(curr, str, timestamp, exec);
259 		if (err)
260 			return err;
261 	} else {
262 		new = comm__new(str, timestamp, exec);
263 		if (!new)
264 			return -ENOMEM;
265 		list_add(&new->list, thread__comm_list(thread));
266 
267 		if (exec)
268 			unwind__flush_access(thread__maps(thread));
269 	}
270 
271 	thread__set_comm_set(thread, true);
272 
273 	return 0;
274 }
275 
276 int __thread__set_comm(struct thread *thread, const char *str, u64 timestamp,
277 		       bool exec)
278 {
279 	int ret;
280 
281 	down_write(thread__comm_lock(thread));
282 	ret = ____thread__set_comm(thread, str, timestamp, exec);
283 	up_write(thread__comm_lock(thread));
284 	return ret;
285 }
286 
287 int thread__set_comm_from_proc(struct thread *thread)
288 {
289 	char path[64];
290 	char *comm = NULL;
291 	size_t sz;
292 	int err = -1;
293 
294 	if (!(snprintf(path, sizeof(path), "%d/task/%d/comm",
295 		       thread__pid(thread), thread__tid(thread)) >= (int)sizeof(path)) &&
296 	    procfs__read_str(path, &comm, &sz) == 0) {
297 		comm[sz - 1] = '\0';
298 		err = thread__set_comm(thread, comm, 0);
299 	}
300 
301 	return err;
302 }
303 
304 static const char *__thread__comm_str(struct thread *thread)
305 	SHARED_LOCKS_REQUIRED(thread__comm_lock(thread))
306 {
307 	const struct comm *comm = __thread__comm(thread);
308 
309 	if (!comm)
310 		return NULL;
311 
312 	return comm__str(comm);
313 }
314 
315 const char *thread__comm_str(struct thread *thread)
316 {
317 	const char *str;
318 
319 	down_read(thread__comm_lock(thread));
320 	str = __thread__comm_str(thread);
321 	up_read(thread__comm_lock(thread));
322 
323 	return str;
324 }
325 
326 static int __thread__comm_len(struct thread *thread, const char *comm)
327 {
328 	if (!comm)
329 		return 0;
330 	thread__set_comm_len(thread, strlen(comm));
331 
332 	return thread__var_comm_len(thread);
333 }
334 
335 /* CHECKME: it should probably better return the max comm len from its comm list */
336 int thread__comm_len(struct thread *thread)
337 {
338 	int comm_len = thread__var_comm_len(thread);
339 
340 	if (!comm_len) {
341 		const char *comm;
342 
343 		down_read(thread__comm_lock(thread));
344 		comm = __thread__comm_str(thread);
345 		comm_len = __thread__comm_len(thread, comm);
346 		up_read(thread__comm_lock(thread));
347 	}
348 
349 	return comm_len;
350 }
351 
352 size_t thread__fprintf(struct thread *thread, FILE *fp)
353 {
354 	return fprintf(fp, "Thread %d %s\n", thread__tid(thread), thread__comm_str(thread)) +
355 	       maps__fprintf(thread__maps(thread), fp);
356 }
357 
358 int thread__insert_map(struct thread *thread, struct map *map)
359 {
360 	int ret;
361 	uint16_t e_machine;
362 
363 	ret = maps__fixup_overlap_and_insert(thread__maps(thread), map);
364 	if (ret)
365 		return ret;
366 
367 	e_machine = thread__e_machine(thread, /*machine=*/NULL, /*e_flags=*/NULL);
368 	return unwind__prepare_access(thread__maps(thread), e_machine);
369 }
370 
371 static int thread__prepare_access(struct thread *thread)
372 {
373 	uint16_t e_machine = thread__e_machine(thread, /*machine=*/NULL, /*e_flags=*/NULL);
374 
375 	return unwind__prepare_access(thread__maps(thread), e_machine);
376 }
377 
378 static int thread__clone_maps(struct thread *thread, struct thread *parent, bool do_maps_clone)
379 {
380 	/* This is new thread, we share map groups for process. */
381 	if (thread__pid(thread) == thread__pid(parent))
382 		return thread__prepare_access(thread);
383 
384 	if (maps__equal(thread__maps(thread), thread__maps(parent))) {
385 		pr_debug("broken map groups on thread %d/%d parent %d/%d\n",
386 			 thread__pid(thread), thread__tid(thread),
387 			 thread__pid(parent), thread__tid(parent));
388 		return 0;
389 	}
390 	/* But this one is new process, copy maps. */
391 	return do_maps_clone ? maps__copy_from(thread__maps(thread), thread__maps(parent)) : 0;
392 }
393 
394 int thread__fork(struct thread *thread, struct thread *parent, u64 timestamp, bool do_maps_clone)
395 {
396 	if (thread__comm_set(parent)) {
397 		const char *comm = thread__comm_str(parent);
398 		int err;
399 		if (!comm)
400 			return -ENOMEM;
401 		err = thread__set_comm(thread, comm, timestamp);
402 		if (err)
403 			return err;
404 	}
405 
406 	thread__set_ppid(thread, thread__tid(parent));
407 	return thread__clone_maps(thread, parent, do_maps_clone);
408 }
409 
410 void thread__find_cpumode_addr_location(struct thread *thread, u64 addr,
411 					bool symbols, struct addr_location *al)
412 {
413 	size_t i;
414 	const u8 cpumodes[] = {
415 		PERF_RECORD_MISC_USER,
416 		PERF_RECORD_MISC_KERNEL,
417 		PERF_RECORD_MISC_GUEST_USER,
418 		PERF_RECORD_MISC_GUEST_KERNEL
419 	};
420 
421 	for (i = 0; i < ARRAY_SIZE(cpumodes); i++) {
422 		if (symbols)
423 			thread__find_symbol(thread, cpumodes[i], addr, al);
424 		else
425 			thread__find_map(thread, cpumodes[i], addr, al);
426 
427 		if (al->map)
428 			break;
429 	}
430 }
431 
432 static uint16_t read_proc_e_machine_for_pid(pid_t pid, uint32_t *e_flags)
433 {
434 	char path[6 /* "/proc/" */ + 11 /* max length of pid */ + 5 /* "/exe\0" */];
435 	int fd;
436 	uint16_t e_machine = EM_NONE;
437 
438 	snprintf(path, sizeof(path), "/proc/%d/exe", pid);
439 	fd = open(path, O_RDONLY);
440 	if (fd >= 0) {
441 		e_machine = dso__read_e_machine(/*optional_dso=*/NULL, fd, e_flags);
442 		close(fd);
443 	}
444 	return e_machine;
445 }
446 
447 struct thread__e_machine_callback_args {
448 	struct machine *machine;
449 	uint32_t e_flags;
450 	uint16_t e_machine;
451 };
452 
453 static int thread__e_machine_callback(struct map *map, void *_args)
454 {
455 	struct thread__e_machine_callback_args *args = _args;
456 	struct dso *dso = map__dso(map);
457 
458 	if (!dso)
459 		return 0; // No dso, continue search.
460 
461 	args->e_machine = dso__e_machine(dso, args->machine, &args->e_flags);
462 	return args->e_machine != EM_NONE ? 1 /* stop search */ : 0 /* continue search */;
463 }
464 
465 uint16_t thread__e_machine(struct thread *thread, struct machine *machine, uint32_t *e_flags)
466 {
467 	pid_t tid, pid;
468 	uint16_t e_machine = RC_CHK_ACCESS(thread)->e_machine;
469 	uint32_t local_e_flags = 0;
470 	struct thread__e_machine_callback_args args = {
471 		.machine = machine,
472 		.e_flags = 0,
473 		.e_machine = EM_NONE,
474 	};
475 
476 	if (e_machine != EM_NONE) {
477 		if (e_flags)
478 			*e_flags = thread__e_flags(thread);
479 		return e_machine;
480 	}
481 
482 	if (machine == NULL) {
483 		struct maps *maps = thread__maps(thread);
484 
485 		machine = maps__machine(maps);
486 	}
487 	tid = thread__tid(thread);
488 	pid = thread__pid(thread);
489 	if (pid != tid) {
490 		struct thread *parent = machine__findnew_thread(machine, pid, pid);
491 
492 		if (parent) {
493 			e_machine = thread__e_machine(parent, machine, &local_e_flags);
494 			thread__put(parent);
495 			goto out;
496 		}
497 		/* Something went wrong, fallback. */
498 	}
499 	/* Reading on the PID thread. First try to find from the maps. */
500 	maps__for_each_map(thread__maps(thread), thread__e_machine_callback, &args);
501 
502 	if (args.e_machine != EM_NONE) {
503 		e_machine = args.e_machine;
504 		local_e_flags = args.e_flags;
505 	} else {
506 		/* Maps failed, perhaps we're live with map events disabled. */
507 		bool is_live = machine->machines == NULL;
508 
509 		if (!is_live) {
510 			/* Check if the session has a data file. */
511 			struct perf_session *session = container_of(machine->machines,
512 								    struct perf_session,
513 								    machines);
514 
515 			is_live = !!session->data;
516 		}
517 		/* Read from /proc/pid/exe if live. */
518 		if (is_live)
519 			e_machine = read_proc_e_machine_for_pid(pid, &local_e_flags);
520 	}
521 out:
522 	if (e_machine != EM_NONE) {
523 		thread__set_e_machine(thread, e_machine);
524 		thread__set_e_flags(thread, local_e_flags);
525 	} else {
526 		e_machine = EM_HOST;
527 		local_e_flags = EF_HOST;
528 	}
529 	if (e_flags)
530 		*e_flags = local_e_flags;
531 	return e_machine;
532 }
533 
534 struct thread *thread__main_thread(struct machine *machine, struct thread *thread)
535 {
536 	if (thread__pid(thread) == thread__tid(thread))
537 		return thread__get(thread);
538 
539 	if (thread__pid(thread) == -1)
540 		return NULL;
541 
542 	return machine__find_thread(machine, thread__pid(thread), thread__pid(thread));
543 }
544 
545 int thread__memcpy(struct thread *thread, struct machine *machine,
546 		   void *buf, u64 ip, int len, bool *is64bit)
547 {
548 	u8 cpumode = PERF_RECORD_MISC_USER;
549 	struct addr_location al;
550 	struct dso *dso;
551 	long offset;
552 
553 	if (machine__kernel_ip(machine, ip))
554 		cpumode = PERF_RECORD_MISC_KERNEL;
555 
556 	addr_location__init(&al);
557 	if (!thread__find_map(thread, cpumode, ip, &al)) {
558 		addr_location__exit(&al);
559 		return -1;
560 	}
561 
562 	dso = map__dso(al.map);
563 
564 	if (!dso || dso__data(dso)->status == DSO_DATA_STATUS_ERROR || map__load(al.map) < 0) {
565 		addr_location__exit(&al);
566 		return -1;
567 	}
568 
569 	offset = map__map_ip(al.map, ip);
570 	if (is64bit)
571 		*is64bit = dso__is_64_bit(dso);
572 
573 	addr_location__exit(&al);
574 
575 	return dso__data_read_offset(dso, machine, offset, buf, len);
576 }
577 
578 void thread__free_stitch_list(struct thread *thread)
579 {
580 	struct lbr_stitch *lbr_stitch = thread__lbr_stitch(thread);
581 	struct stitch_list *pos, *tmp;
582 
583 	if (!lbr_stitch)
584 		return;
585 
586 	list_for_each_entry_safe(pos, tmp, &lbr_stitch->lists, node) {
587 		map_symbol__exit(&pos->cursor.ms);
588 		list_del_init(&pos->node);
589 		free(pos);
590 	}
591 
592 	list_for_each_entry_safe(pos, tmp, &lbr_stitch->free_lists, node) {
593 		list_del_init(&pos->node);
594 		free(pos);
595 	}
596 
597 	for (unsigned int i = 0 ; i < lbr_stitch->prev_lbr_cursor_size; i++)
598 		map_symbol__exit(&lbr_stitch->prev_lbr_cursor[i].ms);
599 
600 	zfree(&lbr_stitch->prev_lbr_cursor);
601 	free(thread__lbr_stitch(thread));
602 	thread__set_lbr_stitch(thread, NULL);
603 }
604