• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // REQUIRES: x86_64-target-arch
4 
5 #include <assert.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 
10 #ifndef __has_feature
11 #define __has_feature(x) 0
12 #endif
13 
14 #if __has_feature(memory_sanitizer)
15 #include <sanitizer/msan_interface.h>
check_mem_is_good(void * p,size_t s)16 static void check_mem_is_good(void *p, size_t s) {
17   __msan_check_mem_is_initialized(p, s);
18 }
19 #elif __has_feature(address_sanitizer)
20 #include <sanitizer/asan_interface.h>
check_mem_is_good(void * p,size_t s)21 static void check_mem_is_good(void *p, size_t s) {
22   assert(__asan_region_is_poisoned(p, s) == 0);
23 }
24 #else
check_mem_is_good(void * p,size_t s)25 static void check_mem_is_good(void *p, size_t s) {}
26 #endif
27 
run(bool flush)28 static void run(bool flush) {
29   char *buf;
30   size_t buf_len;
31   fprintf(stderr, " &buf %p, &buf_len %p\n", &buf, &buf_len);
32   FILE *fp = open_memstream(&buf, &buf_len);
33   fprintf(fp, "hello");
34   if (flush) {
35     fflush(fp);
36     check_mem_is_good(&buf, sizeof(buf));
37     check_mem_is_good(&buf_len, sizeof(buf_len));
38     check_mem_is_good(buf, buf_len);
39   }
40 
41   char *p = new char[1024];
42   memset(p, 'a', 1023);
43   p[1023] = 0;
44   for (int i = 0; i < 100; ++i)
45     fprintf(fp, "%s", p);
46   delete[] p;
47 
48   if (flush) {
49     fflush(fp);
50     fprintf(stderr, " %p addr %p, len %zu\n", &buf, buf, buf_len);
51     check_mem_is_good(&buf, sizeof(buf));
52     check_mem_is_good(&buf_len, sizeof(buf_len));
53     check_mem_is_good(buf, buf_len);\
54   }
55 
56   fclose(fp);
57   check_mem_is_good(&buf, sizeof(buf));
58   check_mem_is_good(&buf_len, sizeof(buf_len));
59   check_mem_is_good(buf, buf_len);
60 
61   free(buf);
62 }
63 
main(void)64 int main(void) {
65   for (int i = 0; i < 100; ++i)
66     run(false);
67   for (int i = 0; i < 100; ++i)
68     run(true);
69   return 0;
70 }
71