Merge tag 'sunxi-dt-for-3.17-2' of git://git.kernel.org/pub/scm/linux/kernel/git...
[deliverable/linux.git] / tools / perf / util / data.c
1 #include <linux/compiler.h>
2 #include <linux/kernel.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <unistd.h>
6 #include <string.h>
7
8 #include "data.h"
9 #include "util.h"
10 #include "debug.h"
11
12 static bool check_pipe(struct perf_data_file *file)
13 {
14 struct stat st;
15 bool is_pipe = false;
16 int fd = perf_data_file__is_read(file) ?
17 STDIN_FILENO : STDOUT_FILENO;
18
19 if (!file->path) {
20 if (!fstat(fd, &st) && S_ISFIFO(st.st_mode))
21 is_pipe = true;
22 } else {
23 if (!strcmp(file->path, "-"))
24 is_pipe = true;
25 }
26
27 if (is_pipe)
28 file->fd = fd;
29
30 return file->is_pipe = is_pipe;
31 }
32
33 static int check_backup(struct perf_data_file *file)
34 {
35 struct stat st;
36
37 if (!stat(file->path, &st) && st.st_size) {
38 /* TODO check errors properly */
39 char oldname[PATH_MAX];
40 snprintf(oldname, sizeof(oldname), "%s.old",
41 file->path);
42 unlink(oldname);
43 rename(file->path, oldname);
44 }
45
46 return 0;
47 }
48
49 static int open_file_read(struct perf_data_file *file)
50 {
51 struct stat st;
52 int fd;
53
54 fd = open(file->path, O_RDONLY);
55 if (fd < 0) {
56 int err = errno;
57
58 pr_err("failed to open %s: %s", file->path, strerror(err));
59 if (err == ENOENT && !strcmp(file->path, "perf.data"))
60 pr_err(" (try 'perf record' first)");
61 pr_err("\n");
62 return -err;
63 }
64
65 if (fstat(fd, &st) < 0)
66 goto out_close;
67
68 if (!file->force && st.st_uid && (st.st_uid != geteuid())) {
69 pr_err("File %s not owned by current user or root (use -f to override)\n",
70 file->path);
71 goto out_close;
72 }
73
74 if (!st.st_size) {
75 pr_info("zero-sized file (%s), nothing to do!\n",
76 file->path);
77 goto out_close;
78 }
79
80 file->size = st.st_size;
81 return fd;
82
83 out_close:
84 close(fd);
85 return -1;
86 }
87
88 static int open_file_write(struct perf_data_file *file)
89 {
90 int fd;
91
92 if (check_backup(file))
93 return -1;
94
95 fd = open(file->path, O_CREAT|O_RDWR|O_TRUNC, S_IRUSR|S_IWUSR);
96
97 if (fd < 0)
98 pr_err("failed to open %s : %s\n", file->path, strerror(errno));
99
100 return fd;
101 }
102
103 static int open_file(struct perf_data_file *file)
104 {
105 int fd;
106
107 fd = perf_data_file__is_read(file) ?
108 open_file_read(file) : open_file_write(file);
109
110 file->fd = fd;
111 return fd < 0 ? -1 : 0;
112 }
113
114 int perf_data_file__open(struct perf_data_file *file)
115 {
116 if (check_pipe(file))
117 return 0;
118
119 if (!file->path)
120 file->path = "perf.data";
121
122 return open_file(file);
123 }
124
125 void perf_data_file__close(struct perf_data_file *file)
126 {
127 close(file->fd);
128 }
129
130 ssize_t perf_data_file__write(struct perf_data_file *file,
131 void *buf, size_t size)
132 {
133 return writen(file->fd, buf, size);
134 }
This page took 0.033732 seconds and 5 git commands to generate.