summaryrefslogtreecommitdiff
path: root/source/kit/shared_memory.win32.c
blob: 34bb2763d70ab5833084d24ba4a5afd3996dfda0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "shared_memory.h"

#if defined(_WIN32) && !defined(__CYGWIN__)
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
#  include <windows.h>

kit_shared_memory_t kit_shared_memory_open(kit_str_t name, i64 size,
                                           i32 mode) {
  kit_shared_memory_t mem;
  memset(&mem, 0, sizeof mem);

  char buf[264] = "Global\\";

  assert(size > 0);
  assert(name.size > 0);
  assert(name.size + 8 < sizeof buf);
  assert(name.values != NULL);

  if (name.size <= 0) {
    mem.status = KIT_ERROR_INVALID_NAME;
    return mem;
  }

  if (name.size + 8 >= sizeof buf) {
    mem.status = KIT_ERROR_NAME_TOO_LONG;
    return mem;
  }

  for (i64 i = 0; i < name.size; i++)
    if (name.values[i] == '/' || name.values[i] == '\\') {
      mem.status = KIT_ERROR_INVALID_NAME;
      return mem;
    }

  memcpy(buf + 7, name.values, name.size);
  buf[7 + name.size] = '\0';

  HANDLE h = mode == KIT_SHARED_MEMORY_CREATE
                 ? CreateFileMappingA(
                       INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
                       (DWORD) (size >> 32), (DWORD) size, buf)
                 : OpenFileMappingA(FILE_MAP_ALL_ACCESS, 0, buf);

  if (h == INVALID_HANDLE_VALUE) {
    mem.status = KIT_ERROR_OPEN_FAILED;
    return mem;
  }

  void *p = MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0,
                          (SIZE_T) size);

  if (p == NULL) {
    CloseHandle(h);
    mem.status = KIT_ERROR_MAP_FAILED;
    return mem;
  }

  mem.status  = KIT_OK;
  mem.size    = size;
  mem.bytes   = (u8 *) p;
  mem._handle = h;
  return mem;
}

kit_status_t kit_shared_memory_close(kit_shared_memory_t *mem) {
  assert(mem != NULL);

  i32 status = KIT_OK;

  if (!UnmapViewOfFile(mem->bytes))
    status |= KIT_ERROR_UNMAP_FAILED;
  if (!CloseHandle(mem->_handle))
    status |= KIT_ERROR_UNLINK_FAILED;

  return status;
}

kit_status_t kit_shared_memory_clean(kit_str_t name) {
  //  Do nothing.
  //

  return KIT_OK;
}
#endif