Overview / System & concurrency

plugin

Dynamic plugin loading with a C contract, and an ABI gate that rejects an incompatible plugin without running a single line of it. Hot swap with calls in flight.

Always compiled: part of the core build.Include #include <ethereal/cpp/plugin/plugin_inc.hpp>C layer

plugin_inc.hpp

#include <ethereal/cpp/plugin/plugin_inc.hpp>

Aggregate entry point of the Plugin module.

Dynamic libraries and plugins, in two layers:

  • Ethereal::Plugin::CDynamicLibrary : 'LoadLibrary' and 'dlopen' behind the same interface, with the file name decorated per system and the error text captured at once ('dlerror' is cleared when read, and 'GetLastError' is overwritten by the next call).
  • Ethereal::Plugin::CPluginHost : loads a folder of plugins, checks the contract generation before reading any other field, collects failures instead of stopping, and unloads in the reverse order of the load.

The plugin contract is C, not an abstract C++ class. The reasons are in 'host.hpp': name decoration differs between compilers, the virtual table layout is not standard, standard library types change size between debug and release in MSVC, and there are two heaps.

Unloading invalidates everything that came from that library: function pointers, virtual tables, string literals, static objects and the stack unwinding tables. The program does not crash at the unload, it crashes later, far away. See rule 1 in 'library.hpp'.

Including this header brings the whole module.

dependency.hpp

#include <ethereal/cpp/plugin/dependency.hpp>

Load order of the plugins.

Sorts the plugins so that each one loads after the ones it depends on. Three rules are part of the contract:

Cycle members. The spec asks for "a topological sort with cycle detection reporting the cycle members, not just 'cycle detected'". With forty plugins, "there is a cycle" means reading forty manifests by hand, while "A -> B -> C -> A" is fixed in a minute. Coloring (white, gray, black) finds the cycle when an edge reaches a gray vertex, but at that point it does not know the members. The traversal path is kept and cut from the repeated vertex. The test suite checks the names.

Deterministic order. A graph with slack admits several valid orders. Picking by arrival order would load the same install one way on one machine and another way on the next, because the order in which a file system lists a folder is not stable. A plugin that works in only one of the orders then fails on some machines only. Ties are broken by name, and the suite shuffles the input and expects the same output.

Optional dependencies. A missing optional dependency is not an error. It does not block the load and does not constrain the order, since there is nothing to order against.

struct

SDependency

Ethereal::Plugin#
C++
struct   SDependency   final
{
    /// @brief  Name of the plugin it needs.
    std::string        sName;

    /// @brief  true when its absence does not block the load.
    bool            bOptional = false;
};

A dependency declared by a plugin.

struct

SDependencyNode

Ethereal::Plugin#
C++
struct   SDependencyNode   final
{
    /// @brief  Name of the plugin.
    std::string                        sName;

    /// @brief  Plugins it needs.
    std::vector< SDependency >        Dependencies;
};

A plugin and the plugins it depends on.

enum

ESortError

Ethereal::Plugin#
C++
enum class   ESortError : ETL_UINT8
{
    /// @brief  Sorted.
    eNone = 0,

    /// @brief  An argument is not valid.
    eInvalidArgument,

    /// @brief  Two plugins with the same name.
    ///
    /// @details  Neither one is picked. Only the caller knows which one was
    ///            meant, and picking one silently would make the install
    ///            depend on the order the folder is read.
    eDuplicateName,

    /// @brief  A required dependency is missing.
    eMissingDependency,

    /// @brief  There is a cycle. The members are in @ref SSortResult::CycleMembers.
    eCycle
};

What can go wrong while sorting.

function

SortErrorName

Ethereal::Plugin#
const ETL_CHAR * SortErrorName( ESortError eError ) noexcept;

Name of the error, for messages. Never returns null.

struct

SSortResult

Ethereal::Plugin#
C++
struct   SSortResult   final
{
    /// @brief  'sizeof( SSortResult )'.
    ETL_UINT32                    iStructSize = sizeof( SSortResult );

    /// @brief  What happened.
    ESortError                    eError = ESortError::eNone;

    /// @brief  Explicit padding.
    ETL_UINT8                    aPad[ 3 ] = {};

    /// @brief  Load order: plugins with no dependencies come first.
    ///
    /// @details  Unloading uses the reverse of this order.
    std::vector< std::string >    Order;

    /// @brief  Members of the cycle, when there was one.
    ///
    /// @details  In traversal order, with the first one repeated at the end
    ///            so the cycle reads whole: @c { "A", "B", "C", "A" }. One
    ///            extra element saves the reader from working out that the
    ///            last one points to the first.
    std::vector< std::string >    CycleMembers;

    /// @brief  Missing name, when a required dependency was missing.
    std::string                    sMissingName;

    /// @brief  Plugin that required it.
    ///
    /// @details  Without it, "'network' is missing" in an install of forty
    ///            plugins sends the user looking for who asked for it.
    std::string                    sMissingRequiredBy;

    /// @brief  Repeated name, when there was a duplicate.
    std::string                    sDuplicateName;
};

Result of the sort.

function

TopologicalOrder

Ethereal::Plugin#
ESortError TopologicalOrder( const std::vector< SDependencyNode > & Nodes, SSortResult * pOut );

Sorts the plugins in the order they can load.

Follows the three rules in the file header: cycle members, deterministic tie break and optional dependencies. Allocates. Cold path, it runs once at startup. Thread safety: full.

Nodes
The plugins and their dependencies.
pOut
Receives the result. Must not be null.
ESortError::eNone, or what prevented the sort.

host.hpp

#include <ethereal/cpp/plugin/host.hpp>

Plugin host: loads, keeps and unloads plugins.

The contract is C, and that is not nostalgia. The obvious form, an abstract C++ class with virtual methods that the plugin inherits, does not cross a dynamic library boundary. It works in the tests, on the same machine, with the same compiler, and fails the first time someone else builds a plugin. The reasons:

  • Name decoration differs between compilers, and even between versions of the same one. 'GetProcAddress' asks for a name, and in C++ that name is not what you wrote.
  • The virtual table layout is not standard. MSVC and Itanium (GCC/Clang) order it differently with multiple inheritance.
  • Standard library types change size between debug and release builds in MSVC. Passing a 'std::string' from one to the other reads garbage.
  • The heap is a different one. Memory allocated on one side and freed on the other corrupts, and the damage shows up much later. So the contract is a plain data structure with 'extern "C"' function pointers and a version in front. Nothing else crosses.

The version is the first field and the only one read before the check. With the version in the middle of the structure, reading the name of a plugin from another generation would already be a read at the wrong offset, possibly an invalid pointer followed by a walk through memory. The host reads SPluginInfo::uAbiVersion, compares it with PLUGIN_ABI_VERSION, and only touches the rest if it matches.

A failing plugin does not take the host down. Loading a folder of plugins is an operation where failure is normal: a file of another architecture, a missing dependency, an old version. Failures are collected in CPluginHost::Failures, and what worked stays loaded.

Unloading is in the reverse order of loading. Plugins depend on each other in the order they were loaded, and unloading the first before the last leaves the last pointing to code that left memory. See rule 1 in 'library.hpp'.

const

PLUGIN_ABI_VERSION

Ethereal::Plugin#
constexpr ETL_UINT32 PLUGIN_ABI_VERSION = 1;

Generation of the contract. A plugin that declares another one is rejected.

const

PLUGIN_ENTRY_NAME

Ethereal::Plugin#
constexpr const char * PLUGIN_ENTRY_NAME = "EtherealPluginEntry";

Name of the entry symbol every plugin must export.

Must be extern "C", otherwise the exported name is the one decorated by the compiler and no host finds it.

struct

SPluginInfo

Ethereal::Plugin#
C++
struct   SPluginInfo
{
    /// @brief  The first field, and the only one read before it is checked.
    ///
    /// @details  See the file header: with the version at another offset,
    ///            reading any other field of a plugin from another generation
    ///            would already be a read at the wrong offset.
    ETL_UINT32        uAbiVersion;

    /// @brief  Name, unique among the loaded plugins.
    const char *    sName;

    /// @brief  Plugin version. Free form, it belongs to the plugin.
    const char *    sVersion;

    /// @brief  One line of description. May be null.
    const char *    sDescription;

    /// @brief  Called once, after the load. Returning false aborts the load of
    ///             that plugin, and it is unloaded.
    bool            ( *pfnInitialize )( void * pHostContext );

    /// @brief  Called once, before the library leaves memory.
    void            ( *pfnShutdown )( void );

    /// @brief  How the host asks the plugin for something concrete.
    ///
    /// @details  Interface name and version are agreed between the two.
    ///            Returning null means "I do not offer that".
    void *            ( *pfnQuery )( const char * sInterfaceName, ETL_UINT32 uVersion );
};

What a plugin tells about itself, and what it offers.

Plain data structure, nothing of C++ inside. Every pointer may be null, and the host checks before calling: a plugin that only offers an interface and needs no initialization is legitimate.

alias

PluginEntryFn

Ethereal::Plugin#
using PluginEntryFn = const SPluginInfo * ( * )( void );

Signature of the entry point.

enum

EPluginError

Ethereal::Plugin#
C++
enum class EPluginError : ETL_UINT8
{
    /// @brief  No error.
    eNone = 0,

    /// @brief  Did not even load as a dynamic library.
    eLoadFailed,

    /// @brief  Loaded, but does not export @ref PLUGIN_ENTRY_NAME. Probably a
    ///             regular library that was in the same folder.
    eNoEntryPoint,

    /// @brief  The entry point returned null.
    eNoInfo,

    /// @brief  The contract generation does not match.
    eBadAbiVersion,

    /// @brief  The structure came without a name.
    eBadInfo,

    /// @brief  A plugin with that name was already loaded.
    eDuplicateName,

    /// @brief  The plugin initialization returned false.
    eInitFailed,

    /// @brief  No plugin with that name.
    eNotFound,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///             has ended, or the license passed was refused (see
    ///             Bundle::UnlockBundle).
    eNotLicensed
};

What can go wrong while loading a plugin.

struct

SPluginLoadResult

Ethereal::Plugin#
C++
struct   SPluginLoadResult   final
{
    /// @brief  What happened.
    EPluginError    eError = EPluginError::eNone;

    /// @brief  Path of the library.
    std::string        sPath;

    /// @brief  Plugin name, when it was read.
    std::string        sName;

    /// @brief  Description of the failure.
    std::string        sMessage;

    /// @brief  true when the load succeeded.
    ///
    ETL_API_NOIGN    bool IsOk() const ETL_NOEXCEPT    { return eError == EPluginError::eNone; }
};

Result of loading a plugin.

class

CPluginHost

Ethereal::Plugin#

Loads, keeps and unloads plugins.

class CPluginHost final

The rules are in the file header: version in front, failure that does not take the host down, and unload in reverse order.

When the host is destroyed, every pointer obtained from any plugin stops being valid, and so does every object they created. See rule 1 in library.hpp.
constructor

CPluginHost

#
CPluginHost();

Constructor. No plugin loaded.

function

SetHostContext

#
void SetHostContext( void * pContext ) noexcept;

Sets what is passed to pfnInitialize of each plugin.

Must be agreed between host and plugin, and crosses as void* on purpose: anything richer would be C++ crossing the boundary. Must stay valid while any plugin is loaded.

pContext
The host context.
function

LoadOne

#
SPluginLoadResult LoadOne( const std::string & sPath );

Loads a plugin from a path.

sPath
Path of the library.
The result. Check SPluginLoadResult::IsOk.
function

LoadDirectory

#
std::size_t LoadDirectory( const std::string & sDirectory );

Loads every plugin found in sDirectory.

Only looks at files with the dynamic library extension of this system. What fails goes to Failures and does not stop the others.

The file system order is not stable, so the files are sorted by name before loading. Without it, the initialization order would change between machines, and a dependency bug between plugins would show up on one and not on another.

sDirectory
Folder to scan.
How many loaded.
function

Unload

#
bool Unload( const std::string & sName );

Unloads one plugin by name, calling its shutdown first.

sName
Plugin name.
false when there is no plugin with that name.
function

UnloadAll

#
void UnloadAll();

Unloads every plugin, in the reverse order of the load.

function

Count

#
std::size_t Count() const noexcept;

Number of loaded plugins.

function

Has

#
bool Has( const std::string & sName ) const;

true when a plugin with that name is loaded.

function

Find

#
const SPluginInfo * Find( const std::string & sName ) const;

Info of a plugin, or null.

The pointer belongs to the plugin and dies with it.
function

Names

#
std::vector< std::string > Names() const;

Names, in load order.

function

Query

#
void * Query( const std::string & sPluginName, const std::string & sInterfaceName, const ETL_UINT32 uVersion );

Asks a plugin for an interface.

sPluginName
Plugin name.
sInterfaceName
Interface name.
uVersion
Interface version.
Null when the plugin does not exist, does not offer queries, or does not offer that interface in that version.
function

Failures

#
const std::vector< SPluginLoadResult > & Failures() const noexcept;

What failed since the last ClearFailures.

Failing to load a plugin is normal, so it is collected instead of stopping. What is not normal is nobody looking at this list.

function

ClearFailures

#
void ClearFailures() noexcept;

Clears the failure list.

hotswap.hpp

#include <ethereal/cpp/plugin/hotswap.hpp>

Swaps the entry table of a plugin while it is being called.

The spec calls this "the single hardest correctness requirement in the module", and the reason is this sentence: "Unloading a module with a live call in flight is a guaranteed crash." The memory where the code was is no longer mapped, and the call that was inside returns to an address that does not exist. No 'try' catches that, and the crash report points to the wrong place.

Reader side, no lock and no branch. The spec: "Hot reload must swap an atomic pointer to the function table. Readers take the pointer once at the top of their operation. No reader-side lock, no reader-side branch beyond the pointer load." The reader does this, in order, and nothing else: 1. announces it entered, writing an odd number in its slot. 2. a fence. 3. reads the table pointer. 4. uses it. 5. announces it left, writing the next even number. No loop, no condition, no lock. There is a fence, and without it this is wrong: the slot write and the pointer read are a store-load pair, the one pair the processor is allowed to reorder. Without the fence the reader may read the pointer before announcing it entered. The writer looks at the slot, sees it idle, concludes nobody is inside, and unloads the library under a call in progress.

Writer side, wait for each reader to pass a quiescent point. After swapping the pointer, the writer cannot release the old table while someone is still inside. For each reader it reads the slot. If even, that reader is outside and there is nothing to wait for: when it enters, it enters after the swap and sees the new table. If odd, that reader is inside now, and the writer waits until the number changes. A change means it left, or left and entered again, and in both cases the call that was in progress is over. It does not wait for the number to become even: a reader in a tight loop can enter and leave several times between two reads of the writer, and waiting for a specific value could wait for a moment never observed.

Why not a 'shared_mutex'. It would put a shared atomic write on the path of every plugin call, and the spec sets a target of less than two nanoseconds over an indirect call. A read lock, even uncontended, costs more than that, and with dozens of threads its cache line becomes the bottleneck. The per thread slot is shared with nobody: each one in its own cache line, written only by its owner.

const

ETL_HOT_MAX_READERS

Ethereal::Plugin#
constexpr ETL_UINT32 ETL_HOT_MAX_READERS = 32u;

Number of simultaneous readers the table supports.

Fixed on purpose. Growing the slot list would need a lock on the registration path, which runs once per thread, but it would also need to synchronize with whoever is reading right now.

Thirty two is more than any reasonable host needs. Whoever needs more changes it here and rebuilds. Registering the thirty third returns an error, not a silent corruption.

class

CHotTable

Ethereal::Plugin#

An entry table that can be swapped with calls in progress.

class CHotTable final

Read the notes in the file header before changing anything. They are contract, and the reader fence in particular cannot be optimized away.

The padding of this type is intended (the alignment). See 'ETL_BEGIN_INTENDED_PADDING'.

constructor

CHotTable

#
CHotTable() noexcept;

Constructor. No table set.

function

RegisterReader

#
ETL_UINT32 RegisterReader() noexcept;

Reserves a slot for this thread.

Once per thread, off the hot path.

The slot number, or ETL_HOT_MAX_READERS when none is left.
function

UnregisterReader

#
void UnregisterReader( ETL_UINT32 uSlot ) noexcept;

Returns the slot.

uSlot
Slot from RegisterReader.
function

Enter

#
const SPluginEntries * Enter( ETL_UINT32 uSlot ) noexcept;

Enters, and returns the table to use until leaving.

No lock and no branch. See the file header for what this does and in which order.

The returned pointer is valid until Leave. Keeping it after that is exactly the crash this file exists to prevent.

uSlot
Slot from RegisterReader.
The current table.
function

Leave

#
void Leave( ETL_UINT32 uSlot ) noexcept;

Leaves.

uSlot
Slot from RegisterReader.
function

Swap

#
const SPluginEntries * Swap( const SPluginEntries * pNew ) noexcept;

Sets a table, without waiting for anyone.

pNew
The new table.
The previous one.
function

Drain

#
ETL_UINT32 Drain( ETL_UINT32 uSpinLimit = 0u ) noexcept;

Waits until no call in progress can be in the previous table.

Call this after Swap and before unloading anything. It is the only thing between a reload and a guaranteed crash.

uSpinLimit
Busy wait rounds before yielding the processor. Zero uses a reasonable value.
Number of readers that had to be waited for. Zero means nobody was inside, the common case.
function

Current

#
const SPluginEntries * Current() const noexcept;

Current table, without entering. For diagnostics.

function

ReaderCount

#
ETL_UINT32 ReaderCount() const noexcept;

Number of slots in use.

function

InsideCount

#
ETL_UINT32 InsideCount() const noexcept;

Number of readers inside right now. For diagnostics.

library.hpp

#include <ethereal/cpp/plugin/library.hpp>

Dynamic library loading behind one interface.

Five rules, and the first one kills processes.

1. Unloading invalidates everything that came from the library. Not only function pointers: also the virtual tables of the objects it created, the string literals it returned, its static objects and the stack unwinding tables used by exception handling. An object created by a library and destroyed after the library left memory jumps into nothing in its destructor. An exception crossing what is left of it ends the process. None of this happens at the 'Unload' call. It happens later, somewhere else, and the stack does not point here. That is why CDynamicLibrary is movable and not copyable, and why CPluginHost unloads in the reverse order of the load.

2. A missing symbol is the common case. A plugin built against an older SDK does not have the new symbols. That is daily life for whoever ships an SDK, not a programming error. CDynamicLibrary::GetSymbol returns null and keeps the reason. No exception and no assert. A plugin loader must be able to say "this version does not fit" instead of crashing.

3. The file name differs on each system: 'foo.dll', 'libfoo.so', 'libfoo.dylib'. DecorateName builds the right one, so the caller code has no '#ifdef' around.

4. A bare name is a hijacking vector. 'LoadLibrary("help.dll")' searches a list of directories that, in several setups, includes the current working directory. Whoever controls that directory picks the code your process runs. CDynamicLibrary::Load accepts a bare name because it is sometimes what is wanted (a system library), but the right thing is an absolute path, and CDynamicLibrary::LoadFromDirectory makes that the easy path.

5. The system error is short lived and must be captured at once. 'dlerror' clears itself when read, and 'GetLastError' is overwritten by the next system call, including one made inside a destructor on the error path. The text is captured right after the failure and kept in CDynamicLibrary::LastError.

enum

ELibraryError

Ethereal::Plugin#
C++
enum class ELibraryError : ETL_UINT8
{
    /// @brief  No error.
    eNone = 0,

    /// @brief  The library could not be loaded: missing file, wrong
    ///             architecture, or one of its dependencies is missing. The system
    ///             text in @ref CDynamicLibrary::LastError says which.
    eLoadFailed,

    /// @brief  The requested symbol does not exist in that library. See rule 2.
    eSymbolNotFound,

    /// @brief  The operation was requested with no library loaded.
    eNotLoaded,

    /// @brief  The path is empty.
    eInvalidPath,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///             has ended, or the license passed was refused (see
    ///             Bundle::UnlockBundle).
    eNotLicensed
};

What can go wrong.

function

DecorateName

Ethereal::Plugin#
std::string DecorateName( const std::string & sBaseName );

Builds the file name of a library for this system.

@c "network" becomes @c "network.dll" on Windows, @c "libnetwork.so" on Linux and @c "libnetwork.dylib" on macOS. See rule 3.

sBaseName
Library name without prefix or extension.
The decorated file name.
function

LibraryExtension

Ethereal::Plugin#
const char * LibraryExtension() noexcept;

Dynamic library extension of this system, with the dot.

class

CDynamicLibrary

Ethereal::Plugin#

A loaded dynamic library, with the symbols it exports.

class CDynamicLibrary final

Movable, not copyable: two copies would mean two unloads of the same load, and the second would tear down what was still in use.

Everything that came from this library dies with it: function pointers, virtual tables, string literals it returned, its static objects. See rule 1 in the file header. The program does not crash at Unload, it crashes later, far away. ``cpp Ethereal::Plugin::CDynamicLibrary Lib; if( Lib.LoadFromDirectory( sFolder, "network" ) ) { using FnAdd = int ( * )( int, int ); if( const auto pfnAdd = Lib.GetFunction< FnAdd >( "Add" ) ) const int iR = pfnAdd( 2, 3 ); }
constructor

CDynamicLibrary

#
CDynamicLibrary();

Constructor. No library loaded.

constructor

CDynamicLibrary

#
CDynamicLibrary( CDynamicLibrary && Other ) noexcept;

Move constructor. The source is left valid and empty.

operator

operator=

#
CDynamicLibrary & operator=( CDynamicLibrary && Other ) noexcept;

Move assignment. Unloads the current library first.

function

Load

#
bool Load( const std::string & sPath );

Loads sPath.

Accepts an absolute path, a relative path or a bare name. A bare name leaves the search to the system, which in several setups includes the current working directory (see rule 4). To load something of your own, prefer LoadFromDirectory.

A library already loaded is unloaded first.

sPath
Path or name of the library.
false on failure. The reason is in LastError, and ELibraryError::eNotLicensed in Error when the library is not licensed.
function

LoadFromDirectory

#
bool LoadFromDirectory( const std::string & sDirectory, const std::string & sBaseName );

Loads sBaseName from sDirectory, decorating the name.

The safe form and the one to prefer: the path is built here, and the system search is left out.

sDirectory
Folder of the library.
sBaseName
Library name without prefix or extension.
false on failure. The reason is in LastError.
function

Unload

#
void Unload() noexcept;

Unloads the library.

After this, every symbol obtained from this library is invalid, and so is every object it created. See rule 1.
function

IsLoaded

#
bool IsLoaded() const noexcept;

true when a library is loaded.

function

Path

#
const std::string & Path() const noexcept;

Path the library was loaded with.

function

GetSymbol

#
void * GetSymbol( const std::string & sName );

Address of sName, or null when it does not exist.

A missing symbol is not a programming error, it is a plugin built against an older version. See rule 2.

The name is the exported one. In C++ it is decorated by the compiler and differs between compilers, so the entry point of a plugin must be extern "C".

sName
Exported symbol name.
The address, or null.
function

GetFunction

#
template< typename TFn > TFn GetFunction( const std::string & sName )

Same as GetSymbol, already cast to the function type.

The cast from void* to a function pointer is formally undefined in C, and POSIX defines it precisely to allow this. It lives in one place, here, instead of spread over callers.

sName
Exported symbol name.
The function pointer, or null.
function

HasSymbol

#
bool HasSymbol( const std::string & sName );

Tells whether sName exists, without returning the address.

sName
Exported symbol name.
true when the symbol exists.
function

Error

#
ELibraryError Error() const noexcept;

Error of the last operation.

function

LastError

#
const std::string & LastError() const noexcept;

System text for the last failure.

Captured at the moment of the failure, not later: dlerror clears itself when read and GetLastError is overwritten by the next call, including one made inside a destructor. See rule 5.

library_load.hpp

#include <ethereal/cpp/plugin/library_load.hpp>

Loads a dynamic library, saying where to look.

How a library is searched for is a security question. The spec is explicit: "Search path control: absolute path, explicit directory list, and the platform default, selected explicitly. The platform default is not the default in this API, because implicit search order is a security problem (DLL planting). The caller must opt in."

The planting attack works like this: the program asks for 'network', the system searches a list of folders, and someone puts a file with that name in a folder that comes before the right one. The program loads the attacker's file and runs its code with the privileges of whoever ran the program. On Windows the list includes, depending on the setup, the folder of the executable, the system folders, the current folder and the whole 'PATH'. The current folder belongs to whoever opened the program, not to whoever wrote it. On POSIX there is 'LD_LIBRARY_PATH', which anyone sets before starting the process.

None of those lists is chosen by the author of the library. The default here is ESearchPolicy::eExactPath, which does not search anywhere: it uses what it was given and rejects a name that does not say where it is. Whoever wants the system order asks for it by name, and the name is ugly on purpose.

Before this addition, 'CDynamicLibrary::Load' called 'LoadLibraryA' and 'dlopen' with the path as given. With a full path that is safe. With a plain name it is the system search order, so the library was already doing by default what the spec forbids. The old entry point stays, because the host and the tests use it with full paths. The new one is the one that rejects.

const

ETL_LIB_NONE

Ethereal::Plugin#
constexpr ETL_UINT32 ETL_LIB_NONE = 0u;

Nothing requested.

const

ETL_LIB_LAZY

Ethereal::Plugin#
constexpr ETL_UINT32 ETL_LIB_LAZY = 1u << 0;

Resolves symbols only when they are used.

Faster to load and slower to blow up: a missing symbol shows up at the first call, far from where the load happened. Does not exist on Windows and is ignored there, resolution is always immediate.

const

ETL_LIB_NOW

Ethereal::Plugin#
constexpr ETL_UINT32 ETL_LIB_NOW = 1u << 1;

Resolves everything now. A missing symbol fails the load.

const

ETL_LIB_GLOBAL

Ethereal::Plugin#
constexpr ETL_UINT32 ETL_LIB_GLOBAL = 1u << 2;

Its symbols become visible to libraries loaded later.

const

ETL_LIB_LOCAL

Ethereal::Plugin#
constexpr ETL_UINT32 ETL_LIB_LOCAL = 1u << 3;

Its symbols stay with whoever loaded it. The sensible choice.

const

ETL_LIB_NODELETE

Ethereal::Plugin#
constexpr ETL_UINT32 ETL_LIB_NODELETE = 1u << 4;

Does not really unload when the last owner releases it.

For a library that registers things that outlive it, such as a global destructor or a signal handler. Unloading it leaves pointers to code that is no longer mapped.

const

ETL_LIB_ALREADY_LOADED

Ethereal::Plugin#
constexpr ETL_UINT32 ETL_LIB_ALREADY_LOADED = 1u << 5;

Returns it only if it is already loaded. Loads nothing.

The only way to ask "is this already here?" without the side effect of bringing the library into the process.

const

ETL_LIB_SEARCH_OWN_DIR

Ethereal::Plugin#
constexpr ETL_UINT32 ETL_LIB_SEARCH_OWN_DIR = 1u << 6;

Its dependencies are searched in its own folder, not the program's.

A plugin that ships its own libraries next to it needs this. Without it, the system searches the dependencies in the folder of the executable, and may find a wrong version or nothing.

enum

ESearchPolicy

Ethereal::Plugin#
C++
enum class   ESearchPolicy : ETL_UINT8
{
    /// @brief  The default: uses the path as given and searches nowhere.
    ///
    /// @details  A name with no folder separator is rejected, because handing
    ///            it to the system would accept the system search order, which
    ///            this API does not do on its own.
    eExactPath = 0,

    /// @brief  Only in the folders the caller listed, in the order listed.
    ///
    /// @details  The first one that has the file wins. No other is consulted:
    ///            not the system's, not the current one, not 'PATH'.
    eDirectories = 1,

    /// @brief  The system order. Read the file header before choosing this.
    ///
    /// @details  Includes the current folder and environment variables the
    ///            user controls. The right option to load a library of the
    ///            system itself ('ws2_32', 'libz'), the wrong one to load a
    ///            plugin.
    ePlatformDefault = 2
};

Where the library may be searched for.

function

SearchPolicyName

Ethereal::Plugin#
const ETL_CHAR * SearchPolicyName( ESearchPolicy ePolicy ) noexcept;

Name of the policy, for messages. Never returns null.

enum

ELoadError

Ethereal::Plugin#
C++
enum class   ELoadError : ETL_UINT8
{
    /// @brief  Loaded.
    eNone = 0,

    /// @brief  The path is empty.
    eEmptyPath,

    /// @brief  @ref ESearchPolicy::eExactPath was requested with a name that
    ///             does not say where it is.
    ///
    /// @details  This is not a caller bug to work around. It is the deliberate
    ///            refusal to hand the choice of the file to the system search
    ///            order. Either give the path, list the folders, or ask for the
    ///            system order by name.
    eAmbiguousName,

    /// @brief  A folder list was requested and the list is empty.
    eNoDirectories,

    /// @brief  Not in any of the listed folders.
    eNotFound,

    /// @brief  The system refused to load. The text says why.
    eSystemRefused,

    /// @brief  @ref ETL_LIB_ALREADY_LOADED was requested and it was not loaded.
    eNotLoaded,

    /// @brief  Flags that contradict each other.
    ///
    /// @details  @c LAZY with @c NOW, or @c GLOBAL with @c LOCAL. Silently
    ///            picking one would make the program behave in a way nobody
    ///            asked for.
    eConflictingFlags,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///             has ended, or the license passed was refused (see
    ///             Bundle::UnlockBundle).
    eNotLicensed
};

What can go wrong while resolving and loading.

function

LoadErrorName

Ethereal::Plugin#
const ETL_CHAR * LoadErrorName( ELoadError eError ) noexcept;

Name of the error, for messages. Never returns null.

struct

SLoadRequest

Ethereal::Plugin#
C++
struct   SLoadRequest   final
{
    /// @brief  'sizeof( SLoadRequest )'.
    ETL_UINT32        iStructSize = sizeof( SLoadRequest );

    /// @brief  Combination of ETL_LIB_*.
    ETL_UINT32        uFlags = ETL_LIB_NONE;

    /// @brief  Where to search. See the file header.
    ESearchPolicy    eSearch = ESearchPolicy::eExactPath;

    /// @brief  Explicit padding.
    ETL_UINT8        aPad[ 7 ] = {};

    /// @brief  The folders, for @ref ESearchPolicy::eDirectories. In order.
    std::vector< std::string >    Directories;
};

The whole load request.

struct

SLoadResult

Ethereal::Plugin#
C++
struct   SLoadResult   final
{
    /// @brief  'sizeof( SLoadResult )'.
    ETL_UINT32        iStructSize = sizeof( SLoadResult );

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding = 0;

    /// @brief  What happened.
    ELoadError        eError = ELoadError::eNone;

    /// @brief  Explicit padding.
    ETL_UINT8        aPad[ 7 ] = {};

    /// @brief  The path actually opened.
    ///
    /// @details  Look at this when debugging a wrong load. With a folder list,
    ///            knowing which one won is the difference between seeing the
    ///            problem and guessing.
    std::string        sResolvedPath;

    /// @brief  What the system said when it refused. Empty when it did not.
    std::string        sSystemMessage;

    /// @brief  The native handle. Null when not loaded.
    void *            pNativeHandle = nullptr;

    /// @brief  How many times this process requested this library, this one included.
    ///
    /// @details  One means it was the first time. More than one means it was
    ///            already in the process, and the system returned the same
    ///            handle instead of mapping another copy.
    ETL_UINT32        uRefCount = 0;

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding2 = 0;
};

Result of a load.

function

LoadLibraryEx

Ethereal::Plugin#
ELoadError LoadLibraryEx( const std::string & sPath, const SLoadRequest & Request, SLoadResult * pOut );

Loads a dynamic library, saying where to search.

Read the file header. The default searches nowhere, on purpose.

Dropping the result without calling ReleaseLibrary leaves the library loaded. Sometimes that is what is wanted, so it is not an error.

Thread safety: full. The count table has its own lock.

sPath
The path, or the name, depending on the policy.
Request
The request.
pOut
Receives the result. Must not be null.
ELoadError::eNone, or what prevented the load. The same value goes to pOut.
function

ReleaseLibrary

Ethereal::Plugin#
ETL_UINT32 ReleaseLibrary( void * pNativeHandle ) noexcept;

Releases a library loaded by LoadLibraryEx.

pNativeHandle
The handle from the result.
References left. Zero means it was unloaded.
function

LibraryRefCount

Ethereal::Plugin#
ETL_UINT32 LibraryRefCount( void * pNativeHandle ) noexcept;

How many times this library was requested and not yet released.

Answers "why is this still loaded?", one of the hardest questions to answer without a number.

pNativeHandle
The handle from the result.
The count, or zero when the handle is unknown.
function

LastSystemError

Ethereal::Plugin#
ETL_UINT64 LastSystemError( ETL_CHAR * pOut, ETL_UINT64 uOut ) noexcept;

Text of the last system error, copied into the caller buffer.

The spec asks for it in these words: "Error reporting must include the platform error string ('dlerror', 'FormatMessage'), copied into a caller-provided buffer."

Copied, not borrowed: 'dlerror' returns a pointer the next call invalidates, and 'FormatMessage' returns memory someone has to free. Both ways of getting it wrong end in the same place.

pOut
Receives the text. Always null terminated when uOut > 0.
uOut
Capacity of pOut.
Size of the whole text, without the terminator, even when it did not fit (two pass protocol).

lifecycle.hpp

#include <ethereal/cpp/plugin/lifecycle.hpp>

Lifecycle of a plugin: Init, Start, Stop, Shutdown.

Init -> Start -> Stop -> Shutdown

If 'Init' fails, 'Shutdown' is not called. Getting this rule wrong is what corrupts memory most often, and the spec asks for it to be documented clearly. An 'Init' that failed may have failed on its first line, before building what 'Shutdown' would destroy. Calling 'Shutdown' there hands uninitialized pointers to a destructor, and the damage shows up later, when the freed memory is reused by something else. The contract a plugin author can rely on: if 'Init' returns an error, nothing else is called and the library is unloaded. On the other side, 'Init' must clean up what it built before returning an error. Nobody else will.

An invalid transition is an error, not a silent no-op. The spec says "State machine transitions are strictly enforced and a bad transition is a hard error, not a no-op." Calling 'Start' twice, or 'Stop' before starting, is a caller bug. Swallowing it makes the program look fine until the plugin keeps state, and then the symptom is something else, somewhere else. The transition table is a data array, not a chain of 'if'. The test suite walks every pair of state and operation and checks each one. With chained 'if', the test would repeat the same logic and agree with its bug.

No exception crosses the boundary. The spec says "Every callback into the plugin is wrapped so a thrown exception (from a plugin built by someone else, with exceptions on) cannot cross the boundary. Catch and convert to a failure status at the shim." There is a real limit to this: 'catch( ... )' catches what the same runtime threw. A plugin built with another C++ runtime (another compiler, version or Windows configuration) throws through a mechanism this side does not recognize, and the process ends before reaching the 'catch'. The host cannot fix that. The rule in 'plugin_abi.h' covers it: entries are 'extern "C"' and return 'int', and a well written plugin does not let exceptions out. The 'catch' here is a net for badly written plugins, not a guarantee against differently built ones.

enum

EPluginState

Ethereal::Plugin#
C++
enum class   EPluginState : ETL_UINT8
{
    /// @brief  The library is not in memory.
    eUnloaded = 0,

    /// @brief  Loaded, entries resolved, and none of its code has run yet.
    eLoaded = 1,

    /// @brief  'Init' returned success.
    eInitialized = 2,

    /// @brief  'Start' returned success. It is running.
    eStarted = 3,

    /// @brief  'Stop' returned success. It can start again.
    eStopped = 4,

    /// @brief  Something failed. There is no way out of this state.
    ///
    /// @details  A failed plugin is quarantined and the host goes on without
    ///            it, as the spec asks under "Isolation". Starting again from
    ///            the same point would call code already shown to be broken,
    ///            with an unknown internal state.
    eFailed = 5
};

Where the plugin is in its lifecycle.

The values are ABI: never reorder.

function

PluginStateName

Ethereal::Plugin#
const ETL_CHAR * PluginStateName( EPluginState eState ) noexcept;

Name of the state, for messages. Never returns null.

enum

EPluginOp

Ethereal::Plugin#
C++
enum class   EPluginOp : ETL_UINT8
{
    /// @brief  Calls 'Init'.
    eInit = 0,

    /// @brief  Calls 'Start'.
    eStart = 1,

    /// @brief  Calls 'Stop'.
    eStop = 2,

    /// @brief  Calls 'Shutdown'.
    eShutdown = 3,

    /// @brief  Number of operations. Not an operation.
    eCount = 4
};

What can be asked of a plugin.

function

PluginOpName

Ethereal::Plugin#
const ETL_CHAR * PluginOpName( EPluginOp eOp ) noexcept;

Name of the operation, for messages. Never returns null.

function

IsTransitionAllowed

Ethereal::Plugin#
bool IsTransitionAllowed( EPluginState eFrom, EPluginOp eOp ) noexcept;

Tells whether the operation is allowed in that state.

Exposed on purpose, so the suite can walk every pair and check each one against a table written by hand in the test. A rule that only exists inside the function that applies it can only be tested by repeating it, and a test that repeats the logic agrees with its bug.

eFrom
Current state.
eOp
Requested operation.
true when allowed.
function

StateAfter

Ethereal::Plugin#
EPluginState StateAfter( EPluginState eFrom, EPluginOp eOp ) noexcept;

State the operation leaves the plugin in, when it succeeds.

eFrom
Current state.
eOp
Requested operation.
The next state.
struct

SPluginEntries

Ethereal::Plugin#
C++
struct   SPluginEntries   final
{
    /// @brief  'sizeof( SPluginEntries )'.
    ETL_UINT32                iStructSize = sizeof( SPluginEntries );

    /// @brief  Explicit padding.
    ETL_UINT32                uPadding = 0;

    /// @brief  'Init' entry.
    ETLC_PluginInitFn        pfnInit = nullptr;

    /// @brief  'Start' entry.
    ETLC_PluginStartFn        pfnStart = nullptr;

    /// @brief  'Stop' entry.
    ETLC_PluginStopFn        pfnStop = nullptr;

    /// @brief  'Shutdown' entry.
    ETLC_PluginShutdownFn    pfnShutdown = nullptr;

    /// @brief  'Query' entry.
    ETLC_PluginQueryFn        pfnQuery = nullptr;

    /// @brief  Optional: state export across a reload.
    ///
    /// @details  Null when the plugin does not export it, which is the common
    ///            case, and the reload then happens without state. See the
    ///            memory ownership note in @c plugin_abi.h: the block belongs
    ///            to the host allocator, because the library that allocated it
    ///            is no longer mapped when it is freed.
    ETLC_PluginExportStateFn    pfnExportState = nullptr;

    /// @brief  Optional: state import across a reload. See @ref pfnExportState.
    ETLC_PluginImportStateFn    pfnImportState = nullptr;
};

The plugin function pointers, resolved once.

The spec puts a performance mandate on this: "Resolved entry points are stored in a flat vtable-like struct of raw function pointers owned by the host. After Start, calling a plugin function is one indirect call through a cached pointer. No lookup, no map, no string comparison, no lock."

So it is a plain structure of raw pointers, resolved at load and never at the first call. Lazy resolution would put a question per call on the hot path, plus a concurrency question that does not need to exist.

enum

ELifecycleError

Ethereal::Plugin#
C++
enum class   ELifecycleError : ETL_UINT8
{
    /// @brief  Done.
    eNone = 0,

    /// @brief  The operation is not allowed in the current state.
    ///
    /// @details  Not a silent no-op, on purpose. See the file header.
    eBadTransition,

    /// @brief  The entry this operation needs does not exist in the library.
    eMissingEntry,

    /// @brief  The plugin returned an error.
    ePluginRefused,

    /// @brief  The plugin threw an exception, caught at the boundary.
    ///
    /// @details  Kept apart from @ref ePluginRefused on purpose: refusing is
    ///            expected behavior, throwing is not. A plugin that throws has
    ///            a bug, and whoever operates the program deserves to know the
    ///            difference.
    ePluginThrew,

    /// @brief  An argument is not valid.
    eInvalidArgument
};

What can go wrong while driving the lifecycle of a plugin.

function

LifecycleErrorName

Ethereal::Plugin#
const ETL_CHAR * LifecycleErrorName( ELifecycleError eError ) noexcept;

Name of the error, for messages. Never returns null.

struct

SLifecycleResult

Ethereal::Plugin#
C++
struct   SLifecycleResult   final
{
    /// @brief  'sizeof( SLifecycleResult )'.
    ETL_UINT32            iStructSize = sizeof( SLifecycleResult );

    /// @brief  What happened on the host side.
    ELifecycleError        eError = ELifecycleError::eNone;

    /// @brief  Explicit padding.
    ETL_UINT8            aPad[ 3 ] = {};

    /// @brief  What the plugin returned. Only meaningful when it was called.
    ETL_INT32            iPluginReturn = 0;

    /// @brief  State it was left in.
    EPluginState        eState = EPluginState::eUnloaded;

    /// @brief  Explicit padding.
    ETL_UINT8            aPad2[ 3 ] = {};

    /// @brief  Nonzero when the library must be unloaded now.
    ///
    /// @details  Set when 'Init' failed: by the rule in the file header,
    ///            'Shutdown' will not be called and nothing else can be done
    ///            with that library. The lifecycle driver reads this and
    ///            releases the library.
    ETL_INT32            iShouldUnload = 0;
};

Result of a lifecycle operation.

function

RunLifecycleOp

Ethereal::Plugin#
ELifecycleError RunLifecycleOp( const SPluginEntries & Entries, EPluginState * pState, EPluginOp eOp, const ETLC_PluginContext * pContext, SLifecycleResult * pOut );

Runs one lifecycle operation of a plugin, with a safety net.

Checks the transition, calls the entry inside a 'catch', translates what came back and updates the state. The three rules in the file header are contract.

Does not allocate. Thread safety: none. The lifecycle driver serializes, because the order is the contract.

Entries
Entries already resolved.
pState
The state, read and written. Must not be null.
eOp
What to do.
pContext
Only for EPluginOp::eInit. Ignored by the others.
pOut
Receives the result. Must not be null.
ELifecycleError::eNone, or what prevented the operation.

manifest.hpp

#include <ethereal/cpp/plugin/manifest.hpp>

Reads the plugin manifest without running the plugin.

The spec requires a wrong ABI version to be rejected with the plugin code most likely never having run, and the acceptance test checks it with a plugin that calls 'abort()' in a static initializer.

Loading a dynamic library runs its static initializers. There is no 'dlopen' that skips them on POSIX, so any gate that needs the library loaded comes too late. Nothing is loaded here. The manifest is exported data (see the main note in 'plugin_abi.h'), and data is read from the file with the same tables the loader would use, without handing control to anyone.

Numeric fields are read whole: ABI version, structure size, plugin version, API range, counts. Text fields are not. A 'const char *' inside the image on disk does not point anywhere yet: it is zero waiting for a relocation, or it holds the link address, which only becomes real once the loader places the image. That is enough for the gate, which decides on a number. Name and description are for display, and by then the plugin is loaded, or there is the sidecar manifest, which the spec asks for to scan a folder of two hundred without opening any.

This does not link the Platform module, on purpose. The spec says "The Plugin module does not link Platform". Platform has an export walk that looks similar but reads an image already loaded and returns an address. Here a file is read and bytes are returned. The code finds one data symbol with a linear scan of the name table. No hash table, no Bloom filter, no symbol versions: none of that pays off for a single lookup on a cold path.

enum

EManifestError

Ethereal::Plugin#
C++
enum class   EManifestError : ETL_UINT8
{
    /// @brief  Read.
    eNone = 0,

    /// @brief  The path is empty, or the output pointer is null.
    eInvalidArgument,

    /// @brief  The file does not exist or cannot be read.
    eNotFound,

    /// @brief  The file is not an image for this platform.
    ///
    /// @details  Wrong architecture, wrong format, or not a library at all.
    eNotAnImage,

    /// @brief  It is an image, and it does not export the manifest symbol.
    ///
    /// @details  Almost always means it is not a plugin, just a regular
    ///            library that happened to be in the folder.
    eNoManifest,

    /// @brief  The symbol exists and its content makes no sense.
    ///
    /// @details  Declared size smaller than the first two fields, or pointing
    ///            outside the image. A corrupted image looks like this.
    eBadManifest
};

What can go wrong while probing the manifest.

function

ManifestErrorName

Ethereal::Plugin#
const ETL_CHAR * ManifestErrorName( EManifestError eError ) noexcept;

Name of the error, for messages. Never returns null.

struct

SManifestProbe

Ethereal::Plugin#
C++
struct   SManifestProbe   final
{
    /// @brief  'sizeof( SManifestProbe )'.
    ETL_UINT32        iStructSize = sizeof( SManifestProbe );

    /// @brief  ABI version the plugin was built with.
    ///
    /// @details  The only field that can be trusted before the comparison.
    ///            If it does not match @c ETL_PLUGIN_ABI_VERSION, the rest of
    ///            the structure has a layout that is not ours, and any other
    ///            field read is garbage.
    ETL_UINT32        uAbiVersion = 0;

    /// @brief  'sizeof( ETLC_PluginManifest )' when the plugin was built.
    ETL_UINT32        uStructSize = 0;

    /// @brief  Bytes of the symbol actually read.
    ETL_UINT32        uBytesRead = 0;

    /// @brief  Plugin major version.
    ETL_UINT16        uMajor = 0;

    /// @brief  Plugin minor version.
    ETL_UINT16        uMinor = 0;

    /// @brief  Plugin patch version.
    ETL_UINT16        uPatch = 0;

    /// @brief  Explicit padding.
    ETL_UINT16        uPadding = 0;

    /// @brief  Lowest API version the plugin can talk to.
    ETL_UINT32        uApiVersionMin = 0;

    /// @brief  Highest API version the plugin can talk to.
    ETL_UINT32        uApiVersionMax = 0;

    /// @brief  Number of dependencies declared.
    ETL_UINT32        uDependencyCount = 0;

    /// @brief  Number of services provided.
    ETL_UINT32        uProvidedCount = 0;
};

What was read from the manifest without running the plugin.

Numbers only. See the file header on what cannot be read from the file.

function

ProbeManifest

Ethereal::Plugin#
EManifestError ProbeManifest( const std::string & sPath, SManifestProbe * pOut );

Reads the manifest of a file without loading or running anything.

This is what makes the ABI gate possible. Read the file header before replacing it with something that looks simpler: anything simpler loads the library, which is exactly what cannot be done.

Opens the file for reading, walks the export table, finds the manifest data symbol, reads its bytes and closes. The plugin code never gets control.

Allocates, the file is read into memory. Cold path. Thread safety: full.

sPath
Path of the library file.
pOut
Receives the result. Must not be null.
EManifestError::eNone, or what prevented the read.
function

IsAbiCompatible

Ethereal::Plugin#
bool IsAbiCompatible( const std::string & sPath, SManifestProbe * pProbeOut = nullptr, EManifestError * pErrorOut = nullptr );

Tells whether the plugin is compatible with this host.

Convenience over ProbeManifest for the common case. Also returns false when the read failed, which is the safe answer: a plugin that cannot be probed is not loaded.

sPath
Path of the library file.
pProbeOut
Optional. Receives what was read, even when incompatible.
pErrorOut
Optional. Receives the reason.
true when the manifest was read and the ABI version matches.
function

SidecarPathFor

Ethereal::Plugin#
std::string SidecarPathFor( const std::string & sLibPath );

Path of the sidecar file for a library.

Replaces the extension with .etlmanifest. A library with no extension gets it appended.

sLibPath
Path of the library.
Path of the sidecar.
function

WriteSidecar

Ethereal::Plugin#
bool WriteSidecar( const SManifestProbe & Probe, const std::string & sPath );

Writes the sidecar file from what was read from the library.

For a build step or a packaging tool. The format is 'key=value' text, one per line.

Probe
What was read from the library.
sPath
Path of the sidecar to write.
true when the file was written and closed.
function

ParseSidecarText

Ethereal::Plugin#
EManifestError ParseSidecarText( const char * pText, ETL_UINT64 uBytes, SManifestProbe * pOut );

Parses the text of a sidecar manifest, without touching the disk.

Reading and parsing are kept apart on purpose. Scanning a large folder is dominated by the cost of opening files, and without the split there is no way to tell how much is the disk and how much is ours. Measuring it by subtracting two large numbers even gave negative values.

Also serves callers that already have the bytes: a package, an embedded resource.

pText
The text.
uBytes
Size of the text, in bytes.
pOut
Receives the result. Must not be null.
EManifestError::eNone, or what prevented the parse.
function

ProbeSidecar

Ethereal::Plugin#
EManifestError ProbeSidecar( const std::string & sPath, SManifestProbe * pOut );

Reads the sidecar file. Does not open the library.

For discovery, not for deciding to load. See the note above.

sPath
Path of the sidecar.
pOut
Receives the result. Must not be null.
EManifestError::eNone, or what prevented the read.

registry.hpp

#include <ethereal/cpp/plugin/registry.hpp>

Plugin registry: discovers, sorts, loads and serves interfaces.

This class exists because its pieces already existed and did not talk to each other. The module already had, written and tested one by one:

  • ProbeManifest : reads the manifest from the file without loading anything.
  • ProbeSidecar : reads the sidecar manifest, for discovery without opening the library.
  • TopologicalOrder : sorts by dependency and reports the cycle members.
  • RunLifecycleOp : drives the lifecycle with the exception barrier. None of them was called by anything outside its own bench. The existing host loaded a folder in alphabetical order, and its comment said that without sorting "a dependency bug would show up on one machine and not another", describing the problem the topological sort next to it solved and nobody invoked. The spec asks for this as one class for that reason: the loose pieces pass their tests, and what they exist to do does not happen.

Discover, load and start are three things, and the spec keeps them apart:

  • CPluginRegistry::Scan looks at the folder and loads nothing. The spec justifies it with "scanning a directory of 200 plugins to find the three you want".
  • CPluginRegistry::LoadAll maps the ones that passed the gate, reads their manifest to know their dependencies, sorts, and only then starts them. Mapping is not starting, and that distinction makes the sort possible: the dependency list is made of strings that live inside the image, readable only after mapping it. What does not run before the right order is the plugin ETLC_Plugin_Init, which is what matters.

The sidecar manifest decides nothing. It speeds up discovery and nothing else. Anyone who writes to the folder writes in it whatever they want. The ABI gate still reads the manifest from inside the library file, with ProbeManifest, before mapping anything.

enum

ERegistryError

Ethereal::Plugin#
C++
enum class   ERegistryError : ETL_UINT8
{
    /// @brief  No error.
    eNone = 0,

    /// @brief  The path is not a folder, or could not be read.
    eBadDirectory,

    /// @brief  There is a dependency cycle. The members go to @ref SLoadReport.
    eCycle,

    /// @brief  A dependency nobody provides is missing.
    eMissingDependency,

    /// @brief  At least one plugin failed. The others started anyway.
    ePartial,

    /// @brief  Called out of order, typically @c LoadAll without @c Scan.
    eInvalidState,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///             has ended, or the license passed was refused (see
    ///             Bundle::UnlockBundle).
    eNotLicensed
};

What can go wrong in the registry.

function

RegistryErrorName

Ethereal::Plugin#
const ETL_CHAR * RegistryErrorName( const ERegistryError eError ) noexcept;

Name of the error, for reports. Never returns null.

struct

SScanOptions

Ethereal::Plugin#
C++
struct   SScanOptions   final
{
    /// @brief  'sizeof( SScanOptions )'.
    ETL_UINT32        iStructSize = sizeof( SScanOptions );

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding = 0;

    /// @brief  Uses the sidecar manifest when it exists.
    ///
    /// @details  This is what makes the scan cheap: reading a two hundred byte
    ///            text file costs a fraction of walking the export table of a
    ///            library.
    ///
    ///           With no sidecar file it falls back to @ref ProbeManifest,
    ///            which still loads nothing, it only costs more.
    bool            bUseSidecar = true;

    /// @brief  Keeps in the list the ones that do not pass the ABI gate.
    ///
    /// @details  For diagnostics, not for loading: @ref CPluginRegistry::LoadAll
    ///            always skips them. A tool that tells the user "this plugin is
    ///            from another generation" needs to see them, a normal host
    ///            does not.
    bool            bKeepIncompatible = false;

    /// @brief  Descends into subfolders.
    bool            bRecursive = false;

    /// @brief  Explicit padding.
    bool            bPadding = false;
};

What is wanted from the scan.

struct

SScanEntry

Ethereal::Plugin#
C++
struct   SScanEntry   final
{
    /// @brief  'sizeof( SScanEntry )'.
    ETL_UINT32            iStructSize = sizeof( SScanEntry );

    /// @brief  true when it passed the ABI gate.
    bool                bAbiOk = false;

    /// @brief  true when the manifest came from the sidecar file, not the library.
    ///
    /// @details  Matters for diagnostics: an outdated sidecar describes a
    ///            library that is no longer that one, and the symptom is a plugin
    ///            that "should load" and does not.
    bool                bFromSidecar = false;

    /// @brief  Explicit padding.
    ETL_UINT16            uPadding = 0;

    /// @brief  Path of the library.
    std::string            sPath;

    /// @brief  What was read without loading. Numbers only, see @ref SManifestProbe.
    SManifestProbe        Probe;

    /// @brief  What prevented the read, when @ref bAbiOk is false.
    EManifestError        eError = EManifestError::eNone;
};

A candidate found by the scan, without having been loaded.

struct

SPluginReport

Ethereal::Plugin#
C++
struct   SPluginReport   final
{
    /// @brief  'sizeof( SPluginReport )'.
    ETL_UINT32            iStructSize = sizeof( SPluginReport );

    /// @brief  State it was left in.
    EPluginState        eState = EPluginState::eUnloaded;

    /// @brief  Explicit padding.
    ETL_UINT16            uPadding = 0;

    /// @brief  Name its manifest declares.
    std::string            sName;

    /// @brief  Path of the library.
    std::string            sPath;

    /// @brief  What went wrong, when @ref eState is @c eFailed.
    std::string            sMessage;
};

What happened to one plugin.

struct

SLoadReport

Ethereal::Plugin#
C++
struct   SLoadReport   final
{
    /// @brief  Number left running.
    std::size_t                    uStarted = 0;

    /// @brief  Number put in quarantine.
    std::size_t                    uFailed = 0;

    /// @brief  Members of the cycle, when there was one.
    ///
    /// @details  The members, not "there is a cycle". The spec asks for it, and
    ///            the reason is practical: with twenty plugins, "there is a
    ///            cycle" sends the integrator searching a graph of twenty nodes.
    std::vector< std::string >    CycleMembers;

    /// @brief  Dependencies nobody provides, with who asked for them.
    std::vector< std::string >    Missing;

    /// @brief  One per plugin, in the order they were handled.
    std::vector< SPluginReport >    Plugins;
};

Report of a whole load.

class

CPluginRegistry

Ethereal::Plugin#

Discovers, sorts by dependency, loads and serves interfaces.

class CPluginRegistry final

Movable, not copyable.

constructor

CPluginRegistry

#
CPluginRegistry();

Constructor. Nothing scanned or loaded.

constructor

CPluginRegistry

#
CPluginRegistry( CPluginRegistry && Other ) noexcept;

Move constructor.

operator

operator=

#
CPluginRegistry & operator = ( CPluginRegistry && Other ) noexcept;

Move assignment. Unloads the current plugins first.

function

Scan

#
ERegistryError Scan( const std::string & sDirectory, const SScanOptions & Options = SScanOptions(), std::size_t * pFound = nullptr );

Looks at the folder. Loads nothing.

Accumulates: scanning two folders leaves both lists together. A repeated path does not go in twice.

sDirectory
Folder to scan.
Options
Scan options.
pFound
Receives the number of candidates kept. May be null.
ERegistryError::eNone, or what prevented the scan.
function

Scanned

#
const std::vector< SScanEntry > & Scanned() const noexcept;

What the scan found.

function

ClearScan

#
void ClearScan() noexcept;

Forgets what was scanned. Does not touch what is already loaded.

function

LoadAll

#
ERegistryError LoadAll( SLoadReport * pReport = nullptr );

Loads everything the scan found, in dependency order.

A cycle loads nothing. Starting "the ones that can" would leave a set that depends on things that are not there, and the failure would show up at the first call instead of here.

One failure does not stop the others. A plugin whose Init returns an error stays in EPluginState::eFailed, and the host goes on, which is the isolation the spec asks for. The report says which one, and why.

pReport
Optional. Receives the report.
ERegistryError::eNone, ERegistryError::ePartial, or what prevented the load.
function

UnloadAll

#
void UnloadAll() noexcept;

Unloads everything, in the reverse order of the load.

A plugin depends on the ones started before it. Unloading the first before the last would leave the last pointing to code that already left memory.

function

Count

#
std::size_t Count() const noexcept;

Number of loaded plugins.

function

Query

#
void * Query( const std::string & sInterfaceName, const ETL_UINT32 uVersion ) const;

Asks for an interface from whichever plugin offers it.

This is the query the spec asks for. The difference from the previous one is not convenience: with the plugin name as an argument, whoever wants a renderer must know which plugin offers it, and then plugins stop being replaceable, which was the reason they exist.

The search uses the pProvidedInterfaces list each manifest declares, which nobody read until now.

Cache the pointer. This is for link time, never a hot path: the caller keeps what it gets.

sInterfaceName
Interface name.
uVersion
Interface version.
The interface, or null.
function

QueryFrom

#
void * QueryFrom( const std::string & sPluginName, const std::string & sInterfaceName, const ETL_UINT32 uVersion ) const;

Same as Query, but only in one plugin.

sPluginName
Plugin name.
sInterfaceName
Interface name.
uVersion
Interface version.
The interface, or null.
alias

bool

#
using FVisitPlugin = bool ( * )( const std::string & sName, const EPluginState eState, void * pUser );

Called for each plugin. Returning false stops the walk.

function

EnumPlugins

#
std::size_t EnumPlugins( FVisitPlugin pVisit, void * pUser ) const;

Walks the plugins.

A function pointer with user data, not a returned vector: returning a vector of strings allocates once per name, and a caller looking for one pays for all.

pVisit
Called for each plugin.
pUser
Passed to pVisit.
Number of plugins visited.
function

StateOf

#
EPluginState StateOf( const std::string & sName ) const;

State of a plugin by name.

function

LastReport

#
const SLoadReport & LastReport() const noexcept;

Report of the last LoadAll.

reload.hpp

#include <ethereal/cpp/plugin/reload.hpp>

Reloads a plugin without stopping the host.

The spec describes the sequence like this: "Reload(sName) performs: stop, drain, swap, start, with the new module loaded from a temporary copy so the original file can be replaced on Windows (where a loaded DLL is locked)."

The order this code follows differs from that list. Written exactly, the list has a problem: draining before the swap is useless. The drain waits for the readers of the current table. If the swap has not happened yet, new readers keep arriving at the old table while it waits. The drain only closes after the swap. The real sequence is: 1. export the state of the old one. 2. copy the file, load the copy, resolve symbols, 'Init', import the state. All of this is preparation: if it fails, it is aborted and the old one keeps serving as if nothing happened. 3. 'Stop' on the old one. 4. 'Start' on the new one, ready but not yet published. 5. the swap: one atomic write, the only moment anything changes for callers. 6. the drain: wait for whoever entered the old table before the swap. 7. 'Shutdown' on the old one, unload, delete the old copy. 8. free the state block.

The window that remains: between 3 and 5, a caller still sees the old table, and the old plugin has already received 'Stop'. It cannot be closed without both running at the same time, which breaks any plugin holding an exclusive resource. The choice is between a short "stopped but still visible" window and a "two owners of the same resource" one, and this is the less destructive of the two.

Why a temporary copy, and why in the same folder. On Windows a loaded DLL is locked: nobody replaces it while it is mapped. Always loading from a copy keeps the original unlocked, so it can be replaced by a new version at any time, which is what makes hot reload exist. The copy stays in the folder of the original, not in a temp folder. A library usually depends on others next to it, and changing folders changes how those dependencies resolve. The reload would then fail for a reason that has nothing to do with the reload.

enum

EReloadError

Ethereal::Plugin#
C++
enum class   EReloadError : ETL_UINT8
{
    /// @brief  Reloaded.
    eNone = 0,

    /// @brief  Nothing is loaded to reload.
    eNotLoaded,

    /// @brief  The copy could not be made.
    eCopyFailed,

    /// @brief  The system refused to load the copy.
    eLoadFailed,

    /// @brief  The copy does not export what a plugin must export.
    eMissingSymbols,

    /// @brief  The copy did not pass the image verification.
    eVerifyRefused,

    /// @brief  @c Init of the copy returned an error.
    ///
    /// @details  'Shutdown' is then not called on it, and it is unloaded. The
    ///            old plugin keeps serving.
    eInitFailed,

    /// @brief  @c ImportState returned an error.
    eImportFailed,

    /// @brief  @c Start of the copy returned an error.
    eStartFailed,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///             has ended, or the license passed was refused (see
    ///             Bundle::UnlockBundle).
    eNotLicensed
};

What can go wrong in a reload.

function

ReloadErrorName

Ethereal::Plugin#
const ETL_CHAR * ReloadErrorName( EReloadError eError ) noexcept;

Name of the error, for messages. Never returns null.

function

ResolveEntries

Ethereal::Plugin#
bool ResolveEntries( void * pNativeHandle, SPluginEntries * pOut ) noexcept;

Resolves the symbols of a plugin into the flat table.

Required: Init, Start, Stop, Shutdown. Optional: Query, ExportState, ImportState.

Everything is resolved here, at load. Resolving at the first call would put a question per call on the hot path, plus a concurrency question that does not need to exist.

pNativeHandle
What LoadLibraryEx returned.
pOut
Receives the table.
true when all required symbols are present.
struct

SReloadOptions

Ethereal::Plugin#
C++
struct   SReloadOptions   final
{
    /// @brief  'sizeof( SReloadOptions )'.
    ETL_UINT32                iStructSize = sizeof( SReloadOptions );

    /// @brief  Busy wait rounds of the drain. Zero uses the default.
    ETL_UINT32                uSpinLimit = 0;

    /// @brief  Context handed to @c Init. Null passes a minimal context.
    const ETLC_PluginContext *    pContext = nullptr;
};

What a load or reload needs to know.

struct

SReloadReport

Ethereal::Plugin#
C++
struct   SReloadReport   final
{
    /// @brief  'sizeof( SReloadReport )'.
    ETL_UINT32        iStructSize = sizeof( SReloadReport );

    /// @brief  Number of readers the drain had to wait for.
    ETL_UINT32        uDrained = 0;

    /// @brief  Bytes of state passed from one copy to the other.
    ETL_UINT64        uStateBytes = 0;

    /// @brief  Generation after this reload. Starts at 1 on the first load.
    ETL_UINT32        uGeneration = 0;

    /// @brief  A temporary copy that could not be deleted.
    ///
    /// @details  On Windows this happens when something still holds the file.
    ///            It is no reason for the reload to fail, since it already
    ///            happened, but it is garbage on disk and it is reported instead
    ///            of hidden.
    bool            bTempLeaked = false;

    /// @brief  Explicit padding.
    ETL_UINT8        aPad[ 3 ] = {};
};

What the reload found.

class

CHotPlugin

Ethereal::Plugin#

A live plugin, reloaded under its callers.

class CHotPlugin final

Owns the original path, the copy in use, the system handle, the flat tables and the atomic table that is swapped.

No ETL_CLASS_ALIGN: the members aligned to the cache line already give 64, and a smaller alignment was ignored (C4359).

constructor

CHotPlugin

#
CHotPlugin() noexcept;

Constructor. Nothing loaded.

function

Load

#
EReloadError Load( const std::string & sPath, const SReloadOptions & Options, SReloadReport * pReport ) noexcept;

Loads for the first time, from a copy.

sPath
Path of the original library.
Options
Load options.
pReport
Optional. Receives the report.
EReloadError::eNone, or what prevented the load.
function

Reload

#
EReloadError Reload( const SReloadOptions & Options, SReloadReport * pReport ) noexcept;

Reloads from the original file, which may have changed meanwhile.

See the whole sequence in the file header. When it fails during the preparation, what was loaded keeps serving and nothing changes for callers.

Options
Reload options.
pReport
Optional. Receives the report.
EReloadError::eNone, or what prevented the reload.
function

Unload

#
void Unload( ETL_UINT32 uSpinLimit = 0u ) noexcept;

Stops, drains, destroys and unloads.

uSpinLimit
Busy wait rounds of the drain. Zero uses the default.
function

Table

#
CHotTable & Table() noexcept

The table that is swapped. Callers enter through it.

function

Path

#
const std::string & Path() const noexcept

Path of the original file.

function

Generation

#
ETL_UINT32 Generation() const noexcept

Number of loads so far. The first load is generation 1.

function

IsLoaded

#
bool IsLoaded() const noexcept

true when something is loaded.

function

LeakedCopies

#
ETL_UINT32 LeakedCopies() const noexcept

Number of temporary copies left undeleted, since the start.

verification.hpp

#include <ethereal/cpp/plugin/verification.hpp>

Checks the image before loading it.

The spec asks for three things, all optional except the last: "Optional signature verification before load, through an injected IImageVerifier seam (Platform provides an implementation). The Plugin module does not link Platform." "Optional hash allowlist." "Refusal to load from a world-writable directory, on by default on POSIX."

Why a seam and not a call into Platform. The spec says this module does not link Platform, and the reason is not tidiness. A library consumer may want plugins without the system signature reading, and whoever wants signatures may have a policy that is not the system's (an own root, a list of signers, a cutoff date). So only the question lives here. The answer comes from outside.

Why this does not return a verdict on its own. Platform already has 'QuerySignature', written on purpose to return facts and not a verdict: who signed, when, with which algorithm, and whether the chain closes. It does not check revocation, and it says so. The decision to trust belongs to the integrator, and this seam is where it comes in.

enum

EVerifyResult

Ethereal::Plugin#
C++
enum class   EVerifyResult : ETL_UINT8
{
    /// @brief  Passed the verifier policy.
    eOk = 0,

    /// @brief  Has no signature at all.
    eNotSigned,

    /// @brief  Has a signature, and it does not match the content.
    eBadSignature,

    /// @brief  The signature matches, and the signer is not in the policy.
    eUntrustedSigner,

    /// @brief  The verifier cannot answer here.
    ///
    /// @details  Neither "passed" nor "failed". It is the case of a platform
    ///            where the question has no answer, and treating it as approval
    ///            would turn the lack of a mechanism into permission.
    eUnavailable
};

What an image verifier has to say about it.

function

VerifyResultName

Ethereal::Plugin#
const ETL_CHAR * VerifyResultName( EVerifyResult eResult ) noexcept;

Name of the verdict, for messages. Never returns null.

class

IImageVerifier

Ethereal::Plugin#

The signature seam. The answer comes from outside the module.

class IImageVerifier

See the file header. The Plugin module does not link Platform. Whoever wants signatures implements this and injects it.

destructor

~IImageVerifier

#
virtual ~IImageVerifier() = default;

Virtual destructor.

function

VerifyImage

#
virtual EVerifyResult VerifyImage( const std::string & sPath ) noexcept = 0;

Tells whether this file passes the signature policy.

Must not throw. It is called from inside a load that promises not to throw, and an exception here would break that promise.

sPath
Path of the file, in UTF-8.
The verdict. EVerifyResult::eUnavailable when unknown.
enum

EDirectoryTrust

Ethereal::Plugin#
C++
enum class   EDirectoryTrust : ETL_UINT8
{
    /// @brief  Only the owner or the group can write, or the sticky bit protects.
    eRestricted = 0,

    /// @brief  Anyone can write here, so anyone can replace the file.
    eWorldWritable,

    /// @brief  Could not be found out.
    ///
    /// @details  Again, this is not "fine". It is "unknown", and the policy of
    ///            the loader decides.
    eUnknown
};

What was found about who can write to the folder.

function

DirectoryTrustName

Ethereal::Plugin#
const ETL_CHAR * DirectoryTrustName( EDirectoryTrust eTrust ) noexcept;

Name of the state, for messages. Never returns null.

function

QueryDirectoryTrust

Ethereal::Plugin#
EDirectoryTrust QueryDirectoryTrust( const std::string & sPath ) noexcept;

Who can write to the folder that holds this file.

Measures the folder, not the file, on purpose: a read only file in a world writable folder can be deleted and recreated by anyone. The file permissions do not protect against that. The folder permissions do.

sPath
Path of a file. Its folder is what gets measured.
The trust of the folder.
function

HashFileSha256

Ethereal::Plugin#
bool HashFileSha256( const std::string & sPath, std::string & sOut ) noexcept;

SHA-256 digest of a file, in lowercase hexadecimal.

Reads the whole file into memory. The SHA256 of this library is single pass, with no update and finalize, so there is no way to hash in chunks. For a plugin (tens or hundreds of KiB) this is cheap. For a large file it would not be, and the right fix would be adding streaming to the cryptography module, not working around it here.

sPath
Path of the file.
sOut
Receives 64 characters. Left empty when the file could not be read.
true when the file was read and hashed.
struct

SVerifyPolicy

Ethereal::Plugin#
C++
struct   SVerifyPolicy   final
{
    /// @brief  'sizeof( SVerifyPolicy )'.
    ETL_UINT32            iStructSize = sizeof( SVerifyPolicy );

    /// @brief  Refuses to load from a world writable folder.
    ///
    /// @details  On by default on POSIX, as the spec requires. On Windows the
    ///            measurement is different and the default is off. See the
    ///            implementation file for exactly what is measured there.
    #if defined( ETL_PLATFORM_WINDOWS )
        bool            bRefuseWorldWritable = false;
    #else /// POSIX
        bool            bRefuseWorldWritable = true;
    #endif

    /// @brief  Treats "unknown" as a refusal.
    ///
    /// @details  Off by default: on a platform where the question has no answer,
    ///            turning this on would refuse everything.
    bool                bRefuseUnknown = false;

    /// @brief  Explicit padding.
    ETL_UINT8            aPad[ 2 ] = {};

    /// @brief  Who answers for the signature. Null checks no signature.
    IImageVerifier *    pVerifier = nullptr;

    /// @brief  Allowed digests, in lowercase hexadecimal. Empty checks nothing.
    ///
    /// @details  An empty list is not a list that refuses everything. It means
    ///            "there is no list", the common case. A list with one item means
    ///            "only this one".
    std::vector< std::string >    AllowedHashes;
};

Verification policy of a load.

enum

EVerifyRefusal

Ethereal::Plugin#
C++
enum class   EVerifyRefusal : ETL_UINT8
{
    /// @brief  Did not refuse.
    eNone = 0,

    /// @brief  The folder is world writable.
    eWorldWritable,

    /// @brief  Who writes to the folder is unknown, and the policy requires knowing.
    eTrustUnknown,

    /// @brief  The file could not be read to hash it.
    eUnreadable,

    /// @brief  The digest is not in the list.
    eHashNotAllowed,

    /// @brief  The signature verifier said no.
    eSignature
};

Why the verification refused.

function

VerifyRefusalName

Ethereal::Plugin#
const ETL_CHAR * VerifyRefusalName( EVerifyRefusal eRefusal ) noexcept;

Name of the reason, for messages. Never returns null.

struct

SVerifyReport

Ethereal::Plugin#
C++
struct   SVerifyReport   final
{
    /// @brief  'sizeof( SVerifyReport )'.
    ETL_UINT32        iStructSize = sizeof( SVerifyReport );

    /// @brief  Explicit padding.
    ETL_UINT32        uPadding = 0;

    /// @brief  Reason of the refusal, or @ref EVerifyRefusal::eNone.
    EVerifyRefusal    eRefusal = EVerifyRefusal::eNone;

    /// @brief  What was found about the folder.
    EDirectoryTrust    eTrust = EDirectoryTrust::eUnknown;

    /// @brief  What the signature verifier said. @c eUnavailable when there was none.
    EVerifyResult    eSignature = EVerifyResult::eUnavailable;

    /// @brief  Explicit padding.
    ETL_UINT8        aPad = 0;

    /// @brief  Digest of the file, when computed. Empty when not.
    std::string        sHash;
};

What the verification found.

function

VerifyBeforeLoad

Ethereal::Plugin#
bool VerifyBeforeLoad( const std::string & sPath, const SVerifyPolicy & Policy, SVerifyReport * pReport ) noexcept;

Applies the policy to a file, before loading it.

The order of the checks is deliberate: first the folder, then the digest, then the signature. From the cheapest to the most expensive, and from the coarsest to the finest. There is no point reading a whole file to hash it if it sits where anyone can replace it.

sPath
Path of the file.
Policy
The policy.
pReport
Receives what was found. May be null.
true when the policy allows the load.