1// Test fopencookie interceptor.
2// RUN: %clangxx_msan -std=c++11 -O0 %s -o %t && %run %t
3// RUN: %clangxx_msan -std=c++11 -fsanitize-memory-track-origins -O0 %s -o %t && %run %t
4
5#include <assert.h>
6#include <pthread.h>
7#include <stdint.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11
12#include <sanitizer/msan_interface.h>
13
14constexpr uintptr_t kMagicCookie = 0x12345678;
15
16static ssize_t cookie_read(void *cookie, char *buf, size_t size) {
17 assert((uintptr_t)cookie == kMagicCookie);
18 memset(s: buf, c: 0, n: size);
19 return 0;
20}
21
22static ssize_t cookie_write(void *cookie, const char *buf, size_t size) {
23 assert((uintptr_t)cookie == kMagicCookie);
24 __msan_check_mem_is_initialized(x: buf, size);
25 return 0;
26}
27
28static int cookie_seek(void *cookie, off64_t *offset, int whence) {
29 assert((uintptr_t)cookie == kMagicCookie);
30 __msan_check_mem_is_initialized(x: offset, size: sizeof(*offset));
31 return 0;
32}
33
34static int cookie_close(void *cookie) {
35 assert((uintptr_t)cookie == kMagicCookie);
36 return 0;
37}
38
39void PoisonStack() { char a[8192]; }
40
41void TestPoisonStack() {
42 // Verify that PoisonStack has poisoned the stack - otherwise this test is not
43 // testing anything.
44 char a;
45 assert(__msan_test_shadow(&a - 1000, 1) == 0);
46}
47
48int main() {
49 void *cookie = (void *)kMagicCookie;
50 FILE *f = fopencookie(magic_cookie: cookie, modes: "rw",
51 io_funcs: {.read: cookie_read, .write: cookie_write, .seek: cookie_seek, .close: cookie_close});
52 PoisonStack();
53 TestPoisonStack();
54 fseek(stream: f, off: 100, SEEK_SET);
55 char buf[50];
56 fread(ptr: buf, size: 50, n: 1, stream: f);
57 fwrite(ptr: buf, size: 50, n: 1, s: f);
58 fclose(stream: f);
59
60 f = fopencookie(magic_cookie: cookie, modes: "rw", io_funcs: {.read: nullptr, .write: nullptr, .seek: nullptr, .close: nullptr});
61 fseek(stream: f, off: 100, SEEK_SET);
62 fread(ptr: buf, size: 50, n: 1, stream: f);
63 fwrite(ptr: buf, size: 50, n: 1, s: f);
64 fclose(stream: f);
65}
66

source code of compiler-rt/test/msan/Linux/fopencookie.cpp