• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ipc_message.h"
17 #include "utils/logger.h"
18 #include "ipc_unix_socket.h"
19 
20 namespace ark::dprof::ipc {
SendMessage(int fd,const Message & message)21 bool SendMessage(int fd, const Message &message)
22 {
23     Message::Id messageId = message.GetId();
24     if (!SendAll(fd, &messageId, sizeof(messageId))) {
25         PLOG(ERROR, DPROF) << "Cannot send message id";
26         return false;
27     }
28 
29     uint32_t size = message.GetSize();
30     if (!SendAll(fd, &size, sizeof(size))) {
31         PLOG(ERROR, DPROF) << "Cannot send data size";
32         return false;
33     }
34 
35     if (size != 0 && !SendAll(fd, message.GetData(), message.GetSize())) {
36         PLOG(ERROR, DPROF) << "Cannot send message data, size=" << message.GetSize();
37         return false;
38     }
39 
40     return true;
41 }
42 
RecvMessage(int fd,Message & message)43 int RecvMessage(int fd, Message &message)
44 {
45     constexpr int DEFAULT_TIMEOUT = 500; /* 0.5 sec */
46 
47     Message::Id messageId;
48     int ret = RecvTimeout(fd, &messageId, sizeof(messageId), DEFAULT_TIMEOUT);
49     if (ret == 0) {
50         // socket was closed
51         return 0;
52     }
53     if (ret == -1) {
54         LOG(ERROR, DPROF) << "Cannot get messageId";
55         return -1;
56     }
57 
58     uint32_t size;
59     if (RecvTimeout(fd, &size, sizeof(size), DEFAULT_TIMEOUT) <= 0) {
60         LOG(ERROR, DPROF) << "Cannot get data size";
61         return -1;
62     }
63 
64     if (size > Message::MAX_DATA_SIZE) {
65         LOG(ERROR, DPROF) << "Data size is too large, size=" << size;
66         return -1;
67     }
68 
69     std::vector<uint8_t> data(size);
70     if (size != 0) {
71         if (RecvTimeout(fd, data.data(), data.size(), DEFAULT_TIMEOUT) <= 0) {
72             LOG(ERROR, DPROF) << "Canot get message data";
73             return -1;
74         }
75     }
76 
77     message = Message(messageId, std::move(data));
78     return 1;
79 }
80 }  // namespace ark::dprof::ipc
81