1 /*
2  * Copyright 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "common/libs/transport/channel.h"
18 
19 namespace cuttlefish {
20 namespace transport {
21 
operator ()(RawMessage * ptr)22 void MessageDestroyer::operator()(RawMessage* ptr) {
23   std::memset(ptr, 0, sizeof(RawMessage) + ptr->payload_size);
24   std::free(ptr);
25 }
26 
27 /**
28  * Allocates memory for a RawMessage carrying a message of size
29  * `payload_size`.
30  */
CreateMessage(uint32_t command,bool is_response,size_t payload_size)31 Result<ManagedMessage> CreateMessage(uint32_t command, bool is_response, size_t payload_size) {
32   const auto bytes_to_allocate = sizeof(RawMessage) + payload_size;
33   auto memory = std::malloc(bytes_to_allocate);
34   CF_EXPECT(memory != nullptr,
35             "Cannot allocate " << bytes_to_allocate << " bytes for secure_env RPC message");
36   auto message = reinterpret_cast<RawMessage*>(memory);
37   message->command = command;
38   message->is_response = is_response;
39   message->payload_size = payload_size;
40   return ManagedMessage(message);
41 }
42 
CreateMessage(uint32_t command,size_t payload_size)43 Result<ManagedMessage> CreateMessage(uint32_t command, size_t payload_size) {
44   return CreateMessage(command, false, payload_size);
45 }
46 
47 }  // namespace transport
48 }  // namespace cuttlefish