Implement posix app loading (#643)

- Added POSIX desktop support for SDK builds, application packaging, and integration testing.
- Added POSIX filesystem partitions and improved application path handling.
- Added simulator support for loading and running applications dynamically.
- Improved simulator task stack handling and display startup reliability.
- Improved simulator display scaling, resizing, high-DPI support, and pointer accuracy.
- Fixed LVGL timers and input polling on POSIX. (fixes simulator with Linux on some Intel graphics platforms)
- Standardized data paths across platforms.
- Logging now works via separate task: this allows apps to write to log without it affecting their stdout (for apps that output text as relevant date for other apps, like the File Selection app)
- Fixes for app stdio
This commit is contained in:
Ken Van Hoeylandt
2026-08-31 22:09:04 +02:00
committed by GitHub
parent d3656bcd3d
commit 643cbc3806
66 changed files with 2139 additions and 336 deletions
+9
View File
@@ -10,3 +10,12 @@ tactility_add_module(app-module
INCLUDE_DIRS include/
REQUIRES TactilityKernel service-module minitar
)
# Tells source/io.cpp its real-syscall fallback must go through __real_read/write/close()
# rather than calling ::read/::write/::close() directly, on every platform whose build wraps
# those symbols (ESP-IDF always; POSIX except macOS, whose linker doesn't support --wrap) -
# see Tactility/CMakeLists.txt and the top-level CMakeLists.txt for where that's applied.
if (NOT APPLE)
tactility_get_module_name(app-module MODULE_NAME)
target_compile_definitions(${MODULE_NAME} PRIVATE TT_APP_IO_WRAPS_STDIO)
endif ()
+17
View File
@@ -111,6 +111,23 @@ struct AppStreamBinding {
*/
error_t app_manager_start_with_streams(const char* id, const struct AppStreamBinding* bindings, size_t binding_count, AppInstanceId* out_app_instance_id);
/**
* Combines app_manager_start_for_result() and app_manager_start_with_streams(): starts @a id as
* a modal child of @a parent_instance_id (see app_manager_start_for_result()'s own doc for the
* result-delivery contract) with @a bindings installed into its fd table before its task begins
* executing (see app_manager_start_with_streams()'s own doc for stream ownership). For a child
* that needs to hand back more than an int32_t (e.g. a path) via its own stdout instead of the
* "get last result" getter pattern (see app_manager_start_for_result()) - see e.g.
* tt::app::fileselection::startForExistingFile().
* @param[in] argv see app_manager_start_for_result().
* @param[in] bindings see app_manager_start_with_streams().
* @retval ERROR_NOT_FOUND no manifest with this id is registered, or no AppLoaderApi is registered
* @retval ERROR_OUT_OF_RANGE a binding's producer_fd is out of range
* @retval ERROR_RESOURCE a binding's event_group has no free bits left to claim
* @retval ERROR_NONE on success
*/
error_t app_manager_start_for_result_with_streams(const char* id, AppInstanceId parent_instance_id, int argc, const char* const argv[], const struct AppStreamBinding* bindings, size_t binding_count, AppInstanceId* out_app_instance_id);
/**
* Stop an app instance permanently. Emits APP_EVENT_CLOSE and bound-waits for its task to exit
* if it was running.
+16 -4
View File
@@ -7,7 +7,7 @@
#include <cerrno>
#ifdef ESP_PLATFORM
#if defined(TT_APP_IO_WRAPS_STDIO)
extern "C" {
ssize_t __real_read(int fd, void* buffer, size_t size);
ssize_t __real_write(int fd, const void* buffer, size_t size);
@@ -56,7 +56,7 @@ ssize_t app_io_read(int fd, void* buffer, size_t size) {
errno = EBADF;
return -1;
}
#ifdef ESP_PLATFORM
#if defined(TT_APP_IO_WRAPS_STDIO)
return __real_read(fd, buffer, size);
#else
return ::read(fd, buffer, size);
@@ -71,13 +71,25 @@ ssize_t app_io_write(int fd, const void* buffer, size_t size) {
if (file.ops->release != nullptr) {
file.ops->release(file.object);
}
// Tee to the real fd too: a bound stream only exists because a parent explicitly asked
// to capture this app instance's own output (see AppStreamBinding), but generic code
// running on that same instance's thread - most commonly the platform's own logging
// (LOG_I/etc, which calls write() the same as anything else) - has no way to know its
// output is currently being intercepted. Without this, a log line emitted while any app
// instance has its stdout captured would vanish from the console entirely instead of
// just also being visible to the capturing parent.
#if defined(TT_APP_IO_WRAPS_STDIO)
__real_write(fd, buffer, size);
#else
::write(fd, buffer, size);
#endif
return result;
}
if (table != nullptr && app_fd_table_is_app_owned(table, fd)) {
errno = EBADF;
return -1;
}
#ifdef ESP_PLATFORM
#if defined(TT_APP_IO_WRAPS_STDIO)
return __real_write(fd, buffer, size);
#else
return ::write(fd, buffer, size);
@@ -96,7 +108,7 @@ int app_io_close(int fd) {
return -1;
}
}
#ifdef ESP_PLATFORM
#if defined(TT_APP_IO_WRAPS_STDIO)
return __real_close(fd);
#else
return ::close(fd);
+4
View File
@@ -178,6 +178,10 @@ error_t app_manager_start_with_streams(const char* id, const AppStreamBinding* b
return start_internal(id, 0, 0, nullptr, bindings, binding_count, out_app_instance_id);
}
error_t app_manager_start_for_result_with_streams(const char* id, AppInstanceId parent_instance_id, int argc, const char* const argv[], const AppStreamBinding* bindings, size_t binding_count, AppInstanceId* out_app_instance_id) {
return start_internal(id, parent_instance_id, argc, copy_arguments(argc, argv), bindings, binding_count, out_app_instance_id);
}
error_t app_manager_stop(AppInstanceId app_instance_id) {
return app_scheduler_stop(app_instance_id, pdMS_TO_TICKS(2000));
}
+1
View File
@@ -38,6 +38,7 @@ static const ModuleSymbol SYMBOLS[] = {
DEFINE_MODULE_SYMBOL(app_manager_start_with_parameters),
DEFINE_MODULE_SYMBOL(app_manager_start_for_result),
DEFINE_MODULE_SYMBOL(app_manager_start_with_streams),
DEFINE_MODULE_SYMBOL(app_manager_start_for_result_with_streams),
DEFINE_MODULE_SYMBOL(app_manager_stop),
DEFINE_MODULE_SYMBOL(app_manager_get_state),
DEFINE_MODULE_SYMBOL(app_manager_find_manifest),
+7
View File
@@ -199,12 +199,19 @@ void app_task_main(void* context) {
check(pvTaskGetThreadLocalStoragePointer(nullptr, APP_INSTANCE_ID_THREAD_SLOT_INDEX) == nullptr);
vTaskSetThreadLocalStoragePointer(nullptr, APP_INSTANCE_ID_THREAD_SLOT_INDEX, reinterpret_cast<void*>(static_cast<uintptr_t>(ctx->app_instance_id)));
// Debug logging so it's invisible by default
// When logging happens, it can distort the application stdout, which breaks apps that use
// stdout to output important information, such as the file selection dialog app.
LOG_I(TAG, "[instance %lu] Task started", ctx->app_instance_id);
set_state(ctx->app_instance_id, APP_INSTANCE_STATE_ACTIVE);
int32_t result = ctx->loader->run(ctx->runtime, ctx->app_instance_id, ctx->argc, ctx->argv);
// The platform might buffer stdout (e.g. esp-idf with newlib)
// Do a manual flush to ensure data has been written:
fflush(stdout);
vTaskSetThreadLocalStoragePointer(nullptr, APP_INSTANCE_ID_THREAD_SLOT_INDEX, nullptr);
ctx->loader->unload(ctx->runtime);
+21
View File
@@ -6,10 +6,31 @@ enable_language(C CXX ASM)
file(GLOB_RECURSE TEST_SOURCES CONFIGURE_DEPENDS ${PROJECT_SOURCE_DIR}/source/*.cpp)
add_executable(AppModuleTests EXCLUDE_FROM_ALL ${TEST_SOURCES})
if (NOT APPLE)
# Provides __wrap_read/write/close for the -Wl,--wrap= below (see Tactility/CMakeLists.txt
# for the canonical pairing of this file with those flags).
target_sources(AppModuleTests PRIVATE ${CMAKE_CURRENT_LIST_DIR}/../../../Tactility/Source/AppStdioWrap.cpp)
endif ()
target_include_directories(AppModuleTests PRIVATE ${DOCTESTINC})
add_test(NAME AppModuleTests COMMAND AppModuleTests)
# Matches app-module's own TT_APP_IO_WRAPS_STDIO (see Modules/app-module/CMakeLists.txt):
# io.cpp calls __real_read/write/close() on non-Apple POSIX, so any final link of it needs
# these wraps too, or those symbols go unresolved. The printf-family/getc-family flags are
# needed for the same reason: AppStdioWrap.cpp compiles those __wrap_* functions unconditionally
# on this platform (see its own #if guard), and they reference __real_vfprintf/fputs/fputc/
# fgetc/fgets - those only exist once the matching --wrap flag is passed.
if (NOT APPLE)
target_link_options(AppModuleTests PRIVATE
"-Wl,--wrap=read" "-Wl,--wrap=write" "-Wl,--wrap=close"
"-Wl,--wrap=printf" "-Wl,--wrap=fprintf" "-Wl,--wrap=vprintf" "-Wl,--wrap=vfprintf"
"-Wl,--wrap=puts" "-Wl,--wrap=fputs" "-Wl,--wrap=putchar" "-Wl,--wrap=fputc"
"-Wl,--wrap=getchar" "-Wl,--wrap=fgetc" "-Wl,--wrap=fgets"
)
endif ()
target_link_libraries(AppModuleTests PUBLIC
TactilityKernel
app-module
+17
View File
@@ -0,0 +1,17 @@
cmake_minimum_required(VERSION 3.20)
include("${CMAKE_CURRENT_LIST_DIR}/../../Buildscripts/module.cmake")
file(GLOB_RECURSE SOURCE_FILES "source/*.c*")
tactility_add_module(app-posix-module
SRCS ${SOURCE_FILES}
INCLUDE_DIRS include/
REQUIRES TactilityKernel app-module service-module
PRIV_REQUIRES ${CMAKE_DL_LIBS}
)
# Baked in at compile time, mirroring ESP32's CONFIG_IDF_TARGET - names the installed-app binary
# (e.g. "elf/posix-x86_64.so") this Tactility process's own architecture can dlopen(), letting one
# .app package bundle a variant per posix architecture, same as one .app bundles a .elf per chip.
target_compile_definitions(app-posix-module PRIVATE "TACTILITY_POSIX_ARCH=\"${CMAKE_SYSTEM_PROCESSOR}\"")
@@ -0,0 +1,195 @@
Apache License
==============
_Version 2.0, January 2004_
_&lt;<http://www.apache.org/licenses/>&gt;_
### Terms and Conditions for use, reproduction, and distribution
#### 1. Definitions
“License” shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, “control” means **(i)** the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
outstanding shares, or **(iii)** beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising
permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
“Object” form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
“submitted” means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
#### 2. Grant of Copyright License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
#### 3. Grant of Patent License
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
#### 4. Redistribution
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
this License; and
* **(b)** You must cause any modified files to carry prominent notices stating that You
changed the files; and
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
#### 5. Submission of Contributions
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
#### 6. Trademarks
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
#### 7. Disclaimer of Warranty
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
#### 8. Limitation of Liability
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
#### 9. Accepting Warranty or Additional Liability
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
_END OF TERMS AND CONDITIONS_
### APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets `[]` replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same “printed page” as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
extern struct Module app_posix_module;
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,124 @@
// SPDX-License-Identifier: Apache-2.0
#include <app/loader.h>
#include <app/location.h>
#include <tactility/error.h>
#include <tactility/log.h>
#include <service/manager.h>
#include <dlfcn.h>
#include <sys/stat.h>
#include <new>
#include <string>
constexpr auto* TAG = "app_posix_loader";
namespace {
/** load()-allocated state, passed back through run()/unload(). */
struct PosixAppRuntime {
void* handle = nullptr;
};
bool is_regular_file(const std::string& path) {
struct stat path_stat {};
return ::stat(path.c_str(), &path_stat) == 0 && S_ISREG(path_stat.st_mode);
}
// location.location can be either an app's install directory or the .so file directly; the
// former resolves to the per-architecture binary at {dir}/elf/posix-{TACTILITY_POSIX_ARCH}.so,
// mirroring app_esp32_loader_service.cpp's resolve_elf_path().
error_t resolve_app_path(const std::string& path, std::string& resolvedPath) {
if (path.ends_with(".so")) {
resolvedPath = path;
return ERROR_NONE;
}
std::string shared_object_path = path + "/elf/posix-" TACTILITY_POSIX_ARCH ".so";
if (!is_regular_file(shared_object_path)) {
return ERROR_NOT_FOUND;
}
resolvedPath = shared_object_path;
return ERROR_NONE;
}
error_t api_load(AppLocation location, AppRuntime* out_runtime) {
if (location.type != APP_LOCATION_PATH) {
LOG_E(TAG, "Unsupported location type");
return ERROR_NOT_SUPPORTED;
}
std::string app_path;
auto error = resolve_app_path(static_cast<const char*>(location.location), app_path);
if (error != ERROR_NONE) {
LOG_E(TAG, "Failed to resolve app path: %s", location.location);
return error;
}
LOG_I(TAG, "Loading %s", app_path.c_str());
// RTLD_NOW: a missing symbol fails here, not mid-run(). RTLD_LOCAL: this app's own exported
// symbols (if any beyond its entry point) don't leak into the process's global scope and
// clash with a different app's.
void* handle = dlopen(app_path.c_str(), RTLD_NOW | RTLD_LOCAL);
if (handle == nullptr) {
LOG_E(TAG, "dlopen(%s) failed: %s", app_path.c_str(), dlerror());
return ERROR_NOT_FOUND;
}
auto* runtime = new (std::nothrow) PosixAppRuntime { .handle = handle };
if (runtime == nullptr) {
LOG_E(TAG, "Out of memory");
dlclose(handle);
return ERROR_OUT_OF_MEMORY;
}
*out_runtime = runtime;
return ERROR_NONE;
}
int32_t api_run(AppRuntime runtime_ptr, uint32_t /*app_instance_id*/, int argc, char* argv[]) {
auto* runtime = static_cast<PosixAppRuntime*>(runtime_ptr);
dlerror(); // clear any pending error, per dlsym(3)'s own recommended idiom for telling a NULL
// symbol address apart from a real lookup failure
void* symbol = dlsym(runtime->handle, "main");
const char* lookup_error = dlerror();
if (symbol == nullptr || lookup_error != nullptr) {
LOG_E(TAG, "dlsym(\"main\") failed: %s", lookup_error != nullptr ? lookup_error : "not found");
return -1;
}
auto* main_fn = reinterpret_cast<AppMainFn>(symbol);
return main_fn(argc, argv);
}
void api_unload(AppRuntime runtime_ptr) {
auto* runtime = static_cast<PosixAppRuntime*>(runtime_ptr);
dlclose(runtime->handle);
delete runtime;
}
AppLoaderApi loader_api = {
.load = api_load,
.run = api_run,
.unload = api_unload,
};
void* create_service(const ServiceManifest*) {
return &loader_api;
}
void destroy_service(const ServiceManifest*, void*) {
}
} // namespace
ServiceManifest loader_service_manifest = {
.id = APP_LOADER_PATH_SERVICE_ID,
.create_service = create_service,
.destroy_service = destroy_service,
.on_start = nullptr,
.on_stop = nullptr,
};
@@ -0,0 +1,30 @@
// SPDX-License-Identifier: Apache-2.0
#include <app_posix/module.h>
#include <service/manager.h>
#include <tactility/error.h>
#include <tactility/module.h>
extern "C" {
extern ServiceManifest loader_service_manifest;
static error_t start() {
return service_manager_add(&loader_service_manifest, /*auto_start=*/true);
}
static error_t stop() {
return service_manager_remove(loader_service_manifest.id);
}
Module app_posix_module = {
.name = "app-posix",
.start = start,
.stop = stop,
.drivers = nullptr,
.symbols = nullptr,
.internal = nullptr,
};
}
@@ -0,0 +1,37 @@
project(AppPosixModuleTests)
enable_language(C CXX ASM)
# Fixture: a tiny shared object with a main() the test dlopen()s through app-posix-module's real
# loader service. Deliberately not linked against app-module, so its call into
# app_scheduler_current_app_id() stays undefined until dlopen() resolves it against
# AppPosixModuleTests's own copy, exactly like a real Tactility-embedded app would resolve
# against the running Tactility binary.
add_library(app_posix_module_test_fixture SHARED EXCLUDE_FROM_ALL ${CMAKE_CURRENT_LIST_DIR}/fixtures/fixture_app.cpp)
target_include_directories(app_posix_module_test_fixture PRIVATE ${CMAKE_SOURCE_DIR}/Modules/app-module/include)
set_target_properties(app_posix_module_test_fixture PROPERTIES POSITION_INDEPENDENT_CODE ON)
file(GLOB_RECURSE TEST_SOURCES CONFIGURE_DEPENDS ${PROJECT_SOURCE_DIR}/source/*.cpp)
add_executable(AppPosixModuleTests EXCLUDE_FROM_ALL ${TEST_SOURCES})
add_dependencies(AppPosixModuleTests app_posix_module_test_fixture)
target_include_directories(AppPosixModuleTests PRIVATE ${DOCTESTINC})
target_compile_definitions(AppPosixModuleTests PRIVATE
FIXTURE_APP_PATH="$<TARGET_FILE:app_posix_module_test_fixture>"
)
add_test(NAME AppPosixModuleTests COMMAND AppPosixModuleTests)
target_link_libraries(AppPosixModuleTests PUBLIC
TactilityKernel
app-module
app-posix-module
service-module
platform-posix
freertos_kernel
${CMAKE_DL_LIBS}
)
# So the fixture's undefined app_scheduler_current_app_id() reference can resolve against this
# test binary's own copy at dlopen() time. See app-posix-module's own ENABLE_EXPORTS comment on
# the real Tactility executable for why this is needed.
set_target_properties(AppPosixModuleTests PROPERTIES ENABLE_EXPORTS ON)
+12
View File
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: Apache-2.0
#include <app/scheduler.h>
#include <cstdint>
// Deliberately not linked against app-module: app_scheduler_current_app_id() stays an undefined
// symbol in this .so, resolved at dlopen() time against the loading process's own copy. Proves
// app-posix-module's loader lets a loaded app call straight back into Tactility without linking
// its own copy of it.
extern "C" int32_t main(int, char*[]) {
return static_cast<int32_t>(app_scheduler_current_app_id());
}
@@ -0,0 +1,113 @@
// SPDX-License-Identifier: Apache-2.0
#include "doctest.h"
#include <app/event.h>
#include <app/loader.h>
#include <app/manager.h>
#include <app/scheduler.h>
#include <service/manager.h>
#include <tactility/delay.h>
#include <atomic>
extern ServiceManifest loader_service_manifest; // app-posix-module's own
extern ServiceManifest app_internal_loader_service_manifest; // app-module's real memory loader
namespace {
void ensure_path_loader_registered() {
if (service_manager_find_instance(APP_LOADER_PATH_SERVICE_ID) == nullptr) {
service_manager_add(&loader_service_manifest, /*auto_start=*/true);
}
}
void ensure_memory_loader_registered() {
if (service_manager_find_instance(APP_LOADER_MEMORY_SERVICE_ID) == nullptr) {
service_manager_add(&app_internal_loader_service_manifest, /*auto_start=*/true);
}
}
bool wait_for_state(AppInstanceId id, AppInstanceState target, uint32_t timeout_ms) {
uint32_t waited = 0;
while (waited < timeout_ms) {
if (app_manager_get_state(id) == target) {
return true;
}
delay_millis(10);
waited += 10;
}
return app_manager_get_state(id) == target;
}
std::atomic<int32_t> g_fixture_result { -1 };
std::atomic<bool> g_fixture_result_received { false };
// Starts the dlopen()ed fixture as its own modal child and stashes its returned result, so the
// test can inspect that result from the (in-process, directly readable) parent's own task.
int32_t parent_app_main(int, char*[]) {
TaskEventGroup event_group {};
task_event_group_construct(&event_group);
AppEventSubscription sub {};
app_event_subscribe(&sub, &event_group);
AppInstanceId self_id = app_scheduler_current_app_id();
AppManifest fixture_manifest {
"test.posix.fixture", "Fixture", APP_CATEGORY_USER,
{ APP_LOCATION_PATH, const_cast<char*>(FIXTURE_APP_PATH) }
};
app_manager_add(&fixture_manifest);
AppInstanceId fixture_id = 0;
app_manager_start_for_result("test.posix.fixture", self_id, 0, nullptr, &fixture_id);
while (true) {
if (task_event_group_wait_any(&event_group, nullptr, pdMS_TO_TICKS(5000)) != ERROR_NONE) {
break; // safety net so a bug here can't hang the test suite
}
AppEvent event {};
bool got_result = false;
while (app_event_poll(&sub, &event) == ERROR_NONE) {
if (event.type == APP_EVENT_RESULT && event.result.launch_id == fixture_id) {
g_fixture_result.store(event.result.result, std::memory_order_release);
got_result = true;
}
}
if (got_result) {
break;
}
}
g_fixture_result_received.store(true, std::memory_order_release);
app_manager_remove("test.posix.fixture");
app_event_unsubscribe(&sub);
task_event_group_destruct(&event_group);
return 0;
}
} // namespace
TEST_CASE("app-posix-module's loader-path service dlopen()s a .so and calls its main(), which resolves a real Tactility symbol against the host") {
ensure_path_loader_registered();
ensure_memory_loader_registered();
g_fixture_result.store(-1, std::memory_order_relaxed);
g_fixture_result_received.store(false, std::memory_order_relaxed);
AppManifest parent_manifest { "test.posix.parent", "Parent", APP_CATEGORY_USER, { APP_LOCATION_MEMORY, reinterpret_cast<void*>(parent_app_main) } };
REQUIRE_EQ(app_manager_add(&parent_manifest), ERROR_NONE);
AppInstanceId parent_id = 0;
REQUIRE_EQ(app_manager_start("test.posix.parent", &parent_id), ERROR_NONE);
REQUIRE(wait_for_state(parent_id, APP_INSTANCE_STATE_STOPPED, 3000));
CHECK(g_fixture_result_received.load(std::memory_order_acquire));
// A positive AppInstanceId proves the fixture's dlopen()ed main() actually resolved and
// called app_scheduler_current_app_id() against the host process, not just "ran and returned
// a hardcoded value" - 0 would mean it thought it wasn't running as an app instance at all.
CHECK_GT(g_fixture_result.load(std::memory_order_acquire), 0);
app_manager_remove("test.posix.parent");
}
@@ -0,0 +1,54 @@
#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"
#include <cassert>
#include "FreeRTOS.h"
#include "task.h"
typedef struct {
int argc;
char** argv;
int result;
} TestTaskData;
void test_task(void* parameter) {
auto* data = (TestTaskData*)parameter;
doctest::Context context;
context.applyCommandLine(data->argc, data->argv);
// overrides
context.setOption("no-breaks", true); // don't break in the debugger when assertions fail
data->result = context.run();
vTaskEndScheduler();
vTaskDelete(nullptr);
}
int main(int argc, char** argv) {
TestTaskData data = {
.argc = argc,
.argv = argv,
.result = 0
};
BaseType_t task_result = xTaskCreate(
test_task,
"test_task",
8192,
&data,
1,
nullptr
);
if (task_result != pdPASS) {
return 1;
}
vTaskStartScheduler();
return data.result;
}
@@ -28,6 +28,11 @@ static uint32_t task_max_sleep_ms = 10;
static TaskHandle_t lvgl_task_handle = NULL;
static bool lvgl_task_interrupt_requested = false;
// ESP32 gets LVGL's tick driven for free by esp_lvgl_port; POSIX has no such
// helper, so lv_tick_get() would otherwise stay at 0 forever and every timer
// (indev polling included) would look permanently "not due yet".
static uint32_t lvgl_last_tick_millis = 0;
#define LVGL_STOP_POLL_INTERVAL 10
#define LVGL_STOP_TIMEOUT 5000
@@ -80,7 +85,13 @@ static void lvgl_task(void* arg) {
// on_start must be called from the task, otherwise the display doesn't work
if (lvgl_module_config.on_start) lvgl_module_config.on_start();
lvgl_last_tick_millis = (uint32_t)get_millis();
while (!lvgl_task_is_interrupt_requested()) {
uint32_t now_millis = (uint32_t)get_millis();
lv_tick_inc(now_millis - lvgl_last_tick_millis);
lvgl_last_tick_millis = now_millis;
if (lvgl_try_lock(10)) {
task_delay_ms = lv_timer_handler();
lvgl_unlock();
@@ -8,6 +8,7 @@ extern "C" {
static const ModuleSymbol SYMBOLS[] = {
DEFINE_MODULE_SYMBOL(window_manager_create),
DEFINE_MODULE_SYMBOL(window_manager_create_ext),
DEFINE_MODULE_SYMBOL(window_manager_remove),
DEFINE_MODULE_SYMBOL(window_manager_get_state),
DEFINE_MODULE_SYMBOL(window_manager_await_state_change),