Perl hook (L1)
Ready
The hub proposes this hook for the containers it fits, and nothing changes until a player approves the proposal (Hook proposals). The cheat sheet has the steps by hand.
For Perl web services that serve many requests from one process: Mojolicious (the daemon, morbo, hypnotoad workers), PSGI apps on Twiggy, Starman, plackup and other Plack servers, and raw TCP services built on AnyEvent or Mojo::IOLoop. It gets in compose-only: a read-only mount of vulnboxd's hook directory and two switches added to PERL5OPT. The image, the cpanfile and the source stay untouched. The hook is one pure-Perl module plus a tiny, version-independent native shim. It needs nothing from CPAN.
Covers
| Versions | |
|---|---|
| Perl 5 | 5.10–5.42 by design; tested 5.36 and 5.40, threaded and unthreaded, glibc and musl (Alpine), x86_64 and aarch64 |
| Mojolicious | 7–9 (tested 9.39): Mojo::Server::Daemon, morbo, hypnotoad / prefork workers, Mojo::Server::PSGI |
| Mojo raw servers | Mojo::IOLoop->server (one session per connection) |
| PSGI | Plack 1.x (plackup, Plack::Runner, Plack::Util::load_psgi), Twiggy 0.10x, Starman 0.40x, HTTP::Server::PSGI; any framework on PSGI (Dancer2, Catalyst, Mojolicious in PSGI mode, Kelp, …) |
| AnyEvent | 5–7 (tested 7.17), EV and pure-Perl backends: AnyEvent::Socket::tcp_server raw servers |
| Backends to the core | the bundled XSUB shim (default); FFI::Platypus 1.x/2.x when the image has it and the shim can't be used |
What the kernel already links exactly, without this hook:
- CGI scripts and forking servers (
Net::Server::Fork,HTTP::Server::Simplewith a forkingnet_server, inetd/xinetd/socat-style launchers) start one process per connection. The process lineage links everything. No hook is needed (see X1). - Preforking servers (Starman,
Net::Server::PreFork, hypnotoad with one connection per worker at a time): one worker serves one client socket at a time, so the sensor's unambiguous-ownership rule applies. The hook only adds request boundaries and the request index on keep-alive connections. - Event loops (the Mojolicious daemon, Twiggy, AnyEvent and
Mojo::IOLoopservers) serve many connections from one thread. The kernel can't tell their requests apart, so the hook is required.
How it gets in
From a registry (local development, or a build with network; the same release as the hook directory): cpanm VbxTrace@1.0.0, then PERL5OPT=-MVbxTrace; see Local development.
Compose-only (default). The hub proposes:
services:
<service>:
+ volumes:
+ - /usr/local/lib/vulnboxd/trace:/opt/vbxtrace:ro
+ environment:
+ PERL5OPT: "-Mlib=/opt/vbxtrace/perl -MVbxTrace"PERL5OPT holds command-line switches, not paths. If the service already sets it, the hook is appended with a space (PERL5OPT: "-Mstrict -Mlib=/opt/vbxtrace/perl -MVbxTrace"). With the list form of environment, the hub adds - PERL5OPT=-Mlib=/opt/vbxtrace/perl -MVbxTrace. To apply it by hand, add both blocks and run docker compose up -d <service>. Every perl in the container then loads the hook before its own code: perl app.pl, morbo, hypnotoad, plackup, twiggy, starman, and every process they fork.
The hub proposes this when it detects any of:
- a
cpanfile,cpanfile.snapshot,Makefile.PL,Build.PL,dist.ini,*.psgior Perl scripts in the service directory; - a
perl:*orbitnami/perlbase image; perl,morbo,hypnotoad,plackup,twiggy,starman,starletorcarton execin the command;- Mojolicious, AnyEvent, Plack, Twiggy, Starman, Dancer2 or Catalyst among the dependencies.
The template is hooks/perl/l1/proposals/perl5opt.toml.
Source change (fallback, taint mode). Perl ignores PERL5OPT (and PERL5LIB) under taint mode, i.e. for #!/usr/bin/perl -T or perl -T app.pl. It is also no help when an entrypoint wrapper clears the environment. For those cases the hub proposes the mount plus one line right after the #! line of the main script:
BEGIN { if (-e '/opt/vbxtrace/perl/VbxTrace.pm') { unshift @INC, '/opt/vbxtrace/perl'; require VbxTrace } }Without the mount the line does nothing, so the service still starts. Tested under -T. The template is hooks/perl/l1/proposals/taint.toml (with taint.diff).
What it records
| Event | Emitted from | Join key |
|---|---|---|
request_begin / request_end (HTTP) | Mojolicious: Mojolicious::handler and the transaction's finish event, with the status. PSGI: around the app, with the status from the response (for delayed responses, when the responder receives the status) | the accepted socket's local port and peer address and port, and the request index |
request_begin / request_end (raw TCP, protocol raw, index 0) | Mojo::IOLoop->server accept callback / stream close; AnyEvent::Socket::tcp_server accept callback / the socket being freed | the accepted socket's local port and peer |
context_enter / context_exit | around every stretch of code the hook runs on behalf of a request (see below) | the thread (the whole process, since Perl runs one thread) |
spawned | fork (a CORE::GLOBAL::fork override), in the parent, with the child's pid | the child pid |
Where the values come from:
- Peer and local port. Mojolicious: the transaction's
local_port,original_remote_address(not theX-Forwarded-Forvalue thatreverse_proxymode shows asremote_address) andremote_port. These are taken from the accepted socket by the daemon. PSGI:getsockname/getpeernameonpsgix.io(the connection's socket, which Twiggy, Starman andHTTP::Server::PSGIprovide), elseSERVER_PORT,REMOTE_ADDR,REMOTE_PORT. Raw sessions:getsockname/getpeernameon the accepted socket. - Request index. Mojolicious: the daemon's own count of requests on the connection (read in
Mojo::Server::Daemon::_build_tx). PSGI: counted perpsgix.iosocket. When neither is available (a PSGI server withoutpsgix.io, a Mojolicious app on a server other than the daemon), the hook sendsVBX_REQUEST_INDEX_UNKNOWNand never a guess. - Protocol.
http1, orwebsocketfor a WebSocket handshake. On PSGI,http2whenSERVER_PROTOCOLsays so.
The hook emits no connected and opened events of its own, and no spawned for system, backticks or pipe opens. Those all happen inside a context window, where the kernel links the connect(2), open(2), fork/execve exactly (next section). This also covers sockets and files opened by XS code (DBD drivers, Net::SSLeay, IO::AIO submissions), which no Perl-level wrapper would see.
Context following
Perl has no built-in way to carry a request through callbacks, so the hook does it itself. It keeps one current context per process. That is all it needs: Perl's event loops run on a single thread (ithreads services are thread-per-connection and kernel-exact anyway).
Windows. Whenever the hook runs code on behalf of a request, it emits context_enter before and context_exit after (or exit A / enter B when switching from A to B, and back). It does this through a guard object, so an exception that unwinds the code closes the window too. Within a window the thread runs nothing but that request's code, so the sensor attributes every syscall it sees there to the request. Windows open around:
- the request handler:
Mojolicious::handler, the PSGI app, the accept callback of a raw server; - events of objects that belong to one request: everything emitted on a request's Mojo transaction (the rendering,
$c->on(...), WebSocket messages,finish), and on a raw session'sMojo::IOLoop::Stream(read,close). These objects are bound to their context in a field hash, which drops the binding when the object is freed; - I/O watchers on a raw session's socket (
AE::ioandAnyEvent->ioon the accepted socket: everyAnyEvent::Handleread and write callback of that session); - callbacks registered inside a window, which run in that window's context later:
Mojo::Promisethen/catch/finally(so->thenchains andasync/awaitcontinuations);Mojo::IOLoop->timerandnext_tick;- the callback of a non-blocking
Mojo::UserAgentrequest; - the parent callback of
Mojo::IOLoop::Subprocess; - one-shot
AE::timer/AnyEvent->timer; AnyEventcondvarcb;- delayed PSGI responses.
Deliberately not followed. These may serve other requests later, and following them would attribute that work to the wrong request:
- recurring timers;
- I/O watchers on sockets that aren't a raw session (the daemon's keep-alive connections, pooled user agent connections);
- subscriptions on long-lived emitters (the app, the user agent).
Their callbacks run with no context. So do nested event loops (Mojo::IOLoop->start/one_tick, $condvar->recv): while they run, other requests' callbacks may run.
Fork. A child continues outside any window: its lineage is the kernel's. Windows opened in the parent are never closed in the child, and the child's own requests (prefork workers) get fresh contexts.
handoff is not used: work that leaves the process (Subprocess, fork) is linked by the child pid.
Known gaps
- Callbacks the hook doesn't know run with no context. Examples:
EVwatchers created directly,IO::Async,POE,Coro, and custom event emitters other than Mojo's. Their syscalls are then linked only by the kernel's own rules. Work done synchronously in the request handler is always covered. system, backticks, pipe opens are linked through the window (the fork happens inside it), not by an explicitspawnedwith the pid. Aforkcalled outside any window (e.g. from an unknown callback) gets nospawned.- PSGI servers without
psgix.ioreportrequest_indexas unknown (the peer is still exact). Feersum and Corona are untested. - Streaming responses (PSGI writer, Mojo
writechunks) continue afterrequest_end. The PSGI end is when the server gets the status line. Their later callbacks still carry the request's context. - Raw AnyEvent sessions end when the accepted socket is freed. Code that keeps the handle around after closing it delays
request_enduntil it is dropped. - Code compiled before the hook (modules listed before it in
PERL5OPT) doesn't see theforkoverride. Frameworks loaded before the hook are still wrapped. - Taint mode ignores
PERL5OPT: use the source fallback. - Perls built with
-DPERL_RC_STACK(an experimental 5.40+ option) and 32-bit perls: the shim refuses to load and the hook stays off (FFI::Platypus is still used when present).
Safety
What is wrapped:
- Methods, only after their module has loaded:
- Mojolicious:
Mojolicious::handler,Mojo::Server::Daemon::_build_tx(reads the request count),Mojo::IOLoop::server,Mojo::EventEmitter::emit,Mojo::Promise::then/_finally,Mojo::IOLoop::timer/next_tick/start/one_tick,Mojo::UserAgent::start,Mojo::IOLoop::Subprocess::run; - PSGI:
Plack::Runner::locate_app,Plack::Util::load_psgi,Twiggy::Server::register_service,Starman::Server::run,HTTP::Server::PSGI::run; - AnyEvent:
AnyEvent::Socket::tcp_server,AE::io,AE::timer, the backend'sio/timer,AnyEvent::CondVar::Base::cb/recv.
- Mojolicious:
- Process-wide:
CORE::GLOBAL::fork, chained to an existing override;- module loading:
${^HOOK}{require__after}on Perl 5.38+, aCORE::GLOBAL::requireoverride on older perls. That override runs the realrequirein a stub compiled at the caller's package, file and line, so "Can't locate …" and compile errors read exactly as without the hook ($SIG{__DIE__}sees them once).
How wrappers stay invisible:
- Callback-capturing wrappers rebuild
@_(never assigning to its aliased elements) andgotothe original. Callers,caller(),wantarrayand croak locations stay the same. The prototypes and names of wrapped subs are kept. - Window wrappers call the original in the caller's context and return its result unchanged.
VbxTraceis listed in%Carp::Internal, socroaklocations skip it. $@,$!and$^Eare saved around everything the hook does.
Load order and cost:
- The callback and emitter wrappers are installed only when the first request starts with a tracer attached.
- Until then, and whenever no tracer is attached when a request starts, the hook creates no context. It does nothing beyond the handler-level check
vbx_v1_enabled()once per request.
Failure behaviour:
- Every call into the core runs inside
eval, and failures are counted. After 5, the hook switches itself off for the process: all wrappers take their fast path and no event is sent. VBXTRACE=0stops it from loading anything at start.VBXTRACE_CHAOS=1(tests only) makes every call into the core fail. The sample services answer byte-identically with the hook failing (chaos), working (events) and absent (baseline).
The native shim (perl/auto/VbxTrace/vbxperl-<arch>.so) exists because DynaLoader can't call plain C functions: dl_install_xsub makes an XSUB, which perl calls as xsub(my_perl, cv) and which must work the Perl argument stack itself. The shim is a few such XSUBs. One build per architecture serves every Perl 5 version, threaded or not, on glibc or musl:
- It includes no Perl headers and links no libc.
- It calls only Perl API functions every perl exports with the same signature.
- It finds the argument stack through
PL_stack_sp/PL_stack_base/PL_markstack_ptr: globals in unthreaded perls, the first fields of the interpreter in threaded ones. It locatesmarkstack_ptrat start by checking candidates against a call with known arguments. If no candidate matches exactly, the hook stays off. - Every later call re-checks the layout and does nothing if it doesn't fit.
- The core's functions are found by
DynaLoaderin/opt/vbxtrace/libvbxtrace-<arch>.soand their addresses handed to the shim, so the shim links nothing.
With FFI::Platypus in the image and the shim unusable, the hook uses Platypus instead.
Overhead has not been measured yet; that's a later phase.
Turning it off
Set VBXTRACE=0 in the service's environment and restart it, or revert the change that added the hook; vulnboxd's rollback covers a hook that breaks a service. Reverting removes the PERL5OPT addition and the mount; nothing was installed into the image.
Troubleshooting
Are the probes there?
readelf -n /usr/local/lib/vulnboxd/trace/libvbxtrace-x86_64.solists them;sudo bpftrace -l 'usdt:/usr/local/lib/vulnboxd/trace/libvbxtrace-x86_64.so:*'too.Is the hook loaded?
grep vbx /proc/<pid>/mapsshould showlibvbxtrace-<arch>.soandvbxperl-<arch>.so. From inside the container:shperl -Mlib=/opt/vbxtrace/perl -MVbxTrace -e 'print "$VbxTrace::ACTIVE $VbxTrace::BACKEND\n"'This prints
1 shim(or1 platypus).0means the core or the shim couldn't be loaded, orVBXTRACE=0.Which links did a flow get? The hub shows each link's method; this package's are
hook:L1.PERL5OPTreplaced instead of appended: other switches the service relied on (e.g.-Mutf8) vanish. Keep both, separated by a space.Taint mode (
-Ton the#!line or the command):PERL5OPTis ignored silently. Use the source fallback.No events from an event-loop service: check that the framework is one of the covered ones. Perl code calling
EV/IO::Asyncdirectly runs outside any window (see Known gaps).VBXTRACE_PERL_BACKEND=shim|platypusforces one backend (for debugging).