result.h 11 KB

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