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 
fromAidl(const NativeHandle & handle,bool doDup)25 static native_handle_t* fromAidl(const NativeHandle& handle, bool doDup) {
26     native_handle_t* to = native_handle_create(handle.fds.size(), handle.ints.size());
27     if (!to) return nullptr;
28 
29     for (size_t i = 0; i < handle.fds.size(); i++) {
30         int fd = handle.fds[i].get();
31         to->data[i] = doDup ? fcntl(fd, F_DUPFD_CLOEXEC, 0) : fd;
32     }
33     memcpy(to->data + handle.fds.size(), handle.ints.data(), handle.ints.size() * sizeof(int));
34     return to;
35 }
36 
makeFromAidl(const NativeHandle & handle)37 native_handle_t* makeFromAidl(const NativeHandle& handle) {
38     return fromAidl(handle, false /* doDup */);
39 }
dupFromAidl(const NativeHandle & handle)40 native_handle_t* dupFromAidl(const NativeHandle& handle) {
41     return fromAidl(handle, true /* doDup */);
42 }
43 
toAidl(const native_handle_t * handle,bool doDup)44 static NativeHandle toAidl(const native_handle_t* handle, bool doDup) {
45     NativeHandle to;
46 
47     to.fds = std::vector<ndk::ScopedFileDescriptor>(handle->numFds);
48     for (size_t i = 0; i < handle->numFds; i++) {
49         int fd = handle->data[i];
50         to.fds.at(i).set(doDup ? fcntl(fd, F_DUPFD_CLOEXEC, 0) : fd);
51     }
52 
53     to.ints = std::vector<int32_t>(handle->data + handle->numFds,
54                                    handle->data + handle->numFds + handle->numInts);
55     return to;
56 }
57 
makeToAidl(const native_handle_t * handle)58 NativeHandle makeToAidl(const native_handle_t* handle) {
59     return toAidl(handle, false /* doDup */);
60 }
61 
dupToAidl(const native_handle_t * handle)62 NativeHandle dupToAidl(const native_handle_t* handle) {
63     return toAidl(handle, true /* doDup */);
64 }
65 
66 }  // namespace android
67