1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/compiler.h>
3 #include <linux/kernel.h>
16 #define O_CLOEXEC 0x400000
17 #elif defined(__alpha__) || defined(__hppa__)
18 #define O_CLOEXEC 010000000
20 #define O_CLOEXEC 02000000
24 static bool check_pipe(struct perf_data_file *file)
28 int fd = perf_data_file__is_read(file) ?
29 STDIN_FILENO : STDOUT_FILENO;
32 if (!fstat(fd, &st) && S_ISFIFO(st.st_mode))
35 if (!strcmp(file->path, "-"))
42 return file->is_pipe = is_pipe;
45 static int check_backup(struct perf_data_file *file)
49 if (!stat(file->path, &st) && st.st_size) {
50 /* TODO check errors properly */
51 char oldname[PATH_MAX];
52 snprintf(oldname, sizeof(oldname), "%s.old",
55 rename(file->path, oldname);
61 static int open_file_read(struct perf_data_file *file)
65 char sbuf[STRERR_BUFSIZE];
67 fd = open(file->path, O_RDONLY);
71 pr_err("failed to open %s: %s", file->path,
72 str_error_r(err, sbuf, sizeof(sbuf)));
73 if (err == ENOENT && !strcmp(file->path, "perf.data"))
74 pr_err(" (try 'perf record' first)");
79 if (fstat(fd, &st) < 0)
82 if (!file->force && st.st_uid && (st.st_uid != geteuid())) {
83 pr_err("File %s not owned by current user or root (use -f to override)\n",
89 pr_info("zero-sized file (%s), nothing to do!\n",
94 file->size = st.st_size;
102 static int open_file_write(struct perf_data_file *file)
105 char sbuf[STRERR_BUFSIZE];
107 if (check_backup(file))
110 fd = open(file->path, O_CREAT|O_RDWR|O_TRUNC|O_CLOEXEC,
114 pr_err("failed to open %s : %s\n", file->path,
115 str_error_r(errno, sbuf, sizeof(sbuf)));
120 static int open_file(struct perf_data_file *file)
124 fd = perf_data_file__is_read(file) ?
125 open_file_read(file) : open_file_write(file);
128 return fd < 0 ? -1 : 0;
131 int perf_data_file__open(struct perf_data_file *file)
133 if (check_pipe(file))
137 file->path = "perf.data";
139 return open_file(file);
142 void perf_data_file__close(struct perf_data_file *file)
147 ssize_t perf_data_file__write(struct perf_data_file *file,
148 void *buf, size_t size)
150 return writen(file->fd, buf, size);
153 int perf_data_file__switch(struct perf_data_file *file,
155 size_t pos, bool at_exit)
160 if (check_pipe(file))
162 if (perf_data_file__is_read(file))
165 if (asprintf(&new_filepath, "%s.%s", file->path, postfix) < 0)
169 * Only fire a warning, don't return error, continue fill
172 if (rename(file->path, new_filepath))
173 pr_warning("Failed to rename %s to %s\n", file->path, new_filepath);
177 ret = perf_data_file__open(file);
181 if (lseek(file->fd, pos, SEEK_SET) == (off_t)-1) {
183 pr_debug("Failed to lseek to %zu: %s",
184 pos, strerror(errno));