YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
ShmemPlatform.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2026-2026 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-License-Identifier: BSD-3-Clause
4 */
5
6#include "ShmemPlatform.h"
7#include "ShmemLogComponent.h"
8
9#include <yarp/os/Log.h>
10
11#include <cerrno>
12#include <cstring>
13#include <mutex>
14
15#if defined(_WIN32)
16# ifndef WIN32_LEAN_AND_MEAN
17# define WIN32_LEAN_AND_MEAN
18# endif
19# ifndef NOMINMAX
20# define NOMINMAX
21# endif
22# include <winsock2.h>
23# include <ws2tcpip.h>
24# include <windows.h>
25#else
26# include <arpa/inet.h>
27# include <fcntl.h>
28# include <netdb.h>
29# include <netinet/in.h>
30# include <semaphore.h>
31# include <sys/mman.h>
32# include <sys/socket.h>
33# include <sys/stat.h>
34# include <sys/types.h>
35# include <unistd.h>
36# if defined(__APPLE__)
37# include <chrono>
38# include <thread>
39# else
40# include <ctime>
41# endif
42#endif
43
44namespace {
45
46#if defined(_WIN32)
47
48using native_socket_t = SOCKET;
49const native_socket_t invalid_socket = INVALID_SOCKET;
50
51void ensureSocketInit()
52{
53 static std::once_flag flag;
54 std::call_once(flag, []() {
55 WSADATA wsaData;
56 WSAStartup(MAKEWORD(2, 2), &wsaData);
57 });
58}
59
60int closeNativeSocket(native_socket_t s)
61{
62 return closesocket(s);
63}
64
65bool isInterrupted()
66{
67 return false;
68}
69
70std::string lastError()
71{
72 return std::to_string(GetLastError());
73}
74
75std::string lastSocketError()
76{
77 return std::to_string(WSAGetLastError());
78}
79
80#else
81
82using native_socket_t = int;
83const native_socket_t invalid_socket = -1;
84
85void ensureSocketInit()
86{
87}
88
89int closeNativeSocket(native_socket_t s)
90{
91 return ::close(s);
92}
93
94bool isInterrupted()
95{
96 return errno == EINTR;
97}
98
99std::string lastError()
100{
101 return std::strerror(errno);
102}
103
104std::string lastSocketError()
105{
106 return std::strerror(errno);
107}
108
109#endif
110
111native_socket_t toNative(std::intptr_t fd)
112{
113 return static_cast<native_socket_t>(fd);
114}
115
116std::intptr_t fromNative(native_socket_t s)
117{
118 return (s == invalid_socket) ? -1 : static_cast<std::intptr_t>(s);
119}
120
121bool addressToString(const sockaddr_in& addr, std::string& host, int& port)
122{
123 char buf[INET_ADDRSTRLEN];
124 if (inet_ntop(AF_INET, const_cast<in_addr*>(&addr.sin_addr), buf, sizeof(buf)) == nullptr) {
125 return false;
126 }
127 host = buf;
128 port = ntohs(addr.sin_port);
129 return true;
130}
131
132} // namespace
133
134
135std::string shmem::objectName(const char* kind, int port, int index)
136{
137 std::string name;
138#if !defined(_WIN32)
139 // POSIX names must start with a slash
140 // (and must be shorter than 31 characters on macOS)
141 name = "/";
142#endif
143 name += "yarp_shm_";
144 name += kind;
145 name += "_" + std::to_string(port);
146 if (index >= 0) {
147 name += "_" + std::to_string(index);
148 }
149 return name;
150}
151
152
153/******************************************************************************
154 * SharedMemory
155 ******************************************************************************/
156
161
162#if defined(_WIN32)
163
164bool shmem::SharedMemory::create(const std::string& name, size_t size)
165{
166 close();
167
168 const auto sz = static_cast<unsigned long long>(size);
169 HANDLE h = CreateFileMappingA(INVALID_HANDLE_VALUE,
170 nullptr,
171 PAGE_READWRITE,
172 static_cast<DWORD>(sz >> 32),
173 static_cast<DWORD>(sz & 0xFFFFFFFFULL),
174 name.c_str());
175 if (h == nullptr) {
176 yCError(SHMEMCARRIER, "Cannot create shared memory %s (error %s)", name.c_str(), lastError().c_str());
177 return false;
178 }
179 if (GetLastError() == ERROR_ALREADY_EXISTS) {
180 // The object is still in use by someone else, and it might be too small
181 CloseHandle(h);
182 yCError(SHMEMCARRIER, "Shared memory %s already exists", name.c_str());
183 return false;
184 }
185
186 void* p = MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, 0);
187 if (p == nullptr) {
188 yCError(SHMEMCARRIER, "Cannot map shared memory %s (error %s)", name.c_str(), lastError().c_str());
189 CloseHandle(h);
190 return false;
191 }
192
193 m_handle = h;
194 m_data = p;
195 m_size = size;
196 return true;
197}
198
199bool shmem::SharedMemory::open(const std::string& name)
200{
201 close();
202
203 HANDLE h = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, name.c_str());
204 if (h == nullptr) {
205 yCError(SHMEMCARRIER, "Cannot open shared memory %s (error %s)", name.c_str(), lastError().c_str());
206 return false;
207 }
208
209 void* p = MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, 0);
210 if (p == nullptr) {
211 yCError(SHMEMCARRIER, "Cannot map shared memory %s (error %s)", name.c_str(), lastError().c_str());
212 CloseHandle(h);
213 return false;
214 }
215
216 MEMORY_BASIC_INFORMATION info;
217 m_size = (VirtualQuery(p, &info, sizeof(info)) != 0) ? info.RegionSize : 0;
218 m_handle = h;
219 m_data = p;
220 return true;
221}
222
224{
225 if (m_data != nullptr) {
226 UnmapViewOfFile(m_data);
227 m_data = nullptr;
228 }
229 if (m_handle != nullptr) {
230 CloseHandle(static_cast<HANDLE>(m_handle));
231 m_handle = nullptr;
232 }
233 m_size = 0;
234}
235
236void shmem::SharedMemory::unlink(const std::string& name)
237{
238 // Windows kernel objects are destroyed when the last handle is closed
239 YARP_UNUSED(name);
240}
241
242#else // POSIX
243
244bool shmem::SharedMemory::create(const std::string& name, size_t size)
245{
246 close();
247
248 // Remove any stale segment left by a crashed process
249 shm_unlink(name.c_str());
250
251 int fd = shm_open(name.c_str(), O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
252 if (fd < 0) {
253 yCError(SHMEMCARRIER, "Cannot create shared memory %s (%s)", name.c_str(), lastError().c_str());
254 return false;
255 }
256
257 if (ftruncate(fd, static_cast<off_t>(size)) != 0) {
258 yCError(SHMEMCARRIER, "Cannot resize shared memory %s (%s)", name.c_str(), lastError().c_str());
259 ::close(fd);
260 shm_unlink(name.c_str());
261 return false;
262 }
263
264 void* p = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
265 ::close(fd);
266 if (p == MAP_FAILED) {
267 yCError(SHMEMCARRIER, "Cannot map shared memory %s (%s)", name.c_str(), lastError().c_str());
268 shm_unlink(name.c_str());
269 return false;
270 }
271
272 m_data = p;
273 m_size = size;
274 return true;
275}
276
277bool shmem::SharedMemory::open(const std::string& name)
278{
279 close();
280
281 int fd = shm_open(name.c_str(), O_RDWR, 0);
282 if (fd < 0) {
283 yCError(SHMEMCARRIER, "Cannot open shared memory %s (%s)", name.c_str(), lastError().c_str());
284 return false;
285 }
286
287 struct stat st;
288 if (fstat(fd, &st) != 0 || st.st_size <= 0) {
289 yCError(SHMEMCARRIER, "Cannot get the size of shared memory %s", name.c_str());
290 ::close(fd);
291 return false;
292 }
293
294 const auto size = static_cast<size_t>(st.st_size);
295 void* p = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
296 ::close(fd);
297 if (p == MAP_FAILED) {
298 yCError(SHMEMCARRIER, "Cannot map shared memory %s (%s)", name.c_str(), lastError().c_str());
299 return false;
300 }
301
302 m_data = p;
303 m_size = size;
304 return true;
305}
306
308{
309 if (m_data != nullptr) {
310 munmap(m_data, m_size);
311 m_data = nullptr;
312 }
313 m_size = 0;
314}
315
316void shmem::SharedMemory::unlink(const std::string& name)
317{
318 shm_unlink(name.c_str());
319}
320
321#endif
322
323
324/******************************************************************************
325 * NamedSemaphore
326 ******************************************************************************/
327
332
333#if defined(_WIN32)
334
335bool shmem::NamedSemaphore::create(const std::string& name, unsigned int initial, unsigned int max)
336{
337 close();
338
339 HANDLE h = CreateSemaphoreA(nullptr, static_cast<LONG>(initial), static_cast<LONG>(max), name.c_str());
340 if (h == nullptr) {
341 yCError(SHMEMCARRIER, "Cannot create semaphore %s (error %s)", name.c_str(), lastError().c_str());
342 return false;
343 }
344 if (GetLastError() == ERROR_ALREADY_EXISTS) {
345 // The object is still in use by someone else, its count is unknown
346 CloseHandle(h);
347 yCError(SHMEMCARRIER, "Semaphore %s already exists", name.c_str());
348 return false;
349 }
350 m_handle = h;
351 return true;
352}
353
354bool shmem::NamedSemaphore::open(const std::string& name)
355{
356 close();
357
358 HANDLE h = OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, FALSE, name.c_str());
359 if (h == nullptr) {
360 yCError(SHMEMCARRIER, "Cannot open semaphore %s (error %s)", name.c_str(), lastError().c_str());
361 return false;
362 }
363 m_handle = h;
364 return true;
365}
366
368{
369 if (m_handle != nullptr) {
370 CloseHandle(static_cast<HANDLE>(m_handle));
371 m_handle = nullptr;
372 }
373}
374
375void shmem::NamedSemaphore::unlink(const std::string& name)
376{
377 // Windows kernel objects are destroyed when the last handle is closed
378 YARP_UNUSED(name);
379}
380
382{
383 if (m_handle == nullptr) {
384 return false;
385 }
386 return WaitForSingleObject(static_cast<HANDLE>(m_handle), INFINITE) == WAIT_OBJECT_0;
387}
388
389bool shmem::NamedSemaphore::waitFor(double timeout)
390{
391 if (m_handle == nullptr) {
392 return false;
393 }
394 const auto ms = static_cast<DWORD>(timeout > 0 ? timeout * 1000.0 : 0);
395 return WaitForSingleObject(static_cast<HANDLE>(m_handle), ms) == WAIT_OBJECT_0;
396}
397
399{
400 if (m_handle == nullptr) {
401 return false;
402 }
403 return ReleaseSemaphore(static_cast<HANDLE>(m_handle), 1, nullptr) != 0;
404}
405
406#else // POSIX
407
408bool shmem::NamedSemaphore::create(const std::string& name, unsigned int initial, unsigned int max)
409{
410 YARP_UNUSED(max);
411 close();
412
413 // Remove any stale semaphore left by a crashed process
414 sem_unlink(name.c_str());
415
416 sem_t* s = sem_open(name.c_str(), O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, initial);
417 if (s == SEM_FAILED) {
418 yCError(SHMEMCARRIER, "Cannot create semaphore %s (%s)", name.c_str(), lastError().c_str());
419 return false;
420 }
421 m_handle = s;
422 return true;
423}
424
425bool shmem::NamedSemaphore::open(const std::string& name)
426{
427 close();
428
429 sem_t* s = sem_open(name.c_str(), 0);
430 if (s == SEM_FAILED) {
431 yCError(SHMEMCARRIER, "Cannot open semaphore %s (%s)", name.c_str(), lastError().c_str());
432 return false;
433 }
434 m_handle = s;
435 return true;
436}
437
439{
440 if (m_handle != nullptr) {
441 sem_close(static_cast<sem_t*>(m_handle));
442 m_handle = nullptr;
443 }
444}
445
446void shmem::NamedSemaphore::unlink(const std::string& name)
447{
448 sem_unlink(name.c_str());
449}
450
452{
453 if (m_handle == nullptr) {
454 return false;
455 }
456 while (sem_wait(static_cast<sem_t*>(m_handle)) != 0) {
457 if (errno != EINTR) {
458 return false;
459 }
460 }
461 return true;
462}
463
465{
466 if (m_handle == nullptr) {
467 return false;
468 }
469 auto* s = static_cast<sem_t*>(m_handle);
470
471#if defined(__APPLE__)
472 // sem_timedwait is not available on macOS
473 const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration<double>(timeout);
474 while (true) {
475 if (sem_trywait(s) == 0) {
476 return true;
477 }
478 if (errno != EAGAIN && errno != EINTR) {
479 return false;
480 }
481 if (std::chrono::steady_clock::now() >= deadline) {
482 return false;
483 }
484 std::this_thread::sleep_for(std::chrono::microseconds(100));
485 }
486#else
487 // The timeout of sem_timedwait is an absolute time
488 struct timespec ts;
489 clock_gettime(CLOCK_REALTIME, &ts);
490 const auto sec = static_cast<time_t>(timeout);
491 ts.tv_sec += sec;
492 ts.tv_nsec += static_cast<long>((timeout - static_cast<double>(sec)) * 1e9);
493 if (ts.tv_nsec >= 1000000000L) {
494 ts.tv_sec += 1;
495 ts.tv_nsec -= 1000000000L;
496 }
497 while (sem_timedwait(s, &ts) != 0) {
498 if (errno != EINTR) {
499 return false;
500 }
501 }
502 return true;
503#endif
504}
505
507{
508 if (m_handle == nullptr) {
509 return false;
510 }
511 return sem_post(static_cast<sem_t*>(m_handle)) == 0;
512}
513
514#endif
515
516
517/******************************************************************************
518 * Socket
519 ******************************************************************************/
520
522{
523 close();
524}
525
527{
528 ensureSocketInit();
529 close();
530
531 native_socket_t s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
532 if (s == invalid_socket) {
533 yCError(SHMEMCARRIER, "Cannot create socket (%s)", lastSocketError().c_str());
534 return false;
535 }
536
537 sockaddr_in addr;
538 std::memset(&addr, 0, sizeof(addr));
539 addr.sin_family = AF_INET;
540 addr.sin_addr.s_addr = htonl(INADDR_ANY);
541 addr.sin_port = htons(static_cast<uint16_t>(port));
542
543 if (::bind(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
544 yCError(SHMEMCARRIER, "Cannot bind socket to port %d (%s)", port, lastSocketError().c_str());
545 closeNativeSocket(s);
546 return false;
547 }
548
549 if (::listen(s, 5) != 0) {
550 yCError(SHMEMCARRIER, "Cannot listen on socket (%s)", lastSocketError().c_str());
551 closeNativeSocket(s);
552 return false;
553 }
554
555 m_fd = fromNative(s);
556 return true;
557}
558
560{
561 stream.close();
562 if (m_fd < 0) {
563 return false;
564 }
565
566 native_socket_t s;
567 do {
568 s = ::accept(toNative(m_fd), nullptr, nullptr);
569 } while (s == invalid_socket && isInterrupted());
570
571 if (s == invalid_socket) {
572 yCError(SHMEMCARRIER, "Cannot accept connection (%s)", lastSocketError().c_str());
573 return false;
574 }
575
576 stream.m_fd = fromNative(s);
577 return true;
578}
579
580bool shmem::Socket::connect(const std::string& host, int port)
581{
582 ensureSocketInit();
583 close();
584
585 addrinfo hints;
586 std::memset(&hints, 0, sizeof(hints));
587 hints.ai_family = AF_INET;
588 hints.ai_socktype = SOCK_STREAM;
589 hints.ai_protocol = IPPROTO_TCP;
590
591 addrinfo* res = nullptr;
592 const std::string service = std::to_string(port);
593 if (getaddrinfo(host.c_str(), service.c_str(), &hints, &res) != 0 || res == nullptr) {
594 yCError(SHMEMCARRIER, "Cannot resolve address %s:%d", host.c_str(), port);
595 return false;
596 }
597
598 native_socket_t s = invalid_socket;
599 for (addrinfo* ai = res; ai != nullptr; ai = ai->ai_next) {
600 s = ::socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
601 if (s == invalid_socket) {
602 continue;
603 }
604 int ret;
605 do {
606 ret = ::connect(s, ai->ai_addr, static_cast<int>(ai->ai_addrlen));
607 } while (ret != 0 && isInterrupted());
608 if (ret == 0) {
609 break;
610 }
611 closeNativeSocket(s);
612 s = invalid_socket;
613 }
614 freeaddrinfo(res);
615
616 if (s == invalid_socket) {
617 yCError(SHMEMCARRIER, "Cannot connect to %s:%d (%s)", host.c_str(), port, lastSocketError().c_str());
618 return false;
619 }
620
621#if defined(__APPLE__)
622 int on = 1;
623 setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
624#endif
625
626 m_fd = fromNative(s);
627 return true;
628}
629
630bool shmem::Socket::sendAll(const void* data, size_t len)
631{
632 if (m_fd < 0) {
633 return false;
634 }
635
636#if defined(MSG_NOSIGNAL)
637 const int flags = MSG_NOSIGNAL;
638#else
639 const int flags = 0;
640#endif
641
642 const char* p = static_cast<const char*>(data);
643 while (len > 0) {
644 auto ret = ::send(toNative(m_fd), p, static_cast<int>(len), flags);
645 if (ret < 0) {
646 if (isInterrupted()) {
647 continue;
648 }
649 return false;
650 }
651 if (ret == 0) {
652 return false;
653 }
654 p += ret;
655 len -= static_cast<size_t>(ret);
656 }
657 return true;
658}
659
660bool shmem::Socket::recvAll(void* data, size_t len)
661{
662 if (m_fd < 0) {
663 return false;
664 }
665
666 char* p = static_cast<char*>(data);
667 while (len > 0) {
668 auto ret = ::recv(toNative(m_fd), p, static_cast<int>(len), 0);
669 if (ret < 0) {
670 if (isInterrupted()) {
671 continue;
672 }
673 return false;
674 }
675 if (ret == 0) {
676 return false;
677 }
678 p += ret;
679 len -= static_cast<size_t>(ret);
680 }
681 return true;
682}
683
685{
686 if (m_fd < 0) {
687 return true;
688 }
689 // Nothing is ever sent on this socket after the handshake
690 char buf;
691 auto ret = ::recv(toNative(m_fd), &buf, 1, 0);
692 if (ret == 0) {
693 // Orderly shutdown
694 return true;
695 }
696 if (ret > 0) {
697 return false;
698 }
699 // When a process dies, the connection is usually reset (e.g. on Windows
700 // recv fails with WSAECONNRESET), therefore any error except "no data
701 // available" means that the peer is gone
702#if defined(_WIN32)
703 const int err = WSAGetLastError();
704 return !(err == WSAEWOULDBLOCK || err == WSAEINTR);
705#else
706 return !(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR);
707#endif
708}
709
711{
712 if (m_fd < 0) {
713 return false;
714 }
715#if defined(_WIN32)
716 u_long mode = 1;
717 return ioctlsocket(toNative(m_fd), FIONBIO, &mode) == 0;
718#else
719 int flags = fcntl(toNative(m_fd), F_GETFL, 0);
720 if (flags < 0) {
721 return false;
722 }
723 return fcntl(toNative(m_fd), F_SETFL, flags | O_NONBLOCK) == 0;
724#endif
725}
726
727bool shmem::Socket::getLocalAddress(std::string& host, int& port) const
728{
729 if (m_fd < 0) {
730 return false;
731 }
732 sockaddr_in addr;
733 socklen_t len = sizeof(addr);
734 if (getsockname(toNative(m_fd), reinterpret_cast<sockaddr*>(&addr), &len) != 0) {
735 return false;
736 }
737 return addressToString(addr, host, port);
738}
739
740bool shmem::Socket::getRemoteAddress(std::string& host, int& port) const
741{
742 if (m_fd < 0) {
743 return false;
744 }
745 sockaddr_in addr;
746 socklen_t len = sizeof(addr);
747 if (getpeername(toNative(m_fd), reinterpret_cast<sockaddr*>(&addr), &len) != 0) {
748 return false;
749 }
750 return addressToString(addr, host, port);
751}
752
754{
755 if (m_fd >= 0) {
756 closeNativeSocket(toNative(m_fd));
757 m_fd = -1;
758 }
759}
FeatureMode mode
void * HANDLE
const yarp::os::LogComponent & SHMEMCARRIER()
bool waitFor(double timeout)
Wait at most timeout seconds. Returns true if the semaphore was acquired.
bool wait()
Wait until the semaphore is available.
static void unlink(const std::string &name)
Remove the name of the semaphore (no-op on Windows)
bool create(const std::string &name, unsigned int initial, unsigned int max)
Create a new semaphore (removing any stale semaphore with the same name)
bool open(const std::string &name)
Open an existing semaphore.
static void unlink(const std::string &name)
Remove the name of the segment (no-op on Windows)
void close()
Unmap the segment.
bool create(const std::string &name, size_t size)
Create a new segment (removing any stale segment with the same name)
bool open(const std::string &name)
Open an existing segment.
A minimal IPv4 TCP socket.
bool recvAll(void *data, size_t len)
Receive exactly len bytes (blocking socket)
bool accept(Socket &stream)
Accept a connection on a listening socket.
bool connect(const std::string &host, int port)
bool listen(int port)
Listen on all the interfaces (port 0 means any free port)
bool isPeerClosed()
Check, on a non-blocking socket, whether the connection was closed or reset by the peer (e....
bool sendAll(const void *data, size_t len)
Send exactly len bytes (blocking socket)
bool getRemoteAddress(std::string &host, int &port) const
bool getLocalAddress(std::string &host, int &port) const
#define yCError(component,...)
std::string objectName(const char *kind, int port, int index=-1)
Build the name of a named inter-process object.
#define YARP_UNUSED(var)
Definition api.h:162