[FL-3097] fbt, faploader: minimal app module implementation (#2420)

* fbt, faploader: minimal app module implementation
* faploader, libs: moved API hashtable core to flipper_application
* example: compound api
* lib: flipper_application: naming fixes, doxygen comments
* fbt: changed `requires` manifest field behavior for app extensions
* examples: refactored plugin apps; faploader: changed new API naming; fbt: changed PLUGIN app type meaning
* loader: dropped support for debug apps & plugin menus
* moved applications/plugins -> applications/external
* Restored x bit on chiplist_convert.py
* git: fixed free-dap submodule path
* pvs: updated submodule paths
* examples: example_advanced_plugins.c: removed potential memory leak on errors
* examples: example_plugins: refined requires
* fbt: not deploying app modules for debug/sample apps; extra validation for .PLUGIN-type apps
* apps: removed cdefines for external apps
* fbt: moved ext app path definition
* fbt: reworked fap_dist handling; f18: synced api_symbols.csv
* fbt: removed resources_paths for extapps
* scripts: reworked storage
* scripts: reworked runfap.py & selfupdate.py to use new api
* wip: fal runner
* fbt: moved file packaging into separate module
* scripts: storage: fixes
* scripts: storage: minor fixes for new api
* fbt: changed internal artifact storage details for external apps
* scripts: storage: additional fixes and better error reporting; examples: using APP_DATA_PATH()
* fbt, scripts: reworked launch_app to deploy plugins; moved old runfap.py to distfap.py
* fbt: extra check for plugins descriptors
* fbt: additional checks in emitter
* fbt: better info message on SDK rebuild
* scripts: removed requirements.txt
* loader: removed remnants of plugins & debug menus
* post-review fixes
This commit is contained in:
hedger
2023-03-14 18:29:28 +04:00
committed by GitHub
parent 4bd3dca16f
commit 53435579b3
376 changed files with 2041 additions and 1036 deletions

View File

@@ -6,6 +6,10 @@ env.Append(
],
SDK_HEADERS=[
File("flipper_application.h"),
File("plugins/plugin_manager.h"),
File("plugins/composite_resolver.h"),
File("api_hashtable/api_hashtable.h"),
File("api_hashtable/compilesort.hpp"),
],
)
@@ -14,6 +18,7 @@ libenv = env.Clone(FW_LIB_NAME="flipper_application")
libenv.ApplyLibFlags()
sources = libenv.GlobRecursive("*.c")
sources.append(File("api_hashtable/api_hashtable.cpp"))
lib = libenv.StaticLibrary("${FW_LIB_NAME}", sources)
libenv.Install("${LIB_DIST_DIR}", lib)

View File

@@ -0,0 +1,38 @@
#include "api_hashtable.h"
#include <furi.h>
#include <algorithm>
#define TAG "hashtable_api"
bool elf_resolve_from_hashtable(
const ElfApiInterface* interface,
const char* name,
Elf32_Addr* address) {
const HashtableApiInterface* hashtable_interface =
static_cast<const HashtableApiInterface*>(interface);
bool result = false;
uint32_t gnu_sym_hash = elf_gnu_hash(name);
sym_entry key = {
.hash = gnu_sym_hash,
.address = 0,
};
auto find_res =
std::lower_bound(hashtable_interface->table_cbegin, hashtable_interface->table_cend, key);
if((find_res == hashtable_interface->table_cend || (find_res->hash != gnu_sym_hash))) {
FURI_LOG_W(
TAG,
"Can't find symbol '%s' (hash %lx) @ %p!",
name,
gnu_sym_hash,
hashtable_interface->table_cbegin);
result = false;
} else {
result = true;
*address = find_res->address;
}
return result;
}

View File

@@ -0,0 +1,85 @@
#pragma once
#include <flipper_application/elf/elf_api_interface.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Symbol table entry
*/
struct sym_entry {
uint32_t hash;
uint32_t address;
};
/**
* @brief Resolver for API entries using a pre-sorted table with hashes
* @param interface pointer to HashtableApiInterface
* @param name function name
* @param address output for function address
* @return true if the table contains a function
*/
bool elf_resolve_from_hashtable(
const ElfApiInterface* interface,
const char* name,
Elf32_Addr* address);
#ifdef __cplusplus
}
#include <array>
#include <algorithm>
/**
* @brief HashtableApiInterface is an implementation of ElfApiInterface
* that uses a hash table to resolve function addresses.
* table_cbegin and table_cend must point to a sorted array of sym_entry
*/
struct HashtableApiInterface : public ElfApiInterface {
const sym_entry *table_cbegin, *table_cend;
};
#define API_METHOD(x, ret_type, args_type) \
sym_entry { \
.hash = elf_gnu_hash(#x), .address = (uint32_t)(static_cast<ret_type(*) args_type>(x)) \
}
#define API_VARIABLE(x, var_type) \
sym_entry { .hash = elf_gnu_hash(#x), .address = (uint32_t)(&(x)), }
constexpr bool operator<(const sym_entry& k1, const sym_entry& k2) {
return k1.hash < k2.hash;
}
/**
* @brief Calculate hash for a string using the ELF GNU hash algorithm
* @param s string to calculate hash for
* @return hash value
*/
constexpr uint32_t elf_gnu_hash(const char* s) {
uint32_t h = 0x1505;
for(unsigned char c = *s; c != '\0'; c = *++s) {
h = (h << 5) + h + c;
}
return h;
}
/* Compile-time check for hash collisions in API table.
* Usage: static_assert(!has_hash_collisions(api_methods), "Hash collision detected");
*/
template <std::size_t N>
constexpr bool has_hash_collisions(const std::array<sym_entry, N>& api_methods) {
for(std::size_t i = 0; i < (N - 1); ++i) {
if(api_methods[i].hash == api_methods[i + 1].hash) {
return true;
}
}
return false;
}
#endif

View File

@@ -0,0 +1,115 @@
/**
* Implementation of compile-time sort for symbol table entries.
*/
#pragma once
#ifdef __cplusplus
#include <iterator>
#include <array>
namespace cstd {
template <typename RAIt>
constexpr RAIt next(RAIt it, typename std::iterator_traits<RAIt>::difference_type n = 1) {
return it + n;
}
template <typename RAIt>
constexpr auto distance(RAIt first, RAIt last) {
return last - first;
}
template <class ForwardIt1, class ForwardIt2>
constexpr void iter_swap(ForwardIt1 a, ForwardIt2 b) {
auto temp = std::move(*a);
*a = std::move(*b);
*b = std::move(temp);
}
template <class InputIt, class UnaryPredicate>
constexpr InputIt find_if_not(InputIt first, InputIt last, UnaryPredicate q) {
for(; first != last; ++first) {
if(!q(*first)) {
return first;
}
}
return last;
}
template <class ForwardIt, class UnaryPredicate>
constexpr ForwardIt partition(ForwardIt first, ForwardIt last, UnaryPredicate p) {
first = cstd::find_if_not(first, last, p);
if(first == last) return first;
for(ForwardIt i = cstd::next(first); i != last; ++i) {
if(p(*i)) {
cstd::iter_swap(i, first);
++first;
}
}
return first;
}
}
template <class RAIt, class Compare = std::less<> >
constexpr void quick_sort(RAIt first, RAIt last, Compare cmp = Compare{}) {
auto const N = cstd::distance(first, last);
if(N <= 1) return;
auto const pivot = *cstd::next(first, N / 2);
auto const middle1 =
cstd::partition(first, last, [=](auto const& elem) { return cmp(elem, pivot); });
auto const middle2 =
cstd::partition(middle1, last, [=](auto const& elem) { return !cmp(pivot, elem); });
quick_sort(first, middle1, cmp); // assert(std::is_sorted(first, middle1, cmp));
quick_sort(middle2, last, cmp); // assert(std::is_sorted(middle2, last, cmp));
}
template <typename Range>
constexpr auto sort(Range&& range) {
quick_sort(std::begin(range), std::end(range));
return range;
}
template <typename V, typename... T>
constexpr auto array_of(T&&... t) -> std::array<V, sizeof...(T)> {
return {{std::forward<T>(t)...}};
}
template <typename T, typename... N>
constexpr auto my_make_array(N&&... args) -> std::array<T, sizeof...(args)> {
return {std::forward<N>(args)...};
}
namespace traits {
template <typename T, typename... Ts>
struct array_type {
using type = T;
};
template <typename T, typename... Ts>
static constexpr bool are_same_type() {
return std::conjunction_v<std::is_same<T, Ts>...>;
}
}
template <typename... T>
constexpr auto create_array(const T&&... values) {
using array_type = typename traits::array_type<T...>::type;
static_assert(sizeof...(T) > 0, "an array must have at least one element");
static_assert(traits::are_same_type<T...>(), "all elements must have same type");
return std::array<array_type, sizeof...(T)>{values...};
}
template <typename T, typename... Ts>
constexpr auto create_array_t(const Ts&&... values) {
using array_type = T;
static_assert(sizeof...(Ts) > 0, "an array must have at least one element");
static_assert(traits::are_same_type<Ts...>(), "all elements must have same type");
return std::array<array_type, sizeof...(Ts)>{static_cast<T>(values)...};
}
#endif

View File

@@ -3,10 +3,14 @@
#include <elf.h>
#include <stdbool.h>
#define ELF_INVALID_ADDRESS 0xFFFFFFFF
typedef struct {
/**
* @brief Interface for ELF loader to resolve symbols
*/
typedef struct ElfApiInterface {
uint16_t api_version_major;
uint16_t api_version_minor;
bool (*resolver_callback)(const char* name, Elf32_Addr* address);
bool (*resolver_callback)(
const struct ElfApiInterface* interface,
const char* name,
Elf32_Addr* address);
} ElfApiInterface;

View File

@@ -17,6 +17,8 @@
#define FURI_LOG_D(...)
#endif
#define ELF_INVALID_ADDRESS 0xFFFFFFFF
#define TRAMPOLINE_CODE_SIZE 6
/**
@@ -166,7 +168,7 @@ static ELFSection* elf_section_of(ELFFile* elf, int index) {
static Elf32_Addr elf_address_of(ELFFile* elf, Elf32_Sym* sym, const char* sName) {
if(sym->st_shndx == SHN_UNDEF) {
Elf32_Addr addr = 0;
if(elf->api_interface->resolver_callback(sName, &addr)) {
if(elf->api_interface->resolver_callback(elf->api_interface, sName, &addr)) {
return addr;
}
} else {
@@ -514,10 +516,13 @@ static SectionType elf_preload_section(
section_p->sec_idx = section_idx;
if(section_header->sh_type == SHT_PREINIT_ARRAY) {
furi_assert(elf->preinit_array == NULL);
elf->preinit_array = section_p;
} else if(section_header->sh_type == SHT_INIT_ARRAY) {
furi_assert(elf->init_array == NULL);
elf->init_array = section_p;
} else if(section_header->sh_type == SHT_FINI_ARRAY) {
furi_assert(elf->fini_array == NULL);
elf->fini_array = section_p;
}
@@ -605,10 +610,17 @@ ELFFile* elf_file_alloc(Storage* storage, const ElfApiInterface* api_interface)
elf->api_interface = api_interface;
ELFSectionDict_init(elf->sections);
AddressCache_init(elf->trampoline_cache);
elf->init_array_called = false;
return elf;
}
void elf_file_free(ELFFile* elf) {
// furi_check(!elf->init_array_called);
if(elf->init_array_called) {
FURI_LOG_W(TAG, "Init array was called, but fini array wasn't");
elf_file_call_section_list(elf->fini_array, true);
}
// free sections data
{
ELFSectionDict_it_t it;
@@ -774,19 +786,26 @@ ELFFileLoadStatus elf_file_load_sections(ELFFile* elf) {
return status;
}
void elf_file_pre_run(ELFFile* elf) {
void elf_file_call_init(ELFFile* elf) {
furi_check(!elf->init_array_called);
elf_file_call_section_list(elf->preinit_array, false);
elf_file_call_section_list(elf->init_array, false);
elf->init_array_called = true;
}
int32_t elf_file_run(ELFFile* elf, void* args) {
int32_t result;
result = ((int32_t(*)(void*))elf->entry)(args);
return result;
bool elf_file_is_init_complete(ELFFile* elf) {
return elf->init_array_called;
}
void elf_file_post_run(ELFFile* elf) {
void* elf_file_get_entry_point(ELFFile* elf) {
furi_check(elf->init_array_called);
return (void*)elf->entry;
}
void elf_file_call_fini(ELFFile* elf) {
furi_check(elf->init_array_called);
elf_file_call_section_list(elf->fini_array, true);
elf->init_array_called = false;
}
const ElfApiInterface* elf_file_get_api_interface(ELFFile* elf_file) {

View File

@@ -82,24 +82,34 @@ bool elf_file_load_section_table(ELFFile* elf_file);
ELFFileLoadStatus elf_file_load_sections(ELFFile* elf_file);
/**
* @brief Execute ELF file pre-run stage, call static constructors for example (load stage #3)
* @brief Execute ELF file pre-run stage,
* call static constructors for example (load stage #3)
* Must be done before invoking any code from the ELF file
* @param elf
*/
void elf_file_pre_run(ELFFile* elf);
void elf_file_call_init(ELFFile* elf);
/**
* @brief Run ELF file (load stage #4)
* @brief Check if ELF file pre-run stage was executed and its code is runnable
* @param elf
*/
bool elf_file_is_init_complete(ELFFile* elf);
/**
* @brief Get actual entry point for ELF file
* @param elf_file
* @param args
* @return int32_t
*/
int32_t elf_file_run(ELFFile* elf_file, void* args);
void* elf_file_get_entry_point(ELFFile* elf_file);
/**
* @brief Execute ELF file post-run stage, call static destructors for example (load stage #5)
* @brief Execute ELF file post-run stage,
* call static destructors for example (load stage #5)
* Must be done if any code from the ELF file was executed
* @param elf
*/
void elf_file_post_run(ELFFile* elf);
void elf_file_call_fini(ELFFile* elf);
/**
* @brief Get ELF file API interface

View File

@@ -45,6 +45,8 @@ struct ELFFile {
ELFSection* preinit_array;
ELFSection* init_array;
ELFSection* fini_array;
bool init_array_called;
};
#ifdef __cplusplus

View File

@@ -10,6 +10,7 @@ struct FlipperApplication {
FlipperApplicationManifest manifest;
ELFFile* elf;
FuriThread* thread;
void* ep_thread_args;
};
/* For debugger access to app state */
@@ -20,9 +21,14 @@ FlipperApplication*
FlipperApplication* app = malloc(sizeof(FlipperApplication));
app->elf = elf_file_alloc(storage, api_interface);
app->thread = NULL;
app->ep_thread_args = NULL;
return app;
}
bool flipper_application_is_plugin(FlipperApplication* app) {
return app->manifest.stack_size == 0;
}
void flipper_application_free(FlipperApplication* app) {
furi_assert(app);
@@ -31,9 +37,16 @@ void flipper_application_free(FlipperApplication* app) {
furi_thread_free(app->thread);
}
last_loaded_app = NULL;
if(!flipper_application_is_plugin(app)) {
last_loaded_app = NULL;
}
elf_file_clear_debug_info(&app->state);
if(elf_file_is_init_complete(app->elf)) {
elf_file_call_fini(app->elf);
}
elf_file_free(app->elf);
free(app);
}
@@ -140,7 +153,9 @@ const FlipperApplicationManifest* flipper_application_get_manifest(FlipperApplic
}
FlipperApplicationLoadStatus flipper_application_map_to_memory(FlipperApplication* app) {
last_loaded_app = app;
if(!flipper_application_is_plugin(app)) {
last_loaded_app = app;
}
ELFFileLoadStatus status = elf_file_load_sections(app->elf);
switch(status) {
@@ -157,9 +172,15 @@ FlipperApplicationLoadStatus flipper_application_map_to_memory(FlipperApplicatio
}
static int32_t flipper_application_thread(void* context) {
elf_file_pre_run(last_loaded_app->elf);
int32_t result = elf_file_run(last_loaded_app->elf, context);
elf_file_post_run(last_loaded_app->elf);
furi_assert(context);
FlipperApplication* app = (FlipperApplication*)context;
elf_file_call_init(app->elf);
FlipperApplicationEntryPoint entry_point = elf_file_get_entry_point(app->elf);
int32_t ret_code = entry_point(app->ep_thread_args);
elf_file_call_fini(app->elf);
// wait until all notifications from RAM are completed
NotificationApp* notifications = furi_record_open(RECORD_NOTIFICATION);
@@ -169,17 +190,17 @@ static int32_t flipper_application_thread(void* context) {
notification_message_block(notifications, &sequence_empty);
furi_record_close(RECORD_NOTIFICATION);
return result;
return ret_code;
}
FuriThread* flipper_application_spawn(FlipperApplication* app, void* args) {
furi_check(app->thread == NULL);
furi_check(!flipper_application_is_plugin(app));
app->ep_thread_args = args;
const FlipperApplicationManifest* manifest = flipper_application_get_manifest(app);
furi_check(manifest->stack_size > 0);
app->thread = furi_thread_alloc_ex(
manifest->name, manifest->stack_size, flipper_application_thread, args);
manifest->name, manifest->stack_size, flipper_application_thread, app);
return app->thread;
}
@@ -213,3 +234,28 @@ const char* flipper_application_load_status_to_string(FlipperApplicationLoadStat
}
return load_status_strings[status];
}
const FlipperAppPluginDescriptor*
flipper_application_plugin_get_descriptor(FlipperApplication* app) {
if(!flipper_application_is_plugin(app)) {
return NULL;
}
if(!elf_file_is_init_complete(app->elf)) {
elf_file_call_init(app->elf);
}
typedef const FlipperAppPluginDescriptor* (*get_lib_descriptor_t)(void);
get_lib_descriptor_t lib_ep = elf_file_get_entry_point(app->elf);
furi_check(lib_ep);
const FlipperAppPluginDescriptor* lib_descriptor = lib_ep();
FURI_LOG_D(
TAG,
"Library for %s, API v. %lu loaded",
lib_descriptor->appid,
lib_descriptor->ep_api_version);
return lib_descriptor;
}

View File

@@ -115,6 +115,40 @@ FlipperApplicationLoadStatus flipper_application_map_to_memory(FlipperApplicatio
*/
FuriThread* flipper_application_spawn(FlipperApplication* app, void* args);
/**
* @brief Check if application is a plugin (not a runnable standalone app)
* @param app Application pointer
* @return true if application is a plugin, false otherwise
*/
bool flipper_application_is_plugin(FlipperApplication* app);
/**
* @brief Entry point prototype for standalone applications
*/
typedef int32_t (*FlipperApplicationEntryPoint)(void*);
/**
* @brief An object that describes a plugin - must be returned by plugin's entry point
*/
typedef struct {
const char* appid;
const uint32_t ep_api_version;
const void* entry_point;
} FlipperAppPluginDescriptor;
/**
* @brief Entry point prototype for plugins
*/
typedef const FlipperAppPluginDescriptor* (*FlipperApplicationPluginEntryPoint)(void);
/**
* @brief Get plugin descriptor for preloaded plugin
* @param app Application pointer
* @return Pointer to plugin descriptor
*/
const FlipperAppPluginDescriptor*
flipper_application_plugin_get_descriptor(FlipperApplication* app);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,52 @@
#include "composite_resolver.h"
#include <m-list.h>
#include <m-algo.h>
LIST_DEF(ElfApiInterfaceList, const ElfApiInterface*, M_POD_OPLIST)
#define M_OPL_ElfApiInterfaceList_t() LIST_OPLIST(ElfApiInterfaceList, M_POD_OPLIST)
struct CompositeApiResolver {
ElfApiInterface api_interface;
ElfApiInterfaceList_t interfaces;
};
static bool composite_api_resolver_callback(
const ElfApiInterface* interface,
const char* name,
Elf32_Addr* address) {
CompositeApiResolver* resolver = (CompositeApiResolver*)interface;
for
M_EACH(interface, resolver->interfaces, ElfApiInterfaceList_t) {
if((*interface)->resolver_callback(*interface, name, address)) {
return true;
}
}
return false;
}
CompositeApiResolver* composite_api_resolver_alloc() {
CompositeApiResolver* resolver = malloc(sizeof(CompositeApiResolver));
resolver->api_interface.api_version_major = 0;
resolver->api_interface.api_version_minor = 0;
resolver->api_interface.resolver_callback = &composite_api_resolver_callback;
ElfApiInterfaceList_init(resolver->interfaces);
return resolver;
}
void composite_api_resolver_free(CompositeApiResolver* resolver) {
ElfApiInterfaceList_clear(resolver->interfaces);
free(resolver);
}
void composite_api_resolver_add(CompositeApiResolver* resolver, const ElfApiInterface* interface) {
if(ElfApiInterfaceList_empty_p(resolver->interfaces)) {
resolver->api_interface.api_version_major = interface->api_version_major;
resolver->api_interface.api_version_minor = interface->api_version_minor;
}
ElfApiInterfaceList_push_back(resolver->interfaces, interface);
}
const ElfApiInterface* composite_api_resolver_get(CompositeApiResolver* resolver) {
return &resolver->api_interface;
}

View File

@@ -0,0 +1,46 @@
#pragma once
#include <flipper_application/elf/elf_api_interface.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Composite API resolver
* Resolves API interface by calling all resolvers in order
* Uses API version from first resolver
* Note: when using hashtable resolvers, collisions between tables are not detected
* Can be cast to ElfApiInterface*
*/
typedef struct CompositeApiResolver CompositeApiResolver;
/**
* @brief Allocate composite API resolver
* @return CompositeApiResolver* instance
*/
CompositeApiResolver* composite_api_resolver_alloc();
/**
* @brief Free composite API resolver
* @param resolver Instance
*/
void composite_api_resolver_free(CompositeApiResolver* resolver);
/**
* @brief Add API resolver to composite resolver
* @param resolver Instance
* @param interface API resolver
*/
void composite_api_resolver_add(CompositeApiResolver* resolver, const ElfApiInterface* interface);
/**
* @brief Get API interface from composite resolver
* @param resolver Instance
* @return API interface
*/
const ElfApiInterface* composite_api_resolver_get(CompositeApiResolver* resolver);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,153 @@
#include "plugin_manager.h"
#include <loader/firmware_api/firmware_api.h>
#include <storage/storage.h>
#include <toolbox/path.h>
#include <m-array.h>
#include <m-algo.h>
#include <furi.h>
#define TAG "libmgr"
ARRAY_DEF(FlipperApplicationList, FlipperApplication*, M_PTR_OPLIST)
#define M_OPL_FlipperApplicationList_t() ARRAY_OPLIST(FlipperApplicationList, M_PTR_OPLIST)
struct PluginManager {
const char* application_id;
uint32_t api_version;
Storage* storage;
FlipperApplicationList_t libs;
const ElfApiInterface* api_interface;
};
PluginManager* plugin_manager_alloc(
const char* application_id,
uint32_t api_version,
const ElfApiInterface* api_interface) {
PluginManager* manager = malloc(sizeof(PluginManager));
manager->application_id = application_id;
manager->api_version = api_version;
manager->api_interface = api_interface ? api_interface : firmware_api_interface;
manager->storage = furi_record_open(RECORD_STORAGE);
FlipperApplicationList_init(manager->libs);
return manager;
}
void plugin_manager_free(PluginManager* manager) {
for
M_EACH(loaded_lib, manager->libs, FlipperApplicationList_t) {
flipper_application_free(*loaded_lib);
}
FlipperApplicationList_clear(manager->libs);
furi_record_close(RECORD_STORAGE);
free(manager);
}
PluginManagerError plugin_manager_load_single(PluginManager* manager, const char* path) {
FlipperApplication* lib = flipper_application_alloc(manager->storage, manager->api_interface);
PluginManagerError error = PluginManagerErrorNone;
do {
FlipperApplicationPreloadStatus preload_res = flipper_application_preload(lib, path);
if(preload_res != FlipperApplicationPreloadStatusSuccess) {
FURI_LOG_E(TAG, "Failed to preload %s", path);
error = PluginManagerErrorLoaderError;
break;
}
if(!flipper_application_is_plugin(lib)) {
FURI_LOG_E(TAG, "Not a plugin %s", path);
error = PluginManagerErrorLoaderError;
break;
}
FlipperApplicationLoadStatus load_status = flipper_application_map_to_memory(lib);
if(load_status != FlipperApplicationLoadStatusSuccess) {
FURI_LOG_E(TAG, "Failed to load module_demo_plugin1.fal");
break;
}
const FlipperAppPluginDescriptor* app_descriptor =
flipper_application_plugin_get_descriptor(lib);
if(!app_descriptor) {
FURI_LOG_E(TAG, "Failed to get descriptor %s", path);
error = PluginManagerErrorLoaderError;
break;
}
if(strcmp(app_descriptor->appid, manager->application_id) != 0) {
FURI_LOG_E(TAG, "Application id mismatch %s", path);
error = PluginManagerErrorApplicationIdMismatch;
break;
}
if(app_descriptor->ep_api_version != manager->api_version) {
FURI_LOG_E(TAG, "API version mismatch %s", path);
error = PluginManagerErrorAPIVersionMismatch;
break;
}
FlipperApplicationList_push_back(manager->libs, lib);
} while(false);
if(error != PluginManagerErrorNone) {
flipper_application_free(lib);
}
return error;
}
PluginManagerError plugin_manager_load_all(PluginManager* manager, const char* path) {
File* directory = storage_file_alloc(manager->storage);
char file_name_buffer[256];
FuriString* file_name = furi_string_alloc();
do {
if(!storage_dir_open(directory, path)) {
FURI_LOG_E(TAG, "Failed to open directory %s", path);
break;
}
while(true) {
if(!storage_dir_read(directory, NULL, file_name_buffer, sizeof(file_name_buffer))) {
break;
}
furi_string_set(file_name, file_name_buffer);
if(!furi_string_end_with_str(file_name, ".fal")) {
continue;
}
path_concat(path, file_name_buffer, file_name);
FURI_LOG_D(TAG, "Loading %s", furi_string_get_cstr(file_name));
PluginManagerError error =
plugin_manager_load_single(manager, furi_string_get_cstr(file_name));
if(error != PluginManagerErrorNone) {
FURI_LOG_E(TAG, "Failed to load %s", furi_string_get_cstr(file_name));
break;
}
}
} while(false);
storage_dir_close(directory);
storage_file_free(directory);
furi_string_free(file_name);
return PluginManagerErrorNone;
}
uint32_t plugin_manager_get_count(PluginManager* manager) {
return FlipperApplicationList_size(manager->libs);
}
const FlipperAppPluginDescriptor* plugin_manager_get(PluginManager* manager, uint32_t index) {
FlipperApplication* app = *FlipperApplicationList_get(manager->libs, index);
return flipper_application_plugin_get_descriptor(app);
}
const void* plugin_manager_get_ep(PluginManager* manager, uint32_t index) {
const FlipperAppPluginDescriptor* lib_descr = plugin_manager_get(manager, index);
furi_check(lib_descr);
return lib_descr->entry_point;
}

View File

@@ -0,0 +1,82 @@
#pragma once
#include <flipper_application/flipper_application.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Object that manages plugins for an application
* Implements mass loading of plugins and provides access to their descriptors
*/
typedef struct PluginManager PluginManager;
typedef enum {
PluginManagerErrorNone = 0,
PluginManagerErrorLoaderError,
PluginManagerErrorApplicationIdMismatch,
PluginManagerErrorAPIVersionMismatch,
} PluginManagerError;
/**
* @brief Allocates new PluginManager
* @param application_id Application ID filter - only plugins with matching ID will be loaded
* @param api_version Application API version filter - only plugins with matching API version
* @param api_interface Application API interface - used to resolve plugins' API imports
* If plugin uses private application's API, use CompoundApiInterface
* @return new PluginManager instance
*/
PluginManager* plugin_manager_alloc(
const char* application_id,
uint32_t api_version,
const ElfApiInterface* api_interface);
/**
* @brief Frees PluginManager
* @param manager PluginManager instance
*/
void plugin_manager_free(PluginManager* manager);
/**
* @brief Loads single plugin by full path
* @param manager PluginManager instance
* @param path Path to plugin
* @return Error code
*/
PluginManagerError plugin_manager_load_single(PluginManager* manager, const char* path);
/**
* @brief Loads all plugins from specified directory
* @param manager PluginManager instance
* @param path Path to directory
* @return Error code
*/
PluginManagerError plugin_manager_load_all(PluginManager* manager, const char* path);
/**
* @brief Returns number of loaded plugins
* @param manager PluginManager instance
* @return Number of loaded plugins
*/
uint32_t plugin_manager_get_count(PluginManager* manager);
/**
* @brief Returns plugin descriptor by index
* @param manager PluginManager instance
* @param index Plugin index
* @return Plugin descriptor
*/
const FlipperAppPluginDescriptor* plugin_manager_get(PluginManager* manager, uint32_t index);
/**
* @brief Returns plugin entry point by index
* @param manager PluginManager instance
* @param index Plugin index
* @return Plugin entry point
*/
const void* plugin_manager_get_ep(PluginManager* manager, uint32_t index);
#ifdef __cplusplus
}
#endif