data.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. #include "data.h"
  8. #include "util.h"
  9. static bool check_pipe(struct perf_data_file *file)
  10. {
  11. struct stat st;
  12. bool is_pipe = false;
  13. int fd = perf_data_file__is_read(file) ?
  14. STDIN_FILENO : STDOUT_FILENO;
  15. if (!file->path) {
  16. if (!fstat(fd, &st) && S_ISFIFO(st.st_mode))
  17. is_pipe = true;
  18. } else {
  19. if (!strcmp(file->path, "-"))
  20. is_pipe = true;
  21. }
  22. if (is_pipe)
  23. file->fd = fd;
  24. return file->is_pipe = is_pipe;
  25. }
  26. static int check_backup(struct perf_data_file *file)
  27. {
  28. struct stat st;
  29. if (!stat(file->path, &st) && st.st_size) {
  30. /* TODO check errors properly */
  31. char oldname[PATH_MAX];
  32. snprintf(oldname, sizeof(oldname), "%s.old",
  33. file->path);
  34. unlink(oldname);
  35. rename(file->path, oldname);
  36. }
  37. return 0;
  38. }
  39. static int open_file_read(struct perf_data_file *file)
  40. {
  41. struct stat st;
  42. int fd;
  43. fd = open(file->path, O_RDONLY);
  44. if (fd < 0) {
  45. int err = errno;
  46. pr_err("failed to open %s: %s", file->path, strerror(err));
  47. if (err == ENOENT && !strcmp(file->path, "perf.data"))
  48. pr_err(" (try 'perf record' first)");
  49. pr_err("\n");
  50. return -err;
  51. }
  52. if (fstat(fd, &st) < 0)
  53. goto out_close;
  54. if (!file->force && st.st_uid && (st.st_uid != geteuid())) {
  55. pr_err("file %s not owned by current user or root\n",
  56. file->path);
  57. goto out_close;
  58. }
  59. if (!st.st_size) {
  60. pr_info("zero-sized file (%s), nothing to do!\n",
  61. file->path);
  62. goto out_close;
  63. }
  64. file->size = st.st_size;
  65. return fd;
  66. out_close:
  67. close(fd);
  68. return -1;
  69. }
  70. static int open_file_write(struct perf_data_file *file)
  71. {
  72. if (check_backup(file))
  73. return -1;
  74. return open(file->path, O_CREAT|O_RDWR|O_TRUNC, S_IRUSR|S_IWUSR);
  75. }
  76. static int open_file(struct perf_data_file *file)
  77. {
  78. int fd;
  79. fd = perf_data_file__is_read(file) ?
  80. open_file_read(file) : open_file_write(file);
  81. file->fd = fd;
  82. return fd < 0 ? -1 : 0;
  83. }
  84. int perf_data_file__open(struct perf_data_file *file)
  85. {
  86. if (check_pipe(file))
  87. return 0;
  88. if (!file->path)
  89. file->path = "perf.data";
  90. return open_file(file);
  91. }
  92. void perf_data_file__close(struct perf_data_file *file)
  93. {
  94. close(file->fd);
  95. }