]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/fuzzer/FuzzerShmem.h
MFC r355070:
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / fuzzer / FuzzerShmem.h
1 //===- FuzzerShmem.h - shared memory interface ------------------*- C++ -* ===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // SharedMemoryRegion
10 //===----------------------------------------------------------------------===//
11
12 #ifndef LLVM_FUZZER_SHMEM_H
13 #define LLVM_FUZZER_SHMEM_H
14
15 #include <algorithm>
16 #include <cstring>
17 #include <string>
18
19 #include "FuzzerDefs.h"
20
21 namespace fuzzer {
22
23 class SharedMemoryRegion {
24  public:
25   bool Create(const char *Name);
26   bool Open(const char *Name);
27   bool Destroy(const char *Name);
28   uint8_t *GetData() { return Data; }
29   void PostServer() {Post(0);}
30   void WaitServer() {Wait(0);}
31   void PostClient() {Post(1);}
32   void WaitClient() {Wait(1);}
33
34   size_t WriteByteArray(const uint8_t *Bytes, size_t N) {
35     assert(N <= kShmemSize - sizeof(N));
36     memcpy(GetData(), &N, sizeof(N));
37     memcpy(GetData() + sizeof(N), Bytes, N);
38     assert(N == ReadByteArraySize());
39     return N;
40   }
41   size_t ReadByteArraySize() {
42     size_t Res;
43     memcpy(&Res, GetData(), sizeof(Res));
44     return Res;
45   }
46   uint8_t *GetByteArray() { return GetData() + sizeof(size_t); }
47
48   bool IsServer() const { return Data && IAmServer; }
49   bool IsClient() const { return Data && !IAmServer; }
50
51 private:
52
53   static const size_t kShmemSize = 1 << 22;
54   bool IAmServer;
55   std::string Path(const char *Name);
56   std::string SemName(const char *Name, int Idx);
57   void Post(int Idx);
58   void Wait(int Idx);
59
60   bool Map(int fd);
61   uint8_t *Data = nullptr;
62   void *Semaphore[2];
63 };
64
65 extern SharedMemoryRegion SMR;
66
67 }  // namespace fuzzer
68
69 #endif  // LLVM_FUZZER_SHMEM_H