|
| 1 | +//! add-flags.py(LDFLAGS): -Wl,--stack-first -Wl,--initial-memory=327680 |
| 2 | + |
| 3 | +#include <__macro_PAGESIZE.h> |
| 4 | +#include <stdio.h> |
| 5 | +#include <string.h> |
| 6 | + |
| 7 | +void test(char *ptr, char *want) { |
| 8 | + char *got = strrchr(ptr, 7); |
| 9 | + if (got != want) { |
| 10 | + printf("strrchr(%p, 7) = %p, want %p\n", ptr, got, want); |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +int main(void) { |
| 15 | + char *const LIMIT = (char *)(__builtin_wasm_memory_size(0) * PAGESIZE); |
| 16 | + |
| 17 | + for (ptrdiff_t length = 0; length < 64; length++) { |
| 18 | + for (ptrdiff_t alignment = 0; alignment < 24; alignment++) { |
| 19 | + for (ptrdiff_t pos = -2; pos < length + 2; pos++) { |
| 20 | + // Create a buffer with the given length, at a pointer with the given |
| 21 | + // alignment. Using the offset LIMIT - PAGESIZE - 8 means many buffers |
| 22 | + // will straddle a (Wasm, and likely OS) page boundary. Place the |
| 23 | + // character to find at every position in the buffer, including just |
| 24 | + // prior to it and after its end. |
| 25 | + char *ptr = LIMIT - PAGESIZE - 8 + alignment; |
| 26 | + memset(LIMIT - 2 * PAGESIZE, 0, 2 * PAGESIZE); |
| 27 | + memset(ptr, 5, pos > length ? pos : length); |
| 28 | + |
| 29 | + // The last instance of the character is found. |
| 30 | + ptr[0] = 7; |
| 31 | + ptr[pos] = 7; |
| 32 | + ptr[length] = 0; |
| 33 | + |
| 34 | + // The character is found if it's within range. |
| 35 | + char *want = NULL; |
| 36 | + if (length > 0) want = 0 <= pos && pos < length ? &ptr[pos] : ptr; |
| 37 | + test(ptr, want); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + // We need space for the terminator. |
| 42 | + if (length <= 1) continue; |
| 43 | + |
| 44 | + // Ensure we never read past the end of memory. |
| 45 | + char *ptr = LIMIT - length; |
| 46 | + memset(LIMIT - 2 * PAGESIZE, 0, 2 * PAGESIZE); |
| 47 | + memset(ptr, 5, length); |
| 48 | + |
| 49 | + ptr[0] = 7; |
| 50 | + ptr[length - 2] = 7; |
| 51 | + ptr[length - 1] = 0; |
| 52 | + test(ptr, &ptr[length - 2]); |
| 53 | + } |
| 54 | + |
| 55 | + return 0; |
| 56 | +} |
0 commit comments