* Add missing ChangeLog entry.
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_common.cc
blobd4da3206e130f3753a9fb4279e9ed6a0437087ef
1 //===-- sanitizer_common.cc -----------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries.
10 //===----------------------------------------------------------------------===//
12 #include "sanitizer_common.h"
13 #include "sanitizer_flags.h"
14 #include "sanitizer_libc.h"
16 namespace __sanitizer {
18 const char *SanitizerToolName = "SanitizerTool";
20 uptr GetPageSizeCached() {
21 static uptr PageSize;
22 if (!PageSize)
23 PageSize = GetPageSize();
24 return PageSize;
28 // By default, dump to stderr. If |log_to_file| is true and |report_fd_pid|
29 // isn't equal to the current PID, try to obtain file descriptor by opening
30 // file "report_path_prefix.<PID>".
31 fd_t report_fd = kStderrFd;
33 // Set via __sanitizer_set_report_path.
34 bool log_to_file = false;
35 char report_path_prefix[sizeof(report_path_prefix)];
37 // PID of process that opened |report_fd|. If a fork() occurs, the PID of the
38 // child thread will be different from |report_fd_pid|.
39 uptr report_fd_pid = 0;
41 // PID of the tracer task in StopTheWorld. It shares the address space with the
42 // main process, but has a different PID and thus requires special handling.
43 uptr stoptheworld_tracer_pid = 0;
44 // Cached pid of parent process - if the parent process dies, we want to keep
45 // writing to the same log file.
46 uptr stoptheworld_tracer_ppid = 0;
48 static DieCallbackType DieCallback;
49 void SetDieCallback(DieCallbackType callback) {
50 DieCallback = callback;
53 DieCallbackType GetDieCallback() {
54 return DieCallback;
57 void NORETURN Die() {
58 if (DieCallback) {
59 DieCallback();
61 internal__exit(1);
64 static CheckFailedCallbackType CheckFailedCallback;
65 void SetCheckFailedCallback(CheckFailedCallbackType callback) {
66 CheckFailedCallback = callback;
69 void NORETURN CheckFailed(const char *file, int line, const char *cond,
70 u64 v1, u64 v2) {
71 if (CheckFailedCallback) {
72 CheckFailedCallback(file, line, cond, v1, v2);
74 Report("Sanitizer CHECK failed: %s:%d %s (%lld, %lld)\n", file, line, cond,
75 v1, v2);
76 Die();
79 uptr ReadFileToBuffer(const char *file_name, char **buff,
80 uptr *buff_size, uptr max_len) {
81 uptr PageSize = GetPageSizeCached();
82 uptr kMinFileLen = PageSize;
83 uptr read_len = 0;
84 *buff = 0;
85 *buff_size = 0;
86 // The files we usually open are not seekable, so try different buffer sizes.
87 for (uptr size = kMinFileLen; size <= max_len; size *= 2) {
88 uptr openrv = OpenFile(file_name, /*write*/ false);
89 if (internal_iserror(openrv)) return 0;
90 fd_t fd = openrv;
91 UnmapOrDie(*buff, *buff_size);
92 *buff = (char*)MmapOrDie(size, __func__);
93 *buff_size = size;
94 // Read up to one page at a time.
95 read_len = 0;
96 bool reached_eof = false;
97 while (read_len + PageSize <= size) {
98 uptr just_read = internal_read(fd, *buff + read_len, PageSize);
99 if (just_read == 0) {
100 reached_eof = true;
101 break;
103 read_len += just_read;
105 internal_close(fd);
106 if (reached_eof) // We've read the whole file.
107 break;
109 return read_len;
112 typedef bool UptrComparisonFunction(const uptr &a, const uptr &b);
114 template<class T>
115 static inline bool CompareLess(const T &a, const T &b) {
116 return a < b;
119 void SortArray(uptr *array, uptr size) {
120 InternalSort<uptr*, UptrComparisonFunction>(&array, size, CompareLess);
123 // We want to map a chunk of address space aligned to 'alignment'.
124 // We do it by maping a bit more and then unmaping redundant pieces.
125 // We probably can do it with fewer syscalls in some OS-dependent way.
126 void *MmapAlignedOrDie(uptr size, uptr alignment, const char *mem_type) {
127 // uptr PageSize = GetPageSizeCached();
128 CHECK(IsPowerOfTwo(size));
129 CHECK(IsPowerOfTwo(alignment));
130 uptr map_size = size + alignment;
131 uptr map_res = (uptr)MmapOrDie(map_size, mem_type);
132 uptr map_end = map_res + map_size;
133 uptr res = map_res;
134 if (res & (alignment - 1)) // Not aligned.
135 res = (map_res + alignment) & ~(alignment - 1);
136 uptr end = res + size;
137 if (res != map_res)
138 UnmapOrDie((void*)map_res, res - map_res);
139 if (end != map_end)
140 UnmapOrDie((void*)end, map_end - end);
141 return (void*)res;
144 const char *StripPathPrefix(const char *filepath,
145 const char *strip_path_prefix) {
146 if (filepath == 0) return 0;
147 if (strip_path_prefix == 0) return filepath;
148 const char *pos = internal_strstr(filepath, strip_path_prefix);
149 if (pos == 0) return filepath;
150 pos += internal_strlen(strip_path_prefix);
151 if (pos[0] == '.' && pos[1] == '/')
152 pos += 2;
153 return pos;
156 void PrintSourceLocation(InternalScopedString *buffer, const char *file,
157 int line, int column) {
158 CHECK(file);
159 buffer->append("%s",
160 StripPathPrefix(file, common_flags()->strip_path_prefix));
161 if (line > 0) {
162 buffer->append(":%d", line);
163 if (column > 0)
164 buffer->append(":%d", column);
168 void PrintModuleAndOffset(InternalScopedString *buffer, const char *module,
169 uptr offset) {
170 buffer->append("(%s+0x%zx)",
171 StripPathPrefix(module, common_flags()->strip_path_prefix),
172 offset);
175 void ReportErrorSummary(const char *error_message) {
176 if (!common_flags()->print_summary)
177 return;
178 InternalScopedBuffer<char> buff(kMaxSummaryLength);
179 internal_snprintf(buff.data(), buff.size(),
180 "SUMMARY: %s: %s", SanitizerToolName, error_message);
181 __sanitizer_report_error_summary(buff.data());
184 void ReportErrorSummary(const char *error_type, const char *file,
185 int line, const char *function) {
186 if (!common_flags()->print_summary)
187 return;
188 InternalScopedBuffer<char> buff(kMaxSummaryLength);
189 internal_snprintf(
190 buff.data(), buff.size(), "%s %s:%d %s", error_type,
191 file ? StripPathPrefix(file, common_flags()->strip_path_prefix) : "??",
192 line, function ? function : "??");
193 ReportErrorSummary(buff.data());
196 LoadedModule::LoadedModule(const char *module_name, uptr base_address) {
197 full_name_ = internal_strdup(module_name);
198 base_address_ = base_address;
199 n_ranges_ = 0;
202 void LoadedModule::addAddressRange(uptr beg, uptr end, bool executable) {
203 CHECK_LT(n_ranges_, kMaxNumberOfAddressRanges);
204 ranges_[n_ranges_].beg = beg;
205 ranges_[n_ranges_].end = end;
206 exec_[n_ranges_] = executable;
207 n_ranges_++;
210 bool LoadedModule::containsAddress(uptr address) const {
211 for (uptr i = 0; i < n_ranges_; i++) {
212 if (ranges_[i].beg <= address && address < ranges_[i].end)
213 return true;
215 return false;
218 char *StripModuleName(const char *module) {
219 if (module == 0)
220 return 0;
221 const char *short_module_name = internal_strrchr(module, '/');
222 if (short_module_name)
223 short_module_name += 1;
224 else
225 short_module_name = module;
226 return internal_strdup(short_module_name);
229 static atomic_uintptr_t g_total_mmaped;
231 void IncreaseTotalMmap(uptr size) {
232 if (!common_flags()->mmap_limit_mb) return;
233 uptr total_mmaped =
234 atomic_fetch_add(&g_total_mmaped, size, memory_order_relaxed) + size;
235 if ((total_mmaped >> 20) > common_flags()->mmap_limit_mb) {
236 // Since for now mmap_limit_mb is not a user-facing flag, just CHECK.
237 uptr mmap_limit_mb = common_flags()->mmap_limit_mb;
238 common_flags()->mmap_limit_mb = 0; // Allow mmap in CHECK.
239 RAW_CHECK(total_mmaped >> 20 < mmap_limit_mb);
243 void DecreaseTotalMmap(uptr size) {
244 if (!common_flags()->mmap_limit_mb) return;
245 atomic_fetch_sub(&g_total_mmaped, size, memory_order_relaxed);
248 } // namespace __sanitizer
250 using namespace __sanitizer; // NOLINT
252 extern "C" {
253 void __sanitizer_set_report_path(const char *path) {
254 if (!path)
255 return;
256 uptr len = internal_strlen(path);
257 if (len > sizeof(report_path_prefix) - 100) {
258 Report("ERROR: Path is too long: %c%c%c%c%c%c%c%c...\n",
259 path[0], path[1], path[2], path[3],
260 path[4], path[5], path[6], path[7]);
261 Die();
263 if (report_fd != kStdoutFd &&
264 report_fd != kStderrFd &&
265 report_fd != kInvalidFd)
266 internal_close(report_fd);
267 report_fd = kInvalidFd;
268 log_to_file = false;
269 if (internal_strcmp(path, "stdout") == 0) {
270 report_fd = kStdoutFd;
271 } else if (internal_strcmp(path, "stderr") == 0) {
272 report_fd = kStderrFd;
273 } else {
274 internal_strncpy(report_path_prefix, path, sizeof(report_path_prefix));
275 report_path_prefix[len] = '\0';
276 log_to_file = true;
280 void __sanitizer_report_error_summary(const char *error_summary) {
281 Printf("%s\n", error_summary);
283 } // extern "C"