Kostya Serebryany | 98d592c | 2017-01-20 20:57:07 +0000 | [diff] [blame] | 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, size_t Size); |
| 26 | bool Open(const char *Name); |
| 27 | bool Destroy(const char *Name); |
| 28 | size_t GetSize() const { return Size; } |
| 29 | uint8_t *GetData() { return Data; } |
| 30 | void PostServer() {Post(0);} |
| 31 | void WaitServer() {Wait(0);} |
| 32 | void PostClient() {Post(1);} |
| 33 | void WaitClient() {Wait(1);} |
| 34 | |
| 35 | size_t WriteByteArray(const uint8_t *Bytes, size_t N) { |
| 36 | N = std::min(N, GetSize() - sizeof(N)); |
| 37 | memcpy(GetData(), &N, sizeof(N)); |
| 38 | memcpy(GetData() + sizeof(N), Bytes, N); |
| 39 | assert(N == ReadByteArraySize()); |
| 40 | return N; |
| 41 | } |
| 42 | size_t ReadByteArraySize() { |
| 43 | size_t Res; |
| 44 | memcpy(&Res, GetData(), sizeof(Res)); |
| 45 | return Res; |
| 46 | } |
| 47 | uint8_t *GetByteArray() { return GetData() + sizeof(size_t); } |
| 48 | |
| 49 | bool IsServer() const { return Data && IAmServer; } |
| 50 | bool IsClient() const { return Data && !IAmServer; } |
| 51 | |
| 52 | private: |
| 53 | bool IAmServer; |
| 54 | std::string Path(const char *Name); |
| 55 | std::string SemName(const char *Name, int Idx); |
| 56 | void Post(int Idx); |
| 57 | void Wait(int Idx); |
| 58 | |
| 59 | bool Map(int fd); |
| 60 | size_t Size = 0; |
| 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 |