1 // RUN: %clangxx -m64 -O0 -g -xc++ %s -o %t && %run %t
2 // RUN: %clangxx -m64 -O3 -g -xc++ %s -o %t && %run %t
3
4 #include <assert.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 #ifndef __has_feature
10 #define __has_feature(x) 0
11 #endif
12
13 #if __has_feature(memory_sanitizer)
14 #include <sanitizer/msan_interface.h>
check_mem_is_good(void * p,size_t s)15 static void check_mem_is_good(void *p, size_t s) {
16 __msan_check_mem_is_initialized(p, s);
17 }
18 #elif __has_feature(address_sanitizer)
19 #include <sanitizer/asan_interface.h>
check_mem_is_good(void * p,size_t s)20 static void check_mem_is_good(void *p, size_t s) {
21 assert(__asan_region_is_poisoned(p, s) == 0);
22 }
23 #else
check_mem_is_good(void * p,size_t s)24 static void check_mem_is_good(void *p, size_t s) {}
25 #endif
26
run(void)27 static void run(void) {
28 char *buf;
29 size_t buf_len;
30 fprintf(stderr, " &buf %p, &buf_len %p\n", &buf, &buf_len);
31 FILE *fp = open_memstream(&buf, &buf_len);
32 fprintf(fp, "hello");
33 fflush(fp);
34 check_mem_is_good(&buf, sizeof(buf));
35 check_mem_is_good(&buf_len, sizeof(buf_len));
36 check_mem_is_good(buf, buf_len);
37
38 char *p = new char[1024];
39 memset(p, 'a', 1023);
40 p[1023] = 0;
41 for (int i = 0; i < 100; ++i)
42 fprintf(fp, "%s", p);
43 delete[] p;
44 fflush(fp);
45 fprintf(stderr, " %p addr %p, len %zu\n", &buf, buf, buf_len);
46 check_mem_is_good(&buf, sizeof(buf));
47 check_mem_is_good(&buf_len, sizeof(buf_len));
48 check_mem_is_good(buf, buf_len);
49 fclose(fp);
50 free(buf);
51 }
52
main(void)53 int main(void) {
54 for (int i = 0; i < 100; ++i)
55 run();
56 return 0;
57 }
58