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