Compare commits

..

7 Commits

Author SHA1 Message Date
ReinUsesLisp
bc699ace15 service/bsd: Handle Poll with no entries accurately
Testing shows that Poll called with zero entries returns -1 and signals
an errno of zero.
2020-07-28 01:51:47 -03:00
ReinUsesLisp
f7d59f3e0e services/bsd: Implement most of bsd:s
This implements: Socket, Poll, Accept, Bind, Connect, GetPeerName,
GetSockName, Listen, Fcntl, SetSockOpt, Shutdown, Recv, RecvFrom,
Send, SendTo, Write, and Close

The implementation was done referencing: SwIPC, switchbrew, testing
with libnx and inspecting its code, general information about bsd
sockets online, and analysing official software.

Not everything from these service calls is implemented, but everything
that is not implemented will be logged in some way.
2020-07-28 01:48:42 -03:00
ReinUsesLisp
2c67bbf609 service/sockets: Add worker pool abstraction
Manage worker threads with an easy to use abstraction.
We can expand this to support thread deletion in the future.
2020-07-28 01:47:03 -03:00
ReinUsesLisp
5692c48ab7 service/sockets: Add worker abstraction to execute blocking calls asynchronously
This abstraction allows executing blocking functions (like recvfrom on a
socket configured for blocking) without blocking the service thread.
It is intended to be used with SleepClientThread.
2020-07-28 01:47:03 -03:00
ReinUsesLisp
80b4bd3583 service/sockets: Add translate functions
These functions translate from Network enumerations/structures to guest
enumerations/structures and viceversa.
2020-07-28 01:47:03 -03:00
ReinUsesLisp
22263ccaa4 service/sockets: Add enumerations and structures
Add guest enumerations and structures used in socket services
2020-07-28 01:47:03 -03:00
ReinUsesLisp
ef8acc9c3d services/nifm: Implement GetCurrentIpAddress
This is trivially implemented using the Network abstraction

- Used by ftpd
2020-07-28 01:47:03 -03:00
49 changed files with 1600 additions and 602 deletions

View File

@@ -60,7 +60,6 @@ else()
-Wmissing-declarations
-Wno-attributes
-Wno-unused-parameter
-fconcepts
)
if (ARCHITECTURE_x86_64)

View File

@@ -110,7 +110,6 @@ add_library(common STATIC
common_funcs.h
common_paths.h
common_types.h
concepts.h
dynamic_library.cpp
dynamic_library.h
fiber.cpp

View File

@@ -35,7 +35,6 @@
#define KEYS_DIR "keys"
#define LOAD_DIR "load"
#define DUMP_DIR "dump"
#define SCREENSHOTS_DIR "screenshots"
#define SHADER_DIR "shader"
#define LOG_DIR "log"

View File

@@ -1,32 +0,0 @@
// Copyright 2020 yuzu emulator team
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
namespace Common {
#include <type_traits>
// Check if type is like an STL container
template <typename T>
concept IsSTLContainer = requires(T t) {
typename T::value_type;
typename T::iterator;
typename T::const_iterator;
// TODO(ogniK): Replace below is std::same_as<void> when MSVC supports it.
t.begin();
t.end();
t.cbegin();
t.cend();
t.data();
t.size();
};
// Check if type T is derived from T2
template <typename T, typename T2>
concept IsBaseOf = requires {
std::is_base_of_v<T, T2>;
};
} // namespace Common

View File

@@ -695,7 +695,6 @@ const std::string& GetUserPath(UserPath path, const std::string& new_path) {
paths.emplace(UserPath::NANDDir, user_path + NAND_DIR DIR_SEP);
paths.emplace(UserPath::LoadDir, user_path + LOAD_DIR DIR_SEP);
paths.emplace(UserPath::DumpDir, user_path + DUMP_DIR DIR_SEP);
paths.emplace(UserPath::ScreenshotsDir, user_path + SCREENSHOTS_DIR DIR_SEP);
paths.emplace(UserPath::ShaderDir, user_path + SHADER_DIR DIR_SEP);
paths.emplace(UserPath::SysDataDir, user_path + SYSDATA_DIR DIR_SEP);
paths.emplace(UserPath::KeysDir, user_path + KEYS_DIR DIR_SEP);

View File

@@ -32,7 +32,6 @@ enum class UserPath {
SDMCDir,
LoadDir,
DumpDir,
ScreenshotsDir,
ShaderDir,
SysDataDir,
UserDir,

View File

@@ -491,6 +491,7 @@ add_library(core STATIC
hle/service/sm/controller.h
hle/service/sm/sm.cpp
hle/service/sm/sm.h
hle/service/sockets/blocking_worker.h
hle/service/sockets/bsd.cpp
hle/service/sockets/bsd.h
hle/service/sockets/ethc.cpp
@@ -501,6 +502,8 @@ add_library(core STATIC
hle/service/sockets/sfdnsres.h
hle/service/sockets/sockets.cpp
hle/service/sockets/sockets.h
hle/service/sockets/sockets_translate.cpp
hle/service/sockets/sockets_translate.h
hle/service/spl/csrng.cpp
hle/service/spl/csrng.h
hle/service/spl/module.cpp

View File

@@ -146,7 +146,7 @@ struct System::Impl {
ResultStatus Init(System& system, Frontend::EmuWindow& emu_window) {
LOG_DEBUG(HW_Memory, "initialized OK");
device_memory = std::make_unique<Core::DeviceMemory>();
device_memory = std::make_unique<Core::DeviceMemory>(system);
is_multicore = Settings::values.use_multi_core.GetValue();
is_async_gpu = is_multicore || Settings::values.use_asynchronous_gpu_emulation.GetValue();

View File

@@ -52,15 +52,15 @@ void CpuManager::Shutdown() {
}
std::function<void(void*)> CpuManager::GetGuestThreadStartFunc() {
return GuestThreadFunction;
return std::function<void(void*)>(GuestThreadFunction);
}
std::function<void(void*)> CpuManager::GetIdleThreadStartFunc() {
return IdleThreadFunction;
return std::function<void(void*)>(IdleThreadFunction);
}
std::function<void(void*)> CpuManager::GetSuspendThreadStartFunc() {
return SuspendThreadFunction;
return std::function<void(void*)>(SuspendThreadFunction);
}
void CpuManager::GuestThreadFunction(void* cpu_manager_) {

View File

@@ -2,11 +2,14 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "core/core.h"
#include "core/device_memory.h"
#include "core/memory.h"
namespace Core {
DeviceMemory::DeviceMemory() : buffer{DramMemoryMap::Size} {}
DeviceMemory::DeviceMemory(System& system) : buffer{DramMemoryMap::Size}, system{system} {}
DeviceMemory::~DeviceMemory() = default;
} // namespace Core

View File

@@ -4,11 +4,14 @@
#pragma once
#include "common/common_types.h"
#include "common/assert.h"
#include "common/common_funcs.h"
#include "common/virtual_buffer.h"
namespace Core {
class System;
namespace DramMemoryMap {
enum : u64 {
Base = 0x80000000ULL,
@@ -23,7 +26,7 @@ enum : u64 {
class DeviceMemory : NonCopyable {
public:
explicit DeviceMemory();
explicit DeviceMemory(Core::System& system);
~DeviceMemory();
template <typename T>
@@ -42,6 +45,7 @@ public:
private:
Common::VirtualBuffer<u8> buffer;
Core::System& system;
};
} // namespace Core

View File

@@ -547,6 +547,56 @@ InstallResult RegisteredCache::InstallEntry(const XCI& xci, bool overwrite_if_ex
return InstallEntry(*xci.GetSecurePartitionNSP(), overwrite_if_exists, copy);
}
bool RegisteredCache::RemoveExistingEntry(u64 title_id) {
const auto delete_nca = [this](const NcaID& id) {
const auto path = GetRelativePathFromNcaID(id, false, true, false);
if (dir->GetFileRelative(path) == nullptr) {
return false;
}
Core::Crypto::SHA256Hash hash{};
mbedtls_sha256_ret(id.data(), id.size(), hash.data(), 0);
const auto dirname = fmt::format("000000{:02X}", hash[0]);
const auto dir2 = GetOrCreateDirectoryRelative(dir, dirname);
const auto res = dir2->DeleteFile(fmt::format("{}.nca", Common::HexToString(id, false)));
return res;
};
// If an entry exists in the registered cache, remove it
if (HasEntry(title_id, ContentRecordType::Meta)) {
LOG_INFO(Loader,
"Previously installed entry (v{}) for title_id={:016X} detected! "
"Attempting to remove...",
GetEntryVersion(title_id).value_or(0), title_id);
// Get all the ncas associated with the current CNMT and delete them
const auto meta_old_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::Meta).value_or(NcaID{});
const auto program_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::Program).value_or(NcaID{});
const auto data_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::Data).value_or(NcaID{});
const auto control_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::Control).value_or(NcaID{});
const auto html_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::HtmlDocument).value_or(NcaID{});
const auto legal_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::LegalInformation).value_or(NcaID{});
delete_nca(meta_old_id);
delete_nca(program_id);
delete_nca(data_id);
delete_nca(control_id);
delete_nca(html_id);
delete_nca(legal_id);
return true;
}
return false;
}
InstallResult RegisteredCache::InstallEntry(const NSP& nsp, bool overwrite_if_exists,
const VfsCopyFunction& copy) {
const auto ncas = nsp.GetNCAsCollapsed();
@@ -642,57 +692,6 @@ InstallResult RegisteredCache::InstallEntry(const NCA& nca, TitleType type,
return RawInstallNCA(nca, copy, overwrite_if_exists, c_rec.nca_id);
}
bool RegisteredCache::RemoveExistingEntry(u64 title_id) const {
const auto delete_nca = [this](const NcaID& id) {
const auto path = GetRelativePathFromNcaID(id, false, true, false);
const bool isFile = dir->GetFileRelative(path) != nullptr;
const bool isDir = dir->GetDirectoryRelative(path) != nullptr;
if (isFile) {
return dir->DeleteFile(path);
} else if (isDir) {
return dir->DeleteSubdirectoryRecursive(path);
}
return false;
};
// If an entry exists in the registered cache, remove it
if (HasEntry(title_id, ContentRecordType::Meta)) {
LOG_INFO(Loader,
"Previously installed entry (v{}) for title_id={:016X} detected! "
"Attempting to remove...",
GetEntryVersion(title_id).value_or(0), title_id);
// Get all the ncas associated with the current CNMT and delete them
const auto meta_old_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::Meta).value_or(NcaID{});
const auto program_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::Program).value_or(NcaID{});
const auto data_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::Data).value_or(NcaID{});
const auto control_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::Control).value_or(NcaID{});
const auto html_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::HtmlDocument).value_or(NcaID{});
const auto legal_id =
GetNcaIDFromMetadata(title_id, ContentRecordType::LegalInformation).value_or(NcaID{});
const auto deleted_meta = delete_nca(meta_old_id);
const auto deleted_program = delete_nca(program_id);
const auto deleted_data = delete_nca(data_id);
const auto deleted_control = delete_nca(control_id);
const auto deleted_html = delete_nca(html_id);
const auto deleted_legal = delete_nca(legal_id);
return deleted_meta && (deleted_meta || deleted_program || deleted_data ||
deleted_control || deleted_html || deleted_legal);
}
return false;
}
InstallResult RegisteredCache::RawInstallNCA(const NCA& nca, const VfsCopyFunction& copy,
bool overwrite_if_exists,
std::optional<NcaID> override_id) {

View File

@@ -155,6 +155,9 @@ public:
std::optional<TitleType> title_type = {}, std::optional<ContentRecordType> record_type = {},
std::optional<u64> title_id = {}) const override;
// Removes an existing entry based on title id
bool RemoveExistingEntry(u64 title_id);
// Raw copies all the ncas from the xci/nsp to the csache. Does some quick checks to make sure
// there is a meta NCA and all of them are accessible.
InstallResult InstallEntry(const XCI& xci, bool overwrite_if_exists = false,
@@ -169,9 +172,6 @@ public:
InstallResult InstallEntry(const NCA& nca, TitleType type, bool overwrite_if_exists = false,
const VfsCopyFunction& copy = &VfsRawCopy);
// Removes an existing entry based on title id
bool RemoveExistingEntry(u64 title_id) const;
private:
template <typename T>
void IterateAllMetadata(std::vector<T>& out,

View File

@@ -70,18 +70,14 @@ NAX::NAX(VirtualFile file_, std::array<u8, 0x10> nca_id)
NAX::~NAX() = default;
Loader::ResultStatus NAX::Parse(std::string_view path) {
if (file == nullptr) {
return Loader::ResultStatus::ErrorNullFile;
}
if (file->ReadObject(header.get()) != sizeof(NAXHeader)) {
if (file->ReadObject(header.get()) != sizeof(NAXHeader))
return Loader::ResultStatus::ErrorBadNAXHeader;
}
if (header->magic != Common::MakeMagic('N', 'A', 'X', '0')) {
if (header->magic != Common::MakeMagic('N', 'A', 'X', '0'))
return Loader::ResultStatus::ErrorBadNAXHeader;
}
if (file->GetSize() < NAX_HEADER_PADDING_SIZE + header->file_size) {
if (file->GetSize() < NAX_HEADER_PADDING_SIZE + header->file_size)
return Loader::ResultStatus::ErrorIncorrectNAXFileSize;
}
keys.DeriveSDSeedLazy();
std::array<Core::Crypto::Key256, 2> sd_keys{};

View File

@@ -13,7 +13,6 @@
#include <vector>
#include <boost/container/small_vector.hpp>
#include "common/common_types.h"
#include "common/concepts.h"
#include "common/swap.h"
#include "core/hle/ipc.h"
#include "core/hle/kernel/object.h"
@@ -194,24 +193,23 @@ public:
/* Helper function to write a buffer using the appropriate buffer descriptor
*
* @tparam T an arbitrary container that satisfies the
* ContiguousContainer concept in the C++ standard library or a trivially copyable type.
* @tparam ContiguousContainer an arbitrary container that satisfies the
* ContiguousContainer concept in the C++ standard library.
*
* @param data The container/data to write into a buffer.
* @param container The container to write the data of into a buffer.
* @param buffer_index The buffer in particular to write to.
*/
template <typename T, typename = std::enable_if_t<!std::is_pointer_v<T>>>
std::size_t WriteBuffer(const T& data, std::size_t buffer_index = 0) const {
if constexpr (Common::IsSTLContainer<T>) {
using ContiguousType = typename T::value_type;
static_assert(std::is_trivially_copyable_v<ContiguousType>,
"Container to WriteBuffer must contain trivially copyable objects");
return WriteBuffer(std::data(data), std::size(data) * sizeof(ContiguousType),
buffer_index);
} else {
static_assert(std::is_trivially_copyable_v<T>, "T must be trivially copyable");
return WriteBuffer(&data, sizeof(T), buffer_index);
}
template <typename ContiguousContainer,
typename = std::enable_if_t<!std::is_pointer_v<ContiguousContainer>>>
std::size_t WriteBuffer(const ContiguousContainer& container,
std::size_t buffer_index = 0) const {
using ContiguousType = typename ContiguousContainer::value_type;
static_assert(std::is_trivially_copyable_v<ContiguousType>,
"Container to WriteBuffer must contain trivially copyable objects");
return WriteBuffer(std::data(container), std::size(container) * sizeof(ContiguousType),
buffer_index);
}
/// Helper function to get the size of the input buffer

View File

@@ -286,7 +286,9 @@ protected:
ProfileBase profile_base{};
ProfileData data{};
if (profile_manager.GetProfileBaseAndData(user_id, profile_base, data)) {
ctx.WriteBuffer(data);
std::array<u8, sizeof(ProfileData)> raw_data;
std::memcpy(raw_data.data(), &data, sizeof(ProfileData));
ctx.WriteBuffer(raw_data);
IPC::ResponseBuilder rb{ctx, 16};
rb.Push(RESULT_SUCCESS);
rb.PushRaw(profile_base);
@@ -331,7 +333,7 @@ protected:
std::vector<u8> buffer(size);
image.ReadBytes(buffer.data(), buffer.size());
ctx.WriteBuffer(buffer);
ctx.WriteBuffer(buffer.data(), buffer.size());
rb.Push<u32>(size);
}

View File

@@ -92,7 +92,7 @@ private:
if (performance) {
rb.Push<u64>(*performance);
}
ctx.WriteBuffer(samples);
ctx.WriteBuffer(samples.data(), samples.size() * sizeof(s16));
}
bool DecodeOpusData(u32& consumed, u32& sample_count, const std::vector<u8>& input,

View File

@@ -112,7 +112,7 @@ private:
void GetImpl(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_BCAT, "called");
ctx.WriteBuffer(impl);
ctx.WriteBuffer(&impl, sizeof(DeliveryCacheProgressImpl));
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);

View File

@@ -160,7 +160,7 @@ private:
return;
}
ctx.WriteBuffer(key);
ctx.WriteBuffer(key.data(), key.size());
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);

View File

@@ -127,7 +127,7 @@ private:
const u32 array_size = rp.Pop<u32>();
LOG_DEBUG(Service_NFP, "called, array_size={}", array_size);
ctx.WriteBuffer(device_handle);
ctx.WriteBuffer(&device_handle, sizeof(device_handle));
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
@@ -220,7 +220,7 @@ private:
tag_info.protocol = 1; // TODO(ogniK): Figure out actual values
tag_info.tag_type = 2;
ctx.WriteBuffer(tag_info);
ctx.WriteBuffer(&tag_info, sizeof(TagInfo));
rb.Push(RESULT_SUCCESS);
}
@@ -237,7 +237,7 @@ private:
IPC::ResponseBuilder rb{ctx, 2};
auto amiibo = nfp_interface.GetAmiiboBuffer();
ctx.WriteBuffer(amiibo.model_info);
ctx.WriteBuffer(&amiibo.model_info, sizeof(amiibo.model_info));
rb.Push(RESULT_SUCCESS);
}
@@ -283,7 +283,7 @@ private:
CommonInfo common_info{};
common_info.application_area_size = 0;
ctx.WriteBuffer(common_info);
ctx.WriteBuffer(&common_info, sizeof(CommonInfo));
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);

View File

@@ -9,6 +9,7 @@
#include "core/hle/kernel/writable_event.h"
#include "core/hle/service/nifm/nifm.h"
#include "core/hle/service/service.h"
#include "core/network/network.h"
#include "core/settings.h"
namespace Service::NIFM {
@@ -174,6 +175,16 @@ private:
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
}
void GetCurrentIpAddress(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_NIFM, "(STUBBED) called");
const auto [ipv4, error] = Network::GetHostIPv4Address();
UNIMPLEMENTED_IF(error != Network::Errno::SUCCESS);
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.PushRaw(ipv4);
}
void CreateTemporaryNetworkProfile(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_NIFM, "called");
@@ -235,7 +246,7 @@ IGeneralService::IGeneralService(Core::System& system)
{9, nullptr, "SetNetworkProfile"},
{10, &IGeneralService::RemoveNetworkProfile, "RemoveNetworkProfile"},
{11, nullptr, "GetScanDataOld"},
{12, nullptr, "GetCurrentIpAddress"},
{12, &IGeneralService::GetCurrentIpAddress, "GetCurrentIpAddress"},
{13, nullptr, "GetCurrentAccessPointOld"},
{14, &IGeneralService::CreateTemporaryNetworkProfile, "CreateTemporaryNetworkProfile"},
{15, nullptr, "GetCurrentIpConfigInfo"},

View File

@@ -246,7 +246,7 @@ void Init(std::shared_ptr<SM::ServiceManager>& sm, Core::System& system) {
PSC::InstallInterfaces(*sm);
PSM::InstallInterfaces(*sm);
Set::InstallInterfaces(*sm);
Sockets::InstallInterfaces(*sm);
Sockets::InstallInterfaces(*sm, system);
SPL::InstallInterfaces(*sm);
SSL::InstallInterfaces(*sm);
Time::InstallInterfaces(system);

View File

@@ -106,7 +106,7 @@ void GetKeyCodeMapImpl(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
ctx.WriteBuffer(layout);
ctx.WriteBuffer(&layout, sizeof(KeyboardLayout));
}
} // Anonymous namespace

View File

@@ -0,0 +1,162 @@
// Copyright 2020 yuzu emulator team
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <atomic>
#include <memory>
#include <string>
#include <string_view>
#include <thread>
#include <variant>
#include <vector>
#include <fmt/format.h>
#include "common/assert.h"
#include "common/microprofile.h"
#include "common/thread.h"
#include "core/core.h"
#include "core/hle/kernel/hle_ipc.h"
#include "core/hle/kernel/kernel.h"
#include "core/hle/kernel/thread.h"
#include "core/hle/kernel/writable_event.h"
namespace Service::Sockets {
/**
* Worker abstraction to execute blocking calls on host without blocking the guest thread
*
* @tparam Service Service where the work is executed
* @tparam ...Types Types of work to execute
*/
template <class Service, class... Types>
class BlockingWorker {
using This = BlockingWorker<Service, Types...>;
using WorkVariant = std::variant<std::monostate, Types...>;
public:
/// Create a new worker
static std::unique_ptr<This> Create(Core::System& system, Service* service,
std::string_view name) {
return std::unique_ptr<This>(new This(system, service, name));
}
~BlockingWorker() {
while (!is_available.load(std::memory_order_relaxed)) {
// Busy wait until work is finished
std::this_thread::yield();
}
// Monostate means to exit the thread
work = std::monostate{};
work_event.Set();
thread.join();
}
/**
* Try to capture the worker to send work after a success
* @returns True when the worker has been successfully captured
*/
bool TryCapture() {
bool expected = true;
return is_available.compare_exchange_weak(expected, false, std::memory_order_relaxed,
std::memory_order_relaxed);
}
/**
* Send work to this worker abstraction
* @see TryCapture must be called before attempting to call this function
*/
template <class Work>
void SendWork(Work new_work) {
ASSERT_MSG(!is_available, "Trying to send work on a worker that's not captured");
work = std::move(new_work);
work_event.Set();
}
/// Generate a callback for @see SleepClientThread
template <class Work>
auto Callback() {
return [this](std::shared_ptr<Kernel::Thread>, Kernel::HLERequestContext& ctx,
Kernel::ThreadWakeupReason reason) {
ASSERT(reason == Kernel::ThreadWakeupReason::Signal);
std::get<Work>(work).Response(ctx);
is_available.store(true);
};
}
/// Get kernel event that will be signalled by the worker when the host operation finishes
std::shared_ptr<Kernel::WritableEvent> KernelEvent() const {
return kernel_event;
}
private:
explicit BlockingWorker(Core::System& system, Service* service, std::string_view name) {
auto pair = Kernel::WritableEvent::CreateEventPair(system.Kernel(), std::string(name));
kernel_event = std::move(pair.writable);
thread = std::thread([this, &system, service, name] { Run(system, service, name); });
}
void Run(Core::System& system, Service* service, std::string_view name) {
system.RegisterHostThread();
const std::string thread_name = fmt::format("yuzu:{}", name);
MicroProfileOnThreadCreate(thread_name.c_str());
Common::SetCurrentThreadName(thread_name.c_str());
bool keep_running = true;
while (keep_running) {
work_event.Wait();
const auto visit_fn = [service, &keep_running](auto&& w) {
using T = std::decay_t<decltype(w)>;
if constexpr (std::is_same_v<T, std::monostate>) {
keep_running = false;
} else {
w.Execute(service);
}
};
std::visit(visit_fn, work);
kernel_event->Signal();
}
}
std::thread thread;
WorkVariant work;
Common::Event work_event;
std::shared_ptr<Kernel::WritableEvent> kernel_event;
std::atomic_bool is_available{true};
};
template <class Service, class... Types>
class BlockingWorkerPool {
using Worker = BlockingWorker<Service, Types...>;
public:
explicit BlockingWorkerPool(Core::System& system_, Service* service_)
: system{system_}, service{service_} {}
/// Returns a captured worker thread, creating new ones if necessary
Worker* CaptureWorker() {
for (auto& worker : workers) {
if (worker->TryCapture()) {
return worker.get();
}
}
auto new_worker = Worker::Create(system, service, fmt::format("BSD:{}", workers.size()));
[[maybe_unused]] const bool success = new_worker->TryCapture();
ASSERT(success);
return workers.emplace_back(std::move(new_worker)).get();
}
private:
Core::System& system;
Service* const service;
std::vector<std::unique_ptr<Worker>> workers;
};
} // namespace Service::Sockets

View File

@@ -2,18 +2,138 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <array>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <fmt/format.h>
#include "common/microprofile.h"
#include "common/thread.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/thread.h"
#include "core/hle/service/sockets/bsd.h"
#include "core/hle/service/sockets/sockets_translate.h"
#include "core/network/network.h"
#include "core/network/sockets.h"
namespace Service::Sockets {
namespace {
bool IsConnectionBased(Type type) {
switch (type) {
case Type::STREAM:
return true;
case Type::DGRAM:
return false;
default:
UNIMPLEMENTED_MSG("Unimplemented type={}", static_cast<int>(type));
return false;
}
}
} // Anonymous namespace
void BSD::PollWork::Execute(BSD* bsd) {
std::tie(ret, bsd_errno) = bsd->PollImpl(write_buffer, read_buffer, nfds, timeout);
}
void BSD::PollWork::Response(Kernel::HLERequestContext& ctx) {
ctx.WriteBuffer(write_buffer);
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push<s32>(ret);
rb.PushEnum(bsd_errno);
}
void BSD::AcceptWork::Execute(BSD* bsd) {
std::tie(ret, bsd_errno) = bsd->AcceptImpl(fd, write_buffer);
}
void BSD::AcceptWork::Response(Kernel::HLERequestContext& ctx) {
ctx.WriteBuffer(write_buffer);
IPC::ResponseBuilder rb{ctx, 5};
rb.Push(RESULT_SUCCESS);
rb.Push<s32>(ret);
rb.PushEnum(bsd_errno);
rb.Push<u32>(static_cast<u32>(write_buffer.size()));
}
void BSD::ConnectWork::Execute(BSD* bsd) {
bsd_errno = bsd->ConnectImpl(fd, addr);
}
void BSD::ConnectWork::Response(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push<s32>(bsd_errno == Errno::SUCCESS ? 0 : -1);
rb.PushEnum(bsd_errno);
}
void BSD::RecvWork::Execute(BSD* bsd) {
std::tie(ret, bsd_errno) = bsd->RecvImpl(fd, flags, message);
}
void BSD::RecvWork::Response(Kernel::HLERequestContext& ctx) {
ctx.WriteBuffer(message);
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push<s32>(ret);
rb.PushEnum(bsd_errno);
}
void BSD::RecvFromWork::Execute(BSD* bsd) {
std::tie(ret, bsd_errno) = bsd->RecvFromImpl(fd, flags, message, addr);
}
void BSD::RecvFromWork::Response(Kernel::HLERequestContext& ctx) {
ctx.WriteBuffer(message, 0);
if (!addr.empty()) {
ctx.WriteBuffer(addr, 1);
}
IPC::ResponseBuilder rb{ctx, 5};
rb.Push(RESULT_SUCCESS);
rb.Push<s32>(ret);
rb.PushEnum(bsd_errno);
rb.Push<u32>(static_cast<u32>(addr.size()));
}
void BSD::SendWork::Execute(BSD* bsd) {
std::tie(ret, bsd_errno) = bsd->SendImpl(fd, flags, message);
}
void BSD::SendWork::Response(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push<s32>(ret);
rb.PushEnum(bsd_errno);
}
void BSD::SendToWork::Execute(BSD* bsd) {
std::tie(ret, bsd_errno) = bsd->SendToImpl(fd, flags, message, addr);
}
void BSD::SendToWork::Response(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push<s32>(ret);
rb.PushEnum(bsd_errno);
}
void BSD::RegisterClient(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service, "(STUBBED) called");
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(0); // bsd errno
rb.Push<s32>(0); // bsd errno
}
void BSD::StartMonitoring(Kernel::HLERequestContext& ctx) {
@@ -26,20 +146,19 @@ void BSD::StartMonitoring(Kernel::HLERequestContext& ctx) {
void BSD::Socket(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const u32 domain = rp.Pop<u32>();
const u32 type = rp.Pop<u32>();
const u32 protocol = rp.Pop<u32>();
u32 domain = rp.Pop<u32>();
u32 type = rp.Pop<u32>();
u32 protocol = rp.Pop<u32>();
LOG_DEBUG(Service, "called. domain={} type={} protocol={}", domain, type, protocol);
LOG_WARNING(Service, "(STUBBED) called domain={} type={} protocol={}", domain, type, protocol);
u32 fd = next_fd++;
const auto [fd, bsd_errno] = SocketImpl(static_cast<Domain>(domain), static_cast<Type>(type),
static_cast<Protocol>(protocol));
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(fd);
rb.Push<u32>(0); // bsd errno
rb.Push<s32>(fd);
rb.PushEnum(bsd_errno);
}
void BSD::Select(Kernel::HLERequestContext& ctx) {
@@ -52,67 +171,663 @@ void BSD::Select(Kernel::HLERequestContext& ctx) {
rb.Push<u32>(0); // bsd errno
}
void BSD::Poll(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const s32 nfds = rp.Pop<s32>();
const s32 timeout = rp.Pop<s32>();
LOG_DEBUG(Service, "called. nfds={} timeout={}", nfds, timeout);
ExecuteWork(ctx, "BSD:Poll", timeout != 0,
PollWork{
.nfds = nfds,
.timeout = timeout,
.read_buffer = ctx.ReadBuffer(),
.write_buffer = std::vector<u8>(ctx.GetWriteBufferSize()),
});
}
void BSD::Accept(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
LOG_DEBUG(Service, "called. fd={}", fd);
ExecuteWork(ctx, "BSD:Accept", IsBlockingSocket(fd),
AcceptWork{
.fd = fd,
.write_buffer = std::vector<u8>(ctx.GetWriteBufferSize()),
});
}
void BSD::Bind(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service, "(STUBBED) called");
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
IPC::ResponseBuilder rb{ctx, 4};
LOG_DEBUG(Service, "called. fd={} addrlen={}", fd, ctx.GetReadBufferSize());
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(0); // ret
rb.Push<u32>(0); // bsd errno
BuildErrnoResponse(ctx, BindImpl(fd, ctx.ReadBuffer()));
}
void BSD::Connect(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service, "(STUBBED) called");
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
IPC::ResponseBuilder rb{ctx, 4};
LOG_DEBUG(Service, "called. fd={} addrlen={}", fd, ctx.GetReadBufferSize());
ExecuteWork(ctx, "BSD:Connect", IsBlockingSocket(fd),
ConnectWork{
.fd = fd,
.addr = ctx.ReadBuffer(),
});
}
void BSD::GetPeerName(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
LOG_DEBUG(Service, "called. fd={}", fd);
std::vector<u8> write_buffer(ctx.GetWriteBufferSize());
const Errno bsd_errno = GetPeerNameImpl(fd, write_buffer);
ctx.WriteBuffer(write_buffer);
IPC::ResponseBuilder rb{ctx, 5};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(0); // ret
rb.Push<u32>(0); // bsd errno
rb.Push<s32>(bsd_errno != Errno::SUCCESS ? -1 : 0);
rb.PushEnum(bsd_errno);
rb.Push<u32>(static_cast<u32>(write_buffer.size()));
}
void BSD::GetSockName(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
LOG_DEBUG(Service, "called. fd={}", fd);
std::vector<u8> write_buffer(ctx.GetWriteBufferSize());
const Errno bsd_errno = GetSockNameImpl(fd, write_buffer);
ctx.WriteBuffer(write_buffer);
IPC::ResponseBuilder rb{ctx, 5};
rb.Push(RESULT_SUCCESS);
rb.Push<s32>(bsd_errno != Errno::SUCCESS ? -1 : 0);
rb.PushEnum(bsd_errno);
rb.Push<u32>(static_cast<u32>(write_buffer.size()));
}
void BSD::Listen(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service, "(STUBBED) called");
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
const s32 backlog = rp.Pop<s32>();
LOG_DEBUG(Service, "called. fd={} backlog={}", fd, backlog);
BuildErrnoResponse(ctx, ListenImpl(fd, backlog));
}
void BSD::Fcntl(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
const s32 cmd = rp.Pop<s32>();
const s32 arg = rp.Pop<s32>();
LOG_DEBUG(Service, "called. fd={} cmd={} arg={}", fd, cmd, arg);
const auto [ret, bsd_errno] = FcntlImpl(fd, static_cast<FcntlCmd>(cmd), arg);
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(0); // ret
rb.Push<u32>(0); // bsd errno
rb.Push<s32>(ret);
rb.PushEnum(bsd_errno);
}
void BSD::SetSockOpt(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service, "(STUBBED) called");
IPC::RequestParser rp{ctx};
IPC::ResponseBuilder rb{ctx, 4};
const s32 fd = rp.Pop<s32>();
const u32 level = rp.Pop<u32>();
const OptName optname = static_cast<OptName>(rp.Pop<u32>());
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(0); // ret
rb.Push<u32>(0); // bsd errno
const std::vector<u8> buffer = ctx.ReadBuffer();
const u8* optval = buffer.empty() ? nullptr : buffer.data();
size_t optlen = buffer.size();
std::array<u64, 2> values;
if ((optname == OptName::SNDTIMEO || optname == OptName::RCVTIMEO) && buffer.size() == 8) {
std::memcpy(values.data(), buffer.data(), sizeof(values));
optlen = sizeof(values);
optval = reinterpret_cast<const u8*>(values.data());
}
LOG_DEBUG(Service, "called. fd={} level={} optname=0x{:x} optlen={}", fd, level,
static_cast<u32>(optname), optlen);
BuildErrnoResponse(ctx, SetSockOptImpl(fd, level, optname, optlen, optval));
}
void BSD::Shutdown(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
const s32 how = rp.Pop<s32>();
LOG_DEBUG(Service, "called. fd={} how={}", fd, how);
BuildErrnoResponse(ctx, ShutdownImpl(fd, how));
}
void BSD::Recv(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
const u32 flags = rp.Pop<u32>();
LOG_DEBUG(Service, "called. fd={} flags=0x{:x} len={}", fd, flags, ctx.GetWriteBufferSize());
ExecuteWork(ctx, "BSD:Recv", IsBlockingSocket(fd),
RecvWork{
.fd = fd,
.flags = flags,
.message = std::vector<u8>(ctx.GetWriteBufferSize()),
});
}
void BSD::RecvFrom(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
const u32 flags = rp.Pop<u32>();
LOG_DEBUG(Service, "called. fd={} flags=0x{:x} len={} addrlen={}", fd, flags,
ctx.GetWriteBufferSize(0), ctx.GetWriteBufferSize(1));
ExecuteWork(ctx, "BSD:RecvFrom", IsBlockingSocket(fd),
RecvFromWork{
.fd = fd,
.flags = flags,
.message = std::vector<u8>(ctx.GetWriteBufferSize(0)),
.addr = std::vector<u8>(ctx.GetWriteBufferSize(1)),
});
}
void BSD::Send(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
const u32 flags = rp.Pop<u32>();
LOG_DEBUG(Service, "called. fd={} flags=0x{:x} len={}", fd, flags, ctx.GetReadBufferSize());
ExecuteWork(ctx, "BSD:Send", IsBlockingSocket(fd),
SendWork{
.fd = fd,
.flags = flags,
.message = ctx.ReadBuffer(),
});
}
void BSD::SendTo(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service, "(STUBBED) called");
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
const u32 flags = rp.Pop<u32>();
IPC::ResponseBuilder rb{ctx, 4};
LOG_DEBUG(Service, "called. fd={} flags=0x{} len={} addrlen={}", fd, flags,
ctx.GetReadBufferSize(0), ctx.GetReadBufferSize(1));
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(0); // ret
rb.Push<u32>(0); // bsd errno
ExecuteWork(ctx, "BSD:SendTo", IsBlockingSocket(fd),
SendToWork{
.fd = fd,
.flags = flags,
.message = ctx.ReadBuffer(0),
.addr = ctx.ReadBuffer(1),
});
}
void BSD::Write(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
LOG_DEBUG(Service, "called. fd={} len={}", fd, ctx.GetReadBufferSize());
ExecuteWork(ctx, "BSD:Write", IsBlockingSocket(fd),
SendWork{
.fd = fd,
.flags = 0,
.message = ctx.ReadBuffer(),
});
}
void BSD::Close(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service, "(STUBBED) called");
IPC::RequestParser rp{ctx};
const s32 fd = rp.Pop<s32>();
LOG_DEBUG(Service, "called. fd={}", fd);
BuildErrnoResponse(ctx, CloseImpl(fd));
}
template <typename Work>
void BSD::ExecuteWork(Kernel::HLERequestContext& ctx, std::string_view sleep_reason,
bool is_blocking, Work work) {
if (!is_blocking) {
work.Execute(this);
work.Response(ctx);
return;
}
// Signal a dummy response to make IPC validation happy
// This will be overwritten by the SleepClientThread callback
work.Response(ctx);
auto worker = worker_pool.CaptureWorker();
ctx.SleepClientThread(std::string(sleep_reason), std::numeric_limits<u64>::max(),
worker->Callback<Work>(), worker->KernelEvent());
worker->SendWork(std::move(work));
}
std::pair<s32, Errno> BSD::SocketImpl(Domain domain, Type type, Protocol protocol) {
if (type == Type::SEQPACKET) {
UNIMPLEMENTED_MSG("SOCK_SEQPACKET errno management");
} else if (type == Type::RAW && (domain != Domain::INET || protocol != Protocol::ICMP)) {
UNIMPLEMENTED_MSG("SOCK_RAW errno management");
}
[[maybe_unused]] const bool unk_flag = (static_cast<u32>(type) & 0x20000000) != 0;
UNIMPLEMENTED_IF_MSG(unk_flag, "Unknown flag in type");
type = static_cast<Type>(static_cast<u32>(type) & ~0x20000000);
const s32 fd = FindFreeFileDescriptorHandle();
if (fd < 0) {
LOG_ERROR(Service, "No more file descriptors available");
return {-1, Errno::MFILE};
}
FileDescriptor& descriptor = file_descriptors[fd].emplace();
// ENONMEM might be thrown here
LOG_INFO(Service, "New socket fd={}", fd);
descriptor.socket = std::make_unique<Network::Socket>();
descriptor.socket->Initialize(Translate(domain), Translate(type), Translate(type, protocol));
descriptor.is_connection_based = IsConnectionBased(type);
return {fd, Errno::SUCCESS};
}
std::pair<s32, Errno> BSD::PollImpl(std::vector<u8>& write_buffer, std::vector<u8> read_buffer,
s32 nfds, s32 timeout) {
if (write_buffer.size() < nfds * sizeof(PollFD)) {
return {-1, Errno::INVAL};
}
if (nfds == 0) {
// When no entries are provided, -1 is returned with errno zero
return {-1, Errno::SUCCESS};
}
const size_t length = std::min(read_buffer.size(), write_buffer.size());
std::vector<PollFD> fds(nfds);
std::memcpy(fds.data(), read_buffer.data(), length);
if (timeout >= 0) {
const s64 seconds = timeout / 1000;
const u64 nanoseconds = 1'000'000 * (static_cast<u64>(timeout) % 1000);
if (seconds < 0) {
return {-1, Errno::INVAL};
}
if (nanoseconds > 999'999'999) {
return {-1, Errno::INVAL};
}
} else if (timeout != -1) {
return {-1, Errno::INVAL};
}
for (PollFD& pollfd : fds) {
ASSERT(pollfd.revents == 0);
if (pollfd.fd > MAX_FD || pollfd.fd < 0) {
LOG_ERROR(Service, "File descriptor handle={} is invalid", pollfd.fd);
pollfd.revents = 0;
return {0, Errno::SUCCESS};
}
std::optional<FileDescriptor>& descriptor = file_descriptors[pollfd.fd];
if (!descriptor) {
LOG_ERROR(Service, "File descriptor handle={} is not allocated", pollfd.fd);
pollfd.revents = POLL_NVAL;
return {0, Errno::SUCCESS};
}
}
std::vector<Network::PollFD> host_pollfds(fds.size());
std::transform(fds.begin(), fds.end(), host_pollfds.begin(), [this](PollFD pollfd) {
Network::PollFD result;
result.socket = file_descriptors[pollfd.fd]->socket.get();
result.events = TranslatePollEventsToHost(pollfd.events);
result.revents = 0;
return result;
});
const auto result = Network::Poll(host_pollfds, timeout);
const size_t num = host_pollfds.size();
for (size_t i = 0; i < num; ++i) {
fds[i].revents = TranslatePollEventsToGuest(host_pollfds[i].revents);
}
std::memcpy(write_buffer.data(), fds.data(), length);
return Translate(result);
}
std::pair<s32, Errno> BSD::AcceptImpl(s32 fd, std::vector<u8>& write_buffer) {
if (!IsFileDescriptorValid(fd)) {
return {-1, Errno::BADF};
}
const s32 new_fd = FindFreeFileDescriptorHandle();
if (new_fd < 0) {
LOG_ERROR(Service, "No more file descriptors available");
return {-1, Errno::MFILE};
}
FileDescriptor& descriptor = *file_descriptors[fd];
auto [result, bsd_errno] = descriptor.socket->Accept();
if (bsd_errno != Network::Errno::SUCCESS) {
return {-1, Translate(bsd_errno)};
}
FileDescriptor& new_descriptor = file_descriptors[new_fd].emplace();
new_descriptor.socket = std::move(result.socket);
new_descriptor.is_connection_based = descriptor.is_connection_based;
ASSERT(write_buffer.size() == sizeof(SockAddrIn));
const SockAddrIn guest_addr_in = Translate(result.sockaddr_in);
std::memcpy(write_buffer.data(), &guest_addr_in, sizeof(guest_addr_in));
return {new_fd, Errno::SUCCESS};
}
Errno BSD::BindImpl(s32 fd, const std::vector<u8>& addr) {
if (!IsFileDescriptorValid(fd)) {
return Errno::BADF;
}
ASSERT(addr.size() == sizeof(SockAddrIn));
SockAddrIn addr_in;
std::memcpy(&addr_in, addr.data(), sizeof(addr_in));
return Translate(file_descriptors[fd]->socket->Bind(Translate(addr_in)));
}
Errno BSD::ConnectImpl(s32 fd, const std::vector<u8>& addr) {
if (!IsFileDescriptorValid(fd)) {
return Errno::BADF;
}
UNIMPLEMENTED_IF(addr.size() != sizeof(SockAddrIn));
SockAddrIn addr_in;
std::memcpy(&addr_in, addr.data(), sizeof(addr_in));
return Translate(file_descriptors[fd]->socket->Connect(Translate(addr_in)));
}
Errno BSD::GetPeerNameImpl(s32 fd, std::vector<u8>& write_buffer) {
if (!IsFileDescriptorValid(fd)) {
return Errno::BADF;
}
const auto [addr_in, bsd_errno] = file_descriptors[fd]->socket->GetPeerName();
if (bsd_errno != Network::Errno::SUCCESS) {
return Translate(bsd_errno);
}
const SockAddrIn guest_addrin = Translate(addr_in);
ASSERT(write_buffer.size() == sizeof(guest_addrin));
std::memcpy(write_buffer.data(), &guest_addrin, sizeof(guest_addrin));
return Translate(bsd_errno);
}
Errno BSD::GetSockNameImpl(s32 fd, std::vector<u8>& write_buffer) {
if (!IsFileDescriptorValid(fd)) {
return Errno::BADF;
}
const auto [addr_in, bsd_errno] = file_descriptors[fd]->socket->GetSockName();
if (bsd_errno != Network::Errno::SUCCESS) {
return Translate(bsd_errno);
}
const SockAddrIn guest_addrin = Translate(addr_in);
ASSERT(write_buffer.size() == sizeof(guest_addrin));
std::memcpy(write_buffer.data(), &guest_addrin, sizeof(guest_addrin));
return Translate(bsd_errno);
}
Errno BSD::ListenImpl(s32 fd, s32 backlog) {
if (!IsFileDescriptorValid(fd)) {
return Errno::BADF;
}
return Translate(file_descriptors[fd]->socket->Listen(backlog));
}
std::pair<s32, Errno> BSD::FcntlImpl(s32 fd, FcntlCmd cmd, s32 arg) {
if (!IsFileDescriptorValid(fd)) {
return {-1, Errno::BADF};
}
FileDescriptor& descriptor = *file_descriptors[fd];
switch (cmd) {
case FcntlCmd::GETFL:
ASSERT(arg == 0);
return {descriptor.flags, Errno::SUCCESS};
case FcntlCmd::SETFL: {
const bool enable = (arg & FLAG_O_NONBLOCK) != 0;
const Errno bsd_errno = Translate(descriptor.socket->SetNonBlock(enable));
if (bsd_errno != Errno::SUCCESS) {
return {-1, bsd_errno};
}
descriptor.flags = arg;
return {0, Errno::SUCCESS};
}
default:
UNIMPLEMENTED_MSG("Unimplemented cmd={}", static_cast<int>(cmd));
return {-1, Errno::SUCCESS};
}
}
Errno BSD::SetSockOptImpl(s32 fd, u32 level, OptName optname, size_t optlen, const void* optval) {
UNIMPLEMENTED_IF(level != 0xffff); // SOL_SOCKET
if (!IsFileDescriptorValid(fd)) {
return Errno::BADF;
}
Network::Socket* const socket = file_descriptors[fd]->socket.get();
if (optname == OptName::LINGER) {
ASSERT(optlen == sizeof(Linger));
Linger linger;
std::memcpy(&linger, optval, sizeof(linger));
ASSERT(linger.onoff == 0 || linger.onoff == 1);
return Translate(socket->SetLinger(linger.onoff != 0, linger.linger));
}
ASSERT(optlen == sizeof(u32));
u32 value;
std::memcpy(&value, optval, sizeof(value));
switch (optname) {
case OptName::REUSEADDR:
ASSERT(value == 0 || value == 1);
return Translate(socket->SetReuseAddr(value != 0));
case OptName::BROADCAST:
ASSERT(value == 0 || value == 1);
return Translate(socket->SetBroadcast(value != 0));
case OptName::SNDBUF:
return Translate(socket->SetSndBuf(value));
case OptName::RCVBUF:
return Translate(socket->SetRcvBuf(value));
case OptName::SNDTIMEO:
return Translate(socket->SetSndTimeo(value));
case OptName::RCVTIMEO:
return Translate(socket->SetRcvTimeo(value));
default:
UNIMPLEMENTED_MSG("Unimplemented optname={}", static_cast<int>(optname));
return Errno::SUCCESS;
}
}
Errno BSD::ShutdownImpl(s32 fd, s32 how) {
if (!IsFileDescriptorValid(fd)) {
return Errno::BADF;
}
const Network::ShutdownHow host_how = Translate(static_cast<ShutdownHow>(how));
return Translate(file_descriptors[fd]->socket->Shutdown(host_how));
}
std::pair<s32, Errno> BSD::RecvImpl(s32 fd, u32 flags, std::vector<u8>& message) {
if (!IsFileDescriptorValid(fd)) {
return {-1, Errno::BADF};
}
return Translate(file_descriptors[fd]->socket->Recv(flags, message));
}
std::pair<s32, Errno> BSD::RecvFromImpl(s32 fd, u32 flags, std::vector<u8>& message,
std::vector<u8>& addr) {
if (!IsFileDescriptorValid(fd)) {
return {-1, Errno::BADF};
}
FileDescriptor& descriptor = *file_descriptors[fd];
Network::SockAddrIn addr_in{};
Network::SockAddrIn* p_addr_in = nullptr;
if (descriptor.is_connection_based) {
// Connection based file descriptors (e.g. TCP) zero addr
addr.clear();
} else {
p_addr_in = &addr_in;
}
// Apply flags
if ((flags & FLAG_MSG_DONTWAIT) != 0) {
flags &= ~FLAG_MSG_DONTWAIT;
if ((descriptor.flags & FLAG_O_NONBLOCK) == 0) {
descriptor.socket->SetNonBlock(true);
}
}
const auto [ret, bsd_errno] = Translate(descriptor.socket->RecvFrom(flags, message, p_addr_in));
// Restore original state
if ((descriptor.flags & FLAG_O_NONBLOCK) == 0) {
descriptor.socket->SetNonBlock(false);
}
if (p_addr_in) {
if (ret < 0) {
addr.clear();
} else {
ASSERT(addr.size() == sizeof(SockAddrIn));
const SockAddrIn result = Translate(addr_in);
std::memcpy(addr.data(), &result, sizeof(result));
}
}
return {ret, bsd_errno};
}
std::pair<s32, Errno> BSD::SendImpl(s32 fd, u32 flags, const std::vector<u8>& message) {
if (!IsFileDescriptorValid(fd)) {
return {-1, Errno::BADF};
}
return Translate(file_descriptors[fd]->socket->Send(message, flags));
}
std::pair<s32, Errno> BSD::SendToImpl(s32 fd, u32 flags, const std::vector<u8>& message,
const std::vector<u8>& addr) {
if (!IsFileDescriptorValid(fd)) {
return {-1, Errno::BADF};
}
Network::SockAddrIn addr_in;
Network::SockAddrIn* p_addr_in = nullptr;
if (!addr.empty()) {
ASSERT(addr.size() == sizeof(SockAddrIn));
SockAddrIn guest_addr_in;
std::memcpy(&guest_addr_in, addr.data(), sizeof(guest_addr_in));
addr_in = Translate(guest_addr_in);
}
return Translate(file_descriptors[fd]->socket->SendTo(flags, message, p_addr_in));
}
Errno BSD::CloseImpl(s32 fd) {
if (!IsFileDescriptorValid(fd)) {
return Errno::BADF;
}
const Errno bsd_errno = Translate(file_descriptors[fd]->socket->Close());
if (bsd_errno != Errno::SUCCESS) {
return bsd_errno;
}
LOG_INFO(Service, "Close socket fd={}", fd);
file_descriptors[fd].reset();
return bsd_errno;
}
s32 BSD::FindFreeFileDescriptorHandle() noexcept {
for (s32 fd = 0; fd < static_cast<s32>(file_descriptors.size()); ++fd) {
if (!file_descriptors[fd]) {
return fd;
}
}
return -1;
}
bool BSD::IsFileDescriptorValid(s32 fd) const noexcept {
if (fd > MAX_FD || fd < 0) {
LOG_ERROR(Service, "Invalid file descriptor handle={}", fd);
return false;
}
if (!file_descriptors[fd]) {
LOG_ERROR(Service, "File descriptor handle={} is not allocated", fd);
return false;
}
return true;
}
bool BSD::IsBlockingSocket(s32 fd) const noexcept {
// Inform invalid sockets as non-blocking
// This way we avoid using a worker thread as it will fail without blocking host
if (fd > MAX_FD || fd < 0) {
return false;
}
if (!file_descriptors[fd]) {
return false;
}
return (file_descriptors[fd]->flags & FLAG_O_NONBLOCK) != 0;
}
void BSD::BuildErrnoResponse(Kernel::HLERequestContext& ctx, Errno bsd_errno) const noexcept {
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(0); // ret
rb.Push<u32>(0); // bsd errno
rb.Push<s32>(bsd_errno == Errno::SUCCESS ? 0 : -1);
rb.PushEnum(bsd_errno);
}
BSD::BSD(const char* name) : ServiceFramework(name) {
BSD::BSD(Core::System& system, const char* name)
: ServiceFramework(name), worker_pool{system, this} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &BSD::RegisterClient, "RegisterClient"},
@@ -121,25 +836,25 @@ BSD::BSD(const char* name) : ServiceFramework(name) {
{3, nullptr, "SocketExempt"},
{4, nullptr, "Open"},
{5, &BSD::Select, "Select"},
{6, nullptr, "Poll"},
{6, &BSD::Poll, "Poll"},
{7, nullptr, "Sysctl"},
{8, nullptr, "Recv"},
{9, nullptr, "RecvFrom"},
{10, nullptr, "Send"},
{8, &BSD::Recv, "Recv"},
{9, &BSD::RecvFrom, "RecvFrom"},
{10, &BSD::Send, "Send"},
{11, &BSD::SendTo, "SendTo"},
{12, nullptr, "Accept"},
{12, &BSD::Accept, "Accept"},
{13, &BSD::Bind, "Bind"},
{14, &BSD::Connect, "Connect"},
{15, nullptr, "GetPeerName"},
{16, nullptr, "GetSockName"},
{15, &BSD::GetPeerName, "GetPeerName"},
{16, &BSD::GetSockName, "GetSockName"},
{17, nullptr, "GetSockOpt"},
{18, &BSD::Listen, "Listen"},
{19, nullptr, "Ioctl"},
{20, nullptr, "Fcntl"},
{20, &BSD::Fcntl, "Fcntl"},
{21, &BSD::SetSockOpt, "SetSockOpt"},
{22, nullptr, "Shutdown"},
{22, &BSD::Shutdown, "Shutdown"},
{23, nullptr, "ShutdownAllSockets"},
{24, nullptr, "Write"},
{24, &BSD::Write, "Write"},
{25, nullptr, "Read"},
{26, &BSD::Close, "Close"},
{27, nullptr, "DuplicateSocket"},

View File

@@ -4,30 +4,174 @@
#pragma once
#include <memory>
#include <string_view>
#include <vector>
#include "common/common_types.h"
#include "core/hle/kernel/hle_ipc.h"
#include "core/hle/service/service.h"
#include "core/hle/service/sockets/blocking_worker.h"
#include "core/hle/service/sockets/sockets.h"
namespace Core {
class System;
}
namespace Network {
class Socket;
}
namespace Service::Sockets {
class BSD final : public ServiceFramework<BSD> {
public:
explicit BSD(const char* name);
explicit BSD(Core::System& system, const char* name);
~BSD() override;
private:
/// Maximum number of file descriptors
static constexpr size_t MAX_FD = 128;
struct FileDescriptor {
std::unique_ptr<Network::Socket> socket;
s32 flags = 0;
bool is_connection_based = false;
};
struct PollWork {
void Execute(BSD* bsd);
void Response(Kernel::HLERequestContext& ctx);
s32 nfds;
s32 timeout;
std::vector<u8> read_buffer;
std::vector<u8> write_buffer;
s32 ret{};
Errno bsd_errno{};
};
struct AcceptWork {
void Execute(BSD* bsd);
void Response(Kernel::HLERequestContext& ctx);
s32 fd;
std::vector<u8> write_buffer;
s32 ret{};
Errno bsd_errno{};
};
struct ConnectWork {
void Execute(BSD* bsd);
void Response(Kernel::HLERequestContext& ctx);
s32 fd;
std::vector<u8> addr;
Errno bsd_errno{};
};
struct RecvWork {
void Execute(BSD* bsd);
void Response(Kernel::HLERequestContext& ctx);
s32 fd;
u32 flags;
std::vector<u8> message;
s32 ret{};
Errno bsd_errno{};
};
struct RecvFromWork {
void Execute(BSD* bsd);
void Response(Kernel::HLERequestContext& ctx);
s32 fd;
u32 flags;
std::vector<u8> message;
std::vector<u8> addr;
s32 ret{};
Errno bsd_errno{};
};
struct SendWork {
void Execute(BSD* bsd);
void Response(Kernel::HLERequestContext& ctx);
s32 fd;
u32 flags;
std::vector<u8> message;
s32 ret{};
Errno bsd_errno{};
};
struct SendToWork {
void Execute(BSD* bsd);
void Response(Kernel::HLERequestContext& ctx);
s32 fd;
u32 flags;
std::vector<u8> message;
std::vector<u8> addr;
s32 ret{};
Errno bsd_errno{};
};
void RegisterClient(Kernel::HLERequestContext& ctx);
void StartMonitoring(Kernel::HLERequestContext& ctx);
void Socket(Kernel::HLERequestContext& ctx);
void Select(Kernel::HLERequestContext& ctx);
void Poll(Kernel::HLERequestContext& ctx);
void Accept(Kernel::HLERequestContext& ctx);
void Bind(Kernel::HLERequestContext& ctx);
void Connect(Kernel::HLERequestContext& ctx);
void GetPeerName(Kernel::HLERequestContext& ctx);
void GetSockName(Kernel::HLERequestContext& ctx);
void Listen(Kernel::HLERequestContext& ctx);
void Fcntl(Kernel::HLERequestContext& ctx);
void SetSockOpt(Kernel::HLERequestContext& ctx);
void Shutdown(Kernel::HLERequestContext& ctx);
void Recv(Kernel::HLERequestContext& ctx);
void RecvFrom(Kernel::HLERequestContext& ctx);
void Send(Kernel::HLERequestContext& ctx);
void SendTo(Kernel::HLERequestContext& ctx);
void Write(Kernel::HLERequestContext& ctx);
void Close(Kernel::HLERequestContext& ctx);
/// Id to use for the next open file descriptor.
u32 next_fd = 1;
template <typename Work>
void ExecuteWork(Kernel::HLERequestContext& ctx, std::string_view sleep_reason,
bool is_blocking, Work work);
std::pair<s32, Errno> SocketImpl(Domain domain, Type type, Protocol protocol);
std::pair<s32, Errno> PollImpl(std::vector<u8>& write_buffer, std::vector<u8> read_buffer,
s32 nfds, s32 timeout);
std::pair<s32, Errno> AcceptImpl(s32 fd, std::vector<u8>& write_buffer);
Errno BindImpl(s32 fd, const std::vector<u8>& addr);
Errno ConnectImpl(s32 fd, const std::vector<u8>& addr);
Errno GetPeerNameImpl(s32 fd, std::vector<u8>& write_buffer);
Errno GetSockNameImpl(s32 fd, std::vector<u8>& write_buffer);
Errno ListenImpl(s32 fd, s32 backlog);
std::pair<s32, Errno> FcntlImpl(s32 fd, FcntlCmd cmd, s32 arg);
Errno SetSockOptImpl(s32 fd, u32 level, OptName optname, size_t optlen, const void* optval);
Errno ShutdownImpl(s32 fd, s32 how);
std::pair<s32, Errno> RecvImpl(s32 fd, u32 flags, std::vector<u8>& message);
std::pair<s32, Errno> RecvFromImpl(s32 fd, u32 flags, std::vector<u8>& message,
std::vector<u8>& addr);
std::pair<s32, Errno> SendImpl(s32 fd, u32 flags, const std::vector<u8>& message);
std::pair<s32, Errno> SendToImpl(s32 fd, u32 flags, const std::vector<u8>& message,
const std::vector<u8>& addr);
Errno CloseImpl(s32 fd);
s32 FindFreeFileDescriptorHandle() noexcept;
bool IsFileDescriptorValid(s32 fd) const noexcept;
bool IsBlockingSocket(s32 fd) const noexcept;
void BuildErrnoResponse(Kernel::HLERequestContext& ctx, Errno bsd_errno) const noexcept;
std::array<std::optional<FileDescriptor>, MAX_FD> file_descriptors;
BlockingWorkerPool<BSD, PollWork, AcceptWork, ConnectWork, RecvWork, RecvFromWork, SendWork,
SendToWork>
worker_pool;
};
class BSDCFG final : public ServiceFramework<BSDCFG> {

View File

@@ -10,9 +10,9 @@
namespace Service::Sockets {
void InstallInterfaces(SM::ServiceManager& service_manager) {
std::make_shared<BSD>("bsd:s")->InstallAsService(service_manager);
std::make_shared<BSD>("bsd:u")->InstallAsService(service_manager);
void InstallInterfaces(SM::ServiceManager& service_manager, Core::System& system) {
std::make_shared<BSD>(system, "bsd:s")->InstallAsService(service_manager);
std::make_shared<BSD>(system, "bsd:u")->InstallAsService(service_manager);
std::make_shared<BSDCFG>()->InstallAsService(service_manager);
std::make_shared<ETHC_C>()->InstallAsService(service_manager);

View File

@@ -4,11 +4,94 @@
#pragma once
#include "common/common_types.h"
#include "core/hle/service/service.h"
namespace Core {
class System;
}
namespace Service::Sockets {
enum class Errno : u32 {
SUCCESS = 0,
BADF = 9,
AGAIN = 11,
INVAL = 22,
MFILE = 24,
NOTCONN = 107,
};
enum class Domain : u32 {
INET = 2,
};
enum class Type : u32 {
STREAM = 1,
DGRAM = 2,
RAW = 3,
SEQPACKET = 5,
};
enum class Protocol : u32 {
UNSPECIFIED = 0,
ICMP = 1,
TCP = 6,
UDP = 17,
};
enum class OptName : u32 {
REUSEADDR = 0x4,
BROADCAST = 0x20,
LINGER = 0x80,
SNDBUF = 0x1001,
RCVBUF = 0x1002,
SNDTIMEO = 0x1005,
RCVTIMEO = 0x1006,
};
enum class ShutdownHow : s32 {
RD = 0,
WR = 1,
RDWR = 2,
};
enum class FcntlCmd : s32 {
GETFL = 3,
SETFL = 4,
};
struct SockAddrIn {
u8 len;
u8 family;
u16 portno;
std::array<u8, 4> ip;
std::array<u8, 8> zeroes;
};
struct PollFD {
s32 fd;
u16 events;
u16 revents;
};
struct Linger {
u32 onoff;
u32 linger;
};
constexpr u16 POLL_IN = 0x01;
constexpr u16 POLL_PRI = 0x02;
constexpr u16 POLL_OUT = 0x04;
constexpr u16 POLL_ERR = 0x08;
constexpr u16 POLL_HUP = 0x10;
constexpr u16 POLL_NVAL = 0x20;
constexpr u32 FLAG_MSG_DONTWAIT = 0x80;
constexpr u32 FLAG_O_NONBLOCK = 0x800;
/// Registers all Sockets services with the specified service manager.
void InstallInterfaces(SM::ServiceManager& service_manager);
void InstallInterfaces(SM::ServiceManager& service_manager, Core::System& system);
} // namespace Service::Sockets

View File

@@ -0,0 +1,165 @@
// Copyright 2020 yuzu emulator team
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <utility>
#include "common/assert.h"
#include "common/common_types.h"
#include "core/hle/service/sockets/sockets.h"
#include "core/hle/service/sockets/sockets_translate.h"
#include "core/network/network.h"
namespace Service::Sockets {
Errno Translate(Network::Errno value) {
switch (value) {
case Network::Errno::SUCCESS:
return Errno::SUCCESS;
case Network::Errno::BADF:
return Errno::BADF;
case Network::Errno::AGAIN:
return Errno::AGAIN;
case Network::Errno::INVAL:
return Errno::INVAL;
case Network::Errno::MFILE:
return Errno::MFILE;
case Network::Errno::NOTCONN:
return Errno::NOTCONN;
default:
UNIMPLEMENTED_MSG("Unimplemented errno={}", static_cast<int>(value));
return Errno::SUCCESS;
}
}
std::pair<s32, Errno> Translate(std::pair<s32, Network::Errno> value) {
return {value.first, Translate(value.second)};
}
Network::Domain Translate(Domain domain) {
switch (domain) {
case Domain::INET:
return Network::Domain::INET;
default:
UNIMPLEMENTED_MSG("Unimplemented domain={}", static_cast<int>(domain));
return {};
}
}
Domain Translate(Network::Domain domain) {
switch (domain) {
case Network::Domain::INET:
return Domain::INET;
default:
UNIMPLEMENTED_MSG("Unimplemented domain={}", static_cast<int>(domain));
return {};
}
}
Network::Type Translate(Type type) {
switch (type) {
case Type::STREAM:
return Network::Type::STREAM;
case Type::DGRAM:
return Network::Type::DGRAM;
default:
UNIMPLEMENTED_MSG("Unimplemented type={}", static_cast<int>(type));
}
}
Network::Protocol Translate(Type type, Protocol protocol) {
switch (protocol) {
case Protocol::UNSPECIFIED:
LOG_WARNING(Service, "Unspecified protocol, assuming protocol from type");
switch (type) {
case Type::DGRAM:
return Network::Protocol::UDP;
case Type::STREAM:
return Network::Protocol::TCP;
default:
return Network::Protocol::TCP;
}
case Protocol::TCP:
return Network::Protocol::TCP;
case Protocol::UDP:
return Network::Protocol::UDP;
default:
UNIMPLEMENTED_MSG("Unimplemented protocol={}", static_cast<int>(protocol));
return Network::Protocol::TCP;
}
}
u16 TranslatePollEventsToHost(u16 flags) {
u16 result = 0;
const auto translate = [&result, &flags](u16 from, u16 to) {
if ((flags & from) != 0) {
flags &= ~from;
result |= to;
}
};
translate(POLL_IN, Network::POLL_IN);
translate(POLL_PRI, Network::POLL_PRI);
translate(POLL_OUT, Network::POLL_OUT);
translate(POLL_ERR, Network::POLL_ERR);
translate(POLL_HUP, Network::POLL_HUP);
translate(POLL_NVAL, Network::POLL_NVAL);
UNIMPLEMENTED_IF_MSG(flags != 0, "Unimplemented flags={}", flags);
return result;
}
u16 TranslatePollEventsToGuest(u16 flags) {
u16 result = 0;
const auto translate = [&result, &flags](u16 from, u16 to) {
if ((flags & from) != 0) {
flags &= ~from;
result |= to;
}
};
translate(Network::POLL_IN, POLL_IN);
translate(Network::POLL_PRI, POLL_PRI);
translate(Network::POLL_OUT, POLL_OUT);
translate(Network::POLL_ERR, POLL_ERR);
translate(Network::POLL_HUP, POLL_HUP);
translate(Network::POLL_NVAL, POLL_NVAL);
UNIMPLEMENTED_IF_MSG(flags != 0, "Unimplemented flags={}", flags);
return result;
}
Network::SockAddrIn Translate(SockAddrIn value) {
ASSERT(value.len == 0 || value.len == sizeof(value));
Network::SockAddrIn result;
result.family = Translate(static_cast<Domain>(value.family));
result.ip = value.ip;
result.portno = value.portno >> 8 | value.portno << 8;
return result;
}
SockAddrIn Translate(Network::SockAddrIn value) {
SockAddrIn result;
result.len = sizeof(result);
result.family = static_cast<u8>(Translate(value.family));
result.portno = value.portno >> 8 | value.portno << 8;
result.ip = value.ip;
result.zeroes = {};
return result;
}
Network::ShutdownHow Translate(ShutdownHow how) {
switch (how) {
case ShutdownHow::RD:
return Network::ShutdownHow::RD;
case ShutdownHow::WR:
return Network::ShutdownHow::WR;
case ShutdownHow::RDWR:
return Network::ShutdownHow::RDWR;
default:
UNIMPLEMENTED_MSG("Unimplemented how={}", static_cast<int>(how));
return {};
}
}
} // namespace Service::Sockets

View File

@@ -0,0 +1,48 @@
// Copyright 2020 yuzu emulator team
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <utility>
#include "common/common_types.h"
#include "core/hle/service/sockets/sockets.h"
#include "core/network/network.h"
namespace Service::Sockets {
/// Translate abstract errno to guest errno
Errno Translate(Network::Errno value);
/// Translate abstract return value errno pair to guest return value errno pair
std::pair<s32, Errno> Translate(std::pair<s32, Network::Errno> value);
/// Translate guest domain to abstract domain
Network::Domain Translate(Domain domain);
/// Translate abstract domain to guest domain
Domain Translate(Network::Domain domain);
/// Translate guest type to abstract type
Network::Type Translate(Type type);
/// Translate guest protocol to abstract protocol
Network::Protocol Translate(Type type, Protocol protocol);
/// Translate abstract poll event flags to guest poll event flags
u16 TranslatePollEventsToHost(u16 flags);
/// Translate guest poll event flags to abstract poll event flags
u16 TranslatePollEventsToGuest(u16 flags);
/// Translate guest socket address structure to abstract socket address structure
Network::SockAddrIn Translate(SockAddrIn value);
/// Translate abstract socket address structure to guest socket address structure
SockAddrIn Translate(Network::SockAddrIn value);
/// Translate guest shutdown mode to abstract shutdown mode
Network::ShutdownHow Translate(ShutdownHow how);
} // namespace Service::Sockets

View File

@@ -290,7 +290,7 @@ void Module::Interface::GetClockSnapshot(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
ctx.WriteBuffer(clock_snapshot);
ctx.WriteBuffer(&clock_snapshot, sizeof(Clock::ClockSnapshot));
}
void Module::Interface::GetClockSnapshotFromSystemClockContext(Kernel::HLERequestContext& ctx) {
@@ -313,7 +313,7 @@ void Module::Interface::GetClockSnapshotFromSystemClockContext(Kernel::HLEReques
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
ctx.WriteBuffer(clock_snapshot);
ctx.WriteBuffer(&clock_snapshot, sizeof(Clock::ClockSnapshot));
}
void Module::Interface::CalculateStandardUserSystemClockDifferenceByUser(

View File

@@ -142,7 +142,7 @@ void ITimeZoneService::ToPosixTime(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.PushRaw<u32>(1); // Number of times we're returning
ctx.WriteBuffer(posix_time);
ctx.WriteBuffer(&posix_time, sizeof(s64));
}
void ITimeZoneService::ToPosixTimeWithMyRule(Kernel::HLERequestContext& ctx) {
@@ -164,7 +164,7 @@ void ITimeZoneService::ToPosixTimeWithMyRule(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.PushRaw<u32>(1); // Number of times we're returning
ctx.WriteBuffer(posix_time);
ctx.WriteBuffer(&posix_time, sizeof(s64));
}
} // namespace Service::Time

View File

@@ -173,6 +173,7 @@ void RestoreGlobalState() {
values.use_assembly_shaders.SetGlobal(true);
values.use_asynchronous_shaders.SetGlobal(true);
values.use_fast_gpu_time.SetGlobal(true);
values.force_30fps_mode.SetGlobal(true);
values.bg_red.SetGlobal(true);
values.bg_green.SetGlobal(true);
values.bg_blue.SetGlobal(true);

View File

@@ -435,6 +435,7 @@ struct Values {
Setting<bool> use_vsync;
Setting<bool> use_assembly_shaders;
Setting<bool> use_asynchronous_shaders;
Setting<bool> force_30fps_mode;
Setting<bool> use_fast_gpu_time;
Setting<float> bg_red;

View File

@@ -46,16 +46,20 @@ struct ScopeInit final {
Core::Timing::CoreTiming core_timing;
};
#pragma optimize("", off)
u64 TestTimerSpeed(Core::Timing::CoreTiming& core_timing) {
const u64 start = core_timing.GetGlobalTimeNs().count();
volatile u64 placebo = 0;
u64 start = core_timing.GetGlobalTimeNs().count();
u64 placebo = 0;
for (std::size_t i = 0; i < 1000; i++) {
placebo = placebo + core_timing.GetGlobalTimeNs().count();
placebo += core_timing.GetGlobalTimeNs().count();
}
const u64 end = core_timing.GetGlobalTimeNs().count();
return end - start;
u64 end = core_timing.GetGlobalTimeNs().count();
return (end - start);
}
#pragma optimize("", on)
} // Anonymous namespace
TEST_CASE("CoreTiming[BasicOrder]", "[core]") {

View File

@@ -2,8 +2,6 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <array>
#include <bitset>
#include <cstddef>

View File

@@ -74,9 +74,9 @@ SurfaceParams SurfaceParams::CreateForTexture(const FormatLookupTable& lookup_ta
SurfaceParams params;
params.is_tiled = tic.IsTiled();
params.srgb_conversion = tic.IsSrgbConversionEnabled();
params.block_width = params.is_tiled ? tic.BlockWidth() : 0;
params.block_height = params.is_tiled ? tic.BlockHeight() : 0;
params.block_depth = params.is_tiled ? tic.BlockDepth() : 0;
params.block_width = params.is_tiled ? tic.BlockWidth() : 0,
params.block_height = params.is_tiled ? tic.BlockHeight() : 0,
params.block_depth = params.is_tiled ? tic.BlockDepth() : 0,
params.tile_width_spacing = params.is_tiled ? (1 << tic.tile_width_spacing.Value()) : 1;
params.pixel_format = lookup_table.GetPixelFormat(
tic.format, params.srgb_conversion, tic.r_type, tic.g_type, tic.b_type, tic.a_type);
@@ -130,13 +130,14 @@ SurfaceParams SurfaceParams::CreateForImage(const FormatLookupTable& lookup_tabl
SurfaceParams params;
params.is_tiled = tic.IsTiled();
params.srgb_conversion = tic.IsSrgbConversionEnabled();
params.block_width = params.is_tiled ? tic.BlockWidth() : 0;
params.block_height = params.is_tiled ? tic.BlockHeight() : 0;
params.block_depth = params.is_tiled ? tic.BlockDepth() : 0;
params.block_width = params.is_tiled ? tic.BlockWidth() : 0,
params.block_height = params.is_tiled ? tic.BlockHeight() : 0,
params.block_depth = params.is_tiled ? tic.BlockDepth() : 0,
params.tile_width_spacing = params.is_tiled ? (1 << tic.tile_width_spacing.Value()) : 1;
params.pixel_format = lookup_table.GetPixelFormat(
tic.format, params.srgb_conversion, tic.r_type, tic.g_type, tic.b_type, tic.a_type);
params.type = GetFormatType(params.pixel_format);
params.type = GetFormatType(params.pixel_format);
params.target = ImageTypeToSurfaceTarget(entry.type);
// TODO: on 1DBuffer we should use the tic info.
if (tic.IsBuffer()) {
@@ -166,30 +167,27 @@ SurfaceParams SurfaceParams::CreateForImage(const FormatLookupTable& lookup_tabl
SurfaceParams SurfaceParams::CreateForDepthBuffer(Core::System& system) {
const auto& regs = system.GPU().Maxwell3D().regs;
SurfaceParams params;
params.is_tiled = regs.zeta.memory_layout.type ==
Tegra::Engines::Maxwell3D::Regs::InvMemoryLayout::BlockLinear;
params.srgb_conversion = false;
params.block_width = std::min(regs.zeta.memory_layout.block_width.Value(), 5U);
params.block_height = std::min(regs.zeta.memory_layout.block_height.Value(), 5U);
params.block_depth = std::min(regs.zeta.memory_layout.block_depth.Value(), 5U);
params.tile_width_spacing = 1;
params.pixel_format = PixelFormatFromDepthFormat(regs.zeta.format);
params.type = GetFormatType(params.pixel_format);
params.width = regs.zeta_width;
params.height = regs.zeta_height;
params.pitch = 0;
params.num_levels = 1;
params.emulated_levels = 1;
const auto block_depth = std::min(regs.zeta.memory_layout.block_depth.Value(), 5U);
const bool is_layered = regs.zeta_layers > 1 && block_depth == 0;
const auto pixel_format = PixelFormatFromDepthFormat(regs.zeta.format);
return {
.is_tiled = regs.zeta.memory_layout.type ==
Tegra::Engines::Maxwell3D::Regs::InvMemoryLayout::BlockLinear,
.srgb_conversion = false,
.is_layered = is_layered,
.block_width = std::min(regs.zeta.memory_layout.block_width.Value(), 5U),
.block_height = std::min(regs.zeta.memory_layout.block_height.Value(), 5U),
.block_depth = block_depth,
.tile_width_spacing = 1,
.width = regs.zeta_width,
.height = regs.zeta_height,
.depth = is_layered ? regs.zeta_layers.Value() : 1U,
.pitch = 0,
.num_levels = 1,
.emulated_levels = 1,
.pixel_format = pixel_format,
.type = GetFormatType(pixel_format),
.target = is_layered ? SurfaceTarget::Texture2DArray : SurfaceTarget::Texture2D,
};
const bool is_layered = regs.zeta_layers > 1 && params.block_depth == 0;
params.is_layered = is_layered;
params.target = is_layered ? SurfaceTarget::Texture2DArray : SurfaceTarget::Texture2D;
params.depth = is_layered ? regs.zeta_layers.Value() : 1U;
return params;
}
SurfaceParams SurfaceParams::CreateForFramebuffer(Core::System& system, std::size_t index) {
@@ -235,29 +233,24 @@ SurfaceParams SurfaceParams::CreateForFramebuffer(Core::System& system, std::siz
SurfaceParams SurfaceParams::CreateForFermiCopySurface(
const Tegra::Engines::Fermi2D::Regs::Surface& config) {
const bool is_tiled = !config.linear;
const auto pixel_format = PixelFormatFromRenderTargetFormat(config.format);
SurfaceParams params{
.is_tiled = is_tiled,
.srgb_conversion = config.format == Tegra::RenderTargetFormat::B8G8R8A8_SRGB ||
config.format == Tegra::RenderTargetFormat::A8B8G8R8_SRGB,
.block_width = is_tiled ? std::min(config.BlockWidth(), 5U) : 0U,
.block_height = is_tiled ? std::min(config.BlockHeight(), 5U) : 0U,
.block_depth = is_tiled ? std::min(config.BlockDepth(), 5U) : 0U,
.tile_width_spacing = 1,
.width = config.width,
.height = config.height,
.depth = 1,
.pitch = config.pitch,
.num_levels = 1,
.emulated_levels = 1,
.pixel_format = pixel_format,
.type = GetFormatType(pixel_format),
// TODO(Rodrigo): Try to guess texture arrays from parameters
.target = SurfaceTarget::Texture2D,
};
SurfaceParams params{};
params.is_tiled = !config.linear;
params.srgb_conversion = config.format == Tegra::RenderTargetFormat::B8G8R8A8_SRGB ||
config.format == Tegra::RenderTargetFormat::A8B8G8R8_SRGB;
params.block_width = params.is_tiled ? std::min(config.BlockWidth(), 5U) : 0,
params.block_height = params.is_tiled ? std::min(config.BlockHeight(), 5U) : 0,
params.block_depth = params.is_tiled ? std::min(config.BlockDepth(), 5U) : 0,
params.tile_width_spacing = 1;
params.pixel_format = PixelFormatFromRenderTargetFormat(config.format);
params.type = GetFormatType(params.pixel_format);
params.width = config.width;
params.height = config.height;
params.pitch = config.pitch;
// TODO(Rodrigo): Try to guess texture arrays from parameters
params.target = SurfaceTarget::Texture2D;
params.depth = 1;
params.num_levels = 1;
params.emulated_levels = 1;
params.is_layered = params.IsLayered();
return params;
}

View File

@@ -578,6 +578,7 @@ void Config::ReadPathValues() {
UISettings::values.roms_path = ReadSetting(QStringLiteral("romsPath")).toString();
UISettings::values.symbols_path = ReadSetting(QStringLiteral("symbolsPath")).toString();
UISettings::values.screenshot_path = ReadSetting(QStringLiteral("screenshotPath")).toString();
UISettings::values.game_dir_deprecated =
ReadSetting(QStringLiteral("gameListRootDir"), QStringLiteral(".")).toString();
UISettings::values.game_dir_deprecated_deepscan =
@@ -665,6 +666,8 @@ void Config::ReadRendererValues() {
QStringLiteral("use_asynchronous_shaders"), false);
ReadSettingGlobal(Settings::values.use_fast_gpu_time, QStringLiteral("use_fast_gpu_time"),
true);
ReadSettingGlobal(Settings::values.force_30fps_mode, QStringLiteral("force_30fps_mode"), false);
ReadSettingGlobal(Settings::values.bg_red, QStringLiteral("bg_red"), 0.0);
ReadSettingGlobal(Settings::values.bg_green, QStringLiteral("bg_green"), 0.0);
ReadSettingGlobal(Settings::values.bg_blue, QStringLiteral("bg_blue"), 0.0);
@@ -672,22 +675,6 @@ void Config::ReadRendererValues() {
qt_config->endGroup();
}
void Config::ReadScreenshotValues() {
qt_config->beginGroup(QStringLiteral("Screenshots"));
UISettings::values.enable_screenshot_save_as =
ReadSetting(QStringLiteral("enable_screenshot_save_as"), true).toBool();
FileUtil::GetUserPath(
FileUtil::UserPath::ScreenshotsDir,
qt_config
->value(QStringLiteral("screenshot_path"), QString::fromStdString(FileUtil::GetUserPath(
FileUtil::UserPath::ScreenshotsDir)))
.toString()
.toStdString());
qt_config->endGroup();
}
void Config::ReadShortcutValues() {
qt_config->beginGroup(QStringLiteral("Shortcuts"));
@@ -769,7 +756,6 @@ void Config::ReadUIValues() {
ReadUIGamelistValues();
ReadUILayoutValues();
ReadPathValues();
ReadScreenshotValues();
ReadShortcutValues();
UISettings::values.single_window_mode =
@@ -1099,6 +1085,7 @@ void Config::SavePathValues() {
WriteSetting(QStringLiteral("romsPath"), UISettings::values.roms_path);
WriteSetting(QStringLiteral("symbolsPath"), UISettings::values.symbols_path);
WriteSetting(QStringLiteral("screenshotPath"), UISettings::values.screenshot_path);
qt_config->beginWriteArray(QStringLiteral("gamedirs"));
for (int i = 0; i < UISettings::values.game_dirs.size(); ++i) {
qt_config->setArrayIndex(i);
@@ -1166,6 +1153,9 @@ void Config::SaveRendererValues() {
Settings::values.use_asynchronous_shaders, false);
WriteSettingGlobal(QStringLiteral("use_fast_gpu_time"), Settings::values.use_fast_gpu_time,
true);
WriteSettingGlobal(QStringLiteral("force_30fps_mode"), Settings::values.force_30fps_mode,
false);
// Cast to double because Qt's written float values are not human-readable
WriteSettingGlobal(QStringLiteral("bg_red"), Settings::values.bg_red, 0.0);
WriteSettingGlobal(QStringLiteral("bg_green"), Settings::values.bg_green, 0.0);
@@ -1174,17 +1164,6 @@ void Config::SaveRendererValues() {
qt_config->endGroup();
}
void Config::SaveScreenshotValues() {
qt_config->beginGroup(QStringLiteral("Screenshots"));
WriteSetting(QStringLiteral("enable_screenshot_save_as"),
UISettings::values.enable_screenshot_save_as);
WriteSetting(QStringLiteral("screenshot_path"),
QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::ScreenshotsDir)));
qt_config->endGroup();
}
void Config::SaveShortcutValues() {
qt_config->beginGroup(QStringLiteral("Shortcuts"));
@@ -1247,7 +1226,6 @@ void Config::SaveUIValues() {
SaveUIGamelistValues();
SaveUILayoutValues();
SavePathValues();
SaveScreenshotValues();
SaveShortcutValues();
WriteSetting(QStringLiteral("singleWindowMode"), UISettings::values.single_window_mode, true);

View File

@@ -51,7 +51,6 @@ private:
void ReadPathValues();
void ReadCpuValues();
void ReadRendererValues();
void ReadScreenshotValues();
void ReadShortcutValues();
void ReadSystemValues();
void ReadUIValues();
@@ -77,7 +76,6 @@ private:
void SavePathValues();
void SaveCpuValues();
void SaveRendererValues();
void SaveScreenshotValues();
void SaveShortcutValues();
void SaveSystemValues();
void SaveUIValues();

View File

@@ -25,12 +25,14 @@ void ConfigureGraphicsAdvanced::SetConfiguration() {
ui->use_vsync->setEnabled(runtime_lock);
ui->use_assembly_shaders->setEnabled(runtime_lock);
ui->use_asynchronous_shaders->setEnabled(runtime_lock);
ui->force_30fps_mode->setEnabled(runtime_lock);
ui->anisotropic_filtering_combobox->setEnabled(runtime_lock);
ui->use_vsync->setChecked(Settings::values.use_vsync.GetValue());
ui->use_assembly_shaders->setChecked(Settings::values.use_assembly_shaders.GetValue());
ui->use_asynchronous_shaders->setChecked(Settings::values.use_asynchronous_shaders.GetValue());
ui->use_fast_gpu_time->setChecked(Settings::values.use_fast_gpu_time.GetValue());
ui->force_30fps_mode->setChecked(Settings::values.force_30fps_mode.GetValue());
if (Settings::configuring_global) {
ui->gpu_accuracy->setCurrentIndex(
@@ -76,6 +78,9 @@ void ConfigureGraphicsAdvanced::ApplyConfiguration() {
if (Settings::values.use_fast_gpu_time.UsingGlobal()) {
Settings::values.use_fast_gpu_time.SetValue(ui->use_fast_gpu_time->isChecked());
}
if (Settings::values.force_30fps_mode.UsingGlobal()) {
Settings::values.force_30fps_mode.SetValue(ui->force_30fps_mode->isChecked());
}
if (Settings::values.max_anisotropy.UsingGlobal()) {
Settings::values.max_anisotropy.SetValue(
ui->anisotropic_filtering_combobox->currentIndex());
@@ -92,6 +97,8 @@ void ConfigureGraphicsAdvanced::ApplyConfiguration() {
use_asynchronous_shaders);
ConfigurationShared::ApplyPerGameSetting(&Settings::values.use_fast_gpu_time,
ui->use_fast_gpu_time, use_fast_gpu_time);
ConfigurationShared::ApplyPerGameSetting(&Settings::values.force_30fps_mode,
ui->force_30fps_mode, force_30fps_mode);
ConfigurationShared::ApplyPerGameSetting(&Settings::values.max_anisotropy,
ui->anisotropic_filtering_combobox);
@@ -125,6 +132,7 @@ void ConfigureGraphicsAdvanced::SetupPerGameUI() {
ui->use_asynchronous_shaders->setEnabled(
Settings::values.use_asynchronous_shaders.UsingGlobal());
ui->use_fast_gpu_time->setEnabled(Settings::values.use_fast_gpu_time.UsingGlobal());
ui->force_30fps_mode->setEnabled(Settings::values.force_30fps_mode.UsingGlobal());
ui->anisotropic_filtering_combobox->setEnabled(
Settings::values.max_anisotropy.UsingGlobal());
@@ -141,6 +149,8 @@ void ConfigureGraphicsAdvanced::SetupPerGameUI() {
Settings::values.use_asynchronous_shaders, use_asynchronous_shaders);
ConfigurationShared::SetColoredTristate(ui->use_fast_gpu_time, "use_fast_gpu_time",
Settings::values.use_fast_gpu_time, use_fast_gpu_time);
ConfigurationShared::SetColoredTristate(ui->force_30fps_mode, "force_30fps_mode",
Settings::values.force_30fps_mode, force_30fps_mode);
ConfigurationShared::SetColoredComboBox(
ui->gpu_accuracy, ui->label_gpu_accuracy, "label_gpu_accuracy",
static_cast<int>(Settings::values.gpu_accuracy.GetValue(true)));

View File

@@ -38,4 +38,5 @@ private:
ConfigurationShared::CheckState use_assembly_shaders;
ConfigurationShared::CheckState use_asynchronous_shaders;
ConfigurationShared::CheckState use_fast_gpu_time;
ConfigurationShared::CheckState force_30fps_mode;
};

View File

@@ -96,6 +96,13 @@
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="force_30fps_mode">
<property name="text">
<string>Force 30 FPS mode</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="use_fast_gpu_time">
<property name="text">

View File

@@ -4,11 +4,9 @@
#include <array>
#include <utility>
#include <QFileDialog>
#include <QDirIterator>
#include "common/common_types.h"
#include "common/file_util.h"
#include "core/settings.h"
#include "ui_configure_ui.h"
#include "yuzu/configuration/configure_ui.h"
@@ -57,18 +55,6 @@ ConfigureUi::ConfigureUi(QWidget* parent) : QWidget(parent), ui(new Ui::Configur
[=]() { ConfigureUi::UpdateSecondRowComboBox(); });
connect(ui->row_2_text_combobox, QOverload<int>::of(&QComboBox::activated),
[=]() { ConfigureUi::UpdateFirstRowComboBox(); });
// Set screenshot path to user specification.
connect(ui->screenshot_path_button, &QToolButton::pressed, this, [this] {
const QString& filename =
QFileDialog::getExistingDirectory(
this, tr("Select Screenshots Path..."),
QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::ScreenshotsDir))) +
QDir::separator();
if (!filename.isEmpty()) {
ui->screenshot_path_edit->setText(filename);
}
});
}
ConfigureUi::~ConfigureUi() = default;
@@ -80,10 +66,6 @@ void ConfigureUi::ApplyConfiguration() {
UISettings::values.icon_size = ui->icon_size_combobox->currentData().toUInt();
UISettings::values.row_1_text_id = ui->row_1_text_combobox->currentData().toUInt();
UISettings::values.row_2_text_id = ui->row_2_text_combobox->currentData().toUInt();
UISettings::values.enable_screenshot_save_as = ui->enable_screenshot_save_as->isChecked();
FileUtil::GetUserPath(FileUtil::UserPath::ScreenshotsDir,
ui->screenshot_path_edit->text().toStdString());
Settings::Apply();
}
@@ -98,10 +80,6 @@ void ConfigureUi::SetConfiguration() {
ui->show_add_ons->setChecked(UISettings::values.show_add_ons);
ui->icon_size_combobox->setCurrentIndex(
ui->icon_size_combobox->findData(UISettings::values.icon_size));
ui->enable_screenshot_save_as->setChecked(UISettings::values.enable_screenshot_save_as);
ui->screenshot_path_edit->setText(
QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::ScreenshotsDir)));
}
void ConfigureUi::changeEvent(QEvent* event) {

View File

@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>363</width>
<height>391</height>
<width>300</width>
<height>377</height>
</rect>
</property>
<property name="windowTitle">
@@ -127,47 +127,6 @@
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="screenshots_GroupBox">
<property name="title">
<string>Screenshots</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<item>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QCheckBox" name="enable_screenshot_save_as">
<property name="text">
<string>Ask Where To Save Screenshots (Windows Only)</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Screenshots Path: </string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="screenshot_path_edit"/>
</item>
<item>
<widget class="QToolButton" name="screenshot_path_button">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">

View File

@@ -474,56 +474,28 @@ void GameList::PopupContextMenu(const QPoint& menu_location) {
void GameList::AddGamePopup(QMenu& context_menu, u64 program_id, std::string path) {
QAction* open_save_location = context_menu.addAction(tr("Open Save Data Location"));
QAction* open_mod_location = context_menu.addAction(tr("Open Mod Data Location"));
QAction* open_lfs_location = context_menu.addAction(tr("Open Mod Data Location"));
QAction* open_transferable_shader_cache =
context_menu.addAction(tr("Open Transferable Shader Cache"));
context_menu.addSeparator();
QMenu* remove_menu = context_menu.addMenu(tr("Remove"));
QAction* remove_update = remove_menu->addAction(tr("Remove Installed Update"));
QAction* remove_dlc = remove_menu->addAction(tr("Remove All Installed DLC"));
QAction* remove_shader_cache = remove_menu->addAction(tr("Remove Shader Cache"));
QAction* remove_custom_config = remove_menu->addAction(tr("Remove Custom Configuration"));
remove_menu->addSeparator();
QAction* remove_all_content = remove_menu->addAction(tr("Remove All Installed Contents"));
QAction* dump_romfs = context_menu.addAction(tr("Dump RomFS"));
QAction* copy_tid = context_menu.addAction(tr("Copy Title ID to Clipboard"));
QAction* navigate_to_gamedb_entry = context_menu.addAction(tr("Navigate to GameDB entry"));
context_menu.addSeparator();
QAction* properties = context_menu.addAction(tr("Properties"));
open_save_location->setVisible(program_id != 0);
open_mod_location->setVisible(program_id != 0);
open_transferable_shader_cache->setVisible(program_id != 0);
remove_update->setVisible(program_id != 0);
remove_dlc->setVisible(program_id != 0);
remove_shader_cache->setVisible(program_id != 0);
remove_all_content->setVisible(program_id != 0);
open_save_location->setEnabled(program_id != 0);
auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
navigate_to_gamedb_entry->setVisible(it != compatibility_list.end() && program_id != 0);
connect(open_save_location, &QAction::triggered, [this, program_id, path]() {
emit OpenFolderRequested(GameListOpenTarget::SaveData, path);
});
connect(open_mod_location, &QAction::triggered, [this, program_id, path]() {
connect(open_lfs_location, &QAction::triggered, [this, program_id, path]() {
emit OpenFolderRequested(GameListOpenTarget::ModData, path);
});
connect(open_transferable_shader_cache, &QAction::triggered,
[this, program_id]() { emit OpenTransferableShaderCacheRequested(program_id); });
connect(remove_all_content, &QAction::triggered, [this, program_id]() {
emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::Game);
});
connect(remove_update, &QAction::triggered, [this, program_id]() {
emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::Update);
});
connect(remove_dlc, &QAction::triggered, [this, program_id]() {
emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::AddOnContent);
});
connect(remove_shader_cache, &QAction::triggered, [this, program_id]() {
emit RemoveFileRequested(program_id, GameListRemoveTarget::ShaderCache);
});
connect(remove_custom_config, &QAction::triggered, [this, program_id]() {
emit RemoveFileRequested(program_id, GameListRemoveTarget::CustomConfiguration);
});
connect(dump_romfs, &QAction::triggered,
[this, program_id, path]() { emit DumpRomFSRequested(program_id, path); });
connect(copy_tid, &QAction::triggered,

View File

@@ -39,17 +39,6 @@ enum class GameListOpenTarget {
ModData,
};
enum class GameListRemoveTarget {
ShaderCache,
CustomConfiguration,
};
enum class InstalledEntryType {
Game,
Update,
AddOnContent,
};
class GameList : public QWidget {
Q_OBJECT
@@ -86,8 +75,6 @@ signals:
void ShouldCancelWorker();
void OpenFolderRequested(GameListOpenTarget target, const std::string& game_path);
void OpenTransferableShaderCacheRequested(u64 program_id);
void RemoveInstalledEntryRequested(u64 program_id, InstalledEntryType type);
void RemoveFileRequested(u64 program_id, GameListRemoveTarget target);
void DumpRomFSRequested(u64 program_id, const std::string& game_path);
void CopyTIDRequested(u64 program_id);
void NavigateToGamedbEntryRequested(u64 program_id,
@@ -130,6 +117,8 @@ private:
friend class GameListSearchField;
};
Q_DECLARE_METATYPE(GameListOpenTarget);
class GameListPlaceholder : public QWidget {
Q_OBJECT
public:

View File

@@ -847,9 +847,6 @@ void GMainWindow::ConnectWidgetEvents() {
connect(game_list, &GameList::OpenFolderRequested, this, &GMainWindow::OnGameListOpenFolder);
connect(game_list, &GameList::OpenTransferableShaderCacheRequested, this,
&GMainWindow::OnTransferableShaderCacheOpenFile);
connect(game_list, &GameList::RemoveInstalledEntryRequested, this,
&GMainWindow::OnGameListRemoveInstalledEntry);
connect(game_list, &GameList::RemoveFileRequested, this, &GMainWindow::OnGameListRemoveFile);
connect(game_list, &GameList::DumpRomFSRequested, this, &GMainWindow::OnGameListDumpRomFS);
connect(game_list, &GameList::CopyTIDRequested, this, &GMainWindow::OnGameListCopyTID);
connect(game_list, &GameList::NavigateToGamedbEntryRequested, this,
@@ -1260,6 +1257,7 @@ void GMainWindow::OnGameListOpenFolder(GameListOpenTarget target, const std::str
case GameListOpenTarget::SaveData: {
open_target = tr("Save Data");
const std::string nand_dir = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir);
ASSERT(program_id != 0);
if (has_user_save) {
// User save data
@@ -1324,12 +1322,14 @@ void GMainWindow::OnGameListOpenFolder(GameListOpenTarget target, const std::str
}
void GMainWindow::OnTransferableShaderCacheOpenFile(u64 program_id) {
ASSERT(program_id != 0);
const QString shader_dir =
QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::ShaderDir));
const QString transferable_shader_cache_folder_path =
const QString tranferable_shader_cache_folder_path =
shader_dir + QStringLiteral("opengl") + QDir::separator() + QStringLiteral("transferable");
const QString transferable_shader_cache_file_path =
transferable_shader_cache_folder_path + QDir::separator() +
tranferable_shader_cache_folder_path + QDir::separator() +
QString::fromStdString(fmt::format("{:016X}.bin", program_id));
if (!QFile::exists(transferable_shader_cache_file_path)) {
@@ -1350,7 +1350,7 @@ void GMainWindow::OnTransferableShaderCacheOpenFile(u64 program_id) {
param << QDir::toNativeSeparators(transferable_shader_cache_file_path);
QProcess::startDetached(explorer, param);
#else
QDesktopServices::openUrl(QUrl::fromLocalFile(transferable_shader_cache_folder_path));
QDesktopServices::openUrl(QUrl::fromLocalFile(tranferable_shader_cache_folder_path));
#endif
}
@@ -1394,174 +1394,6 @@ static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src
return true;
}
void GMainWindow::OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type) {
const QString entry_type = [this, type] {
switch (type) {
case InstalledEntryType::Game:
return tr("Contents");
case InstalledEntryType::Update:
return tr("Update");
case InstalledEntryType::AddOnContent:
return tr("DLC");
default:
return QString{};
}
}();
if (QMessageBox::question(
this, tr("Remove Entry"), tr("Remove Installed Game %1?").arg(entry_type),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
return;
}
switch (type) {
case InstalledEntryType::Game:
RemoveBaseContent(program_id, entry_type);
[[fallthrough]];
case InstalledEntryType::Update:
RemoveUpdateContent(program_id, entry_type);
if (type != InstalledEntryType::Game) {
break;
}
[[fallthrough]];
case InstalledEntryType::AddOnContent:
RemoveAddOnContent(program_id, entry_type);
break;
}
FileUtil::DeleteDirRecursively(FileUtil::GetUserPath(FileUtil::UserPath::CacheDir) + DIR_SEP +
"game_list");
game_list->PopulateAsync(UISettings::values.game_dirs);
}
void GMainWindow::RemoveBaseContent(u64 program_id, const QString& entry_type) {
const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(program_id) ||
fs_controller.GetSDMCContents()->RemoveExistingEntry(program_id);
if (res) {
QMessageBox::information(this, tr("Successfully Removed"),
tr("Successfully removed the installed base game."));
} else {
QMessageBox::warning(
this, tr("Error Removing %1").arg(entry_type),
tr("The base game is not installed in the NAND and cannot be removed."));
}
}
void GMainWindow::RemoveUpdateContent(u64 program_id, const QString& entry_type) {
const auto update_id = program_id | 0x800;
const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(update_id) ||
fs_controller.GetSDMCContents()->RemoveExistingEntry(update_id);
if (res) {
QMessageBox::information(this, tr("Successfully Removed"),
tr("Successfully removed the installed update."));
} else {
QMessageBox::warning(this, tr("Error Removing %1").arg(entry_type),
tr("There is no update installed for this title."));
}
}
void GMainWindow::RemoveAddOnContent(u64 program_id, const QString& entry_type) {
u32 count{};
const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
const auto dlc_entries = Core::System::GetInstance().GetContentProvider().ListEntriesFilter(
FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
for (const auto& entry : dlc_entries) {
if ((entry.title_id & DLC_BASE_TITLE_ID_MASK) == program_id) {
const auto res =
fs_controller.GetUserNANDContents()->RemoveExistingEntry(entry.title_id) ||
fs_controller.GetSDMCContents()->RemoveExistingEntry(entry.title_id);
if (res) {
++count;
}
}
}
if (count == 0) {
QMessageBox::warning(this, tr("Error Removing %1").arg(entry_type),
tr("There are no DLC installed for this title."));
return;
}
QMessageBox::information(this, tr("Successfully Removed"),
tr("Successfully removed %1 installed DLC.").arg(count));
}
void GMainWindow::OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target) {
const QString question = [this, target] {
switch (target) {
case GameListRemoveTarget::ShaderCache:
return tr("Delete Transferable Shader Cache?");
case GameListRemoveTarget::CustomConfiguration:
return tr("Remove Custom Game Configuration?");
default:
return QString{};
}
}();
if (QMessageBox::question(this, tr("Remove File"), question, QMessageBox::Yes | QMessageBox::No,
QMessageBox::No) != QMessageBox::Yes) {
return;
}
switch (target) {
case GameListRemoveTarget::ShaderCache:
RemoveTransferableShaderCache(program_id);
break;
case GameListRemoveTarget::CustomConfiguration:
RemoveCustomConfiguration(program_id);
break;
}
}
void GMainWindow::RemoveTransferableShaderCache(u64 program_id) {
const QString shader_dir =
QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::ShaderDir));
const QString transferable_shader_cache_folder_path =
shader_dir + QStringLiteral("opengl") + QDir::separator() + QStringLiteral("transferable");
const QString transferable_shader_cache_file_path =
transferable_shader_cache_folder_path + QDir::separator() +
QString::fromStdString(fmt::format("{:016X}.bin", program_id));
if (!QFile::exists(transferable_shader_cache_file_path)) {
QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
tr("A shader cache for this title does not exist."));
return;
}
if (QFile::remove(transferable_shader_cache_file_path)) {
QMessageBox::information(this, tr("Successfully Removed"),
tr("Successfully removed the transferable shader cache."));
} else {
QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
tr("Failed to remove the transferable shader cache."));
}
}
void GMainWindow::RemoveCustomConfiguration(u64 program_id) {
const QString config_dir =
QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::ConfigDir));
const QString custom_config_file_path =
config_dir + QString::fromStdString(fmt::format("{:016X}.ini", program_id));
if (!QFile::exists(custom_config_file_path)) {
QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
tr("A custom configuration for this title does not exist."));
return;
}
if (QFile::remove(custom_config_file_path)) {
QMessageBox::information(this, tr("Successfully Removed"),
tr("Successfully removed the custom game configuration."));
} else {
QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
tr("Failed to remove the custom game configuration."));
}
}
void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path) {
const auto failed = [this] {
QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
@@ -1823,7 +1655,7 @@ void GMainWindow::OnMenuInstallToNAND() {
ui.action_Install_File_NAND->setEnabled(false);
install_progress = new QProgressDialog(QString{}, tr("Cancel"), 0, total_size, this);
install_progress = new QProgressDialog(QStringLiteral(""), tr("Cancel"), 0, total_size, this);
install_progress->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint &
~Qt::WindowMaximizeButtonHint);
install_progress->setAttribute(Qt::WA_DeleteOnClose, true);
@@ -1873,18 +1705,18 @@ void GMainWindow::OnMenuInstallToNAND() {
install_progress->close();
const QString install_results =
(new_files.isEmpty() ? QString{}
(new_files.isEmpty() ? QStringLiteral("")
: tr("%n file(s) were newly installed\n", "", new_files.size())) +
(overwritten_files.isEmpty()
? QString{}
? QStringLiteral("")
: tr("%n file(s) were overwritten\n", "", overwritten_files.size())) +
(failed_files.isEmpty() ? QString{}
(failed_files.isEmpty() ? QStringLiteral("")
: tr("%n file(s) failed to install\n", "", failed_files.size()));
QMessageBox::information(this, tr("Install Results"), install_results);
game_list->PopulateAsync(UISettings::values.game_dirs);
FileUtil::DeleteDirRecursively(FileUtil::GetUserPath(FileUtil::UserPath::CacheDir) + DIR_SEP +
"game_list");
game_list->PopulateAsync(UISettings::values.game_dirs);
ui.action_Install_File_NAND->setEnabled(true);
}
@@ -2321,28 +2153,17 @@ void GMainWindow::OnToggleFilterBar() {
void GMainWindow::OnCaptureScreenshot() {
OnPauseGame();
const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
const auto screenshot_path =
QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::ScreenshotsDir));
const auto date =
QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd_hh-mm-ss-zzz"));
QString filename = QStringLiteral("%1%2_%3.png")
.arg(screenshot_path)
.arg(title_id, 16, 16, QLatin1Char{'0'})
.arg(date);
#ifdef _WIN32
if (UISettings::values.enable_screenshot_save_as) {
filename = QFileDialog::getSaveFileName(this, tr("Capture Screenshot"), filename,
tr("PNG Image (*.png)"));
if (filename.isEmpty()) {
OnStartGame();
return;
QFileDialog png_dialog(this, tr("Capture Screenshot"), UISettings::values.screenshot_path,
tr("PNG Image (*.png)"));
png_dialog.setAcceptMode(QFileDialog::AcceptSave);
png_dialog.setDefaultSuffix(QStringLiteral("png"));
if (png_dialog.exec()) {
const QString path = png_dialog.selectedFiles().first();
if (!path.isEmpty()) {
UISettings::values.screenshot_path = QFileInfo(path).path();
render_window->CaptureScreenshot(UISettings::values.screenshot_resolution_factor, path);
}
}
#endif
render_window->CaptureScreenshot(UISettings::values.screenshot_resolution_factor, filename);
OnStartGame();
}
@@ -2381,7 +2202,8 @@ void GMainWindow::UpdateStatusBar() {
if (shaders_building != 0) {
shader_building_label->setText(
tr("Building: %n shader(s)", "", static_cast<int>(shaders_building)));
tr("Building: %1 shader").arg(shaders_building) +
(shaders_building != 1 ? QString::fromStdString("s") : QString::fromStdString("")));
shader_building_label->setVisible(true);
} else {
shader_building_label->setVisible(false);

View File

@@ -32,8 +32,6 @@ class QPushButton;
class QProgressDialog;
class WaitTreeWidget;
enum class GameListOpenTarget;
enum class GameListRemoveTarget;
enum class InstalledEntryType;
class GameListPlaceholder;
namespace Core::Frontend {
@@ -200,8 +198,6 @@ private slots:
void OnGameListLoadFile(QString game_path);
void OnGameListOpenFolder(GameListOpenTarget target, const std::string& game_path);
void OnTransferableShaderCacheOpenFile(u64 program_id);
void OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type);
void OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target);
void OnGameListDumpRomFS(u64 program_id, const std::string& game_path);
void OnGameListCopyTID(u64 program_id);
void OnGameListNavigateToGamedbEntry(u64 program_id,
@@ -233,11 +229,6 @@ private slots:
void OnLanguageChanged(const QString& locale);
private:
void RemoveBaseContent(u64 program_id, const QString& entry_type);
void RemoveUpdateContent(u64 program_id, const QString& entry_type);
void RemoveAddOnContent(u64 program_id, const QString& entry_type);
void RemoveTransferableShaderCache(u64 program_id);
void RemoveCustomConfiguration(u64 program_id);
std::optional<u64> SelectRomFSDumpTarget(const FileSys::ContentProvider&, u64 program_id);
InstallResult InstallNSPXCI(const QString& filename);
InstallResult InstallNCA(const QString& filename);

View File

@@ -66,11 +66,11 @@ struct Values {
// Discord RPC
bool enable_discord_presence;
bool enable_screenshot_save_as;
u16 screenshot_resolution_factor;
QString roms_path;
QString symbols_path;
QString screenshot_path;
QString game_dir_deprecated;
bool game_dir_deprecated_deepscan;
QVector<UISettings::GameDir> game_dirs;