Skip to content

Commit 86e23fc

Browse files
Romain-Geissler-1AkevinAlbs
authored andcommitted
CDRIVER-4627 use posix_fallocate when available (#1244)
Avoids an unexpected crash with SIGBUS when trying to allocate a /dev/shm shared memory but there is not enough memory. Indeed ftruncate doesn't ensure memory is properly allocated, it ony changes the file size from the VFS point of view, but doesn't actually allocate any memory. So ftruncate might work despite we have no memory left, and later when trying to zero-memset the mmapped buffer, we might actually get a SIGBUS signal crashing the whole process. Instead, make sure we can allocate the whole shared memory using posix_fallocate and gracefully handle allocation problems, without crashing. The chromium project faced a similar issue in the past: https://bugs.chromium.org/p/chromium/issues/detail?id=951431
1 parent ef4a9a0 commit 86e23fc

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

src/libmongoc/src/mongoc/mongoc-counters.c

+9-6
Original file line numberDiff line numberDiff line change
@@ -181,15 +181,18 @@ mongoc_counters_alloc (size_t size)
181181
goto fail_noclean;
182182
}
183183

184-
/*
185-
* NOTE:
186-
*
187-
* ftruncate() will cause reads to be zero. Therefore, we don't need to
188-
* do write() of zeroes to initialize the shared memory area.
189-
*/
184+
#if defined(__APPLE__)
185+
// macOS does not have posix_fallocate available.
190186
if (-1 == ftruncate (fd, size)) {
191187
goto fail_cleanup;
192188
}
189+
#else
190+
// Prefer posix_fallocate on Linux. posix_fallocate ensures that disk space
191+
// is allocated.
192+
if (0 != posix_fallocate (fd, 0, size)) {
193+
goto fail_cleanup;
194+
}
195+
#endif // __APPLE__
193196

194197
mem = mmap (NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
195198
if (mem == MAP_FAILED) {

0 commit comments

Comments
 (0)