diff options
Diffstat (limited to 'src/core')
66 files changed, 1133 insertions, 635 deletions
diff --git a/src/core/3ds.h b/src/core/3ds.h new file mode 100644 index 000000000..8715e27db --- /dev/null +++ b/src/core/3ds.h @@ -0,0 +1,21 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +namespace Core { + +// 3DS Video Constants +// ------------------- + +// NOTE: The LCDs actually rotate the image 90 degrees when displaying. Because of that the +// framebuffers in video memory are stored in column-major order and rendered sideways, causing +// the widths and heights of the framebuffers read by the LCD to be switched compared to the +// heights and widths of the screens listed here. +constexpr int kScreenTopWidth = 400; ///< 3DS top screen width +constexpr int kScreenTopHeight = 240; ///< 3DS top screen height +constexpr int kScreenBottomWidth = 320; ///< 3DS bottom screen width +constexpr int kScreenBottomHeight = 240; ///< 3DS bottom screen height + +} // namespace Core diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index c733e5d21..d66139c9c 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -32,6 +32,7 @@ set(SRCS frontend/camera/factory.cpp frontend/camera/interface.cpp frontend/emu_window.cpp + frontend/framebuffer_layout.cpp frontend/motion_emu.cpp gdbstub/gdbstub.cpp hle/config_mem.cpp @@ -44,6 +45,7 @@ set(SRCS hle/kernel/client_port.cpp hle/kernel/client_session.cpp hle/kernel/event.cpp + hle/kernel/handle_table.cpp hle/kernel/kernel.cpp hle/kernel/memory.cpp hle/kernel/mutex.cpp @@ -56,6 +58,7 @@ set(SRCS hle/kernel/thread.cpp hle/kernel/timer.cpp hle/kernel/vm_manager.cpp + hle/kernel/wait_object.cpp hle/service/ac/ac.cpp hle/service/ac/ac_i.cpp hle/service/ac/ac_u.cpp @@ -174,9 +177,11 @@ set(SRCS memory.cpp perf_stats.cpp settings.cpp + telemetry_session.cpp ) set(HEADERS + 3ds.h arm/arm_interface.h arm/dynarmic/arm_dynarmic.h arm/dynarmic/arm_dynarmic_cp15.h @@ -215,6 +220,7 @@ set(HEADERS frontend/camera/factory.h frontend/camera/interface.h frontend/emu_window.h + frontend/framebuffer_layout.h frontend/input.h frontend/motion_emu.h gdbstub/gdbstub.h @@ -230,7 +236,9 @@ set(HEADERS hle/kernel/address_arbiter.h hle/kernel/client_port.h hle/kernel/client_session.h + hle/kernel/errors.h hle/kernel/event.h + hle/kernel/handle_table.h hle/kernel/kernel.h hle/kernel/memory.h hle/kernel/mutex.h @@ -244,6 +252,7 @@ set(HEADERS hle/kernel/thread.h hle/kernel/timer.h hle/kernel/vm_manager.h + hle/kernel/wait_object.h hle/result.h hle/service/ac/ac.h hle/service/ac/ac_i.h @@ -366,13 +375,10 @@ set(HEADERS mmio.h perf_stats.h settings.h + telemetry_session.h ) -include_directories(../../externals/dynarmic/include) -include_directories(../../externals/cryptopp) - create_directory_groups(${SRCS} ${HEADERS}) - add_library(core STATIC ${SRCS} ${HEADERS}) - -target_link_libraries(core dynarmic cryptopp) +target_link_libraries(core PUBLIC common PRIVATE audio_core video_core) +target_link_libraries(core PUBLIC Boost::boost PRIVATE cryptopp dynarmic) diff --git a/src/core/core.cpp b/src/core/core.cpp index 881f1e93c..450e7566d 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -132,6 +132,8 @@ System::ResultStatus System::Init(EmuWindow* emu_window, u32 system_mode) { cpu_core = std::make_unique<ARM_DynCom>(USER32MODE); } + telemetry_session = std::make_unique<Core::TelemetrySession>(); + CoreTiming::Init(); HW::Init(); Kernel::Init(system_mode); @@ -162,6 +164,7 @@ void System::Shutdown() { CoreTiming::Shutdown(); cpu_core = nullptr; app_loader = nullptr; + telemetry_session = nullptr; LOG_DEBUG(Core, "Shutdown OK"); } diff --git a/src/core/core.h b/src/core/core.h index 6c9c936b5..6af772831 100644 --- a/src/core/core.h +++ b/src/core/core.h @@ -9,6 +9,7 @@ #include "common/common_types.h" #include "core/memory.h" #include "core/perf_stats.h" +#include "core/telemetry_session.h" class EmuWindow; class ARM_Interface; @@ -80,6 +81,14 @@ public: return cpu_core != nullptr; } + /** + * Returns a reference to the telemetry session for this emulation session. + * @returns Reference to the telemetry session. + */ + Core::TelemetrySession& TelemetrySession() const { + return *telemetry_session; + } + /// Prepare the core emulation for a reschedule void PrepareReschedule(); @@ -117,6 +126,9 @@ private: /// When true, signals that a reschedule should happen bool reschedule_pending{}; + /// Telemetry session for this emulation session + std::unique_ptr<Core::TelemetrySession> telemetry_session; + static System s_instance; }; @@ -124,4 +136,8 @@ inline ARM_Interface& CPU() { return System::GetInstance().CPU(); } +inline TelemetrySession& Telemetry() { + return System::GetInstance().TelemetrySession(); +} + } // namespace Core diff --git a/src/core/file_sys/archive_extsavedata.cpp b/src/core/file_sys/archive_extsavedata.cpp index f454e7840..4867c9d17 100644 --- a/src/core/file_sys/archive_extsavedata.cpp +++ b/src/core/file_sys/archive_extsavedata.cpp @@ -38,8 +38,7 @@ public: ResultVal<size_t> Write(u64 offset, size_t length, bool flush, const u8* buffer) const override { if (offset > size) { - return ResultCode(ErrorDescription::FS_WriteBeyondEnd, ErrorModule::FS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return ERR_WRITE_BEYOND_END; } else if (offset == size) { return MakeResult<size_t>(0); } @@ -191,11 +190,9 @@ ResultVal<std::unique_ptr<ArchiveBackend>> ArchiveFactory_ExtSaveData::Open(cons // TODO(Subv): Verify the archive behavior of SharedExtSaveData compared to ExtSaveData. // ExtSaveData seems to return FS_NotFound (120) when the archive doesn't exist. if (!shared) { - return ResultCode(ErrorDescription::FS_NotFound, ErrorModule::FS, - ErrorSummary::InvalidState, ErrorLevel::Status); + return ERR_NOT_FOUND_INVALID_STATE; } else { - return ResultCode(ErrorDescription::FS_NotFormatted, ErrorModule::FS, - ErrorSummary::InvalidState, ErrorLevel::Status); + return ERR_NOT_FORMATTED; } } auto archive = std::make_unique<ExtSaveDataArchive>(fullpath); @@ -230,8 +227,7 @@ ResultVal<ArchiveFormatInfo> ArchiveFactory_ExtSaveData::GetFormatInfo(const Pat if (!file.IsOpen()) { LOG_ERROR(Service_FS, "Could not open metadata information for archive"); // TODO(Subv): Verify error code - return ResultCode(ErrorDescription::FS_NotFormatted, ErrorModule::FS, - ErrorSummary::InvalidState, ErrorLevel::Status); + return ERR_NOT_FORMATTED; } ArchiveFormatInfo info = {}; diff --git a/src/core/file_sys/archive_source_sd_savedata.cpp b/src/core/file_sys/archive_source_sd_savedata.cpp index f31a68038..a7e331724 100644 --- a/src/core/file_sys/archive_source_sd_savedata.cpp +++ b/src/core/file_sys/archive_source_sd_savedata.cpp @@ -6,6 +6,7 @@ #include "common/logging/log.h" #include "common/string_util.h" #include "core/file_sys/archive_source_sd_savedata.h" +#include "core/file_sys/errors.h" #include "core/file_sys/savedata_archive.h" #include "core/hle/service/fs/archive.h" @@ -49,8 +50,7 @@ ResultVal<std::unique_ptr<ArchiveBackend>> ArchiveSource_SDSaveData::Open(u64 pr // save file/directory structure expected by the game has not yet been initialized. // Returning the NotFormatted error code will signal the game to provision the SaveData // archive with the files and folders that it expects. - return ResultCode(ErrorDescription::FS_NotFormatted, ErrorModule::FS, - ErrorSummary::InvalidState, ErrorLevel::Status); + return ERR_NOT_FORMATTED; } auto archive = std::make_unique<SaveDataArchive>(std::move(concrete_mount_point)); @@ -81,8 +81,7 @@ ResultVal<ArchiveFormatInfo> ArchiveSource_SDSaveData::GetFormatInfo(u64 program if (!file.IsOpen()) { LOG_ERROR(Service_FS, "Could not open metadata information for archive"); // TODO(Subv): Verify error code - return ResultCode(ErrorDescription::FS_NotFormatted, ErrorModule::FS, - ErrorSummary::InvalidState, ErrorLevel::Status); + return ERR_NOT_FORMATTED; } ArchiveFormatInfo info = {}; diff --git a/src/core/file_sys/archive_systemsavedata.cpp b/src/core/file_sys/archive_systemsavedata.cpp index 8986b5c0e..81423bffd 100644 --- a/src/core/file_sys/archive_systemsavedata.cpp +++ b/src/core/file_sys/archive_systemsavedata.cpp @@ -9,6 +9,7 @@ #include "common/file_util.h" #include "common/string_util.h" #include "core/file_sys/archive_systemsavedata.h" +#include "core/file_sys/errors.h" #include "core/file_sys/savedata_archive.h" #include "core/hle/service/fs/archive.h" @@ -53,8 +54,7 @@ ResultVal<std::unique_ptr<ArchiveBackend>> ArchiveFactory_SystemSaveData::Open(c std::string fullpath = GetSystemSaveDataPath(base_path, path); if (!FileUtil::Exists(fullpath)) { // TODO(Subv): Check error code, this one is probably wrong - return ResultCode(ErrorDescription::FS_NotFormatted, ErrorModule::FS, - ErrorSummary::InvalidState, ErrorLevel::Status); + return ERR_NOT_FORMATTED; } auto archive = std::make_unique<SaveDataArchive>(fullpath); return MakeResult<std::unique_ptr<ArchiveBackend>>(std::move(archive)); diff --git a/src/core/file_sys/disk_archive.cpp b/src/core/file_sys/disk_archive.cpp index a243d9a13..98d80aabc 100644 --- a/src/core/file_sys/disk_archive.cpp +++ b/src/core/file_sys/disk_archive.cpp @@ -9,6 +9,7 @@ #include "common/file_util.h" #include "common/logging/log.h" #include "core/file_sys/disk_archive.h" +#include "core/file_sys/errors.h" //////////////////////////////////////////////////////////////////////////////////////////////////// // FileSys namespace @@ -17,8 +18,7 @@ namespace FileSys { ResultVal<size_t> DiskFile::Read(const u64 offset, const size_t length, u8* buffer) const { if (!mode.read_flag) - return ResultCode(ErrorDescription::FS_InvalidOpenFlags, ErrorModule::FS, - ErrorSummary::Canceled, ErrorLevel::Status); + return ERROR_INVALID_OPEN_FLAGS; file->Seek(offset, SEEK_SET); return MakeResult<size_t>(file->ReadBytes(buffer, length)); @@ -27,8 +27,7 @@ ResultVal<size_t> DiskFile::Read(const u64 offset, const size_t length, u8* buff ResultVal<size_t> DiskFile::Write(const u64 offset, const size_t length, const bool flush, const u8* buffer) const { if (!mode.write_flag) - return ResultCode(ErrorDescription::FS_InvalidOpenFlags, ErrorModule::FS, - ErrorSummary::Canceled, ErrorLevel::Status); + return ERROR_INVALID_OPEN_FLAGS; file->Seek(offset, SEEK_SET); size_t written = file->WriteBytes(buffer, length); diff --git a/src/core/file_sys/errors.h b/src/core/file_sys/errors.h index 9fc8d753b..a974bc775 100644 --- a/src/core/file_sys/errors.h +++ b/src/core/file_sys/errors.h @@ -2,52 +2,93 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#pragma once + #include "core/hle/result.h" namespace FileSys { -const ResultCode ERROR_INVALID_PATH(ErrorDescription::FS_InvalidPath, ErrorModule::FS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); -const ResultCode ERROR_UNSUPPORTED_OPEN_FLAGS(ErrorDescription::FS_UnsupportedOpenFlags, - ErrorModule::FS, ErrorSummary::NotSupported, - ErrorLevel::Usage); -const ResultCode ERROR_INVALID_OPEN_FLAGS(ErrorDescription::FS_InvalidOpenFlags, ErrorModule::FS, - ErrorSummary::Canceled, ErrorLevel::Status); -const ResultCode ERROR_INVALID_READ_FLAG(ErrorDescription::FS_InvalidReadFlag, ErrorModule::FS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); -const ResultCode ERROR_FILE_NOT_FOUND(ErrorDescription::FS_FileNotFound, ErrorModule::FS, - ErrorSummary::NotFound, ErrorLevel::Status); -const ResultCode ERROR_PATH_NOT_FOUND(ErrorDescription::FS_PathNotFound, ErrorModule::FS, - ErrorSummary::NotFound, ErrorLevel::Status); -const ResultCode ERROR_NOT_FOUND(ErrorDescription::FS_NotFound, ErrorModule::FS, - ErrorSummary::NotFound, ErrorLevel::Status); -const ResultCode ERROR_UNEXPECTED_FILE_OR_DIRECTORY(ErrorDescription::FS_UnexpectedFileOrDirectory, - ErrorModule::FS, ErrorSummary::NotSupported, - ErrorLevel::Usage); -const ResultCode ERROR_UNEXPECTED_FILE_OR_DIRECTORY_SDMC(ErrorDescription::FS_NotAFile, - ErrorModule::FS, ErrorSummary::Canceled, - ErrorLevel::Status); -const ResultCode ERROR_DIRECTORY_ALREADY_EXISTS(ErrorDescription::FS_DirectoryAlreadyExists, - ErrorModule::FS, ErrorSummary::NothingHappened, - ErrorLevel::Status); -const ResultCode ERROR_FILE_ALREADY_EXISTS(ErrorDescription::FS_FileAlreadyExists, ErrorModule::FS, - ErrorSummary::NothingHappened, ErrorLevel::Status); -const ResultCode ERROR_ALREADY_EXISTS(ErrorDescription::FS_AlreadyExists, ErrorModule::FS, - ErrorSummary::NothingHappened, ErrorLevel::Status); -const ResultCode ERROR_DIRECTORY_NOT_EMPTY(ErrorDescription::FS_DirectoryNotEmpty, ErrorModule::FS, - ErrorSummary::Canceled, ErrorLevel::Status); -const ResultCode ERROR_GAMECARD_NOT_INSERTED(ErrorDescription::FS_GameCardNotInserted, - ErrorModule::FS, ErrorSummary::NotFound, - ErrorLevel::Status); -const ResultCode ERROR_INCORRECT_EXEFS_READ_SIZE(ErrorDescription::FS_IncorrectExeFSReadSize, - ErrorModule::FS, ErrorSummary::NotSupported, - ErrorLevel::Usage); -const ResultCode ERROR_ROMFS_NOT_FOUND(ErrorDescription::FS_RomFSNotFound, ErrorModule::FS, - ErrorSummary::NotFound, ErrorLevel::Status); -const ResultCode ERROR_COMMAND_NOT_ALLOWED(ErrorDescription::FS_CommandNotAllowed, ErrorModule::FS, - ErrorSummary::WrongArgument, ErrorLevel::Permanent); -const ResultCode ERROR_EXEFS_SECTION_NOT_FOUND(ErrorDescription::FS_ExeFSSectionNotFound, - ErrorModule::FS, ErrorSummary::NotFound, - ErrorLevel::Status); +namespace ErrCodes { +enum { + RomFSNotFound = 100, + ArchiveNotMounted = 101, + FileNotFound = 112, + PathNotFound = 113, + GameCardNotInserted = 141, + NotFound = 120, + FileAlreadyExists = 180, + DirectoryAlreadyExists = 185, + AlreadyExists = 190, + InvalidOpenFlags = 230, + DirectoryNotEmpty = 240, + NotAFile = 250, + NotFormatted = 340, ///< This is used by the FS service when creating a SaveData archive + ExeFSSectionNotFound = 567, + CommandNotAllowed = 630, + InvalidReadFlag = 700, + InvalidPath = 702, + WriteBeyondEnd = 705, + UnsupportedOpenFlags = 760, + IncorrectExeFSReadSize = 761, + UnexpectedFileOrDirectory = 770, +}; +} + +constexpr ResultCode ERROR_INVALID_PATH(ErrCodes::InvalidPath, ErrorModule::FS, + ErrorSummary::InvalidArgument, ErrorLevel::Usage); +constexpr ResultCode ERROR_UNSUPPORTED_OPEN_FLAGS(ErrCodes::UnsupportedOpenFlags, ErrorModule::FS, + ErrorSummary::NotSupported, ErrorLevel::Usage); +constexpr ResultCode ERROR_INVALID_OPEN_FLAGS(ErrCodes::InvalidOpenFlags, ErrorModule::FS, + ErrorSummary::Canceled, ErrorLevel::Status); +constexpr ResultCode ERROR_INVALID_READ_FLAG(ErrCodes::InvalidReadFlag, ErrorModule::FS, + ErrorSummary::InvalidArgument, ErrorLevel::Usage); +constexpr ResultCode ERROR_FILE_NOT_FOUND(ErrCodes::FileNotFound, ErrorModule::FS, + ErrorSummary::NotFound, ErrorLevel::Status); +constexpr ResultCode ERROR_PATH_NOT_FOUND(ErrCodes::PathNotFound, ErrorModule::FS, + ErrorSummary::NotFound, ErrorLevel::Status); +constexpr ResultCode ERROR_NOT_FOUND(ErrCodes::NotFound, ErrorModule::FS, ErrorSummary::NotFound, + ErrorLevel::Status); +constexpr ResultCode ERROR_UNEXPECTED_FILE_OR_DIRECTORY(ErrCodes::UnexpectedFileOrDirectory, + ErrorModule::FS, ErrorSummary::NotSupported, + ErrorLevel::Usage); +constexpr ResultCode ERROR_UNEXPECTED_FILE_OR_DIRECTORY_SDMC(ErrCodes::NotAFile, ErrorModule::FS, + ErrorSummary::Canceled, + ErrorLevel::Status); +constexpr ResultCode ERROR_DIRECTORY_ALREADY_EXISTS(ErrCodes::DirectoryAlreadyExists, + ErrorModule::FS, ErrorSummary::NothingHappened, + ErrorLevel::Status); +constexpr ResultCode ERROR_FILE_ALREADY_EXISTS(ErrCodes::FileAlreadyExists, ErrorModule::FS, + ErrorSummary::NothingHappened, ErrorLevel::Status); +constexpr ResultCode ERROR_ALREADY_EXISTS(ErrCodes::AlreadyExists, ErrorModule::FS, + ErrorSummary::NothingHappened, ErrorLevel::Status); +constexpr ResultCode ERROR_DIRECTORY_NOT_EMPTY(ErrCodes::DirectoryNotEmpty, ErrorModule::FS, + ErrorSummary::Canceled, ErrorLevel::Status); +constexpr ResultCode ERROR_GAMECARD_NOT_INSERTED(ErrCodes::GameCardNotInserted, ErrorModule::FS, + ErrorSummary::NotFound, ErrorLevel::Status); +constexpr ResultCode ERROR_INCORRECT_EXEFS_READ_SIZE(ErrCodes::IncorrectExeFSReadSize, + ErrorModule::FS, ErrorSummary::NotSupported, + ErrorLevel::Usage); +constexpr ResultCode ERROR_ROMFS_NOT_FOUND(ErrCodes::RomFSNotFound, ErrorModule::FS, + ErrorSummary::NotFound, ErrorLevel::Status); +constexpr ResultCode ERROR_COMMAND_NOT_ALLOWED(ErrCodes::CommandNotAllowed, ErrorModule::FS, + ErrorSummary::WrongArgument, ErrorLevel::Permanent); +constexpr ResultCode ERROR_EXEFS_SECTION_NOT_FOUND(ErrCodes::ExeFSSectionNotFound, ErrorModule::FS, + ErrorSummary::NotFound, ErrorLevel::Status); + +/// Returned when a function is passed an invalid archive handle. +constexpr ResultCode ERR_INVALID_ARCHIVE_HANDLE(ErrCodes::ArchiveNotMounted, ErrorModule::FS, + ErrorSummary::NotFound, + ErrorLevel::Status); // 0xC8804465 +constexpr ResultCode ERR_WRITE_BEYOND_END(ErrCodes::WriteBeyondEnd, ErrorModule::FS, + ErrorSummary::InvalidArgument, ErrorLevel::Usage); + +/** + * Variant of ERROR_NOT_FOUND returned in some places in the code. Unknown if these usages are + * correct or a bug. + */ +constexpr ResultCode ERR_NOT_FOUND_INVALID_STATE(ErrCodes::NotFound, ErrorModule::FS, + ErrorSummary::InvalidState, ErrorLevel::Status); +constexpr ResultCode ERR_NOT_FORMATTED(ErrCodes::NotFormatted, ErrorModule::FS, + ErrorSummary::InvalidState, ErrorLevel::Status); } // namespace FileSys diff --git a/src/core/frontend/emu_window.cpp b/src/core/frontend/emu_window.cpp index 5fdb3a7e8..4f7d54a33 100644 --- a/src/core/frontend/emu_window.cpp +++ b/src/core/frontend/emu_window.cpp @@ -5,10 +5,10 @@ #include <algorithm> #include <cmath> #include "common/assert.h" +#include "core/3ds.h" #include "core/core.h" #include "core/frontend/emu_window.h" #include "core/settings.h" -#include "video_core/video_core.h" /** * Check if the given x/y coordinates are within the touchpad specified by the framebuffer layout @@ -38,11 +38,9 @@ void EmuWindow::TouchPressed(unsigned framebuffer_x, unsigned framebuffer_y) { if (!IsWithinTouchscreen(framebuffer_layout, framebuffer_x, framebuffer_y)) return; - touch_x = VideoCore::kScreenBottomWidth * - (framebuffer_x - framebuffer_layout.bottom_screen.left) / + touch_x = Core::kScreenBottomWidth * (framebuffer_x - framebuffer_layout.bottom_screen.left) / (framebuffer_layout.bottom_screen.right - framebuffer_layout.bottom_screen.left); - touch_y = VideoCore::kScreenBottomHeight * - (framebuffer_y - framebuffer_layout.bottom_screen.top) / + touch_y = Core::kScreenBottomHeight * (framebuffer_y - framebuffer_layout.bottom_screen.top) / (framebuffer_layout.bottom_screen.bottom - framebuffer_layout.bottom_screen.top); touch_pressed = true; diff --git a/src/core/frontend/emu_window.h b/src/core/frontend/emu_window.h index 36f2667fa..9414123a4 100644 --- a/src/core/frontend/emu_window.h +++ b/src/core/frontend/emu_window.h @@ -8,8 +8,8 @@ #include <tuple> #include <utility> #include "common/common_types.h" -#include "common/framebuffer_layout.h" #include "common/math_util.h" +#include "core/frontend/framebuffer_layout.h" /** * Abstraction class used to provide an interface between emulation code and the frontend diff --git a/src/core/frontend/framebuffer_layout.cpp b/src/core/frontend/framebuffer_layout.cpp new file mode 100644 index 000000000..d2d02f9ff --- /dev/null +++ b/src/core/frontend/framebuffer_layout.cpp @@ -0,0 +1,161 @@ +// Copyright 2016 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include <cmath> + +#include "common/assert.h" +#include "core/3ds.h" +#include "core/frontend/framebuffer_layout.h" +#include "core/settings.h" + +namespace Layout { + +static const float TOP_SCREEN_ASPECT_RATIO = + static_cast<float>(Core::kScreenTopHeight) / Core::kScreenTopWidth; +static const float BOT_SCREEN_ASPECT_RATIO = + static_cast<float>(Core::kScreenBottomHeight) / Core::kScreenBottomWidth; + +float FramebufferLayout::GetScalingRatio() const { + return static_cast<float>(top_screen.GetWidth()) / Core::kScreenTopWidth; +} + +// Finds the largest size subrectangle contained in window area that is confined to the aspect ratio +template <class T> +static MathUtil::Rectangle<T> maxRectangle(MathUtil::Rectangle<T> window_area, + float screen_aspect_ratio) { + float scale = std::min(static_cast<float>(window_area.GetWidth()), + window_area.GetHeight() / screen_aspect_ratio); + return MathUtil::Rectangle<T>{0, 0, static_cast<T>(std::round(scale)), + static_cast<T>(std::round(scale * screen_aspect_ratio))}; +} + +FramebufferLayout DefaultFrameLayout(unsigned width, unsigned height, bool swapped) { + ASSERT(width > 0); + ASSERT(height > 0); + + FramebufferLayout res{width, height, true, true, {}, {}}; + // Default layout gives equal screen sizes to the top and bottom screen + MathUtil::Rectangle<unsigned> screen_window_area{0, 0, width, height / 2}; + MathUtil::Rectangle<unsigned> top_screen = + maxRectangle(screen_window_area, TOP_SCREEN_ASPECT_RATIO); + MathUtil::Rectangle<unsigned> bot_screen = + maxRectangle(screen_window_area, BOT_SCREEN_ASPECT_RATIO); + + float window_aspect_ratio = static_cast<float>(height) / width; + // both screens height are taken into account by multiplying by 2 + float emulation_aspect_ratio = TOP_SCREEN_ASPECT_RATIO * 2; + + if (window_aspect_ratio < emulation_aspect_ratio) { + // Apply borders to the left and right sides of the window. + top_screen = + top_screen.TranslateX((screen_window_area.GetWidth() - top_screen.GetWidth()) / 2); + bot_screen = + bot_screen.TranslateX((screen_window_area.GetWidth() - bot_screen.GetWidth()) / 2); + } else { + // Window is narrower than the emulation content => apply borders to the top and bottom + // Recalculate the bottom screen to account for the width difference between top and bottom + screen_window_area = {0, 0, width, top_screen.GetHeight()}; + bot_screen = maxRectangle(screen_window_area, BOT_SCREEN_ASPECT_RATIO); + bot_screen = bot_screen.TranslateX((top_screen.GetWidth() - bot_screen.GetWidth()) / 2); + if (swapped) { + bot_screen = bot_screen.TranslateY(height / 2 - bot_screen.GetHeight()); + } else { + top_screen = top_screen.TranslateY(height / 2 - top_screen.GetHeight()); + } + } + // Move the top screen to the bottom if we are swapped. + res.top_screen = swapped ? top_screen.TranslateY(height / 2) : top_screen; + res.bottom_screen = swapped ? bot_screen : bot_screen.TranslateY(height / 2); + return res; +} + +FramebufferLayout SingleFrameLayout(unsigned width, unsigned height, bool swapped) { + ASSERT(width > 0); + ASSERT(height > 0); + // The drawing code needs at least somewhat valid values for both screens + // so just calculate them both even if the other isn't showing. + FramebufferLayout res{width, height, !swapped, swapped, {}, {}}; + + MathUtil::Rectangle<unsigned> screen_window_area{0, 0, width, height}; + MathUtil::Rectangle<unsigned> top_screen = + maxRectangle(screen_window_area, TOP_SCREEN_ASPECT_RATIO); + MathUtil::Rectangle<unsigned> bot_screen = + maxRectangle(screen_window_area, BOT_SCREEN_ASPECT_RATIO); + + float window_aspect_ratio = static_cast<float>(height) / width; + float emulation_aspect_ratio = (swapped) ? BOT_SCREEN_ASPECT_RATIO : TOP_SCREEN_ASPECT_RATIO; + + if (window_aspect_ratio < emulation_aspect_ratio) { + top_screen = + top_screen.TranslateX((screen_window_area.GetWidth() - top_screen.GetWidth()) / 2); + bot_screen = + bot_screen.TranslateX((screen_window_area.GetWidth() - bot_screen.GetWidth()) / 2); + } else { + top_screen = top_screen.TranslateY((height - top_screen.GetHeight()) / 2); + bot_screen = bot_screen.TranslateY((height - bot_screen.GetHeight()) / 2); + } + res.top_screen = top_screen; + res.bottom_screen = bot_screen; + return res; +} + +FramebufferLayout LargeFrameLayout(unsigned width, unsigned height, bool swapped) { + ASSERT(width > 0); + ASSERT(height > 0); + + FramebufferLayout res{width, height, true, true, {}, {}}; + // Split the window into two parts. Give 4x width to the main screen and 1x width to the small + // To do that, find the total emulation box and maximize that based on window size + float window_aspect_ratio = static_cast<float>(height) / width; + float emulation_aspect_ratio = + swapped + ? Core::kScreenBottomHeight * 4 / + (Core::kScreenBottomWidth * 4.0f + Core::kScreenTopWidth) + : Core::kScreenTopHeight * 4 / + (Core::kScreenTopWidth * 4.0f + Core::kScreenBottomWidth); + float large_screen_aspect_ratio = swapped ? BOT_SCREEN_ASPECT_RATIO : TOP_SCREEN_ASPECT_RATIO; + float small_screen_aspect_ratio = swapped ? TOP_SCREEN_ASPECT_RATIO : BOT_SCREEN_ASPECT_RATIO; + + MathUtil::Rectangle<unsigned> screen_window_area{0, 0, width, height}; + MathUtil::Rectangle<unsigned> total_rect = + maxRectangle(screen_window_area, emulation_aspect_ratio); + MathUtil::Rectangle<unsigned> large_screen = + maxRectangle(total_rect, large_screen_aspect_ratio); + MathUtil::Rectangle<unsigned> fourth_size_rect = total_rect.Scale(.25f); + MathUtil::Rectangle<unsigned> small_screen = + maxRectangle(fourth_size_rect, small_screen_aspect_ratio); + + if (window_aspect_ratio < emulation_aspect_ratio) { + large_screen = + large_screen.TranslateX((screen_window_area.GetWidth() - total_rect.GetWidth()) / 2); + } else { + large_screen = large_screen.TranslateY((height - total_rect.GetHeight()) / 2); + } + // Shift the small screen to the bottom right corner + small_screen = + small_screen.TranslateX(large_screen.right) + .TranslateY(large_screen.GetHeight() + large_screen.top - small_screen.GetHeight()); + res.top_screen = swapped ? small_screen : large_screen; + res.bottom_screen = swapped ? large_screen : small_screen; + return res; +} + +FramebufferLayout CustomFrameLayout(unsigned width, unsigned height) { + ASSERT(width > 0); + ASSERT(height > 0); + + FramebufferLayout res{width, height, true, true, {}, {}}; + + MathUtil::Rectangle<unsigned> top_screen{ + Settings::values.custom_top_left, Settings::values.custom_top_top, + Settings::values.custom_top_right, Settings::values.custom_top_bottom}; + MathUtil::Rectangle<unsigned> bot_screen{ + Settings::values.custom_bottom_left, Settings::values.custom_bottom_top, + Settings::values.custom_bottom_right, Settings::values.custom_bottom_bottom}; + + res.top_screen = top_screen; + res.bottom_screen = bot_screen; + return res; +} +} diff --git a/src/core/frontend/framebuffer_layout.h b/src/core/frontend/framebuffer_layout.h new file mode 100644 index 000000000..9a7738969 --- /dev/null +++ b/src/core/frontend/framebuffer_layout.h @@ -0,0 +1,64 @@ +// Copyright 2016 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include "common/math_util.h" + +namespace Layout { + +/// Describes the layout of the window framebuffer (size and top/bottom screen positions) +struct FramebufferLayout { + unsigned width; + unsigned height; + bool top_screen_enabled; + bool bottom_screen_enabled; + MathUtil::Rectangle<unsigned> top_screen; + MathUtil::Rectangle<unsigned> bottom_screen; + + /** + * Returns the ration of pixel size of the top screen, compared to the native size of the 3DS + * screen. + */ + float GetScalingRatio() const; +}; + +/** + * Factory method for constructing a default FramebufferLayout + * @param width Window framebuffer width in pixels + * @param height Window framebuffer height in pixels + * @param is_swapped if true, the bottom screen will be displayed above the top screen + * @return Newly created FramebufferLayout object with default screen regions initialized + */ +FramebufferLayout DefaultFrameLayout(unsigned width, unsigned height, bool is_swapped); + +/** + * Factory method for constructing a FramebufferLayout with only the top or bottom screen + * @param width Window framebuffer width in pixels + * @param height Window framebuffer height in pixels + * @param is_swapped if true, the bottom screen will be displayed (and the top won't be displayed) + * @return Newly created FramebufferLayout object with default screen regions initialized + */ +FramebufferLayout SingleFrameLayout(unsigned width, unsigned height, bool is_swapped); + +/** + * Factory method for constructing a Frame with the a 4x size Top screen with a 1x size bottom + * screen on the right + * This is useful in particular because it matches well with a 1920x1080 resolution monitor + * @param width Window framebuffer width in pixels + * @param height Window framebuffer height in pixels + * @param is_swapped if true, the bottom screen will be the large display + * @return Newly created FramebufferLayout object with default screen regions initialized + */ +FramebufferLayout LargeFrameLayout(unsigned width, unsigned height, bool is_swapped); + +/** + * Factory method for constructing a custom FramebufferLayout + * @param width Window framebuffer width in pixels + * @param height Window framebuffer height in pixels + * @return Newly created FramebufferLayout object with default screen regions initialized + */ +FramebufferLayout CustomFrameLayout(unsigned width, unsigned height); + +} // namespace Layout diff --git a/src/core/hle/applets/mii_selector.cpp b/src/core/hle/applets/mii_selector.cpp index 07c7f5b99..89f08daa2 100644 --- a/src/core/hle/applets/mii_selector.cpp +++ b/src/core/hle/applets/mii_selector.cpp @@ -11,7 +11,6 @@ #include "core/hle/kernel/kernel.h" #include "core/hle/kernel/shared_memory.h" #include "core/hle/result.h" -#include "video_core/video_core.h" //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/core/hle/applets/swkbd.cpp b/src/core/hle/applets/swkbd.cpp index 059297fbc..fdf8807b0 100644 --- a/src/core/hle/applets/swkbd.cpp +++ b/src/core/hle/applets/swkbd.cpp @@ -14,7 +14,6 @@ #include "core/hle/service/gsp_gpu.h" #include "core/hle/service/hid/hid.h" #include "core/memory.h" -#include "video_core/video_core.h" //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/core/hle/function_wrappers.h b/src/core/hle/function_wrappers.h index f6eb900f0..18b6e7017 100644 --- a/src/core/hle/function_wrappers.h +++ b/src/core/hle/function_wrappers.h @@ -53,7 +53,7 @@ void Wrap() { FuncReturn(retval); } -template <ResultCode func(u32*, s32, u32, u32, u32, s32)> +template <ResultCode func(u32*, u32, u32, u32, u32, s32)> void Wrap() { u32 param_1 = 0; u32 retval = func(¶m_1, PARAM(0), PARAM(1), PARAM(2), PARAM(3), PARAM(4)).raw; diff --git a/src/core/hle/ipc.h b/src/core/hle/ipc.h index 3a5d481a5..303ca090d 100644 --- a/src/core/hle/ipc.h +++ b/src/core/hle/ipc.h @@ -5,6 +5,7 @@ #pragma once #include "common/common_types.h" +#include "core/hle/kernel/errors.h" #include "core/hle/kernel/thread.h" #include "core/memory.h" @@ -43,6 +44,12 @@ inline u32* GetStaticBuffers(const int offset = 0) { namespace IPC { +// These errors are commonly returned by invalid IPC translations, so alias them here for +// convenience. +// TODO(yuriks): These will probably go away once translation is implemented inside the kernel. +using Kernel::ERR_INVALID_BUFFER_DESCRIPTOR; +constexpr auto ERR_INVALID_HANDLE = Kernel::ERR_INVALID_HANDLE_OS; + enum DescriptorType : u32 { // Buffer related desciptors types (mask : 0x0F) StaticBuffer = 0x02, diff --git a/src/core/hle/ipc_helpers.h b/src/core/hle/ipc_helpers.h index 06c4c5a85..d7348c09d 100644 --- a/src/core/hle/ipc_helpers.h +++ b/src/core/hle/ipc_helpers.h @@ -3,7 +3,9 @@ // Refer to the license.txt file included. #pragma once + #include "core/hle/ipc.h" +#include "core/hle/kernel/handle_table.h" #include "core/hle/kernel/kernel.h" namespace IPC { diff --git a/src/core/hle/kernel/address_arbiter.cpp b/src/core/hle/kernel/address_arbiter.cpp index 01fab123e..776d342f0 100644 --- a/src/core/hle/kernel/address_arbiter.cpp +++ b/src/core/hle/kernel/address_arbiter.cpp @@ -5,6 +5,7 @@ #include "common/common_types.h" #include "common/logging/log.h" #include "core/hle/kernel/address_arbiter.h" +#include "core/hle/kernel/errors.h" #include "core/hle/kernel/thread.h" #include "core/memory.h" @@ -74,8 +75,7 @@ ResultCode AddressArbiter::ArbitrateAddress(ArbitrationType type, VAddr address, default: LOG_ERROR(Kernel, "unknown type=%d", type); - return ResultCode(ErrorDescription::InvalidEnumValue, ErrorModule::Kernel, - ErrorSummary::WrongArgument, ErrorLevel::Usage); + return ERR_INVALID_ENUM_VALUE_FND; } // The calls that use a timeout seem to always return a Timeout error even if they did not put @@ -83,8 +83,7 @@ ResultCode AddressArbiter::ArbitrateAddress(ArbitrationType type, VAddr address, if (type == ArbitrationType::WaitIfLessThanWithTimeout || type == ArbitrationType::DecrementAndWaitIfLessThanWithTimeout) { - return ResultCode(ErrorDescription::Timeout, ErrorModule::OS, ErrorSummary::StatusChanged, - ErrorLevel::Info); + return RESULT_TIMEOUT; } return RESULT_SUCCESS; } diff --git a/src/core/hle/kernel/address_arbiter.h b/src/core/hle/kernel/address_arbiter.h index 6a7af93a9..1d24401b1 100644 --- a/src/core/hle/kernel/address_arbiter.h +++ b/src/core/hle/kernel/address_arbiter.h @@ -6,6 +6,7 @@ #include "common/common_types.h" #include "core/hle/kernel/kernel.h" +#include "core/hle/result.h" // Address arbiters are an underlying kernel synchronization object that can be created/used via // supervisor calls (SVCs). They function as sort of a global lock. Typically, games/other CTR diff --git a/src/core/hle/kernel/client_port.cpp b/src/core/hle/kernel/client_port.cpp index ddcf4c916..03ffdece1 100644 --- a/src/core/hle/kernel/client_port.cpp +++ b/src/core/hle/kernel/client_port.cpp @@ -5,6 +5,7 @@ #include "common/assert.h" #include "core/hle/kernel/client_port.h" #include "core/hle/kernel/client_session.h" +#include "core/hle/kernel/errors.h" #include "core/hle/kernel/kernel.h" #include "core/hle/kernel/server_port.h" #include "core/hle/kernel/server_session.h" @@ -19,8 +20,7 @@ ResultVal<SharedPtr<ClientSession>> ClientPort::Connect() { // AcceptSession before returning from this call. if (active_sessions >= max_sessions) { - return ResultCode(ErrorDescription::MaxConnectionsReached, ErrorModule::OS, - ErrorSummary::WouldBlock, ErrorLevel::Temporary); + return ERR_MAX_CONNECTIONS_REACHED; } active_sessions++; diff --git a/src/core/hle/kernel/client_port.h b/src/core/hle/kernel/client_port.h index 511490c7c..8f7d6ac44 100644 --- a/src/core/hle/kernel/client_port.h +++ b/src/core/hle/kernel/client_port.h @@ -7,6 +7,7 @@ #include <string> #include "common/common_types.h" #include "core/hle/kernel/kernel.h" +#include "core/hle/result.h" namespace Kernel { diff --git a/src/core/hle/kernel/client_session.cpp b/src/core/hle/kernel/client_session.cpp index e297b7464..783b1c061 100644 --- a/src/core/hle/kernel/client_session.cpp +++ b/src/core/hle/kernel/client_session.cpp @@ -30,8 +30,7 @@ ResultCode ClientSession::SendSyncRequest() { if (parent->server) return parent->server->HandleSyncRequest(); - return ResultCode(ErrorDescription::SessionClosedByRemote, ErrorModule::OS, - ErrorSummary::Canceled, ErrorLevel::Status); + return ERR_SESSION_CLOSED_BY_REMOTE; } } // namespace diff --git a/src/core/hle/kernel/client_session.h b/src/core/hle/kernel/client_session.h index 9f3adb72b..2de379c09 100644 --- a/src/core/hle/kernel/client_session.h +++ b/src/core/hle/kernel/client_session.h @@ -6,10 +6,9 @@ #include <memory> #include <string> - #include "common/common_types.h" - #include "core/hle/kernel/kernel.h" +#include "core/hle/result.h" namespace Kernel { diff --git a/src/core/hle/kernel/errors.h b/src/core/hle/kernel/errors.h new file mode 100644 index 000000000..b3b60e7df --- /dev/null +++ b/src/core/hle/kernel/errors.h @@ -0,0 +1,98 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include "core/hle/result.h" + +namespace Kernel { + +namespace ErrCodes { +enum { + OutOfHandles = 19, + SessionClosedByRemote = 26, + PortNameTooLong = 30, + WrongPermission = 46, + InvalidBufferDescriptor = 48, + MaxConnectionsReached = 52, +}; +} + +// WARNING: The kernel is quite inconsistent in it's usage of errors code. Make sure to always +// double check that the code matches before re-using the constant. + +constexpr ResultCode ERR_OUT_OF_HANDLES(ErrCodes::OutOfHandles, ErrorModule::Kernel, + ErrorSummary::OutOfResource, + ErrorLevel::Permanent); // 0xD8600413 +constexpr ResultCode ERR_SESSION_CLOSED_BY_REMOTE(ErrCodes::SessionClosedByRemote, ErrorModule::OS, + ErrorSummary::Canceled, + ErrorLevel::Status); // 0xC920181A +constexpr ResultCode ERR_PORT_NAME_TOO_LONG(ErrCodes::PortNameTooLong, ErrorModule::OS, + ErrorSummary::InvalidArgument, + ErrorLevel::Usage); // 0xE0E0181E +constexpr ResultCode ERR_WRONG_PERMISSION(ErrCodes::WrongPermission, ErrorModule::OS, + ErrorSummary::WrongArgument, ErrorLevel::Permanent); +constexpr ResultCode ERR_INVALID_BUFFER_DESCRIPTOR(ErrCodes::InvalidBufferDescriptor, + ErrorModule::OS, ErrorSummary::WrongArgument, + ErrorLevel::Permanent); +constexpr ResultCode ERR_MAX_CONNECTIONS_REACHED(ErrCodes::MaxConnectionsReached, ErrorModule::OS, + ErrorSummary::WouldBlock, + ErrorLevel::Temporary); // 0xD0401834 + +constexpr ResultCode ERR_NOT_AUTHORIZED(ErrorDescription::NotAuthorized, ErrorModule::OS, + ErrorSummary::WrongArgument, + ErrorLevel::Permanent); // 0xD9001BEA +constexpr ResultCode ERR_INVALID_ENUM_VALUE(ErrorDescription::InvalidEnumValue, ErrorModule::Kernel, + ErrorSummary::InvalidArgument, + ErrorLevel::Permanent); // 0xD8E007ED +constexpr ResultCode ERR_INVALID_ENUM_VALUE_FND(ErrorDescription::InvalidEnumValue, + ErrorModule::FND, ErrorSummary::InvalidArgument, + ErrorLevel::Permanent); // 0xD8E093ED +constexpr ResultCode ERR_INVALID_COMBINATION(ErrorDescription::InvalidCombination, ErrorModule::OS, + ErrorSummary::InvalidArgument, + ErrorLevel::Usage); // 0xE0E01BEE +constexpr ResultCode ERR_INVALID_COMBINATION_KERNEL(ErrorDescription::InvalidCombination, + ErrorModule::Kernel, + ErrorSummary::WrongArgument, + ErrorLevel::Permanent); // 0xD90007EE +constexpr ResultCode ERR_MISALIGNED_ADDRESS(ErrorDescription::MisalignedAddress, ErrorModule::OS, + ErrorSummary::InvalidArgument, + ErrorLevel::Usage); // 0xE0E01BF1 +constexpr ResultCode ERR_MISALIGNED_SIZE(ErrorDescription::MisalignedSize, ErrorModule::OS, + ErrorSummary::InvalidArgument, + ErrorLevel::Usage); // 0xE0E01BF2 +constexpr ResultCode ERR_OUT_OF_MEMORY(ErrorDescription::OutOfMemory, ErrorModule::Kernel, + ErrorSummary::OutOfResource, + ErrorLevel::Permanent); // 0xD86007F3 +constexpr ResultCode ERR_NOT_IMPLEMENTED(ErrorDescription::NotImplemented, ErrorModule::OS, + ErrorSummary::InvalidArgument, + ErrorLevel::Usage); // 0xE0E01BF4 +constexpr ResultCode ERR_INVALID_ADDRESS(ErrorDescription::InvalidAddress, ErrorModule::OS, + ErrorSummary::InvalidArgument, + ErrorLevel::Usage); // 0xE0E01BF5 +constexpr ResultCode ERR_INVALID_ADDRESS_STATE(ErrorDescription::InvalidAddress, ErrorModule::OS, + ErrorSummary::InvalidState, + ErrorLevel::Usage); // 0xE0A01BF5 +constexpr ResultCode ERR_INVALID_POINTER(ErrorDescription::InvalidPointer, ErrorModule::Kernel, + ErrorSummary::InvalidArgument, + ErrorLevel::Permanent); // 0xD8E007F6 +constexpr ResultCode ERR_INVALID_HANDLE(ErrorDescription::InvalidHandle, ErrorModule::Kernel, + ErrorSummary::InvalidArgument, + ErrorLevel::Permanent); // 0xD8E007F7 +/// Alternate code returned instead of ERR_INVALID_HANDLE in some code paths. +constexpr ResultCode ERR_INVALID_HANDLE_OS(ErrorDescription::InvalidHandle, ErrorModule::OS, + ErrorSummary::WrongArgument, + ErrorLevel::Permanent); // 0xD9001BF7 +constexpr ResultCode ERR_NOT_FOUND(ErrorDescription::NotFound, ErrorModule::Kernel, + ErrorSummary::NotFound, ErrorLevel::Permanent); // 0xD88007FA +constexpr ResultCode ERR_OUT_OF_RANGE(ErrorDescription::OutOfRange, ErrorModule::OS, + ErrorSummary::InvalidArgument, + ErrorLevel::Usage); // 0xE0E01BFD +constexpr ResultCode ERR_OUT_OF_RANGE_KERNEL(ErrorDescription::OutOfRange, ErrorModule::Kernel, + ErrorSummary::InvalidArgument, + ErrorLevel::Permanent); // 0xD8E007FD +constexpr ResultCode RESULT_TIMEOUT(ErrorDescription::Timeout, ErrorModule::OS, + ErrorSummary::StatusChanged, ErrorLevel::Info); + +} // namespace Kernel diff --git a/src/core/hle/kernel/event.h b/src/core/hle/kernel/event.h index 3e3673508..cc41abb85 100644 --- a/src/core/hle/kernel/event.h +++ b/src/core/hle/kernel/event.h @@ -6,6 +6,7 @@ #include "common/common_types.h" #include "core/hle/kernel/kernel.h" +#include "core/hle/kernel/wait_object.h" namespace Kernel { diff --git a/src/core/hle/kernel/handle_table.cpp b/src/core/hle/kernel/handle_table.cpp new file mode 100644 index 000000000..c7322d883 --- /dev/null +++ b/src/core/hle/kernel/handle_table.cpp @@ -0,0 +1,97 @@ +// Copyright 2014 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include <utility> +#include "common/assert.h" +#include "common/logging/log.h" +#include "core/hle/kernel/errors.h" +#include "core/hle/kernel/handle_table.h" +#include "core/hle/kernel/kernel.h" +#include "core/hle/kernel/process.h" +#include "core/hle/kernel/thread.h" + +namespace Kernel { + +HandleTable g_handle_table; + +HandleTable::HandleTable() { + next_generation = 1; + Clear(); +} + +ResultVal<Handle> HandleTable::Create(SharedPtr<Object> obj) { + DEBUG_ASSERT(obj != nullptr); + + u16 slot = next_free_slot; + if (slot >= generations.size()) { + LOG_ERROR(Kernel, "Unable to allocate Handle, too many slots in use."); + return ERR_OUT_OF_HANDLES; + } + next_free_slot = generations[slot]; + + u16 generation = next_generation++; + + // Overflow count so it fits in the 15 bits dedicated to the generation in the handle. + // CTR-OS doesn't use generation 0, so skip straight to 1. + if (next_generation >= (1 << 15)) + next_generation = 1; + + generations[slot] = generation; + objects[slot] = std::move(obj); + + Handle handle = generation | (slot << 15); + return MakeResult<Handle>(handle); +} + +ResultVal<Handle> HandleTable::Duplicate(Handle handle) { + SharedPtr<Object> object = GetGeneric(handle); + if (object == nullptr) { + LOG_ERROR(Kernel, "Tried to duplicate invalid handle: %08X", handle); + return ERR_INVALID_HANDLE; + } + return Create(std::move(object)); +} + +ResultCode HandleTable::Close(Handle handle) { + if (!IsValid(handle)) + return ERR_INVALID_HANDLE; + + u16 slot = GetSlot(handle); + + objects[slot] = nullptr; + + generations[slot] = next_free_slot; + next_free_slot = slot; + return RESULT_SUCCESS; +} + +bool HandleTable::IsValid(Handle handle) const { + size_t slot = GetSlot(handle); + u16 generation = GetGeneration(handle); + + return slot < MAX_COUNT && objects[slot] != nullptr && generations[slot] == generation; +} + +SharedPtr<Object> HandleTable::GetGeneric(Handle handle) const { + if (handle == CurrentThread) { + return GetCurrentThread(); + } else if (handle == CurrentProcess) { + return g_current_process; + } + + if (!IsValid(handle)) { + return nullptr; + } + return objects[GetSlot(handle)]; +} + +void HandleTable::Clear() { + for (u16 i = 0; i < MAX_COUNT; ++i) { + generations[i] = i + 1; + objects[i] = nullptr; + } + next_free_slot = 0; +} + +} // namespace diff --git a/src/core/hle/kernel/handle_table.h b/src/core/hle/kernel/handle_table.h new file mode 100644 index 000000000..d6aaefbf7 --- /dev/null +++ b/src/core/hle/kernel/handle_table.h @@ -0,0 +1,126 @@ +// Copyright 2014 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include <array> +#include <cstddef> +#include "common/common_types.h" +#include "core/hle/kernel/kernel.h" +#include "core/hle/result.h" + +namespace Kernel { + +enum KernelHandle : Handle { + CurrentThread = 0xFFFF8000, + CurrentProcess = 0xFFFF8001, +}; + +/** + * This class allows the creation of Handles, which are references to objects that can be tested + * for validity and looked up. Here they are used to pass references to kernel objects to/from the + * emulated process. it has been designed so that it follows the same handle format and has + * approximately the same restrictions as the handle manager in the CTR-OS. + * + * Handles contain two sub-fields: a slot index (bits 31:15) and a generation value (bits 14:0). + * The slot index is used to index into the arrays in this class to access the data corresponding + * to the Handle. + * + * To prevent accidental use of a freed Handle whose slot has already been reused, a global counter + * is kept and incremented every time a Handle is created. This is the Handle's "generation". The + * value of the counter is stored into the Handle as well as in the handle table (in the + * "generations" array). When looking up a handle, the Handle's generation must match with the + * value stored on the class, otherwise the Handle is considered invalid. + * + * To find free slots when allocating a Handle without needing to scan the entire object array, the + * generations field of unallocated slots is re-purposed as a linked list of indices to free slots. + * When a Handle is created, an index is popped off the list and used for the new Handle. When it + * is destroyed, it is again pushed onto the list to be re-used by the next allocation. It is + * likely that this allocation strategy differs from the one used in CTR-OS, but this hasn't been + * verified and isn't likely to cause any problems. + */ +class HandleTable final : NonCopyable { +public: + HandleTable(); + + /** + * Allocates a handle for the given object. + * @return The created Handle or one of the following errors: + * - `ERR_OUT_OF_HANDLES`: the maximum number of handles has been exceeded. + */ + ResultVal<Handle> Create(SharedPtr<Object> obj); + + /** + * Returns a new handle that points to the same object as the passed in handle. + * @return The duplicated Handle or one of the following errors: + * - `ERR_INVALID_HANDLE`: an invalid handle was passed in. + * - Any errors returned by `Create()`. + */ + ResultVal<Handle> Duplicate(Handle handle); + + /** + * Closes a handle, removing it from the table and decreasing the object's ref-count. + * @return `RESULT_SUCCESS` or one of the following errors: + * - `ERR_INVALID_HANDLE`: an invalid handle was passed in. + */ + ResultCode Close(Handle handle); + + /// Checks if a handle is valid and points to an existing object. + bool IsValid(Handle handle) const; + + /** + * Looks up a handle. + * @return Pointer to the looked-up object, or `nullptr` if the handle is not valid. + */ + SharedPtr<Object> GetGeneric(Handle handle) const; + + /** + * Looks up a handle while verifying its type. + * @return Pointer to the looked-up object, or `nullptr` if the handle is not valid or its + * type differs from the requested one. + */ + template <class T> + SharedPtr<T> Get(Handle handle) const { + return DynamicObjectCast<T>(GetGeneric(handle)); + } + + /// Closes all handles held in this table. + void Clear(); + +private: + /** + * This is the maximum limit of handles allowed per process in CTR-OS. It can be further + * reduced by ExHeader values, but this is not emulated here. + */ + static const size_t MAX_COUNT = 4096; + + static u16 GetSlot(Handle handle) { + return handle >> 15; + } + static u16 GetGeneration(Handle handle) { + return handle & 0x7FFF; + } + + /// Stores the Object referenced by the handle or null if the slot is empty. + std::array<SharedPtr<Object>, MAX_COUNT> objects; + + /** + * The value of `next_generation` when the handle was created, used to check for validity. For + * empty slots, contains the index of the next free slot in the list. + */ + std::array<u16, MAX_COUNT> generations; + + /** + * Global counter of the number of created handles. Stored in `generations` when a handle is + * created, and wraps around to 1 when it hits 0x8000. + */ + u16 next_generation; + + /// Head of the free slots linked list. + u16 next_free_slot; +}; + +extern HandleTable g_handle_table; + +} // namespace diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp index f599916f0..7470a97ca 100644 --- a/src/core/hle/kernel/kernel.cpp +++ b/src/core/hle/kernel/kernel.cpp @@ -2,10 +2,8 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#include <algorithm> -#include "common/assert.h" -#include "common/logging/log.h" #include "core/hle/config_mem.h" +#include "core/hle/kernel/handle_table.h" #include "core/hle/kernel/kernel.h" #include "core/hle/kernel/memory.h" #include "core/hle/kernel/process.h" @@ -17,165 +15,6 @@ namespace Kernel { unsigned int Object::next_object_id; -HandleTable g_handle_table; - -void WaitObject::AddWaitingThread(SharedPtr<Thread> thread) { - auto itr = std::find(waiting_threads.begin(), waiting_threads.end(), thread); - if (itr == waiting_threads.end()) - waiting_threads.push_back(std::move(thread)); -} - -void WaitObject::RemoveWaitingThread(Thread* thread) { - auto itr = std::find(waiting_threads.begin(), waiting_threads.end(), thread); - // If a thread passed multiple handles to the same object, - // the kernel might attempt to remove the thread from the object's - // waiting threads list multiple times. - if (itr != waiting_threads.end()) - waiting_threads.erase(itr); -} - -SharedPtr<Thread> WaitObject::GetHighestPriorityReadyThread() { - Thread* candidate = nullptr; - s32 candidate_priority = THREADPRIO_LOWEST + 1; - - for (const auto& thread : waiting_threads) { - // The list of waiting threads must not contain threads that are not waiting to be awakened. - ASSERT_MSG(thread->status == THREADSTATUS_WAIT_SYNCH_ANY || - thread->status == THREADSTATUS_WAIT_SYNCH_ALL, - "Inconsistent thread statuses in waiting_threads"); - - if (thread->current_priority >= candidate_priority) - continue; - - if (ShouldWait(thread.get())) - continue; - - // A thread is ready to run if it's either in THREADSTATUS_WAIT_SYNCH_ANY or - // in THREADSTATUS_WAIT_SYNCH_ALL and the rest of the objects it is waiting on are ready. - bool ready_to_run = true; - if (thread->status == THREADSTATUS_WAIT_SYNCH_ALL) { - ready_to_run = std::none_of(thread->wait_objects.begin(), thread->wait_objects.end(), - [&thread](const SharedPtr<WaitObject>& object) { - return object->ShouldWait(thread.get()); - }); - } - - if (ready_to_run) { - candidate = thread.get(); - candidate_priority = thread->current_priority; - } - } - - return candidate; -} - -void WaitObject::WakeupAllWaitingThreads() { - while (auto thread = GetHighestPriorityReadyThread()) { - if (!thread->IsSleepingOnWaitAll()) { - Acquire(thread.get()); - // Set the output index of the WaitSynchronizationN call to the index of this object. - if (thread->wait_set_output) { - thread->SetWaitSynchronizationOutput(thread->GetWaitObjectIndex(this)); - thread->wait_set_output = false; - } - } else { - for (auto& object : thread->wait_objects) { - object->Acquire(thread.get()); - } - // Note: This case doesn't update the output index of WaitSynchronizationN. - } - - for (auto& object : thread->wait_objects) - object->RemoveWaitingThread(thread.get()); - thread->wait_objects.clear(); - - thread->SetWaitSynchronizationResult(RESULT_SUCCESS); - thread->ResumeFromWait(); - } -} - -const std::vector<SharedPtr<Thread>>& WaitObject::GetWaitingThreads() const { - return waiting_threads; -} - -HandleTable::HandleTable() { - next_generation = 1; - Clear(); -} - -ResultVal<Handle> HandleTable::Create(SharedPtr<Object> obj) { - DEBUG_ASSERT(obj != nullptr); - - u16 slot = next_free_slot; - if (slot >= generations.size()) { - LOG_ERROR(Kernel, "Unable to allocate Handle, too many slots in use."); - return ERR_OUT_OF_HANDLES; - } - next_free_slot = generations[slot]; - - u16 generation = next_generation++; - - // Overflow count so it fits in the 15 bits dedicated to the generation in the handle. - // CTR-OS doesn't use generation 0, so skip straight to 1. - if (next_generation >= (1 << 15)) - next_generation = 1; - - generations[slot] = generation; - objects[slot] = std::move(obj); - - Handle handle = generation | (slot << 15); - return MakeResult<Handle>(handle); -} - -ResultVal<Handle> HandleTable::Duplicate(Handle handle) { - SharedPtr<Object> object = GetGeneric(handle); - if (object == nullptr) { - LOG_ERROR(Kernel, "Tried to duplicate invalid handle: %08X", handle); - return ERR_INVALID_HANDLE; - } - return Create(std::move(object)); -} - -ResultCode HandleTable::Close(Handle handle) { - if (!IsValid(handle)) - return ERR_INVALID_HANDLE; - - u16 slot = GetSlot(handle); - - objects[slot] = nullptr; - - generations[slot] = next_free_slot; - next_free_slot = slot; - return RESULT_SUCCESS; -} - -bool HandleTable::IsValid(Handle handle) const { - size_t slot = GetSlot(handle); - u16 generation = GetGeneration(handle); - - return slot < MAX_COUNT && objects[slot] != nullptr && generations[slot] == generation; -} - -SharedPtr<Object> HandleTable::GetGeneric(Handle handle) const { - if (handle == CurrentThread) { - return GetCurrentThread(); - } else if (handle == CurrentProcess) { - return g_current_process; - } - - if (!IsValid(handle)) { - return nullptr; - } - return objects[GetSlot(handle)]; -} - -void HandleTable::Clear() { - for (u16 i = 0; i < MAX_COUNT; ++i) { - generations[i] = i + 1; - objects[i] = nullptr; - } - next_free_slot = 0; -} /// Initialize the kernel void Init(u32 system_mode) { diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h index bb8b99bb5..9cf288b08 100644 --- a/src/core/hle/kernel/kernel.h +++ b/src/core/hle/kernel/kernel.h @@ -4,33 +4,16 @@ #pragma once -#include <algorithm> -#include <array> #include <cstddef> #include <string> -#include <vector> +#include <utility> #include <boost/smart_ptr/intrusive_ptr.hpp> #include "common/common_types.h" -#include "core/hle/result.h" namespace Kernel { using Handle = u32; -class Thread; - -// TODO: Verify code -const ResultCode ERR_OUT_OF_HANDLES(ErrorDescription::OutOfMemory, ErrorModule::Kernel, - ErrorSummary::OutOfResource, ErrorLevel::Temporary); -// TOOD: Verify code -const ResultCode ERR_INVALID_HANDLE(ErrorDescription::InvalidHandle, ErrorModule::Kernel, - ErrorSummary::InvalidArgument, ErrorLevel::Permanent); - -enum KernelHandle : Handle { - CurrentThread = 0xFFFF8000, - CurrentProcess = 0xFFFF8001, -}; - enum class HandleType : u32 { Unknown, Event, @@ -128,170 +111,17 @@ inline void intrusive_ptr_release(Object* object) { template <typename T> using SharedPtr = boost::intrusive_ptr<T>; -/// Class that represents a Kernel object that a thread can be waiting on -class WaitObject : public Object { -public: - /** - * Check if the specified thread should wait until the object is available - * @param thread The thread about which we're deciding. - * @return True if the current thread should wait due to this object being unavailable - */ - virtual bool ShouldWait(Thread* thread) const = 0; - - /// Acquire/lock the object for the specified thread if it is available - virtual void Acquire(Thread* thread) = 0; - - /** - * Add a thread to wait on this object - * @param thread Pointer to thread to add - */ - virtual void AddWaitingThread(SharedPtr<Thread> thread); - - /** - * Removes a thread from waiting on this object (e.g. if it was resumed already) - * @param thread Pointer to thread to remove - */ - virtual void RemoveWaitingThread(Thread* thread); - - /** - * Wake up all threads waiting on this object that can be awoken, in priority order, - * and set the synchronization result and output of the thread. - */ - virtual void WakeupAllWaitingThreads(); - - /// Obtains the highest priority thread that is ready to run from this object's waiting list. - SharedPtr<Thread> GetHighestPriorityReadyThread(); - - /// Get a const reference to the waiting threads list for debug use - const std::vector<SharedPtr<Thread>>& GetWaitingThreads() const; - -private: - /// Threads waiting for this object to become available - std::vector<SharedPtr<Thread>> waiting_threads; -}; - /** - * This class allows the creation of Handles, which are references to objects that can be tested - * for validity and looked up. Here they are used to pass references to kernel objects to/from the - * emulated process. it has been designed so that it follows the same handle format and has - * approximately the same restrictions as the handle manager in the CTR-OS. - * - * Handles contain two sub-fields: a slot index (bits 31:15) and a generation value (bits 14:0). - * The slot index is used to index into the arrays in this class to access the data corresponding - * to the Handle. - * - * To prevent accidental use of a freed Handle whose slot has already been reused, a global counter - * is kept and incremented every time a Handle is created. This is the Handle's "generation". The - * value of the counter is stored into the Handle as well as in the handle table (in the - * "generations" array). When looking up a handle, the Handle's generation must match with the - * value stored on the class, otherwise the Handle is considered invalid. - * - * To find free slots when allocating a Handle without needing to scan the entire object array, the - * generations field of unallocated slots is re-purposed as a linked list of indices to free slots. - * When a Handle is created, an index is popped off the list and used for the new Handle. When it - * is destroyed, it is again pushed onto the list to be re-used by the next allocation. It is - * likely that this allocation strategy differs from the one used in CTR-OS, but this hasn't been - * verified and isn't likely to cause any problems. + * Attempts to downcast the given Object pointer to a pointer to T. + * @return Derived pointer to the object, or `nullptr` if `object` isn't of type T. */ -class HandleTable final : NonCopyable { -public: - HandleTable(); - - /** - * Allocates a handle for the given object. - * @return The created Handle or one of the following errors: - * - `ERR_OUT_OF_HANDLES`: the maximum number of handles has been exceeded. - */ - ResultVal<Handle> Create(SharedPtr<Object> obj); - - /** - * Returns a new handle that points to the same object as the passed in handle. - * @return The duplicated Handle or one of the following errors: - * - `ERR_INVALID_HANDLE`: an invalid handle was passed in. - * - Any errors returned by `Create()`. - */ - ResultVal<Handle> Duplicate(Handle handle); - - /** - * Closes a handle, removing it from the table and decreasing the object's ref-count. - * @return `RESULT_SUCCESS` or one of the following errors: - * - `ERR_INVALID_HANDLE`: an invalid handle was passed in. - */ - ResultCode Close(Handle handle); - - /// Checks if a handle is valid and points to an existing object. - bool IsValid(Handle handle) const; - - /** - * Looks up a handle. - * @return Pointer to the looked-up object, or `nullptr` if the handle is not valid. - */ - SharedPtr<Object> GetGeneric(Handle handle) const; - - /** - * Looks up a handle while verifying its type. - * @return Pointer to the looked-up object, or `nullptr` if the handle is not valid or its - * type differs from the handle type `T::HANDLE_TYPE`. - */ - template <class T> - SharedPtr<T> Get(Handle handle) const { - SharedPtr<Object> object = GetGeneric(handle); - if (object != nullptr && object->GetHandleType() == T::HANDLE_TYPE) { - return boost::static_pointer_cast<T>(std::move(object)); - } - return nullptr; - } - - /** - * Looks up a handle while verifying that it is an object that a thread can wait on - * @return Pointer to the looked-up object, or `nullptr` if the handle is not valid or it is - * not a waitable object. - */ - SharedPtr<WaitObject> GetWaitObject(Handle handle) const { - SharedPtr<Object> object = GetGeneric(handle); - if (object != nullptr && object->IsWaitable()) { - return boost::static_pointer_cast<WaitObject>(std::move(object)); - } - return nullptr; - } - - /// Closes all handles held in this table. - void Clear(); - -private: - /** - * This is the maximum limit of handles allowed per process in CTR-OS. It can be further - * reduced by ExHeader values, but this is not emulated here. - */ - static const size_t MAX_COUNT = 4096; - - static u16 GetSlot(Handle handle) { - return handle >> 15; - } - static u16 GetGeneration(Handle handle) { - return handle & 0x7FFF; +template <typename T> +inline SharedPtr<T> DynamicObjectCast(SharedPtr<Object> object) { + if (object != nullptr && object->GetHandleType() == T::HANDLE_TYPE) { + return boost::static_pointer_cast<T>(std::move(object)); } - - /// Stores the Object referenced by the handle or null if the slot is empty. - std::array<SharedPtr<Object>, MAX_COUNT> objects; - - /** - * The value of `next_generation` when the handle was created, used to check for validity. For - * empty slots, contains the index of the next free slot in the list. - */ - std::array<u16, MAX_COUNT> generations; - - /** - * Global counter of the number of created handles. Stored in `generations` when a handle is - * created, and wraps around to 1 when it hits 0x8000. - */ - u16 next_generation; - - /// Head of the free slots linked list. - u16 next_free_slot; -}; - -extern HandleTable g_handle_table; + return nullptr; +} /// Initialize the kernel with the specified system mode. void Init(u32 system_mode); diff --git a/src/core/hle/kernel/memory.cpp b/src/core/hle/kernel/memory.cpp index 8250a90b5..804f23b1c 100644 --- a/src/core/hle/kernel/memory.cpp +++ b/src/core/hle/kernel/memory.cpp @@ -2,6 +2,7 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include <algorithm> #include <cinttypes> #include <map> #include <memory> diff --git a/src/core/hle/kernel/mutex.h b/src/core/hle/kernel/mutex.h index c57adf400..bacacd690 100644 --- a/src/core/hle/kernel/mutex.h +++ b/src/core/hle/kernel/mutex.h @@ -7,6 +7,7 @@ #include <string> #include "common/common_types.h" #include "core/hle/kernel/kernel.h" +#include "core/hle/kernel/wait_object.h" namespace Kernel { diff --git a/src/core/hle/kernel/process.cpp b/src/core/hle/kernel/process.cpp index 32cb25fb7..1c31ec950 100644 --- a/src/core/hle/kernel/process.cpp +++ b/src/core/hle/kernel/process.cpp @@ -6,6 +6,7 @@ #include "common/assert.h" #include "common/common_funcs.h" #include "common/logging/log.h" +#include "core/hle/kernel/errors.h" #include "core/hle/kernel/memory.h" #include "core/hle/kernel/process.h" #include "core/hle/kernel/resource_limit.h" diff --git a/src/core/hle/kernel/resource_limit.cpp b/src/core/hle/kernel/resource_limit.cpp index 3f51bc5de..a8f10a3ee 100644 --- a/src/core/hle/kernel/resource_limit.cpp +++ b/src/core/hle/kernel/resource_limit.cpp @@ -3,6 +3,7 @@ // Refer to the license.txt file included. #include <cstring> +#include "common/assert.h" #include "common/logging/log.h" #include "core/hle/kernel/resource_limit.h" diff --git a/src/core/hle/kernel/semaphore.cpp b/src/core/hle/kernel/semaphore.cpp index 8bda2f75d..fcf586728 100644 --- a/src/core/hle/kernel/semaphore.cpp +++ b/src/core/hle/kernel/semaphore.cpp @@ -3,6 +3,7 @@ // Refer to the license.txt file included. #include "common/assert.h" +#include "core/hle/kernel/errors.h" #include "core/hle/kernel/kernel.h" #include "core/hle/kernel/semaphore.h" #include "core/hle/kernel/thread.h" @@ -16,8 +17,7 @@ ResultVal<SharedPtr<Semaphore>> Semaphore::Create(s32 initial_count, s32 max_cou std::string name) { if (initial_count > max_count) - return ResultCode(ErrorDescription::InvalidCombination, ErrorModule::Kernel, - ErrorSummary::WrongArgument, ErrorLevel::Permanent); + return ERR_INVALID_COMBINATION_KERNEL; SharedPtr<Semaphore> semaphore(new Semaphore); @@ -42,8 +42,7 @@ void Semaphore::Acquire(Thread* thread) { ResultVal<s32> Semaphore::Release(s32 release_count) { if (max_count - available_count < release_count) - return ResultCode(ErrorDescription::OutOfRange, ErrorModule::Kernel, - ErrorSummary::InvalidArgument, ErrorLevel::Permanent); + return ERR_OUT_OF_RANGE_KERNEL; s32 previous_count = available_count; available_count += release_count; diff --git a/src/core/hle/kernel/semaphore.h b/src/core/hle/kernel/semaphore.h index cde94f7cc..7b0cacf2e 100644 --- a/src/core/hle/kernel/semaphore.h +++ b/src/core/hle/kernel/semaphore.h @@ -8,6 +8,8 @@ #include <string> #include "common/common_types.h" #include "core/hle/kernel/kernel.h" +#include "core/hle/kernel/wait_object.h" +#include "core/hle/result.h" namespace Kernel { diff --git a/src/core/hle/kernel/server_port.h b/src/core/hle/kernel/server_port.h index 6f8bdb6a9..2a24d8412 100644 --- a/src/core/hle/kernel/server_port.h +++ b/src/core/hle/kernel/server_port.h @@ -9,6 +9,7 @@ #include <tuple> #include "common/common_types.h" #include "core/hle/kernel/kernel.h" +#include "core/hle/kernel/wait_object.h" namespace Service { class SessionRequestHandler; diff --git a/src/core/hle/kernel/server_session.h b/src/core/hle/kernel/server_session.h index c907d487c..f1b76d8aa 100644 --- a/src/core/hle/kernel/server_session.h +++ b/src/core/hle/kernel/server_session.h @@ -10,7 +10,7 @@ #include "common/common_types.h" #include "core/hle/kernel/kernel.h" #include "core/hle/kernel/session.h" -#include "core/hle/kernel/thread.h" +#include "core/hle/kernel/wait_object.h" #include "core/hle/result.h" #include "core/hle/service/service.h" #include "core/memory.h" @@ -20,6 +20,7 @@ namespace Kernel { class ClientSession; class ClientPort; class ServerSession; +class Thread; /** * Kernel object representing the server endpoint of an IPC session. Sessions are the basic CTR-OS diff --git a/src/core/hle/kernel/shared_memory.cpp b/src/core/hle/kernel/shared_memory.cpp index bc1560d12..922e5ab58 100644 --- a/src/core/hle/kernel/shared_memory.cpp +++ b/src/core/hle/kernel/shared_memory.cpp @@ -4,6 +4,7 @@ #include <cstring> #include "common/logging/log.h" +#include "core/hle/kernel/errors.h" #include "core/hle/kernel/memory.h" #include "core/hle/kernel/shared_memory.h" #include "core/memory.h" @@ -102,24 +103,21 @@ ResultCode SharedMemory::Map(Process* target_process, VAddr address, MemoryPermi // Automatically allocated memory blocks can only be mapped with other_permissions = DontCare if (base_address == 0 && other_permissions != MemoryPermission::DontCare) { - return ResultCode(ErrorDescription::InvalidCombination, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return ERR_INVALID_COMBINATION; } // Error out if the requested permissions don't match what the creator process allows. if (static_cast<u32>(permissions) & ~static_cast<u32>(own_other_permissions)) { LOG_ERROR(Kernel, "cannot map id=%u, address=0x%08X name=%s, permissions don't match", GetObjectId(), address, name.c_str()); - return ResultCode(ErrorDescription::InvalidCombination, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return ERR_INVALID_COMBINATION; } // Heap-backed memory blocks can not be mapped with other_permissions = DontCare if (base_address != 0 && other_permissions == MemoryPermission::DontCare) { LOG_ERROR(Kernel, "cannot map id=%u, address=0x%08X name=%s, permissions don't match", GetObjectId(), address, name.c_str()); - return ResultCode(ErrorDescription::InvalidCombination, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return ERR_INVALID_COMBINATION; } // Error out if the provided permissions are not compatible with what the creator process needs. @@ -127,8 +125,7 @@ ResultCode SharedMemory::Map(Process* target_process, VAddr address, MemoryPermi static_cast<u32>(this->permissions) & ~static_cast<u32>(other_permissions)) { LOG_ERROR(Kernel, "cannot map id=%u, address=0x%08X name=%s, permissions don't match", GetObjectId(), address, name.c_str()); - return ResultCode(ErrorDescription::WrongPermission, ErrorModule::OS, - ErrorSummary::WrongArgument, ErrorLevel::Permanent); + return ERR_WRONG_PERMISSION; } // TODO(Subv): Check for the Shared Device Mem flag in the creator process. @@ -144,8 +141,7 @@ ResultCode SharedMemory::Map(Process* target_process, VAddr address, MemoryPermi if (address < Memory::HEAP_VADDR || address + size >= Memory::SHARED_MEMORY_VADDR_END) { LOG_ERROR(Kernel, "cannot map id=%u, address=0x%08X name=%s, invalid address", GetObjectId(), address, name.c_str()); - return ResultCode(ErrorDescription::InvalidAddress, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return ERR_INVALID_ADDRESS; } } diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp index 3b7555d87..75ce626f8 100644 --- a/src/core/hle/kernel/thread.cpp +++ b/src/core/hle/kernel/thread.cpp @@ -14,6 +14,8 @@ #include "core/arm/skyeye_common/armstate.h" #include "core/core.h" #include "core/core_timing.h" +#include "core/hle/kernel/errors.h" +#include "core/hle/kernel/handle_table.h" #include "core/hle/kernel/kernel.h" #include "core/hle/kernel/memory.h" #include "core/hle/kernel/mutex.h" @@ -241,9 +243,7 @@ static void ThreadWakeupCallback(u64 thread_handle, int cycles_late) { for (auto& object : thread->wait_objects) object->RemoveWaitingThread(thread.get()); thread->wait_objects.clear(); - thread->SetWaitSynchronizationResult(ResultCode(ErrorDescription::Timeout, ErrorModule::OS, - ErrorSummary::StatusChanged, - ErrorLevel::Info)); + thread->SetWaitSynchronizationResult(RESULT_TIMEOUT); } thread->ResumeFromWait(); @@ -351,10 +351,20 @@ static void ResetThreadContext(ARM_Interface::ThreadContext& context, u32 stack_ context.cpsr = USER32MODE | ((entry_point & 1) << 5); // Usermode and THUMB mode } -ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, s32 priority, +ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, u32 priority, u32 arg, s32 processor_id, VAddr stack_top) { - ASSERT_MSG(priority >= THREADPRIO_HIGHEST && priority <= THREADPRIO_LOWEST, - "Invalid thread priority"); + // Check if priority is in ranged. Lowest priority -> highest priority id. + if (priority > THREADPRIO_LOWEST) { + LOG_ERROR(Kernel_SVC, "Invalid thread priority: %d", priority); + return ERR_OUT_OF_RANGE; + } + + if (processor_id > THREADPROCESSORID_MAX) { + LOG_ERROR(Kernel_SVC, "Invalid processor id: %d", processor_id); + return ERR_OUT_OF_RANGE_KERNEL; + } + + // TODO(yuriks): Other checks, returning 0xD9001BEA if (!Memory::IsValidVirtualAddress(entry_point)) { LOG_ERROR(Kernel_SVC, "(name=%s): invalid entry %08x", name.c_str(), entry_point); @@ -399,8 +409,7 @@ ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, if (linheap_memory->size() + Memory::PAGE_SIZE > memory_region->size) { LOG_ERROR(Kernel_SVC, "Not enough space in region to allocate a new TLS page for thread"); - return ResultCode(ErrorDescription::OutOfMemory, ErrorModule::Kernel, - ErrorSummary::OutOfResource, ErrorLevel::Permanent); + return ERR_OUT_OF_MEMORY; } u32 offset = linheap_memory->size(); diff --git a/src/core/hle/kernel/thread.h b/src/core/hle/kernel/thread.h index 6ab31c70b..6a3566f15 100644 --- a/src/core/hle/kernel/thread.h +++ b/src/core/hle/kernel/thread.h @@ -12,6 +12,7 @@ #include "common/common_types.h" #include "core/arm/arm_interface.h" #include "core/hle/kernel/kernel.h" +#include "core/hle/kernel/wait_object.h" #include "core/hle/result.h" enum ThreadPriority : s32 { @@ -57,7 +58,7 @@ public: * @param stack_top The address of the thread's stack top * @return A shared pointer to the newly created thread */ - static ResultVal<SharedPtr<Thread>> Create(std::string name, VAddr entry_point, s32 priority, + static ResultVal<SharedPtr<Thread>> Create(std::string name, VAddr entry_point, u32 priority, u32 arg, s32 processor_id, VAddr stack_top); std::string GetName() const override { diff --git a/src/core/hle/kernel/timer.cpp b/src/core/hle/kernel/timer.cpp index a00c75679..6f2cf3b02 100644 --- a/src/core/hle/kernel/timer.cpp +++ b/src/core/hle/kernel/timer.cpp @@ -6,6 +6,7 @@ #include "common/assert.h" #include "common/logging/log.h" #include "core/core_timing.h" +#include "core/hle/kernel/handle_table.h" #include "core/hle/kernel/kernel.h" #include "core/hle/kernel/thread.h" #include "core/hle/kernel/timer.h" diff --git a/src/core/hle/kernel/timer.h b/src/core/hle/kernel/timer.h index b0f818933..82552372d 100644 --- a/src/core/hle/kernel/timer.h +++ b/src/core/hle/kernel/timer.h @@ -6,6 +6,7 @@ #include "common/common_types.h" #include "core/hle/kernel/kernel.h" +#include "core/hle/kernel/wait_object.h" namespace Kernel { diff --git a/src/core/hle/kernel/vm_manager.cpp b/src/core/hle/kernel/vm_manager.cpp index 6dd24f846..cef1f7fa8 100644 --- a/src/core/hle/kernel/vm_manager.cpp +++ b/src/core/hle/kernel/vm_manager.cpp @@ -4,6 +4,7 @@ #include <iterator> #include "common/assert.h" +#include "core/hle/kernel/errors.h" #include "core/hle/kernel/vm_manager.h" #include "core/memory.h" #include "core/memory_setup.h" diff --git a/src/core/hle/kernel/vm_manager.h b/src/core/hle/kernel/vm_manager.h index 9055664b2..38e0d74d0 100644 --- a/src/core/hle/kernel/vm_manager.h +++ b/src/core/hle/kernel/vm_manager.h @@ -13,14 +13,6 @@ namespace Kernel { -const ResultCode ERR_INVALID_ADDRESS{// 0xE0E01BF5 - ErrorDescription::InvalidAddress, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage}; - -const ResultCode ERR_INVALID_ADDRESS_STATE{// 0xE0A01BF5 - ErrorDescription::InvalidAddress, ErrorModule::OS, - ErrorSummary::InvalidState, ErrorLevel::Usage}; - enum class VMAType : u8 { /// VMA represents an unmapped region of the address space. Free, diff --git a/src/core/hle/kernel/wait_object.cpp b/src/core/hle/kernel/wait_object.cpp new file mode 100644 index 000000000..f245eda6c --- /dev/null +++ b/src/core/hle/kernel/wait_object.cpp @@ -0,0 +1,99 @@ +// Copyright 2014 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include <algorithm> +#include "common/assert.h" +#include "common/logging/log.h" +#include "core/hle/config_mem.h" +#include "core/hle/kernel/errors.h" +#include "core/hle/kernel/kernel.h" +#include "core/hle/kernel/memory.h" +#include "core/hle/kernel/process.h" +#include "core/hle/kernel/resource_limit.h" +#include "core/hle/kernel/thread.h" +#include "core/hle/kernel/timer.h" +#include "core/hle/shared_page.h" + +namespace Kernel { + +void WaitObject::AddWaitingThread(SharedPtr<Thread> thread) { + auto itr = std::find(waiting_threads.begin(), waiting_threads.end(), thread); + if (itr == waiting_threads.end()) + waiting_threads.push_back(std::move(thread)); +} + +void WaitObject::RemoveWaitingThread(Thread* thread) { + auto itr = std::find(waiting_threads.begin(), waiting_threads.end(), thread); + // If a thread passed multiple handles to the same object, + // the kernel might attempt to remove the thread from the object's + // waiting threads list multiple times. + if (itr != waiting_threads.end()) + waiting_threads.erase(itr); +} + +SharedPtr<Thread> WaitObject::GetHighestPriorityReadyThread() { + Thread* candidate = nullptr; + s32 candidate_priority = THREADPRIO_LOWEST + 1; + + for (const auto& thread : waiting_threads) { + // The list of waiting threads must not contain threads that are not waiting to be awakened. + ASSERT_MSG(thread->status == THREADSTATUS_WAIT_SYNCH_ANY || + thread->status == THREADSTATUS_WAIT_SYNCH_ALL, + "Inconsistent thread statuses in waiting_threads"); + + if (thread->current_priority >= candidate_priority) + continue; + + if (ShouldWait(thread.get())) + continue; + + // A thread is ready to run if it's either in THREADSTATUS_WAIT_SYNCH_ANY or + // in THREADSTATUS_WAIT_SYNCH_ALL and the rest of the objects it is waiting on are ready. + bool ready_to_run = true; + if (thread->status == THREADSTATUS_WAIT_SYNCH_ALL) { + ready_to_run = std::none_of(thread->wait_objects.begin(), thread->wait_objects.end(), + [&thread](const SharedPtr<WaitObject>& object) { + return object->ShouldWait(thread.get()); + }); + } + + if (ready_to_run) { + candidate = thread.get(); + candidate_priority = thread->current_priority; + } + } + + return candidate; +} + +void WaitObject::WakeupAllWaitingThreads() { + while (auto thread = GetHighestPriorityReadyThread()) { + if (!thread->IsSleepingOnWaitAll()) { + Acquire(thread.get()); + // Set the output index of the WaitSynchronizationN call to the index of this object. + if (thread->wait_set_output) { + thread->SetWaitSynchronizationOutput(thread->GetWaitObjectIndex(this)); + thread->wait_set_output = false; + } + } else { + for (auto& object : thread->wait_objects) { + object->Acquire(thread.get()); + } + // Note: This case doesn't update the output index of WaitSynchronizationN. + } + + for (auto& object : thread->wait_objects) + object->RemoveWaitingThread(thread.get()); + thread->wait_objects.clear(); + + thread->SetWaitSynchronizationResult(RESULT_SUCCESS); + thread->ResumeFromWait(); + } +} + +const std::vector<SharedPtr<Thread>>& WaitObject::GetWaitingThreads() const { + return waiting_threads; +} + +} // namespace Kernel diff --git a/src/core/hle/kernel/wait_object.h b/src/core/hle/kernel/wait_object.h new file mode 100644 index 000000000..861578186 --- /dev/null +++ b/src/core/hle/kernel/wait_object.h @@ -0,0 +1,67 @@ +// Copyright 2014 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include <vector> +#include <boost/smart_ptr/intrusive_ptr.hpp> +#include "common/common_types.h" +#include "core/hle/kernel/kernel.h" + +namespace Kernel { + +class Thread; + +/// Class that represents a Kernel object that a thread can be waiting on +class WaitObject : public Object { +public: + /** + * Check if the specified thread should wait until the object is available + * @param thread The thread about which we're deciding. + * @return True if the current thread should wait due to this object being unavailable + */ + virtual bool ShouldWait(Thread* thread) const = 0; + + /// Acquire/lock the object for the specified thread if it is available + virtual void Acquire(Thread* thread) = 0; + + /** + * Add a thread to wait on this object + * @param thread Pointer to thread to add + */ + virtual void AddWaitingThread(SharedPtr<Thread> thread); + + /** + * Removes a thread from waiting on this object (e.g. if it was resumed already) + * @param thread Pointer to thread to remove + */ + virtual void RemoveWaitingThread(Thread* thread); + + /** + * Wake up all threads waiting on this object that can be awoken, in priority order, + * and set the synchronization result and output of the thread. + */ + virtual void WakeupAllWaitingThreads(); + + /// Obtains the highest priority thread that is ready to run from this object's waiting list. + SharedPtr<Thread> GetHighestPriorityReadyThread(); + + /// Get a const reference to the waiting threads list for debug use + const std::vector<SharedPtr<Thread>>& GetWaitingThreads() const; + +private: + /// Threads waiting for this object to become available + std::vector<SharedPtr<Thread>> waiting_threads; +}; + +// Specialization of DynamicObjectCast for WaitObjects +template <> +inline SharedPtr<WaitObject> DynamicObjectCast<WaitObject>(SharedPtr<Object> object) { + if (object != nullptr && object->IsWaitable()) { + return boost::static_pointer_cast<WaitObject>(std::move(object)); + } + return nullptr; +} + +} // namespace Kernel diff --git a/src/core/hle/result.h b/src/core/hle/result.h index 13b948871..c49650f7d 100644 --- a/src/core/hle/result.h +++ b/src/core/hle/result.h @@ -13,38 +13,15 @@ // All the constants in this file come from http://3dbrew.org/wiki/Error_codes -/// Detailed description of the error. This listing is likely incomplete. +/** + * Detailed description of the error. Code 0 always means success. Codes 1000 and above are + * considered "well-known" and have common values between all modules. The meaning of other codes + * vary by module. + */ enum class ErrorDescription : u32 { Success = 0, - SessionClosedByRemote = 26, - WrongPermission = 46, - OS_InvalidBufferDescriptor = 48, - MaxConnectionsReached = 52, - WrongAddress = 53, - FS_RomFSNotFound = 100, - FS_ArchiveNotMounted = 101, - FS_FileNotFound = 112, - FS_PathNotFound = 113, - FS_GameCardNotInserted = 141, - FS_NotFound = 120, - FS_FileAlreadyExists = 180, - FS_DirectoryAlreadyExists = 185, - FS_AlreadyExists = 190, - FS_InvalidOpenFlags = 230, - FS_DirectoryNotEmpty = 240, - FS_NotAFile = 250, - FS_NotFormatted = 340, ///< This is used by the FS service when creating a SaveData archive - OutofRangeOrMisalignedAddress = - 513, // TODO(purpasmart): Check if this name fits its actual usage - GPU_FirstInitialization = 519, - FS_ExeFSSectionNotFound = 567, - FS_CommandNotAllowed = 630, - FS_InvalidReadFlag = 700, - FS_InvalidPath = 702, - FS_WriteBeyondEnd = 705, - FS_UnsupportedOpenFlags = 760, - FS_IncorrectExeFSReadSize = 761, - FS_UnexpectedFileOrDirectory = 770, + + // Codes 1000 and above are considered "well-known" and have common values between all modules. InvalidSection = 1000, TooLarge = 1001, NotAuthorized = 1002, @@ -218,7 +195,7 @@ enum class ErrorLevel : u32 { union ResultCode { u32 raw; - BitField<0, 10, ErrorDescription> description; + BitField<0, 10, u32> description; BitField<10, 8, ErrorModule> module; BitField<21, 6, ErrorSummary> summary; @@ -228,45 +205,46 @@ union ResultCode { // error BitField<31, 1, u32> is_error; - explicit ResultCode(u32 raw) : raw(raw) {} - ResultCode(ErrorDescription description_, ErrorModule module_, ErrorSummary summary_, - ErrorLevel level_) - : raw(0) { - description.Assign(description_); - module.Assign(module_); - summary.Assign(summary_); - level.Assign(level_); - } + constexpr explicit ResultCode(u32 raw) : raw(raw) {} + + constexpr ResultCode(ErrorDescription description, ErrorModule module, ErrorSummary summary, + ErrorLevel level) + : ResultCode(static_cast<u32>(description), module, summary, level) {} + + constexpr ResultCode(u32 description_, ErrorModule module_, ErrorSummary summary_, + ErrorLevel level_) + : raw(description.FormatValue(description_) | module.FormatValue(module_) | + summary.FormatValue(summary_) | level.FormatValue(level_)) {} - ResultCode& operator=(const ResultCode& o) { + constexpr ResultCode& operator=(const ResultCode& o) { raw = o.raw; return *this; } - bool IsSuccess() const { - return is_error == 0; + constexpr bool IsSuccess() const { + return is_error.ExtractValue(raw) == 0; } - bool IsError() const { - return is_error == 1; + constexpr bool IsError() const { + return is_error.ExtractValue(raw) == 1; } }; -inline bool operator==(const ResultCode& a, const ResultCode& b) { +constexpr bool operator==(const ResultCode& a, const ResultCode& b) { return a.raw == b.raw; } -inline bool operator!=(const ResultCode& a, const ResultCode& b) { +constexpr bool operator!=(const ResultCode& a, const ResultCode& b) { return a.raw != b.raw; } // Convenience functions for creating some common kinds of errors: /// The default success `ResultCode`. -const ResultCode RESULT_SUCCESS(0); +constexpr ResultCode RESULT_SUCCESS(0); /// Might be returned instead of a dummy success for unimplemented APIs. -inline ResultCode UnimplementedFunction(ErrorModule module) { +constexpr ResultCode UnimplementedFunction(ErrorModule module) { return ResultCode(ErrorDescription::NotImplemented, module, ErrorSummary::NotSupported, ErrorLevel::Permanent); } diff --git a/src/core/hle/service/apt/apt.h b/src/core/hle/service/apt/apt.h index e63b61450..ee80926d2 100644 --- a/src/core/hle/service/apt/apt.h +++ b/src/core/hle/service/apt/apt.h @@ -4,6 +4,8 @@ #pragma once +#include <vector> +#include "common/common_funcs.h" #include "common/common_types.h" #include "common/swap.h" #include "core/hle/kernel/kernel.h" diff --git a/src/core/hle/service/boss/boss.cpp b/src/core/hle/service/boss/boss.cpp index e0de037f8..91056189a 100644 --- a/src/core/hle/service/boss/boss.cpp +++ b/src/core/hle/service/boss/boss.cpp @@ -24,9 +24,7 @@ void InitializeSession(Service::Interface* self) { if (translation != IPC::CallingPidDesc()) { cmd_buff[0] = IPC::MakeHeader(0, 0x1, 0); // 0x40 - cmd_buff[1] = ResultCode(ErrorDescription::OS_InvalidBufferDescriptor, ErrorModule::OS, - ErrorSummary::WrongArgument, ErrorLevel::Permanent) - .raw; + cmd_buff[1] = IPC::ERR_INVALID_BUFFER_DESCRIPTOR.raw; LOG_ERROR(Service_BOSS, "The translation was invalid, translation=0x%08X", translation); return; } diff --git a/src/core/hle/service/cfg/cfg.cpp b/src/core/hle/service/cfg/cfg.cpp index 8c8c1ec77..caa41ded7 100644 --- a/src/core/hle/service/cfg/cfg.cpp +++ b/src/core/hle/service/cfg/cfg.cpp @@ -11,6 +11,7 @@ #include "common/string_util.h" #include "common/swap.h" #include "core/file_sys/archive_systemsavedata.h" +#include "core/file_sys/errors.h" #include "core/file_sys/file_backend.h" #include "core/hle/result.h" #include "core/hle/service/cfg/cfg.h" @@ -411,7 +412,7 @@ ResultCode UpdateConfigNANDSavegame() { ResultCode FormatConfig() { ResultCode res = DeleteConfigNANDSaveFile(); // The delete command fails if the file doesn't exist, so we have to check that too - if (!res.IsSuccess() && res.description != ErrorDescription::FS_FileNotFound) { + if (!res.IsSuccess() && res != FileSys::ERROR_FILE_NOT_FOUND) { return res; } // Delete the old data @@ -534,7 +535,7 @@ ResultCode LoadConfigNANDSaveFile() { Service::FS::OpenArchive(Service::FS::ArchiveIdCode::SystemSaveData, archive_path); // If the archive didn't exist, create the files inside - if (archive_result.Code().description == ErrorDescription::FS_NotFormatted) { + if (archive_result.Code() == FileSys::ERR_NOT_FORMATTED) { // Format the archive to create the directories Service::FS::FormatArchive(Service::FS::ArchiveIdCode::SystemSaveData, FileSys::ArchiveFormatInfo(), archive_path); diff --git a/src/core/hle/service/dsp_dsp.cpp b/src/core/hle/service/dsp_dsp.cpp index 39711ea97..79171a0bc 100644 --- a/src/core/hle/service/dsp_dsp.cpp +++ b/src/core/hle/service/dsp_dsp.cpp @@ -289,9 +289,7 @@ static void WriteProcessPipe(Service::Interface* self) { "size=0x%X, buffer=0x%08X", cmd_buff[3], pipe_index, size, buffer); cmd_buff[0] = IPC::MakeHeader(0, 1, 0); - cmd_buff[1] = ResultCode(ErrorDescription::OS_InvalidBufferDescriptor, ErrorModule::OS, - ErrorSummary::WrongArgument, ErrorLevel::Permanent) - .raw; + cmd_buff[1] = IPC::ERR_INVALID_BUFFER_DESCRIPTOR.raw; return; } diff --git a/src/core/hle/service/fs/archive.cpp b/src/core/hle/service/fs/archive.cpp index 6cddc1fdb..632712f2c 100644 --- a/src/core/hle/service/fs/archive.cpp +++ b/src/core/hle/service/fs/archive.cpp @@ -22,6 +22,7 @@ #include "core/file_sys/archive_sdmcwriteonly.h" #include "core/file_sys/archive_systemsavedata.h" #include "core/file_sys/directory_backend.h" +#include "core/file_sys/errors.h" #include "core/file_sys/file_backend.h" #include "core/hle/kernel/client_session.h" #include "core/hle/result.h" @@ -50,16 +51,6 @@ static constexpr Kernel::Handle INVALID_HANDLE{}; namespace Service { namespace FS { -// TODO: Verify code -/// Returned when a function is passed an invalid handle. -const ResultCode ERR_INVALID_HANDLE(ErrorDescription::InvalidHandle, ErrorModule::FS, - ErrorSummary::InvalidArgument, ErrorLevel::Permanent); - -/// Returned when a function is passed an invalid archive handle. -const ResultCode ERR_INVALID_ARCHIVE_HANDLE(ErrorDescription::FS_ArchiveNotMounted, ErrorModule::FS, - ErrorSummary::NotFound, - ErrorLevel::Status); // 0xC8804465 - // Command to access archive file enum class FileCommand : u32 { Dummy1 = 0x000100C6, @@ -284,7 +275,7 @@ ResultVal<ArchiveHandle> OpenArchive(ArchiveIdCode id_code, FileSys::Path& archi ResultCode CloseArchive(ArchiveHandle handle) { if (handle_map.erase(handle) == 0) - return ERR_INVALID_ARCHIVE_HANDLE; + return FileSys::ERR_INVALID_ARCHIVE_HANDLE; else return RESULT_SUCCESS; } @@ -309,7 +300,7 @@ ResultVal<std::shared_ptr<File>> OpenFileFromArchive(ArchiveHandle archive_handl const FileSys::Mode mode) { ArchiveBackend* archive = GetArchive(archive_handle); if (archive == nullptr) - return ERR_INVALID_ARCHIVE_HANDLE; + return FileSys::ERR_INVALID_ARCHIVE_HANDLE; auto backend = archive->OpenFile(path, mode); if (backend.Failed()) @@ -322,7 +313,7 @@ ResultVal<std::shared_ptr<File>> OpenFileFromArchive(ArchiveHandle archive_handl ResultCode DeleteFileFromArchive(ArchiveHandle archive_handle, const FileSys::Path& path) { ArchiveBackend* archive = GetArchive(archive_handle); if (archive == nullptr) - return ERR_INVALID_ARCHIVE_HANDLE; + return FileSys::ERR_INVALID_ARCHIVE_HANDLE; return archive->DeleteFile(path); } @@ -334,7 +325,7 @@ ResultCode RenameFileBetweenArchives(ArchiveHandle src_archive_handle, ArchiveBackend* src_archive = GetArchive(src_archive_handle); ArchiveBackend* dest_archive = GetArchive(dest_archive_handle); if (src_archive == nullptr || dest_archive == nullptr) - return ERR_INVALID_ARCHIVE_HANDLE; + return FileSys::ERR_INVALID_ARCHIVE_HANDLE; if (src_archive == dest_archive) { return src_archive->RenameFile(src_path, dest_path); @@ -347,7 +338,7 @@ ResultCode RenameFileBetweenArchives(ArchiveHandle src_archive_handle, ResultCode DeleteDirectoryFromArchive(ArchiveHandle archive_handle, const FileSys::Path& path) { ArchiveBackend* archive = GetArchive(archive_handle); if (archive == nullptr) - return ERR_INVALID_ARCHIVE_HANDLE; + return FileSys::ERR_INVALID_ARCHIVE_HANDLE; return archive->DeleteDirectory(path); } @@ -356,7 +347,7 @@ ResultCode DeleteDirectoryRecursivelyFromArchive(ArchiveHandle archive_handle, const FileSys::Path& path) { ArchiveBackend* archive = GetArchive(archive_handle); if (archive == nullptr) - return ERR_INVALID_ARCHIVE_HANDLE; + return FileSys::ERR_INVALID_ARCHIVE_HANDLE; return archive->DeleteDirectoryRecursively(path); } @@ -365,7 +356,7 @@ ResultCode CreateFileInArchive(ArchiveHandle archive_handle, const FileSys::Path u64 file_size) { ArchiveBackend* archive = GetArchive(archive_handle); if (archive == nullptr) - return ERR_INVALID_ARCHIVE_HANDLE; + return FileSys::ERR_INVALID_ARCHIVE_HANDLE; return archive->CreateFile(path, file_size); } @@ -373,7 +364,7 @@ ResultCode CreateFileInArchive(ArchiveHandle archive_handle, const FileSys::Path ResultCode CreateDirectoryFromArchive(ArchiveHandle archive_handle, const FileSys::Path& path) { ArchiveBackend* archive = GetArchive(archive_handle); if (archive == nullptr) - return ERR_INVALID_ARCHIVE_HANDLE; + return FileSys::ERR_INVALID_ARCHIVE_HANDLE; return archive->CreateDirectory(path); } @@ -385,7 +376,7 @@ ResultCode RenameDirectoryBetweenArchives(ArchiveHandle src_archive_handle, ArchiveBackend* src_archive = GetArchive(src_archive_handle); ArchiveBackend* dest_archive = GetArchive(dest_archive_handle); if (src_archive == nullptr || dest_archive == nullptr) - return ERR_INVALID_ARCHIVE_HANDLE; + return FileSys::ERR_INVALID_ARCHIVE_HANDLE; if (src_archive == dest_archive) { return src_archive->RenameDirectory(src_path, dest_path); @@ -399,7 +390,7 @@ ResultVal<std::shared_ptr<Directory>> OpenDirectoryFromArchive(ArchiveHandle arc const FileSys::Path& path) { ArchiveBackend* archive = GetArchive(archive_handle); if (archive == nullptr) - return ERR_INVALID_ARCHIVE_HANDLE; + return FileSys::ERR_INVALID_ARCHIVE_HANDLE; auto backend = archive->OpenDirectory(path); if (backend.Failed()) @@ -412,7 +403,7 @@ ResultVal<std::shared_ptr<Directory>> OpenDirectoryFromArchive(ArchiveHandle arc ResultVal<u64> GetFreeBytesInArchive(ArchiveHandle archive_handle) { ArchiveBackend* archive = GetArchive(archive_handle); if (archive == nullptr) - return ERR_INVALID_ARCHIVE_HANDLE; + return FileSys::ERR_INVALID_ARCHIVE_HANDLE; return MakeResult<u64>(archive->GetFreeBytes()); } diff --git a/src/core/hle/service/fs/fs_user.cpp b/src/core/hle/service/fs/fs_user.cpp index 33b290699..e53a970d3 100644 --- a/src/core/hle/service/fs/fs_user.cpp +++ b/src/core/hle/service/fs/fs_user.cpp @@ -8,6 +8,7 @@ #include "common/logging/log.h" #include "common/scope_exit.h" #include "common/string_util.h" +#include "core/file_sys/errors.h" #include "core/hle/kernel/client_session.h" #include "core/hle/result.h" #include "core/hle/service/fs/archive.h" @@ -539,9 +540,7 @@ static void FormatSaveData(Service::Interface* self) { if (archive_id != FS::ArchiveIdCode::SaveData) { LOG_ERROR(Service_FS, "tried to format an archive different than SaveData, %u", static_cast<u32>(archive_id)); - cmd_buff[1] = ResultCode(ErrorDescription::FS_InvalidPath, ErrorModule::FS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage) - .raw; + cmd_buff[1] = FileSys::ERROR_INVALID_PATH.raw; return; } @@ -802,9 +801,7 @@ static void InitializeWithSdkVersion(Service::Interface* self) { cmd_buff[1] = RESULT_SUCCESS.raw; } else { LOG_ERROR(Service_FS, "ProcessId Header must be 0x20"); - cmd_buff[1] = ResultCode(ErrorDescription::OS_InvalidBufferDescriptor, ErrorModule::OS, - ErrorSummary::WrongArgument, ErrorLevel::Permanent) - .raw; + cmd_buff[1] = IPC::ERR_INVALID_BUFFER_DESCRIPTOR.raw; } } diff --git a/src/core/hle/service/gsp_gpu.cpp b/src/core/hle/service/gsp_gpu.cpp index a960778a7..94f6b8a9c 100644 --- a/src/core/hle/service/gsp_gpu.cpp +++ b/src/core/hle/service/gsp_gpu.cpp @@ -8,11 +8,11 @@ #include "core/hle/kernel/event.h" #include "core/hle/kernel/shared_memory.h" #include "core/hle/result.h" +#include "core/hle/service/gsp_gpu.h" #include "core/hw/gpu.h" #include "core/hw/hw.h" #include "core/hw/lcd.h" #include "core/memory.h" -#include "gsp_gpu.h" #include "video_core/debug_utils/debug_utils.h" #include "video_core/gpu_debugger.h" @@ -25,13 +25,24 @@ namespace GSP { // Beginning address of HW regs const u32 REGS_BEGIN = 0x1EB00000; -const ResultCode ERR_GSP_REGS_OUTOFRANGE_OR_MISALIGNED( - ErrorDescription::OutofRangeOrMisalignedAddress, ErrorModule::GX, ErrorSummary::InvalidArgument, - ErrorLevel::Usage); // 0xE0E02A01 -const ResultCode ERR_GSP_REGS_MISALIGNED(ErrorDescription::MisalignedSize, ErrorModule::GX, +namespace ErrCodes { +enum { + // TODO(purpasmart): Check if this name fits its actual usage + OutofRangeOrMisalignedAddress = 513, + FirstInitialization = 519, +}; +} + +constexpr ResultCode RESULT_FIRST_INITIALIZATION(ErrCodes::FirstInitialization, ErrorModule::GX, + ErrorSummary::Success, ErrorLevel::Success); +constexpr ResultCode ERR_REGS_OUTOFRANGE_OR_MISALIGNED(ErrCodes::OutofRangeOrMisalignedAddress, + ErrorModule::GX, + ErrorSummary::InvalidArgument, + ErrorLevel::Usage); // 0xE0E02A01 +constexpr ResultCode ERR_REGS_MISALIGNED(ErrorDescription::MisalignedSize, ErrorModule::GX, ErrorSummary::InvalidArgument, ErrorLevel::Usage); // 0xE0E02BF2 -const ResultCode ERR_GSP_REGS_INVALID_SIZE(ErrorDescription::InvalidSize, ErrorModule::GX, +constexpr ResultCode ERR_REGS_INVALID_SIZE(ErrorDescription::InvalidSize, ErrorModule::GX, ErrorSummary::InvalidArgument, ErrorLevel::Usage); // 0xE0E02BEC @@ -93,11 +104,11 @@ static ResultCode WriteHWRegs(u32 base_address, u32 size_in_bytes, VAddr data_va LOG_ERROR(Service_GSP, "Write address was out of range or misaligned! (address=0x%08x, size=0x%08x)", base_address, size_in_bytes); - return ERR_GSP_REGS_OUTOFRANGE_OR_MISALIGNED; + return ERR_REGS_OUTOFRANGE_OR_MISALIGNED; } else if (size_in_bytes <= max_size_in_bytes) { if (size_in_bytes & 3) { LOG_ERROR(Service_GSP, "Misaligned size 0x%08x", size_in_bytes); - return ERR_GSP_REGS_MISALIGNED; + return ERR_REGS_MISALIGNED; } else { while (size_in_bytes > 0) { WriteSingleHWReg(base_address, Memory::Read32(data_vaddr)); @@ -111,7 +122,7 @@ static ResultCode WriteHWRegs(u32 base_address, u32 size_in_bytes, VAddr data_va } else { LOG_ERROR(Service_GSP, "Out of range size 0x%08x", size_in_bytes); - return ERR_GSP_REGS_INVALID_SIZE; + return ERR_REGS_INVALID_SIZE; } } @@ -134,11 +145,11 @@ static ResultCode WriteHWRegsWithMask(u32 base_address, u32 size_in_bytes, VAddr LOG_ERROR(Service_GSP, "Write address was out of range or misaligned! (address=0x%08x, size=0x%08x)", base_address, size_in_bytes); - return ERR_GSP_REGS_OUTOFRANGE_OR_MISALIGNED; + return ERR_REGS_OUTOFRANGE_OR_MISALIGNED; } else if (size_in_bytes <= max_size_in_bytes) { if (size_in_bytes & 3) { LOG_ERROR(Service_GSP, "Misaligned size 0x%08x", size_in_bytes); - return ERR_GSP_REGS_MISALIGNED; + return ERR_REGS_MISALIGNED; } else { while (size_in_bytes > 0) { const u32 reg_address = base_address + REGS_BEGIN; @@ -164,7 +175,7 @@ static ResultCode WriteHWRegsWithMask(u32 base_address, u32 size_in_bytes, VAddr } else { LOG_ERROR(Service_GSP, "Out of range size 0x%08x", size_in_bytes); - return ERR_GSP_REGS_INVALID_SIZE; + return ERR_REGS_INVALID_SIZE; } } @@ -372,9 +383,7 @@ static void RegisterInterruptRelayQueue(Interface* self) { if (first_initialization) { // This specific code is required for a successful initialization, rather than 0 first_initialization = false; - cmd_buff[1] = ResultCode(ErrorDescription::GPU_FirstInitialization, ErrorModule::GX, - ErrorSummary::Success, ErrorLevel::Success) - .raw; + cmd_buff[1] = RESULT_FIRST_INITIALIZATION.raw; } else { cmd_buff[1] = RESULT_SUCCESS.raw; } diff --git a/src/core/hle/service/ir/ir_user.cpp b/src/core/hle/service/ir/ir_user.cpp index 226af0083..369115f09 100644 --- a/src/core/hle/service/ir/ir_user.cpp +++ b/src/core/hle/service/ir/ir_user.cpp @@ -267,8 +267,7 @@ static void InitializeIrNopShared(Interface* self) { shared_memory = Kernel::g_handle_table.Get<Kernel::SharedMemory>(handle); if (!shared_memory) { LOG_CRITICAL(Service_IR, "invalid shared memory handle 0x%08X", handle); - rb.Push(ResultCode(ErrorDescription::InvalidHandle, ErrorModule::OS, - ErrorSummary::WrongArgument, ErrorLevel::Permanent)); + rb.Push(IPC::ERR_INVALID_HANDLE); return; } shared_memory->name = "IR_USER: shared memory"; diff --git a/src/core/hle/service/ptm/ptm.cpp b/src/core/hle/service/ptm/ptm.cpp index 319e8c946..39382ef09 100644 --- a/src/core/hle/service/ptm/ptm.cpp +++ b/src/core/hle/service/ptm/ptm.cpp @@ -3,6 +3,7 @@ // Refer to the license.txt file included. #include "common/logging/log.h" +#include "core/file_sys/errors.h" #include "core/file_sys/file_backend.h" #include "core/hle/service/fs/archive.h" #include "core/hle/service/ptm/ptm.h" @@ -134,7 +135,7 @@ void Init() { auto archive_result = Service::FS::OpenArchive(Service::FS::ArchiveIdCode::SharedExtSaveData, archive_path); // If the archive didn't exist, create the files inside - if (archive_result.Code().description == ErrorDescription::FS_NotFormatted) { + if (archive_result.Code() == FileSys::ERR_NOT_FORMATTED) { // Format the archive to create the directories Service::FS::FormatArchive(Service::FS::ArchiveIdCode::SharedExtSaveData, FileSys::ArchiveFormatInfo(), archive_path); diff --git a/src/core/hle/service/service.h b/src/core/hle/service/service.h index e6a5f1417..ffabc24a4 100644 --- a/src/core/hle/service/service.h +++ b/src/core/hle/service/service.h @@ -12,7 +12,6 @@ #include "core/hle/ipc.h" #include "core/hle/ipc_helpers.h" #include "core/hle/kernel/client_port.h" -#include "core/hle/kernel/thread.h" #include "core/hle/result.h" #include "core/memory.h" diff --git a/src/core/hle/service/srv.cpp b/src/core/hle/service/srv.cpp index 3bd787147..130c9d25e 100644 --- a/src/core/hle/service/srv.cpp +++ b/src/core/hle/service/srv.cpp @@ -30,9 +30,7 @@ static void RegisterClient(Interface* self) { if (cmd_buff[1] != IPC::CallingPidDesc()) { cmd_buff[0] = IPC::MakeHeader(0x0, 0x1, 0); // 0x40 - cmd_buff[1] = ResultCode(ErrorDescription::OS_InvalidBufferDescriptor, ErrorModule::OS, - ErrorSummary::WrongArgument, ErrorLevel::Permanent) - .raw; + cmd_buff[1] = IPC::ERR_INVALID_BUFFER_DESCRIPTOR.raw; return; } cmd_buff[0] = IPC::MakeHeader(0x1, 0x1, 0); // 0x10040 diff --git a/src/core/hle/svc.cpp b/src/core/hle/svc.cpp index 8538cfc9d..e68b9f16a 100644 --- a/src/core/hle/svc.cpp +++ b/src/core/hle/svc.cpp @@ -2,6 +2,7 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include <algorithm> #include <cinttypes> #include <map> #include "common/logging/log.h" @@ -14,7 +15,9 @@ #include "core/hle/kernel/address_arbiter.h" #include "core/hle/kernel/client_port.h" #include "core/hle/kernel/client_session.h" +#include "core/hle/kernel/errors.h" #include "core/hle/kernel/event.h" +#include "core/hle/kernel/handle_table.h" #include "core/hle/kernel/memory.h" #include "core/hle/kernel/mutex.h" #include "core/hle/kernel/process.h" @@ -26,6 +29,7 @@ #include "core/hle/kernel/thread.h" #include "core/hle/kernel/timer.h" #include "core/hle/kernel/vm_manager.h" +#include "core/hle/kernel/wait_object.h" #include "core/hle/result.h" #include "core/hle/service/service.h" @@ -37,25 +41,6 @@ using Kernel::ERR_INVALID_HANDLE; namespace SVC { -const ResultCode ERR_NOT_FOUND(ErrorDescription::NotFound, ErrorModule::Kernel, - ErrorSummary::NotFound, ErrorLevel::Permanent); // 0xD88007FA -const ResultCode ERR_PORT_NAME_TOO_LONG(ErrorDescription(30), ErrorModule::OS, - ErrorSummary::InvalidArgument, - ErrorLevel::Usage); // 0xE0E0181E - -const ResultCode ERR_SYNC_TIMEOUT(ErrorDescription::Timeout, ErrorModule::OS, - ErrorSummary::StatusChanged, ErrorLevel::Info); - -const ResultCode ERR_MISALIGNED_ADDRESS{// 0xE0E01BF1 - ErrorDescription::MisalignedAddress, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage}; -const ResultCode ERR_MISALIGNED_SIZE{// 0xE0E01BF2 - ErrorDescription::MisalignedSize, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage}; -const ResultCode ERR_INVALID_COMBINATION{// 0xE0E01BEE - ErrorDescription::InvalidCombination, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage}; - enum ControlMemoryOperation { MEMOP_FREE = 1, MEMOP_RESERVE = 2, // This operation seems to be unsupported in the kernel @@ -195,8 +180,7 @@ static ResultCode MapMemoryBlock(Kernel::Handle handle, u32 addr, u32 permission LOG_ERROR(Kernel_SVC, "unknown permissions=0x%08X", permissions); } - return ResultCode(ErrorDescription::InvalidCombination, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return Kernel::ERR_INVALID_COMBINATION; } static ResultCode UnmapMemoryBlock(Kernel::Handle handle, u32 addr) { @@ -216,16 +200,16 @@ static ResultCode UnmapMemoryBlock(Kernel::Handle handle, u32 addr) { /// Connect to an OS service given the port name, returns the handle to the port to out static ResultCode ConnectToPort(Kernel::Handle* out_handle, const char* port_name) { if (port_name == nullptr) - return ERR_NOT_FOUND; + return Kernel::ERR_NOT_FOUND; if (std::strlen(port_name) > 11) - return ERR_PORT_NAME_TOO_LONG; + return Kernel::ERR_PORT_NAME_TOO_LONG; LOG_TRACE(Kernel_SVC, "called port_name=%s", port_name); auto it = Service::g_kernel_named_ports.find(port_name); if (it == Service::g_kernel_named_ports.end()) { LOG_WARNING(Kernel_SVC, "tried to connect to unknown port: %s", port_name); - return ERR_NOT_FOUND; + return Kernel::ERR_NOT_FOUND; } auto client_port = it->second; @@ -263,7 +247,7 @@ static ResultCode CloseHandle(Kernel::Handle handle) { /// Wait for a handle to synchronize, timeout after the specified nanoseconds static ResultCode WaitSynchronization1(Kernel::Handle handle, s64 nano_seconds) { - auto object = Kernel::g_handle_table.GetWaitObject(handle); + auto object = Kernel::g_handle_table.Get<Kernel::WaitObject>(handle); Kernel::Thread* thread = Kernel::GetCurrentThread(); if (object == nullptr) @@ -275,7 +259,7 @@ static ResultCode WaitSynchronization1(Kernel::Handle handle, s64 nano_seconds) if (object->ShouldWait(thread)) { if (nano_seconds == 0) - return ERR_SYNC_TIMEOUT; + return Kernel::RESULT_TIMEOUT; thread->wait_objects = {object}; object->AddWaitingThread(thread); @@ -289,7 +273,7 @@ static ResultCode WaitSynchronization1(Kernel::Handle handle, s64 nano_seconds) // Note: The output of this SVC will be set to RESULT_SUCCESS if the thread // resumes due to a signal in its wait objects. // Otherwise we retain the default value of timeout. - return ERR_SYNC_TIMEOUT; + return Kernel::RESULT_TIMEOUT; } object->Acquire(thread); @@ -304,8 +288,7 @@ static ResultCode WaitSynchronizationN(s32* out, Kernel::Handle* handles, s32 ha // Check if 'handles' is invalid if (handles == nullptr) - return ResultCode(ErrorDescription::InvalidPointer, ErrorModule::Kernel, - ErrorSummary::InvalidArgument, ErrorLevel::Permanent); + return Kernel::ERR_INVALID_POINTER; // NOTE: on real hardware, there is no nullptr check for 'out' (tested with firmware 4.4). If // this happens, the running application will crash. @@ -313,14 +296,13 @@ static ResultCode WaitSynchronizationN(s32* out, Kernel::Handle* handles, s32 ha // Check if 'handle_count' is invalid if (handle_count < 0) - return ResultCode(ErrorDescription::OutOfRange, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return Kernel::ERR_OUT_OF_RANGE; using ObjectPtr = Kernel::SharedPtr<Kernel::WaitObject>; std::vector<ObjectPtr> objects(handle_count); for (int i = 0; i < handle_count; ++i) { - auto object = Kernel::g_handle_table.GetWaitObject(handles[i]); + auto object = Kernel::g_handle_table.Get<Kernel::WaitObject>(handles[i]); if (object == nullptr) return ERR_INVALID_HANDLE; objects[i] = object; @@ -344,7 +326,7 @@ static ResultCode WaitSynchronizationN(s32* out, Kernel::Handle* handles, s32 ha // If a timeout value of 0 was provided, just return the Timeout error code instead of // suspending the thread. if (nano_seconds == 0) - return ERR_SYNC_TIMEOUT; + return Kernel::RESULT_TIMEOUT; // Put the thread to sleep thread->status = THREADSTATUS_WAIT_SYNCH_ALL; @@ -365,7 +347,7 @@ static ResultCode WaitSynchronizationN(s32* out, Kernel::Handle* handles, s32 ha *out = -1; // Note: The output of this SVC will be set to RESULT_SUCCESS if the thread resumes due to // a signal in one of its wait objects. - return ERR_SYNC_TIMEOUT; + return Kernel::RESULT_TIMEOUT; } else { // Find the first object that is acquirable in the provided list of objects auto itr = std::find_if(objects.begin(), objects.end(), [thread](const ObjectPtr& object) { @@ -385,7 +367,7 @@ static ResultCode WaitSynchronizationN(s32* out, Kernel::Handle* handles, s32 ha // If a timeout value of 0 was provided, just return the Timeout error code instead of // suspending the thread. if (nano_seconds == 0) - return ERR_SYNC_TIMEOUT; + return Kernel::RESULT_TIMEOUT; // Put the thread to sleep thread->status = THREADSTATUS_WAIT_SYNCH_ANY; @@ -411,7 +393,7 @@ static ResultCode WaitSynchronizationN(s32* out, Kernel::Handle* handles, s32 ha // Otherwise we retain the default value of timeout, and -1 in the out parameter thread->wait_set_output = true; *out = -1; - return ERR_SYNC_TIMEOUT; + return Kernel::RESULT_TIMEOUT; } } @@ -520,22 +502,20 @@ static ResultCode GetResourceLimitLimitValues(s64* values, Kernel::Handle resour } /// Creates a new thread -static ResultCode CreateThread(Kernel::Handle* out_handle, s32 priority, u32 entry_point, u32 arg, +static ResultCode CreateThread(Kernel::Handle* out_handle, u32 priority, u32 entry_point, u32 arg, u32 stack_top, s32 processor_id) { using Kernel::Thread; std::string name = Common::StringFromFormat("unknown-%08" PRIX32, entry_point); if (priority > THREADPRIO_LOWEST) { - return ResultCode(ErrorDescription::OutOfRange, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return Kernel::ERR_OUT_OF_RANGE; } using Kernel::ResourceLimit; Kernel::SharedPtr<ResourceLimit>& resource_limit = Kernel::g_current_process->resource_limit; if (resource_limit->GetMaxResourceValue(Kernel::ResourceTypes::PRIORITY) > priority) { - return ResultCode(ErrorDescription::NotAuthorized, ErrorModule::OS, - ErrorSummary::WrongArgument, ErrorLevel::Permanent); + return Kernel::ERR_NOT_AUTHORIZED; } switch (processor_id) { @@ -605,8 +585,7 @@ static ResultCode GetThreadPriority(s32* priority, Kernel::Handle handle) { /// Sets the priority for the specified thread static ResultCode SetThreadPriority(Kernel::Handle handle, s32 priority) { if (priority > THREADPRIO_LOWEST) { - return ResultCode(ErrorDescription::OutOfRange, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return Kernel::ERR_OUT_OF_RANGE; } SharedPtr<Kernel::Thread> thread = Kernel::g_handle_table.Get<Kernel::Thread>(handle); @@ -618,8 +597,7 @@ static ResultCode SetThreadPriority(Kernel::Handle handle, s32 priority) { // the one from the thread owner's resource limit. Kernel::SharedPtr<ResourceLimit>& resource_limit = Kernel::g_current_process->resource_limit; if (resource_limit->GetMaxResourceValue(Kernel::ResourceTypes::PRIORITY) > priority) { - return ResultCode(ErrorDescription::NotAuthorized, ErrorModule::OS, - ErrorSummary::WrongArgument, ErrorLevel::Permanent); + return Kernel::ERR_NOT_AUTHORIZED; } thread->SetPriority(priority); @@ -743,8 +721,7 @@ static ResultCode QueryProcessMemory(MemoryInfo* memory_info, PageInfo* page_inf auto vma = process->vm_manager.FindVMA(addr); if (vma == Kernel::g_current_process->vm_manager.vma_map.end()) - return ResultCode(ErrorDescription::InvalidAddress, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return Kernel::ERR_INVALID_ADDRESS; memory_info->base_address = vma->second.base; memory_info->permission = static_cast<u32>(vma->second.permissions); @@ -842,8 +819,7 @@ static ResultCode SetTimer(Kernel::Handle handle, s64 initial, s64 interval) { LOG_TRACE(Kernel_SVC, "called timer=0x%08X", handle); if (initial < 0 || interval < 0) { - return ResultCode(ErrorDescription::OutOfRange, ErrorModule::Kernel, - ErrorSummary::InvalidArgument, ErrorLevel::Permanent); + return Kernel::ERR_OUT_OF_RANGE_KERNEL; } SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle); @@ -902,8 +878,7 @@ static ResultCode CreateMemoryBlock(Kernel::Handle* out_handle, u32 addr, u32 si using Kernel::SharedMemory; if (size % Memory::PAGE_SIZE != 0) - return ResultCode(ErrorDescription::MisalignedSize, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return Kernel::ERR_MISALIGNED_SIZE; SharedPtr<SharedMemory> shared_memory = nullptr; @@ -924,16 +899,14 @@ static ResultCode CreateMemoryBlock(Kernel::Handle* out_handle, u32 addr, u32 si if (!VerifyPermissions(static_cast<MemoryPermission>(my_permission)) || !VerifyPermissions(static_cast<MemoryPermission>(other_permission))) - return ResultCode(ErrorDescription::InvalidCombination, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return Kernel::ERR_INVALID_COMBINATION; // TODO(Subv): Processes with memory type APPLICATION are not allowed // to create memory blocks with addr = 0, any attempts to do so // should return error 0xD92007EA. if ((addr < Memory::PROCESS_IMAGE_VADDR || addr + size > Memory::SHARED_MEMORY_VADDR_END) && addr != 0) { - return ResultCode(ErrorDescription::InvalidAddress, ErrorModule::OS, - ErrorSummary::InvalidArgument, ErrorLevel::Usage); + return Kernel::ERR_INVALID_ADDRESS; } // When trying to create a memory block with address = 0, @@ -1035,7 +1008,7 @@ static ResultCode GetProcessInfo(s64* out, Kernel::Handle process_handle, u32 ty *out = process->heap_used + process->linear_heap_used + process->misc_memory_used; if (*out % Memory::PAGE_SIZE != 0) { LOG_ERROR(Kernel_SVC, "called, memory size not page-aligned"); - return ERR_MISALIGNED_SIZE; + return Kernel::ERR_MISALIGNED_SIZE; } break; case 1: @@ -1051,19 +1024,15 @@ static ResultCode GetProcessInfo(s64* out, Kernel::Handle process_handle, u32 ty case 20: *out = Memory::FCRAM_PADDR - process->GetLinearHeapBase(); break; + case 21: + case 22: + case 23: + // These return a different error value than higher invalid values + LOG_ERROR(Kernel_SVC, "unknown GetProcessInfo type=%u", type); + return Kernel::ERR_NOT_IMPLEMENTED; default: LOG_ERROR(Kernel_SVC, "unknown GetProcessInfo type=%u", type); - - if (type >= 21 && type <= 23) { - return ResultCode( // 0xE0E01BF4 - ErrorDescription::NotImplemented, ErrorModule::OS, ErrorSummary::InvalidArgument, - ErrorLevel::Usage); - } else { - return ResultCode( // 0xD8E007ED - ErrorDescription::InvalidEnumValue, ErrorModule::Kernel, - ErrorSummary::InvalidArgument, ErrorLevel::Permanent); - } - break; + return Kernel::ERR_INVALID_ENUM_VALUE; } return RESULT_SUCCESS; diff --git a/src/core/loader/ncch.cpp b/src/core/loader/ncch.cpp index 1a4e3efa8..beeb13ffa 100644 --- a/src/core/loader/ncch.cpp +++ b/src/core/loader/ncch.cpp @@ -9,6 +9,7 @@ #include "common/logging/log.h" #include "common/string_util.h" #include "common/swap.h" +#include "core/core.h" #include "core/file_sys/archive_selfncch.h" #include "core/hle/kernel/process.h" #include "core/hle/kernel/resource_limit.h" @@ -339,6 +340,8 @@ ResultStatus AppLoader_NCCH::Load() { LOG_INFO(Loader, "Program ID: %016" PRIX64, ncch_header.program_id); + Core::Telemetry().AddField(Telemetry::FieldType::Session, "ProgramId", ncch_header.program_id); + is_loaded = true; // Set state to loaded result = LoadExec(); // Load the executable into memory for booting diff --git a/src/core/settings.cpp b/src/core/settings.cpp index d2e7c6b97..d4f0429d1 100644 --- a/src/core/settings.cpp +++ b/src/core/settings.cpp @@ -6,7 +6,7 @@ #include "core/gdbstub/gdbstub.h" #include "core/hle/service/hid/hid.h" #include "core/hle/service/ir/ir.h" -#include "settings.h" +#include "core/settings.h" #include "video_core/video_core.h" #include "core/frontend/emu_window.h" diff --git a/src/core/telemetry_session.cpp b/src/core/telemetry_session.cpp new file mode 100644 index 000000000..ddc8b262e --- /dev/null +++ b/src/core/telemetry_session.cpp @@ -0,0 +1,42 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include <cstring> + +#include "common/scm_rev.h" +#include "core/telemetry_session.h" + +namespace Core { + +TelemetrySession::TelemetrySession() { + // TODO(bunnei): Replace with a backend that logs to our web service + backend = std::make_unique<Telemetry::NullVisitor>(); + + // Log one-time session start information + const auto duration{std::chrono::steady_clock::now().time_since_epoch()}; + const auto start_time{std::chrono::duration_cast<std::chrono::microseconds>(duration).count()}; + AddField(Telemetry::FieldType::Session, "StartTime", start_time); + + // Log one-time application information + const bool is_git_dirty{std::strstr(Common::g_scm_desc, "dirty") != nullptr}; + AddField(Telemetry::FieldType::App, "GitIsDirty", is_git_dirty); + AddField(Telemetry::FieldType::App, "GitBranch", Common::g_scm_branch); + AddField(Telemetry::FieldType::App, "GitRevision", Common::g_scm_rev); +} + +TelemetrySession::~TelemetrySession() { + // Log one-time session end information + const auto duration{std::chrono::steady_clock::now().time_since_epoch()}; + const auto end_time{std::chrono::duration_cast<std::chrono::microseconds>(duration).count()}; + AddField(Telemetry::FieldType::Session, "EndTime", end_time); + + // Complete the session, submitting to web service if necessary + // This is just a placeholder to wrap up the session once the core completes and this is + // destroyed. This will be moved elsewhere once we are actually doing real I/O with the service. + field_collection.Accept(*backend); + backend->Complete(); + backend = nullptr; +} + +} // namespace Core diff --git a/src/core/telemetry_session.h b/src/core/telemetry_session.h new file mode 100644 index 000000000..cf53835c3 --- /dev/null +++ b/src/core/telemetry_session.h @@ -0,0 +1,38 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include <memory> +#include "common/telemetry.h" + +namespace Core { + +/** + * Instruments telemetry for this emulation session. Creates a new set of telemetry fields on each + * session, logging any one-time fields. Interfaces with the telemetry backend used for submitting + * data to the web service. Submits session data on close. + */ +class TelemetrySession : NonCopyable { +public: + TelemetrySession(); + ~TelemetrySession(); + + /** + * Wrapper around the Telemetry::FieldCollection::AddField method. + * @param type Type of the field to add. + * @param name Name of the field to add. + * @param value Value for the field to add. + */ + template <typename T> + void AddField(Telemetry::FieldType type, const char* name, T value) { + field_collection.AddField(type, name, std::move(value)); + } + +private: + Telemetry::FieldCollection field_collection; ///< Tracks all added fields for the session + std::unique_ptr<Telemetry::VisitorInterface> backend; ///< Backend interface that logs fields +}; + +} // namespace Core diff --git a/src/core/tracer/recorder.cpp b/src/core/tracer/recorder.cpp index 276a5b288..55b3b5efc 100644 --- a/src/core/tracer/recorder.cpp +++ b/src/core/tracer/recorder.cpp @@ -6,7 +6,7 @@ #include "common/assert.h" #include "common/file_util.h" #include "common/logging/log.h" -#include "recorder.h" +#include "core/tracer/recorder.h" namespace CiTrace { diff --git a/src/core/tracer/recorder.h b/src/core/tracer/recorder.h index aea363b95..39e6ec4fd 100644 --- a/src/core/tracer/recorder.h +++ b/src/core/tracer/recorder.h @@ -8,8 +8,8 @@ #include <unordered_map> #include <vector> #include <boost/crc.hpp> -#include "citrace.h" #include "common/common_types.h" +#include "core/tracer/citrace.h" namespace CiTrace { |