result.h 11 KB

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