1 /*
2 * Copyright (C) 2020 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 <aidlcommonsupport/NativeHandle.h>
18
19 #include <fcntl.h>
20
21 namespace android {
22
23 using aidl::android::hardware::common::NativeHandle;
24
25 /**
26 * Checks if a NativeHandle is null
27 */
isAidlNativeHandleEmpty(const NativeHandle & handle)28 bool isAidlNativeHandleEmpty(const NativeHandle& handle) {
29 return handle.fds.empty() && handle.ints.empty();
30 }
31
fromAidl(const NativeHandle & handle,bool doDup)32 static native_handle_t* fromAidl(const NativeHandle& handle, bool doDup) {
33 native_handle_t* to = native_handle_create(handle.fds.size(), handle.ints.size());
34 if (!to) return nullptr;
35
36 for (size_t i = 0; i < handle.fds.size(); i++) {
37 int fd = handle.fds[i].get();
38 to->data[i] = doDup ? fcntl(fd, F_DUPFD_CLOEXEC, 0) : fd;
39 }
40 memcpy(to->data + handle.fds.size(), handle.ints.data(), handle.ints.size() * sizeof(int));
41 return to;
42 }
43
makeFromAidl(const NativeHandle & handle)44 native_handle_t* makeFromAidl(const NativeHandle& handle) {
45 return fromAidl(handle, false /* doDup */);
46 }
dupFromAidl(const NativeHandle & handle)47 native_handle_t* dupFromAidl(const NativeHandle& handle) {
48 return fromAidl(handle, true /* doDup */);
49 }
50
toAidl(const native_handle_t * handle,bool doDup)51 static NativeHandle toAidl(const native_handle_t* handle, bool doDup) {
52 NativeHandle to;
53
54 to.fds = std::vector<ndk::ScopedFileDescriptor>(handle->numFds);
55 for (size_t i = 0; i < handle->numFds; i++) {
56 int fd = handle->data[i];
57 to.fds.at(i).set(doDup ? fcntl(fd, F_DUPFD_CLOEXEC, 0) : fd);
58 }
59
60 to.ints = std::vector<int32_t>(handle->data + handle->numFds,
61 handle->data + handle->numFds + handle->numInts);
62 return to;
63 }
64
makeToAidl(const native_handle_t * handle)65 NativeHandle makeToAidl(const native_handle_t* handle) {
66 return toAidl(handle, false /* doDup */);
67 }
68
dupToAidl(const native_handle_t * handle)69 NativeHandle dupToAidl(const native_handle_t* handle) {
70 return toAidl(handle, true /* doDup */);
71 }
72
73 } // namespace android
74