File: ftrace.c

package info (click to toggle)
trinity 1.9%2Bgit20200331.4d2343bd18c7b-2%2Bdeb11u1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 3,080 kB
  • sloc: ansic: 32,746; sh: 536; makefile: 164
file content (90 lines) | stat: -rw-r--r-- 2,047 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

#include "ftrace.h"
#include "trinity.h"

static int trace_fd = -1;

// TODO: if passed a dir, generate filename with datestamp

static const char defaultdumpfilename[] = "/boot/trace.txt";
const char *ftracedumpname = defaultdumpfilename;

static void dump_trace(void)
{
	int tracein, traceout;
	ssize_t in = -1, out = -1;
	char buffer[4096];
	const char tracefile[] = "/sys/kernel/debug/tracing/trace";

	tracein = open(tracefile, O_RDONLY);
	if (tracein == -1) {
		if (errno != -EEXIST)
			output(0, "Error opening %s : %s\n", tracefile, strerror(errno));
		goto fail_tracein;
	}

	traceout = open(ftracedumpname, O_CREAT | O_WRONLY, 0600);
	if (traceout == -1) {
		output(0, "Error opening %s : %s\n", ftracedumpname, strerror(errno));
		goto fail_traceout;
	}

	while (in != 0) {
		in = read(tracein, buffer, 4096);
		if (in > 0) {
			out = write(traceout, buffer, in);
			if (out == -1) {
				output(0, "Error writing trace to %s. %s\n", ftracedumpname, strerror(errno));
				goto fail;
			}
		}

		if (in == -1) {
			output(0, "something went wrong reading from trace. %s\n", strerror(errno));
			goto fail;
		}
	}

	output(0, "Dumped trace to %s\n", ftracedumpname);
fail:
	fsync(traceout);
	close(traceout);
fail_traceout:
	close(tracein);
fail_tracein:
	if (ftracedumpname != defaultdumpfilename) {
		free((void *)ftracedumpname);
		ftracedumpname = NULL;
	}
}

void setup_ftrace(void)
{
	//todo: check for root
	trace_fd = open("/sys/kernel/debug/tracing/tracing_on", O_WRONLY);
	if (trace_fd == -1) {
		if (errno != -EEXIST) {
			output(0, "Error opening tracing_on : %s\n", strerror(errno));
			return;
		}
	}
	output(0, "Opened ftrace tracing_on as fd %d\n", trace_fd);
	output(0, "Ftrace log will be dumped to %s\n", ftracedumpname);
}

void stop_ftrace(void)
{
	if (trace_fd != -1) {
		if (write(trace_fd, "0", 1) == -1) {
			output(0, "Stopping ftrace failed! %s\n", strerror(errno));
			return;
		}
		dump_trace();
		return;
	}
}