thread.c 1.9 KB
Newer Older
1 2 3 4
#include "../perf.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
5
#include "session.h"
6 7
#include "thread.h"
#include "util.h"
8
#include "debug.h"
9

10
struct thread *thread__new(pid_t pid, pid_t tid)
11
{
12
	struct thread *thread = zalloc(sizeof(*thread));
13

14 15 16 17 18 19 20 21
	if (thread != NULL) {
		map_groups__init(&thread->mg);
		thread->pid_ = pid;
		thread->tid = tid;
		thread->ppid = -1;
		thread->comm = malloc(32);
		if (thread->comm)
			snprintf(thread->comm, 32, ":%d", thread->tid);
22 23
	}

24
	return thread;
25 26
}

27
void thread__delete(struct thread *thread)
28
{
29 30 31
	map_groups__exit(&thread->mg);
	free(thread->comm);
	free(thread);
32 33
}

34 35
int thread__set_comm(struct thread *thread, const char *comm,
		     u64 timestamp __maybe_unused)
36
{
37 38
	int err;

39 40 41 42
	if (thread->comm)
		free(thread->comm);
	thread->comm = strdup(comm);
	err = thread->comm == NULL ? -ENOMEM : 0;
43
	if (!err) {
44
		thread->comm_set = true;
45 46
	}
	return err;
47 48
}

49 50 51 52 53
const char *thread__comm_str(const struct thread *thread)
{
	return thread->comm;
}

54
int thread__comm_len(struct thread *thread)
55
{
56 57
	if (!thread->comm_len) {
		if (!thread->comm)
58
			return 0;
59
		thread->comm_len = strlen(thread->comm);
60 61
	}

62
	return thread->comm_len;
63 64
}

65
size_t thread__fprintf(struct thread *thread, FILE *fp)
66
{
67
	return fprintf(fp, "Thread %d %s\n", thread->tid, thread__comm_str(thread)) +
68
	       map_groups__fprintf(&thread->mg, verbose, fp);
69 70
}

71
void thread__insert_map(struct thread *thread, struct map *map)
72
{
73 74
	map_groups__fixup_overlappings(&thread->mg, map, verbose, stderr);
	map_groups__insert(&thread->mg, map);
75 76
}

77 78
int thread__fork(struct thread *thread, struct thread *parent,
		 u64 timestamp __maybe_unused)
79 80
{
	int i;
81

82
	if (parent->comm_set) {
83 84 85 86
		if (thread->comm)
			free(thread->comm);
		thread->comm = strdup(parent->comm);
		if (!thread->comm)
87
			return -ENOMEM;
88
		thread->comm_set = true;
89
	}
90

91
	for (i = 0; i < MAP__NR_TYPES; ++i)
92
		if (map_groups__clone(&thread->mg, &parent->mg, i) < 0)
93
			return -ENOMEM;
94

95
	thread->ppid = parent->tid;
96

97 98
	return 0;
}