Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

375 lines
10KB

  1. /*
  2. * Carla shared memory utils
  3. * Copyright (C) 2013-2015 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #ifndef CARLA_SHM_UTILS_HPP_INCLUDED
  18. #define CARLA_SHM_UTILS_HPP_INCLUDED
  19. #include "CarlaUtils.hpp"
  20. #ifdef CARLA_OS_WIN
  21. struct carla_shm_t { HANDLE map; bool isServer; const char* filename; };
  22. # define carla_shm_t_INIT { INVALID_HANDLE_VALUE, true, nullptr }
  23. #else
  24. # ifndef __WINE__
  25. # include <cerrno>
  26. # endif
  27. # include <fcntl.h>
  28. # include <sys/mman.h>
  29. # ifndef MAP_LOCKED
  30. # define MAP_LOCKED 0x0
  31. # endif
  32. struct carla_shm_t { int fd; const char* filename; std::size_t size; };
  33. # define carla_shm_t_INIT { -1, nullptr, 0 }
  34. #endif
  35. // -----------------------------------------------------------------------
  36. // shared memory calls
  37. /*
  38. * Null object returned when a shared memory operation fails.
  39. */
  40. static const carla_shm_t gNullCarlaShm = carla_shm_t_INIT;
  41. /*
  42. * Check if a shared memory object is valid.
  43. */
  44. static inline
  45. bool carla_is_shm_valid(const carla_shm_t& shm) noexcept
  46. {
  47. #ifdef CARLA_OS_WIN
  48. return (shm.filename != nullptr);
  49. #else
  50. return (shm.fd >= 0);
  51. #endif
  52. }
  53. /*
  54. * Initialize a shared memory object to an invalid state.
  55. */
  56. static inline
  57. void carla_shm_init(carla_shm_t& shm) noexcept
  58. {
  59. shm = gNullCarlaShm;
  60. }
  61. /*
  62. * Create and open a new shared memory object.
  63. * Returns an invalid object if the operation failed or the filename already exists.
  64. */
  65. static inline
  66. carla_shm_t carla_shm_create(const char* const filename) noexcept
  67. {
  68. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', gNullCarlaShm);
  69. carla_shm_t ret;
  70. #ifdef CARLA_OS_WIN
  71. ret.map = INVALID_HANDLE_VALUE;
  72. ret.isServer = true;
  73. ret.filename = carla_strdup_safe(filename);
  74. #else
  75. try {
  76. ret.fd = ::shm_open(filename, O_CREAT|O_EXCL|O_RDWR, 0600);
  77. ret.filename = (ret.fd >= 0) ? carla_strdup_safe(filename) : nullptr;
  78. ret.size = 0;
  79. if (ret.fd >= 0 && ret.filename == nullptr)
  80. {
  81. ::close(ret.fd);
  82. ::shm_unlink(filename);
  83. ret.fd = -1;
  84. }
  85. } CARLA_SAFE_EXCEPTION_RETURN("carla_shm_create", gNullCarlaShm);
  86. #endif
  87. return ret;
  88. }
  89. /*
  90. * Attach to an existing shared memory object.
  91. */
  92. static inline
  93. carla_shm_t carla_shm_attach(const char* const filename) noexcept
  94. {
  95. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', gNullCarlaShm);
  96. carla_shm_t ret;
  97. #ifdef CARLA_OS_WIN
  98. ret.map = INVALID_HANDLE_VALUE;
  99. ret.isServer = false;
  100. ret.filename = carla_strdup_safe(filename);
  101. #else
  102. try {
  103. ret.fd = ::shm_open(filename, O_RDWR, 0);
  104. ret.filename = nullptr;
  105. ret.size = 0;
  106. } CARLA_SAFE_EXCEPTION_RETURN("carla_shm_attach", gNullCarlaShm);
  107. #endif
  108. return ret;
  109. }
  110. /*
  111. * Close a shared memory object and invalidate it.
  112. */
  113. static inline
  114. void carla_shm_close(carla_shm_t& shm) noexcept
  115. {
  116. CARLA_SAFE_ASSERT_RETURN(carla_is_shm_valid(shm),);
  117. #ifdef CARLA_OS_WIN
  118. CARLA_SAFE_ASSERT(shm.map == INVALID_HANDLE_VALUE);
  119. #endif
  120. #ifdef CARLA_OS_WIN
  121. if (shm.filename != nullptr)
  122. delete[] shm.filename;
  123. #else
  124. try {
  125. ::close(shm.fd);
  126. if (shm.filename != nullptr)
  127. {
  128. ::shm_unlink(shm.filename);
  129. delete[] shm.filename;
  130. }
  131. } CARLA_SAFE_EXCEPTION("carla_shm_close");
  132. #endif
  133. shm = gNullCarlaShm;
  134. }
  135. /*
  136. * Map a shared memory object to @a size bytes and return the memory address.
  137. * @note One shared memory object can only have one mapping at a time.
  138. */
  139. static inline
  140. void* carla_shm_map(carla_shm_t& shm, const std::size_t size) noexcept
  141. {
  142. CARLA_SAFE_ASSERT_RETURN(carla_is_shm_valid(shm), nullptr);
  143. CARLA_SAFE_ASSERT_RETURN(size > 0, nullptr);
  144. #ifdef CARLA_OS_WIN
  145. CARLA_SAFE_ASSERT_RETURN(shm.map == INVALID_HANDLE_VALUE, nullptr);
  146. #else
  147. CARLA_SAFE_ASSERT_RETURN(shm.size == 0, nullptr);
  148. #endif
  149. try {
  150. #ifdef CARLA_OS_WIN
  151. HANDLE map;
  152. if (shm.isServer)
  153. {
  154. SECURITY_ATTRIBUTES sa;
  155. carla_zeroStruct(sa);
  156. sa.nLength = sizeof(sa);
  157. sa.bInheritHandle = TRUE;
  158. map = ::CreateFileMappingA(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE|SEC_COMMIT, 0, size, shm.filename);
  159. if (map == nullptr || map == INVALID_HANDLE_VALUE)
  160. {
  161. const DWORD errorCode = ::GetLastError();
  162. carla_stderr2("CreateFileMapping failed for '%s', size:%lu, isServer:%i, errorCode:%x",
  163. shm.filename, size, shm.isServer, errorCode);
  164. return nullptr;
  165. }
  166. }
  167. else
  168. {
  169. map = ::OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, shm.filename);
  170. CARLA_SAFE_ASSERT_RETURN(map != nullptr, nullptr);
  171. CARLA_SAFE_ASSERT_RETURN(map != INVALID_HANDLE_VALUE, nullptr);
  172. }
  173. void* const ptr = ::MapViewOfFile(map, FILE_MAP_ALL_ACCESS, 0, 0, size);
  174. if (ptr == nullptr)
  175. {
  176. const DWORD errorCode = ::GetLastError();
  177. carla_stderr2("MapViewOfFile failed for '%s', size:%lu, isServer:%i, errorCode:%u",
  178. shm.filename, size, shm.isServer, errorCode);
  179. ::CloseHandle(map);
  180. return nullptr;
  181. }
  182. shm.map = map;
  183. return ptr;
  184. #else
  185. if (shm.filename != nullptr)
  186. {
  187. const int ret(::ftruncate(shm.fd, static_cast<off_t>(size)));
  188. CARLA_SAFE_ASSERT_RETURN(ret == 0, nullptr);
  189. }
  190. void* const ptr(::mmap(nullptr, size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_LOCKED, shm.fd, 0));
  191. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, nullptr);
  192. if (ptr == MAP_FAILED)
  193. {
  194. carla_stderr2("carla_shm_map() - mmap failed: %s", std::strerror(errno));
  195. return nullptr;
  196. }
  197. shm.size = size;
  198. return ptr;
  199. #endif
  200. } CARLA_SAFE_EXCEPTION_RETURN("carla_shm_map", nullptr);
  201. }
  202. /*
  203. * Unmap a shared memory object address.
  204. */
  205. static inline
  206. void carla_shm_unmap(carla_shm_t& shm, void* const ptr) noexcept
  207. {
  208. CARLA_SAFE_ASSERT_RETURN(carla_is_shm_valid(shm),);
  209. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  210. #ifdef CARLA_OS_WIN
  211. CARLA_SAFE_ASSERT_RETURN(shm.map != INVALID_HANDLE_VALUE,);
  212. #else
  213. CARLA_SAFE_ASSERT_RETURN(shm.size > 0,);
  214. #endif
  215. try {
  216. #ifdef CARLA_OS_WIN
  217. const HANDLE map(shm.map);
  218. shm.map = INVALID_HANDLE_VALUE;
  219. ::UnmapViewOfFile(ptr);
  220. ::CloseHandle(map);
  221. #else
  222. const std::size_t size(shm.size);
  223. shm.size = 0;
  224. const int ret(::munmap(ptr, size));
  225. CARLA_SAFE_ASSERT(ret == 0);
  226. #endif
  227. } CARLA_SAFE_EXCEPTION("carla_shm_unmap");
  228. }
  229. #ifndef __WINE__
  230. // -----------------------------------------------------------------------
  231. // advanced calls
  232. /*
  233. * Create and open a new shared memory object for a XXXXXX temp filename.
  234. * Will keep trying until a free random filename is obtained.
  235. */
  236. static inline
  237. carla_shm_t carla_shm_create_temp(char* const fileBase) noexcept
  238. {
  239. // check if the fileBase name is valid
  240. CARLA_SAFE_ASSERT_RETURN(fileBase != nullptr, gNullCarlaShm);
  241. const std::size_t fileBaseLen(std::strlen(fileBase));
  242. CARLA_SAFE_ASSERT_RETURN(fileBaseLen > 6, gNullCarlaShm);
  243. CARLA_SAFE_ASSERT_RETURN(std::strcmp(fileBase + (fileBaseLen - 6), "XXXXXX") == 0, gNullCarlaShm);
  244. // character set to use randomly
  245. static const char charSet[] = "abcdefghijklmnopqrstuvwxyz"
  246. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  247. "0123456789";
  248. static const int charSetLen = static_cast<int>(std::strlen(charSet) - 1); // -1 to avoid trailing '\0'
  249. // try until getting a valid shm is obtained or an error occurs
  250. for (;;)
  251. {
  252. // fill the XXXXXX characters randomly
  253. for (std::size_t c = fileBaseLen - 6; c < fileBaseLen; ++c)
  254. fileBase[c] = charSet[std::rand() % charSetLen];
  255. #ifdef CARLA_OS_WIN
  256. // Windows: check if file already exists
  257. const HANDLE h = ::CreateFileMapping(INVALID_HANDLE_VALUE, nullptr,
  258. PAGE_READWRITE|SEC_COMMIT, 0, 8, fileBase);
  259. if (h == INVALID_HANDLE_VALUE)
  260. {
  261. carla_stderr("carla_shm_create_temp(%s) - file mapping test error", fileBase);
  262. return gNullCarlaShm;
  263. }
  264. const DWORD error = ::GetLastError();
  265. ::CloseHandle(h);
  266. if (error == ERROR_ALREADY_EXISTS)
  267. {
  268. carla_stderr("carla_shm_create_temp(%s) - file exists, retrying", fileBase);
  269. continue;
  270. }
  271. #endif
  272. // (try to) create new shm for this filename
  273. const carla_shm_t shm = carla_shm_create(fileBase);
  274. // all ok!
  275. if (carla_is_shm_valid(shm))
  276. return shm;
  277. #ifndef CARLA_OS_WIN
  278. // Non-Windows: if file already exists, keep trying
  279. if (errno == EEXIST)
  280. {
  281. carla_stderr("carla_shm_create_temp(%s) - file exists, retrying", fileBase);
  282. continue;
  283. }
  284. const int localerrno = errno;
  285. carla_stderr("carla_shm_create_temp(%s) - failed, error code %i", fileBase, localerrno);
  286. #endif
  287. // some unknown error occurred, return null
  288. return gNullCarlaShm;
  289. }
  290. }
  291. // -----------------------------------------------------------------------
  292. // shared memory, templated calls
  293. /*
  294. * Map a shared memory object, handling object type and size.
  295. */
  296. template<typename T>
  297. static inline
  298. T* carla_shm_map(carla_shm_t& shm) noexcept
  299. {
  300. return (T*)carla_shm_map(shm, sizeof(T));
  301. }
  302. /*
  303. * Map a shared memory object and return if it's non-null.
  304. */
  305. template<typename T>
  306. static inline
  307. bool carla_shm_map(carla_shm_t& shm, T*& value) noexcept
  308. {
  309. value = (T*)carla_shm_map(shm, sizeof(T));
  310. return (value != nullptr);
  311. }
  312. #endif // __WINE__
  313. // -----------------------------------------------------------------------
  314. #ifndef CARLA_OS_LINUX
  315. # undef MAP_LOCKED
  316. #endif
  317. #endif // CARLA_SHM_UTILS_HPP_INCLUDED