Skip to content

Plugin CPP23 API

github-actions[bot] edited this page Dec 4, 2026 · 1 revision

GridLock C++23 Plugin & Host Extension Guide

C++23 plugins compile directly against the pure-C99 headers in include/gridlock/plugin_api.h using extern "C" entry-point linkage (GRIDLOCK_PLUGIN_EXPORT), letting you use modern C++23 (std::expected, std::span, std::string_view, RAII) internally while maintaining a zero-Qt, compiler-independent C99 ABI v2.0 boundary.


1. ABI & Exception Firewall Rules

  1. Never unwind C++ exceptions across C ABI frames: Every callback passed to GridLock (gridlock_plugin_init, shutdown, command callbacks, autocmds, type visualizers, variable actions, canvas click/key handlers) must catch all exceptions (try { ... } catch (...) { return GRIDLOCK_ERR_UNSUPPORTED; }) and be marked noexcept.
  2. Keep gridlock_plugin_init in extern "C": include/gridlock/plugin_api.h wraps declarations in extern "C" { ... } under __cplusplus. Export gridlock_plugin_init with GRIDLOCK_PLUGIN_EXPORT and hide internal symbols via -fvisibility=hidden -fvisibility-inlines-hidden plus a plugin.map linker version script (see C99 ABI v2.0 Reference).
  3. Deterministic RAII State Ownership: Store plugin state in a struct owned via std::unique_ptr (released into out_desc->plugin_ctx on success and deleted inside shutdown) or allocate tracked host buffers via host->core->alloc_bytes wrapped in a custom RAII deleter that runs before shutdown() returns.

2. RAII & std::expected / std::span Helpers

Wrap C99 sub-table calls in lightweight noexcept helpers so domain code remains expressive and leak-free without any external wrapper header:

#include <gridlock/plugin_api.h>

#include <cstddef>
#include <cstdint>
#include <expected>
#include <memory>
#include <span>
#include <string>
#include <string_view>
#include <vector>

namespace my_plugin {

// RAII handle for host-tracked allocations (must be destroyed before shutdown returns).
struct HostDeleter {
  const gridlock_host_api_t* host = nullptr;
  void operator()(std::byte* ptr) const noexcept {
    if (ptr && host && host->core && host->core->free_bytes) {
      host->core->free_bytes(host->host_ctx, ptr);
    }
  }
};
using HostByteBuffer = std::unique_ptr<std::byte[], HostDeleter>;

[[nodiscard]] inline std::expected<HostByteBuffer, GridLockStatus> allocHostBytes(
    const gridlock_host_api_t* host, std::size_t numBytes) noexcept {
  if (!host || !host->core || !host->core->alloc_bytes) {
    return std::unexpected(GRIDLOCK_ERR_INVALID_ARG);
  }
  if (numBytes == 0u) return HostByteBuffer{nullptr, HostDeleter{host}};
  auto* raw = static_cast<std::byte*>(host->core->alloc_bytes(host->host_ctx, numBytes));
  if (!raw) return std::unexpected(GRIDLOCK_ERR_BUFFER_TOO_SMALL);
  return HostByteBuffer{raw, HostDeleter{host}};
}

[[nodiscard]] inline std::expected<std::string, GridLockStatus> evalExpr(
    const gridlock_host_api_t* host, int32_t rank, std::string_view expr) noexcept {
  try {
    if (!host || !host->dbg || !host->dbg->eval_expr) {
      return std::unexpected(GRIDLOCK_ERR_INVALID_ARG);
    }
    std::string exprZ(expr);
    std::string buf(256, '\0');
    size_t outLen = 0;
    GridLockStatus st = host->dbg->eval_expr(
        host->host_ctx, rank, exprZ.c_str(), buf.data(), buf.size(), &outLen);
    if (st == GRIDLOCK_ERR_BUFFER_TOO_SMALL && outLen < (16u * 1024u * 1024u)) {
      buf.resize(outLen + 1);
      st = host->dbg->eval_expr(
          host->host_ctx, rank, exprZ.c_str(), buf.data(), buf.size(), &outLen);
    }
    if (st != GRIDLOCK_OK) return std::unexpected(st);
    buf.resize(outLen);
    return buf;
  } catch (...) {
    return std::unexpected(GRIDLOCK_ERR_UNSUPPORTED);
  }
}

[[nodiscard]] inline std::expected<std::size_t, GridLockStatus> readBytes(
    const gridlock_host_api_t* host,
    int32_t rank,
    uint64_t address,
    std::span<std::byte> out) noexcept {
  if (!host || !host->dbg || !host->dbg->read_memory) {
    return std::unexpected(GRIDLOCK_ERR_INVALID_ARG);
  }
  if (out.empty()) return std::size_t{0};
  size_t got = 0;
  const GridLockStatus st = host->dbg->read_memory(
      host->host_ctx, rank, address, out.data(), out.size(), &got);
  if (st != GRIDLOCK_OK) return std::unexpected(st);
  return got;
}

}  // namespace my_plugin

3. End-to-End Walkthrough: examples/plugins/domain_mesh_probe/

examples/plugins/domain_mesh_probe/ demonstrates a production-hardened C++23 scientific FEM mesh exporter that inspects stopped MPI ranks and writes ASCII VTK snapshots without linking Qt6 or internal GridLock libraries:

sequenceDiagram
  participant USER as User (VariablesDockWidget)
  participant PHB as PluginHostBridge (host->dbg / host->ui)
  participant PLUG as domain_mesh_probe.so
  participant COORD as GdbRankCoordinator / process_vm_readv
  participant FS as 0700 Runtime Dir (O_NOFOLLOW)

  USER->>PHB: Right-click FemMesh variable -> Dump Mesh Refinement Step
  PHB->>PLUG: onDumpMeshVariableAction(ctx, host, varCtx) [noexcept firewall]
  PLUG->>PHB: evalExpr(rank, "(expr).num_vertices" / "num_elements" / "vertices")
  PHB->>COORD: Silent MI token evaluation (zero Evaluator dock pollution)
  COORD-->>PLUG: vertexCount, elementCount, verticesAddr
  PLUG->>PHB: readBytes(rank, verticesAddr, xyzCoords span [<= 65536 * 3 doubles])
  PHB->>COORD: Local process_vm_readv fast path (or 64 KiB MI chunks)
  COORD-->>PLUG: Raw IEEE-754 double vertex coordinates
  PLUG->>FS: mkdir 0700 + open(O_CREAT | O_TRUNC | O_NOFOLLOW, 0600) + write ASCII VTK
  PLUG->>PHB: host->ui->emit_structured_event("domain.mesh_probe.step", jsonPayload)
  Note over PLUG,PHB: Stores auto_probe_expr so subsequent on_rank_stopped events export step N+1
Loading

Key C++23 Engineering Patterns Illustrated

  1. ABI Version & Size Handshake: Validates host->api_version (GRIDLOCK_PLUGIN_API_VERSION = 0x00020000u), host->struct_size, and required sub-tables (host->dbg, host->ui, host->core) before registering any callbacks.
  2. Regex Variable Action (host->dbg->register_variable_action): Registers "mesh_probe.dump_refinement_step" with type_regex = ".*Mesh.*", matching any C/C++ struct or class containing Mesh in its debugger type name, and records varCtx->expression_utf8 in ctx->auto_probe_expr so subsequent on_rank_stopped events automatically emit a continuous VTK time series (mesh_step_<rank>_<step>.vtk).
  3. Bounded Memory Reads (std::expected + std::span): Caps vertex reads at kMaxProbeVertices = 65536u (1.5 MiB per step) and reads raw double coordinates directly into std::vector<double> via readBytes(...), propagating errors cleanly without throwing across C ABI frames.
  4. Symlink-Safe Private File Output: Resolves $GRIDLOCK_MESH_PROBE_DIR, $XDG_RUNTIME_DIR/gridlock/mesh_probe, or /tmp/gridlock-<uid>/mesh_probe, enforces 0700 ownership via lstat() + geteuid(), and opens VTK files with O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC (0600) followed by fstat() S_ISREG verification.
  5. RAII Teardown: Stores MeshProbeContext in std::unique_ptr during gridlock_plugin_init, transfers ownership via state.release() to out_desc->plugin_ctx only on success, and destroys it inside noexcept onShutdown.

4. Complete C++23 2D Canvas Plugin Example

#include <gridlock/plugin_api.h>

#include <array>
#include <cstdio>
#include <memory>

namespace {

struct ConvergencePlugin {
  const gridlock_host_api_t* host = nullptr;
  gridlock_panel_id_t panelId = GRIDLOCK_INVALID_PANEL_ID;
};

void GRIDLOCK_CALL onCanvasClick(void* ud,
                                 gridlock_panel_id_t /*panelId*/,
                                 float x, float y,
                                 int32_t /*row*/, int32_t /*col*/,
                                 int32_t button) noexcept {
  try {
    auto* self = static_cast<ConvergencePlugin*>(ud);
    if (!self || !self->host || !self->host->core) return;
    char buf[96]{};
    std::snprintf(buf, sizeof(buf), "Clicked (%.1f, %.1f) btn=%d", x, y, button);
    self->host->core->log_message(self->host->host_ctx, GRIDLOCK_LOG_INFO, buf);
  } catch (...) {
  }
}

void GRIDLOCK_CALL onShutdown(void* pluginCtx, const gridlock_host_api_t* /*host*/) noexcept {
  delete static_cast<ConvergencePlugin*>(pluginCtx);
}

}  // namespace

extern "C" GRIDLOCK_PLUGIN_EXPORT GridLockStatus GRIDLOCK_CALL gridlock_plugin_init(
    const gridlock_host_api_t* host,
    gridlock_plugin_descriptor_t* out_desc) {
  try {
    if (!host || !out_desc ||
        GRIDLOCK_API_VERSION_MAJOR(host->api_version) != GRIDLOCK_PLUGIN_ABI_MAJOR ||
        host->struct_size < static_cast<uint32_t>(sizeof(gridlock_host_api_t))) {
      return GRIDLOCK_ERR_ABI_MISMATCH;
    }
    auto state = std::make_unique<ConvergencePlugin>();
    state->host = host;

    if (host->ui && host->ui->create_panel) {
      gridlock_panel_desc_t pdesc{};
      pdesc.struct_size = static_cast<uint32_t>(sizeof(pdesc));
      pdesc.panel_key_utf8 = "cpp23.convergence";
      pdesc.title_utf8 = "Residual Convergence (C++23)";
      pdesc.kind = GRIDLOCK_PANEL_CANVAS;
      pdesc.dock_area = GRIDLOCK_PANEL_DOCK_BOTTOM;
      if (host->ui->create_panel(host->host_ctx, &pdesc, &state->panelId) == GRIDLOCK_OK) {
        std::array<gridlock_draw_cmd_t, 2> cmds{};
        cmds[0].struct_size = sizeof(gridlock_draw_cmd_t);
        cmds[0].op = GRIDLOCK_DRAW_CLEAR;
        cmds[0].rgba_fill = 0x1E1E2EFFu;
        cmds[1].struct_size = sizeof(gridlock_draw_cmd_t);
        cmds[1].op = GRIDLOCK_DRAW_RECT;
        cmds[1].x = 10.0f; cmds[1].y = 10.0f; cmds[1].w = 180.0f; cmds[1].h = 40.0f;
        cmds[1].rgba_fill = 0x89B4FAFFu;
        host->ui->canvas_submit_commands(host->host_ctx, state->panelId, cmds.data(), 2u);
        host->ui->canvas_set_click_handler(host->host_ctx, state->panelId, &onCanvasClick, state.get());
      }
    }

    out_desc->api_version = GRIDLOCK_PLUGIN_API_VERSION;
    out_desc->struct_size = static_cast<uint32_t>(sizeof(*out_desc));
    out_desc->reserved_flags = 0u;
    out_desc->plugin_id_utf8 = "org.example.convergence_cpp23";
    out_desc->plugin_name_utf8 = "Convergence Plotter (C++23)";
    out_desc->plugin_version_utf8 = "1.0.0";
    out_desc->description_utf8 = "C++23 ABI v2.0 canvas plugin";
    out_desc->plugin_ctx = state.release();
    out_desc->shutdown = &onShutdown;
    return GRIDLOCK_OK;
  } catch (...) {
    return GRIDLOCK_ERR_UNSUPPORTED;
  }
}

5. Build Recipes (Meson, CMake & Make with plugin.map)

Include plugin.map (see C99 ABI v2.0 Reference) so C++ inline/template statics never emit STB_GNU_UNIQUE symbols that prevent live hot-reloading.

Meson (meson.build + meson_options.txt)

# meson_options.txt
option('gridlock_include_dir', type: 'string', value: '/usr/local/include',
       description: 'Path containing gridlock/plugin_api.h')
# meson.build
project('convergence_cpp23', 'cpp',
  version: '1.0.0',
  default_options: ['cpp_std=c++23', 'warning_level=3'])

inc = include_directories(get_option('gridlock_include_dir'))
map_file = meson.current_source_dir() / 'plugin.map'

shared_module('convergence_cpp23',
  'convergence.cpp',
  include_directories: inc,
  cpp_args: ['-fvisibility-inlines-hidden'],
  gnu_symbol_visibility: 'hidden',
  link_args: host_machine.system() == 'linux' ? ['-Wl,--version-script=' + map_file] : [],
  name_prefix: 'lib')

CMake (CMakeLists.txt)

cmake_minimum_required(VERSION 3.24)
project(convergence_cpp23 LANGUAGES CXX)

set(GRIDLOCK_INCLUDE_DIR "/usr/local/include" CACHE PATH "Path to gridlock/plugin_api.h")

add_library(convergence_cpp23 MODULE convergence.cpp)
target_compile_features(convergence_cpp23 PRIVATE cxx_std_23)
target_include_directories(convergence_cpp23 PRIVATE "${GRIDLOCK_INCLUDE_DIR}")
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
  target_link_options(convergence_cpp23 PRIVATE
    "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/plugin.map")
endif()
set_target_properties(convergence_cpp23 PROPERTIES
  CXX_VISIBILITY_PRESET hidden
  VISIBILITY_INLINES_HIDDEN ON
  PREFIX "lib")

Verify headlessly after building:

QT_QPA_PLATFORM=offscreen ./builddir/gridlock --verify-plugin ./build/libconvergence_cpp23.so

Clone this wiki locally