result.h 12 KB

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