result.h 11 KB

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