1 /*
2  * Copyright (C) 2019 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 #ifndef android_hardware_automotive_vehicle_V2_0_impl_virtualization_Utils_H_
18 #define android_hardware_automotive_vehicle_V2_0_impl_virtualization_Utils_H_
19 
20 #include <sys/time.h>
21 #include <chrono>
22 #include <optional>
23 #include <string>
24 
25 #ifdef __BIONIC__
26 #include <android-base/logging.h>
27 
28 #include <vsockinfo.h>
29 #endif  // __BIONIC__
30 
31 namespace android {
32 namespace hardware {
33 namespace automotive {
34 namespace vehicle {
35 namespace V2_0 {
36 namespace impl {
37 
38 template <class duration_t>
39 constexpr struct timeval TimeValFromChronoDuration(duration_t duration) {
40     using std::micro;
41     using std::chrono::duration_cast;
42     using std::chrono::microseconds;
43     using std::chrono::seconds;
44     return {
45             .tv_sec = static_cast<time_t>(duration_cast<seconds>(duration).count()),
46             .tv_usec = static_cast<suseconds_t>(duration_cast<microseconds>(duration).count() %
47                                                 micro::den),
48     };
49 }
50 
51 // True means fd is ready, False means timeout
52 bool WaitForReadWithTimeout(int fd, struct timeval&& timeout);
53 
54 // True means fd is ready, False means timeout
55 template <class duration_t>
56 bool WaitForReadWithTimeout(int fd, duration_t timeout) {
57     return WaitForReadWithTimeout(fd, TimeValFromChronoDuration(timeout));
58 }
59 
60 struct VirtualizedVhalServerInfo {
61 #ifdef __BIONIC__
62     android::hardware::automotive::utils::VsockConnectionInfo vsock;
63 #else
64     struct {
65         unsigned cid = 0;
66         unsigned port = 0;
67     } vsock;
68 #endif
69 
70     std::string powerStateMarkerFilePath;
71     std::string powerStateSocket;
72 
73     static std::optional<VirtualizedVhalServerInfo> fromCommandLine(int argc, char* argv[],
74                                                                     std::string* error);
75 
76 #ifdef __BIONIC__
77     static std::optional<VirtualizedVhalServerInfo> fromRoPropertyStore();
78 #endif
79 
80     std::string getServerUri() const;
81 };
82 
83 }  // namespace impl
84 }  // namespace V2_0
85 }  // namespace vehicle
86 }  // namespace automotive
87 }  // namespace hardware
88 }  // namespace android
89 
90 #endif  // android_hardware_automotive_vehicle_V2_0_impl_virtualization_Utils_H_
91