From 483249a2049632a6bc06f01ad951080cd636ca41 Mon Sep 17 00:00:00 2001 From: Kirill Zhumarin Date: Sun, 20 Sep 2026 09:46:09 +0000 Subject: [PATCH] Some experiments with docker --- .dockerignore | 14 ++ .gitignore | 3 + CMakeLists.txt | 55 +++-- Dockerfile | 45 ++++ common/IpcProto.h | 9 +- host-helper/CMakeLists.txt | 48 ++++- host-helper/src/AppWindow.cpp | 119 ++++++---- host-helper/src/AppWindow.h | 25 +-- host-helper/src/DockerProcess.cpp | 31 +++ host-helper/src/DockerProcess.h | 25 +++ host-helper/src/KeyCodes.cpp | 2 +- host-helper/src/Launcher.cpp | 322 ++++++++++++++++++++++++++++ host-helper/src/Launcher.h | 37 ++++ host-helper/src/main.cpp | 87 +++++--- host-helper/tests/AppWindowTest.cpp | 50 +++++ host-helper/tests/LauncherTest.cpp | 258 ++++++++++++++++++++++ src/FFS.cpp | 24 ++- src/FFS.h | 3 +- src/IPC.cpp | 158 +++++++------- src/IPC.h | 33 +-- src/Resources.cpp | 12 +- src/elfloader/debug.c | 33 ++- src/io/Loop.h | 3 +- src/main.cpp | 71 +++--- src/main.h | 5 - src/swi/csm.cpp | 2 + src/swi/file.cpp | 7 + src/swi/gbs.cpp | 4 + src/swi/gui.h | 7 +- src/swi/gui/lcdlayer.cpp | 33 ++- src/swi/image.cpp | 14 +- src/swi/init.cpp | 6 +- src/swi/obs.cpp | 7 + src/swi/proc/helper.cpp | 5 +- src/swi/proc/mmi.cpp | 2 +- src/swi/wstring.cpp | 2 +- src/swilib/switab-stubs.cpp | 8 + 37 files changed, 1274 insertions(+), 295 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 host-helper/src/DockerProcess.cpp create mode 100644 host-helper/src/DockerProcess.h create mode 100644 host-helper/src/Launcher.cpp create mode 100644 host-helper/src/Launcher.h create mode 100644 host-helper/tests/AppWindowTest.cpp create mode 100644 host-helper/tests/LauncherTest.cpp delete mode 100644 src/main.h diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..0232c75 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,14 @@ +.git +.agents +.cache +.codex +.idea +.kdev4 +build +cmake-build-* +host-helper/.cache +host-helper/.qt +host-helper/build +*.core +*.elf +*.wad diff --git a/.gitignore b/.gitignore index dd8d32e..85e1702 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +AGENTS.md +.idea/ +root/ build host-helper/build CMakeCache.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 0354b14..f16578c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,18 +2,14 @@ cmake_minimum_required(VERSION 3.15) set(CMAKE_EXPORT_COMPILE_COMMANDS true) -include(${CMAKE_CURRENT_SOURCE_DIR}/toolchain.cmake) +option(ELF_EMU_NATIVE_ARM "Build natively on ARM" OFF) + +if(NOT ELF_EMU_NATIVE_ARM) + include(${CMAKE_CURRENT_SOURCE_DIR}/toolchain.cmake) +endif() project(elfloader3 LANGUAGES C ASM CXX) -include(ExternalProject) -ExternalProject_Add(host_helper - SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/host-helper" - BINARY_DIR "${CMAKE_CURRENT_SOURCE_DIR}/host-helper/build" - INSTALL_COMMAND "" - BUILD_ALWAYS ON -) - set(CMAKE_CXX_STANDARD 20) set(CMAKE_C_STANDARD 11) @@ -29,7 +25,7 @@ add_subdirectory(third_party/zlib-1.2.1) add_subdirectory(third_party/argparse) add_subdirectory(third_party/spdlog) -add_executable(elfloader3 +set(ELFLOADER_SOURCES src/main.cpp src/glue.cpp src/IPC.cpp @@ -96,15 +92,32 @@ add_executable(elfloader3 src/elfloader/log.c ) -target_compile_options(elfloader3 PUBLIC -Wall -Werror -Wno-unused-function -Wsign-compare -Wno-psabi -g) -target_compile_definitions(elfloader3 PUBLIC -DNEWSGOLD=1 -DELKA=1 -DSWILIB_LINUX_SIMULATOR=1) -target_link_options(elfloader3 PUBLIC -Wl,--dynamic-linker=/usr/arm-linux-gnueabihf/lib/ld-linux-armhf.so.3 -Wl,-rpath=/usr/arm-linux-gnueabihf/lib/) -target_link_libraries(elfloader3 PUBLIC ssl crypto png z argparse spdlog) +function(add_elfloader target platform) + add_executable(${target} ${ELFLOADER_SOURCES}) + target_compile_options(${target} PUBLIC -Wall -Werror -Wno-unused-function -Wsign-compare -Wno-psabi -g) + target_compile_definitions(${target} PUBLIC SWILIB_LINUX_SIMULATOR=1) -target_include_directories(elfloader3 PUBLIC SYSTEM overrides) -target_include_directories(elfloader3 PUBLIC SYSTEM ../sdk/swilib/include/) -target_include_directories(elfloader3 PUBLIC SYSTEM third_party/stb) -target_include_directories(elfloader3 PRIVATE .) -target_include_directories(elfloader3 PUBLIC common) -target_link_directories(elfloader3 PUBLIC ${CMAKE_BINARY_DIR}/lib) -target_link_directories(elfloader3 PUBLIC .) + if(platform STREQUAL "ELKA") + target_compile_definitions(${target} PUBLIC NEWSGOLD=1 ELKA=1) + elseif(platform STREQUAL "NSG") + target_compile_definitions(${target} PUBLIC NEWSGOLD=1) + else() + target_compile_definitions(${target} PUBLIC SGOLD=1) + endif() + + if(CMAKE_CROSSCOMPILING) + target_link_options(${target} PUBLIC -Wl,--dynamic-linker=/usr/arm-linux-gnueabihf/lib/ld-linux-armhf.so.3 -Wl,-rpath=/usr/arm-linux-gnueabihf/lib/) + endif() + target_link_libraries(${target} PUBLIC ssl crypto png z argparse spdlog) + target_include_directories(${target} PUBLIC SYSTEM overrides) + target_include_directories(${target} PUBLIC SYSTEM ../sdk/swilib/include/) + target_include_directories(${target} PUBLIC SYSTEM third_party/stb) + target_include_directories(${target} PRIVATE .) + target_include_directories(${target} PUBLIC common) + target_link_directories(${target} PUBLIC ${CMAKE_BINARY_DIR}/lib) + target_link_directories(${target} PUBLIC .) +endfunction() + +add_elfloader(elfloader3 ELKA) +add_elfloader(elfloader3-nsg NSG) +add_elfloader(elfloader3-sg SG) diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..aa05989 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,45 @@ +# syntax=docker/dockerfile:1 + +FROM debian:trixie-slim AS builder + +ARG DEBIAN_FRONTEND=noninteractive + +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + cmake \ + g++ \ + make \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /src +COPY . . + +RUN --mount=type=bind,from=sdk,target=/sdk,ro \ + --mount=type=cache,id=elf-emu-native-arm-build,target=/build,sharing=locked \ + cmake -S . -B /build -DCMAKE_BUILD_TYPE=RelWithDebInfo -DELF_EMU_NATIVE_ARM=ON \ + && cmake --build /build --parallel 4 \ + && mkdir -p /out/elka /out/nsg /out/sg \ + && cp /build/elfloader3 /out/elka/elfloader3 \ + && cp /build/elfloader3-nsg /out/nsg/elfloader3 \ + && cp /build/elfloader3-sg /out/sg/elfloader3 \ + && cp -a /out /runtime-out \ + && strip --strip-debug /runtime-out/*/elfloader3 + +FROM scratch AS export + +COPY --from=builder /out/ / + +FROM debian:trixie-slim AS runtime + +ARG DEBIAN_FRONTEND=noninteractive + +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + libstdc++6 \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=builder /runtime-out/ /app/ +COPY --from=builder /src/res /app/res +COPY --from=builder /src/rootfs /app/rootfs + +RUN chmod -R a+rX /app/res /app/rootfs diff --git a/common/IpcProto.h b/common/IpcProto.h index 6f75e1d..be2c817 100644 --- a/common/IpcProto.h +++ b/common/IpcProto.h @@ -3,6 +3,7 @@ #include enum IpcCmd: int8_t { + IPC_CMD_SCREEN, IPC_CMD_REDRAW, IPC_CMD_KEY_EVENT, }; @@ -497,7 +498,13 @@ enum IpcKeyCode { #pragma pack(push, 1) struct IpcPacket { IpcCmd cmd; - uint8_t size; + uint32_t size; +}; + +struct IpcPacketScreen { + IpcPacket header; + uint32_t width; + uint32_t height; }; struct IpcPacketRedraw { diff --git a/host-helper/CMakeLists.txt b/host-helper/CMakeLists.txt index f8cb1d4..457c9a3 100644 --- a/host-helper/CMakeLists.txt +++ b/host-helper/CMakeLists.txt @@ -4,16 +4,48 @@ set(CMAKE_EXPORT_COMPILE_COMMANDS true) project(host-helper LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 20) + find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets Network) +include(CTest) + +if(BUILD_TESTING) + find_package(Qt6 REQUIRED COMPONENTS Test) +endif() + qt_standard_project_setup() -qt_add_executable(elfloader3-helper src/main.cpp src/AppWindow.cpp src/KeyCodes.cpp) - -target_link_libraries(elfloader3-helper PRIVATE - Qt6::Core - Qt6::Gui - Qt6::Widgets - Qt6::Network +qt_add_executable(elf-emu + src/main.cpp + src/AppWindow.cpp + src/DockerProcess.cpp + src/KeyCodes.cpp + src/Launcher.cpp ) -target_include_directories(elfloader3-helper PUBLIC ../common) + +target_link_libraries(elf-emu PRIVATE + Qt6::Core + Qt6::Gui + Qt6::Widgets + Qt6::Network +) +target_include_directories(elf-emu PUBLIC ../common) + +if(BUILD_TESTING) + add_executable(launcher-test tests/LauncherTest.cpp src/Launcher.cpp) + add_dependencies(launcher-test elf-emu) + target_link_libraries(launcher-test PRIVATE Qt6::Core Qt6::Test) + target_include_directories(launcher-test PUBLIC ../common) + add_test(NAME launcher-test COMMAND launcher-test) + + add_executable(app-window-test + tests/AppWindowTest.cpp + src/AppWindow.cpp + src/KeyCodes.cpp + ) + target_link_libraries(app-window-test PRIVATE Qt6::Gui Qt6::Network Qt6::Test) + target_include_directories(app-window-test PUBLIC ../common) + add_test(NAME app-window-test COMMAND app-window-test) + set_tests_properties(app-window-test PROPERTIES ENVIRONMENT QT_QPA_PLATFORM=offscreen) +endif() diff --git a/host-helper/src/AppWindow.cpp b/host-helper/src/AppWindow.cpp index 5bc6c88..258391a 100644 --- a/host-helper/src/AppWindow.cpp +++ b/host-helper/src/AppWindow.cpp @@ -1,41 +1,59 @@ #include "AppWindow.h" -#include "IpcProto.h" -#include +#include +#include +#include +#include -AppWindow::AppWindow(uint8_t *buffer, QString socket, int w, int h, QWindow *parent) : QWindow(parent), m_backingStore(new QBackingStore(this)), m_socket(this) { - m_width = w; - m_height = h; - m_screen_buffer = buffer; - m_socket_path = socket; - m_image = QImage(m_screen_buffer, m_width, m_height, QImage::Format_ARGB32); +#include +#include + +AppWindow::AppWindow(quint16 port, QWindow *parent) : QWindow(parent), m_port(port), m_socket(this), m_backingStore(new QBackingStore(this)) { + m_screen_buffer.resize(m_width * m_height * 4); + m_image = QImage(m_screen_buffer.data(), m_width, m_height, QImage::Format_ARGB32); QRect screen_geometry = QGuiApplication::primaryScreen()->geometry(); int x = (screen_geometry.width() - m_width) / 2; int y = (screen_geometry.height() - m_height) / 2; setGeometry(x, y, m_width, m_height); - - setMinimumSize(QSize(width(), height())); - setMaximumSize(QSize(width(), height())); + setMinimumSize(QSize(m_width, m_height)); + setMaximumSize(QSize(m_width, m_height)); connect(&m_socket, &QIODevice::readyRead, [this]() { - char buffer[4096]; - auto readed = m_socket.read(buffer, sizeof(buffer)); - if (readed > 0) { - m_rx_buffer.insert(m_rx_buffer.end(), buffer, buffer + readed); + try { + QByteArray data = m_socket.readAll(); + m_rx_buffer.insert(m_rx_buffer.end(), data.begin(), data.end()); parseRxBuffer(); + } catch (const std::exception &e) { + qCritical().noquote() << e.what(); + QCoreApplication::exit(1); } }); - connect(&m_socket, &QLocalSocket::errorOccurred, [this]() { - QCoreApplication::quit(); + connect(&m_socket, &QTcpSocket::connected, [this]() { + m_connected = true; + }); + + connect(&m_socket, &QTcpSocket::disconnected, [this]() { + m_connected = false; + if (m_ready) { + QCoreApplication::quit(); + } else { + QTimer::singleShot(100, this, &AppWindow::connectToServer); + } + }); + + connect(&m_socket, &QTcpSocket::errorOccurred, [this]() { + if (!m_ready) + QTimer::singleShot(100, this, &AppWindow::connectToServer); }); } void AppWindow::parseRxBuffer() { while (m_rx_buffer.size() >= sizeof(IpcPacket)) { - IpcPacket *pkt = reinterpret_cast(&m_rx_buffer[0]); - + IpcPacket *pkt = reinterpret_cast(m_rx_buffer.data()); + if (pkt->size < sizeof(IpcPacket) || pkt->size > 16 * 1024 * 1024) + throw std::runtime_error("Invalid IPC packet size."); if (m_rx_buffer.size() < pkt->size) break; @@ -46,16 +64,38 @@ void AppWindow::parseRxBuffer() { void AppWindow::handleIpcCommand(IpcPacket *pkt) { switch (pkt->cmd) { - case IPC_CMD_REDRAW: - { - IpcPacketRedraw *pkt_redraw = reinterpret_cast(pkt); - renderNow(QRect(QPoint(pkt_redraw->x, pkt_redraw->y), QPoint(pkt_redraw->x2, pkt_redraw->y2))); + case IPC_CMD_SCREEN: { + if (pkt->size != sizeof(IpcPacketScreen)) + throw std::runtime_error("Invalid screen packet."); + + auto *screen = reinterpret_cast(pkt); + if (screen->width == 0 || screen->height == 0 || screen->width > 4096 || screen->height > 4096) + throw std::runtime_error("Invalid screen size."); + m_width = screen->width; + m_height = screen->height; + m_screen_buffer.resize(m_width * m_height * 4); + m_image = QImage(m_screen_buffer.data(), m_width, m_height, QImage::Format_ARGB32); + m_ready = true; + resize(m_width, m_height); + setMinimumSize(QSize(m_width, m_height)); + setMaximumSize(QSize(m_width, m_height)); + break; + } + + case IPC_CMD_REDRAW: { + if (pkt->size != sizeof(IpcPacketRedraw) + m_screen_buffer.size()) + throw std::runtime_error("Invalid redraw packet."); + + auto *redraw = reinterpret_cast(pkt); + uint8_t *pixels = reinterpret_cast(pkt) + sizeof(IpcPacketRedraw); + std::memcpy(m_screen_buffer.data(), pixels, m_screen_buffer.size()); + renderNow(QRect(QPoint(redraw->x, redraw->y), QPoint(redraw->x2, redraw->y2))); + break; } - break; default: - qDebug("UNKNOWN CMD: %d\n", pkt->cmd); - break; + qWarning("Unknown IPC command: %d", pkt->cmd); + break; } } @@ -66,32 +106,29 @@ void AppWindow::sendIpcCommand(IpcPacket *pkt) { } void AppWindow::connectToServer() { - m_socket.connectToServer(m_socket_path); - if (!m_socket.waitForConnected(5000)) - throw std::runtime_error("Can't connect to ELF simulator server!"); + if (m_socket.state() == QAbstractSocket::UnconnectedState) + m_socket.connectToHost(QHostAddress::LocalHost, m_port); } bool AppWindow::event(QEvent *event) { if (event->type() == QEvent::KeyRelease || event->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast(event); + QKeyEvent *key_event = static_cast(event); IpcPacketKeyEvent pkt = {}; pkt.header = { IPC_CMD_KEY_EVENT, sizeof(IpcPacketKeyEvent) }; - pkt.keycode = toIpcKeyCode(keyEvent); - pkt.modifiers = toIpcKeyModifier(keyEvent); + pkt.keycode = toIpcKeyCode(key_event); + pkt.modifiers = toIpcKeyModifier(key_event); - const char *text = keyEvent->text().toLocal8Bit().data(); - strncpy(pkt.text, text, sizeof(pkt.text)); + QByteArray text = key_event->text().toLocal8Bit(); + std::strncpy(pkt.text, text.constData(), sizeof(pkt.text) - 1); if (event->type() == QEvent::KeyPress) { - // qDebug("key release %d%s", keyEvent->key(), keyEvent->isAutoRepeat() ? " [auto]" : ""); - pkt.state = keyEvent->isAutoRepeat() ? IPC_KEY_REPEAT : IPC_KEY_PRESS; + pkt.state = key_event->isAutoRepeat() ? IPC_KEY_REPEAT : IPC_KEY_PRESS; } else { - // qDebug("key press %d%s", keyEvent->key(), keyEvent->isAutoRepeat() ? " [auto]" : ""); pkt.state = IPC_KEY_RELEASE; } - sendIpcCommand(&pkt.header); - + if (m_connected) + sendIpcCommand(&pkt.header); return true; } @@ -106,8 +143,8 @@ void AppWindow::renderLater() { requestUpdate(); } -void AppWindow::resizeEvent(QResizeEvent *resizeEvent) { - m_backingStore->resize(resizeEvent->size()); +void AppWindow::resizeEvent(QResizeEvent *resize_event) { + m_backingStore->resize(resize_event->size()); } void AppWindow::exposeEvent(QExposeEvent *) { diff --git a/host-helper/src/AppWindow.h b/host-helper/src/AppWindow.h index 1ed0c44..caea944 100644 --- a/host-helper/src/AppWindow.h +++ b/host-helper/src/AppWindow.h @@ -1,8 +1,8 @@ #pragma once -#include #include -#include +#include +#include #include @@ -12,32 +12,33 @@ class AppWindow: public QWindow { Q_OBJECT protected: - int m_width; - int m_height; - QDataStream *m_stream = nullptr; - uint8_t *m_screen_buffer = nullptr; - QString m_socket_path; - QLocalSocket m_socket; + int m_width = 132; + int m_height = 176; + quint16 m_port; + bool m_connected = false; + bool m_ready = false; + QTcpSocket m_socket; std::vector m_rx_buffer; + std::vector m_screen_buffer; QImage m_image; uint32_t toIpcKeyCode(QKeyEvent *e); uint32_t toIpcKeyModifier(QKeyEvent *e); -public: - explicit AppWindow(uint8_t *buffer, QString socket, int w, int h, QWindow *parent = nullptr); - void parseRxBuffer(); void handleIpcCommand(IpcPacket *pkt); void sendIpcCommand(IpcPacket *pkt); +public: + explicit AppWindow(quint16 port, QWindow *parent = nullptr); + void connectToServer(); + public slots: void renderLater(); void renderNow(const QRect &update); protected: bool event(QEvent *event) override; - void resizeEvent(QResizeEvent *event) override; void exposeEvent(QExposeEvent *event) override; diff --git a/host-helper/src/DockerProcess.cpp b/host-helper/src/DockerProcess.cpp new file mode 100644 index 0000000..5421f43 --- /dev/null +++ b/host-helper/src/DockerProcess.cpp @@ -0,0 +1,31 @@ +#include "DockerProcess.h" + +#include + +DockerProcess::DockerProcess(QString name, QObject *parent) : QObject(parent), m_name(std::move(name)), m_process(this) { + m_process.setProcessChannelMode(QProcess::ForwardedChannels); + connect(&m_process, &QProcess::finished, [this](int exit_code) { + m_started = false; + emit finished(exit_code); + }); +} + +DockerProcess::~DockerProcess() { + stop(); +} + +void DockerProcess::start(const QStringList &arguments) { + m_process.start("docker", arguments); + if (!m_process.waitForStarted()) + throw std::runtime_error(m_process.errorString().toStdString()); + m_started = true; +} + +void DockerProcess::stop() { + if (!m_started) + return; + + QProcess::execute("docker", { "stop", "--timeout", "1", m_name }); + m_process.waitForFinished(3000); + m_started = false; +} diff --git a/host-helper/src/DockerProcess.h b/host-helper/src/DockerProcess.h new file mode 100644 index 0000000..b0f6e7a --- /dev/null +++ b/host-helper/src/DockerProcess.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include +#include +#include + +class DockerProcess: public QObject { + Q_OBJECT + +protected: + QString m_name; + QProcess m_process; + bool m_started = false; + +public: + explicit DockerProcess(QString name, QObject *parent = nullptr); + ~DockerProcess() override; + + void start(const QStringList &arguments); + void stop(); + +signals: + void finished(int exit_code); +}; diff --git a/host-helper/src/KeyCodes.cpp b/host-helper/src/KeyCodes.cpp index 2b891c2..61b8351 100644 --- a/host-helper/src/KeyCodes.cpp +++ b/host-helper/src/KeyCodes.cpp @@ -2,7 +2,7 @@ uint32_t AppWindow::toIpcKeyModifier(QKeyEvent *e) { uint32_t flags = 0; - if ((e->modifiers() & Qt::NoModifier)) + if (e->modifiers() == Qt::NoModifier) flags |= IPC_NO_MODIFIER; if ((e->modifiers() & Qt::ShiftModifier)) flags |= IPC_SHIFT_MODIFIER; diff --git a/host-helper/src/Launcher.cpp b/host-helper/src/Launcher.cpp new file mode 100644 index 0000000..9f48165 --- /dev/null +++ b/host-helper/src/Launcher.cpp @@ -0,0 +1,322 @@ +#include "Launcher.h" + +#include +#include +#include +#include +#include + +#ifdef Q_OS_UNIX +#include +#endif + +#include + +struct PathMapping { + QString source; + QString ffs_path; +}; + +static QString existingPath(const QString &path, bool directory) { + QFileInfo info(path); + QString canonical = info.canonicalFilePath(); + if (canonical.isEmpty()) + throw std::runtime_error(QString("Path does not exist: %1").arg(path).toStdString()); + if (directory && !info.isDir()) + throw std::runtime_error(QString("Not a directory: %1").arg(path).toStdString()); + return QDir::cleanPath(canonical); +} + +static QString findSdk(const QString &app_dir) { + QDir dir(app_dir); + do { + QString sdk = dir.filePath("sdk"); + if (QFileInfo(sdk + "/swilib/include").isDir()) + return sdk; + } while (dir.cdUp()); + + QString sdk = QDir::home().filePath("dev/sie/sdk"); + if (QFileInfo(sdk + "/swilib/include").isDir()) + return sdk; + throw std::runtime_error("SDK not found. Use --sdk or ELF_EMU_SDK."); +} + +static QString parseRoot(const QString &path, bool dry_run) { + QString root = QFileInfo(path).absoluteFilePath(); + if (!dry_run && !QDir().mkpath(root)) + throw std::runtime_error(QString("Can't create root directory: %1").arg(root).toStdString()); + return QFileInfo::exists(root) ? existingPath(root, true) : QDir::cleanPath(root); +} + +static QString parseSdk(const QString &path, const QString &app_dir) { + QString sdk = path; + if (sdk.isEmpty()) + sdk = qEnvironmentVariable("ELF_EMU_SDK"); + if (sdk.isEmpty()) + sdk = findSdk(app_dir); + sdk = existingPath(sdk, true); + if (!QFileInfo::exists(sdk + "/swilib/include")) + throw std::runtime_error(QString("Invalid SDK directory: %1").arg(sdk).toStdString()); + return sdk; +} + +static bool isInside(const QString &path, const QString &directory) { +#ifdef Q_OS_WIN + Qt::CaseSensitivity sensitivity = Qt::CaseInsensitive; +#else + Qt::CaseSensitivity sensitivity = Qt::CaseSensitive; +#endif + return path.compare(directory, sensitivity) == 0 || path.startsWith(directory + '/', sensitivity); +} + +static QString normalizeFfsPath(const QString &path) { + QString normalized = path; + normalized.replace('\\', '/'); + + QRegularExpression re("^([0124abAB]):(?:/(.*))?$"); + QRegularExpressionMatch match = re.match(normalized); + if (!match.hasMatch()) + throw std::runtime_error(QString("Invalid FFS path: %1").arg(path).toStdString()); + + QString drive = match.captured(1).toLower(); + QString tail = QDir::cleanPath("/" + match.captured(2)); + return drive + ":" + (tail == "/" ? "" : tail); +} + +static QString ffsContainerPath(const QString &ffs_path) { + static const QMap dirs = { + { "0", "Data" }, + { "1", "Cache" }, + { "2", "Config" }, + { "4", "MMCard" }, + { "a", "Cache" }, + { "b", "Config" }, + }; + + QString drive = ffs_path.left(1); + QString tail = ffs_path.mid(2); + return QDir::cleanPath("/ffs/" + dirs.value(drive) + "/" + tail); +} + +static BindMount parseBind(const QString &value, bool read_only) { + int separator = value.lastIndexOf('='); + if (separator <= 0 || separator == value.size() - 1) + throw std::runtime_error(QString("Invalid bind, expected HOST=FFS: %1").arg(value).toStdString()); + + BindMount bind; + bind.source = existingPath(value.left(separator), true); + bind.ffs_path = normalizeFfsPath(value.mid(separator + 1)); + bind.container_path = ffsContainerPath(bind.ffs_path); + bind.read_only = read_only; + return bind; +} + +QString Launcher::mapPath(const QString &path, const LaunchOptions &options) { + QString canonical = existingPath(path, false); + QList mappings = { + { options.root + "/Data", "0:" }, + { options.root + "/Cache", options.platform == "sg" ? "a:" : "1:" }, + { options.root + "/Config", options.platform == "sg" ? "b:" : "2:" }, + { options.root + "/MMCard", "4:" }, + }; + for (const auto &bind: options.binds) + mappings.push_back({ bind.source, bind.ffs_path }); + + const PathMapping *best = nullptr; + for (const auto &mapping: mappings) { + if (isInside(canonical, mapping.source) && (!best || mapping.source.size() > best->source.size())) + best = &mapping; + } + + if (!best) + throw std::runtime_error(QString("Path is outside root and binds: %1").arg(path).toStdString()); + + QString relative = QDir(best->source).relativeFilePath(canonical); + if (relative == ".") + return best->ffs_path; + return best->ffs_path + "/" + relative; +} + +static void addMount(QStringList &args, const QString &source, const QString &target, bool read_only) { + if (source.contains(',') || target.contains(',')) + throw std::runtime_error(QString("Docker mount path contains a comma: %1 -> %2").arg(source, target).toStdString()); + + QString mount = QString("type=bind,source=%1,target=%2").arg(source, target); + if (read_only) + mount += ",readonly"; + args << "--mount" << mount; +} + +static void addMounts(QStringList &args, const LaunchOptions &options) { + addMount(args, options.root, "/ffs", false); + addMount(args, options.sdk, "/sdk", true); + + for (const auto &bind: options.binds) + addMount(args, bind.source, bind.container_path, bind.read_only); + + for (int i = 0; i < options.library_dirs.size(); i++) + addMount(args, options.library_dirs[i], QString("/libs/%1").arg(i), true); +} + +static void addInitArguments(QStringList &args, const LaunchOptions &options) { + for (const auto &dir: { "Data", "Cache", "Config", "MMCard" }) { + QString path = options.root + '/' + dir; + if (!QFileInfo::exists(path) || QFileInfo::exists(options.root + "/.elf-emu-init-" + dir)) + args << "--init-missing" << dir; + } + for (const auto &bind: options.binds) + args << "--init-exclude" << bind.container_path; +} + +void Launcher::prepareRoot(const LaunchOptions &options) { + for (const auto &dir: { "Data", "Cache", "Config", "MMCard" }) { + QString path = options.root + '/' + dir; + if (!QFileInfo::exists(path)) { + QString marker_path = options.root + "/.elf-emu-init-" + dir; + QFile marker(marker_path); + if (!marker.open(QIODevice::WriteOnly)) + throw std::runtime_error(QString("Can't mark drive for initialization: %1").arg(marker_path).toStdString()); + } + if (!QDir().mkpath(path)) + throw std::runtime_error(QString("Can't create drive directory: %1").arg(path).toStdString()); + } + for (const auto &bind: options.binds) { + QString path = options.root + bind.container_path.mid(4); + if (!QDir().mkpath(path)) + throw std::runtime_error(QString("Can't create bind directory: %1").arg(path).toStdString()); + } +} + +LaunchOptions Launcher::parse(QCoreApplication &app) { + QCommandLineParser parser; + parser.setApplicationDescription("Run Siemens ELF applications in Docker"); + parser.addHelpOption(); + + QCommandLineOption version_option({ "v", "version" }, "Show version information."); + QCommandLineOption file_option({ "f", "file" }, "ELF file inside root or a bind.", "elf"); + QCommandLineOption root_option({ "r", "root" }, "Virtual phone filesystem root.", "dir"); + QCommandLineOption platform_option({ "p", "platform" }, "Target platform: sg, nsg or elka.", "platform", "elka"); + QCommandLineOption arg_option({ "a", "arg" }, "File passed to the ELF application.", "file"); + QCommandLineOption bind_option({ "b", "bind" }, "Add a read-write HOST=FFS bind.", "host=ffs"); + QCommandLineOption bind_ro_option({ "B", "bind-ro" }, "Add a read-only HOST=FFS bind.", "host=ffs"); + QCommandLineOption lib_option({ "L", "lib-dir" }, "Add a read-only library directory.", "dir"); + QCommandLineOption sdk_option({ "s", "sdk" }, "Path to the local SDK.", "dir"); + QCommandLineOption gdb_option({ "g", "gdb" }, "Wait for GDB on the given host port.", "port"); + QCommandLineOption no_gui_option({ "n", "no-gui" }, "Run without the phone window."); + QCommandLineOption verbose_option({ "V", "verbose" }, "Enable verbose ARM elfloader logs."); + QCommandLineOption dry_run_option({ "d", "dry-run" }, "Print the Docker command without running it."); + QCommandLineOption image_option("image", "Docker image name.", "image", "elf-emu:latest"); + + parser.addOptions({ + version_option, + file_option, + root_option, + platform_option, + arg_option, + bind_option, + bind_ro_option, + lib_option, + sdk_option, + gdb_option, + no_gui_option, + verbose_option, + dry_run_option, + image_option, + }); + parser.process(app); + if (parser.isSet(version_option)) + parser.showVersion(); + + if (!parser.isSet(root_option)) + throw std::runtime_error("Missing required --root option."); + if (!parser.isSet(file_option)) + throw std::runtime_error("Missing required --file option."); + if (!parser.positionalArguments().isEmpty()) + throw std::runtime_error("Unexpected positional arguments."); + + LaunchOptions options; + options.platform = parser.value(platform_option).toLower(); + if (options.platform != "sg" && options.platform != "nsg" && options.platform != "elka") + throw std::runtime_error(QString("Unknown platform: %1").arg(options.platform).toStdString()); + + options.root = parseRoot(parser.value(root_option), parser.isSet(dry_run_option)); + + for (const auto &value: parser.values(bind_option)) + options.binds.push_back(parseBind(value, false)); + for (const auto &value: parser.values(bind_ro_option)) + options.binds.push_back(parseBind(value, true)); + + options.elf = Launcher::mapPath(parser.value(file_option), options); + if (parser.isSet(arg_option)) + options.arg = Launcher::mapPath(parser.value(arg_option), options); + + options.sdk = parseSdk(parser.value(sdk_option), app.applicationDirPath()); + + for (const auto &dir: parser.values(lib_option)) + options.library_dirs.push_back(existingPath(dir, true)); + + if (parser.isSet(gdb_option)) { + bool ok = false; + options.gdb_port = parser.value(gdb_option).toInt(&ok); + if (!ok || options.gdb_port < 1 || options.gdb_port > 65535) + throw std::runtime_error("GDB port must be between 1 and 65535."); + } + + options.image = parser.value(image_option); + options.container_name = QString("elf-emu-%1").arg(app.applicationPid()); + options.no_gui = parser.isSet(no_gui_option); + options.verbose = parser.isSet(verbose_option); + options.dry_run = parser.isSet(dry_run_option); + return options; +} + +QStringList Launcher::dockerArguments(const LaunchOptions &options, quint16 ipc_port) { + QStringList args = { + "run", + "--platform", "linux/arm/v7", + "--rm", + "--name", options.container_name, + "--env", "HOME=/ffs/MMCard", + }; + +#ifdef Q_OS_UNIX + args << "--user" << QString("%1:%2").arg(getuid()).arg(getgid()); +#endif + + addMounts(args, options); + + if (ipc_port != 0) + args << "--publish" << QString("127.0.0.1:%1:%1").arg(ipc_port); + if (options.gdb_port != 0) { + args << "--publish" << QString("127.0.0.1:%1:%1").arg(options.gdb_port); + args << "--env" << QString("QEMU_GDB=%1").arg(options.gdb_port); + } + + args << options.image; + args << QString("/app/%1/elfloader3").arg(options.platform); + args << "--root" << "/ffs"; + args << "--sdk" << "/sdk"; + args << "--file" << options.elf; + addInitArguments(args, options); + + if (!options.arg.isEmpty()) + args << "--arg" << options.arg; + for (int i = 0; i < options.library_dirs.size(); i++) + args << "--lib-dir" << QString("/libs/%1").arg(i); + if (ipc_port != 0) + args << "--ipc-port" << QString::number(ipc_port); + if (options.verbose) + args << "--verbose"; + + return args; +} + +QString Launcher::dockerCommand(const LaunchOptions &options, quint16 ipc_port) { + QStringList command = { "docker" }; + for (const auto &arg: dockerArguments(options, ipc_port)) { + QString escaped = arg; + escaped.replace('\'', "'\\''"); + command.push_back("'" + escaped + "'"); + } + return command.join(' '); +} diff --git a/host-helper/src/Launcher.h b/host-helper/src/Launcher.h new file mode 100644 index 0000000..fdcd9a2 --- /dev/null +++ b/host-helper/src/Launcher.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include + +struct BindMount { + QString source; + QString ffs_path; + QString container_path; + bool read_only = false; +}; + +struct LaunchOptions { + QString root; + QString platform; + QString sdk; + QString elf; + QString arg; + QString image; + QString container_name; + QStringList library_dirs; + QList binds; + int gdb_port = 0; + bool no_gui = false; + bool verbose = false; + bool dry_run = false; +}; + +class Launcher { +public: + static LaunchOptions parse(QCoreApplication &app); + static QString mapPath(const QString &path, const LaunchOptions &options); + static void prepareRoot(const LaunchOptions &options); + static QStringList dockerArguments(const LaunchOptions &options, quint16 ipc_port); + static QString dockerCommand(const LaunchOptions &options, quint16 ipc_port); +}; diff --git a/host-helper/src/main.cpp b/host-helper/src/main.cpp index d592852..356ec6c 100644 --- a/host-helper/src/main.cpp +++ b/host-helper/src/main.cpp @@ -1,33 +1,66 @@ -#include -#include - -#include -#include - #include "AppWindow.h" +#include "DockerProcess.h" +#include "Launcher.h" + +#include +#include +#include +#include +#include + +#include + +static quint16 findFreePort(int excluded_port) { + quint16 port; + do { + QTcpServer server; + if (!server.listen(QHostAddress::LocalHost, 0)) + throw std::runtime_error(server.errorString().toStdString()); + port = server.serverPort(); + } while (port == excluded_port); + return port; +} int main(int argc, char *argv[]) { - QApplication app(argc, argv); + QCoreApplication::setApplicationName("elf-emu"); + QCoreApplication::setApplicationVersion("1.0.0"); - if (argc != 5) { - printf("usage: %s \n", argv[0]); - return -1; + std::unique_ptr app = std::make_unique(argc, argv); + + try { + LaunchOptions options = Launcher::parse(*app); + if (!options.no_gui && !options.dry_run) { + app.reset(); + app = std::make_unique(argc, argv); + } + + quint16 ipc_port = 0; + if (!options.no_gui) + ipc_port = findFreePort(options.gdb_port); + + if (options.dry_run) { + QTextStream(stdout) << Launcher::dockerCommand(options, ipc_port) << '\n'; + return 0; + } + + DockerProcess docker(options.container_name); + QObject::connect(&docker, &DockerProcess::finished, app.get(), [&app](int exit_code) { + app->exit(exit_code); + }); + QStringList arguments = Launcher::dockerArguments(options, ipc_port); + Launcher::prepareRoot(options); + docker.start(arguments); + + std::unique_ptr window; + if (!options.no_gui) { + window = std::make_unique(ipc_port); + window->show(); + window->connectToServer(); + } + + return app->exec(); + } catch (const std::exception &e) { + QTextStream(stderr) << e.what() << '\n'; + return 1; } - - int mem_id = atoi(argv[1]); - const char *socket = argv[2]; - int width = atoi(argv[3]); - int height = atoi(argv[4]); - - auto mem = reinterpret_cast(shmat(mem_id, NULL, 0)); - if (mem == (void *) -1) { - perror("shmat"); - return -1; - } - - AppWindow win(mem, socket, width, height); - win.connectToServer(); - win.show(); - - return app.exec(); } diff --git a/host-helper/tests/AppWindowTest.cpp b/host-helper/tests/AppWindowTest.cpp new file mode 100644 index 0000000..880b8ca --- /dev/null +++ b/host-helper/tests/AppWindowTest.cpp @@ -0,0 +1,50 @@ +#include "../src/AppWindow.h" + +#include +#include +#include + +class AppWindowTest: public QObject { + Q_OBJECT + +private slots: + void reconnectsUntilArmIpcStarts(); + void forwardsKeyWithoutModifiers(); +}; + +void AppWindowTest::reconnectsUntilArmIpcStarts() { + QTcpServer server; + QVERIFY(server.listen(QHostAddress::LocalHost, 0)); + quint16 port = server.serverPort(); + server.close(); + + AppWindow window(port); + window.connectToServer(); + QTest::qWait(200); + + QVERIFY(server.listen(QHostAddress::LocalHost, port)); + QTRY_VERIFY_WITH_TIMEOUT(server.hasPendingConnections(), 2000); +} + +void AppWindowTest::forwardsKeyWithoutModifiers() { + QTcpServer server; + QVERIFY(server.listen(QHostAddress::LocalHost, 0)); + + AppWindow window(server.serverPort()); + window.connectToServer(); + QTRY_VERIFY_WITH_TIMEOUT(server.hasPendingConnections(), 2000); + QTcpSocket *socket = server.nextPendingConnection(); + + QTest::keyPress(&window, Qt::Key_5); + QTRY_VERIFY_WITH_TIMEOUT(socket->bytesAvailable() >= sizeof(IpcPacketKeyEvent), 2000); + QByteArray data = socket->read(sizeof(IpcPacketKeyEvent)); + auto *key = reinterpret_cast(data.constData()); + QCOMPARE(key->header.cmd, IPC_CMD_KEY_EVENT); + QCOMPARE(key->keycode, static_cast(IPC_KEY_5)); + QCOMPARE(key->modifiers, static_cast(IPC_NO_MODIFIER)); + QCOMPARE(key->state, IPC_KEY_PRESS); +} + +QTEST_MAIN(AppWindowTest) + +#include "AppWindowTest.moc" diff --git a/host-helper/tests/LauncherTest.cpp b/host-helper/tests/LauncherTest.cpp new file mode 100644 index 0000000..6f0931f --- /dev/null +++ b/host-helper/tests/LauncherTest.cpp @@ -0,0 +1,258 @@ +#include "../src/Launcher.h" + +#include +#include +#include +#include +#include +#include +#include + +class LauncherTest: public QObject { + Q_OBJECT + +private slots: + void mapsRootAndBindPaths(); + void rejectsPathOutsideMounts(); + void buildsDockerArguments(); + void initializesMissingRootWithNestedBind(); + void parsesHostCommandLine(); + void findsSdkInParentOrHome(); +}; + +static void createFile(const QString &path) { + QFile file(path); + QVERIFY(file.open(QIODevice::WriteOnly)); +} + +static LaunchOptions makeOptions(const QString &root, const QString &external) { + LaunchOptions options; + options.root = QFileInfo(root).canonicalFilePath(); + options.platform = "elka"; + options.sdk = external; + options.image = "elf-emu:test"; + options.container_name = "elf-emu-test"; + options.binds.push_back({ + .source = QFileInfo(external).canonicalFilePath(), + .ffs_path = "4:/home", + .container_path = "/ffs/MMCard/home", + .read_only = true, + }); + return options; +} + +void LauncherTest::mapsRootAndBindPaths() { + QTemporaryDir temp; + QVERIFY(temp.isValid()); + QString root = temp.path() + "/root"; + QString data = root + "/Data/ZBin"; + QString external = temp.path() + "/external"; + QVERIFY(QDir().mkpath(data)); + QVERIFY(QDir().mkpath(external)); + + QString root_elf = data + "/test.elf"; + QString bind_elf = external + "/bind.elf"; + createFile(root_elf); + createFile(bind_elf); + LaunchOptions options = makeOptions(root, external); + + QCOMPARE(Launcher::mapPath(root_elf, options), QString("0:/ZBin/test.elf")); + QCOMPARE(Launcher::mapPath(bind_elf, options), QString("4:/home/bind.elf")); +} + +void LauncherTest::rejectsPathOutsideMounts() { + QTemporaryDir temp; + QVERIFY(temp.isValid()); + QString root = temp.path() + "/root"; + QString external = temp.path() + "/external"; + QVERIFY(QDir().mkpath(root)); + QVERIFY(QDir().mkpath(external)); + + QString outside_elf = temp.path() + "/outside.elf"; + createFile(outside_elf); + LaunchOptions options = makeOptions(root, external); + + QVERIFY_EXCEPTION_THROWN(Launcher::mapPath(outside_elf, options), std::runtime_error); +} + +void LauncherTest::buildsDockerArguments() { + QTemporaryDir temp; + QVERIFY(temp.isValid()); + QString root = temp.path() + "/root"; + QVERIFY(QDir().mkpath(root)); + + LaunchOptions options; + options.root = root; + options.platform = "elka"; + options.sdk = "/tmp/sdk"; + options.elf = "0:/ZBin/test.elf"; + options.image = "elf-emu:test"; + options.container_name = "elf-emu-test"; + options.gdb_port = 34567; + options.binds.push_back({ + .source = "/tmp/home", + .ffs_path = "4:/home", + .container_path = "/ffs/MMCard/home", + .read_only = true, + }); + + QStringList args = Launcher::dockerArguments(options, 23456); + QCOMPARE(args.mid(0, 3), QStringList({ "run", "--platform", "linux/arm/v7" })); + QVERIFY(args.contains("127.0.0.1:23456:23456")); + QVERIFY(args.contains("127.0.0.1:34567:34567")); + QVERIFY(args.contains("QEMU_GDB=34567")); + QCOMPARE(args.at(args.indexOf("--ipc-port") + 1), QString("23456")); + QVERIFY(args.join('\n').contains("target=/ffs/MMCard/home")); + QVERIFY(args.contains("/app/elka/elfloader3")); +} + +void LauncherTest::initializesMissingRootWithNestedBind() { + QTemporaryDir temp; + QVERIFY(temp.isValid()); + QString root = temp.path() + "/root"; + QString external = temp.path() + "/external"; + QVERIFY(QDir().mkpath(root)); + QVERIFY(QDir().mkpath(external)); + QVERIFY(QDir().mkpath(root + "/Config")); + + LaunchOptions options = makeOptions(root, external); + options.binds[0].ffs_path = "0:/ZBin"; + options.binds[0].container_path = "/ffs/Data/ZBin"; + QStringList args = Launcher::dockerArguments(options, 0); + + QVERIFY(args.contains("--init-missing")); + QVERIFY(args.contains("Data")); + QVERIFY(args.contains("Cache")); + QVERIFY(args.contains("MMCard")); + QVERIFY(!args.contains("Config")); + QVERIFY(args.contains("--init-exclude")); + QVERIFY(args.contains("/ffs/Data/ZBin")); + QVERIFY(!QFileInfo(root + "/Data").exists()); + QVERIFY(!QFileInfo(root + "/Cache").exists()); + QVERIFY(!QFileInfo(root + "/MMCard").exists()); + + Launcher::prepareRoot(options); + QVERIFY(QFileInfo(root + "/Data/ZBin").isDir()); + QVERIFY(QFileInfo(root + "/Cache").isDir()); + QVERIFY(QFileInfo(root + "/MMCard").isDir()); + QVERIFY(QFileInfo(root + "/.elf-emu-init-Data").exists()); + QVERIFY(QFileInfo(root + "/.elf-emu-init-Cache").exists()); + QVERIFY(!QFileInfo(root + "/.elf-emu-init-Config").exists()); + QVERIFY(Launcher::dockerArguments(options, 0).contains("Data")); +} + +void LauncherTest::parsesHostCommandLine() { + QTemporaryDir temp; + QVERIFY(temp.isValid()); + QString root = temp.path() + "/root"; + QString sdk = temp.path() + "/sdk"; + QString elf = root + "/Data/test.elf"; + QVERIFY(QDir().mkpath(root + "/Data")); + QVERIFY(QDir().mkpath(sdk + "/swilib/include")); + createFile(elf); + + QProcess process; + process.setWorkingDirectory(temp.path()); + process.setProcessChannelMode(QProcess::MergedChannels); + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + env.insert("ELF_EMU_SDK", sdk); + env.insert("QT_QPA_PLATFORM", "elf-emu-invalid"); + process.setProcessEnvironment(env); + QString command = QCoreApplication::applicationDirPath() + "/elf-emu"; + QStringList args = { "-d", "-n", "-r", root, "-f", elf, "-V" }; + + process.start(command, args); + QVERIFY(process.waitForFinished(10000)); + QCOMPARE(process.exitCode(), 0); + QString output = process.readAll(); + QVERIFY(output.contains("'--file' '0:/test.elf'")); + QVERIFY(output.contains("'--verbose'")); + QVERIFY(output.contains("source=" + sdk)); + + process.start(command, { "--dry-run", "--no-gui", "--root", root, "--file", elf, "--verbose" }); + QVERIFY(process.waitForFinished(10000)); + QCOMPARE(process.exitCode(), 0); + output = process.readAll(); + QVERIFY(output.contains("'--file' '0:/test.elf'")); + QVERIFY(output.contains("'--verbose'")); + + process.start(command, { "-d", "-r", root, "-f", elf }); + QVERIFY(process.waitForFinished(10000)); + QCOMPARE(process.exitCode(), 0); + output = process.readAll(); + QRegularExpression ipc_port_re("'--publish' '127\\.0\\.0\\.1:(\\d+):\\1'.*'--ipc-port' '\\1'"); + QVERIFY(ipc_port_re.match(output).hasMatch()); + + process.start(command, args + QStringList({ elf })); + QVERIFY(process.waitForFinished(10000)); + QCOMPARE(process.exitCode(), 1); + QVERIFY(process.readAll().contains("Unexpected positional arguments.")); + + process.start(command, { "-d", "-n", "-r", root }); + QVERIFY(process.waitForFinished(10000)); + QCOMPARE(process.exitCode(), 1); + QVERIFY(process.readAll().contains("Missing required --file option.")); + + QString external = temp.path() + "/external"; + QString external_elf = external + "/test.elf"; + QVERIFY(QDir().mkpath(external)); + createFile(external_elf); + for (QString platform: { "sg", "nsg" }) { + QString drive = platform == "sg" ? "1:" : "a:"; + process.start(command, { "-d", "-n", "-r", root, "-p", platform, + "-B", external + "=" + drive + "/ZBin", "-f", external_elf }); + QVERIFY(process.waitForFinished(10000)); + QCOMPARE(process.exitCode(), 0); + output = process.readAll(); + QVERIFY(output.contains("'--file' '" + drive + "/ZBin/test.elf'")); + } + + process.start(command, { "-v" }); + QVERIFY(process.waitForFinished(10000)); + QCOMPARE(process.exitCode(), 0); + QVERIFY(process.readAll().contains("1.0.0")); + + process.start(command, { "--help" }); + QVERIFY(process.waitForFinished(10000)); + QCOMPARE(process.exitCode(), 0); + QVERIFY(process.readAll().contains("--file")); +} + +void LauncherTest::findsSdkInParentOrHome() { + QTemporaryDir temp; + QVERIFY(temp.isValid()); + QString bin = temp.path() + "/apps/nested/bin"; + QString sdk = temp.path() + "/apps/sdk"; + QString home = temp.path() + "/home"; + QString root = temp.path() + "/root"; + QString elf = root + "/Data/test.elf"; + QVERIFY(QDir().mkpath(bin)); + QVERIFY(QDir().mkpath(sdk + "/swilib/include")); + QVERIFY(QDir().mkpath(root + "/Data")); + createFile(elf); + + QString command = bin + "/elf-emu"; + QVERIFY(QFile::copy(QCoreApplication::applicationDirPath() + "/elf-emu", command)); + QProcess process; + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + env.remove("ELF_EMU_SDK"); + process.setProcessEnvironment(env); + process.start(command, { "-d", "-n", "-r", root, "-f", elf }); + QVERIFY(process.waitForFinished(10000)); + QCOMPARE(process.exitCode(), 0); + QVERIFY(QString::fromLocal8Bit(process.readAll()).contains("source=" + sdk)); + + QString home_sdk = home + "/dev/sie/sdk"; + QVERIFY(QDir().mkpath(home + "/dev/sie")); + QVERIFY(QDir().rename(sdk, home_sdk)); + env.insert("HOME", home); + process.setProcessEnvironment(env); + process.start(command, { "-d", "-n", "-r", root, "-f", elf }); + QVERIFY(process.waitForFinished(10000)); + QCOMPARE(process.exitCode(), 0); + QVERIFY(QString::fromLocal8Bit(process.readAll()).contains("source=" + home_sdk)); +} + +QTEST_GUILESS_MAIN(LauncherTest) + +#include "LauncherTest.moc" diff --git a/src/FFS.cpp b/src/FFS.cpp index e3445bf..b878cae 100644 --- a/src/FFS.cpp +++ b/src/FFS.cpp @@ -2,6 +2,7 @@ #include "src/utils/string.h" #include +#include #include #include #include @@ -9,7 +10,7 @@ const std::regex DOS_PATH_RE("^([0-9a-f]:)(?:\\\\|/)(.*?)$", std::regex_constants::ECMAScript | std::regex_constants::icase); static std::map m_mountPoints; -static void rsync(const std::string &source, const std::string &destination); +static void rsync(const std::string &source, const std::string &destination, bool skipExisting = false, const std::vector &exclude = {}); void FFS::mount(const std::string &drive, const std::string &path) { spdlog::debug("Mounting: {}/ -> {}", path, drive); @@ -18,13 +19,13 @@ void FFS::mount(const std::string &drive, const std::string &path) { m_mountPoints[drive] = ""; } -void FFS::mountAndInit(const std::string &drive, const std::string &path, const std::string &defaultContentPath) { - if (!std::filesystem::exists(path)) { +void FFS::mountAndInit(const std::string &drive, const std::string &path, const std::string &defaultContentPath, bool initialize, const std::vector &exclude) { + bool exists = std::filesystem::exists(path); + if (!exists) std::filesystem::create_directories(path); - if (std::filesystem::exists(defaultContentPath)) { - spdlog::debug("Copying: {} -> {}", defaultContentPath, path); - rsync(defaultContentPath, path); - } + if ((!exists || initialize) && std::filesystem::exists(defaultContentPath)) { + spdlog::debug("Copying: {} -> {}", defaultContentPath, path); + rsync(defaultContentPath, path, exists, exclude); } mount(drive, path); } @@ -117,16 +118,19 @@ std::string FFS::caseInsensitivePath(const std::string &path) { return tmpPath; } -static void rsync(const std::string &source, const std::string &destination) { +static void rsync(const std::string &source, const std::string &destination, bool skipExisting, const std::vector &exclude) { + if (std::find(exclude.begin(), exclude.end(), destination) != exclude.end()) + return; if (!std::filesystem::exists(destination)) std::filesystem::create_directories(destination); for (const auto &entry: std::filesystem::directory_iterator(source)) { const auto &entryPath = entry.path(); auto destinationPath = destination / entryPath.filename(); if (std::filesystem::is_directory(entryPath)) { - rsync(entryPath, destinationPath); + rsync(entryPath, destinationPath, skipExisting, exclude); } else if (std::filesystem::is_regular_file(entryPath) || std::filesystem::is_symlink(entryPath)) { - std::filesystem::copy(entryPath, destinationPath, std::filesystem::copy_options::overwrite_existing | std::filesystem::copy_options::recursive); + if (!skipExisting || std::filesystem::symlink_status(destinationPath).type() == std::filesystem::file_type::not_found) + std::filesystem::copy(entryPath, destinationPath, std::filesystem::copy_options::overwrite_existing | std::filesystem::copy_options::recursive); } else { throw std::runtime_error(std::format("Unrecognized file type: {}", entryPath.string())); } diff --git a/src/FFS.h b/src/FFS.h index 0711dd3..0daeaeb 100644 --- a/src/FFS.h +++ b/src/FFS.h @@ -1,11 +1,12 @@ #pragma once #include +#include class FFS { public: static void mount(const std::string &drive, const std::string &path); - static void mountAndInit(const std::string &drive, const std::string &path, const std::string &defaultContentPath); + static void mountAndInit(const std::string &drive, const std::string &path, const std::string &defaultContentPath, bool initialize = false, const std::vector &exclude = {}); static std::string unix2dos(const std::string &path); static std::string dos2unix(const std::string &path); static std::string any2dos(const std::string &path); diff --git a/src/IPC.cpp b/src/IPC.cpp index 4239f1b..1a7ec94 100644 --- a/src/IPC.cpp +++ b/src/IPC.cpp @@ -1,43 +1,38 @@ -#include "src/main.h" #include "src/IPC.h" #include "src/io/Loop.h" -#include "src/utils/string.h" #include "src/utils/time.h" -#include +#include +#include #include #include +#include #include -#include -#include -#include -#include #include +#include +#include IPC *IPC::instance() { static IPC ipc; return &ipc; } -void IPC::start() { - m_socket_path = tempDir() + "/helper.socket"; - m_server_fd = openUnixSock(m_socket_path.c_str()); - m_screen_buffer = createSharedMemory(&m_screen_buffer_id); +void IPC::start(int port) { + m_screen.resize(m_window_height * m_window_width * 4); - runDetachedProcess(m_helper_path, { - std::to_string(m_screen_buffer_id), - m_socket_path, - std::to_string(m_window_width), - std::to_string(m_window_height) - }); + if (port == 0) + return; - spdlog::debug("Waiting for elfloader-helper..."); + m_server_fd = openTcpSock(port); + spdlog::debug("Waiting for GUI on TCP port {}...", port); - m_client_fd = waitForClient(m_server_fd, 10000); + m_client_fd = waitForClient(m_server_fd, 30000); + close(m_server_fd); + m_server_fd = -1; if (m_client_fd < 0) - throw std::runtime_error("Timeout! Helper process is not running!"); + throw std::runtime_error("Timeout waiting for GUI connection."); - spdlog::debug("Connection established."); + spdlog::debug("GUI connection established."); Loop::instance()->watchFd(m_client_fd, Loop::WATCH_READ, [this](Loop::IoWatcherEv ev, int fd) { uint8_t buffer[4096]; @@ -46,10 +41,13 @@ void IPC::start() { case Loop::EV_CAN_READ: { int readed = read(m_client_fd, buffer, sizeof(buffer)); - if (readed >= 0) { + if (readed > 0) { m_rx_buffer.insert(m_rx_buffer.end(), buffer, buffer + readed); parseCommand(); - } else if (errno != EINTR) { + } else if (readed == 0) { + Loop::instance()->unwatchFd(fd); + Loop::instance()->stop(); + } else if (errno != EINTR && errno != EAGAIN) { throw std::runtime_error(std::format("IPC read(): {}", strerror(errno))); } } @@ -57,35 +55,41 @@ void IPC::start() { case Loop::EV_CAN_WRITE: { - m_tx_mutex.lock(); - int written = write(m_client_fd, &m_tx_buffer[0], m_tx_buffer.size()); + std::lock_guard lock(m_tx_mutex); + int written = write(m_client_fd, m_tx_buffer.data(), m_tx_buffer.size()); if (written >= 0) { m_tx_buffer.erase(m_tx_buffer.begin(), m_tx_buffer.begin() + written); - if (!m_tx_buffer.size()) + if (m_tx_buffer.empty()) Loop::instance()->setWatchFdEvents(m_client_fd, Loop::WATCH_READ); - } else if (errno != EINTR) { - m_tx_mutex.unlock(); + } else if (errno != EINTR && errno != EAGAIN) { throw std::runtime_error(std::format("IPC write(): {}", strerror(errno))); } - m_tx_mutex.unlock(); } break; case Loop::EV_HUP: case Loop::EV_ERROR: Loop::instance()->unwatchFd(fd); - spdlog::debug("Window closed..."); Loop::instance()->stop(); - // kill(getpid(), SIGINT); break; } }); + + IpcPacketScreen screen = { + .header = { IPC_CMD_SCREEN, sizeof(IpcPacketScreen) }, + .width = static_cast(m_window_width), + .height = static_cast(m_window_height), + }; + send(&screen.header); + sendRedraw(0, 0, m_window_width - 1, m_window_height - 1); } void IPC::parseCommand() { while (m_rx_buffer.size() >= sizeof(IpcPacket)) { - IpcPacket *pkt = reinterpret_cast(&m_rx_buffer[0]); + IpcPacket *pkt = reinterpret_cast(m_rx_buffer.data()); + if (pkt->size < sizeof(IpcPacket) || pkt->size > 16 * 1024 * 1024) + throw std::runtime_error("Invalid IPC packet size."); if (m_rx_buffer.size() < pkt->size) break; @@ -99,22 +103,36 @@ void IPC::handleCommand(IpcPacket *pkt) { m_handlers[pkt->cmd](pkt); } -uint8_t *IPC::createSharedMemory(int *mem_id) { - *mem_id = shmget(IPC_PRIVATE, m_window_height * m_window_width * 4, IPC_CREAT | 0600); - if (*mem_id < 0) - throw std::runtime_error(std::format("shmget(): {}", strerror(errno))); - auto mem = reinterpret_cast(shmat(*mem_id, NULL, 0)); - if (mem == (uint8_t *) -1) - throw std::runtime_error(std::format("shmat(): {}", strerror(errno))); - return mem; -} - void IPC::send(IpcPacket *pkt) { - m_tx_mutex.lock(); + if (m_client_fd < 0) + return; + + std::lock_guard lock(m_tx_mutex); uint8_t *data = reinterpret_cast(pkt); m_tx_buffer.insert(m_tx_buffer.end(), data, data + pkt->size); Loop::instance()->setWatchFdEvents(m_client_fd, Loop::WATCH_READ | Loop::WATCH_WRITE); - m_tx_mutex.unlock(); +} + +void IPC::sendRedraw(int x, int y, int x2, int y2) { + if (m_client_fd < 0) + return; + + IpcPacketRedraw redraw = { + .header = { + IPC_CMD_REDRAW, + static_cast(sizeof(IpcPacketRedraw) + m_screen.size()), + }, + .x = x, + .y = y, + .x2 = x2, + .y2 = y2, + }; + + std::lock_guard lock(m_tx_mutex); + uint8_t *header = reinterpret_cast(&redraw); + m_tx_buffer.insert(m_tx_buffer.end(), header, header + sizeof(redraw)); + m_tx_buffer.insert(m_tx_buffer.end(), m_screen.begin(), m_screen.end()); + Loop::instance()->setWatchFdEvents(m_client_fd, Loop::WATCH_READ | Loop::WATCH_WRITE); } int IPC::waitForClient(int sock, int timeout) { @@ -141,12 +159,12 @@ int IPC::waitForClient(int sock, int timeout) { } if ((pfd[0].revents & POLLIN)) { - int new_client = accept4(sock, NULL, NULL, SOCK_NONBLOCK); - if (new_client < 0) { + int client = accept4(sock, NULL, NULL, SOCK_NONBLOCK); + if (client < 0) { spdlog::error("accept4(): {}", strerror(errno)); return -1; } - return new_client; + return client; } int elapsed = getCurrentTimestamp() - now; @@ -157,21 +175,23 @@ int IPC::waitForClient(int sock, int timeout) { return -1; } -int IPC::openUnixSock(const char *name) { - int sock; - if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) +int IPC::openTcpSock(int port) { + int sock = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (sock < 0) throw std::runtime_error(std::format("socket(): {}", strerror(errno))); - struct sockaddr_un sock_un; - memset(&sock_un, 0, sizeof(struct sockaddr_un)); + int reuse_addr = 1; + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)) < 0) { + close(sock); + throw std::runtime_error(std::format("setsockopt(): {}", strerror(errno))); + } - sock_un.sun_family = AF_UNIX; - strcpy(sock_un.sun_path, name); + struct sockaddr_in addr = {}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_ANY); + addr.sin_port = htons(port); - unlink(name); - - int socket_length = strlen(sock_un.sun_path) + sizeof(sock_un.sun_family); - if (bind(sock, (struct sockaddr *) &sock_un, socket_length) < 0) { + if (bind(sock, reinterpret_cast(&addr), sizeof(addr)) < 0) { close(sock); throw std::runtime_error(std::format("bind(): {}", strerror(errno))); } @@ -183,25 +203,3 @@ int IPC::openUnixSock(const char *name) { return sock; } - -void IPC::runDetachedProcess(const std::string &path, const std::vector &argv) { - spdlog::debug("[exec] {} {}", path, strJoin(" ", argv)); - pid_t pid = fork(); - if (pid < 0) { - throw std::runtime_error(std::format("fork(): {}", strerror(errno))); - } else if (pid == 0) { - if (setsid() < 0) - throw std::runtime_error(std::format("setsid(): {}", strerror(errno))); - - std::vector args; - args.push_back(const_cast(path.c_str())); - for (const auto &arg :argv) - args.push_back(const_cast(arg.c_str())); - args.push_back(nullptr); - - if (execvp(path.c_str(), args.data()) == -1) - throw std::runtime_error(std::format("execvp(): {}", strerror(errno))); - - exit(0); - } -} diff --git a/src/IPC.h b/src/IPC.h index da697aa..07140b1 100644 --- a/src/IPC.h +++ b/src/IPC.h @@ -4,8 +4,9 @@ #include #include #include -#include +#include #include +#include #include class IPC { @@ -15,55 +16,35 @@ protected: std::mutex m_tx_mutex; std::vector m_rx_buffer; std::vector m_tx_buffer; - std::binary_semaphore m_wait_for_client{0}; - std::function m_start_callback; - int m_screen_buffer_id = -1; - uint8_t *m_screen_buffer = nullptr; - std::string m_helper_path; - std::string m_socket_path; + std::vector m_screen; int m_window_width = 132; int m_window_height = 176; std::map> m_handlers; - uint8_t *createSharedMemory(int *mem_id); void send(IpcPacket *pkt); void parseCommand(); void handleCommand(IpcPacket *pkt); - void runDetachedProcess(const std::string &path, const std::vector &argv); - int openUnixSock(const char *name); + int openTcpSock(int port); int waitForClient(int dock, int timeout); public: static IPC *instance(); inline uint8_t *getScreenBuffer() { - return m_screen_buffer; + return m_screen.data(); } inline void addHandler(IpcCmd cmd, std::function callback) { m_handlers[cmd] = callback; } - inline void sendRedraw(int x, int y, int x2, int y2) { - IpcPacketRedraw packet = { - .header = { IPC_CMD_REDRAW, sizeof(IpcPacketRedraw) }, - .x = x, - .y = y, - .x2 = x2, - .y2 = y2, - }; - send(&packet.header); - } - - inline void setHelperPath(const std::string &helper_path) { - m_helper_path = helper_path; - } + void sendRedraw(int x, int y, int x2, int y2); inline void setWindowSize(int w, int h) { m_window_width = w; m_window_height = h; } - void start(); + void start(int port); }; diff --git a/src/Resources.cpp b/src/Resources.cpp index f27c368..4455e7b 100644 --- a/src/Resources.cpp +++ b/src/Resources.cpp @@ -12,8 +12,9 @@ #include "src/utils/string.h" #include "src/utils/BinaryStream.h" +#ifdef NEWSGOLD static const int E1XX_PICS[] = { -#if defined(ELKA) +#ifdef ELKA 1357, 1355, 1354, 1349, 1351, 1358, 335, 321, 332, 312, 313, 310, 311, 305, 319, 320, 321, 323, 331, 333, 334, 1, 1338, 1340, 50, 43, 49, 42, 46, 1, 55, 40, 47, 53, 36, 35, 39, 37, 38, 1344, 34, 184, 1365, 1366, 1367, 1368, 1361, @@ -28,7 +29,7 @@ static const int E1XX_PICS[] = { 149, 77, 78, 83, 79, 81, 82, 80, 84, 74, 75, 86, 87, 88, 85, 1480, 1481, 1482, 1483, 1484, 1485, 449, 599, 227, 223, 222, 187, 214, 228, 212, 213, 1163, 1489, 419, 1466, 1465, 44, 45, 1172 -#elif defined(NEWSGOLD) +#else 1401, 1399, 1398, 1393, 1395, 1402, 374, 360, 371, 351, 352, 349, 350, 344, 358, 359, 360, 362, 370, 372, 373, 1, 1382, 1384, 68, 61, 67, 60, 64, 1, 73, 58, 65, 71, 54, 53, 57, 55, 56, 1388, 52, 204, 1409, 1410, 1411, 1412, 1405, @@ -45,6 +46,7 @@ static const int E1XX_PICS[] = { 1533, 468, 1510, 1509, 62, 63, 1214 #endif }; +#endif static Resources *m_instance = nullptr; @@ -70,11 +72,13 @@ void Resources::load() { } int Resources::getPicIdByUnicode(uint32_t num) { +#ifdef NEWSGOLD if ((num & 0xFF00) == 0xE100) { size_t index = num & 0xFF; if (index < std::size(E1XX_PICS)) return E1XX_PICS[index]; } +#endif return -1; } @@ -227,7 +231,11 @@ void Resources::loadColorTheme() { std::smatch m; std::regex color_re("^\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s*$", std::regex_constants::ECMAScript | std::regex_constants::icase); +#ifdef NEWSGOLD std::string col = readFile(FFS::dos2unix("2:\\Default\\ColorControls.col")); +#else + std::string col = readFile(FFS::dos2unix("b:\\Default\\SkinScheme.col")); +#endif bool color_data_started = false; for (auto line: strSplit("\n", col)) { diff --git a/src/elfloader/debug.c b/src/elfloader/debug.c index 10099d1..f0f6254 100644 --- a/src/elfloader/debug.c +++ b/src/elfloader/debug.c @@ -26,7 +26,8 @@ void loader_gdb_add_lib(Elf32_Exec *ex) { struct link_map *map = &ex->linkmap; map->l_addr = (Elf32_Addr) (ex->body - ex->v_addr); - map->l_name = ex->fname; + const char *name = strrchr(ex->fname, '\\'); + map->l_name = name ? name + 1 : ex->fname; map->l_ld = (Elf32_Addr) ex->dynamic; if (r_debug_tail) { @@ -44,15 +45,27 @@ void loader_gdb_add_lib(Elf32_Exec *ex) { _gdb_brk(); } -void loader_gdb_remove_lib(Elf32_Exec *ex) { - struct link_map *map = &ex->linkmap; - - if (r_debug_tail == map) - r_debug_tail = map->l_prev; - - if (map->l_prev) map->l_prev->l_next = map->l_next; - if (map->l_next) map->l_next->l_prev = map->l_prev; -} +void loader_gdb_remove_lib(Elf32_Exec *ex) { + struct link_map *map = &ex->linkmap; + struct link_map *cur = _r_debug.r_map; + while (cur && cur != map) + cur = cur->l_next; + if (!cur) + return; + + _r_debug.r_state = RT_DELETE; + _gdb_brk(); + + if (r_debug_tail == map) + r_debug_tail = map->l_prev; + + if (map->l_prev) map->l_prev->l_next = map->l_next; + else _r_debug.r_map = map->l_next; + if (map->l_next) map->l_next->l_prev = map->l_prev; + + _r_debug.r_state = RT_CONSISTENT; + _gdb_brk(); +} static void _gdb_brk(void) { if (_r_debug.r_brk) diff --git a/src/io/Loop.h b/src/io/Loop.h index 745f86a..d2dfb80 100644 --- a/src/io/Loop.h +++ b/src/io/Loop.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -60,7 +61,7 @@ protected: std::map> m_timers; std::mutex m_mutex; - bool m_need_stop = false; + std::atomic m_need_stop = false; int m_global_timer_id = 0; protected: diff --git a/src/main.cpp b/src/main.cpp index 304be18..984e403 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,4 +1,6 @@ #include +#include +#include #include #include #include @@ -9,12 +11,10 @@ #include #include #include -#include #include #include #include -#include "src/main.h" #include "src/IPC.h" #include "src/elfloader/loader.h" #include "src/elfloader/env.h" @@ -73,10 +73,6 @@ int main(int argc, char **argv) { if (std::filesystem::exists(resources_dir + "/../sdk/swilib/include")) default_sdk_path = std::filesystem::canonical(resources_dir + "/../sdk"); - std::string host_helper_path = resources_dir + "/elfloader3-helper"; - if (std::filesystem::exists(resources_dir + "/host-helper/build/elfloader3-helper")) - host_helper_path = resources_dir + "/host-helper/build/elfloader3-helper"; - argparse::ArgumentParser program("elfloader", "1.0.0"); program.add_argument("-f", "--file") .help("Path to file.elf") @@ -103,6 +99,18 @@ int main(int argc, char **argv) { .default_value(false) .implicit_value(true) .nargs(0); + program.add_argument("--ipc-port") + .help("TCP port used by the host GUI") + .default_value(0) + .scan<'i', int>(); + program.add_argument("--init-missing") + .default_value>({}) + .append() + .help("Initialize a drive directory missing before Docker mounted binds"); + program.add_argument("--init-exclude") + .default_value>({}) + .append() + .help("Exclude a bind mount from drive initialization"); try { program.parse_args(argc, argv); @@ -117,20 +125,30 @@ int main(int argc, char **argv) { } else { spdlog::set_level(spdlog::level::info); } + loader_gdb_init(); // Init FFS std::string default_fs_content = resources_dir + "/rootfs/" + getPlatformName(); std::string root_path = program.get("--root"); + auto init_missing = program.get>("--init-missing"); + auto init_exclude = program.get>("--init-exclude"); + auto needsInit = [&](const std::string &dir) { + return std::find(init_missing.begin(), init_missing.end(), dir) != init_missing.end(); + }; - FFS::mountAndInit("0:", root_path + "/Data", default_fs_content + "/Data"); + FFS::mountAndInit("0:", root_path + "/Data", default_fs_content + "/Data", needsInit("Data"), init_exclude); #ifdef NEWSGOLD - FFS::mountAndInit("1:", root_path + "/Cache", default_fs_content + "/Cache"); - FFS::mountAndInit("2:", root_path + "/Config", default_fs_content + "/Config"); + FFS::mountAndInit("1:", root_path + "/Cache", default_fs_content + "/Cache", needsInit("Cache"), init_exclude); + FFS::mountAndInit("2:", root_path + "/Config", default_fs_content + "/Config", needsInit("Config"), init_exclude); #else - FFS::mountAndInit("a:", root_path + "/Cache", default_fs_content + "/Cache"); - FFS::mountAndInit("b:", root_path + "/Config", default_fs_content + "/Config"); + FFS::mountAndInit("a:", root_path + "/Cache", default_fs_content + "/Cache", needsInit("Cache"), init_exclude); + FFS::mountAndInit("b:", root_path + "/Config", default_fs_content + "/Config", needsInit("Config"), init_exclude); #endif - FFS::mountAndInit("4:", root_path + "/MMCard", default_fs_content + "/MMCard"); + FFS::mountAndInit("4:", root_path + "/MMCard", default_fs_content + "/MMCard", needsInit("MMCard"), init_exclude); + for (const auto &dir: { "Data", "Cache", "Config", "MMCard" }) { + if (needsInit(dir) && std::find(init_exclude.begin(), init_exclude.end(), root_path + "/" + dir) == init_exclude.end()) + std::filesystem::remove(root_path + "/.elf-emu-init-" + dir); + } FFS::mount("5:", getUnixHomeDir()); FFS::mount("6:", ""); @@ -205,8 +223,7 @@ int main(int argc, char **argv) { auto *ipc = IPC::instance(); ipc->setWindowSize(ScreenW(), ScreenH()); - ipc->setHelperPath(host_helper_path); - ipc->start(); + ipc->start(program.get("--ipc-port")); Resources::init(resources_dir); OS_Init(); @@ -214,12 +231,15 @@ int main(int argc, char **argv) { loader_install_swihook(); loader_init_swilib(); - Loop::instance()->setTimeout([=]() { - GBS_RunInContext(MMI_CEPID, [=]() { + std::atomic run_result = 0; + Loop::instance()->setTimeout([=, &run_result]() { + GBS_RunInContext(MMI_CEPID, [=, &run_result]() { Elf32_Exec *ex = loader_elf_open(arg0.c_str()); if (!ex) { spdlog::error("Invalid ELF: {}", elf_file); - exit(1); + run_result = 1; + Loop::instance()->stop(); + return; } auto entry = (int (*)(const char *, const char *, const void *)) loader_elf_entry(ex); @@ -234,26 +254,15 @@ int main(int argc, char **argv) { std::signal(SIGALRM, [](int signal) { const char err[] = "Program hangs at exit, sending SIGKILL...\n"; - write(2, err, strlen(err)); + ssize_t written = write(2, err, strlen(err)); + (void) written; kill(getpid(), SIGKILL); }); alarm(10); MOPIProcessGroup::cleanup(); - return 0; -} - -static std::string makeTempDir() { - std::string temp_dir = std::filesystem::temp_directory_path().string() + "/elfloader3-XXXXXX"; - if (!mkdtemp(temp_dir.data())) - throw std::runtime_error(std::format("mkdtemp(): {}", strerror(errno))); - return temp_dir; -} - -std::string tempDir() { - static std::string temp_dir = makeTempDir(); - return temp_dir; + return run_result; } static std::string buildLibraryPathEnv(const std::vector &library_path) { diff --git a/src/main.h b/src/main.h deleted file mode 100644 index 26437f9..0000000 --- a/src/main.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -#include - -std::string tempDir(); diff --git a/src/swi/csm.cpp b/src/swi/csm.cpp index 0a03e94..9adf9e7 100644 --- a/src/swi/csm.cpp +++ b/src/swi/csm.cpp @@ -24,7 +24,9 @@ void CSM_Init() { LL_Init(&csm_q->csm); LL_Init(&csm_q->cmd); +#ifdef NEWSGOLD LL_Init(&csm_q->csm_background); +#endif } static void CSM_Destroy(CSM_RAM *csm) { diff --git a/src/swi/file.cpp b/src/swi/file.cpp index 2a697ee..842849b 100644 --- a/src/swi/file.cpp +++ b/src/swi/file.cpp @@ -126,10 +126,17 @@ int setfilesize(int fd, uint32_t length, uint32_t *err) { return ret; } +#ifdef NEWSGOLD int GetWavLen(const char *path) { spdlog::debug("{}: not implemented!", __func__); return -1; } +#else +int GetWavLen(TWavLen *wav_info) { + spdlog::debug("{}: not implemented!", __func__); + return -1; +} +#endif static void _fillDirEntry(DIR_ENTRY *de, const std::string &file) { struct stat st; diff --git a/src/swi/gbs.cpp b/src/swi/gbs.cpp index b36dba8..a1a0ae0 100644 --- a/src/swi/gbs.cpp +++ b/src/swi/gbs.cpp @@ -205,7 +205,11 @@ void* GetGBSProcAddress(short cepid) { } void CreateICL(PGROUP *pgroup) { +#ifdef NEWSGOLD MOPIProcessGroup::createProcessGroup(pgroup->id << 8, pgroup->name, pgroup->prio); +#else + MOPIProcessGroup::createProcessGroup(pgroup->id << 8, std::format("PGROUP_{:02X}", pgroup->id), pgroup->prio); +#endif } void *GBS_CreateProcessGroupResource(int mask, int unk_zero, PGROUP *pgroup, int size) { diff --git a/src/swi/gui.h b/src/swi/gui.h index e8eaaec..9163e64 100644 --- a/src/swi/gui.h +++ b/src/swi/gui.h @@ -116,14 +116,15 @@ void LCDLAYER_Init(); void LCDLAYER_Create(LCDLAYER *layer, void *unk, int depth, uint8_t type, void *buffer, int width, int height); void LCDLAYER_InvalidateRegion(LCDLAYER *layer, int x, int y, int x2, int y2); void LCDLAYER_ResetInvalidateRegion(LCDLAYER *layer); +void LCDLAYER_ClearRedrawRequest(LCDLAYER *layer); static inline Bitmap::Type LCDLAYER_GetBitmapType(LCDLAYER *layer) { switch (layer->depth) { - case LCDLAYER_DEPTH_BGR233: return Bitmap::TYPE_BGR233; + case LCDLAYER_DEPTH_RGB332: return Bitmap::TYPE_BGR233; case LCDLAYER_DEPTH_BGRA4444: return Bitmap::TYPE_BGRA4444; - case LCDLAYER_DEPTH_BGR565: return Bitmap::TYPE_BGR565; + case LCDLAYER_DEPTH_RGB565: return Bitmap::TYPE_BGR565; default: - case LCDLAYER_DEPTH_BGRA8888: return Bitmap::TYPE_BGRA8888S; + case LCDLAYER_DEPTH_ARGB8888: return Bitmap::TYPE_BGRA8888S; } } diff --git a/src/swi/gui/lcdlayer.cpp b/src/swi/gui/lcdlayer.cpp index 9832ad7..e3f39b5 100644 --- a/src/swi/gui/lcdlayer.cpp +++ b/src/swi/gui/lcdlayer.cpp @@ -4,6 +4,7 @@ #include "swilib/gbs.h" #include #include +#include #include #include #include @@ -12,18 +13,21 @@ static LCDLAYER main_lcd_layer = {}; static LCDLAYER_LIST lcd_layers_list[16] = {}; static RAP_LCDLAYER_LIST rap_lcd_layers_list[16] = {}; static int GetLayerIdByCepId(int *layer); +#ifndef NEWSGOLD +static std::unordered_set redraw_requested; +#endif void LCDLAYER_Init() { - LCDLAYER_Create(&main_lcd_layer, nullptr, LCDLAYER_DEPTH_BGR565, 0, nullptr, ScreenW(), ScreenH()); + LCDLAYER_Create(&main_lcd_layer, nullptr, LCDLAYER_DEPTH_RGB565, 0, nullptr, ScreenW(), ScreenH()); } static int LCDLAYER_CalcBufferSize(int depth, int w, int h) { switch (depth) { case LCDLAYER_DEPTH_WB: return (w + 7) / 8 + h; - case LCDLAYER_DEPTH_BGR233: return w * h; + case LCDLAYER_DEPTH_RGB332: return w * h; case LCDLAYER_DEPTH_BGRA4444: return w * h * 2; - case LCDLAYER_DEPTH_BGR565: return w * h * 2; - case LCDLAYER_DEPTH_BGRA8888: return w * h * 4; + case LCDLAYER_DEPTH_RGB565: return w * h * 2; + case LCDLAYER_DEPTH_ARGB8888: return w * h * 4; } return 0; } @@ -35,10 +39,16 @@ void LCDLAYER_Create(LCDLAYER *layer, void *unk, int depth, uint8_t type, void * layer->h = height; if (!buffer) { +#ifdef NEWSGOLD layer->allocated_size = LCDLAYER_CalcBufferSize(depth, width, height); layer->buffer = malloc(layer->allocated_size); +#else + layer->buffer = malloc(LCDLAYER_CalcBufferSize(depth, width, height)); +#endif } else { +#ifdef NEWSGOLD layer->allocated_size = 0; +#endif layer->buffer = nullptr; } @@ -102,10 +112,25 @@ void LCDLAYER_Flush(LCDLAYER *layer) { } void LCDLAYER_Redraw(LCDLAYER *layer) { +#ifdef NEWSGOLD if (layer->redraw_requested == 0) { GBS_SendMessage(LCD_DISPLAYQUEUE_CEPID, LCD_DISPLAYQUEUE_CMD_REDRAW, 0, layer, 0); layer->redraw_requested = 1; } +#else + if (!redraw_requested.contains(layer)) { + GBS_SendMessage(LCD_DISPLAYQUEUE_CEPID, LCD_DISPLAYQUEUE_CMD_REDRAW, 0, layer, 0); + redraw_requested.insert(layer); + } +#endif +} + +void LCDLAYER_ClearRedrawRequest(LCDLAYER *layer) { +#ifdef NEWSGOLD + layer->redraw_requested = 0; +#else + redraw_requested.erase(layer); +#endif } void LCDLAYER_SetBufferDepth(LCDLAYER *layer, char depth) { diff --git a/src/swi/image.cpp b/src/swi/image.cpp index 082ec7d..50bbdb3 100644 --- a/src/swi/image.cpp +++ b/src/swi/image.cpp @@ -79,12 +79,12 @@ int CalcBitmapSize(short w, short h, char type) { case IMGHDR_TYPE_WB: return ((w + 7) / 8) * h; case 2: return ((w + 3) / 4) * h; // WTF case 3: return ((w + 3) / 4) * h; // WTF - case IMGHDR_TYPE_BGR233: return w * h; + case IMGHDR_TYPE_RGB332: return w * h; case 6: return ((w + 7) / 8 + 8) * h; case 7: return w * h * 2; // WTF - case IMGHDR_TYPE_BGR565: return w * h * 2; + case IMGHDR_TYPE_RGB565: return w * h * 2; case 9: return w * h * 2; // WTF - case IMGHDR_TYPE_BGRA8888: return w * h * 4; + case IMGHDR_TYPE_ARGB8888: return w * h * 4; } spdlog::error("{}: unknown bitmap type: {}", __func__, type); abort(); @@ -113,7 +113,7 @@ IMGHDR *IMG_LoadAny(const std::string &path, bool only_rgb888) { IMGHDR *new_img = (IMGHDR *) malloc(sizeof(IMGHDR)); new_img->w = w; new_img->h = h; - new_img->bpnum = IMGHDR_TYPE_BGRA8888; + new_img->bpnum = IMGHDR_TYPE_ARGB8888; new_img->bitmap = bitmap; bool is_bw = true; @@ -169,9 +169,9 @@ IMGHDR *IMG_LoadAny(const std::string &path, bool only_rgb888) { Bitmap::Type IMG_GetBitmapType(int bpnum) { switch (bpnum) { case IMGHDR_TYPE_WB: return Bitmap::TYPE_WB; - case IMGHDR_TYPE_BGR233: return Bitmap::TYPE_BGR233; - case IMGHDR_TYPE_BGR565: return Bitmap::TYPE_BGR565; - case IMGHDR_TYPE_BGRA8888: return Bitmap::TYPE_BGRA8888; + case IMGHDR_TYPE_RGB332: return Bitmap::TYPE_BGR233; + case IMGHDR_TYPE_RGB565: return Bitmap::TYPE_BGR565; + case IMGHDR_TYPE_ARGB8888: return Bitmap::TYPE_BGRA8888; } spdlog::error("Invalid bitmap type: {}", bpnum); abort(); diff --git a/src/swi/init.cpp b/src/swi/init.cpp index 9cdd364..b40e757 100644 --- a/src/swi/init.cpp +++ b/src/swi/init.cpp @@ -10,14 +10,18 @@ void OS_Init() { PGROUP mmi_pgroup = {}; mmi_pgroup.id = MMI_PGROUP_ID; +#ifdef NEWSGOLD mmi_pgroup.name = (char *) "T_MMIMN"; +#endif mmi_pgroup.prio = 0x5B; CreateICL(&mmi_pgroup); PGROUP helper_pgroup = {}; helper_pgroup.id = RAP_PGROUP_ID; +#ifdef NEWSGOLD helper_pgroup.name = (char *) "T_RAP"; - mmi_pgroup.prio = 0x6E; +#endif + helper_pgroup.prio = 0x6E; CreateICL(&helper_pgroup); GUI_Init(); diff --git a/src/swi/obs.cpp b/src/swi/obs.cpp index 75fb933..b22de75 100644 --- a/src/swi/obs.cpp +++ b/src/swi/obs.cpp @@ -232,10 +232,17 @@ int Obs_Sound_SetRecordingMode(HObj obs, int recording_mode) { return -1; } +#ifdef NEWSGOLD int Obs_SetOutput_File(HObj obs, const WSHDR *filename) { spdlog::debug("{}: not implemented!", __func__); return -1; } +#else +int Obs_SetOutput_File(HObj obs, const char *filename) { + spdlog::debug("{}: not implemented!", __func__); + return -1; +} +#endif int Obs_SetOutput_Uid(HObj obs, int uid) { spdlog::debug("{}: not implemented!", __func__); diff --git a/src/swi/proc/helper.cpp b/src/swi/proc/helper.cpp index 75bf6a8..6427966 100644 --- a/src/swi/proc/helper.cpp +++ b/src/swi/proc/helper.cpp @@ -1,4 +1,5 @@ #include "src/swi/proc/helper.h" +#include #include #include @@ -15,7 +16,9 @@ void Helper_Init() { ((void (*)(int, void *))(msg.data0))(msg.submess, msg.data1); } } else { - GBS_SendMessage(MMI_CEPID, MSG_HELPER_TRANSLATOR, msg.pid_from, (void *) msg.msg, (void *) msg.submess); + GBS_SendMessage(MMI_CEPID, MSG_HELPER_TRANSLATOR, msg.pid_from, + reinterpret_cast(static_cast(msg.msg)), + reinterpret_cast(static_cast(msg.submess))); } }, 0, 0); } diff --git a/src/swi/proc/mmi.cpp b/src/swi/proc/mmi.cpp index 307800e..0f9060b 100644 --- a/src/swi/proc/mmi.cpp +++ b/src/swi/proc/mmi.cpp @@ -19,7 +19,7 @@ void MMI_Init() { return; if (msg.msg == LCD_DISPLAYQUEUE_CMD_REDRAW) { auto *layer = reinterpret_cast(msg.data0); - layer->redraw_requested = 0; + LCDLAYER_ClearRedrawRequest(layer); LCDLAYER_Flush(layer); } else { spdlog::debug("[LCD_DISPLAYQUEUE] unknown cmd {:04X}", toUnsigned(msg.msg)); diff --git a/src/swi/wstring.cpp b/src/swi/wstring.cpp index c862fd5..bde0927 100644 --- a/src/swi/wstring.cpp +++ b/src/swi/wstring.cpp @@ -131,7 +131,7 @@ int16_t wstrchr(WSHDR *ws, uint32_t start_pos, uint32_t ch) { return -1; } -int16_t wstrrchr(WSHDR *ws, uint32_t max_pos, uint32_t ch) { +uint16_t wstrrchr(WSHDR *ws, uint32_t max_pos, uint32_t ch) { assert(ws != nullptr && max_pos <= wstrlen(ws) - 1u); for (int i = max_pos; i >= 0; i--) { diff --git a/src/swilib/switab-stubs.cpp b/src/swilib/switab-stubs.cpp index c81eb8e..e8246de 100644 --- a/src/swilib/switab-stubs.cpp +++ b/src/swilib/switab-stubs.cpp @@ -1108,10 +1108,18 @@ void StartMidlet(char *midlet) { spdlog::debug("{}: not implemented!", __func__); } +#ifdef NEWSGOLD +char *GetLastJavaApplication(const CSM_RAM *csm) { + spdlog::debug("{}: not implemented!", __func__); + (void) csm; + return NULL; +} +#else char *GetLastJavaApplication() { spdlog::debug("{}: not implemented!", __func__); return NULL; } +#endif int IsNoJava() { spdlog::debug("{}: not implemented!", __func__);