1 /*
2  * Copyright (C) 2015 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_BINDER_STATUS_H
18 #define ANDROID_HARDWARE_BINDER_STATUS_H
19 
20 #include <cstdint>
21 #include <sstream>
22 
23 #include <hidl/HidlInternal.h>
24 #include <utils/Errors.h>
25 #include <utils/StrongPointer.h>
26 
27 namespace android {
28 namespace hardware {
29 
30 // HIDL formally separates transport error codes from interface error codes. When developing a HIDL
31 // interface, errors relevant to a service should be placed in the interface design for that HAL.
32 //
33 // For instance:
34 //
35 //     interface I* {
36 //         enum FooStatus { NO_FOO, NO_BAR }; // service-specific errors
37 //         doFoo(...) generates (FooStatus foo);
38 //     };
39 //
40 // When calling into this interface, a Return<*> (in this case Return<FooStatus> object will be
41 // returned). For most clients, it's expected that they'll just get the result from this function
42 // and use it directly. If there is a transport error, the process will just abort. In general,
43 // transport errors are expected only in extremely rare circumstances (bug in the
44 // code/cosmic radiation/etc..). Aborting allows process to restart using their normal happy path
45 // code.
46 //
47 // For certain processes though which are critical to the functionality of the phone (e.g.
48 // hwservicemanager/init), these errors must be handled. Return<*>::isOk and
49 // Return<*>::isDeadObject are provided for these cases. Whenever this is done, special attention
50 // should be paid to testing the unhappy paths to make sure that error handling is handled
51 // properly.
52 
53 // Transport implementation detail. HIDL implementors, see Return below. HAL implementations should
54 // return HIDL-defined errors rather than use this.
55 class Status final {
56 public:
57     // Note: forked from
58     // - frameworks/base/core/java/android/os/android/os/Parcel.java.
59     // - frameworks/native/libs/binder/include/binder/Status.h
60     enum Exception {
61         EX_NONE = 0,
62         EX_SECURITY = -1,
63         EX_BAD_PARCELABLE = -2,
64         EX_ILLEGAL_ARGUMENT = -3,
65         EX_NULL_POINTER = -4,
66         EX_ILLEGAL_STATE = -5,
67         EX_NETWORK_MAIN_THREAD = -6,
68         EX_UNSUPPORTED_OPERATION = -7,
69 
70         // This is special and Java specific; see Parcel.java.
71         EX_HAS_REPLY_HEADER = -128,
72         // This is special, and indicates to C++ binder proxies that the
73         // transaction has failed at a low level.
74         EX_TRANSACTION_FAILED = -129,
75     };
76 
77     // A more readable alias for the default constructor.
78     static Status ok();
79     // Authors should explicitly pick whether their integer is:
80     //  - an exception code (EX_* above)
81     //  - status_t
82     //
83     // Prefer a generic exception code when possible or a status_t
84     // for low level transport errors. Service specific errors
85     // should be at a higher level in HIDL.
86     static Status fromExceptionCode(int32_t exceptionCode);
87     static Status fromExceptionCode(int32_t exceptionCode,
88                                     const char *message);
89     static Status fromStatusT(status_t status);
90 
91     Status() = default;
92     ~Status() = default;
93 
94     // Status objects are copyable and contain just simple data.
95     Status(const Status& status) = default;
96     Status(Status&& status) = default;
97     Status& operator=(const Status& status) = default;
98 
99     // Set one of the pre-defined exception types defined above.
100     void setException(int32_t ex, const char *message);
101     // Setting a |status| != OK causes generated code to return |status|
102     // from Binder transactions, rather than writing an exception into the
103     // reply Parcel.  This is the least preferable way of reporting errors.
104     void setFromStatusT(status_t status);
105 
106     // Get information about an exception.
exceptionCode()107     int32_t exceptionCode() const  { return mException; }
exceptionMessage()108     const char *exceptionMessage() const { return mMessage.c_str(); }
transactionError()109     status_t transactionError() const {
110         return mException == EX_TRANSACTION_FAILED ? mErrorCode : OK;
111     }
112 
isOk()113     bool isOk() const { return mException == EX_NONE; }
114 
115     // For debugging purposes only
116     std::string description() const;
117 
118 private:
119     Status(int32_t exceptionCode, int32_t errorCode);
120     Status(int32_t exceptionCode, int32_t errorCode, const char *message);
121 
122     // If |mException| == EX_TRANSACTION_FAILED, generated code will return
123     // |mErrorCode| as the result of the transaction rather than write an
124     // exception to the reply parcel.
125     //
126     // Otherwise, we always write |mException| to the parcel.
127     // If |mException| !=  EX_NONE, we write |mMessage| as well.
128     int32_t mException = EX_NONE;
129     int32_t mErrorCode = 0;
130     std::string mMessage;
131 };  // class Status
132 
133 // For gtest output logging
134 std::ostream& operator<< (std::ostream& stream, const Status& s);
135 
136 template<typename T> class Return;
137 
138 namespace details {
139     class return_status {
140     private:
141         Status mStatus {};
142         mutable bool mCheckedStatus = false;
143 
144         // called when an unchecked status is discarded
145         // makes sure this status is checked according to the preference
146         // set by setProcessHidlReturnRestriction
147         void onIgnored() const;
148 
149         template <typename T, typename U>
150         friend Return<U> StatusOf(const Return<T> &other);
151     protected:
152         void onValueRetrieval() const;
153     public:
154         void assertOk() const;
return_status()155         return_status() {}
return_status(const Status & s)156         return_status(const Status& s) : mStatus(s) {}
157 
158         return_status(const return_status &) = delete;
159         return_status &operator=(const return_status &) = delete;
160 
return_status(return_status && other)161         return_status(return_status&& other) noexcept { *this = std::move(other); }
162         return_status& operator=(return_status&& other) noexcept;
163 
164         ~return_status();
165 
isOkUnchecked()166         bool isOkUnchecked() const {
167             // someone else will have to check
168             return mStatus.isOk();
169         }
170 
isOk()171         bool isOk() const {
172             mCheckedStatus = true;
173             return mStatus.isOk();
174         }
175 
176         // Check if underlying error is DEAD_OBJECT.
177         // Check mCheckedStatus only if this method returns true.
isDeadObject()178         bool isDeadObject() const {
179             bool dead = mStatus.transactionError() == DEAD_OBJECT;
180 
181             // This way, if you only check isDeadObject your process will
182             // only be killed for more serious unchecked errors
183             if (dead) {
184                 mCheckedStatus = true;
185             }
186 
187             return dead;
188         }
189 
190         // For debugging purposes only
description()191         std::string description() const {
192             // Doesn't consider checked.
193             return mStatus.description();
194         }
195     };
196 }  // namespace details
197 
198 enum class HidlReturnRestriction {
199     // Okay to ignore checking transport errors. This would instead rely on init to reset state
200     // after an error in the underlying transport. This is the default and expected for most
201     // usecases.
202     NONE,
203     // Log when there is an unchecked error.
204     ERROR_IF_UNCHECKED,
205     // Fatal when there is an unchecked error.
206     FATAL_IF_UNCHECKED,
207 };
208 
209 /**
210  * This should be called during process initialization (e.g. before binder threadpool is created).
211  *
212  * Note: default of HidlReturnRestriction::NONE should be good for most usecases. See above.
213  *
214  * The restriction will be applied when Return objects are deconstructed.
215  */
216 void setProcessHidlReturnRestriction(HidlReturnRestriction restriction);
217 
218 template<typename T> class Return : public details::return_status {
219 private:
220     T mVal {};
221 public:
Return(T v)222     Return(T v) : details::return_status(), mVal{v} {}
Return(Status s)223     Return(Status s) : details::return_status(s) {}
224 
225     // move-able.
226     // precondition: "this" has checked status
227     // postcondition: other is safe to destroy after moving to *this.
228     Return(Return&& other) noexcept = default;
229     Return& operator=(Return&&) noexcept = default;
230 
231     ~Return() = default;
232 
T()233     operator T() const {
234         onValueRetrieval();  // assert okay
235         return mVal;
236     }
237 
withDefault(T t)238     T withDefault(T t) {
239         return isOk() ? mVal : t;
240     }
241 };
242 
243 template<typename T> class Return<sp<T>> : public details::return_status {
244 private:
245     sp<T> mVal {};
246 public:
Return(sp<T> v)247     Return(sp<T> v) : details::return_status(), mVal{v} {}
Return(T * v)248     Return(T* v) : details::return_status(), mVal{v} {}
249     // Constructors matching a different type (that is related by inheritance)
Return(sp<U> v)250     template<typename U> Return(sp<U> v) : details::return_status(), mVal{v} {}
Return(U * v)251     template<typename U> Return(U* v) : details::return_status(), mVal{v} {}
Return(Status s)252     Return(Status s) : details::return_status(s) {}
253 
254     // move-able.
255     // precondition: "this" has checked status
256     // postcondition: other is safe to destroy after moving to *this.
257     Return(Return&& other) noexcept = default;
258     Return& operator=(Return&&) noexcept = default;
259 
260     ~Return() = default;
261 
262     operator sp<T>() const {
263         onValueRetrieval();  // assert okay
264         return mVal;
265     }
266 
withDefault(sp<T> t)267     sp<T> withDefault(sp<T> t) {
268         return isOk() ? mVal : t;
269     }
270 };
271 
272 
273 template<> class Return<void> : public details::return_status {
274 public:
Return()275     Return() : details::return_status() {}
Return(const Status & s)276     Return(const Status& s) : details::return_status(s) {}
277 
278     // move-able.
279     // precondition: "this" has checked status
280     // postcondition: other is safe to destroy after moving to *this.
281     Return(Return &&) = default;
282     Return &operator=(Return &&) = default;
283 
284     ~Return() = default;
285 };
286 
Void()287 static inline Return<void> Void() {
288     return Return<void>();
289 }
290 
291 namespace details {
292 // Create a Return<U> from the Status of Return<T>. The provided
293 // Return<T> must have an error status and have it checked.
294 template <typename T, typename U>
StatusOf(const Return<T> & other)295 Return<U> StatusOf(const Return<T> &other) {
296     if (other.mStatus.isOk() || !other.mCheckedStatus) {
297         details::logAlwaysFatal("cannot call statusOf on an OK Status or an unchecked status");
298     }
299     return Return<U>{other.mStatus};
300 }
301 }  // namespace details
302 
303 }  // namespace hardware
304 }  // namespace android
305 
306 #endif // ANDROID_HARDWARE_BINDER_STATUS_H
307