Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,9 @@
[submodule "3rdparty/mbedtls"]
path = 3rdparty/mbedtls
url = https://github.com/Mbed-TLS/mbedtls.git
[submodule "3rdparty/zstd"]
path = 3rdparty/zstd
url = https://github.com/facebook/zstd.git
[submodule "3rdparty/ZArchive"]
path = 3rdparty/ZArchive
url = https://github.com/Exzap/ZArchive.git
1 change: 1 addition & 0 deletions 3rdparty/ZArchive
Submodule ZArchive added at 965b66
1 change: 1 addition & 0 deletions 3rdparty/zstd
Submodule zstd added at f8745d
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,8 @@ set(LIBUSB_ENABLE_UDEV OFF CACHE BOOL "" FORCE)
add_subdirectory(3rdparty/libusb-cmake EXCLUDE_FROM_ALL)
set_target_properties(usb-1.0 PROPERTIES POSITION_INDEPENDENT_CODE ON)

include(cmake/ZArchive.cmake)

add_subdirectory(core/shader/recompiler)
add_subdirectory(core/Decoder/Jpeg)
add_subdirectory(core/Decoder/Png)
Expand Down
25 changes: 25 additions & 0 deletions cmake/ZArchive.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
enable_language(C)

set(ZSTD_BUILD_PROGRAMS OFF CACHE BOOL "" FORCE)
set(ZSTD_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(ZSTD_BUILD_CONTRIB OFF CACHE BOOL "" FORCE)
set(ZSTD_BUILD_SHARED OFF CACHE BOOL "" FORCE)
set(ZSTD_BUILD_STATIC ON CACHE BOOL "" FORCE)
set(ZSTD_LEGACY_SUPPORT OFF CACHE BOOL "" FORCE)
set(ZSTD_MULTITHREAD_SUPPORT OFF CACHE BOOL "" FORCE)
add_subdirectory(${CMAKE_SOURCE_DIR}/3rdparty/zstd/build/cmake ${CMAKE_BINARY_DIR}/3rdparty/zstd EXCLUDE_FROM_ALL)
set_target_properties(libzstd_static PROPERTIES POSITION_INDEPENDENT_CODE ON)

set(ZARCHIVE_SOURCE_DIR ${CMAKE_SOURCE_DIR}/3rdparty/ZArchive)
add_library(zarchive STATIC EXCLUDE_FROM_ALL
${ZARCHIVE_SOURCE_DIR}/src/zarchivereader.cpp
${ZARCHIVE_SOURCE_DIR}/src/zarchivewriter.cpp
${ZARCHIVE_SOURCE_DIR}/src/sha_256.c
)
target_include_directories(zarchive SYSTEM PUBLIC ${ZARCHIVE_SOURCE_DIR}/include)
target_compile_features(zarchive PUBLIC cxx_std_20)
target_link_libraries(zarchive PRIVATE libzstd_static)
set_target_properties(zarchive PROPERTIES POSITION_INDEPENDENT_CODE ON)
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_link_options(zarchive INTERFACE LINKER:--exclude-libs,libzarchive.a:libzstd.a)
endif()
17 changes: 17 additions & 0 deletions core/libs/prx/libc/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
target_sources(libc PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/Export.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/General.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/AppArchive.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/CreationMask.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/FailureReport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/specifics/gcc/StackGuard.cpp
Expand Down Expand Up @@ -57,6 +58,8 @@ target_include_directories(libc PRIVATE
${LIBS_INCLUDE_DIR}
)

target_link_libraries(libc PRIVATE zarchive)

if(WIN32)
target_link_libraries(libc PRIVATE advapi32 ws2_32 iphlpapi)
endif()
Expand All @@ -71,6 +74,20 @@ if(BUILD_TESTING)
set_tests_properties(guest_allocating_strings PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()

add_test_executable(guest_app_archive_tests ${LIBS_INCLUDE_DIR}/tests/GuestAppArchive.cpp)
target_include_directories(guest_app_archive_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_app_archive_tests PRIVATE libc zarchive)
configure_windows_unwind(guest_app_archive_tests)
foreach(mode present absent damaged invalid)
add_test(NAME guest_app_archive_${mode} COMMAND guest_app_archive_tests ${mode})
set_tests_properties(guest_app_archive_${mode} PROPERTIES TIMEOUT 20)
if(WIN32)
set_tests_properties(guest_app_archive_${mode} PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endforeach()

add_test_executable(guest_array_callbacks_tests ${LIBS_INCLUDE_DIR}/tests/GuestArrayCallbacks.cpp)
target_include_directories(guest_array_callbacks_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_array_callbacks_tests PRIVATE libc)
Expand Down
48 changes: 48 additions & 0 deletions core/libs/prx/libc/include/AppArchive.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#ifndef CORE_LIBS_PRX_LIBC_INCLUDE_APPARCHIVE_HPP
#define CORE_LIBS_PRX_LIBC_INCLUDE_APPARCHIVE_HPP

#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <string>
#include <vector>

struct AppArchiveNode {
std::uint32_t Handle;
bool Directory;
std::uint64_t Size;
};

struct AppArchiveBuffer {
void* Base;
std::size_t Length;
};

struct AppArchiveDirectoryEntry {
std::string Name;
bool Directory;
};

extern "C" {

bool AppArchiveLookup_nid_no_patch(const std::filesystem::path& hostPath, AppArchiveNode* node);
std::uint64_t AppArchiveRead_nid_no_patch(std::uint32_t handle, std::uint64_t offset, void* buffer, std::uint64_t length);
std::vector<AppArchiveDirectoryEntry> AppArchiveList_nid_no_patch(std::uint32_t handle);
void AppArchiveReady_nid_no_patch();
void AppArchiveRefuseOnly_nid_no_patch(const std::filesystem::path& hostPath, const char* guestPath, const char* operation);
void AppArchiveRefuseMergedListing_nid_no_patch(const std::filesystem::path& hostPath, const char* guestPath);
void AppArchiveRefuseDescriptor_nid_no_patch(int descriptor, const char* operation);
std::filesystem::path AppArchivePath_nid_no_patch();
bool AppArchiveOnly_nid_no_patch(const std::filesystem::path& hostPath);
bool AppArchiveHasDirectory_nid_no_patch(const std::filesystem::path& hostPath);

void AppArchiveAttach_nid_no_patch(int descriptor, const AppArchiveNode& node);
void AppArchiveShare_nid_no_patch(int from, int to);
void AppArchiveDetach_nid_no_patch(int descriptor);
bool AppArchiveDescriptor_nid_no_patch(int descriptor, AppArchiveNode* node, std::uint64_t* position);
bool AppArchiveDescriptorRead_nid_no_patch(int descriptor, const AppArchiveBuffer* buffers, int count, const std::int64_t* offset, std::uint64_t* read);
bool AppArchiveDescriptorSeek_nid_no_patch(int descriptor, std::int64_t offset, int whence, std::int64_t* position);

}

#endif
4 changes: 2 additions & 2 deletions core/libs/prx/libc/include/FilesystemError.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ inline int FilesystemError(const std::error_code& error) {

std::error_code RenameNative_nid_no_patch(const std::filesystem::path& source, const std::filesystem::path& destination, bool replacesFile);

inline int ResolvePathError_nid_no_patch(const char* path, std::filesystem::path& resolved, bool module = false) {
inline int ResolvePathError_nid_no_patch(const char* path, std::filesystem::path& resolved, bool module = false, bool archived = false) {
try {
resolved = module ? ResolvePathOrRelinkedModule_nid_no_patch(path) : ResolvePath_nid_no_patch(path);
resolved = archived ? ResolveArchivedPath_nid_no_patch(path, module) : module ? ResolvePathOrRelinkedModule_nid_no_patch(path) : ResolvePath_nid_no_patch(path);
return 0;
} catch (const std::filesystem::filesystem_error& error) {
if (error.code() == std::errc::illegal_byte_sequence) return 2;
Expand Down
2 changes: 2 additions & 0 deletions core/libs/prx/libc/include/General.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ extern "C" int HostStandardError_nid_no_patch();

extern "C" std::filesystem::path ResolvePath_nid_no_patch(const char* path);
extern "C" std::filesystem::path ResolvePathOrRelinkedModule_nid_no_patch(const char* path);
extern "C" std::filesystem::path ResolveArchivedPath_nid_no_patch(const char* path, bool module = false);
extern "C" std::filesystem::path ResolveDiskPath_nid_no_patch(const char* path);
extern "C" std::filesystem::path RelinkedModulePath_nid_no_patch(const std::filesystem::path& path);
extern "C" int SetWorkingDirectory_nid_no_patch(const char* resolved);
extern "C" bool FinalPathComponentIsDot_nid_no_patch(const char* path);
Expand Down
239 changes: 239 additions & 0 deletions core/libs/prx/libc/src/AppArchive.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
#include "prx/libc/include/AppArchive.hpp"
#include "prx/libc/include/General.hpp"

#include <zarchive/zarchivereader.h>

#include <algorithm>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <string_view>

namespace {

struct Archive {
std::mutex mutex;
bool opened = false;
std::unique_ptr<ZArchiveReader> reader;
std::filesystem::path path;
std::filesystem::path app0;
};

Archive& State() {
static Archive archive;
return archive;
}

bool SameComponent(std::string_view left, std::string_view right) {
if (left.size() != right.size()) return false;
const auto fold = [](unsigned char value) { return value >= 'A' && value <= 'Z' ? value + ('a' - 'A') : value; };
for (std::size_t i = 0; i < left.size(); ++i) if (fold(left[i]) != fold(right[i])) return false;
return true;
}

Archive& Opened() {
auto& archive = State();
std::lock_guard lock(archive.mutex);
if (archive.opened) return archive;
const auto app0 = ResolveDiskPath_nid_no_patch("/app0").lexically_normal();
auto candidate = app0;
candidate += ".zar";
std::error_code error;
if (std::filesystem::is_regular_file(candidate, error)) {
archive.reader.reset(ZArchiveReader::OpenFromFile(candidate));
if (!archive.reader) throw std::runtime_error("app0.zar is not a readable ZArchive: " + candidate.string());
archive.path = candidate;
}
archive.app0 = app0;
archive.opened = true;
return archive;
}

bool ArchiveRelative(const Archive& archive, const std::filesystem::path& hostPath, std::string& relative) {
const auto normal = hostPath.lexically_normal();
auto part = normal.begin();
for (const auto& component : archive.app0) {
if (part == normal.end() || !SameComponent(part->generic_string(), component.generic_string())) return false;
++part;
}
relative.clear();
for (; part != normal.end(); ++part) {
const auto name = part->generic_string();
if (name.empty() || name == ".") continue;
if (name == "..") return false;
if (!relative.empty()) relative += '/';
relative += name;
}
return true;
}

struct OpenFile {
AppArchiveNode node;
std::uint64_t position = 0;
std::mutex mutex;
};

std::mutex g_descriptorMutex;
std::map<int, std::shared_ptr<OpenFile>> g_descriptors;

std::shared_ptr<OpenFile> Attached(int descriptor) {
std::lock_guard lock(g_descriptorMutex);
const auto found = g_descriptors.find(descriptor);
return found == g_descriptors.end() ? nullptr : found->second;
}

ZArchiveReader& Reader(std::uint32_t handle) {
auto& archive = Opened();
if (!archive.reader) throw std::logic_error("app0.zar handle " + std::to_string(handle) + " used without an archive");
return *archive.reader;
}

}

extern "C" {

bool AppArchiveLookup_nid_no_patch(const std::filesystem::path& hostPath, AppArchiveNode* node) {
if (node == nullptr) throw std::invalid_argument("AppArchiveLookup: null node");
auto& archive = Opened();
if (!archive.reader) return false;
std::string relative;
if (!ArchiveRelative(archive, hostPath, relative)) return false;
const auto handle = archive.reader->LookUp(relative);
if (handle == ZARCHIVE_INVALID_NODE) return false;
node->Handle = handle;
node->Directory = archive.reader->IsDirectory(handle);
node->Size = node->Directory ? 0 : archive.reader->GetFileSize(handle);
return true;
}

std::uint64_t AppArchiveRead_nid_no_patch(std::uint32_t handle, std::uint64_t offset, void* buffer, std::uint64_t length) {
auto& reader = Reader(handle);
if (!reader.IsFile(handle)) throw std::invalid_argument("AppArchiveRead: handle " + std::to_string(handle) + " is not a file");
const auto size = reader.GetFileSize(handle);
if (length == 0 || offset >= size) return 0;
if (buffer == nullptr) throw std::invalid_argument("AppArchiveRead: null buffer");
const auto expected = std::min(length, size - offset);
const auto read = reader.ReadFromFile(handle, offset, length, buffer);
if (read != expected) throw std::runtime_error("app0.zar is damaged: a compressed block of handle " + std::to_string(handle) + " cannot be read");
return read;
}

std::vector<AppArchiveDirectoryEntry> AppArchiveList_nid_no_patch(std::uint32_t handle) {
auto& reader = Reader(handle);
if (!reader.IsDirectory(handle)) throw std::invalid_argument("AppArchiveList: handle " + std::to_string(handle) + " is not a directory");
std::vector<AppArchiveDirectoryEntry> entries;
const auto count = reader.GetDirEntryCount(handle);
entries.reserve(count);
for (std::uint32_t index = 0; index < count; ++index) {
ZArchiveReader::DirEntry entry{};
if (!reader.GetDirEntry(handle, index, entry)) throw std::runtime_error("app0.zar is damaged: directory entry " + std::to_string(index) + " cannot be read");
entries.push_back({std::string(entry.name), entry.isDirectory});
}
return entries;
}

void AppArchiveReady_nid_no_patch() {
(void)Opened();
}

void AppArchiveRefuseOnly_nid_no_patch(const std::filesystem::path& hostPath, const char* guestPath, const char* operation) {
if (AppArchiveOnly_nid_no_patch(hostPath)) NotImplemented_nid_no_patch((std::string(operation) + " " + guestPath + " in app0.zar").c_str());
}

void AppArchiveRefuseMergedListing_nid_no_patch(const std::filesystem::path& hostPath, const char* guestPath) {
if (AppArchiveHasDirectory_nid_no_patch(hostPath)) NotImplemented_nid_no_patch((std::string("listing ") + guestPath + " merged with app0.zar").c_str());
}

void AppArchiveRefuseDescriptor_nid_no_patch(int descriptor, const char* operation) {
if (AppArchiveDescriptor_nid_no_patch(descriptor, nullptr, nullptr)) NotImplemented_nid_no_patch((std::string(operation) + " of a file read from app0.zar").c_str());
}

std::filesystem::path AppArchivePath_nid_no_patch() {
return Opened().path;
}

bool AppArchiveOnly_nid_no_patch(const std::filesystem::path& hostPath) {
auto& archive = Opened();
if (!archive.reader) return false;
std::error_code error;
const auto status = std::filesystem::symlink_status(hostPath, error);
if (std::filesystem::exists(status) || (error && error != std::errc::no_such_file_or_directory)) return false;
AppArchiveNode node{};
return AppArchiveLookup_nid_no_patch(hostPath, &node);
}

bool AppArchiveHasDirectory_nid_no_patch(const std::filesystem::path& hostPath) {
AppArchiveNode node{};
return AppArchiveLookup_nid_no_patch(hostPath, &node) && node.Directory;
}

void AppArchiveAttach_nid_no_patch(int descriptor, const AppArchiveNode& node) {
if (node.Directory) throw std::invalid_argument("AppArchiveAttach: descriptor " + std::to_string(descriptor) + " cannot hold an app0.zar directory");
auto file = std::make_shared<OpenFile>();
file->node = node;
std::lock_guard lock(g_descriptorMutex);
g_descriptors[descriptor] = std::move(file);
}

void AppArchiveShare_nid_no_patch(int from, int to) {
std::lock_guard lock(g_descriptorMutex);
const auto found = g_descriptors.find(from);
if (found == g_descriptors.end()) g_descriptors.erase(to);
else g_descriptors[to] = found->second;
}

void AppArchiveDetach_nid_no_patch(int descriptor) {
std::lock_guard lock(g_descriptorMutex);
g_descriptors.erase(descriptor);
}

bool AppArchiveDescriptor_nid_no_patch(int descriptor, AppArchiveNode* node, std::uint64_t* position) {
const auto file = Attached(descriptor);
if (!file) return false;
std::lock_guard lock(file->mutex);
if (node != nullptr) *node = file->node;
if (position != nullptr) *position = file->position;
return true;
}

bool AppArchiveDescriptorRead_nid_no_patch(int descriptor, const AppArchiveBuffer* buffers, int count, const std::int64_t* offset, std::uint64_t* read) {
const auto file = Attached(descriptor);
if (!file) return false;
if (read == nullptr || count < 0 || (buffers == nullptr && count != 0)) throw std::invalid_argument("AppArchiveDescriptorRead: invalid arguments for descriptor " + std::to_string(descriptor));
if (offset != nullptr && *offset < 0) throw std::invalid_argument("AppArchiveDescriptorRead: negative offset for descriptor " + std::to_string(descriptor));
std::lock_guard lock(file->mutex);
auto cursor = offset != nullptr ? static_cast<std::uint64_t>(*offset) : file->position;
std::uint64_t total = 0;
for (int i = 0; i < count; ++i) {
const auto done = AppArchiveRead_nid_no_patch(file->node.Handle, cursor, buffers[i].Base, buffers[i].Length);
cursor += done;
total += done;
if (done < buffers[i].Length) break;
}
if (offset == nullptr) file->position = cursor;
*read = total;
return true;
}

bool AppArchiveDescriptorSeek_nid_no_patch(int descriptor, std::int64_t offset, int whence, std::int64_t* position) {
const auto file = Attached(descriptor);
if (!file) return false;
if (position == nullptr) throw std::invalid_argument("AppArchiveDescriptorSeek: null position");
std::lock_guard lock(file->mutex);
constexpr auto limit = std::numeric_limits<std::int64_t>::max();
std::int64_t base = 0;
if (whence == 1) base = static_cast<std::int64_t>(file->position);
else if (whence == 2) base = static_cast<std::int64_t>(file->node.Size);
else if (whence != 0) throw std::invalid_argument("AppArchiveDescriptorSeek: invalid whence " + std::to_string(whence));
if ((offset > 0 && base > limit - offset) || base + offset < 0) {
*position = -1;
return true;
}
file->position = static_cast<std::uint64_t>(base + offset);
*position = base + offset;
return true;
}

}
Loading
Loading