xref: /aosp_15_r20/system/libbase/include/android-base/errors.h (revision 8f0ba417480079999ba552f1087ae592091b9d02)
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 // Portable error handling functions. This is only necessary for host-side
18 // code that needs to be cross-platform; code that is only run on Unix should
19 // just use errno and strerror() for simplicity.
20 //
21 // There is some complexity since Windows has (at least) three different error
22 // numbers, not all of which share the same type:
23 //   * errno: for C runtime errors.
24 //   * GetLastError(): Windows non-socket errors.
25 //   * WSAGetLastError(): Windows socket errors.
26 // errno can be passed to strerror() on all platforms, but the other two require
27 // special handling to get the error string. Refer to Microsoft documentation
28 // to determine which error code to check for each function.
29 
30 #pragma once
31 
32 #include <assert.h>
33 
34 #include <string>
35 
36 namespace android {
37 namespace base {
38 
39 // Returns a string describing the given system error code. |error_code| must
40 // be errno on Unix or GetLastError()/WSAGetLastError() on Windows. Passing
41 // errno on Windows has undefined behavior.
42 std::string SystemErrorCodeToString(int error_code);
43 
44 }  // namespace base
45 }  // namespace android
46 
47 // Convenient macros for evaluating a statement, checking if the result is error, and returning it
48 // to the caller. If it is ok then the inner value is unwrapped (if applicable) and returned.
49 //
50 // Usage with Result<T>:
51 //
52 // Result<Foo> getFoo() {...}
53 //
54 // Result<Bar> getBar() {
55 //   Foo foo = OR_RETURN(getFoo());
56 //   return Bar{foo};
57 // }
58 //
59 // Usage with status_t:
60 //
61 // status_t getFoo(Foo*) {...}
62 //
63 // status_t getBar(Bar* bar) {
64 //   Foo foo;
65 //   OR_RETURN(getFoo(&foo));
66 //   *bar = Bar{foo};
67 //   return OK;
68 // }
69 //
70 // Actually this can be used for any type as long as the OkOrFail<T> contract is satisfied. See
71 // below.
72 // If implicit conversion compilation errors occur involving a value type with a templated
73 // forwarding ref ctor, compilation with cpp20 or explicitly converting to the desired
74 // return type is required.
75 #define OR_RETURN(expr) \
76   UNWRAP_OR_DO(__or_return_expr, expr, { return ok_or_fail::Fail(std::move(__or_return_expr)); })
77 
78 // Same as OR_RETURN, but aborts if expr is a failure.
79 #if defined(__BIONIC__)
80 #define OR_FATAL(expr)                                                               \
81   UNWRAP_OR_DO(__or_fatal_expr, expr, {                                              \
82     __assert(__FILE__, __LINE__, ok_or_fail::ErrorMessage(__or_fatal_expr).c_str()); \
83   })
84 #else
85 #define OR_FATAL(expr)                                                    \
86   UNWRAP_OR_DO(__or_fatal_expr, expr, {                                   \
87     fprintf(stderr, "%s:%d: assertion \"%s\" failed", __FILE__, __LINE__, \
88             ok_or_fail::ErrorMessage(__or_fatal_expr).c_str());           \
89     abort();                                                              \
90   })
91 #endif
92 
93 // Variant for use in gtests, which aborts the test function with an assertion failure on error.
94 // This is akin to ASSERT_OK_AND_ASSIGN for absl::Status, except the assignment is external. It
95 // assumes the user depends on libgmock and includes gtest/gtest.h.
96 #define OR_ASSERT_FAIL(expr)                                             \
97   UNWRAP_OR_DO(__or_assert_expr, expr, {                                 \
98     FAIL() << "Value of: " << #expr << "\n"                              \
99            << "  Actual: " << __or_assert_expr.error().message() << "\n" \
100            << "Expected: is ok\n";                                       \
101   })
102 
103 // Generic macro to execute any statement(s) on error. Execution should never reach the end of them.
104 // result_var is assigned expr and is only visible to on_error_stmts.
105 #define UNWRAP_OR_DO(result_var, expr, on_error_stmts)                                         \
106   ({                                                                                           \
107     decltype(expr)&& result_var = (expr);                                                      \
108     typedef android::base::OkOrFail<std::remove_reference_t<decltype(result_var)>> ok_or_fail; \
109     if (!ok_or_fail::IsOk(result_var)) {                                                       \
110       {                                                                                        \
111         on_error_stmts;                                                                        \
112       }                                                                                        \
113       __builtin_unreachable();                                                                 \
114     }                                                                                          \
115     ok_or_fail::Unwrap(std::move(result_var));                                                 \
116   })
117 
118 namespace android {
119 namespace base {
120 
121 // The OkOrFail contract for a type T. This must be implemented for a type T if you want to use
122 // OR_RETURN(stmt) where stmt evalues to a value of type T.
123 template <typename T, typename = void>
124 struct OkOrFail {
125   // Checks if T is ok or fail.
126   static bool IsOk(const T&);
127 
128   // Turns T into the success value.
129   template <typename U>
130   static U Unwrap(T&&);
131 
132   // Moves T into OkOrFail<T>, so that we can convert it to other types
133   OkOrFail(T&& v);
134   OkOrFail() = delete;
135   OkOrFail(const T&) = delete;
136 
137   // And there need to be one or more conversion operators that turns the error value of T into a
138   // target type. For example, for T = Result<V, E>, there can be ...
139   //
140   // // for the case where OR_RETURN is called in a function expecting E
141   // operator E()&& { return val_.error().code(); }
142   //
143   // // for the case where OR_RETURN is called in a function expecting Result<U, E>
144   // template <typename U>
145   // operator Result<U, E>()&& { return val_.error(); }
146 
147   // And there needs to be a method that returns the string representation of the fail value.
148   // static const std::string& ErrorMessage(const T& v);
149   // or
150   // static std::string ErrorMessage(const T& v);
151 };
152 
153 }  // namespace base
154 }  // namespace android
155