From 9f76cb20c4926680184957cc9f53538ccf6f8f46 Mon Sep 17 00:00:00 2001 From: Storm Dragon Date: Wed, 2 Dec 2026 00:38:23 -0500 Subject: [PATCH] Gracefully handle missing libvterm in the console. --- README.md | 7 +- internal/terminal/emulator_linux.go | 19 ++++- internal/terminal/native.c | 106 +++++++++++++++++++++----- internal/terminal/native.h | 5 ++ internal/terminal/paste_linux.go | 8 +- internal/terminal/session_linux.go | 7 +- internal/terminal/vterm_linux_test.go | 94 +++++++++++++++++++++++ 7 files changed, 216 insertions(+), 30 deletions(-) create mode 100644 internal/terminal/vterm_linux_test.go diff --git a/README.md b/README.md index d380b2b1..a5b4e374 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,9 @@ Build requirements: - Linux. The build script obtains the Go version required by [go.mod](go.mod) if a suitable version is not installed. - A C compiler and `pkg-config`. -- Development headers and libraries for libevdev, X11, libvterm, and ALSA. - Their pkg-config names are `libevdev`, `x11`, `vterm`, and `alsa`. +- Development headers and libraries for libevdev, X11, and ALSA. + Their pkg-config names are `libevdev`, `x11`, and `alsa`. +- libvterm development headers (`vterm.h`). Runtime requirements depend on the features you use: @@ -39,6 +40,8 @@ Runtime requirements depend on the features you use: - PulseAudio or PipeWire's PulseAudio service for the default sound driver; ALSA output is also available. - Enchant 2 and a dictionary for your language for spell checking. +- libvterm (`libvterm.so.0`) for X11 terminal mode (`-x`). Console mode does + not load or require it. Its development headers are still needed to build. - `xclip` for X clipboard synchronization. - libusb 1.0 for native DECtalk USB speech, or access to the configured serial device for a serial synthesizer. diff --git a/internal/terminal/emulator_linux.go b/internal/terminal/emulator_linux.go index 9db0b160..2e9fbac2 100644 --- a/internal/terminal/emulator_linux.go +++ b/internal/terminal/emulator_linux.go @@ -36,10 +36,23 @@ type Emulator struct { rows, cols int } +func loadVTerm() error { + switch C.terminal_vterm_load() { + case 1: + return fmt.Errorf("X11 terminal mode (-x) requires libvterm.so.0; the library could not be loaded") + case 2: + return fmt.Errorf("X11 terminal mode (-x) requires a compatible libvterm.so.0; required symbols are missing") + } + return nil +} + func newEmulator(rows, cols int) (*Emulator, error) { if !validSize(rows, cols) { return nil, fmt.Errorf("unsupported terminal geometry %dx%d", cols, rows) } + if err := loadVTerm(); err != nil { + return nil, err + } vt := C.terminal_vterm(C.int(rows), C.int(cols)) if vt == nil { return nil, fmt.Errorf("allocate terminal emulator") @@ -53,15 +66,15 @@ func (e *Emulator) feed(bytes []byte) { if len(bytes) == 0 { return } - C.vterm_input_write(e.native, (*C.char)(unsafe.Pointer(&bytes[0])), C.size_t(len(bytes))) + C.terminal_vterm_input(e.native, (*C.char)(unsafe.Pointer(&bytes[0])), C.size_t(len(bytes))) // The outer terminal answers queries. Discard duplicate emulator replies. var discard [4096]byte - for C.vterm_output_read(e.native, (*C.char)(unsafe.Pointer(&discard[0])), C.size_t(len(discard))) > 0 { + for C.terminal_vterm_output(e.native, (*C.char)(unsafe.Pointer(&discard[0])), C.size_t(len(discard))) > 0 { } } func (e *Emulator) resize(rows, cols int) { - C.vterm_set_size(e.native, C.int(rows), C.int(cols)) + C.terminal_vterm_resize(e.native, C.int(rows), C.int(cols)) e.rows, e.cols = rows, cols } diff --git a/internal/terminal/native.c b/internal/terminal/native.c index f83d7457..e8a488f9 100644 --- a/internal/terminal/native.c +++ b/internal/terminal/native.c @@ -4,12 +4,15 @@ #include #include #include +#include #include #include #include #include #include +#include #include +#include #include #include #include @@ -69,6 +72,71 @@ int terminal_wait(int master, int input, int output, int xfd, int wake, int writ (fds[1].revents || fds[2].revents || (fds[0].revents & POLLOUT) ? 4 : 0); } +// Keep libvterm out of DT_NEEDED: console mode never calls this loader. +// Derive symbol types from the build headers rather than copying the ABI. +#define VTERM_SYMBOLS(X) \ + X(vterm_free) \ + X(vterm_get_size) \ + X(vterm_input_write) \ + X(vterm_keyboard_end_paste) \ + X(vterm_keyboard_key) \ + X(vterm_keyboard_start_paste) \ + X(vterm_new) \ + X(vterm_obtain_screen) \ + X(vterm_obtain_state) \ + X(vterm_output_read) \ + X(vterm_screen_convert_color_to_rgb) \ + X(vterm_screen_enable_altscreen) \ + X(vterm_screen_flush_damage) \ + X(vterm_screen_get_cbdata) \ + X(vterm_screen_get_cell) \ + X(vterm_screen_reset) \ + X(vterm_screen_set_callbacks) \ + X(vterm_set_size) \ + X(vterm_set_utf8) \ + X(vterm_state_get_cursorpos) + +static struct VTermAPI { +#define DECLARE(symbol) __typeof__(&symbol) symbol; + VTERM_SYMBOLS(DECLARE) +#undef DECLARE +} vtermApi; +static pthread_once_t vtermOnce = PTHREAD_ONCE_INIT; +static int vtermStatus = 1; + +static void load_vterm(void) { + void *library = dlopen("libvterm.so.0", RTLD_NOW | RTLD_LOCAL); + if (!library) return; + struct VTermAPI loaded; +#define LOAD(symbol) \ + loaded.symbol = dlsym(library, #symbol); \ + if (!loaded.symbol) { vtermStatus = 2; dlclose(library); return; } + VTERM_SYMBOLS(LOAD) +#undef LOAD + vtermApi = loaded; + vtermStatus = 0; + // Retain the handle for the process lifetime so every emulator can use it. +} +#undef VTERM_SYMBOLS + +int terminal_vterm_load(void) { + pthread_once(&vtermOnce, load_vterm); + return vtermStatus; +} +void terminal_vterm_input(VTerm *vt, const char *bytes, size_t size) { + vtermApi.vterm_input_write(vt, bytes, size); +} +size_t terminal_vterm_output(VTerm *vt, char *bytes, size_t size) { + return vtermApi.vterm_output_read(vt, bytes, size); +} +void terminal_vterm_resize(VTerm *vt, int rows, int cols) { + vtermApi.vterm_set_size(vt, rows, cols); +} +void terminal_vterm_paste(VTerm *vt, int start) { + if (start) vtermApi.vterm_keyboard_start_paste(vt); + else vtermApi.vterm_keyboard_end_paste(vt); +} + static int terminal_property(VTermProp prop, VTermValue *value, void *user) { (void)value; if (prop == VTERM_PROP_ALTSCREEN) (*(uint64_t *)user)++; @@ -76,23 +144,23 @@ static int terminal_property(VTermProp prop, VTermValue *value, void *user) { } static const VTermScreenCallbacks screen_callbacks = {.settermprop=terminal_property}; VTerm *terminal_vterm(int rows, int cols) { - VTerm *vt = vterm_new(rows, cols); + VTerm *vt = vtermApi.vterm_new(rows, cols); if (!vt) return NULL; - vterm_set_utf8(vt, 1); - VTermScreen *screen = vterm_obtain_screen(vt); - vterm_screen_enable_altscreen(screen, 1); - vterm_screen_reset(screen, 1); + vtermApi.vterm_set_utf8(vt, 1); + VTermScreen *screen = vtermApi.vterm_obtain_screen(vt); + vtermApi.vterm_screen_enable_altscreen(screen, 1); + vtermApi.vterm_screen_reset(screen, 1); uint64_t *generation = calloc(1, sizeof(*generation)); - if (!generation) { vterm_free(vt); return NULL; } - vterm_screen_set_callbacks(screen, &screen_callbacks, generation); + if (!generation) { vtermApi.vterm_free(vt); return NULL; } + vtermApi.vterm_screen_set_callbacks(screen, &screen_callbacks, generation); return vt; } void terminal_vterm_free(VTerm *vt) { - free(vterm_screen_get_cbdata(vterm_obtain_screen(vt))); - vterm_free(vt); + free(vtermApi.vterm_screen_get_cbdata(vtermApi.vterm_obtain_screen(vt))); + vtermApi.vterm_free(vt); } uint64_t terminal_generation(VTerm *vt) { - return *(uint64_t *)vterm_screen_get_cbdata(vterm_obtain_screen(vt)); + return *(uint64_t *)vtermApi.vterm_screen_get_cbdata(vtermApi.vterm_obtain_screen(vt)); } static uint32_t cell_color(VTermScreen *screen, VTermColor color) { uint32_t defaults = color.type & (VTERM_COLOR_DEFAULT_FG | VTERM_COLOR_DEFAULT_BG); @@ -100,18 +168,18 @@ static uint32_t cell_color(VTermScreen *screen, VTermColor color) { // than guessing a named color from its current RGB value. if (defaults) return UINT32_C(1) << 31; if (VTERM_COLOR_IS_INDEXED(&color)) return (UINT32_C(1) << 30) | color.indexed.idx; - vterm_screen_convert_color_to_rgb(screen, &color); + vtermApi.vterm_screen_convert_color_to_rgb(screen, &color); return (color.rgb.red << 16) | (color.rgb.green << 8) | color.rgb.blue; } void terminal_cells(VTerm *vt, uint32_t *cells, TerminalAttribute *attributes, int count, int *x, int *y) { int rows, cols; - vterm_get_size(vt, &rows, &cols); - VTermScreen *screen = vterm_obtain_screen(vt); - vterm_screen_flush_damage(screen); + vtermApi.vterm_get_size(vt, &rows, &cols); + VTermScreen *screen = vtermApi.vterm_obtain_screen(vt); + vtermApi.vterm_screen_flush_damage(screen); for (int i = 0; i < count && i < rows * cols; i++) { VTermScreenCell cell; memset(&cell, 0, sizeof(cell)); - vterm_screen_get_cell(screen, (VTermPos){.row=i/cols, .col=i%cols}, &cell); + vtermApi.vterm_screen_get_cell(screen, (VTermPos){.row=i/cols, .col=i%cols}, &cell); // A wide glyph's continuation occupies one cell, without repeating it. cells[i] = cell.chars[0] && cell.chars[0] != (uint32_t)-1 ? cell.chars[0] : ' '; attributes[i] = (TerminalAttribute){ @@ -123,7 +191,7 @@ void terminal_cells(VTerm *vt, uint32_t *cells, TerminalAttribute *attributes, i }; } VTermPos cursor; - vterm_state_get_cursorpos(vterm_obtain_state(vt), &cursor); + vtermApi.vterm_state_get_cursorpos(vtermApi.vterm_obtain_state(vt), &cursor); *x = cursor.col; *y = cursor.row; } @@ -161,14 +229,14 @@ int terminal_key(VTerm *vt, const TerminalEvent *event, char *bytes, int size) { } // Output queries are answered by the outer terminal. Never send a second // response from the reading emulator to the child. - while (vterm_output_read(vt, bytes, size)) {} + while (vtermApi.vterm_output_read(vt, bytes, size)) {} if (key != VTERM_KEY_NONE) { VTermModifier modifiers = VTERM_MOD_NONE; if (event->state & ShiftMask) modifiers |= VTERM_MOD_SHIFT; if (event->state & ControlMask) modifiers |= VTERM_MOD_CTRL; if (event->state & Mod1Mask) modifiers |= VTERM_MOD_ALT; - vterm_keyboard_key(vt, key, modifiers); - return vterm_output_read(vt, bytes, size); + vtermApi.vterm_keyboard_key(vt, key, modifiers); + return vtermApi.vterm_output_read(vt, bytes, size); } int length = event->length < size ? event->length : size; memcpy(bytes, event->text, length); diff --git a/internal/terminal/native.h b/internal/terminal/native.h index 20081f78..6d346c2f 100644 --- a/internal/terminal/native.h +++ b/internal/terminal/native.h @@ -19,8 +19,13 @@ int terminal_restore(int fd, struct termios *saved, int flags); int terminal_size(int fd, int *rows, int *cols); int terminal_resize(int fd, int rows, int cols); int terminal_wait(int master, int input, int output, int xfd, int wake, int writing, int output_pending); +int terminal_vterm_load(void); VTerm *terminal_vterm(int rows, int cols); void terminal_vterm_free(VTerm *vt); +void terminal_vterm_input(VTerm *vt, const char *bytes, size_t size); +size_t terminal_vterm_output(VTerm *vt, char *bytes, size_t size); +void terminal_vterm_resize(VTerm *vt, int rows, int cols); +void terminal_vterm_paste(VTerm *vt, int start); uint64_t terminal_generation(VTerm *vt); typedef struct { uint32_t foreground, background, style; } TerminalAttribute; void terminal_cells(VTerm *vt, uint32_t *cells, TerminalAttribute *attributes, int count, int *x, int *y); diff --git a/internal/terminal/paste_linux.go b/internal/terminal/paste_linux.go index fcc50bfb..68271c4f 100644 --- a/internal/terminal/paste_linux.go +++ b/internal/terminal/paste_linux.go @@ -49,12 +49,12 @@ func (s *Session) QueuePaste(text string) error { s.pasteStart = len(s.pending) s.pasteGeneration = uint64(C.terminal_generation(s.vt.native)) var bytes [32]byte - C.vterm_keyboard_start_paste(s.vt.native) - n := C.vterm_output_read(s.vt.native, (*C.char)(unsafe.Pointer(&bytes[0])), C.size_t(len(bytes))) + C.terminal_vterm_paste(s.vt.native, 1) + n := C.terminal_vterm_output(s.vt.native, (*C.char)(unsafe.Pointer(&bytes[0])), C.size_t(len(bytes))) s.pending = append(s.pending, bytes[:int(n)]...) s.pending = append(s.pending, text...) - C.vterm_keyboard_end_paste(s.vt.native) - n = C.vterm_output_read(s.vt.native, (*C.char)(unsafe.Pointer(&bytes[0])), C.size_t(len(bytes))) + C.terminal_vterm_paste(s.vt.native, 0) + n = C.terminal_vterm_output(s.vt.native, (*C.char)(unsafe.Pointer(&bytes[0])), C.size_t(len(bytes))) s.pending = append(s.pending, bytes[:int(n)]...) s.pasteEnd = len(s.pending) s.armWatch() diff --git a/internal/terminal/session_linux.go b/internal/terminal/session_linux.go index 85f01897..62588068 100644 --- a/internal/terminal/session_linux.go +++ b/internal/terminal/session_linux.go @@ -23,8 +23,8 @@ package terminal /* -#cgo pkg-config: x11 vterm -#cgo LDFLAGS: -lutil +#cgo pkg-config: x11 +#cgo LDFLAGS: -lutil -ldl -pthread #include "native.h" */ import "C" @@ -103,6 +103,9 @@ func validSize(rows, cols int) bool { // the launching terminal; guessing the currently focused window risks grabbing // an unrelated application. There is no console-device or privilege access. func Open(inputFile, outputFile *os.File, router input.Router) (*Session, error) { + if err := loadVTerm(); err != nil { + return nil, err + } window, err := strconv.ParseUint(os.Getenv("WINDOWID"), 0, 32) if err != nil || window == 0 { return nil, fmt.Errorf("-x requires a valid WINDOWID from the launching X11 terminal") diff --git a/internal/terminal/vterm_linux_test.go b/internal/terminal/vterm_linux_test.go new file mode 100644 index 00000000..aff99fe0 --- /dev/null +++ b/internal/terminal/vterm_linux_test.go @@ -0,0 +1,94 @@ +// Copyright (c) 2026 Storm Dragon +// SPDX-License-Identifier: GPL-3.0-or-later + +//go:build linux && cgo + +package terminal + +import ( + "debug/elf" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "git.stormux.org/storm/fenrir/internal/input" +) + +func TestVTermIsOptionalRuntimeLibrary(t *testing.T) { + path, err := os.Executable() + if err != nil { + t.Fatal(err) + } + binary, err := elf.Open(path) + if err != nil { + t.Fatal(err) + } + defer binary.Close() + libraries, err := binary.ImportedLibraries() + if err != nil { + t.Fatal(err) + } + for _, library := range libraries { + if strings.Contains(library, "libvterm") { + t.Fatalf("console startup still requires %s", library) + } + } +} + +func TestVTermUnavailable(t *testing.T) { + if want := os.Getenv("FENRIR_TEST_VTERM_ERROR"); want != "" { + // Each subprocess gets a fresh pthread_once and never touches the live + // display, terminal, keyboards or speech service. + if _, err := newEmulator(4, 20); err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("emulator error = %v, want %q", err, want) + } + if _, err := Open(nil, nil, input.Router{}); err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("X11 startup error = %v, want %q", err, want) + } + return + } + directory := t.TempDir() + compile := func(name, source string) string { + t.Helper() + path := filepath.Join(directory, name) + cmd := exec.Command("cc", "-shared", "-fPIC", "-x", "c", "-", "-o", path, "-ldl") + cmd.Stdin = strings.NewReader(source) + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("compile %s: %v\n%s", name, err, output) + } + return path + } + preload := compile("unavailable.so", ` +#define _GNU_SOURCE +#include +#include +#include +void *dlopen(const char *filename, int flags) { + void *(*realOpen)(const char *, int) = dlsym(RTLD_NEXT, "dlopen"); + if (!realOpen) return NULL; + if (filename && strcmp(filename, "libvterm.so.0") == 0) { + const char *stubPath = getenv("FENRIR_TEST_VTERM_LIBRARY"); + return stubPath && *stubPath ? realOpen(stubPath, flags) : NULL; + } + return realOpen(filename, flags); +} +`) + incomplete := compile("incomplete.so", "void unused(void) {}\n") + for _, fixture := range []struct { + name, library, want string + }{ + {"missing", "", "libvterm.so.0; the library could not be loaded"}, + {"incomplete", incomplete, "libvterm.so.0; required symbols are missing"}, + } { + t.Run(fixture.name, func(t *testing.T) { + cmd := exec.Command(os.Args[0], "-test.run=^TestVTermUnavailable$") + cmd.Env = append(os.Environ(), "LD_PRELOAD="+preload, + "FENRIR_TEST_VTERM_LIBRARY="+fixture.library, "FENRIR_TEST_VTERM_ERROR="+fixture.want) + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("unavailable libvterm: %v\n%s", err, output) + } + }) + } +}