Exception.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "utils/Exception.h"
  2. #include "utils/StringUtils.h"
  3. #include "il2cpp-object-internals.h"
  4. struct Il2CppClass;
  5. namespace il2cpp
  6. {
  7. namespace utils
  8. {
  9. std::string Exception::FormatException(const Il2CppException* ex)
  10. {
  11. #if RUNTIME_TINY
  12. IL2CPP_ASSERT(0 && "Exceptions are not supported with the Tiny runtime");
  13. return std::string();
  14. #else
  15. std::string exception_namespace = ex->klass->namespaze;
  16. std::string exception_type = ex->klass->name;
  17. if (ex->message)
  18. return exception_namespace + "." + exception_type + ": " + il2cpp::utils::StringUtils::Utf16ToUtf8(il2cpp::utils::StringUtils::GetChars(ex->message));
  19. else
  20. return exception_namespace + "." + exception_type;
  21. #endif
  22. }
  23. std::string Exception::FormatInvalidCastException(const Il2CppClass* fromType, const Il2CppClass* toType)
  24. {
  25. std::string message;
  26. #if RUNTIME_TINY
  27. IL2CPP_ASSERT(0 && "Exceptions are not supported with the Tiny runtime");
  28. #else
  29. if (fromType != NULL && toType != NULL)
  30. {
  31. message += "Unable to cast object of type '";
  32. message += fromType->name;
  33. message += "' to type '";
  34. message += toType->name;
  35. message += "'.";
  36. }
  37. #endif
  38. return message;
  39. }
  40. std::string Exception::FormatStackTrace(const Il2CppException* ex)
  41. {
  42. // Exception.RestoreExceptionDispatchInfo() will clear stack_trace, so we need to ensure that we read it only once
  43. Il2CppString* stack_trace = ex->stack_trace;
  44. if (stack_trace)
  45. return il2cpp::utils::StringUtils::Utf16ToUtf8(il2cpp::utils::StringUtils::GetChars(stack_trace));
  46. return "";
  47. }
  48. std::string Exception::FormatBaselibErrorState(const Baselib_ErrorState& errorState)
  49. {
  50. const auto len = Baselib_ErrorState_Explain(&errorState, nullptr, 0, Baselib_ErrorState_ExplainVerbosity_ErrorType_SourceLocation_Explanation);
  51. std::string buffer(len, ' ');
  52. // std::string::data() is const only until C++17
  53. Baselib_ErrorState_Explain(&errorState, &buffer[0], len, Baselib_ErrorState_ExplainVerbosity_ErrorType_SourceLocation_Explanation);
  54. return buffer;
  55. }
  56. } // utils
  57. } // il2cpp