|
14 | 14 | * limitations under the License.
|
15 | 15 | */
|
16 | 16 |
|
| 17 | +#define __STDINT_LIMITS |
| 18 | + |
17 | 19 | #include <gtest/gtest.h>
|
18 | 20 |
|
| 21 | +#include <errno.h> |
19 | 22 | #include <stdint.h>
|
20 | 23 | #include <unistd.h>
|
21 | 24 |
|
22 | 25 | TEST(unistd, sysconf_SC_MONOTONIC_CLOCK) {
|
23 | 26 | ASSERT_GT(sysconf(_SC_MONOTONIC_CLOCK), 0);
|
24 | 27 | }
|
25 | 28 |
|
26 |
| -TEST(unistd, sbrk) { |
27 |
| - void* initial_break = sbrk(0); |
| 29 | +static void* get_brk() { |
| 30 | + return sbrk(0); |
| 31 | +} |
| 32 | + |
| 33 | +static void* page_align(uintptr_t addr) { |
| 34 | + uintptr_t mask = sysconf(_SC_PAGE_SIZE) - 1; |
| 35 | + return reinterpret_cast<void*>((addr + mask) & ~mask); |
| 36 | +} |
| 37 | + |
| 38 | +TEST(unistd, brk) { |
| 39 | + void* initial_break = get_brk(); |
| 40 | + |
| 41 | + // The kernel aligns the break to a page. |
| 42 | + void* new_break = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(initial_break) + 1); |
| 43 | + ASSERT_EQ(0, brk(new_break)); |
| 44 | + ASSERT_GE(get_brk(), new_break); |
28 | 45 |
|
29 |
| - void* new_break = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(initial_break) + 2000); |
| 46 | + new_break = page_align(reinterpret_cast<uintptr_t>(initial_break) + sysconf(_SC_PAGE_SIZE)); |
30 | 47 | ASSERT_EQ(0, brk(new_break));
|
| 48 | + ASSERT_EQ(get_brk(), new_break); |
| 49 | +} |
| 50 | + |
| 51 | +TEST(unistd, brk_ENOMEM) { |
| 52 | + ASSERT_EQ(-1, brk(reinterpret_cast<void*>(-1))); |
| 53 | + ASSERT_EQ(ENOMEM, errno); |
| 54 | +} |
| 55 | + |
| 56 | +TEST(unistd, sbrk_ENOMEM) { |
| 57 | + intptr_t current_brk = reinterpret_cast<intptr_t>(get_brk()); |
| 58 | + |
| 59 | +#if !defined(__GLIBC__) |
| 60 | + // Can't increase by so much that we'd overflow. |
| 61 | + ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(PTRDIFF_MAX)); |
| 62 | + ASSERT_EQ(ENOMEM, errno); |
| 63 | +#endif |
| 64 | + |
| 65 | + // Can't reduce by more than the current break. |
| 66 | + ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(-(current_brk + 1))); |
| 67 | + ASSERT_EQ(ENOMEM, errno); |
31 | 68 |
|
32 |
| - void* final_break = sbrk(0); |
33 |
| - ASSERT_EQ(final_break, new_break); |
| 69 | +#if !defined(__GLIBC__) |
| 70 | + // The maximum negative value is an interesting special case that glibc gets wrong. |
| 71 | + ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(PTRDIFF_MIN)); |
| 72 | + ASSERT_EQ(ENOMEM, errno); |
| 73 | +#endif |
34 | 74 | }
|
0 commit comments