early-access version 1670

main
pineappleEA 2021-05-11 02:22:43 +02:00
parent 1148b01aac
commit 0301e95e45
23 changed files with 452 additions and 240 deletions

View File

@ -1,7 +1,7 @@
yuzu emulator early access yuzu emulator early access
============= =============
This is the source code for early-access 1669. This is the source code for early-access 1670.
## Legal Notice ## Legal Notice

View File

@ -14,8 +14,8 @@ namespace fs = std::filesystem;
// File Operations // File Operations
bool NewFile(const fs::path& path, u64 size) { bool NewFile(const fs::path& path, u64 size) {
if (path.empty()) { if (!ValidatePath(path)) {
LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path)); LOG_ERROR(Common_Filesystem, "Input path is not valid, path={}", PathToUTF8String(path));
return false; return false;
} }
@ -52,8 +52,8 @@ bool NewFile(const fs::path& path, u64 size) {
} }
bool RemoveFile(const fs::path& path) { bool RemoveFile(const fs::path& path) {
if (path.empty()) { if (!ValidatePath(path)) {
LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path)); LOG_ERROR(Common_Filesystem, "Input path is not valid, path={}", PathToUTF8String(path));
return false; return false;
} }
@ -86,8 +86,9 @@ bool RemoveFile(const fs::path& path) {
} }
bool RenameFile(const fs::path& old_path, const fs::path& new_path) { bool RenameFile(const fs::path& old_path, const fs::path& new_path) {
if (old_path.empty() || new_path.empty()) { if (!ValidatePath(old_path) || !ValidatePath(new_path)) {
LOG_ERROR(Common_Filesystem, "One or both input path(s) is empty, old_path={}, new_path={}", LOG_ERROR(Common_Filesystem,
"One or both input path(s) is not valid, old_path={}, new_path={}",
PathToUTF8String(old_path), PathToUTF8String(new_path)); PathToUTF8String(old_path), PathToUTF8String(new_path));
return false; return false;
} }
@ -129,8 +130,8 @@ bool RenameFile(const fs::path& old_path, const fs::path& new_path) {
std::shared_ptr<IOFile> FileOpen(const fs::path& path, FileAccessMode mode, FileType type, std::shared_ptr<IOFile> FileOpen(const fs::path& path, FileAccessMode mode, FileType type,
FileShareFlag flag) { FileShareFlag flag) {
if (path.empty()) { if (!ValidatePath(path)) {
LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path)); LOG_ERROR(Common_Filesystem, "Input path is not valid, path={}", PathToUTF8String(path));
return nullptr; return nullptr;
} }
@ -162,8 +163,8 @@ std::shared_ptr<IOFile> FileOpen(const fs::path& path, FileAccessMode mode, File
// Directory Operations // Directory Operations
bool CreateDir(const fs::path& path) { bool CreateDir(const fs::path& path) {
if (path.empty()) { if (!ValidatePath(path)) {
LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path)); LOG_ERROR(Common_Filesystem, "Input path is not valid, path={}", PathToUTF8String(path));
return false; return false;
} }
@ -196,8 +197,8 @@ bool CreateDir(const fs::path& path) {
} }
bool CreateDirs(const fs::path& path) { bool CreateDirs(const fs::path& path) {
if (path.empty()) { if (!ValidatePath(path)) {
LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path)); LOG_ERROR(Common_Filesystem, "Input path is not valid, path={}", PathToUTF8String(path));
return false; return false;
} }
@ -232,8 +233,8 @@ bool CreateParentDirs(const fs::path& path) {
} }
bool RemoveDir(const fs::path& path) { bool RemoveDir(const fs::path& path) {
if (path.empty()) { if (!ValidatePath(path)) {
LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path)); LOG_ERROR(Common_Filesystem, "Input path is not valid, path={}", PathToUTF8String(path));
return false; return false;
} }
@ -266,8 +267,8 @@ bool RemoveDir(const fs::path& path) {
} }
bool RemoveDirRecursively(const fs::path& path) { bool RemoveDirRecursively(const fs::path& path) {
if (path.empty()) { if (!ValidatePath(path)) {
LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path)); LOG_ERROR(Common_Filesystem, "Input path is not valid, path={}", PathToUTF8String(path));
return false; return false;
} }
@ -301,8 +302,8 @@ bool RemoveDirRecursively(const fs::path& path) {
} }
bool RemoveDirContentsRecursively(const fs::path& path) { bool RemoveDirContentsRecursively(const fs::path& path) {
if (path.empty()) { if (!ValidatePath(path)) {
LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path)); LOG_ERROR(Common_Filesystem, "Input path is not valid, path={}", PathToUTF8String(path));
return false; return false;
} }
@ -353,8 +354,9 @@ bool RemoveDirContentsRecursively(const fs::path& path) {
} }
bool RenameDir(const fs::path& old_path, const fs::path& new_path) { bool RenameDir(const fs::path& old_path, const fs::path& new_path) {
if (old_path.empty() || new_path.empty()) { if (!ValidatePath(old_path) || !ValidatePath(new_path)) {
LOG_ERROR(Common_Filesystem, "One or both input path(s) is empty, old_path={}, new_path={}", LOG_ERROR(Common_Filesystem,
"One or both input path(s) is not valid, old_path={}, new_path={}",
PathToUTF8String(old_path), PathToUTF8String(new_path)); PathToUTF8String(old_path), PathToUTF8String(new_path));
return false; return false;
} }
@ -396,8 +398,8 @@ bool RenameDir(const fs::path& old_path, const fs::path& new_path) {
void IterateDirEntries(const std::filesystem::path& path, const DirEntryCallable& callback, void IterateDirEntries(const std::filesystem::path& path, const DirEntryCallable& callback,
DirEntryFilter filter) { DirEntryFilter filter) {
if (path.empty()) { if (!ValidatePath(path)) {
LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path)); LOG_ERROR(Common_Filesystem, "Input path is not valid, path={}", PathToUTF8String(path));
return; return;
} }
@ -452,8 +454,8 @@ void IterateDirEntries(const std::filesystem::path& path, const DirEntryCallable
void IterateDirEntriesRecursively(const std::filesystem::path& path, void IterateDirEntriesRecursively(const std::filesystem::path& path,
const DirEntryCallable& callback, DirEntryFilter filter) { const DirEntryCallable& callback, DirEntryFilter filter) {
if (path.empty()) { if (!ValidatePath(path)) {
LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path)); LOG_ERROR(Common_Filesystem, "Input path is not valid, path={}", PathToUTF8String(path));
return; return;
} }

View File

@ -20,7 +20,7 @@ class IOFile;
* Creates a new file at path with a specified size. * Creates a new file at path with a specified size.
* *
* Failures occur when: * Failures occur when:
* - Input path is empty * - Input path is not valid
* - The input path's parent directory does not exist * - The input path's parent directory does not exist
* - Filesystem object at path exists * - Filesystem object at path exists
* - Filesystem at path is read only * - Filesystem at path is read only
@ -50,7 +50,7 @@ template <typename Path>
* Removes a file at path. * Removes a file at path.
* *
* Failures occur when: * Failures occur when:
* - Input path is empty * - Input path is not valid
* - Filesystem object at path is not a file * - Filesystem object at path is not a file
* - Filesystem at path is read only * - Filesystem at path is read only
* *
@ -78,7 +78,7 @@ template <typename Path>
* Renames a file from old_path to new_path. * Renames a file from old_path to new_path.
* *
* Failures occur when: * Failures occur when:
* - One or both input path(s) is empty * - One or both input path(s) is not valid
* - Filesystem object at old_path does not exist * - Filesystem object at old_path does not exist
* - Filesystem object at old_path is not a file * - Filesystem object at old_path is not a file
* - Filesystem object at new_path exists * - Filesystem object at new_path exists
@ -117,7 +117,7 @@ template <typename Path1, typename Path2>
* These behaviors are documented in each enum value of FileAccessMode. * These behaviors are documented in each enum value of FileAccessMode.
* *
* Failures occur when: * Failures occur when:
* - Input path is empty * - Input path is not valid
* - Filesystem object at path is not a file * - Filesystem object at path is not a file
* - The file is not opened * - The file is not opened
* *
@ -158,7 +158,7 @@ template <typename Path>
* If you intend to create the parent directory of a file, use CreateParentDir instead. * If you intend to create the parent directory of a file, use CreateParentDir instead.
* *
* Failures occur when: * Failures occur when:
* - Input path is empty * - Input path is not valid
* - The input path's parent directory does not exist * - The input path's parent directory does not exist
* - Filesystem at path is read only * - Filesystem at path is read only
* *
@ -190,7 +190,7 @@ template <typename Path>
* Unlike CreateDir, this creates all of input path's parent directories if they do not exist. * Unlike CreateDir, this creates all of input path's parent directories if they do not exist.
* *
* Failures occur when: * Failures occur when:
* - Input path is empty * - Input path is not valid
* - Filesystem at path is read only * - Filesystem at path is read only
* *
* @param path Filesystem path * @param path Filesystem path
@ -265,7 +265,7 @@ template <typename Path>
* Removes a directory at path. * Removes a directory at path.
* *
* Failures occur when: * Failures occur when:
* - Input path is empty * - Input path is not valid
* - Filesystem object at path is not a directory * - Filesystem object at path is not a directory
* - The given directory is not empty * - The given directory is not empty
* - Filesystem at path is read only * - Filesystem at path is read only
@ -294,7 +294,7 @@ template <typename Path>
* Removes all the contents within the given directory and removes the directory itself. * Removes all the contents within the given directory and removes the directory itself.
* *
* Failures occur when: * Failures occur when:
* - Input path is empty * - Input path is not valid
* - Filesystem object at path is not a directory * - Filesystem object at path is not a directory
* - Filesystem at path is read only * - Filesystem at path is read only
* *
@ -322,7 +322,7 @@ template <typename Path>
* Removes all the contents within the given directory without removing the directory itself. * Removes all the contents within the given directory without removing the directory itself.
* *
* Failures occur when: * Failures occur when:
* - Input path is empty * - Input path is not valid
* - Filesystem object at path is not a directory * - Filesystem object at path is not a directory
* - Filesystem at path is read only * - Filesystem at path is read only
* *
@ -350,7 +350,7 @@ template <typename Path>
* Renames a directory from old_path to new_path. * Renames a directory from old_path to new_path.
* *
* Failures occur when: * Failures occur when:
* - One or both input path(s) is empty * - One or both input path(s) is not valid
* - Filesystem object at old_path does not exist * - Filesystem object at old_path does not exist
* - Filesystem object at old_path is not a directory * - Filesystem object at old_path is not a directory
* - Filesystem object at new_path exists * - Filesystem object at new_path exists
@ -392,7 +392,7 @@ template <typename Path1, typename Path2>
* If the callback returns false or there is an error, the iteration is immediately halted. * If the callback returns false or there is an error, the iteration is immediately halted.
* *
* Failures occur when: * Failures occur when:
* - Input path is empty * - Input path is not valid
* - Filesystem object at path is not a directory * - Filesystem object at path is not a directory
* *
* @param path Filesystem path * @param path Filesystem path
@ -425,7 +425,7 @@ void IterateDirEntries(const Path& path, const DirEntryCallable& callback,
* If the callback returns false or there is an error, the iteration is immediately halted. * If the callback returns false or there is an error, the iteration is immediately halted.
* *
* Failures occur when: * Failures occur when:
* - Input path is empty * - Input path is not valid
* - Filesystem object at path does not exist * - Filesystem object at path does not exist
* - Filesystem object at path is not a directory * - Filesystem object at path is not a directory
* *

View File

@ -4,10 +4,6 @@
#pragma once #pragma once
#ifndef MAX_PATH
#define MAX_PATH 260
#endif
// yuzu data directories // yuzu data directories
#define YUZU_DIR "yuzu" #define YUZU_DIR "yuzu"

View File

@ -37,10 +37,26 @@
#endif #endif
#endif #endif
#ifndef MAX_PATH
#ifdef _WIN32
// This is the maximum number of UTF-16 code units permissible in Windows file paths
#define MAX_PATH 260
#else
// This is the maximum number of UTF-8 code units permissible in all other OSes' file paths
#define MAX_PATH 1024
#endif
#endif
namespace Common::FS { namespace Common::FS {
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace {
constexpr std::array<char8_t, 7> INVALID_CHARS{u':', u'*', u'?', u'"', u'<', u'>', u'|'};
}
/** /**
* The PathManagerImpl is a singleton allowing to manage the mapping of * The PathManagerImpl is a singleton allowing to manage the mapping of
* YuzuPath enums to real filesystem paths. * YuzuPath enums to real filesystem paths.
@ -129,6 +145,41 @@ std::string PathToUTF8String(const fs::path& path) {
return std::string{utf8_string.begin(), utf8_string.end()}; return std::string{utf8_string.begin(), utf8_string.end()};
} }
bool ValidatePath(const fs::path& path) {
if (path.empty()) {
LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path));
return false;
}
#ifdef _WIN32
if (path.u16string().size() >= MAX_PATH) {
LOG_ERROR(Common_Filesystem, "Input path is too long, path={}", PathToUTF8String(path));
return false;
}
#else
if (path.u8string().size() >= MAX_PATH) {
LOG_ERROR(Common_Filesystem, "Input path is too long, path={}", PathToUTF8String(path));
return false;
}
#endif
for (const auto path_char : path.relative_path().u8string()) {
for (const auto invalid_char : INVALID_CHARS) {
if (path_char == invalid_char) {
LOG_ERROR(Common_Filesystem, "Input path contains invalid characters, path={}",
PathToUTF8String(path));
return false;
}
}
}
return true;
}
fs::path ConcatPath(const fs::path& first, const fs::path& second) { fs::path ConcatPath(const fs::path& first, const fs::path& second) {
const bool second_has_dir_sep = IsDirSeparator(second.u8string().front()); const bool second_has_dir_sep = IsDirSeparator(second.u8string().front());

View File

@ -1,4 +1,4 @@
// Copyright 2020 yuzu Emulator Project // Copyright 2021 yuzu Emulator Project
// Licensed under GPLv2 or any later version // Licensed under GPLv2 or any later version
// Refer to the license.txt file included. // Refer to the license.txt file included.
@ -45,6 +45,35 @@ enum class YuzuPath {
*/ */
[[nodiscard]] std::string PathToUTF8String(const std::filesystem::path& path); [[nodiscard]] std::string PathToUTF8String(const std::filesystem::path& path);
/**
* Validates a given path.
*
* A given path is valid if it meets these conditions:
* - The path is not empty
* - The path is not too long
* - The path relative to the platform-specific root path does not contain
* any of the following characters: ':', '*', '?', '"', '<', '>', '|'
*
* @param path Filesystem path
*
* @returns True if the path is valid, false otherwise.
*/
[[nodiscard]] bool ValidatePath(const std::filesystem::path& path);
#ifdef _WIN32
template <typename Path>
[[nodiscard]] bool ValidatePath(const Path& path) {
using ValueType = typename Path::value_type;
if constexpr (IsChar<ValueType>) {
return ValidatePath(ToU8String(path));
} else {
return ValidatePath(std::filesystem::path{path});
}
}
#endif
/** /**
* Concatenates two filesystem paths together. * Concatenates two filesystem paths together.
* *

View File

@ -80,11 +80,12 @@ VirtualFile RealVfsFilesystem::OpenFile(std::string_view path_, Mode perms) {
} }
} }
if (!FS::Exists(path)) { auto backing = FS::FileOpen(path, ModeFlagsToFileAccessMode(perms), FS::FileType::BinaryFile);
if (!backing) {
return nullptr; return nullptr;
} }
auto backing = FS::FileOpen(path, ModeFlagsToFileAccessMode(perms), FS::FileType::BinaryFile);
cache.insert_or_assign(path, backing); cache.insert_or_assign(path, backing);
// Cannot use make_shared as RealVfsFile constructor is private // Cannot use make_shared as RealVfsFile constructor is private

View File

@ -32,7 +32,8 @@ enum class CommandType : u32 {
Control = 5, Control = 5,
RequestWithContext = 6, RequestWithContext = 6,
ControlWithContext = 7, ControlWithContext = 7,
Unspecified, TIPC_Close = 15,
TIPC_CommandRegion = 16, // Start of TIPC commands, this is an offset.
}; };
struct CommandHeader { struct CommandHeader {
@ -57,6 +58,20 @@ struct CommandHeader {
BitField<10, 4, BufferDescriptorCFlag> buf_c_descriptor_flags; BitField<10, 4, BufferDescriptorCFlag> buf_c_descriptor_flags;
BitField<31, 1, u32> enable_handle_descriptor; BitField<31, 1, u32> enable_handle_descriptor;
}; };
bool IsTipc() const {
return type.Value() >= CommandType::TIPC_CommandRegion;
}
bool IsCloseCommand() const {
switch (type.Value()) {
case CommandType::Close:
case CommandType::TIPC_Close:
return true;
default:
return false;
}
}
}; };
static_assert(sizeof(CommandHeader) == 8, "CommandHeader size is incorrect"); static_assert(sizeof(CommandHeader) == 8, "CommandHeader size is incorrect");

View File

@ -15,6 +15,8 @@
#include "core/hle/ipc.h" #include "core/hle/ipc.h"
#include "core/hle/kernel/hle_ipc.h" #include "core/hle/kernel/hle_ipc.h"
#include "core/hle/kernel/k_client_port.h" #include "core/hle/kernel/k_client_port.h"
#include "core/hle/kernel/k_process.h"
#include "core/hle/kernel/k_resource_limit.h"
#include "core/hle/kernel/k_session.h" #include "core/hle/kernel/k_session.h"
#include "core/hle/result.h" #include "core/hle/result.h"
@ -26,7 +28,7 @@ class RequestHelperBase {
protected: protected:
Kernel::HLERequestContext* context = nullptr; Kernel::HLERequestContext* context = nullptr;
u32* cmdbuf; u32* cmdbuf;
ptrdiff_t index = 0; u32 index = 0;
public: public:
explicit RequestHelperBase(u32* command_buffer) : cmdbuf(command_buffer) {} explicit RequestHelperBase(u32* command_buffer) : cmdbuf(command_buffer) {}
@ -38,7 +40,7 @@ public:
if (set_to_null) { if (set_to_null) {
memset(cmdbuf + index, 0, size_in_words * sizeof(u32)); memset(cmdbuf + index, 0, size_in_words * sizeof(u32));
} }
index += static_cast<ptrdiff_t>(size_in_words); index += size_in_words;
} }
/** /**
@ -51,11 +53,11 @@ public:
} }
u32 GetCurrentOffset() const { u32 GetCurrentOffset() const {
return static_cast<u32>(index); return index;
} }
void SetCurrentOffset(u32 offset) { void SetCurrentOffset(u32 offset) {
index = static_cast<ptrdiff_t>(offset); index = offset;
} }
}; };
@ -84,7 +86,9 @@ public:
// The entire size of the raw data section in u32 units, including the 16 bytes of mandatory // The entire size of the raw data section in u32 units, including the 16 bytes of mandatory
// padding. // padding.
u64 raw_data_size = sizeof(IPC::DataPayloadHeader) / 4 + 4 + normal_params_size; u32 raw_data_size = ctx.IsTipc()
? normal_params_size - 1
: sizeof(IPC::DataPayloadHeader) / 4 + 4 + normal_params_size;
u32 num_handles_to_move{}; u32 num_handles_to_move{};
u32 num_domain_objects{}; u32 num_domain_objects{};
@ -100,6 +104,10 @@ public:
raw_data_size += sizeof(DomainMessageHeader) / 4 + num_domain_objects; raw_data_size += sizeof(DomainMessageHeader) / 4 + num_domain_objects;
} }
if (ctx.IsTipc()) {
header.type.Assign(ctx.GetCommandType());
}
header.data_size.Assign(static_cast<u32>(raw_data_size)); header.data_size.Assign(static_cast<u32>(raw_data_size));
if (num_handles_to_copy || num_handles_to_move) { if (num_handles_to_copy || num_handles_to_move) {
header.enable_handle_descriptor.Assign(1); header.enable_handle_descriptor.Assign(1);
@ -111,22 +119,30 @@ public:
handle_descriptor_header.num_handles_to_copy.Assign(num_handles_to_copy); handle_descriptor_header.num_handles_to_copy.Assign(num_handles_to_copy);
handle_descriptor_header.num_handles_to_move.Assign(num_handles_to_move); handle_descriptor_header.num_handles_to_move.Assign(num_handles_to_move);
PushRaw(handle_descriptor_header); PushRaw(handle_descriptor_header);
ctx.handles_offset = index;
Skip(num_handles_to_copy + num_handles_to_move, true); Skip(num_handles_to_copy + num_handles_to_move, true);
} }
AlignWithPadding(); if (!ctx.IsTipc()) {
AlignWithPadding();
if (ctx.Session()->IsDomain() && ctx.HasDomainMessageHeader()) { if (ctx.Session()->IsDomain() && ctx.HasDomainMessageHeader()) {
IPC::DomainMessageHeader domain_header{}; IPC::DomainMessageHeader domain_header{};
domain_header.num_objects = num_domain_objects; domain_header.num_objects = num_domain_objects;
PushRaw(domain_header); PushRaw(domain_header);
}
IPC::DataPayloadHeader data_payload_header{};
data_payload_header.magic = Common::MakeMagic('S', 'F', 'C', 'O');
PushRaw(data_payload_header);
} }
IPC::DataPayloadHeader data_payload_header{}; data_payload_index = index;
data_payload_header.magic = Common::MakeMagic('S', 'F', 'C', 'O');
PushRaw(data_payload_header);
datapayload_index = index; ctx.data_payload_offset = index;
ctx.domain_offset = index + raw_data_size / 4;
} }
template <class T> template <class T>
@ -134,6 +150,9 @@ public:
if (context->Session()->IsDomain()) { if (context->Session()->IsDomain()) {
context->AddDomainObject(std::move(iface)); context->AddDomainObject(std::move(iface));
} else { } else {
kernel.CurrentProcess()->GetResourceLimit()->Reserve(
Kernel::LimitableResource::Sessions, 1);
auto* session = Kernel::KSession::Create(kernel); auto* session = Kernel::KSession::Create(kernel);
session->Initialize(nullptr, iface->GetServiceName()); session->Initialize(nullptr, iface->GetServiceName());
@ -152,7 +171,7 @@ public:
const std::size_t num_move_objects = context->NumMoveObjects(); const std::size_t num_move_objects = context->NumMoveObjects();
ASSERT_MSG(!num_domain_objects || !num_move_objects, ASSERT_MSG(!num_domain_objects || !num_move_objects,
"cannot move normal handles and domain objects"); "cannot move normal handles and domain objects");
ASSERT_MSG((index - datapayload_index) == normal_params_size, ASSERT_MSG((index - data_payload_index) == normal_params_size,
"normal_params_size value is incorrect"); "normal_params_size value is incorrect");
ASSERT_MSG((num_domain_objects + num_move_objects) == num_objects_to_move, ASSERT_MSG((num_domain_objects + num_move_objects) == num_objects_to_move,
"num_objects_to_move value is incorrect"); "num_objects_to_move value is incorrect");
@ -229,14 +248,14 @@ private:
u32 normal_params_size{}; u32 normal_params_size{};
u32 num_handles_to_copy{}; u32 num_handles_to_copy{};
u32 num_objects_to_move{}; ///< Domain objects or move handles, context dependent u32 num_objects_to_move{}; ///< Domain objects or move handles, context dependent
std::ptrdiff_t datapayload_index{}; u32 data_payload_index{};
Kernel::KernelCore& kernel; Kernel::KernelCore& kernel;
}; };
/// Push /// /// Push ///
inline void ResponseBuilder::PushImpl(s32 value) { inline void ResponseBuilder::PushImpl(s32 value) {
cmdbuf[index++] = static_cast<u32>(value); cmdbuf[index++] = value;
} }
inline void ResponseBuilder::PushImpl(u32 value) { inline void ResponseBuilder::PushImpl(u32 value) {

View File

@ -55,7 +55,7 @@ void HLERequestContext::ParseCommandBuffer(const KHandleTable& handle_table, u32
IPC::RequestParser rp(src_cmdbuf); IPC::RequestParser rp(src_cmdbuf);
command_header = rp.PopRaw<IPC::CommandHeader>(); command_header = rp.PopRaw<IPC::CommandHeader>();
if (command_header->type == IPC::CommandType::Close) { if (command_header->IsCloseCommand()) {
// Close does not populate the rest of the IPC header // Close does not populate the rest of the IPC header
return; return;
} }
@ -99,39 +99,43 @@ void HLERequestContext::ParseCommandBuffer(const KHandleTable& handle_table, u32
buffer_w_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorABW>()); buffer_w_desciptors.push_back(rp.PopRaw<IPC::BufferDescriptorABW>());
} }
buffer_c_offset = rp.GetCurrentOffset() + command_header->data_size; const auto buffer_c_offset = rp.GetCurrentOffset() + command_header->data_size;
// Padding to align to 16 bytes if (!command_header->IsTipc()) {
rp.AlignWithPadding(); // Padding to align to 16 bytes
rp.AlignWithPadding();
if (Session()->IsDomain() && ((command_header->type == IPC::CommandType::Request || if (Session()->IsDomain() &&
command_header->type == IPC::CommandType::RequestWithContext) || ((command_header->type == IPC::CommandType::Request ||
!incoming)) { command_header->type == IPC::CommandType::RequestWithContext) ||
// If this is an incoming message, only CommandType "Request" has a domain header !incoming)) {
// All outgoing domain messages have the domain header, if only incoming has it // If this is an incoming message, only CommandType "Request" has a domain header
if (incoming || domain_message_header) { // All outgoing domain messages have the domain header, if only incoming has it
domain_message_header = rp.PopRaw<IPC::DomainMessageHeader>(); if (incoming || domain_message_header) {
} else { domain_message_header = rp.PopRaw<IPC::DomainMessageHeader>();
if (Session()->IsDomain()) { } else {
LOG_WARNING(IPC, "Domain request has no DomainMessageHeader!"); if (Session()->IsDomain()) {
LOG_WARNING(IPC, "Domain request has no DomainMessageHeader!");
}
} }
} }
}
data_payload_header = rp.PopRaw<IPC::DataPayloadHeader>(); data_payload_header = rp.PopRaw<IPC::DataPayloadHeader>();
data_payload_offset = rp.GetCurrentOffset(); data_payload_offset = rp.GetCurrentOffset();
if (domain_message_header && domain_message_header->command == if (domain_message_header &&
IPC::DomainMessageHeader::CommandType::CloseVirtualHandle) { domain_message_header->command ==
// CloseVirtualHandle command does not have SFC* or any data IPC::DomainMessageHeader::CommandType::CloseVirtualHandle) {
return; // CloseVirtualHandle command does not have SFC* or any data
} return;
}
if (incoming) { if (incoming) {
ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'I')); ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'I'));
} else { } else {
ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'O')); ASSERT(data_payload_header->magic == Common::MakeMagic('S', 'F', 'C', 'O'));
}
} }
rp.SetCurrentOffset(buffer_c_offset); rp.SetCurrentOffset(buffer_c_offset);
@ -166,84 +170,55 @@ void HLERequestContext::ParseCommandBuffer(const KHandleTable& handle_table, u32
ResultCode HLERequestContext::PopulateFromIncomingCommandBuffer(const KHandleTable& handle_table, ResultCode HLERequestContext::PopulateFromIncomingCommandBuffer(const KHandleTable& handle_table,
u32_le* src_cmdbuf) { u32_le* src_cmdbuf) {
ParseCommandBuffer(handle_table, src_cmdbuf, true); ParseCommandBuffer(handle_table, src_cmdbuf, true);
if (command_header->type == IPC::CommandType::Close) {
if (command_header->IsCloseCommand()) {
// Close does not populate the rest of the IPC header // Close does not populate the rest of the IPC header
return RESULT_SUCCESS; return RESULT_SUCCESS;
} }
// The data_size already includes the payload header, the padding and the domain header. std::copy_n(src_cmdbuf, IPC::COMMAND_BUFFER_LENGTH, cmd_buf.begin());
std::size_t size = data_payload_offset + command_header->data_size -
sizeof(IPC::DataPayloadHeader) / sizeof(u32) - 4;
if (domain_message_header)
size -= sizeof(IPC::DomainMessageHeader) / sizeof(u32);
std::copy_n(src_cmdbuf, size, cmd_buf.begin());
return RESULT_SUCCESS; return RESULT_SUCCESS;
} }
ResultCode HLERequestContext::WriteToOutgoingCommandBuffer(KThread& requesting_thread) { ResultCode HLERequestContext::WriteToOutgoingCommandBuffer(KThread& requesting_thread) {
auto current_offset = handles_offset;
auto& owner_process = *requesting_thread.GetOwnerProcess(); auto& owner_process = *requesting_thread.GetOwnerProcess();
auto& handle_table = owner_process.GetHandleTable(); auto& handle_table = owner_process.GetHandleTable();
std::array<u32, IPC::COMMAND_BUFFER_LENGTH> dst_cmdbuf; for (auto& object : copy_objects) {
memory.ReadBlock(owner_process, requesting_thread.GetTLSAddress(), dst_cmdbuf.data(), Handle handle{};
dst_cmdbuf.size() * sizeof(u32)); if (object) {
R_TRY(handle_table.Add(&handle, object));
// The header was already built in the internal command buffer. Attempt to parse it to verify
// the integrity and then copy it over to the target command buffer.
ParseCommandBuffer(handle_table, cmd_buf.data(), false);
// The data_size already includes the payload header, the padding and the domain header.
std::size_t size = data_payload_offset + command_header->data_size -
sizeof(IPC::DataPayloadHeader) / sizeof(u32) - 4;
if (domain_message_header)
size -= sizeof(IPC::DomainMessageHeader) / sizeof(u32);
std::copy_n(cmd_buf.begin(), size, dst_cmdbuf.data());
if (command_header->enable_handle_descriptor) {
ASSERT_MSG(!move_objects.empty() || !copy_objects.empty(),
"Handle descriptor bit set but no handles to translate");
// We write the translated handles at a specific offset in the command buffer, this space
// was already reserved when writing the header.
std::size_t current_offset =
(sizeof(IPC::CommandHeader) + sizeof(IPC::HandleDescriptorHeader)) / sizeof(u32);
ASSERT_MSG(!handle_descriptor_header->send_current_pid, "Sending PID is not implemented");
ASSERT(copy_objects.size() == handle_descriptor_header->num_handles_to_copy);
ASSERT(move_objects.size() == handle_descriptor_header->num_handles_to_move);
// We don't make a distinction between copy and move handles when translating since HLE
// services don't deal with handles directly. However, the guest applications might check
// for specific values in each of these descriptors.
for (auto& object : copy_objects) {
ASSERT(object != nullptr);
R_TRY(handle_table.Add(&dst_cmdbuf[current_offset++], object));
} }
cmd_buf[current_offset++] = handle;
}
for (auto& object : move_objects) {
Handle handle{};
if (object) {
R_TRY(handle_table.Add(&handle, object));
for (auto& object : move_objects) { // Close our reference to the object, as it is being moved to the caller.
ASSERT(object != nullptr); object->Close();
R_TRY(handle_table.Add(&dst_cmdbuf[current_offset++], object));
} }
cmd_buf[current_offset++] = handle;
} }
// TODO(Subv): Translate the X/A/B/W buffers. // Write the domain objects to the command buffer, these go after the raw untranslated data.
// TODO(Subv): This completely ignores C buffers.
if (Session()->IsDomain() && domain_message_header) {
ASSERT(domain_message_header->num_objects == domain_objects.size());
// Write the domain objects to the command buffer, these go after the raw untranslated data.
// TODO(Subv): This completely ignores C buffers.
std::size_t domain_offset = size - domain_message_header->num_objects;
if (Session()->IsDomain()) {
current_offset = domain_offset - static_cast<u32>(domain_objects.size());
for (const auto& object : domain_objects) { for (const auto& object : domain_objects) {
server_session->AppendDomainRequestHandler(object); server_session->AppendDomainRequestHandler(object);
dst_cmdbuf[domain_offset++] = cmd_buf[current_offset++] =
static_cast<u32_le>(server_session->NumDomainRequestHandlers()); static_cast<u32_le>(server_session->NumDomainRequestHandlers());
} }
} }
// Copy the translated command buffer back into the thread's command buffer area. // Copy the translated command buffer back into the thread's command buffer area.
memory.WriteBlock(owner_process, requesting_thread.GetTLSAddress(), dst_cmdbuf.data(), memory.WriteBlock(owner_process, requesting_thread.GetTLSAddress(), cmd_buf.data(),
dst_cmdbuf.size() * sizeof(u32)); cmd_buf.size() * sizeof(u32));
return RESULT_SUCCESS; return RESULT_SUCCESS;
} }

View File

@ -66,7 +66,8 @@ public:
* this request (ServerSession, Originator thread, Translated command buffer, etc). * this request (ServerSession, Originator thread, Translated command buffer, etc).
* @returns ResultCode the result code of the translate operation. * @returns ResultCode the result code of the translate operation.
*/ */
virtual ResultCode HandleSyncRequest(Kernel::HLERequestContext& context) = 0; virtual ResultCode HandleSyncRequest(Kernel::KServerSession& session,
Kernel::HLERequestContext& context) = 0;
/** /**
* Signals that a client has just connected to this HLE handler and keeps the * Signals that a client has just connected to this HLE handler and keeps the
@ -128,15 +129,28 @@ public:
/// Writes data from this context back to the requesting process/thread. /// Writes data from this context back to the requesting process/thread.
ResultCode WriteToOutgoingCommandBuffer(KThread& requesting_thread); ResultCode WriteToOutgoingCommandBuffer(KThread& requesting_thread);
u32_le GetCommand() const { u32_le GetHipcCommand() const {
return command; return command;
} }
u32_le GetTipcCommand() const {
return static_cast<u32_le>(command_header->type.Value()) -
static_cast<u32_le>(IPC::CommandType::TIPC_CommandRegion);
}
u32_le GetCommand() const {
return command_header->IsTipc() ? GetTipcCommand() : GetHipcCommand();
}
bool IsTipc() const {
return command_header->IsTipc();
}
IPC::CommandType GetCommandType() const { IPC::CommandType GetCommandType() const {
return command_header->type; return command_header->type;
} }
unsigned GetDataPayloadOffset() const { u32 GetDataPayloadOffset() const {
return data_payload_offset; return data_payload_offset;
} }
@ -291,8 +305,9 @@ private:
std::vector<IPC::BufferDescriptorABW> buffer_w_desciptors; std::vector<IPC::BufferDescriptorABW> buffer_w_desciptors;
std::vector<IPC::BufferDescriptorC> buffer_c_desciptors; std::vector<IPC::BufferDescriptorC> buffer_c_desciptors;
unsigned data_payload_offset{}; u32 data_payload_offset{};
unsigned buffer_c_offset{}; u32 handles_offset{};
u32 domain_offset{};
u32_le command{}; u32_le command{};
std::vector<std::shared_ptr<SessionRequestHandler>> domain_request_handlers; std::vector<std::shared_ptr<SessionRequestHandler>> domain_request_handlers;

View File

@ -91,7 +91,7 @@ ResultCode KClientPort::CreateSession(KClientSession** out) {
// Create a new session. // Create a new session.
KSession* session = KSession::Create(kernel); KSession* session = KSession::Create(kernel);
if (session == nullptr) { if (session == nullptr) {
/* Decrement the session count. */ // Decrement the session count.
const auto prev = num_sessions--; const auto prev = num_sessions--;
if (prev == max_sessions) { if (prev == max_sessions) {
this->NotifyAvailable(); this->NotifyAvailable();

View File

@ -95,7 +95,7 @@ ResultCode KServerSession::HandleDomainSyncRequest(Kernel::HLERequestContext& co
UNREACHABLE(); UNREACHABLE();
return RESULT_SUCCESS; // Ignore error if asserts are off return RESULT_SUCCESS; // Ignore error if asserts are off
} }
return domain_request_handlers[object_id - 1]->HandleSyncRequest(context); return domain_request_handlers[object_id - 1]->HandleSyncRequest(*this, context);
case IPC::DomainMessageHeader::CommandType::CloseVirtualHandle: { case IPC::DomainMessageHeader::CommandType::CloseVirtualHandle: {
LOG_DEBUG(IPC, "CloseVirtualHandle, object_id=0x{:08X}", object_id); LOG_DEBUG(IPC, "CloseVirtualHandle, object_id=0x{:08X}", object_id);
@ -135,7 +135,7 @@ ResultCode KServerSession::CompleteSyncRequest(HLERequestContext& context) {
// If there is no domain header, the regular session handler is used // If there is no domain header, the regular session handler is used
} else if (hle_handler != nullptr) { } else if (hle_handler != nullptr) {
// If this ServerSession has an associated HLE handler, forward the request to it. // If this ServerSession has an associated HLE handler, forward the request to it.
result = hle_handler->HandleSyncRequest(context); result = hle_handler->HandleSyncRequest(*this, context);
} }
if (convert_to_domain) { if (convert_to_domain) {

View File

@ -44,6 +44,7 @@
#include "core/hle/kernel/time_manager.h" #include "core/hle/kernel/time_manager.h"
#include "core/hle/lock.h" #include "core/hle/lock.h"
#include "core/hle/result.h" #include "core/hle/result.h"
#include "core/hle/service/sm/sm.h"
#include "core/memory.h" #include "core/memory.h"
MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70)); MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70));
@ -656,6 +657,7 @@ struct KernelCore::Impl {
/// Map of named ports managed by the kernel, which can be retrieved using /// Map of named ports managed by the kernel, which can be retrieved using
/// the ConnectToPort SVC. /// the ConnectToPort SVC.
std::unordered_map<std::string, ServiceInterfaceFactory> service_interface_factory;
NamedPortTable named_ports; NamedPortTable named_ports;
std::unique_ptr<Core::ExclusiveMonitor> exclusive_monitor; std::unique_ptr<Core::ExclusiveMonitor> exclusive_monitor;
@ -844,18 +846,17 @@ void KernelCore::PrepareReschedule(std::size_t id) {
// TODO: Reimplement, this // TODO: Reimplement, this
} }
void KernelCore::AddNamedPort(std::string name, KClientPort* port) { void KernelCore::RegisterNamedService(std::string name, ServiceInterfaceFactory&& factory) {
port->Open(); impl->service_interface_factory.emplace(std::move(name), factory);
impl->named_ports.emplace(std::move(name), port);
} }
KernelCore::NamedPortTable::iterator KernelCore::FindNamedPort(const std::string& name) { KClientPort* KernelCore::CreateNamedServicePort(std::string name) {
return impl->named_ports.find(name); auto search = impl->service_interface_factory.find(name);
} if (search == impl->service_interface_factory.end()) {
UNIMPLEMENTED();
KernelCore::NamedPortTable::const_iterator KernelCore::FindNamedPort( return {};
const std::string& name) const { }
return impl->named_ports.find(name); return &search->second(impl->system.ServiceManager(), impl->system);
} }
bool KernelCore::IsValidNamedPort(NamedPortTable::const_iterator port) const { bool KernelCore::IsValidNamedPort(NamedPortTable::const_iterator port) const {

View File

@ -27,6 +27,10 @@ class CoreTiming;
struct EventType; struct EventType;
} // namespace Core::Timing } // namespace Core::Timing
namespace Service::SM {
class ServiceManager;
}
namespace Kernel { namespace Kernel {
class KClientPort; class KClientPort;
@ -51,6 +55,9 @@ class ServiceThread;
class Synchronization; class Synchronization;
class TimeManager; class TimeManager;
using ServiceInterfaceFactory =
std::function<KClientPort&(Service::SM::ServiceManager&, Core::System&)>;
namespace Init { namespace Init {
struct KSlabResourceCounts; struct KSlabResourceCounts;
} }
@ -172,14 +179,11 @@ public:
void InvalidateCpuInstructionCacheRange(VAddr addr, std::size_t size); void InvalidateCpuInstructionCacheRange(VAddr addr, std::size_t size);
/// Adds a port to the named port table /// Registers a named HLE service, passing a factory used to open a port to that service.
void AddNamedPort(std::string name, KClientPort* port); void RegisterNamedService(std::string name, ServiceInterfaceFactory&& factory);
/// Finds a port within the named port table with the given name. /// Opens a port to a service previously registered with RegisterNamedService.
NamedPortTable::iterator FindNamedPort(const std::string& name); KClientPort* CreateNamedServicePort(std::string name);
/// Finds a port within the named port table with the given name.
NamedPortTable::const_iterator FindNamedPort(const std::string& name) const;
/// Determines whether or not the given port is a valid named port. /// Determines whether or not the given port is a valid named port.
bool IsValidNamedPort(NamedPortTable::const_iterator port) const; bool IsValidNamedPort(NamedPortTable::const_iterator port) const;

View File

@ -284,12 +284,11 @@ static ResultCode ConnectToNamedPort(Core::System& system, Handle* out, VAddr po
auto& handle_table = kernel.CurrentProcess()->GetHandleTable(); auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
// Find the client port. // Find the client port.
const auto it = kernel.FindNamedPort(port_name); auto port = kernel.CreateNamedServicePort(port_name);
if (!kernel.IsValidNamedPort(it)) { if (!port) {
LOG_WARNING(Kernel_SVC, "tried to connect to unknown port: {}", port_name); LOG_ERROR(Kernel_SVC, "tried to connect to unknown port: {}", port_name);
return ResultNotFound; return ResultNotFound;
} }
auto port = it->second;
// Reserve a handle for the port. // Reserve a handle for the port.
// NOTE: Nintendo really does write directly to the output handle here. // NOTE: Nintendo really does write directly to the output handle here.

View File

@ -111,7 +111,7 @@ void ServiceFrameworkBase::InstallAsService(SM::ServiceManager& service_manager)
port_installed = true; port_installed = true;
} }
void ServiceFrameworkBase::InstallAsNamedPort(Kernel::KernelCore& kernel) { Kernel::KClientPort& ServiceFrameworkBase::CreatePort(Kernel::KernelCore& kernel) {
const auto guard = LockService(); const auto guard = LockService();
ASSERT(!port_installed); ASSERT(!port_installed);
@ -119,9 +119,10 @@ void ServiceFrameworkBase::InstallAsNamedPort(Kernel::KernelCore& kernel) {
auto* port = Kernel::KPort::Create(kernel); auto* port = Kernel::KPort::Create(kernel);
port->Initialize(max_sessions, false, service_name); port->Initialize(max_sessions, false, service_name);
port->GetServerPort().SetHleHandler(shared_from_this()); port->GetServerPort().SetHleHandler(shared_from_this());
kernel.AddNamedPort(service_name, &port->GetClientPort());
port_installed = true; port_installed = true;
return port->GetClientPort();
} }
void ServiceFrameworkBase::RegisterHandlersBase(const FunctionInfoBase* functions, std::size_t n) { void ServiceFrameworkBase::RegisterHandlersBase(const FunctionInfoBase* functions, std::size_t n) {
@ -132,6 +133,16 @@ void ServiceFrameworkBase::RegisterHandlersBase(const FunctionInfoBase* function
} }
} }
void ServiceFrameworkBase::RegisterHandlersBaseTipc(const FunctionInfoBase* functions,
std::size_t n) {
handlers_tipc.reserve(handlers_tipc.size() + n);
for (std::size_t i = 0; i < n; ++i) {
// Usually this array is sorted by id already, so hint to insert at the end
handlers_tipc.emplace_hint(handlers_tipc.cend(), functions[i].expected_header,
functions[i]);
}
}
void ServiceFrameworkBase::ReportUnimplementedFunction(Kernel::HLERequestContext& ctx, void ServiceFrameworkBase::ReportUnimplementedFunction(Kernel::HLERequestContext& ctx,
const FunctionInfoBase* info) { const FunctionInfoBase* info) {
auto cmd_buf = ctx.CommandBuffer(); auto cmd_buf = ctx.CommandBuffer();
@ -166,33 +177,55 @@ void ServiceFrameworkBase::InvokeRequest(Kernel::HLERequestContext& ctx) {
handler_invoker(this, info->handler_callback, ctx); handler_invoker(this, info->handler_callback, ctx);
} }
ResultCode ServiceFrameworkBase::HandleSyncRequest(Kernel::HLERequestContext& context) { void ServiceFrameworkBase::InvokeRequestTipc(Kernel::HLERequestContext& ctx) {
boost::container::flat_map<u32, FunctionInfoBase>::iterator itr;
itr = handlers_tipc.find(ctx.GetCommand());
const FunctionInfoBase* info = itr == handlers_tipc.end() ? nullptr : &itr->second;
if (info == nullptr || info->handler_callback == nullptr) {
return ReportUnimplementedFunction(ctx, info);
}
LOG_TRACE(Service, "{}", MakeFunctionString(info->name, GetServiceName(), ctx.CommandBuffer()));
handler_invoker(this, info->handler_callback, ctx);
}
ResultCode ServiceFrameworkBase::HandleSyncRequest(Kernel::KServerSession& session,
Kernel::HLERequestContext& ctx) {
const auto guard = LockService(); const auto guard = LockService();
switch (context.GetCommandType()) { switch (ctx.GetCommandType()) {
case IPC::CommandType::Close: { case IPC::CommandType::Close:
IPC::ResponseBuilder rb{context, 2}; case IPC::CommandType::TIPC_Close: {
session.Close();
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
return IPC::ERR_REMOTE_PROCESS_DEAD; return IPC::ERR_REMOTE_PROCESS_DEAD;
} }
case IPC::CommandType::ControlWithContext: case IPC::CommandType::ControlWithContext:
case IPC::CommandType::Control: { case IPC::CommandType::Control: {
system.ServiceManager().InvokeControlRequest(context); system.ServiceManager().InvokeControlRequest(ctx);
break; break;
} }
case IPC::CommandType::RequestWithContext: case IPC::CommandType::RequestWithContext:
case IPC::CommandType::Request: { case IPC::CommandType::Request: {
InvokeRequest(context); InvokeRequest(ctx);
break; break;
} }
default: default:
UNIMPLEMENTED_MSG("command_type={}", context.GetCommandType()); if (ctx.IsTipc()) {
InvokeRequestTipc(ctx);
break;
}
UNIMPLEMENTED_MSG("command_type={}", ctx.GetCommandType());
} }
// If emulation was shutdown, we are closing service threads, do not write the response back to // If emulation was shutdown, we are closing service threads, do not write the response back to
// memory that may be shutting down as well. // memory that may be shutting down as well.
if (system.IsPoweredOn()) { if (system.IsPoweredOn()) {
context.WriteToOutgoingCommandBuffer(context.GetThread()); ctx.WriteToOutgoingCommandBuffer(ctx.GetThread());
} }
return RESULT_SUCCESS; return RESULT_SUCCESS;
@ -207,7 +240,7 @@ Services::Services(std::shared_ptr<SM::ServiceManager>& sm, Core::System& system
system.GetFileSystemController().CreateFactories(*system.GetFilesystem(), false); system.GetFileSystemController().CreateFactories(*system.GetFilesystem(), false);
SM::ServiceManager::InstallInterfaces(sm, system); system.Kernel().RegisterNamedService("sm:", SM::ServiceManager::InterfaceFactory);
Account::InstallInterfaces(system); Account::InstallInterfaces(system);
AM::InstallInterfaces(*sm, *nv_flinger, system); AM::InstallInterfaces(*sm, *nv_flinger, system);

View File

@ -21,7 +21,9 @@ class System;
namespace Kernel { namespace Kernel {
class HLERequestContext; class HLERequestContext;
} class KClientPort;
class KServerSession;
} // namespace Kernel
namespace Service { namespace Service {
@ -64,12 +66,19 @@ public:
/// Creates a port pair and registers this service with the given ServiceManager. /// Creates a port pair and registers this service with the given ServiceManager.
void InstallAsService(SM::ServiceManager& service_manager); void InstallAsService(SM::ServiceManager& service_manager);
/// Creates a port pair and registers it on the kernel's global port registry.
void InstallAsNamedPort(Kernel::KernelCore& kernel); /// Invokes a service request routine using the HIPC protocol.
/// Invokes a service request routine.
void InvokeRequest(Kernel::HLERequestContext& ctx); void InvokeRequest(Kernel::HLERequestContext& ctx);
/// Invokes a service request routine using the HIPC protocol.
void InvokeRequestTipc(Kernel::HLERequestContext& ctx);
/// Creates a port pair and registers it on the kernel's global port registry.
Kernel::KClientPort& CreatePort(Kernel::KernelCore& kernel);
/// Handles a synchronization request for the service. /// Handles a synchronization request for the service.
ResultCode HandleSyncRequest(Kernel::HLERequestContext& context) override; ResultCode HandleSyncRequest(Kernel::KServerSession& session,
Kernel::HLERequestContext& context) override;
protected: protected:
/// Member-function pointer type of SyncRequest handlers. /// Member-function pointer type of SyncRequest handlers.
@ -102,6 +111,7 @@ private:
~ServiceFrameworkBase() override; ~ServiceFrameworkBase() override;
void RegisterHandlersBase(const FunctionInfoBase* functions, std::size_t n); void RegisterHandlersBase(const FunctionInfoBase* functions, std::size_t n);
void RegisterHandlersBaseTipc(const FunctionInfoBase* functions, std::size_t n);
void ReportUnimplementedFunction(Kernel::HLERequestContext& ctx, const FunctionInfoBase* info); void ReportUnimplementedFunction(Kernel::HLERequestContext& ctx, const FunctionInfoBase* info);
/// Identifier string used to connect to the service. /// Identifier string used to connect to the service.
@ -116,6 +126,7 @@ private:
/// Function used to safely up-cast pointers to the derived class before invoking a handler. /// Function used to safely up-cast pointers to the derived class before invoking a handler.
InvokerFn* handler_invoker; InvokerFn* handler_invoker;
boost::container::flat_map<u32, FunctionInfoBase> handlers; boost::container::flat_map<u32, FunctionInfoBase> handlers;
boost::container::flat_map<u32, FunctionInfoBase> handlers_tipc;
/// Used to gain exclusive access to the service members, e.g. from CoreTiming thread. /// Used to gain exclusive access to the service members, e.g. from CoreTiming thread.
Common::SpinLock lock_service; Common::SpinLock lock_service;
@ -183,6 +194,20 @@ protected:
RegisterHandlersBase(functions, n); RegisterHandlersBase(functions, n);
} }
/// Registers handlers in the service.
template <std::size_t N>
void RegisterHandlersTipc(const FunctionInfo (&functions)[N]) {
RegisterHandlersTipc(functions, N);
}
/**
* Registers handlers in the service. Usually prefer using the other RegisterHandlers
* overload in order to avoid needing to specify the array size.
*/
void RegisterHandlersTipc(const FunctionInfo* functions, std::size_t n) {
RegisterHandlersBaseTipc(functions, n);
}
private: private:
/** /**
* This function is used to allow invocation of pointers to handlers stored in the base class * This function is used to allow invocation of pointers to handlers stored in the base class

View File

@ -22,21 +22,29 @@ void Controller::ConvertCurrentObjectToDomain(Kernel::HLERequestContext& ctx) {
rb.Push<u32>(1); // Converted sessions start with 1 request handler rb.Push<u32>(1); // Converted sessions start with 1 request handler
} }
void Controller::CloneCurrentObject(Kernel::HLERequestContext& ctx) { void Controller::DuplicateSession(Kernel::HLERequestContext& ctx) {
// TODO(bunnei): This is just creating a new handle to the same Session. I assume this is wrong // TODO(bunnei): This is just creating a new handle to the same Session. I assume this is wrong
// and that we probably want to actually make an entirely new Session, but we still need to // and that we probably want to actually make an entirely new Session, but we still need to
// verify this on hardware. // verify this on hardware.
LOG_DEBUG(Service, "called"); LOG_DEBUG(Service, "called");
auto session = ctx.Session()->GetParent();
// Open a reference to the session to simulate a new one being created.
session->Open();
session->GetClientSession().Open();
session->GetServerSession().Open();
IPC::ResponseBuilder rb{ctx, 2, 0, 1, IPC::ResponseBuilder::Flags::AlwaysMoveHandles}; IPC::ResponseBuilder rb{ctx, 2, 0, 1, IPC::ResponseBuilder::Flags::AlwaysMoveHandles};
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
rb.PushMoveObjects(ctx.Session()->GetParent()->GetClientSession()); rb.PushMoveObjects(session->GetClientSession());
} }
void Controller::CloneCurrentObjectEx(Kernel::HLERequestContext& ctx) { void Controller::DuplicateSessionEx(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service, "(STUBBED) called, using CloneCurrentObject"); LOG_DEBUG(Service, "called");
CloneCurrentObject(ctx); DuplicateSession(ctx);
} }
void Controller::QueryPointerBufferSize(Kernel::HLERequestContext& ctx) { void Controller::QueryPointerBufferSize(Kernel::HLERequestContext& ctx) {
@ -44,7 +52,7 @@ void Controller::QueryPointerBufferSize(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 3}; IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
rb.Push<u16>(0x1000); rb.Push<u16>(0x8000);
} }
// https://switchbrew.org/wiki/IPC_Marshalling // https://switchbrew.org/wiki/IPC_Marshalling
@ -52,9 +60,9 @@ Controller::Controller(Core::System& system_) : ServiceFramework{system_, "IpcCo
static const FunctionInfo functions[] = { static const FunctionInfo functions[] = {
{0, &Controller::ConvertCurrentObjectToDomain, "ConvertCurrentObjectToDomain"}, {0, &Controller::ConvertCurrentObjectToDomain, "ConvertCurrentObjectToDomain"},
{1, nullptr, "CopyFromCurrentDomain"}, {1, nullptr, "CopyFromCurrentDomain"},
{2, &Controller::CloneCurrentObject, "CloneCurrentObject"}, {2, &Controller::DuplicateSession, "DuplicateSession"},
{3, &Controller::QueryPointerBufferSize, "QueryPointerBufferSize"}, {3, &Controller::QueryPointerBufferSize, "QueryPointerBufferSize"},
{4, &Controller::CloneCurrentObjectEx, "CloneCurrentObjectEx"}, {4, &Controller::DuplicateSessionEx, "DuplicateSessionEx"},
}; };
RegisterHandlers(functions); RegisterHandlers(functions);
} }

View File

@ -19,8 +19,8 @@ public:
private: private:
void ConvertCurrentObjectToDomain(Kernel::HLERequestContext& ctx); void ConvertCurrentObjectToDomain(Kernel::HLERequestContext& ctx);
void CloneCurrentObject(Kernel::HLERequestContext& ctx); void DuplicateSession(Kernel::HLERequestContext& ctx);
void CloneCurrentObjectEx(Kernel::HLERequestContext& ctx); void DuplicateSessionEx(Kernel::HLERequestContext& ctx);
void QueryPointerBufferSize(Kernel::HLERequestContext& ctx); void QueryPointerBufferSize(Kernel::HLERequestContext& ctx);
}; };

View File

@ -9,6 +9,7 @@
#include "core/hle/kernel/k_client_port.h" #include "core/hle/kernel/k_client_port.h"
#include "core/hle/kernel/k_client_session.h" #include "core/hle/kernel/k_client_session.h"
#include "core/hle/kernel/k_port.h" #include "core/hle/kernel/k_port.h"
#include "core/hle/kernel/k_scoped_resource_reservation.h"
#include "core/hle/kernel/k_server_port.h" #include "core/hle/kernel/k_server_port.h"
#include "core/hle/kernel/k_server_session.h" #include "core/hle/kernel/k_server_session.h"
#include "core/hle/kernel/k_session.h" #include "core/hle/kernel/k_session.h"
@ -18,6 +19,7 @@
namespace Service::SM { namespace Service::SM {
constexpr ResultCode ERR_NOT_INITIALIZED(ErrorModule::SM, 2);
constexpr ResultCode ERR_ALREADY_REGISTERED(ErrorModule::SM, 4); constexpr ResultCode ERR_ALREADY_REGISTERED(ErrorModule::SM, 4);
constexpr ResultCode ERR_INVALID_NAME(ErrorModule::SM, 6); constexpr ResultCode ERR_INVALID_NAME(ErrorModule::SM, 6);
constexpr ResultCode ERR_SERVICE_NOT_REGISTERED(ErrorModule::SM, 7); constexpr ResultCode ERR_SERVICE_NOT_REGISTERED(ErrorModule::SM, 7);
@ -34,20 +36,17 @@ static ResultCode ValidateServiceName(const std::string& name) {
LOG_ERROR(Service_SM, "Invalid service name! service={}", name); LOG_ERROR(Service_SM, "Invalid service name! service={}", name);
return ERR_INVALID_NAME; return ERR_INVALID_NAME;
} }
if (name.rfind('\0') != std::string::npos) {
LOG_ERROR(Service_SM, "A non null terminated service was passed");
return ERR_INVALID_NAME;
}
return RESULT_SUCCESS; return RESULT_SUCCESS;
} }
void ServiceManager::InstallInterfaces(std::shared_ptr<ServiceManager> self, Core::System& system) { Kernel::KClientPort& ServiceManager::InterfaceFactory(ServiceManager& self, Core::System& system) {
ASSERT(self->sm_interface.expired()); ASSERT(self.sm_interface.expired());
auto sm = std::make_shared<SM>(self, system); auto sm = std::make_shared<SM>(self, system);
sm->InstallAsNamedPort(system.Kernel()); self.sm_interface = sm;
self->sm_interface = sm; self.controller_interface = std::make_unique<Controller>(system);
self->controller_interface = std::make_unique<Controller>(system);
return sm->CreatePort(system.Kernel());
} }
ResultVal<Kernel::KServerPort*> ServiceManager::RegisterService(std::string name, ResultVal<Kernel::KServerPort*> ServiceManager::RegisterService(std::string name,
@ -107,33 +106,68 @@ SM::~SM() = default;
void SM::Initialize(Kernel::HLERequestContext& ctx) { void SM::Initialize(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_SM, "called"); LOG_DEBUG(Service_SM, "called");
is_initialized = true;
IPC::ResponseBuilder rb{ctx, 2}; IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
} }
void SM::GetService(Kernel::HLERequestContext& ctx) { void SM::GetService(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx}; auto result = GetServiceImpl(ctx);
auto name_buf = rp.PopRaw<std::array<char, 8>>(); if (result.Succeeded()) {
auto end = std::find(name_buf.begin(), name_buf.end(), '\0'); IPC::ResponseBuilder rb{ctx, 2, 0, 1, IPC::ResponseBuilder::Flags::AlwaysMoveHandles};
rb.Push(result.Code());
std::string name(name_buf.begin(), end); rb.PushMoveObjects(result.Unwrap());
} else {
auto result = service_manager->GetServicePort(name);
if (result.Failed()) {
IPC::ResponseBuilder rb{ctx, 2}; IPC::ResponseBuilder rb{ctx, 2};
rb.Push(result.Code()); rb.Push(result.Code());
}
}
void SM::GetServiceTipc(Kernel::HLERequestContext& ctx) {
auto result = GetServiceImpl(ctx);
IPC::ResponseBuilder rb{ctx, 2, 0, 1, IPC::ResponseBuilder::Flags::AlwaysMoveHandles};
rb.Push(result.Code());
rb.PushMoveObjects(result.Succeeded() ? result.Unwrap() : nullptr);
}
static std::string PopServiceName(IPC::RequestParser& rp) {
auto name_buf = rp.PopRaw<std::array<char, 8>>();
std::string result;
for (const auto& c : name_buf) {
if (c >= ' ' && c <= '~') {
result.push_back(c);
}
}
return result;
}
ResultVal<Kernel::KClientSession*> SM::GetServiceImpl(Kernel::HLERequestContext& ctx) {
if (!is_initialized) {
return ERR_NOT_INITIALIZED;
}
IPC::RequestParser rp{ctx};
std::string name(PopServiceName(rp));
auto result = service_manager.GetServicePort(name);
if (result.Failed()) {
LOG_ERROR(Service_SM, "called service={} -> error 0x{:08X}", name, result.Code().raw); LOG_ERROR(Service_SM, "called service={} -> error 0x{:08X}", name, result.Code().raw);
if (name.length() == 0) return result.Code();
return; // LibNX Fix
UNIMPLEMENTED();
return;
} }
auto* port = result.Unwrap(); auto* port = result.Unwrap();
Kernel::KScopedResourceReservation session_reservation(
kernel.CurrentProcess()->GetResourceLimit(), Kernel::LimitableResource::Sessions);
R_UNLESS(session_reservation.Succeeded(), Kernel::ResultLimitReached);
auto* session = Kernel::KSession::Create(kernel); auto* session = Kernel::KSession::Create(kernel);
session->Initialize(&port->GetClientPort(), std::move(name)); session->Initialize(&port->GetClientPort(), std::move(name));
// Commit the session reservation.
session_reservation.Commit();
if (port->GetServerPort().GetHLEHandler()) { if (port->GetServerPort().GetHLEHandler()) {
port->GetServerPort().GetHLEHandler()->ClientConnected(&session->GetServerSession()); port->GetServerPort().GetHLEHandler()->ClientConnected(&session->GetServerSession());
} else { } else {
@ -141,18 +175,12 @@ void SM::GetService(Kernel::HLERequestContext& ctx) {
} }
LOG_DEBUG(Service_SM, "called service={} -> session={}", name, session->GetId()); LOG_DEBUG(Service_SM, "called service={} -> session={}", name, session->GetId());
IPC::ResponseBuilder rb{ctx, 2, 0, 1, IPC::ResponseBuilder::Flags::AlwaysMoveHandles}; return MakeResult(&session->GetClientSession());
rb.Push(RESULT_SUCCESS);
rb.PushMoveObjects(session->GetClientSession());
} }
void SM::RegisterService(Kernel::HLERequestContext& ctx) { void SM::RegisterService(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx}; IPC::RequestParser rp{ctx};
std::string name(PopServiceName(rp));
const auto name_buf = rp.PopRaw<std::array<char, 8>>();
const auto end = std::find(name_buf.begin(), name_buf.end(), '\0');
const std::string name(name_buf.begin(), end);
const auto is_light = static_cast<bool>(rp.PopRaw<u32>()); const auto is_light = static_cast<bool>(rp.PopRaw<u32>());
const auto max_session_count = rp.PopRaw<u32>(); const auto max_session_count = rp.PopRaw<u32>();
@ -160,7 +188,7 @@ void SM::RegisterService(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_SM, "called with name={}, max_session_count={}, is_light={}", name, LOG_DEBUG(Service_SM, "called with name={}, max_session_count={}, is_light={}", name,
max_session_count, is_light); max_session_count, is_light);
auto handle = service_manager->RegisterService(name, max_session_count); auto handle = service_manager.RegisterService(name, max_session_count);
if (handle.Failed()) { if (handle.Failed()) {
LOG_ERROR(Service_SM, "failed to register service with error_code={:08X}", LOG_ERROR(Service_SM, "failed to register service with error_code={:08X}",
handle.Code().raw); handle.Code().raw);
@ -178,28 +206,31 @@ void SM::RegisterService(Kernel::HLERequestContext& ctx) {
void SM::UnregisterService(Kernel::HLERequestContext& ctx) { void SM::UnregisterService(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx}; IPC::RequestParser rp{ctx};
std::string name(PopServiceName(rp));
const auto name_buf = rp.PopRaw<std::array<char, 8>>();
const auto end = std::find(name_buf.begin(), name_buf.end(), '\0');
const std::string name(name_buf.begin(), end);
LOG_DEBUG(Service_SM, "called with name={}", name); LOG_DEBUG(Service_SM, "called with name={}", name);
IPC::ResponseBuilder rb{ctx, 2}; IPC::ResponseBuilder rb{ctx, 2};
rb.Push(service_manager->UnregisterService(name)); rb.Push(service_manager.UnregisterService(name));
} }
SM::SM(std::shared_ptr<ServiceManager> service_manager_, Core::System& system_) SM::SM(ServiceManager& service_manager_, Core::System& system_)
: ServiceFramework{system_, "sm:", 4}, : ServiceFramework{system_, "sm:", 4},
service_manager{std::move(service_manager_)}, kernel{system_.Kernel()} { service_manager{service_manager_}, kernel{system_.Kernel()} {
static const FunctionInfo functions[] = { RegisterHandlers({
{0, &SM::Initialize, "Initialize"}, {0, &SM::Initialize, "Initialize"},
{1, &SM::GetService, "GetService"}, {1, &SM::GetService, "GetService"},
{2, &SM::RegisterService, "RegisterService"}, {2, &SM::RegisterService, "RegisterService"},
{3, &SM::UnregisterService, "UnregisterService"}, {3, &SM::UnregisterService, "UnregisterService"},
{4, nullptr, "DetachClient"}, {4, nullptr, "DetachClient"},
}; });
RegisterHandlers(functions); RegisterHandlersTipc({
{0, &SM::Initialize, "Initialize"},
{1, &SM::GetServiceTipc, "GetService"},
{2, &SM::RegisterService, "RegisterService"},
{3, &SM::UnregisterService, "UnregisterService"},
{4, nullptr, "DetachClient"},
});
} }
} // namespace Service::SM } // namespace Service::SM

View File

@ -34,22 +34,26 @@ class Controller;
/// Interface to "sm:" service /// Interface to "sm:" service
class SM final : public ServiceFramework<SM> { class SM final : public ServiceFramework<SM> {
public: public:
explicit SM(std::shared_ptr<ServiceManager> service_manager_, Core::System& system_); explicit SM(ServiceManager& service_manager_, Core::System& system_);
~SM() override; ~SM() override;
private: private:
void Initialize(Kernel::HLERequestContext& ctx); void Initialize(Kernel::HLERequestContext& ctx);
void GetService(Kernel::HLERequestContext& ctx); void GetService(Kernel::HLERequestContext& ctx);
void GetServiceTipc(Kernel::HLERequestContext& ctx);
void RegisterService(Kernel::HLERequestContext& ctx); void RegisterService(Kernel::HLERequestContext& ctx);
void UnregisterService(Kernel::HLERequestContext& ctx); void UnregisterService(Kernel::HLERequestContext& ctx);
std::shared_ptr<ServiceManager> service_manager; ResultVal<Kernel::KClientSession*> GetServiceImpl(Kernel::HLERequestContext& ctx);
ServiceManager& service_manager;
bool is_initialized{};
Kernel::KernelCore& kernel; Kernel::KernelCore& kernel;
}; };
class ServiceManager { class ServiceManager {
public: public:
static void InstallInterfaces(std::shared_ptr<ServiceManager> self, Core::System& system); static Kernel::KClientPort& InterfaceFactory(ServiceManager& self, Core::System& system);
explicit ServiceManager(Kernel::KernelCore& kernel_); explicit ServiceManager(Kernel::KernelCore& kernel_);
~ServiceManager(); ~ServiceManager();

View File

@ -302,6 +302,10 @@ void GameListWorker::ScanFileSystem(ScanTarget target, const std::string& dir_pa
if (!is_dir && if (!is_dir &&
(HasSupportedFileExtension(physical_name) || IsExtractedNCAMain(physical_name))) { (HasSupportedFileExtension(physical_name) || IsExtractedNCAMain(physical_name))) {
const auto file = vfs->OpenFile(physical_name, FileSys::Mode::Read); const auto file = vfs->OpenFile(physical_name, FileSys::Mode::Read);
if (!file) {
return true;
}
auto loader = Loader::GetLoader(system, file); auto loader = Loader::GetLoader(system, file);
if (!loader) { if (!loader) {
return true; return true;