1 #include <linux/compiler.h>
2 #include <linux/kernel.h>
12 static bool check_pipe(struct perf_data_file
*file
)
16 int fd
= perf_data_file__is_read(file
) ?
17 STDIN_FILENO
: STDOUT_FILENO
;
20 if (!fstat(fd
, &st
) && S_ISFIFO(st
.st_mode
))
23 if (!strcmp(file
->path
, "-"))
30 return file
->is_pipe
= is_pipe
;
33 static int check_backup(struct perf_data_file
*file
)
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",
43 rename(file
->path
, oldname
);
49 static int open_file_read(struct perf_data_file
*file
)
53 char sbuf
[STRERR_BUFSIZE
];
55 fd
= open(file
->path
, O_RDONLY
);
59 pr_err("failed to open %s: %s", file
->path
,
60 str_error_r(err
, sbuf
, sizeof(sbuf
)));
61 if (err
== ENOENT
&& !strcmp(file
->path
, "perf.data"))
62 pr_err(" (try 'perf record' first)");
67 if (fstat(fd
, &st
) < 0)
70 if (!file
->force
&& st
.st_uid
&& (st
.st_uid
!= geteuid())) {
71 pr_err("File %s not owned by current user or root (use -f to override)\n",
77 pr_info("zero-sized file (%s), nothing to do!\n",
82 file
->size
= st
.st_size
;
90 static int open_file_write(struct perf_data_file
*file
)
93 char sbuf
[STRERR_BUFSIZE
];
95 if (check_backup(file
))
98 fd
= open(file
->path
, O_CREAT
|O_RDWR
|O_TRUNC
, S_IRUSR
|S_IWUSR
);
101 pr_err("failed to open %s : %s\n", file
->path
,
102 str_error_r(errno
, sbuf
, sizeof(sbuf
)));
107 static int open_file(struct perf_data_file
*file
)
111 fd
= perf_data_file__is_read(file
) ?
112 open_file_read(file
) : open_file_write(file
);
115 return fd
< 0 ? -1 : 0;
118 int perf_data_file__open(struct perf_data_file
*file
)
120 if (check_pipe(file
))
124 file
->path
= "perf.data";
126 return open_file(file
);
129 void perf_data_file__close(struct perf_data_file
*file
)
134 ssize_t
perf_data_file__write(struct perf_data_file
*file
,
135 void *buf
, size_t size
)
137 return writen(file
->fd
, buf
, size
);
140 int perf_data_file__switch(struct perf_data_file
*file
,
142 size_t pos
, bool at_exit
)
147 if (check_pipe(file
))
149 if (perf_data_file__is_read(file
))
152 if (asprintf(&new_filepath
, "%s.%s", file
->path
, postfix
) < 0)
156 * Only fire a warning, don't return error, continue fill
159 if (rename(file
->path
, new_filepath
))
160 pr_warning("Failed to rename %s to %s\n", file
->path
, new_filepath
);
164 ret
= perf_data_file__open(file
);
168 if (lseek(file
->fd
, pos
, SEEK_SET
) == (off_t
)-1) {
170 pr_debug("Failed to lseek to %zu: %s",
171 pos
, strerror(errno
));