Line data Source code
1 : /*
2 : * If not stated otherwise in this file or this component's LICENSE file the
3 : * following copyright and licenses apply:
4 : *
5 : * Copyright 2023 Sky UK
6 : *
7 : * Licensed under the Apache License, Version 2.0 (the "License");
8 : * you may not use this file except in compliance with the License.
9 : * You may obtain a copy of the License at
10 : *
11 : * http://www.apache.org/licenses/LICENSE-2.0
12 : *
13 : * Unless required by applicable law or agreed to in writing, software
14 : * distributed under the License is distributed on an "AS IS" BASIS,
15 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 : * See the License for the specific language governing permissions and
17 : * limitations under the License.
18 : */
19 :
20 : #include "SharedMemoryHandle.h"
21 : #include "RialtoClientLogging.h"
22 : #include <stdexcept>
23 : #include <sys/mman.h>
24 : #include <sys/un.h>
25 : #include <unistd.h>
26 :
27 : namespace firebolt::rialto::client
28 : {
29 10 : SharedMemoryHandle::SharedMemoryHandle(std::int32_t shmFd, std::uint32_t shmBufferLen)
30 10 : : m_shmFd{shmFd}, m_shmBufferLen{shmBufferLen}
31 : {
32 10 : if ((-1 == m_shmFd) || (0U == m_shmBufferLen))
33 : {
34 1 : throw std::runtime_error("Shared buffer invalid");
35 : }
36 :
37 9 : m_shmBuffer = reinterpret_cast<uint8_t *>(mmap(NULL, m_shmBufferLen, PROT_READ | PROT_WRITE, MAP_SHARED, m_shmFd, 0));
38 9 : if (MAP_FAILED == m_shmBuffer)
39 : {
40 1 : close(m_shmFd);
41 1 : m_shmFd = -1;
42 1 : m_shmBuffer = nullptr;
43 1 : m_shmBufferLen = 0U;
44 1 : throw std::runtime_error("Failed to map databuffer: " + std::string(strerror(errno)));
45 : }
46 10 : }
47 :
48 8 : SharedMemoryHandle::~SharedMemoryHandle()
49 : {
50 8 : if (-1 == m_shmFd)
51 : {
52 0 : RIALTO_CLIENT_LOG_WARN("Shared memory not initalised");
53 0 : return;
54 : }
55 :
56 8 : int32_t ret = munmap(m_shmBuffer, m_shmBufferLen);
57 8 : if (-1 == ret)
58 : {
59 0 : RIALTO_CLIENT_LOG_ERROR("Failed to unmap databuffer: %s", strerror(errno));
60 : }
61 : else
62 : {
63 8 : RIALTO_CLIENT_LOG_INFO("Shared buffer was successfully terminated");
64 : }
65 :
66 8 : close(m_shmFd);
67 8 : m_shmBuffer = nullptr;
68 8 : m_shmFd = -1;
69 8 : m_shmBufferLen = 0U;
70 : }
71 :
72 8 : std::uint8_t *SharedMemoryHandle::getShm() const
73 : {
74 8 : return m_shmBuffer;
75 : }
76 : } // namespace firebolt::rialto::client
|