1//===-- sanitizer_file.cpp -----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===---------------------------------------------------------------------===//
8//
9// This file is shared between AddressSanitizer and ThreadSanitizer
10// run-time libraries.  It defines filesystem-related interfaces.  This
11// is separate from sanitizer_common.cpp so that it's simpler to disable
12// all the filesystem support code for a port that doesn't use it.
13//
14//===---------------------------------------------------------------------===//
15
16#include "sanitizer_platform.h"
17
18#if !SANITIZER_FUCHSIA
19
20#include "sanitizer_common.h"
21#include "sanitizer_file.h"
22
23namespace __sanitizer {
24
25void CatastrophicErrorWrite(const char *buffer, uptr length) {
26  WriteToFile(kStderrFd, buffer, length);
27}
28
29StaticSpinMutex report_file_mu;
30ReportFile report_file = {&report_file_mu, kStderrFd, "", "", 0};
31
32void RawWrite(const char *buffer) {
33  report_file.Write(buffer, internal_strlen(buffer));
34}
35
36void ReportFile::ReopenIfNecessary() {
37  mu->CheckLocked();
38  if (fd == kStdoutFd || fd == kStderrFd) return;
39
40  uptr pid = internal_getpid();
41  // If in tracer, use the parent's file.
42  if (pid == stoptheworld_tracer_pid)
43    pid = stoptheworld_tracer_ppid;
44  if (fd != kInvalidFd) {
45    // If the report file is already opened by the current process,
46    // do nothing. Otherwise the report file was opened by the parent
47    // process, close it now.
48    if (fd_pid == pid)
49      return;
50    else
51      CloseFile(fd);
52  }
53
54  const char *exe_name = GetProcessName();
55  if (common_flags()->log_exe_name && exe_name) {
56    internal_snprintf(full_path, kMaxPathLength, "%s.%s.%zu", path_prefix,
57                      exe_name, pid);
58  } else {
59    internal_snprintf(full_path, kMaxPathLength, "%s.%zu", path_prefix, pid);
60  }
61  if (common_flags()->log_suffix) {
62    internal_strlcat(full_path, common_flags()->log_suffix, kMaxPathLength);
63  }
64  error_t err;
65  fd = OpenFile(full_path, WrOnly, &err);
66  if (fd == kInvalidFd) {
67    const char *ErrorMsgPrefix = "ERROR: Can't open file: ";
68    WriteToFile(kStderrFd, ErrorMsgPrefix, internal_strlen(ErrorMsgPrefix));
69    WriteToFile(kStderrFd, full_path, internal_strlen(full_path));
70    char errmsg[100];
71    internal_snprintf(errmsg, sizeof(errmsg), " (reason: %d)", err);
72    WriteToFile(kStderrFd, errmsg, internal_strlen(errmsg));
73    Die();
74  }
75  fd_pid = pid;
76}
77
78static void RecursiveCreateParentDirs(char *path) {
79  if (path[0] == '\0')
80    return;
81  for (int i = 1; path[i] != '\0'; ++i) {
82    char save = path[i];
83    if (!IsPathSeparator(path[i]))
84      continue;
85    path[i] = '\0';
86    /* Some of these will fail, because the directory exists, ignore it. */
87    CreateDir(path);
88    path[i] = save;
89  }
90}
91
92void ReportFile::SetReportPath(const char *path) {
93  if (path) {
94    uptr len = internal_strlen(path);
95    if (len > sizeof(path_prefix) - 100) {
96      Report("ERROR: Path is too long: %c%c%c%c%c%c%c%c...\n", path[0], path[1],
97             path[2], path[3], path[4], path[5], path[6], path[7]);
98      Die();
99    }
100  }
101
102  SpinMutexLock l(mu);
103  if (fd != kStdoutFd && fd != kStderrFd && fd != kInvalidFd)
104    CloseFile(fd);
105  fd = kInvalidFd;
106  if (!path || internal_strcmp(path, "stderr") == 0) {
107    fd = kStderrFd;
108  } else if (internal_strcmp(path, "stdout") == 0) {
109    fd = kStdoutFd;
110  } else {
111    internal_snprintf(path_prefix, kMaxPathLength, "%s", path);
112    RecursiveCreateParentDirs(path_prefix);
113  }
114}
115
116const char *ReportFile::GetReportPath() {
117  SpinMutexLock l(mu);
118  ReopenIfNecessary();
119  return full_path;
120}
121
122bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
123                      uptr *read_len, uptr max_len, error_t *errno_p) {
124  *buff = nullptr;
125  *buff_size = 0;
126  *read_len = 0;
127  if (!max_len)
128    return true;
129  uptr PageSize = GetPageSizeCached();
130  uptr kMinFileLen = Min(PageSize, max_len);
131
132  // The files we usually open are not seekable, so try different buffer sizes.
133  for (uptr size = kMinFileLen;; size = Min(size * 2, max_len)) {
134    UnmapOrDie(*buff, *buff_size);
135    *buff = (char*)MmapOrDie(size, __func__);
136    *buff_size = size;
137    fd_t fd = OpenFile(file_name, RdOnly, errno_p);
138    if (fd == kInvalidFd) {
139      UnmapOrDie(*buff, *buff_size);
140      return false;
141    }
142    *read_len = 0;
143    // Read up to one page at a time.
144    bool reached_eof = false;
145    while (*read_len < size) {
146      uptr just_read;
147      if (!ReadFromFile(fd, *buff + *read_len, size - *read_len, &just_read,
148                        errno_p)) {
149        UnmapOrDie(*buff, *buff_size);
150        CloseFile(fd);
151        return false;
152      }
153      *read_len += just_read;
154      if (just_read == 0 || *read_len == max_len) {
155        reached_eof = true;
156        break;
157      }
158    }
159    CloseFile(fd);
160    if (reached_eof)  // We've read the whole file.
161      break;
162  }
163  return true;
164}
165
166bool ReadFileToVector(const char *file_name,
167                      InternalMmapVectorNoCtor<char> *buff, uptr max_len,
168                      error_t *errno_p) {
169  buff->clear();
170  if (!max_len)
171    return true;
172  uptr PageSize = GetPageSizeCached();
173  fd_t fd = OpenFile(file_name, RdOnly, errno_p);
174  if (fd == kInvalidFd)
175    return false;
176  uptr read_len = 0;
177  while (read_len < max_len) {
178    if (read_len >= buff->size())
179      buff->resize(Min(Max(PageSize, read_len * 2), max_len));
180    CHECK_LT(read_len, buff->size());
181    CHECK_LE(buff->size(), max_len);
182    uptr just_read;
183    if (!ReadFromFile(fd, buff->data() + read_len, buff->size() - read_len,
184                      &just_read, errno_p)) {
185      CloseFile(fd);
186      return false;
187    }
188    read_len += just_read;
189    if (!just_read)
190      break;
191  }
192  CloseFile(fd);
193  buff->resize(read_len);
194  return true;
195}
196
197static const char kPathSeparator = SANITIZER_WINDOWS ? ';' : ':';
198
199char *FindPathToBinary(const char *name) {
200  if (FileExists(name)) {
201    return internal_strdup(name);
202  }
203
204  const char *path = GetEnv("PATH");
205  if (!path)
206    return nullptr;
207  uptr name_len = internal_strlen(name);
208  InternalMmapVector<char> buffer(kMaxPathLength);
209  const char *beg = path;
210  while (true) {
211    const char *end = internal_strchrnul(beg, kPathSeparator);
212    uptr prefix_len = end - beg;
213    if (prefix_len + name_len + 2 <= kMaxPathLength) {
214      internal_memcpy(buffer.data(), beg, prefix_len);
215      buffer[prefix_len] = '/';
216      internal_memcpy(&buffer[prefix_len + 1], name, name_len);
217      buffer[prefix_len + 1 + name_len] = '\0';
218      if (FileExists(buffer.data()))
219        return internal_strdup(buffer.data());
220    }
221    if (*end == '\0') break;
222    beg = end + 1;
223  }
224  return nullptr;
225}
226
227} // namespace __sanitizer
228
229using namespace __sanitizer;
230
231extern "C" {
232void __sanitizer_set_report_path(const char *path) {
233  report_file.SetReportPath(path);
234}
235
236void __sanitizer_set_report_fd(void *fd) {
237  report_file.fd = (fd_t)reinterpret_cast<uptr>(fd);
238  report_file.fd_pid = internal_getpid();
239}
240
241const char *__sanitizer_get_report_path() {
242  return report_file.GetReportPath();
243}
244} // extern "C"
245
246#endif  // !SANITIZER_FUCHSIA
247