1 /* Copyright (c) 2015-2023. The SimGrid Team. All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
6 #include "src/mc/remote/Channel.hpp"
11 #include <sys/socket.h>
12 #include <sys/types.h>
15 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_channel, mc, "MC interprocess communication");
17 namespace simgrid::mc {
18 Channel::Channel(int sock, Channel const& other) : socket_(sock)
20 if (not other.buffer_.empty()) {
21 ssize_t size = other.buffer_.size();
22 XBT_DEBUG("Adopt %d bytes buffered by father channel.", (int)size);
24 memcpy(buffer_.data(), other.buffer_.data(), size);
30 if (this->socket_ >= 0)
34 /** @brief Send a message; returns 0 on success or errno on failure */
35 int Channel::send(const void* message, size_t size) const
37 if (size >= sizeof(int) && is_valid_MessageType(*static_cast<const int*>(message))) {
38 XBT_DEBUG("Sending %s (%zu bytes sent)", to_c_str(*static_cast<const MessageType*>(message)), size);
40 XBT_DEBUG("Sending bytes directly (from address %p) (%zu bytes sent)", message, size);
42 XBT_WARN("Request to send a 0-sized message! Proceeding anyway.");
45 while (::send(this->socket_, message, size, 0) == -1) {
47 XBT_ERROR("Channel::send failure: %s", strerror(errno));
54 ssize_t Channel::receive(const void* message, size_t size, int flags)
56 size_t bufsize = buffer_.size();
58 void* whereto = const_cast<void*>(message);
61 XBT_DEBUG("%d %zu bytes (of %zu expected) are already in buffer", getpid(), bufsize, size);
62 if (bufsize >= size) {
64 memcpy(whereto, buffer_.data(), size);
65 memcpy(static_cast<void*>(buffer_.data()), buffer_.data() + size, bufsize - size);
66 buffer_.resize(bufsize - size);
70 memcpy(whereto, buffer_.data(), bufsize);
73 whereto = static_cast<char*>(whereto) + bufsize;
79 res = recv(this->socket_, whereto, todo, flags);
80 xbt_assert(res != -1 || errno == EAGAIN, "Channel::receive failure: %s", strerror(errno));
85 XBT_DEBUG("%d Wanted %d; Got %d from buffer and %d from network", getpid(), (int)size, (int)copied, (int)res);
87 if (static_cast<size_t>(res) >= sizeof(int) && is_valid_MessageType(*static_cast<const int*>(message))) {
88 XBT_DEBUG("%d Receive %s (requested %zu; received %zd at %p)", getpid(),
89 to_c_str(*static_cast<const MessageType*>(message)), size, res, message);
91 XBT_DEBUG("Receive %zd bytes", res);
96 void Channel::reinject(const char* data, size_t size)
98 xbt_assert(size > 0, "Cannot reinject less than one char (size: %lu)", size);
99 auto prev_size = buffer_.size();
100 XBT_DEBUG("%d Reinject %zu bytes on top of %zu pre-existing bytes", getpid(), size, prev_size);
101 buffer_.resize(prev_size + size);
102 memcpy(buffer_.data() + prev_size, data, size);
104 } // namespace simgrid::mc