Home | History | Annotate | Download | only in Linux
      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-supported-target
      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>
     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>
     21 static void check_mem_is_good(void *p, size_t s) {
     22   assert(__asan_region_is_poisoned(p, s) == 0);
     23 }
     24 #else
     25 static void check_mem_is_good(void *p, size_t s) {}
     26 #endif
     27 
     28 static void run(void) {
     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   fflush(fp);
     35   check_mem_is_good(&buf, sizeof(buf));
     36   check_mem_is_good(&buf_len, sizeof(buf_len));
     37   check_mem_is_good(buf, buf_len);
     38 
     39   char *p = new char[1024];
     40   memset(p, 'a', 1023);
     41   p[1023] = 0;
     42   for (int i = 0; i < 100; ++i)
     43     fprintf(fp, "%s", p);
     44   delete[] p;
     45   fflush(fp);
     46   fprintf(stderr, " %p addr %p, len %zu\n", &buf, buf, buf_len);
     47   check_mem_is_good(&buf, sizeof(buf));
     48   check_mem_is_good(&buf_len, sizeof(buf_len));
     49   check_mem_is_good(buf, buf_len);
     50   fclose(fp);
     51   free(buf);
     52 }
     53 
     54 int main(void) {
     55   for (int i = 0; i < 100; ++i)
     56     run();
     57   return 0;
     58 }
     59