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
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
[submodule "3rdparty/SDL2"]
path = 3rdparty/SDL2
url = https://github.com/libsdl-org/SDL.git
[submodule "3rdparty/libressl-openbsd"]
path = 3rdparty/libressl-openbsd
url = https://github.com/libressl/openbsd.git
[submodule "3rdparty/Vulkan-Headers"]
path = 3rdparty/Vulkan-Headers
url = https://github.com/KhronosGroup/Vulkan-Headers.git
Expand Down
1 change: 1 addition & 0 deletions 3rdparty/libressl-openbsd
Submodule libressl-openbsd added at 078b3d
1 change: 1 addition & 0 deletions core/libs/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ elseif(TARGET mimalloc)
endif()

add_custom_target(libs DEPENDS ${PATCHED_OUTPUTS})
include(prx/libSceLibreSsl/ErrorQueue.cmake)

include(prx/libSceLibreSsl/ProtocolSelection.cmake)

Expand Down
33 changes: 33 additions & 0 deletions core/libs/prx/libSceLibreSsl/ErrorQueue.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
target_sources(libSceLibreSsl PRIVATE ${CMAKE_CURRENT_LIST_DIR}/ErrorQueue.cpp)
target_link_libraries(libSceLibreSsl3 PRIVATE libSceLibreSsl)

if(BUILD_TESTING)
find_package(Python3 REQUIRED COMPONENTS Interpreter)
set(libreSslSource ${PROJECT_SOURCE_DIR}/3rdparty/libressl-openbsd/src/lib/libcrypto)
if(NOT EXISTS ${libreSslSource}/err/err.c)
message(FATAL_ERROR "Initialize 3rdparty/libressl-openbsd with git submodule update --init")
endif()
file(GLOB_RECURSE libreSslStringSources CONFIGURE_DEPENDS ${libreSslSource}/*.h ${libreSslSource}/*.c)
set(libreSslStrings ${CMAKE_CURRENT_BINARY_DIR}/prx/libSceLibreSsl/ErrorStrings.inc)
add_custom_command(OUTPUT ${libreSslStrings}
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_LIST_DIR}/GenerateErrorStrings.py ${libreSslSource} ${libreSslStrings}
DEPENDS ${CMAKE_CURRENT_LIST_DIR}/GenerateErrorStrings.py ${libreSslStringSources}
VERBATIM)

add_test_executable(guest_libressl_error_string_tests ${LIBS_INCLUDE_DIR}/tests/GuestLibreSslErrors.cpp)
target_include_directories(guest_libressl_error_string_tests PRIVATE ${LIBS_INCLUDE_DIR}
${CMAKE_CURRENT_BINARY_DIR}/prx/libSceLibreSsl)
target_sources(guest_libressl_error_string_tests PRIVATE ${libreSslStrings})
target_link_libraries(guest_libressl_error_string_tests PRIVATE libSceLibreSsl libSceLibreSsl3)
configure_windows_unwind(guest_libressl_error_string_tests)
add_test(NAME guest_libressl_errors COMMAND guest_libressl_error_string_tests)
add_test(NAME guest_libressl_free_strings COMMAND guest_libressl_error_string_tests free)
add_test(NAME guest_libressl_free_strings_first COMMAND guest_libressl_error_string_tests free-first)
set_tests_properties(guest_libressl_errors guest_libressl_free_strings
guest_libressl_free_strings_first PROPERTIES TIMEOUT 15)
if(WIN32)
set_tests_properties(guest_libressl_errors guest_libressl_free_strings
guest_libressl_free_strings_first PROPERTIES
ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceLibreSsl>")
endif()
endif()
41 changes: 41 additions & 0 deletions core/libs/prx/libSceLibreSsl/ErrorQueue.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include "ErrorQueue.hpp"
#include "prx/libc/include/General.hpp"
#include <cstdio>
#include <cstring>

namespace {
char errorBuffer[256];
}

extern "C" {
char* APS5_VABI ERR_error_string_nid_postfix(std::uint64_t error, char* buffer) {
if (buffer == nullptr) buffer = errorBuffer;
ERR_error_string_n_nid_postfix(error, buffer, sizeof(errorBuffer));
return buffer;
}

void APS5_VABI ERR_error_string_n_nid_postfix(std::uint64_t error, char* buffer, std::size_t length) {
if (buffer == nullptr && length != 0) NotImplemented_nid_no_patch(__func__);
const int library = (error >> 24) & 255;
const int function = (error >> 12) & 4095;
const int reason = error & 4095;
const int written = std::snprintf(buffer, length, "error:%08llX:lib(%d):func(%d):reason(%d)",
static_cast<unsigned long long>(error), library, function, reason);
if (written >= 0 && static_cast<std::size_t>(written) >= length && length > 4) {
char* next = buffer;
for (std::size_t index = 0; index < 4; ++index) {
char* colon = std::strchr(next, ':');
char* last = buffer + length - 5 + index;
if (colon == nullptr || colon > last) {
colon = last;
*colon = ':';
}
next = colon + 1;
}
}
}

void APS5_VABI ERR_free_strings_nid_postfix() {
}

}
15 changes: 15 additions & 0 deletions core/libs/prx/libSceLibreSsl/ErrorQueue.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#ifndef CORE_LIBS_PRX_LIBSCELIBRESSL_ERRORQUEUE_HPP
#define CORE_LIBS_PRX_LIBSCELIBRESSL_ERRORQUEUE_HPP

#include <cstddef>
#include <cstdint>
#include "include/Error.hpp"
#include "libSceLibreSsl.hpp"
#include "prx/libc/include/general/VabiMacros.hpp"

extern "C" {
std::uint64_t LibreSslPeekLastError_nid_no_patch();

}

#endif
15 changes: 0 additions & 15 deletions core/libs/prx/libSceLibreSsl/Export.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -449,21 +449,6 @@ int APS5_VABI ENGINE_set_default_nid_postfix(void) {
return 0;
}

int APS5_VABI ERR_error_string_nid_postfix(void) {
NotImplemented_nid_no_patch(__func__);
return 0;
}

int APS5_VABI ERR_error_string_n_nid_postfix(void) {
NotImplemented_nid_no_patch(__func__);
return 0;
}

int APS5_VABI ERR_free_strings_nid_postfix(void) {
NotImplemented_nid_no_patch(__func__);
return 0;
}

int APS5_VABI EVP_CIPHER_CTX_cleanup_nid_postfix(void) {
NotImplemented_nid_no_patch(__func__);
return 0;
Expand Down
97 changes: 97 additions & 0 deletions core/libs/prx/libSceLibreSsl/GenerateErrorStrings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import ast
import json
import operator
from pathlib import Path
import re
import sys


source = Path(sys.argv[1])
destination = Path(sys.argv[2])
macros = {}
operations = {ast.BitOr: operator.or_, ast.BitAnd: operator.and_, ast.LShift: operator.lshift,
ast.RShift: operator.rshift, ast.Add: operator.add, ast.Sub: operator.sub}


def uncomment(text):
return re.sub(r"/\*.*?\*/", "", text, flags=re.S)


for header in sorted(source.rglob("*.h")):
for name, value in re.findall(r"^#\s*define\s+(\w+)\s+([^\n]+)", uncomment(header.read_text(encoding="utf-8")), re.M):
if re.fullmatch(r"ERR_(?:LIB|R)_\w+|\w+_[RF]_\w+", name):
if name in macros and macros[name] != value.strip():
raise ValueError(f"Conflicting definition: {name}")
macros[name] = value.strip()


def evaluate(expression):
def visit(node):
if isinstance(node, ast.Constant) and type(node.value) is int:
return node.value
if isinstance(node, ast.Name):
return evaluate(macros[node.id])
if isinstance(node, ast.BinOp) and type(node.op) in operations:
return operations[type(node.op)](visit(node.left), visit(node.right))
raise ValueError(f"Unsupported constant: {expression}")
return visit(ast.parse(expression, mode="eval").body)


def pack(library, function, reason):
return ((library & 255) << 24) | ((function & 4095) << 12) | (reason & 4095)


def code(expression, library):
call = re.fullmatch(r"ERR_(PACK|FUNC|REASON)\((.*)\)", expression.strip())
if call:
values = [evaluate(value.strip()) for value in call[2].split(",")]
if call[1] == "PACK":
return pack(*values)
if call[1] == "FUNC":
return pack(library, values[0], 0)
return pack(library, 0, values[0])
return evaluate(expression.strip())


loader = uncomment((source / "err/err_all.c").read_text(encoding="utf-8"))
loaded = set(re.findall(r"\bERR_load_(\w+)_strings\(\);", loader)) - {"ERR"}
strings = {}
licenses = []
found = set()
for path in sorted(source.rglob("*.c")):
text = path.read_text(encoding="latin-1")
clean = uncomment(text)
library = 0
if path != source / "err/err.c":
names = set(re.findall(r"\bERR_load_(\w+)_strings\(void\)", clean)) & loaded
if not names:
continue
found.update(names)
library_name = re.search(r"#define ERR_FUNC\(func\)\s+ERR_PACK\((\w+),", clean)
if not library_name:
raise ValueError(f"Missing library: {path}")
library = evaluate(library_name[1])
licenses.append(text[:text.index("#include")])
tables = re.findall(r"static ERR_STRING_DATA (\w+)\[\]\s*=\s*\{(.*?)\n\};", clean, re.S)
if not tables:
raise ValueError(f"Missing string tables: {path}")
for name, body in tables:
entries = re.findall(r'\{\s*([^{}]+?),\s*("(?:[^"\\]|\\.)*"|NULL)\s*\}', body, re.S)
remainder = re.sub(r'\{\s*([^{}]+?),\s*("(?:[^"\\]|\\.)*"|NULL)\s*\}', "", body, flags=re.S)
if remainder.strip(" \t\r\n,"):
raise ValueError(f"Unsupported table: {path}: {name}")
for expression, message in entries:
value = code(expression, library)
if value == 0 and message == "NULL":
continue
if message == "NULL":
raise ValueError(f"Missing message: {path}: {expression}")
if name == "ERR_str_functs":
value |= pack(evaluate("ERR_LIB_SYS"), 0, 0)
strings[value] = json.loads(message)
if found != loaded:
raise ValueError(f"Missing libraries: {loaded - found}")
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text("\n".join(licenses) + "\nconstexpr ErrorString CryptoStrings[] = {\n" +
"".join(f" {{0x{value:08X}, {json.dumps(message)}}},\n"
for value, message in sorted(strings.items())) + "};\n", encoding="utf-8")
6 changes: 3 additions & 3 deletions core/libs/prx/libSceLibreSsl/include/Api.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -342,9 +342,9 @@ int APS5_VABI ENGINE_load_builtin_engines_nid_postfix(void);
int APS5_VABI ENGINE_load_private_key_nid_postfix(void);
int APS5_VABI ENGINE_set_default_nid_postfix(void);
void APS5_VABI ERR_clear_error_nid_postfix(void);
int APS5_VABI ERR_error_string_nid_postfix(void);
int APS5_VABI ERR_error_string_n_nid_postfix(void);
int APS5_VABI ERR_free_strings_nid_postfix(void);
char* APS5_VABI ERR_error_string_nid_postfix(std::uint64_t error, char* buffer);
void APS5_VABI ERR_error_string_n_nid_postfix(std::uint64_t error, char* buffer, std::size_t length);
void APS5_VABI ERR_free_strings_nid_postfix();
std::uint64_t APS5_VABI ERR_get_error_nid_postfix(void);
std::uint64_t APS5_VABI ERR_peek_error_nid_postfix(void);
void APS5_VABI ERR_remove_thread_state_nid_postfix(const void* threadId);
Expand Down
2 changes: 1 addition & 1 deletion core/libs/prx/libSceLibreSsl/include/Error.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

extern "C" {

void LibreSslPutError_nid_no_patch(int library, int function, int reason);
void LibreSslPutError_nid_no_patch(int library, int function, int reason, const char* file = nullptr, int line = 0);

}

Expand Down
19 changes: 16 additions & 3 deletions core/libs/prx/libSceLibreSsl/src/Error.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#include "prx/libSceLibreSsl/include/Api.hpp"
#include <array>
#include <cerrno>
#include <cstdint>
#include <type_traits>
#include "prx/libSceLibreSsl/libSceLibreSsl.hpp"
#include "prx/libSceLibreSsl/include/Error.hpp"
#include "prx/libc/include/General.hpp"

Expand All @@ -10,6 +11,8 @@ constexpr int QueueSize = 16;

struct ErrorQueue {
std::array<std::uint64_t, QueueSize> codes;
std::array<const char*, QueueSize> files;
std::array<int, QueueSize> lines;
int top;
int bottom;
};
Expand All @@ -25,6 +28,8 @@ std::uint64_t Oldest(bool remove) {
if (remove) {
queue.bottom = index;
queue.codes[index] = 0;
queue.files[index] = nullptr;
queue.lines[index] = 0;
}
return code;
}
Expand All @@ -36,12 +41,20 @@ void Clear() {

extern "C" {

void LibreSslPutError_nid_no_patch(int library, int function, int reason) {
void LibreSslPutError_nid_no_patch(int library, int function, int reason, const char* file, int line) {
const int savedError = errno;
queue.top = (queue.top + 1) % QueueSize;
if (queue.top == queue.bottom) queue.bottom = (queue.bottom + 1) % QueueSize;
queue.codes[queue.top] = (static_cast<std::uint64_t>(library) & 0xff) << 24 |
(static_cast<std::uint64_t>(function) & 0xfff) << 12 |
(static_cast<std::uint64_t>(reason) & 0xfff);
queue.files[queue.top] = file;
queue.lines[queue.top] = line;
errno = savedError;
}

std::uint64_t LibreSslPeekLastError_nid_no_patch() {
return queue.top == queue.bottom ? 0 : queue.codes[queue.top];
}

std::uint64_t APS5_VABI ERR_get_error_nid_postfix() {
Expand All @@ -57,7 +70,7 @@ void APS5_VABI ERR_clear_error_nid_postfix() {
}

void APS5_VABI ERR_remove_thread_state_nid_postfix(const void* threadId) {
if (threadId != nullptr) NotImplemented_nid_no_patch("ERR_remove_thread_state of a CRYPTO_THREADID");
if (threadId != nullptr) NotImplemented_nid_no_patch(__func__);
Clear();
}

Expand Down
10 changes: 4 additions & 6 deletions core/libs/prx/libSceLibreSsl3/Export.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include <cstddef>
#include <cstdint>
#include "SceTypes.hpp"
#include "prx/libSceLibreSsl/ErrorQueue.hpp"
#include "prx/libc/include/General.hpp"

extern "C" {
Expand Down Expand Up @@ -61,14 +62,11 @@ int APS5_VABI DSA_get0_pqg_nid_postfix(void) {
return 0;
}

int APS5_VABI ERR_load_crypto_strings_nid_postfix(void) {
NotImplemented_nid_no_patch(__func__);
return 0;
void APS5_VABI ERR_load_crypto_strings_nid_postfix() {
}

int APS5_VABI ERR_peek_last_error_nid_postfix(void) {
NotImplemented_nid_no_patch(__func__);
return 0;
std::uint64_t APS5_VABI ERR_peek_last_error_nid_postfix() {
return LibreSslPeekLastError_nid_no_patch();
}

int APS5_VABI ERR_print_errors_cb_nid_postfix(void) {
Expand Down
4 changes: 2 additions & 2 deletions core/libs/prx/libSceLibreSsl3/include/Api.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ int APS5_VABI DH_get0_pqg_nid_postfix(void);
int APS5_VABI DSA_get0_key_nid_postfix(void);
int APS5_VABI DSA_get0_pqg_nid_postfix(void);
int APS5_VABI EC_KEY_up_ref_nid_postfix(LibreSsl3EcKey* key);
int APS5_VABI ERR_load_crypto_strings_nid_postfix(void);
int APS5_VABI ERR_peek_last_error_nid_postfix(void);
void APS5_VABI ERR_load_crypto_strings_nid_postfix();
std::uint64_t APS5_VABI ERR_peek_last_error_nid_postfix();
int APS5_VABI ERR_print_errors_cb_nid_postfix(void);
int APS5_VABI EVP_CIPHER_CTX_set_flags_nid_postfix(void);
int APS5_VABI EVP_DigestInit_nid_postfix(void);
Expand Down
5 changes: 3 additions & 2 deletions core/libs/tests/GuestLibreSslError.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "prx/libSceLibreSsl/include/Api.hpp"
#include "prx/libSceLibreSsl/include/Error.hpp"
#include "prx/libSceLibreSsl/libSceLibreSsl.hpp"
#include "prx/libSceLibreSsl3/libSceLibreSsl3.hpp"
#include "prx/libc/include/general/VabiMacros.hpp"
#include "prx/libSceLibreSsl/include/Error.hpp"
#include <cstdint>
#include <cstdio>
#include <cstdlib>
Expand Down
Loading
Loading