blob: 3bce030ddb23b0e653e708e60b60f5803c0ae006 [file] [log] [blame]
Stephen Hines2d1fdb22014-05-28 23:58:16 -07001// RUN: %clangxx -m64 -O0 -g -xc++ %s -o %t && %run %t
2// RUN: %clangxx -m64 -O3 -g -xc++ %s -o %t && %run %t
Pirama Arumuga Nainar7c915052015-04-08 08:58:29 -07003// REQUIRES: x86_64-supported-target
Stephen Hines2d1fdb22014-05-28 23:58:16 -07004
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>
16static 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>
21static void check_mem_is_good(void *p, size_t s) {
22 assert(__asan_region_is_poisoned(p, s) == 0);
23}
24#else
25static void check_mem_is_good(void *p, size_t s) {}
26#endif
27
Pirama Arumuga Nainar799172d2016-03-03 15:50:30 -080028static void run(bool flush) {
Stephen Hines2d1fdb22014-05-28 23:58:16 -070029 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");
Pirama Arumuga Nainar799172d2016-03-03 15:50:30 -080034 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 }
Stephen Hines2d1fdb22014-05-28 23:58:16 -070040
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;
Pirama Arumuga Nainar799172d2016-03-03 15:50:30 -080047
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);
Stephen Hines2d1fdb22014-05-28 23:58:16 -070057 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);
Pirama Arumuga Nainar799172d2016-03-03 15:50:30 -080060
Stephen Hines2d1fdb22014-05-28 23:58:16 -070061 free(buf);
62}
63
64int main(void) {
65 for (int i = 0; i < 100; ++i)
Pirama Arumuga Nainar799172d2016-03-03 15:50:30 -080066 run(false);
67 for (int i = 0; i < 100; ++i)
68 run(true);
Stephen Hines2d1fdb22014-05-28 23:58:16 -070069 return 0;
70}