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.

377 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. if (shm.isServer) {
  119. CARLA_SAFE_ASSERT(shm.map == INVALID_HANDLE_VALUE);
  120. }
  121. #endif
  122. #ifdef CARLA_OS_WIN
  123. if (shm.filename != nullptr)
  124. delete[] shm.filename;
  125. #else
  126. try {
  127. ::close(shm.fd);
  128. if (shm.filename != nullptr)
  129. {
  130. ::shm_unlink(shm.filename);
  131. delete[] shm.filename;
  132. }
  133. } CARLA_SAFE_EXCEPTION("carla_shm_close");
  134. #endif
  135. shm = gNullCarlaShm;
  136. }
  137. /*
  138. * Map a shared memory object to @a size bytes and return the memory address.
  139. * @note One shared memory object can only have one mapping at a time.
  140. */
  141. static inline
  142. void* carla_shm_map(carla_shm_t& shm, const std::size_t size) noexcept
  143. {
  144. CARLA_SAFE_ASSERT_RETURN(carla_is_shm_valid(shm), nullptr);
  145. CARLA_SAFE_ASSERT_RETURN(size > 0, nullptr);
  146. #ifdef CARLA_OS_WIN
  147. CARLA_SAFE_ASSERT_RETURN(shm.map == INVALID_HANDLE_VALUE, nullptr);
  148. #else
  149. CARLA_SAFE_ASSERT_RETURN(shm.size == 0, nullptr);
  150. #endif
  151. try {
  152. #ifdef CARLA_OS_WIN
  153. HANDLE map;
  154. if (shm.isServer)
  155. {
  156. SECURITY_ATTRIBUTES sa;
  157. carla_zeroStruct(sa);
  158. sa.nLength = sizeof(sa);
  159. sa.bInheritHandle = TRUE;
  160. map = ::CreateFileMappingA(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE|SEC_COMMIT, 0, size, shm.filename);
  161. if (map == nullptr || map == INVALID_HANDLE_VALUE)
  162. {
  163. const DWORD errorCode = ::GetLastError();
  164. carla_stderr2("CreateFileMapping failed for '%s', size:%lu, isServer:%i, errorCode:%x",
  165. shm.filename, size, shm.isServer, errorCode);
  166. return nullptr;
  167. }
  168. }
  169. else
  170. {
  171. map = ::OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, shm.filename);
  172. CARLA_SAFE_ASSERT_RETURN(map != nullptr, nullptr);
  173. CARLA_SAFE_ASSERT_RETURN(map != INVALID_HANDLE_VALUE, nullptr);
  174. }
  175. void* const ptr = ::MapViewOfFile(map, FILE_MAP_ALL_ACCESS, 0, 0, size);
  176. if (ptr == nullptr)
  177. {
  178. const DWORD errorCode = ::GetLastError();
  179. carla_stderr2("MapViewOfFile failed for '%s', size:%lu, isServer:%i, errorCode:%u",
  180. shm.filename, size, shm.isServer, errorCode);
  181. ::CloseHandle(map);
  182. return nullptr;
  183. }
  184. shm.map = map;
  185. return ptr;
  186. #else
  187. if (shm.filename != nullptr)
  188. {
  189. const int ret(::ftruncate(shm.fd, static_cast<off_t>(size)));
  190. CARLA_SAFE_ASSERT_RETURN(ret == 0, nullptr);
  191. }
  192. void* const ptr(::mmap(nullptr, size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_LOCKED, shm.fd, 0));
  193. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, nullptr);
  194. if (ptr == MAP_FAILED)
  195. {
  196. carla_stderr2("carla_shm_map() - mmap failed: %s", std::strerror(errno));
  197. return nullptr;
  198. }
  199. shm.size = size;
  200. return ptr;
  201. #endif
  202. } CARLA_SAFE_EXCEPTION_RETURN("carla_shm_map", nullptr);
  203. }
  204. /*
  205. * Unmap a shared memory object address.
  206. */
  207. static inline
  208. void carla_shm_unmap(carla_shm_t& shm, void* const ptr) noexcept
  209. {
  210. CARLA_SAFE_ASSERT_RETURN(carla_is_shm_valid(shm),);
  211. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  212. #ifdef CARLA_OS_WIN
  213. CARLA_SAFE_ASSERT_RETURN(shm.map != INVALID_HANDLE_VALUE,);
  214. #else
  215. CARLA_SAFE_ASSERT_RETURN(shm.size > 0,);
  216. #endif
  217. try {
  218. #ifdef CARLA_OS_WIN
  219. const HANDLE map = shm.map;
  220. shm.map = INVALID_HANDLE_VALUE;
  221. ::UnmapViewOfFile(ptr);
  222. ::CloseHandle(map);
  223. #else
  224. const std::size_t size(shm.size);
  225. shm.size = 0;
  226. const int ret(::munmap(ptr, size));
  227. CARLA_SAFE_ASSERT(ret == 0);
  228. #endif
  229. } CARLA_SAFE_EXCEPTION("carla_shm_unmap");
  230. }
  231. #ifndef __WINE__
  232. // -----------------------------------------------------------------------
  233. // advanced calls
  234. /*
  235. * Create and open a new shared memory object for a XXXXXX temp filename.
  236. * Will keep trying until a free random filename is obtained.
  237. */
  238. static inline
  239. carla_shm_t carla_shm_create_temp(char* const fileBase) noexcept
  240. {
  241. // check if the fileBase name is valid
  242. CARLA_SAFE_ASSERT_RETURN(fileBase != nullptr, gNullCarlaShm);
  243. const std::size_t fileBaseLen(std::strlen(fileBase));
  244. CARLA_SAFE_ASSERT_RETURN(fileBaseLen > 6, gNullCarlaShm);
  245. CARLA_SAFE_ASSERT_RETURN(std::strcmp(fileBase + (fileBaseLen - 6), "XXXXXX") == 0, gNullCarlaShm);
  246. // character set to use randomly
  247. static const char charSet[] = "abcdefghijklmnopqrstuvwxyz"
  248. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  249. "0123456789";
  250. static const int charSetLen = static_cast<int>(std::strlen(charSet) - 1); // -1 to avoid trailing '\0'
  251. // try until getting a valid shm is obtained or an error occurs
  252. for (;;)
  253. {
  254. // fill the XXXXXX characters randomly
  255. for (std::size_t c = fileBaseLen - 6; c < fileBaseLen; ++c)
  256. fileBase[c] = charSet[std::rand() % charSetLen];
  257. #ifdef CARLA_OS_WIN
  258. // Windows: check if file already exists
  259. const HANDLE h = ::CreateFileMapping(INVALID_HANDLE_VALUE, nullptr,
  260. PAGE_READWRITE|SEC_COMMIT, 0, 8, fileBase);
  261. if (h == INVALID_HANDLE_VALUE)
  262. {
  263. carla_stderr("carla_shm_create_temp(%s) - file mapping test error", fileBase);
  264. return gNullCarlaShm;
  265. }
  266. const DWORD error = ::GetLastError();
  267. ::CloseHandle(h);
  268. if (error == ERROR_ALREADY_EXISTS)
  269. {
  270. carla_stderr("carla_shm_create_temp(%s) - file exists, retrying", fileBase);
  271. continue;
  272. }
  273. #endif
  274. // (try to) create new shm for this filename
  275. const carla_shm_t shm = carla_shm_create(fileBase);
  276. // all ok!
  277. if (carla_is_shm_valid(shm))
  278. return shm;
  279. #ifndef CARLA_OS_WIN
  280. // Non-Windows: if file already exists, keep trying
  281. if (errno == EEXIST)
  282. {
  283. carla_stderr("carla_shm_create_temp(%s) - file exists, retrying", fileBase);
  284. continue;
  285. }
  286. const int localerrno = errno;
  287. carla_stderr("carla_shm_create_temp(%s) - failed, error code %i", fileBase, localerrno);
  288. #endif
  289. // some unknown error occurred, return null
  290. return gNullCarlaShm;
  291. }
  292. }
  293. // -----------------------------------------------------------------------
  294. // shared memory, templated calls
  295. /*
  296. * Map a shared memory object, handling object type and size.
  297. */
  298. template<typename T>
  299. static inline
  300. T* carla_shm_map(carla_shm_t& shm) noexcept
  301. {
  302. return (T*)carla_shm_map(shm, sizeof(T));
  303. }
  304. /*
  305. * Map a shared memory object and return if it's non-null.
  306. */
  307. template<typename T>
  308. static inline
  309. bool carla_shm_map(carla_shm_t& shm, T*& value) noexcept
  310. {
  311. value = (T*)carla_shm_map(shm, sizeof(T));
  312. return (value != nullptr);
  313. }
  314. #endif // __WINE__
  315. // -----------------------------------------------------------------------
  316. #ifndef CARLA_OS_LINUX
  317. # undef MAP_LOCKED
  318. #endif
  319. #endif // CARLA_SHM_UTILS_HPP_INCLUDED