Fix some musl libc issues in armnn
[platform/upstream/armnn.git] / profiling / server / src / basePipeServer / BasePipeServer.cpp
1 //
2 // Copyright © 2020 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5
6 #include "BasePipeServer.hpp"
7
8 #include "common/include/Constants.hpp"
9
10 #include <iostream>
11 #include <boost/cast.hpp>
12 #include <vector>
13 #include <iomanip>
14 #include <string.h>
15
16 using namespace armnnUtils;
17
18 namespace armnnProfiling
19 {
20
21 bool BasePipeServer::ReadFromSocket(uint8_t* packetData, uint32_t expectedLength)
22 {
23     // This is a blocking read until either expectedLength has been received or an error is detected.
24     long totalBytesRead = 0;
25     while (boost::numeric_cast<uint32_t>(totalBytesRead) < expectedLength)
26     {
27         long bytesRead = Sockets::Read(m_ClientConnection, packetData, expectedLength);
28         if (bytesRead < 0)
29         {
30             std::cerr << ": Failure when reading from client socket: " << strerror(errno) << std::endl;
31             return false;
32         }
33         if (bytesRead == 0)
34         {
35             std::cerr << ": EOF while reading from client socket." << std::endl;
36             return false;
37         }
38         totalBytesRead += bytesRead;
39     }
40     return true;
41 };
42
43 bool BasePipeServer::WaitForStreamMetaData()
44 {
45     if (m_EchoPackets)
46     {
47         std::cout << "Waiting for stream meta data..." << std::endl;
48     }
49     // The start of the stream metadata is 2x32bit words, 0 and packet length.
50     uint8_t header[8];
51     if (!ReadFromSocket(header, 8))
52     {
53         return false;
54     }
55     EchoPacket(PacketDirection::ReceivedHeader, header, 8);
56     // The first word, stream_metadata_identifer, should always be 0.
57     if (ToUint32(&header[0], TargetEndianness::BeWire) != 0)
58     {
59         std::cerr << ": Protocol error. The stream_metadata_identifer was not 0." << std::endl;
60         return false;
61     }
62
63     uint8_t pipeMagic[4];
64     if (!ReadFromSocket(pipeMagic, 4))
65     {
66         return false;
67     }
68     EchoPacket(PacketDirection::ReceivedData, pipeMagic, 4);
69
70     // Before we interpret the length we need to read the pipe_magic word to determine endianness.
71     if (ToUint32(&pipeMagic[0], TargetEndianness::BeWire) == armnnProfiling::PIPE_MAGIC)
72     {
73         m_Endianness = TargetEndianness::BeWire;
74     }
75     else if (ToUint32(&pipeMagic[0], TargetEndianness::LeWire) == armnnProfiling::PIPE_MAGIC)
76     {
77         m_Endianness = TargetEndianness::LeWire;
78     }
79     else
80     {
81         std::cerr << ": Protocol read error. Unable to read PIPE_MAGIC value." << std::endl;
82         return false;
83     }
84     // Now we know the endianness we can get the length from the header.
85     // Remember we already read the pipe magic 4 bytes.
86     uint32_t metaDataLength = ToUint32(&header[4], m_Endianness) - 4;
87     // Read the entire packet.
88     std::vector<uint8_t> packetData(metaDataLength);
89     if (metaDataLength !=
90         boost::numeric_cast<uint32_t>(Sockets::Read(m_ClientConnection, packetData.data(), metaDataLength)))
91     {
92         std::cerr << ": Protocol read error. Data length mismatch." << std::endl;
93         return false;
94     }
95     EchoPacket(PacketDirection::ReceivedData, packetData.data(), metaDataLength);
96     m_StreamMetaDataVersion    = ToUint32(&packetData[0], m_Endianness);
97     m_StreamMetaDataMaxDataLen = ToUint32(&packetData[4], m_Endianness);
98     m_StreamMetaDataPid        = ToUint32(&packetData[8], m_Endianness);
99
100     return true;
101 }
102
103 armnn::profiling::Packet BasePipeServer::WaitForPacket(uint32_t timeoutMs)
104 {
105     // Is there currently more than a headers worth of data waiting to be read?
106     int bytes_available;
107     Sockets::Ioctl(m_ClientConnection, FIONREAD, &bytes_available);
108     if (bytes_available > 8)
109     {
110         // Yes there is. Read it:
111         return ReceivePacket();
112     }
113     else
114     {
115         // No there's not. Poll for more data.
116         struct pollfd pollingFd[1]{};
117         pollingFd[0].fd = m_ClientConnection;
118         int pollResult  = Sockets::Poll(pollingFd, 1, static_cast<int>(timeoutMs));
119
120         switch (pollResult)
121         {
122             // Error
123             case -1:
124                 throw armnn::RuntimeException(std::string("File descriptor reported an error during polling: ") +
125                                               strerror(errno));
126
127                 // Timeout
128             case 0:
129                 throw armnn::TimeoutException("Timeout while waiting to receive packet.");
130
131                 // Normal poll return. It could still contain an error signal
132             default:
133                 // Check if the socket reported an error
134                 if (pollingFd[0].revents & (POLLNVAL | POLLERR | POLLHUP))
135                 {
136                     if (pollingFd[0].revents == POLLNVAL)
137                     {
138                         throw armnn::RuntimeException(std::string("Error while polling receiving socket: POLLNVAL"));
139                     }
140                     if (pollingFd[0].revents == POLLERR)
141                     {
142                         throw armnn::RuntimeException(std::string("Error while polling receiving socket: POLLERR: ") +
143                                                       strerror(errno));
144                     }
145                     if (pollingFd[0].revents == POLLHUP)
146                     {
147                         throw armnn::RuntimeException(std::string("Connection closed by remote client: POLLHUP"));
148                     }
149                 }
150
151                 // Check if there is data to read
152                 if (!(pollingFd[0].revents & (POLLIN)))
153                 {
154                     // This is a corner case. The socket as been woken up but not with any data.
155                     // We'll throw a timeout exception to loop around again.
156                     throw armnn::TimeoutException("File descriptor was polled but no data was available to receive.");
157                 }
158                 return ReceivePacket();
159         }
160     }
161 }
162
163 armnn::profiling::Packet BasePipeServer::ReceivePacket()
164 {
165     uint32_t header[2];
166     if (!ReadHeader(header))
167     {
168         return armnn::profiling::Packet();
169     }
170     // Read data_length bytes from the socket.
171     std::unique_ptr<unsigned char[]> uniquePacketData = std::make_unique<unsigned char[]>(header[1]);
172     unsigned char* packetData                         = reinterpret_cast<unsigned char*>(uniquePacketData.get());
173
174     if (!ReadFromSocket(packetData, header[1]))
175     {
176         return armnn::profiling::Packet();
177     }
178
179     EchoPacket(PacketDirection::ReceivedData, packetData, header[1]);
180
181     // Construct received packet
182     armnn::profiling::Packet packetRx = armnn::profiling::Packet(header[0], header[1], uniquePacketData);
183     if (m_EchoPackets)
184     {
185         std::cout << "Processing packet ID= " << packetRx.GetPacketId() << " Length=" << packetRx.GetLength()
186                   << std::endl;
187     }
188
189     return packetRx;
190 }
191
192 bool BasePipeServer::SendPacket(uint32_t packetFamily, uint32_t packetId, const uint8_t* data, uint32_t dataLength)
193 {
194     // Construct a packet from the id and data given and send it to the client.
195     // Encode the header.
196     uint32_t header[2];
197     header[0] = packetFamily << 26 | packetId << 16;
198     header[1] = dataLength;
199     // Add the header to the packet.
200     std::vector<uint8_t> packet(8 + dataLength);
201     InsertU32(header[0], packet.data(), m_Endianness);
202     InsertU32(header[1], packet.data() + 4, m_Endianness);
203     // And the rest of the data if there is any.
204     if (dataLength > 0)
205     {
206         memcpy((packet.data() + 8), data, dataLength);
207     }
208     EchoPacket(PacketDirection::Sending, packet.data(), packet.size());
209     if (-1 == armnnUtils::Sockets::Write(m_ClientConnection, packet.data(), packet.size()))
210     {
211         std::cerr  << ": Failure when writing to client socket: " << strerror(errno) << std::endl;
212         return false;
213     }
214     return true;
215 }
216
217 bool BasePipeServer::ReadHeader(uint32_t headerAsWords[2])
218 {
219     // The header will always be 2x32bit words.
220     uint8_t header[8];
221     if (!ReadFromSocket(header, 8))
222     {
223         return false;
224     }
225     EchoPacket(PacketDirection::ReceivedHeader, header, 8);
226     headerAsWords[0] = ToUint32(&header[0], m_Endianness);
227     headerAsWords[1] = ToUint32(&header[4], m_Endianness);
228     return true;
229 }
230
231 void BasePipeServer::EchoPacket(PacketDirection direction, uint8_t* packet, size_t lengthInBytes)
232 {
233     // If enabled print the contents of the data packet to the console.
234     if (m_EchoPackets)
235     {
236         if (direction == PacketDirection::Sending)
237         {
238             std::cout << "TX " << std::dec << lengthInBytes << " bytes : ";
239         }
240         else if (direction == PacketDirection::ReceivedHeader)
241         {
242             std::cout << "RX Header " << std::dec << lengthInBytes << " bytes : ";
243         }
244         else
245         {
246             std::cout << "RX Data " << std::dec << lengthInBytes << " bytes : ";
247         }
248         for (unsigned int i = 0; i < lengthInBytes; i++)
249         {
250             if ((i % 10) == 0)
251             {
252                 std::cout << std::endl;
253             }
254             std::cout << "0x" << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned int>(packet[i])
255                       << " ";
256         }
257         std::cout << std::endl;
258     }
259 }
260
261 uint32_t BasePipeServer::ToUint32(uint8_t* data, TargetEndianness endianness)
262 {
263     // Extract the first 4 bytes starting at data and push them into a 32bit integer based on the
264     // specified endianness.
265     if (endianness == TargetEndianness::BeWire)
266     {
267         return static_cast<uint32_t>(data[0]) << 24 | static_cast<uint32_t>(data[1]) << 16 |
268                static_cast<uint32_t>(data[2]) << 8 | static_cast<uint32_t>(data[3]);
269     }
270     else
271     {
272         return static_cast<uint32_t>(data[3]) << 24 | static_cast<uint32_t>(data[2]) << 16 |
273                static_cast<uint32_t>(data[1]) << 8 | static_cast<uint32_t>(data[0]);
274     }
275 }
276
277 void BasePipeServer::InsertU32(uint32_t value, uint8_t* data, TargetEndianness endianness)
278 {
279     // Take the bytes of a 32bit integer and copy them into char array starting at data considering
280     // the endianness value.
281     if (endianness == TargetEndianness::BeWire)
282     {
283         *data       = static_cast<uint8_t>((value >> 24) & 0xFF);
284         *(data + 1) = static_cast<uint8_t>((value >> 16) & 0xFF);
285         *(data + 2) = static_cast<uint8_t>((value >> 8) & 0xFF);
286         *(data + 3) = static_cast<uint8_t>(value & 0xFF);
287     }
288     else
289     {
290         *(data + 3) = static_cast<uint8_t>((value >> 24) & 0xFF);
291         *(data + 2) = static_cast<uint8_t>((value >> 16) & 0xFF);
292         *(data + 1) = static_cast<uint8_t>((value >> 8) & 0xFF);
293         *data       = static_cast<uint8_t>(value & 0xFF);
294     }
295 }
296
297 } // namespace armnnProfiling