blob: 53568e0acb69c93c6789b3a7354c2479f3db4fa3 [file] [log] [blame]
Kostya Serebryany98d592c2017-01-20 20:57:07 +00001//===- 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
21namespace fuzzer {
22
23class SharedMemoryRegion {
24 public:
Kostya Serebryany5c76e3d2017-02-01 00:07:47 +000025 bool Create(const char *Name);
Kostya Serebryany98d592c2017-01-20 20:57:07 +000026 bool Open(const char *Name);
27 bool Destroy(const char *Name);
Kostya Serebryany98d592c2017-01-20 20:57:07 +000028 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) {
Kostya Serebryany5c76e3d2017-02-01 00:07:47 +000035 assert(N <= kShmemSize - sizeof(N));
Kostya Serebryany98d592c2017-01-20 20:57:07 +000036 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
51private:
Kostya Serebryany5c76e3d2017-02-01 00:07:47 +000052
53 static const size_t kShmemSize = 1 << 22;
Kostya Serebryany98d592c2017-01-20 20:57:07 +000054 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);
Kostya Serebryany98d592c2017-01-20 20:57:07 +000061 uint8_t *Data = nullptr;
62 void *Semaphore[2];
63};
64
65extern SharedMemoryRegion SMR;
66
67} // namespace fuzzer
68
69#endif // LLVM_FUZZER_SHMEM_H