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.

CarlaShmUtils.hpp 11KB

11 years ago
7 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /*
  2. * Carla shared memory utils
  3. * Copyright (C) 2013-2023 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. struct carla_shm_t { int fd; const char* filename; std::size_t size; };
  30. # define carla_shm_t_INIT { -1, nullptr, 0 }
  31. #endif
  32. // -----------------------------------------------------------------------
  33. // shared memory calls
  34. /*
  35. * Null object returned when a shared memory operation fails.
  36. */
  37. static const carla_shm_t gNullCarlaShm = carla_shm_t_INIT;
  38. /*
  39. * Check if a shared memory object is valid.
  40. */
  41. static inline
  42. bool carla_is_shm_valid(const carla_shm_t& shm) noexcept
  43. {
  44. #ifdef CARLA_OS_WIN
  45. return (shm.filename != nullptr);
  46. #else
  47. return (shm.fd >= 0);
  48. #endif
  49. }
  50. /*
  51. * Initialize a shared memory object to an invalid state.
  52. */
  53. static inline
  54. void carla_shm_init(carla_shm_t& shm) noexcept
  55. {
  56. shm = gNullCarlaShm;
  57. }
  58. /*
  59. * Create and open a new shared memory object.
  60. * Returns an invalid object if the operation failed or the filename already exists.
  61. */
  62. static inline
  63. carla_shm_t carla_shm_create(const char* const filename) noexcept
  64. {
  65. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', gNullCarlaShm);
  66. carla_shm_t ret;
  67. #ifdef CARLA_OS_WIN
  68. ret.map = INVALID_HANDLE_VALUE;
  69. ret.isServer = true;
  70. ret.filename = carla_strdup_safe(filename);
  71. #else
  72. try {
  73. ret.fd = ::shm_open(filename, O_CREAT|O_EXCL|O_RDWR, 0600);
  74. ret.filename = (ret.fd >= 0) ? carla_strdup_safe(filename) : nullptr;
  75. ret.size = 0;
  76. if (ret.fd >= 0 && ret.filename == nullptr)
  77. {
  78. ::close(ret.fd);
  79. ::shm_unlink(filename);
  80. ret.fd = -1;
  81. }
  82. } CARLA_SAFE_EXCEPTION_RETURN("carla_shm_create", gNullCarlaShm);
  83. #endif
  84. return ret;
  85. }
  86. /*
  87. * Attach to an existing shared memory object.
  88. */
  89. static inline
  90. carla_shm_t carla_shm_attach(const char* const filename) noexcept
  91. {
  92. CARLA_SAFE_ASSERT_RETURN(filename != nullptr && filename[0] != '\0', gNullCarlaShm);
  93. carla_shm_t ret;
  94. #ifdef CARLA_OS_WIN
  95. ret.map = INVALID_HANDLE_VALUE;
  96. ret.isServer = false;
  97. ret.filename = carla_strdup_safe(filename);
  98. #else
  99. try {
  100. ret.fd = ::shm_open(filename, O_RDWR, 0);
  101. ret.filename = nullptr;
  102. ret.size = 0;
  103. } CARLA_SAFE_EXCEPTION_RETURN("carla_shm_attach", gNullCarlaShm);
  104. #endif
  105. return ret;
  106. }
  107. /*
  108. * Close a shared memory object and invalidate it.
  109. */
  110. static inline
  111. void carla_shm_close(carla_shm_t& shm) noexcept
  112. {
  113. CARLA_SAFE_ASSERT_RETURN(carla_is_shm_valid(shm),);
  114. #ifdef CARLA_OS_WIN
  115. if (shm.isServer) {
  116. CARLA_SAFE_ASSERT(shm.map == INVALID_HANDLE_VALUE);
  117. }
  118. #endif
  119. #ifdef CARLA_OS_WIN
  120. if (shm.filename != nullptr)
  121. delete[] shm.filename;
  122. #else
  123. try {
  124. ::close(shm.fd);
  125. if (shm.filename != nullptr)
  126. {
  127. ::shm_unlink(shm.filename);
  128. delete[] shm.filename;
  129. }
  130. } CARLA_SAFE_EXCEPTION("carla_shm_close");
  131. #endif
  132. shm = gNullCarlaShm;
  133. }
  134. /*
  135. * Map a shared memory object to @a size bytes and return the memory address.
  136. * @note One shared memory object can only have one mapping at a time.
  137. */
  138. static inline
  139. void* carla_shm_map(carla_shm_t& shm, const std::size_t size) noexcept
  140. {
  141. CARLA_SAFE_ASSERT_RETURN(carla_is_shm_valid(shm), nullptr);
  142. CARLA_SAFE_ASSERT_RETURN(size > 0, nullptr);
  143. #ifdef CARLA_OS_WIN
  144. CARLA_SAFE_ASSERT_RETURN(shm.map == INVALID_HANDLE_VALUE, nullptr);
  145. #else
  146. CARLA_SAFE_ASSERT_RETURN(shm.size == 0, nullptr);
  147. #endif
  148. try {
  149. #ifdef CARLA_OS_WIN
  150. HANDLE map;
  151. if (shm.isServer)
  152. {
  153. SECURITY_ATTRIBUTES sa;
  154. carla_zeroStruct(sa);
  155. sa.nLength = sizeof(sa);
  156. sa.bInheritHandle = TRUE;
  157. map = ::CreateFileMappingA(INVALID_HANDLE_VALUE, &sa,
  158. PAGE_READWRITE|SEC_COMMIT, 0, static_cast<DWORD>(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. ::VirtualLock(ptr, size);
  183. shm.map = map;
  184. return ptr;
  185. #else
  186. if (shm.filename != nullptr)
  187. {
  188. const int ret(::ftruncate(shm.fd, static_cast<off_t>(size)));
  189. CARLA_SAFE_ASSERT_RETURN(ret == 0, nullptr);
  190. }
  191. void* ptr;
  192. #ifdef MAP_LOCKED
  193. ptr = ::mmap(nullptr, size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_LOCKED, shm.fd, 0);
  194. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, nullptr);
  195. if (ptr == MAP_FAILED)
  196. #endif
  197. {
  198. ptr = ::mmap(nullptr, size, PROT_READ|PROT_WRITE, MAP_SHARED, shm.fd, 0);
  199. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, nullptr);
  200. if (ptr == MAP_FAILED)
  201. {
  202. carla_stderr2("carla_shm_map() - mmap failed: %s", std::strerror(errno));
  203. return nullptr;
  204. }
  205. #ifndef MAP_LOCKED
  206. try {
  207. ::mlock(ptr, size);
  208. } CARLA_SAFE_EXCEPTION("carla_shm_map mlock");
  209. #endif
  210. }
  211. shm.size = size;
  212. return ptr;
  213. #endif
  214. } CARLA_SAFE_EXCEPTION_RETURN("carla_shm_map", nullptr);
  215. }
  216. /*
  217. * Unmap a shared memory object address.
  218. */
  219. static inline
  220. void carla_shm_unmap(carla_shm_t& shm, void* const ptr) noexcept
  221. {
  222. CARLA_SAFE_ASSERT_RETURN(carla_is_shm_valid(shm),);
  223. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr,);
  224. #ifdef CARLA_OS_WIN
  225. CARLA_SAFE_ASSERT_RETURN(shm.map != INVALID_HANDLE_VALUE,);
  226. #else
  227. CARLA_SAFE_ASSERT_RETURN(shm.size > 0,);
  228. #endif
  229. try {
  230. #ifdef CARLA_OS_WIN
  231. const HANDLE map = shm.map;
  232. shm.map = INVALID_HANDLE_VALUE;
  233. ::UnmapViewOfFile(ptr);
  234. ::CloseHandle(map);
  235. #else
  236. const std::size_t size(shm.size);
  237. shm.size = 0;
  238. const int ret(::munmap(ptr, size));
  239. CARLA_SAFE_ASSERT(ret == 0);
  240. #endif
  241. } CARLA_SAFE_EXCEPTION("carla_shm_unmap");
  242. }
  243. #ifndef __WINE__
  244. // -----------------------------------------------------------------------
  245. // advanced calls
  246. /*
  247. * Create and open a new shared memory object for a XXXXXX temp filename.
  248. * Will keep trying until a free random filename is obtained.
  249. */
  250. static inline
  251. carla_shm_t carla_shm_create_temp(char* const fileBase) noexcept
  252. {
  253. // check if the fileBase name is valid
  254. CARLA_SAFE_ASSERT_RETURN(fileBase != nullptr, gNullCarlaShm);
  255. const std::size_t fileBaseLen(std::strlen(fileBase));
  256. CARLA_SAFE_ASSERT_RETURN(fileBaseLen > 6, gNullCarlaShm);
  257. CARLA_SAFE_ASSERT_RETURN(std::strcmp(fileBase + (fileBaseLen - 6), "XXXXXX") == 0, gNullCarlaShm);
  258. // character set to use randomly
  259. static const char charSet[] = "abcdefghijklmnopqrstuvwxyz"
  260. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  261. "0123456789";
  262. static const int charSetLen = static_cast<int>(std::strlen(charSet) - 1); // -1 to avoid trailing '\0'
  263. // try until getting a valid shm is obtained or an error occurs
  264. for (;;)
  265. {
  266. // fill the XXXXXX characters randomly
  267. for (std::size_t c = fileBaseLen - 6; c < fileBaseLen; ++c)
  268. fileBase[c] = charSet[std::rand() % charSetLen];
  269. #ifdef CARLA_OS_WIN
  270. // Windows: check if file already exists
  271. const HANDLE h = ::CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr,
  272. PAGE_READWRITE|SEC_COMMIT, 0, 8, fileBase);
  273. if (h == INVALID_HANDLE_VALUE)
  274. {
  275. carla_stderr("carla_shm_create_temp(%s) - file mapping test error", fileBase);
  276. return gNullCarlaShm;
  277. }
  278. const DWORD error = ::GetLastError();
  279. ::CloseHandle(h);
  280. if (error == ERROR_ALREADY_EXISTS)
  281. {
  282. carla_stderr("carla_shm_create_temp(%s) - file exists, retrying", fileBase);
  283. continue;
  284. }
  285. #endif
  286. // (try to) create new shm for this filename
  287. const carla_shm_t shm = carla_shm_create(fileBase);
  288. // all ok!
  289. if (carla_is_shm_valid(shm))
  290. return shm;
  291. #ifndef CARLA_OS_WIN
  292. // Non-Windows: if file already exists, keep trying
  293. if (errno == EEXIST)
  294. {
  295. carla_stderr("carla_shm_create_temp(%s) - file exists, retrying", fileBase);
  296. continue;
  297. }
  298. const int localerrno = errno;
  299. carla_stderr("carla_shm_create_temp(%s) - failed, error code %i", fileBase, localerrno);
  300. #endif
  301. // some unknown error occurred, return null
  302. return gNullCarlaShm;
  303. }
  304. }
  305. // -----------------------------------------------------------------------
  306. // shared memory, templated calls
  307. /*
  308. * Map a shared memory object, handling object type and size.
  309. */
  310. template<typename T>
  311. static inline
  312. T* carla_shm_map(carla_shm_t& shm) noexcept
  313. {
  314. return (T*)carla_shm_map(shm, sizeof(T));
  315. }
  316. /*
  317. * Map a shared memory object and return if it's non-null.
  318. */
  319. template<typename T>
  320. static inline
  321. bool carla_shm_map(carla_shm_t& shm, T*& value) noexcept
  322. {
  323. value = (T*)carla_shm_map(shm, sizeof(T));
  324. return (value != nullptr);
  325. }
  326. #endif // __WINE__
  327. // -----------------------------------------------------------------------
  328. #endif // CARLA_SHM_UTILS_HPP_INCLUDED