1 /*
2  * Copyright (C) 2016 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 #pragma once
18 
19 #include <chrono>
20 #include <future>
21 
22 #include <hidl/Status.h>
23 #include <utils/Errors.h>
24 
25 namespace android {
26 namespace lshal {
27 
28 // Call function on interfaceObject and wait for result until the given timeout has reached.
29 // Callback functions pass to timeoutIPC() may be executed after the this function
30 // has returned, especially if deadline has been reached. Hence, care must be taken when passing
31 // data between the background thread and the main thread. See b/311143089.
32 template<class R, class P, class Function, class I, class... Args>
33 typename std::invoke_result<Function, I *, Args...>::type
timeoutIPC(std::chrono::duration<R,P> wait,const sp<I> & interfaceObject,Function && func,Args &&...args)34 timeoutIPC(std::chrono::duration<R, P> wait, const sp<I> &interfaceObject, Function &&func,
35            Args &&... args) {
36     using ::android::hardware::Status;
37 
38     // Execute on a background thread but do not defer execution.
39     auto future =
40             std::async(std::launch::async, func, interfaceObject, std::forward<Args>(args)...);
41     auto status = future.wait_for(wait);
42     if (status == std::future_status::ready) {
43         return future.get();
44     }
45 
46     // This future belongs to a background thread that we no longer care about.
47     // Putting this in the global list avoids std::future::~future() that may wait for the
48     // result to come back.
49     // This leaks memory, but lshal is a debugging tool, so this is fine.
50     static std::vector<decltype(future)> gDeadPool{};
51     gDeadPool.emplace_back(std::move(future));
52 
53     if (status == std::future_status::timeout) {
54         return Status::fromStatusT(TIMED_OUT);
55     }
56     return Status::fromExceptionCode(Status::Exception::EX_ILLEGAL_STATE, "Illegal future_status");
57 }
58 } // namespace lshal
59 } // namespace android
60