xref: /linux/tools/perf/util/thread.c (revision a77ecea7ced2fef7cc0a8ad0323542f781ad9788)
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 		comm[sz - 1] = '\0';
299 		err = thread__set_comm(thread, comm, 0);
300 	}
301 
302 	return err;
303 }
304 
305 static const char *__thread__comm_str(struct thread *thread)
306 	SHARED_LOCKS_REQUIRED(thread__comm_lock(thread))
307 {
308 	const struct comm *comm = __thread__comm(thread);
309 
310 	if (!comm)
311 		return NULL;
312 
313 	return comm__str(comm);
314 }
315 
316 const char *thread__comm_str(struct thread *thread)
317 {
318 	const char *str;
319 
320 	down_read(thread__comm_lock(thread));
321 	str = __thread__comm_str(thread);
322 	up_read(thread__comm_lock(thread));
323 
324 	return str;
325 }
326 
327 static int __thread__comm_len(struct thread *thread, const char *comm)
328 {
329 	if (!comm)
330 		return 0;
331 	thread__set_comm_len(thread, strlen(comm));
332 
333 	return thread__var_comm_len(thread);
334 }
335 
336 /* CHECKME: it should probably better return the max comm len from its comm list */
337 int thread__comm_len(struct thread *thread)
338 {
339 	int comm_len = thread__var_comm_len(thread);
340 
341 	if (!comm_len) {
342 		const char *comm;
343 
344 		down_read(thread__comm_lock(thread));
345 		comm = __thread__comm_str(thread);
346 		comm_len = __thread__comm_len(thread, comm);
347 		up_read(thread__comm_lock(thread));
348 	}
349 
350 	return comm_len;
351 }
352 
353 size_t thread__fprintf(struct thread *thread, FILE *fp)
354 {
355 	return fprintf(fp, "Thread %d %s\n", thread__tid(thread), thread__comm_str(thread)) +
356 	       maps__fprintf(thread__maps(thread), fp);
357 }
358 
359 int thread__insert_map(struct thread *thread, struct map *map)
360 {
361 	int ret;
362 	uint16_t e_machine;
363 
364 	ret = maps__fixup_overlap_and_insert(thread__maps(thread), map);
365 	if (ret)
366 		return ret;
367 
368 	e_machine = thread__e_machine(thread, /*machine=*/NULL, /*e_flags=*/NULL);
369 	return unwind__prepare_access(thread__maps(thread), e_machine);
370 }
371 
372 static int thread__prepare_access(struct thread *thread)
373 {
374 	uint16_t e_machine = thread__e_machine(thread, /*machine=*/NULL, /*e_flags=*/NULL);
375 
376 	return unwind__prepare_access(thread__maps(thread), e_machine);
377 }
378 
379 static int thread__clone_maps(struct thread *thread, struct thread *parent, bool do_maps_clone)
380 {
381 	/* This is new thread, we share map groups for process. */
382 	if (thread__pid(thread) == thread__pid(parent))
383 		return thread__prepare_access(thread);
384 
385 	if (maps__equal(thread__maps(thread), thread__maps(parent))) {
386 		pr_debug("broken map groups on thread %d/%d parent %d/%d\n",
387 			 thread__pid(thread), thread__tid(thread),
388 			 thread__pid(parent), thread__tid(parent));
389 		return 0;
390 	}
391 	/* But this one is new process, copy maps. */
392 	return do_maps_clone ? maps__copy_from(thread__maps(thread), thread__maps(parent)) : 0;
393 }
394 
395 int thread__fork(struct thread *thread, struct thread *parent, u64 timestamp, bool do_maps_clone)
396 {
397 	if (thread__comm_set(parent)) {
398 		const char *comm = thread__comm_str(parent);
399 		int err;
400 		if (!comm)
401 			return -ENOMEM;
402 		err = thread__set_comm(thread, comm, timestamp);
403 		if (err)
404 			return err;
405 	}
406 
407 	thread__set_ppid(thread, thread__tid(parent));
408 	return thread__clone_maps(thread, parent, do_maps_clone);
409 }
410 
411 void thread__find_cpumode_addr_location(struct thread *thread, u64 addr,
412 					bool symbols, struct addr_location *al)
413 {
414 	size_t i;
415 	const u8 cpumodes[] = {
416 		PERF_RECORD_MISC_USER,
417 		PERF_RECORD_MISC_KERNEL,
418 		PERF_RECORD_MISC_GUEST_USER,
419 		PERF_RECORD_MISC_GUEST_KERNEL
420 	};
421 
422 	for (i = 0; i < ARRAY_SIZE(cpumodes); i++) {
423 		if (symbols)
424 			thread__find_symbol(thread, cpumodes[i], addr, al);
425 		else
426 			thread__find_map(thread, cpumodes[i], addr, al);
427 
428 		if (al->map)
429 			break;
430 	}
431 }
432 
433 static uint16_t read_proc_e_machine_for_pid(pid_t pid, uint32_t *e_flags, bool *is_big_endian)
434 {
435 	char path[6 /* "/proc/" */ + 11 /* max length of pid */ + 5 /* "/exe\0" */];
436 	int fd;
437 	uint16_t e_machine = EM_NONE;
438 
439 	snprintf(path, sizeof(path), "/proc/%d/exe", pid);
440 	fd = open(path, O_RDONLY);
441 	if (fd >= 0) {
442 		e_machine = dso__read_e_machine_endian(/*optional_dso=*/NULL, fd, e_flags,
443 						       is_big_endian);
444 		close(fd);
445 	}
446 	return e_machine;
447 }
448 
449 struct thread__e_machine_callback_args {
450 	struct machine *machine;
451 	uint32_t e_flags;
452 	uint16_t e_machine;
453 	bool is_big_endian;
454 };
455 
456 static int thread__e_machine_callback(struct map *map, void *_args)
457 {
458 	struct thread__e_machine_callback_args *args = _args;
459 	struct dso *dso = map__dso(map);
460 
461 	if (!dso)
462 		return 0; // No dso, continue search.
463 
464 	args->e_machine =
465 		dso__e_machine_endian(dso, args->machine, &args->e_flags, &args->is_big_endian);
466 	return args->e_machine != EM_NONE ? 1 /* stop search */ : 0 /* continue search */;
467 }
468 
469 uint16_t thread__e_machine_endian(struct thread *thread, struct machine *machine, uint32_t *e_flags,
470 				  bool *is_big_endian)
471 {
472 	pid_t tid, pid;
473 	uint16_t e_machine;
474 	uint32_t local_e_flags = 0;
475 	struct thread__e_machine_callback_args args;
476 
477 	if (!thread) {
478 		if (is_big_endian) {
479 			*is_big_endian = perf_arch_is_big_endian(
480 				machine && machine->env ? perf_env__arch(machine->env) : NULL);
481 		}
482 		return perf_env__e_machine(machine ? machine->env : NULL, e_flags);
483 	}
484 
485 	e_machine = RC_CHK_ACCESS(thread)->e_machine;
486 	args.machine = machine;
487 	args.e_flags = 0;
488 	args.e_machine = EM_NONE;
489 	args.is_big_endian = false;
490 
491 	if (e_machine != EM_NONE) {
492 		if (e_flags)
493 			*e_flags = thread__e_flags(thread);
494 		if (is_big_endian)
495 			*is_big_endian = thread__e_is_big_endian(thread);
496 		return e_machine;
497 	}
498 
499 	if (machine == NULL) {
500 		struct maps *maps = thread__maps(thread);
501 
502 		machine = maps__machine(maps);
503 		args.machine = machine;
504 	}
505 	tid = thread__tid(thread);
506 	pid = thread__pid(thread);
507 	if (pid != tid) {
508 		struct thread *parent = machine__findnew_thread(machine, pid, pid);
509 
510 		if (parent) {
511 			e_machine = thread__e_machine_endian(parent, machine, &local_e_flags,
512 							     &args.is_big_endian);
513 			thread__put(parent);
514 			goto out;
515 		}
516 		/* Something went wrong, fallback. */
517 	}
518 	/* Reading on the PID thread. First try to find from the maps. */
519 	maps__for_each_map(thread__maps(thread), thread__e_machine_callback, &args);
520 
521 	if (args.e_machine != EM_NONE) {
522 		e_machine = args.e_machine;
523 		local_e_flags = args.e_flags;
524 	} else {
525 		/* Maps failed, perhaps we're live with map events disabled. */
526 		bool is_live = machine->machines == NULL;
527 
528 		if (!is_live) {
529 			/* Check if the session has a data file. */
530 			struct perf_session *session = container_of(machine->machines,
531 								    struct perf_session,
532 								    machines);
533 
534 			is_live = !!session->data;
535 		}
536 		/* Read from /proc/pid/exe if live. */
537 		if (is_live) {
538 			e_machine = read_proc_e_machine_for_pid(pid, &local_e_flags,
539 								&args.is_big_endian);
540 		} else if (machine && machine->env) {
541 			/* Offline analysis: fallback to environment metadata. */
542 			e_machine = perf_env__e_machine(machine->env, &local_e_flags);
543 			args.is_big_endian = perf_arch_is_big_endian(perf_env__arch(machine->env));
544 		}
545 	}
546 out:
547 	if (e_machine != EM_NONE) {
548 		thread__set_e_flags(thread, local_e_flags);
549 		thread__set_e_is_big_endian(thread, args.is_big_endian);
550 		thread__set_e_machine(thread, e_machine);
551 		if (is_big_endian)
552 			*is_big_endian = args.is_big_endian;
553 	} else {
554 		e_machine = EM_HOST;
555 		local_e_flags = EF_HOST;
556 		if (is_big_endian)
557 			*is_big_endian = (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__);
558 	}
559 	if (e_flags)
560 		*e_flags = local_e_flags;
561 	return e_machine;
562 }
563 
564 struct thread *thread__main_thread(struct machine *machine, struct thread *thread)
565 {
566 	if (thread__pid(thread) == thread__tid(thread))
567 		return thread__get(thread);
568 
569 	if (thread__pid(thread) == -1)
570 		return NULL;
571 
572 	return machine__find_thread(machine, thread__pid(thread), thread__pid(thread));
573 }
574 
575 int thread__memcpy(struct thread *thread, struct machine *machine,
576 		   void *buf, u64 ip, int len, bool *is64bit)
577 {
578 	u8 cpumode = PERF_RECORD_MISC_USER;
579 	struct addr_location al;
580 	struct dso *dso;
581 	long offset;
582 
583 	if (machine__kernel_ip(machine, ip))
584 		cpumode = PERF_RECORD_MISC_KERNEL;
585 
586 	addr_location__init(&al);
587 	if (!thread__find_map(thread, cpumode, ip, &al)) {
588 		addr_location__exit(&al);
589 		return -1;
590 	}
591 
592 	dso = map__dso(al.map);
593 
594 	if (!dso || dso__data(dso)->status == DSO_DATA_STATUS_ERROR || map__load(al.map) < 0) {
595 		addr_location__exit(&al);
596 		return -1;
597 	}
598 
599 	offset = map__map_ip(al.map, ip);
600 	if (is64bit)
601 		*is64bit = dso__is_64_bit(dso);
602 
603 	addr_location__exit(&al);
604 
605 	return dso__data_read_offset(dso, machine, offset, buf, len);
606 }
607 
608 void thread__free_stitch_list(struct thread *thread)
609 {
610 	struct lbr_stitch *lbr_stitch = thread__lbr_stitch(thread);
611 	struct stitch_list *pos, *tmp;
612 
613 	if (!lbr_stitch)
614 		return;
615 
616 	list_for_each_entry_safe(pos, tmp, &lbr_stitch->lists, node) {
617 		map_symbol__exit(&pos->cursor.ms);
618 		list_del_init(&pos->node);
619 		free(pos);
620 	}
621 
622 	list_for_each_entry_safe(pos, tmp, &lbr_stitch->free_lists, node) {
623 		list_del_init(&pos->node);
624 		free(pos);
625 	}
626 
627 	for (unsigned int i = 0 ; i < lbr_stitch->prev_lbr_cursor_size; i++)
628 		map_symbol__exit(&lbr_stitch->prev_lbr_cursor[i].ms);
629 
630 	zfree(&lbr_stitch->prev_lbr_cursor);
631 	free(thread__lbr_stitch(thread));
632 	thread__set_lbr_stitch(thread, NULL);
633 }
634