result.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <new>
  6. #include <type_traits>
  7. #include <utility>
  8. #include "common/assert.h"
  9. #include "common/bit_field.h"
  10. #include "common/common_funcs.h"
  11. #include "common/common_types.h"
  12. // All the constants in this file come from http://3dbrew.org/wiki/Error_codes
  13. /// Detailed description of the error. This listing is likely incomplete.
  14. enum class ErrorDescription : u32 {
  15. Success = 0,
  16. WrongAddress = 53,
  17. FS_NotFound = 120,
  18. FS_AlreadyExists = 190,
  19. FS_InvalidOpenFlags = 230,
  20. FS_NotAFile = 250,
  21. FS_NotFormatted = 340, ///< This is used by the FS service when creating a SaveData archive
  22. OutofRangeOrMisalignedAddress = 513, // TODO(purpasmart): Check if this name fits its actual usage
  23. FS_InvalidPath = 702,
  24. InvalidSection = 1000,
  25. TooLarge = 1001,
  26. NotAuthorized = 1002,
  27. AlreadyDone = 1003,
  28. InvalidSize = 1004,
  29. InvalidEnumValue = 1005,
  30. InvalidCombination = 1006,
  31. NoData = 1007,
  32. Busy = 1008,
  33. MisalignedAddress = 1009,
  34. MisalignedSize = 1010,
  35. OutOfMemory = 1011,
  36. NotImplemented = 1012,
  37. InvalidAddress = 1013,
  38. InvalidPointer = 1014,
  39. InvalidHandle = 1015,
  40. NotInitialized = 1016,
  41. AlreadyInitialized = 1017,
  42. NotFound = 1018,
  43. CancelRequested = 1019,
  44. AlreadyExists = 1020,
  45. OutOfRange = 1021,
  46. Timeout = 1022,
  47. InvalidResultValue = 1023,
  48. };
  49. /**
  50. * Identifies the module which caused the error. Error codes can be propagated through a call
  51. * chain, meaning that this doesn't always correspond to the module where the API call made is
  52. * contained.
  53. */
  54. enum class ErrorModule : u32 {
  55. Common = 0,
  56. Kernel = 1,
  57. Util = 2,
  58. FileServer = 3,
  59. LoaderServer = 4,
  60. TCB = 5,
  61. OS = 6,
  62. DBG = 7,
  63. DMNT = 8,
  64. PDN = 9,
  65. GX = 10,
  66. I2C = 11,
  67. GPIO = 12,
  68. DD = 13,
  69. CODEC = 14,
  70. SPI = 15,
  71. PXI = 16,
  72. FS = 17,
  73. DI = 18,
  74. HID = 19,
  75. CAM = 20,
  76. PI = 21,
  77. PM = 22,
  78. PM_LOW = 23,
  79. FSI = 24,
  80. SRV = 25,
  81. NDM = 26,
  82. NWM = 27,
  83. SOC = 28,
  84. LDR = 29,
  85. ACC = 30,
  86. RomFS = 31,
  87. AM = 32,
  88. HIO = 33,
  89. Updater = 34,
  90. MIC = 35,
  91. FND = 36,
  92. MP = 37,
  93. MPWL = 38,
  94. AC = 39,
  95. HTTP = 40,
  96. DSP = 41,
  97. SND = 42,
  98. DLP = 43,
  99. HIO_LOW = 44,
  100. CSND = 45,
  101. SSL = 46,
  102. AM_LOW = 47,
  103. NEX = 48,
  104. Friends = 49,
  105. RDT = 50,
  106. Applet = 51,
  107. NIM = 52,
  108. PTM = 53,
  109. MIDI = 54,
  110. MC = 55,
  111. SWC = 56,
  112. FatFS = 57,
  113. NGC = 58,
  114. CARD = 59,
  115. CARDNOR = 60,
  116. SDMC = 61,
  117. BOSS = 62,
  118. DBM = 63,
  119. Config = 64,
  120. PS = 65,
  121. CEC = 66,
  122. IR = 67,
  123. UDS = 68,
  124. PL = 69,
  125. CUP = 70,
  126. Gyroscope = 71,
  127. MCU = 72,
  128. NS = 73,
  129. News = 74,
  130. RO_1 = 75,
  131. GD = 76,
  132. CardSPI = 77,
  133. EC = 78,
  134. RO_2 = 79,
  135. WebBrowser = 80,
  136. Test = 81,
  137. ENC = 82,
  138. PIA = 83,
  139. Application = 254,
  140. InvalidResult = 255
  141. };
  142. /// A less specific error cause.
  143. enum class ErrorSummary : u32 {
  144. Success = 0,
  145. NothingHappened = 1,
  146. WouldBlock = 2,
  147. OutOfResource = 3, ///< There are no more kernel resources (memory, table slots) to
  148. ///< execute the operation.
  149. NotFound = 4, ///< A file or resource was not found.
  150. InvalidState = 5,
  151. NotSupported = 6, ///< The operation is not supported or not implemented.
  152. InvalidArgument = 7, ///< Returned when a passed argument is invalid in the current runtime
  153. ///< context. (Invalid handle, out-of-bounds pointer or size, etc.)
  154. WrongArgument = 8, ///< Returned when a passed argument is in an incorrect format for use
  155. ///< with the function. (E.g. Invalid enum value)
  156. Canceled = 9,
  157. StatusChanged = 10,
  158. Internal = 11,
  159. InvalidResult = 63
  160. };
  161. /// The severity of the error.
  162. enum class ErrorLevel : u32 {
  163. Success = 0,
  164. Info = 1,
  165. Status = 25,
  166. Temporary = 26,
  167. Permanent = 27,
  168. Usage = 28,
  169. Reinitialize = 29,
  170. Reset = 30,
  171. Fatal = 31
  172. };
  173. /// Encapsulates a CTR-OS error code, allowing it to be separated into its constituent fields.
  174. union ResultCode {
  175. u32 raw;
  176. BitField<0, 10, ErrorDescription> description;
  177. BitField<10, 8, ErrorModule> module;
  178. BitField<21, 6, ErrorSummary> summary;
  179. BitField<27, 5, ErrorLevel> level;
  180. // The last bit of `level` is checked by apps and the kernel to determine if a result code is an error
  181. BitField<31, 1, u32> is_error;
  182. explicit ResultCode(u32 raw) : raw(raw) {}
  183. ResultCode(ErrorDescription description_, ErrorModule module_,
  184. ErrorSummary summary_, ErrorLevel level_) : raw(0) {
  185. description.Assign(description_);
  186. module.Assign(module_);
  187. summary.Assign(summary_);
  188. level.Assign(level_);
  189. }
  190. ResultCode& operator=(const ResultCode& o) { raw = o.raw; return *this; }
  191. bool IsSuccess() const {
  192. return is_error == 0;
  193. }
  194. bool IsError() const {
  195. return is_error == 1;
  196. }
  197. };
  198. inline bool operator==(const ResultCode& a, const ResultCode& b) {
  199. return a.raw == b.raw;
  200. }
  201. inline bool operator!=(const ResultCode& a, const ResultCode& b) {
  202. return a.raw != b.raw;
  203. }
  204. // Convenience functions for creating some common kinds of errors:
  205. /// The default success `ResultCode`.
  206. const ResultCode RESULT_SUCCESS(0);
  207. /// Might be returned instead of a dummy success for unimplemented APIs.
  208. inline ResultCode UnimplementedFunction(ErrorModule module) {
  209. return ResultCode(ErrorDescription::NotImplemented, module,
  210. ErrorSummary::NotSupported, ErrorLevel::Permanent);
  211. }
  212. /**
  213. * This is an optional value type. It holds a `ResultCode` and, if that code is a success code,
  214. * also holds a result of type `T`. If the code is an error code then trying to access the inner
  215. * value fails, thus ensuring that the ResultCode of functions is always checked properly before
  216. * their return value is used. It is similar in concept to the `std::optional` type
  217. * (http://en.cppreference.com/w/cpp/experimental/optional) originally proposed for inclusion in
  218. * C++14, or the `Result` type in Rust (http://doc.rust-lang.org/std/result/index.html).
  219. *
  220. * An example of how it could be used:
  221. * \code
  222. * ResultVal<int> Frobnicate(float strength) {
  223. * if (strength < 0.f || strength > 1.0f) {
  224. * // Can't frobnicate too weakly or too strongly
  225. * return ResultCode(ErrorDescription::OutOfRange, ErrorModule::Common,
  226. * ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
  227. * } else {
  228. * // Frobnicated! Give caller a cookie
  229. * return MakeResult<int>(42);
  230. * }
  231. * }
  232. * \endcode
  233. *
  234. * \code
  235. * ResultVal<int> frob_result = Frobnicate(0.75f);
  236. * if (frob_result) {
  237. * // Frobbed ok
  238. * printf("My cookie is %d\n", *frob_result);
  239. * } else {
  240. * printf("Guess I overdid it. :( Error code: %ux\n", frob_result.code().hex);
  241. * }
  242. * \endcode
  243. */
  244. template <typename T>
  245. class ResultVal {
  246. public:
  247. /// Constructs an empty `ResultVal` with the given error code. The code must not be a success code.
  248. ResultVal(ResultCode error_code = ResultCode(-1))
  249. : result_code(error_code)
  250. {
  251. ASSERT(error_code.IsError());
  252. }
  253. /**
  254. * Similar to the non-member function `MakeResult`, with the exception that you can manually
  255. * specify the success code. `success_code` must not be an error code.
  256. */
  257. template <typename... Args>
  258. static ResultVal WithCode(ResultCode success_code, Args&&... args) {
  259. ResultVal<T> result;
  260. result.emplace(success_code, std::forward<Args>(args)...);
  261. return result;
  262. }
  263. ResultVal(const ResultVal& o)
  264. : result_code(o.result_code)
  265. {
  266. if (!o.empty()) {
  267. new (&object) T(o.object);
  268. }
  269. }
  270. ResultVal(ResultVal&& o)
  271. : result_code(o.result_code)
  272. {
  273. if (!o.empty()) {
  274. new (&object) T(std::move(o.object));
  275. }
  276. }
  277. ~ResultVal() {
  278. if (!empty()) {
  279. object.~T();
  280. }
  281. }
  282. ResultVal& operator=(const ResultVal& o) {
  283. if (!empty()) {
  284. if (!o.empty()) {
  285. object = o.object;
  286. } else {
  287. object.~T();
  288. }
  289. } else {
  290. if (!o.empty()) {
  291. new (&object) T(o.object);
  292. }
  293. }
  294. result_code = o.result_code;
  295. return *this;
  296. }
  297. /**
  298. * Replaces the current result with a new constructed result value in-place. The code must not
  299. * be an error code.
  300. */
  301. template <typename... Args>
  302. void emplace(ResultCode success_code, Args&&... args) {
  303. ASSERT(success_code.IsSuccess());
  304. if (!empty()) {
  305. object.~T();
  306. }
  307. new (&object) T(std::forward<Args>(args)...);
  308. result_code = success_code;
  309. }
  310. /// Returns true if the `ResultVal` contains an error code and no value.
  311. bool empty() const { return result_code.IsError(); }
  312. /// Returns true if the `ResultVal` contains a return value.
  313. bool Succeeded() const { return result_code.IsSuccess(); }
  314. /// Returns true if the `ResultVal` contains an error code and no value.
  315. bool Failed() const { return empty(); }
  316. ResultCode Code() const { return result_code; }
  317. const T& operator* () const { return object; }
  318. T& operator* () { return object; }
  319. const T* operator->() const { return &object; }
  320. T* operator->() { return &object; }
  321. /// Returns the value contained in this `ResultVal`, or the supplied default if it is missing.
  322. template <typename U>
  323. T ValueOr(U&& value) const {
  324. return !empty() ? object : std::move(value);
  325. }
  326. /// Asserts that the result succeeded and returns a reference to it.
  327. T& Unwrap() {
  328. ASSERT_MSG(Succeeded(), "Tried to Unwrap empty ResultVal");
  329. return **this;
  330. }
  331. T&& MoveFrom() {
  332. return std::move(Unwrap());
  333. }
  334. private:
  335. // A union is used to allocate the storage for the value, while allowing us to construct and
  336. // destruct it at will.
  337. union { T object; };
  338. ResultCode result_code;
  339. };
  340. /**
  341. * This function is a helper used to construct `ResultVal`s. It receives the arguments to construct
  342. * `T` with and creates a success `ResultVal` contained the constructed value.
  343. */
  344. template <typename T, typename... Args>
  345. ResultVal<T> MakeResult(Args&&... args) {
  346. return ResultVal<T>::WithCode(RESULT_SUCCESS, std::forward<Args>(args)...);
  347. }
  348. /**
  349. * Check for the success of `source` (which must evaluate to a ResultVal). If it succeeds, unwraps
  350. * the contained value and assigns it to `target`, which can be either an l-value expression or a
  351. * variable declaration. If it fails the return code is returned from the current function. Thus it
  352. * can be used to cascade errors out, achieving something akin to exception handling.
  353. */
  354. #define CASCADE_RESULT(target, source) \
  355. auto CONCAT2(check_result_L, __LINE__) = source; \
  356. if (CONCAT2(check_result_L, __LINE__).Failed()) \
  357. return CONCAT2(check_result_L, __LINE__).Code(); \
  358. target = std::move(*CONCAT2(check_result_L, __LINE__))