To experiment with network stuff, I was using
UML-based network labs. Many alternatives exist, like
GNS3, Netkit, Marionnet or Cloonix. All of them are
great viable solutions but I still prefer to stick to my minimal
home-made solution with UML virtual machines. Here is why:
I didn t want to use disk images. They take a lot of space and
they have to be maintained. They also become cluttered, especially
if you try to reuse them across several labs. They are also
difficult to share.
I want to be able to access my home directory. It contains the
important configuration files related to the lab and I can put them
in the right place thanks to symbolic links when the lab starts. It
also makes exchanging files with the lab quite easy.
I don t want to boot a complete system. This allows me to be
cheap on memory and each virtual system should boot in a few
seconds.
The use of UML had some drawbacks:
It may be buggy. For example, it is currently not possible to use
gdbserver inside UML without a patch. Sometimes, the kernel
won t even compile.
It is slow.
However, UML features HostFS, a filesystem providing access to any
part of the host filesystem. This is the killer feature which allows
me to not use any virtual disk image and to get access to my home
directory right from the guest.
I discovered recently that QEMU provided 9P, a similar filesystem
on top of VirtIO, the paravirtualized IO framework.
Booting QEMU with a minimal kernel
My initial goal was to experiment with
Nicolas Dichtel s IPv6 ECMP patch. Therefore, I needed to
configure a custom kernel. I have started from make defconfig,
removed everything that was not necessary, added what I needed for my
lab (mostly network stuff) and added the appropriate options for VirtIO
drivers:
No modules. Grab the complete configuration if you want to
have a look.
From here, you can start your kernel with the following command
($LINUX is the appropriate bzImage):
Since there is no disk to boot from, the kernel will panic when trying
to mount the root filesystem. QEMU is configured to not display video
output (-display none). A serial port is defined and uses stdio as
a backend.1 The kernel is configured to use this serial port
as a console (console=ttyS0). A VirtIO console could have been used
instead but it seems it is not possible to make it work early in the
boot process.
The QEMU monitor is setup to listen on a Unix socket. It is possible
to connect to it with socat UNIX:$TMP/vm-$name-console.pipe -.
Initial ramdisk
Update (2012-10)
I was initially unable to mount the host filesystem as the root filesystem
for the guest directly by the kernel. In a comment, Josh
Triplett told me to use /dev/root as the mount
tag to solve this problem. I keep using an initrd in this post but the lab
on GitHub has been updated to not use one.
The copy_exec function is stolen from the initramfs-tools package
in Debian. It will ensure that the appropriate libraries are also
copied. Another solution would have been to use a static busybox.
The setup script is copied as /init in the initial ramdisk. It will
detect it has been invoked as such. If it were omitted, a shell would
be spawned instead. Remove the cp call if you want to experiment
manually.
The flag -initrd allows QEMU to use this initial ramdisk.
Root filesystem
Let s mount our root filesystem using 9P. This is quite easy. First
QEMU needs to be configured to export the host filesystem to
the guest:
You should find a complete root filesystem inside /target/ro. I have
used version=9p2000.u instead of version=9p2000.L because the
latter does not allow a program to mount() a host mount
point.2
Now, you have a read-only root filesystem (because you do not want to
mess with your existing root filesystem and moreover, you did not run
this lab as root, did you?). Let s use a union filesystem. Debian
comes with AUFS while Ubuntu and OpenWRT have migrated to
overlayfs. I was previously using AUFS but got errors on some
specific cases. It is still not clear
which one will end up in the kernel. So, let s try
overlayfs.
I didn t find any patchset ready to be applied on top of my kernel
tree. I was working with David Miller s net-next tree. Here
is how I have applied the overlayfs patch on top of it:
Don t forget to enable CONFIG_OVERLAYFS_FS in .config. Here is how
I configured the whole root filesystem:
info"Setup overlayfs"
mkdir/target
mkdir/target/ro
mkdir/target/rw
mkdir/target/overlay
# Version 9p2000.u allows one to access /dev, /sys and mount new# partitions over them. This is not the case for 9p2000.L.
mount-t9prootshare/target/ro-otrans=virtio,version=9p2000.u
mount-ttmpfstmpfs/target/rw-orw
mount-toverlayfsoverlayfs/target/overlay-olowerdir=/target/ro,upperdir=/target/rw
mount-n-tprocproc/target/overlay/proc
mount-n-tsysfssys/target/overlay/sys
info"Mount home directory on /root"
mount-t9phomeshare/target/overlay/root-otrans=virtio,version=9p2000.L,access=0,rw
info"Mount lab directory on /lab"
mkdir/target/overlay/lab
mount-t9plabshare/target/overlay/lab-otrans=virtio,version=9p2000.L,access=0,rw
info"Chroot"exportSTATE=1
cp"$PROGNAME"/target/overlay
execchroot/target/overlay"$PROGNAME"
You have to export your $ HOME and the lab directory from host:
The use of a VDE switch allows me to run the lab as a non-root
user. It is possible to give Internet access to each VM, either by
using the -net user flag or using slirpvde on a special switch. I
prefer the latter solution since it will allow the VMs to speak to each
other.
Debugging
This lab was mostly done to debug both the kernel and Quagga. Each of
them can be debugged remotely.
Kernel debugging
While the kernel features KGDB, its own debugger, compatible with
GDB, it is easier to use the remote GDB server built inside
QEMU.
To connect to the remote GDB server from the host, first locate the
vmlinux file at the root of the source tree and run GDB on it. The
kernel has to be compiled with CONFIG_DEBUG_INFO=y to get the
appropriate debugging symbols. Then, use socat with the Unix socket
to attach to the remote debugger:
$ gdbvmlinux
GNU gdb (GDB) 7.4.1-debianReading symbols from /home/bernat/src/linux/vmlinux...done.(gdb)target remote socat UNIX:$TMP/vm-r1-gdb.pipe -Remote debugging using socat UNIX:/tmp/tmp.W36qWnrCEj/vm-r1-gdb.pipe -native_safe_halt () at /home/bernat/src/linux/arch/x86/include/asm/irqflags.h:5050 (gdb)
You can now set breakpoints and resume the execution of the kernel.
It is easier to debug the kernel if optimizations are not
enabled. However, it is not possible to
disable them globally. You can however disable them
for some files. For example, to debug net/ipv6/route.c, add
CFLAGS_route.o = -O0 to net/ipv6/Makefile, remove
net/ipv6/route.o and type make.
Userland debugging
To debug a program inside QEMU, you can just use gdb as usual. Your
$HOME directory is available and it should therefore be
straightforward. However, if you want to perform some remote
debugging, that s quite easy. Add a new serial port to QEMU:
$ libtoolexecutegdbserver/dev/ttyS1zebra/zebra
Process /root/code/orange/quagga/build/zebra/.libs/lt-zebra created; pid = 800Remote debugging using /dev/ttyS1
And from the host, you can attach to the remote process:
$ libtoolexecutegdbzebra/zebra
GNU gdb (GDB) 7.4.1-debianReading symbols from /home/bernat/code/orange/quagga/build/zebra/.libs/lt-zebra...done.(gdb)target remote socat UNIX:/tmp/tmp.W36qWnrCEj/vm-r1-serial.pipe -Remote debugging using socat UNIX:/tmp/tmp.W36qWnrCEj/vm-r1-serial.pipe -Reading symbols from /lib64/ld-linux-x86-64.so.2...(no debugging symbols found)...done.Loaded symbols for /lib64/ld-linux-x86-64.so.20x00007ffff7dddaf0 in ?? () from /lib64/ld-linux-x86-64.so.2(gdb)
Demo
For a demo, have a look at the following video:
stdio is configured such that signals are not
enabled. QEMU will not stop when receiving SIGINT. This is
important for the usage we want to have.
Therefore, it is not possible to mount a fresh /proc
on top of the existing one. I have searched a bit but
did not find why. Any comments on this are welcome.
The third release (in twelve years !!) of the sanitizers package
is now on CRAN. sanitizers
provides true positives for programming errors detected by the Address
Sanitizer and friends such as the Undefined Behavior Sanitizer. This
permits validation of the setup when chasing such bug reports: it allows
us to ascertain that the compiler (and instrumented R version) are
correctly set up and the errors we expect to be reported are in fact
reported. That established, a proposed fix no longer exhibiting that
same error will then likely be a suitable one.
A very good resources for all things sanitizers is the Google repo at GitHub
and especially its
wiki.
A little over twelve years since the first release, and three years
since the second one, this update brings chiefly internal package
changes and maintenance. No functional changes, no behavioural
changes.
The brief NEWS entry follows.
Changes in version 0.1.2
(2026-09-12)
Expanded README.md with additional badges, and updated
URLs
Updated continuous integration multiple times
Switched to Authors@R
Added usage, arguments and
value sections to manual page
Review: The Hands of the Emperor, by Victoria Goddard
Series:
Lays of the Hearth-Fire #1
Publisher:
Underhill Books
Copyright:
January 2019
ISBN:
1-988908-15-9
Format:
Kindle
Pages:
739
The Hands of the Emperor is a self-published political fantasy
novel. It's the recommended first book (although not the first published
book) in a
complicated set
of interrelated series. I was not able to definitively confirm that
Underhill Books is Goddard's self-publishing press name, but the press
does not appear to have an Internet presence apart from Goddard's books
and her books appear to be using the standard self-publishing channels.
Cliopher Mdang is the personal secretary of the last emperor of
Astandalas, the magical heart of Zunidh, a man worshiped as a god. The
emperor's word is absolute, his magic supports the health of the entire
world, and he cannot be physically touched without risking physical damage
and severe political and religious punishment. Cliopher is one of the
emperor's closest associates, but the distance between them is still vast.
It therefore represents a terrifying and dangerous breach of etiquette for
him to suggest the emperor may enjoy a vacation on a tropical island near
Cliopher's remote home. The emperor's acceptance of the invitation is even
more startling.
The emperor has opinions about his life as the emperor that no one had
guessed. Cliopher has not assimilated as completely into the bureaucratic
machinery of the empire as it first may appear. And Cliopher's family have
vastly misunderstood the nature of his role in the emperor's government.
I find the marketing blurb for this book unfortunate since, at least to
me, the emphasis on physical touch and intimacy implies that The
Hands of the Emperor is a romance novel or at least has significant
romantic elements. I've been aware of this book for years but put off
reading it because I wasn't quite in the mood for that story. This is not
a romance novel; there is no romance in this book whatsoever. It is a
political fantasy, both in the sense that it is set in a secondary fantasy
world with magic and (apparently) some form of interplanetary travel, and
in the sense that it is a fantasy of governance.
When I say that this book blew up in certain corners of the Internet
during the pandemic, I think you will still underestimate the passion of
its advocates. I heard about this book constantly, in a way that
reminded me of Kushiel's Dart and the
time when fans of Jacqueline Carey would bring her up in every fantasy
conversation, or when we created a Usenet newsgroup for The Wheel of
Time mostly to get the voluminous conversations off of the regular SFF
newsgroup. I'm one of those mildly contrarian people for whom that degree
of enthusiasm is a little off-putting, which is another reason why I
resisted buying a copy for years and only read it in 2026.
It's delightful, although also a bit embarrassing, when the book everyone
was in love with turns out to be just as good as everyone said it was.
I adore stories about friendship, and this is one of the best stories
about friendship that I've ever read. It is a very, very slow burn, but I
also thought the first three quarters of the book was exquisitely paced.
There were long sections where not very much was happening, and yet I
couldn't put the book down because there was so much subtle character work
just beneath the surface.
Almost all of the novel is told in tight third person from Cliopher's
perspective, and I thought that was an excellent choice. Neither Cliopher
nor the narrator comment on things that Cliopher finds obvious, which is
both immersive and critical to the pacing. There are discoveries for the
reader throughout the book, the sort of discoveries that make pieces fit
together satisfyingly in retrospect, and the reader stays sufficiently
ahead of the misunderstandings of Cliopher's friends and family that one
also gets the joy of watching other people discover things that one
figured out a hundred pages earlier.
It helps that I truly liked nearly everyone in this book. There are no
real villains, only a few supporting characters whose role is to be
irritating or corrupt. If you're looking for a lot of conflict and drama,
you may want to save this book for a different mood, but if you're in the
mood for a varied collection of fundamentally good characters working
methodically through the complexities and obstacles of politics and social
systems to improve the world, there are few books I would recommend more.
Goddard achieves one of the hardest tricks of slow burns: steady forward
progress that does not rely on reversals, misunderstandings, or the
friendship equivalent of the third-act breakup. This book spends 700 pages
building towards a climax that managed to be worthy of all 700 pages
without ever annoying me with artificial obstacles, and that's quite a
feat.
I've not said much about the details of the plot. There is one it's not
just character work but I think this book benefits immensely from going
in as blind as possible. I found the twists and turns and growing
revelations so deeply satisfying that I don't want to rob any other reader
of the experience.
The fantasy world-building is intriguing but a bit unsatisfying because it
is so unexplained. We get a few details of the magic system, but since
Cliopher has no magic, he isn't that interested in the details. There is a
catastrophic magical event in the world background, and we learn some of
the details of its practical effects, but the nature of the world before
the cataclysm is so obvious to the characters that it's never explained.
I'm not even certain that this civilization is interplanetary; that feels
like the implication of how characters talk about multiple worlds, but the
method of travel is left entirely undefined. This might be frustrating to
some genre readers, but I personally enjoy books where the world-building
is a bit mysterious. It's a good reason to read more of Goddard's books
set in the same universe.
This was my favorite of the books I've read so far this year, but I do
have one caution and a couple of caveats.
The caution is that Cliopher comes from an island culture based heavily on
(I think) Polynesian cultures. That culture is very central to the story
and is treated with considerable respect, but I still get a bit nervous
when a Canadian author from Nova Scotia with an academic background in
European medieval studies writes a story focused this deeply on a
non-European culture. Nothing about her portrayal seemed off to me
(although there is a very clunky and ham-handed scene about a different
native culture that worries me), and for all I know she has family
background or other connections to the culture she is borrowing from, but
it's possible I missed serious problems.
The flip side of that caution is that I'm delighted to see a fantasy
author drawing on a non-European culture, and I thought the clash of
cultures was very well-handled.
The first caveat is that the story is very focused on good governance, but
both the process and the details of that governance are not going to
satisfy someone reading primarily for the politics. The policies and
reforms are very standard 21st century progressive material that felt a
bit out of place in a quasi-medieval world with magic and airships. Their
implementation is not the point of the story, and is therefore heavily
backgrounded, but that means Goddard barely mentions the inevitable
practical implementation difficulties and does not discuss how they're
overcome.
The world structure also means that Goddard can make use of the favorite
cheat of political reformers in fiction: Absolute monarchy lets you enact
a political agenda without having to do the hard and frustrating work of
persuasion or political (or actual) warfare. This objection is not
entirely fair because we do get some memorable scenes of persuasion, but
the political portion of the plot is unrealistically devoid of setbacks or
resistance that goes beyond token arguments.
Whether this will bother you will depend heavily on what parts of the book
you'd rather focus on. I can see why this was such a popular pandemic
read: The Hands of the Emperor is focused tightly on the joy of
competent people fixing things and does not focus on the arguments,
division, or polarization. The heart of the book is the friendship and
characterization of some deeply admirable people, and the political reform
is incidental background material. I suspect this is the right choice for
readers who aren't political junkies, but I kept having the niggling
objection that the politics felt a bit too pat and simplistic. Goddard
stressed that the characters were investing considerable effort, but even
still, it is not this easy to change the direction of a political system
and idealistic plans usually do not work out this neatly.
The second caveat is that, as previously mentioned, I thought the pacing
was excellent for about three quarters of the book. Goddard is building
towards a grand climax, and I think she built a little too much and tried
to make the climax a bit too grand and risked over-egging the pudding.
That made the payoff feel a bit belabored to me. I still enjoyed it, and
parts of it are wonderfully emotional, but I think the ending might have
been stronger if Goddard had dialed Cliopher back just a little and
tightened up the climax a touch. That said, this book fully commits to
being a sprawling slow burn and that's part of its appeal, so it's
probably better for Goddard to err in that direction than it would have
been to cut short the denouement.
This is one of those books that I'm not sure would exist without
self-publishing. It's a little too long, a little too political in the
wrong ways, a little too devoid of the typical sorts of conflicts expected
in a fantasy book, and too determined to be its own peculiar thing. I
think it would scare off publishers. Unlike some self-published books,
though, I didn't notice any obvious editing flaws or lack of polish. It's
one of those glorious novels that is so very much its own type of story
that it provides an experience that would be hard to replicate with
another book.
I was so deeply satisfied by this book. It's a wish-fulfillment political
fantasy full of diligent restraint and competence porn, so you have to be
in the mood for that. This is not the book to read when you're feeling
cynical, or are in the mood for action and high drama. But if you're in
the mood for a long, slow, open-hearted story of friendship that offers
the fantasy of giving truly good people enough power to be effective, I
highly recommend this one.
Followed in the direct sequel sense by At the Feet of the Sun, but
there is a very complex story progression in this world that I think I'd
have to read all the other books to understand. This was such a satisfying
and complete experience that I'm not in a hurry to figure out which
Goddard book to read next, but I'm sure I'll be returning to this world at
some point.
Rating: 9 out of 10
Team Rcpp is excited to share that an brandnew new version 1.1.2 of
Rcpp is now on CRAN, has also
been uploaded to Debian, and has
already built for r2u
and r-universe;
Windows etc builds at CRAN
should follow in due course.
Rcpp has long established itself
as the most popular way of enhancing R with C or C++ code. Right now,
3236 packages on CRAN depend on
Rcpp for making analytical code go
faster and further. On CRAN, 13.4% of all packages depend (directly) on
Rcpp, and 61.4% of all compiled
packages do. From the cloud mirror of CRAN (which is but a subset of all
CRAN downloads), Rcpp has been
downloaded 121.6 million times. The two published papers (also included
in the package as preprint vignettes) have, respectively, 2263 (JSS, 2011) and 471 (TAS, 2018)
citations, while the the book (Springer useR!,
2013) has another 742.
The is the second update in the 1.1.* series which had, among other
changes, switched to C++11 as
the minimum standard. This release continues as usual with the
six-months January-July cycle started with release
1.0.5 in July 2020. Interim snapshots are always available via the
r-universe page and
repo. We continue to strongly encourage the use of these development
released and their testing we tend to run our systems with them too.
Having said that, we would like to reiterate that we strongly object
to the upstream R release and change management which in this 4.6.*
cycle made several abrupt changes forcing packages which
consume header files to make very abrupt change. Rcpp, just like numerous other CRAN packages demonstrates that
API changes can be undertaken responsibly in a managed manner which
allows for transition periods followed by possible warning periods,
deprecations periods and finally (but only at long last) errors. What
happened here is a speed run to the final stage of forced errors. Uncool
and irritating for something as widely used as R. This forced us to make
an interim release 1.1.1-1.1 even though we have of course had a policy
of always keeping properly tested, installable, and error-free
releases candidate version in the main repository branch and hence
available via R-universe tested
packages for all relevant platforms, and even via binaries for most
(including Ubuntu LTS). It would be nice if R Core found a way to take
advantage of this. Maybe development cycles, running apart for a year as
they do for R, should also include selected packages.
Once again I am not attempting to summarize the different changes.
The full list follows below and details all these changes, their
respective PRs and, if applicable, issue tickets. Big thanks from all of
us to all contributors!
Changes in
Rcpp release version 1.1.2 (2026-07-01)
Changes in Rcpp API:
Use of execinfo.h is again conditional to avoid
build complexity (Dirk in #1445 addressing
#1442)
An internal state component for Datetime is now
int (Dirk in #1448 and #1449 fixing #1447)
Three new (in R 4.6.0) attribute accessors are used conditionally
(Dirk in #1450
closing #1432)
An UBSAN error in the Sugar-based NA comparison has been
corrected (I aki in #1453 fixing #1452)
Treatment of Inf outside of integer range in Sugar function has
been corrected (I aki in #1458 fixing #1455)
Integer overflow protection has been added for sugar functions
(I aki in #1457
fixing #1454)
The parent environment is now accessed via
R_ParentEnv (Dirk in #1460 fixing #1459)
Change to returning dataptr again for better
handling of empty vectors (I aki in #1462 fixing #1461)
Undefined behavior errors in use of ListOf proxies
have been addressed (I aki in #1464 fixing #1463)
Under newer R version, R_UnboundValue is no longer
used (I aki in #1466 fixing #1465)
New R API access point R_getRegisteredNamespace() is
used with current R versions (Dirk in #1469 fixing #1468)
The Nullable::as() exporter now uses an explicit
cast to the templated type (Dirk in #1471 fixing #1470)
A memory leak in the variadic Rcpp::warning()
template has been fixed (Kevin in #1475 fixing #1474)
The Nullable::operatorT() has been added as a
'opt-out' (Dirk in #1477 with
coordination in #1472)
Add templated integer-index overload for operator[]
on small systems such as WASM (Jeroen Ooms in #1482)
The attribute accessors in AttributeProxyPolicy no
longer rely on get__() (Kevin in #1484 fixing #1483)
Changes in Rcpp Documentation:
Reference in the bibliography used by the package vignettes have
been updated.
Changes in Rcpp Deployment:
Excute permissions are set consistently on scripts with shebangs
(Mattias Ellert in #1467)
R 4.5.* has been added to the CI matrix (Dirk in #1476)
Three nag messages issued when obsolete build flag accessors are
used now show Rcpp::: (Dirk in #1480 fixing #1456)
Reference GitHub Actions have been updated to their current
versions (Dirk in #1481)
Non-release Changes:
A non-release hotfix 1.1.1-1 used by CRAN accommodates breaking
changes to the API in R 4.6.0. It would be nice to have the same level
of release management in R itself that CRAN expects from us.
Thanks to my CRANberries, you
can also look at a diff
to the previous interim release along with pre-releases 1.1.1-1
and 1.1.1-1.1
that were needed because R-devel once again sudden decided to move fast
and break things. Not our doing. And there also should not have been a
need to two such uploads but it was amateur hour all around.
Questions, comments etc should go to the GitHub discussion or issue section, or the
Rcpp
list. Bugs reports are welcome at the GitHub issue tracker as
well. GitHub offers decent search for issue, pull requests and
discussions; as many topics have been covered it is worth checking as
well.
I was getting <XF86AudioPlay> is undefined in the status bar of Emacs displayed every 2-3 seconds. Nowhere else I noticed any misbehavior or problems, and also couldn t find any related log entries. It didn t stop, though didn t want to reboot my system to see whether that would fix the problem, but it was driving me nuts.
Now, as a starting point I adjusted my sway configuration, to react to the XF86AudioPlay key press event:
bindsym XF86AudioPlay exec playerctl play-pause
After reloading sway, my music player started to play for 2-3 seconds, stopped playing, started again, etc. It wasn t a Emacs bug, but something indeed seemed to send the XF86AudioPlay key event every 2-3 seconds. It wasn t my USB keyboard or any stuck key on it, as verified also by unplugging it. So which device was causing this?
libinput from libinput-tools to the rescue:
Behind this event12 is sof-hda-dsp Headphone, and evtest confirms that:
% sudo evtest
No device specified, trying to scan all of /dev/input/event*
Available devices:
/dev/input/event0: AT Translated Set 2 keyboard
/dev/input/event1: Sleep Button
/dev/input/event10: ThinkPad Extra Buttons
/dev/input/event11: sof-hda-dsp Mic
/dev/input/event12: sof-hda-dsp Headphone
/dev/input/event13: sof-hda-dsp HDMI/DP,pcm=3
/dev/input/event14: sof-hda-dsp HDMI/DP,pcm=4
/dev/input/event15: sof-hda-dsp HDMI/DP,pcm=5
/dev/input/event16: Yubico YubiKey OTP+FIDO+CCID
/dev/input/event17: Apple Inc. Magic Keyboard with Numeric Keypad
/dev/input/event18: Apple Inc. Magic Keyboard with Numeric Keypad
[...]
Select the device event number [0-24]: ^C
We can even get further information:
% sudo evtest /dev/input/event12
Input driver version is 1.0.1
Input device ID: bus 0x0 vendor 0x0 product 0x0 version 0x0
Input device name: "sof-hda-dsp Headphone"
Supported events:
Event type 0 (EV_SYN)
Event type 1 (EV_KEY)
Event code 114 (KEY_VOLUMEDOWN)
Event code 115 (KEY_VOLUMEUP)
Event code 164 (KEY_PLAYPAUSE)
Event code 582 (KEY_VOICECOMMAND)
Event type 5 (EV_SW)
Event code 2 (SW_HEADPHONE_INSERT) state 0
Properties:
Testing ... (interrupt to exit)
Event: time 1779295060.175766, type 5 (EV_SW), code 2 (SW_HEADPHONE_INSERT), value 1
Event: time 1779295060.175766, -------------- SYN_REPORT ------------
Event: time 1779295061.951168, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 1
Event: time 1779295061.951168, -------------- SYN_REPORT ------------
Event: time 1779295061.951194, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 0
Event: time 1779295061.951194, -------------- SYN_REPORT ------------
Event: time 1779295064.548671, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 1
Event: time 1779295064.548671, -------------- SYN_REPORT ------------
Event: time 1779295064.548689, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 0
Event: time 1779295064.548689, -------------- SYN_REPORT ------------
Event: time 1779295067.437172, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 1
Event: time 1779295067.437172, -------------- SYN_REPORT ------------
Event: time 1779295067.437187, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 0
Event: time 1779295067.437187, -------------- SYN_REPORT ------------
Event: time 1779295070.323775, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 1
Event: time 1779295070.323775, -------------- SYN_REPORT ------------
Event: time 1779295070.323790, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 0
Event: time 1779295070.323790, -------------- SYN_REPORT ------------
Event: time 1779295073.200350, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 1
Event: time 1779295073.200350, -------------- SYN_REPORT ------------
Event: time 1779295073.200373, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 0
Event: time 1779295073.200373, -------------- SYN_REPORT ------------
Event: time 1779295076.076228, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 1
Event: time 1779295076.076228, -------------- SYN_REPORT ------------
Event: time 1779295076.076250, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 0
Event: time 1779295076.076250, -------------- SYN_REPORT ------------
Event: time 1779295078.961740, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 1
Event: time 1779295078.961740, -------------- SYN_REPORT ------------
Event: time 1779295078.961754, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 0
Event: time 1779295078.961754, -------------- SYN_REPORT ------------
Event: time 1779295081.850156, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 1
Event: time 1779295081.850156, -------------- SYN_REPORT ------------
Event: time 1779295081.850175, type 1 (EV_KEY), code 164 (KEY_PLAYPAUSE), value 0
Event: time 1779295081.850175, -------------- SYN_REPORT ------------
Event: time 1779295083.306612, type 5 (EV_SW), code 2 (SW_HEADPHONE_INSERT), value 0
Event: time 1779295083.306612, -------------- SYN_REPORT ------------
So when I plug in my headphone (see the SW_HEADPHONE_INSERT event), the unexpected behavior starts, unplugging stops the problem.
Good! But what was totally unexpected for me: my headphone, being a Beyerdynamic DT-990 Pro, does not have any keys. 8-)
As it turned out, the headphone jack seemed to have been not entirely clean. The analog side of the jack triggers a behavior within the audio codec, where it seems to interpret the fluctuating impedance as a play button of the headset, being pressed, again and again.
I cleaned the jack of my headphone and my XF86AudioPlay problem is gone, case closed.
It started with a thought: to understand people s perspectives on life and its meaning. So I texted folks, What is life (to you)? . Each of the following list items (-) is a response from a different individual, mostly verbatim.
- A lot
- Everyone has a few universal basic qualities, and some special qualities. To me life is pursuit of exploring world based on those qualities and maturing those qualities as one goes on about exploring world/life with those qualities.
Discovering and enhancing experiences as one goes through them.
- life is endless suffering
- my answer might change daily, but this is what I ve noticed and feel recently.
Life is a spectrum with two distinct ends: what we control and what we don t. At birth, the spectrum is largely tilted toward control, but throughout our lives, it gradually shifts toward the other side. Ultimately, as we approach death, we lose all control over any aspect of our existence, reaching the other end of the spectrum.
tho this isn t universal, privilege plays a huge part in what you control tho i believe it holds true for the majority
but yeah man, meaning and purpose are dynamic, it s in their nature to change
i can give you a different answer this evening itself xD
- Zindagi ek nadiya hai,
Aur mujhe tairna nahi aata (translation - Life is a river,
and I don t know how to swim)
On a more serious note, Life is what you make it out for yourself.
The only established truth is that it will end. We can never know if there is something after or if there was something before.
So try to live a life that you feel aspired by?
But this question was beautifully answered by that book which you had about that dying professor
(Me - He was talking about Tuesday s with Morrie)
- My answer is 42
- One, it s living on your own terms, you define everything for yourself, success, normal, whatever. You get to curate your version of it no matter the societal norms.
It s an accumulation of experiences - friends, parents, work, activities, doing shit loads. Sab try karo- travel, zumba, art, music, workout, sports, dil kara ye karna hai karlo. (translation - If your heart wants to do it, just do it.)
Then I think relationships - all that you ve nurtured, people forget maintaining people because of work. It takes efforts to keep people in your life, everyone that comes has a place in yours, how well thats stays is upto you. You also get to curate your people, who stays who don t. Family toh hai hi (translation - family is there) but everyone else that comes along can make it pretty good.
So I don t want to be 50 and be like chalo ab kuch apne liye karte hai (translation - Come on, now let s do something for ourselves) Do whatever shit you want today. Not everything costs money, and if it does get thrifty
But do keep healthy while doing all of that
- Being alive so that my daughter can grow up and i can help raising her kids as well.
Raising kids without mother is tough :P
- Definitively, I feel like Life is a by product of proteins and energy working together.
But in a more personal sense, Life is a dumb joke played onto us. It s a rat race.
But rats exists because of life and then it becomes a chicken-egg problem
Honestly, I don t give good answers to life questions. I m generally the one asking
Life can be like a box of chocolates, you don t know what you re gonna get untill you experience the chocolate(assuming the chocolates are heterogenous and contains a mix of everything)
Camus once said, Life is a revolt , and one of his students added more spice to it like Life is a revolt against the meaninglessness of existence"
I kinda feel like Life is the pursuit of every person s search for meaning
- Imprisonment waiting for execution
I have one more thought while we are on the topic , game with pre defined starting position and predefined destination , path to reach is a maze
- A phase where you can have a really good time or really bad one, usually the mix of both.
A phase where you are prisoner to responsibility and materialistic wants.
It s a hell for you, where you try to create heaven for others.
Being born was never your choice, but ending is always in your hands but you are a prisoner. You fear that leaving this world behind will destroy the heavens you created for others and they will be back to hell. But eventually everyone moves on watching the hourglass of their life.
Once you are left with no desires or no one to create heavens for, you look arround yourself. You see everyone chasing something, everyone scared of their limitted life time sliping away yet you want it to end sooner.
Doesn t matter if it was all good till now, or all bad. The other half is waiting for redemption.
If it was all good, it s best time to die don t wait for the bad to start. If was all bad, it s still the best time to die what if it was the good one and more worst is waiting for you.
We desire to be remembered, yet we want to free from this loop of suffering.
Someone once said, life is a suffering, chose your sufferings.
- Life to me is to live without regrets and live with freedom.
Life is always unpredictable and this unpredictability makes it more interesting and worth it.
- As of now, for the state of mind that I am in , I think for me life is about subtle struggle, subtle inconveniences and yet moving forward cause that s all I know.
I am not sure if any of this has any meaning, but sometimes I feel I was born of a purpose and that the universe has my back.
For me it s about raising my consciousness, understanding people to their depths, gaining moderate material success and helping people to some extend.
I have tried to seek a grander meaning but I have failed.
Life for me is what I make out it.
In my times of great success i rarely think about life for I am busy enjoying it, whatever you may call that state of mind.
- For me its the little things that you enjoy with YOUR people
- Life to me is about living and loving, and doing it in a way that sustains. It s the people who shape you, the work you get absorbed in, the quiet moments in between. There s also the wanting, the drive to figure out what s worth going after and how to get there, but that s just one part of it, not the point of it. And none of it happens in a vacuum. I m aware of the privileges that let me live this way, and I try to hold on to that gratitude. In the end, life has both a material and a non-material side, and a lot of what we do is chasing material things in an attempt to satisfy something non-material within us
- Mere liye (translation - for me) life is staying at my home and studying random economics papers. That s when I enjoy myself the most.
- Very complicated
Some days I wish this life never ended and some time I feel it would be better if it stopped at that moment.
It all depends on the events that happen in the so called life .
So life to me is a string of events that happen anyway and you get to make some decisions which can turn it in any direction and then you wonder how did that happen.
- not forgetting to breathe, learn, eat, game, take a good shit, love, sleep.
- To be honest it changed with time!
At 19 it was about freedom, wasn t sure what freedom meant but i wanted that! To be free from everything, maybe because parents still controlled a part of my life.
Then came 22-24 where i was working, trying to figure out what i want, the meaning changed from freedom to living for myself. To earn more, to be greedy about myself and pursue whatever would help me gain more steps in my career.
Came my mba life, switched my life from doing for myself to trying everything out to have no regrets. Life meaning was just about living with no regrets, invested, gambled, did everything to earn that tag of yeah, have tried that .
Now it has all switched to, it was all just a fake facade. Life turned to having a meaningful life rather than finding meaning in what i am doing. Living for people around me, chhoti chhoti cheezo m khushi (translation - happiness in small things(?)) isn t really a topic of conversation but more of happy thing for me.
So it changed, and m quite happy to be honest. Life did show me a lot of failures, but was privileged enough to face those failures. Gained a lot of learnings if not money
Hopeful for more learnings and change meaning of life with time
- A task.
- You have different answers at different times
You learn different meanings at different times
When you are studying, basically it is about job, finding a partner
then it becomes, house, car other things based on your income
in between, there can be passion too
Free Software was a passion, electoral politics too, but both kind of faded and I want cooperative and user driven development now (prav - something that motivates me every day) and these days learning Chinese and watching Cdrama takes a huge part of my leisure time
it is heavily subjective
and also influences by previous experiences
people around you, how much influence they have on you
it also depends on if they had to struggle in their life or not, for some life did not give much troubles
and trouble itself can be relative
people who never had to struggle may find even smallest challenges as troubles
like if you own a car, your worry is finding a parking slot
- I am too young to think about lyfe
- A ticket to see the show on earth, I guess
I guess life is different depending on the mood. It is a very broad question.
(Me - What is it in this present mood?)
Learning stuff (like I am learning a new language) and being happy but also to regulate emotions in a world where being optimistic is getting harder each day.
Life is also having a unique set of glasses you wear. Both in terms of looking from your eyeballs and your psychological perspective. Both are unique and cannot be replicated.
It is interesting what people on their deathbed think of life. If I know I am dying, my perspective would change a whole lot.
Life is finishing reading books while we are alive
Life is sleeping after a good XMPP chat
- uhh to word it? life is just like a journey from A to somewhere and its all about what paths you take and what line you get on to me, just a series of short adventures that all connect to a larger sequence until you can t have any more adventures-
(Me - eee, THE END. drop dead, like a coin)
yeaaaah- I am not really for spirituality of an afterlife, to me life just ends at some point, after which point there fails to remain a discernable you, and some X time after which, you will be last remembered, try to make that last time a good one I guess?
(Me - no soul?)
uhhh not in the way most people think of it i guess?
theres just a lot of yous, theres the physical you, there is the idea of you, there is the expectation of you, and one of the undefinable you I would label as the soul maybe? like the part thats not physically you, but also certainly you
(Me - can t say I understood part, but I get you in this sense)
mhm- well its about just questioning who you are more so questioning what life is-, I have sadly spent way too much time trying to figure that out
- Making the best of the time you have
- living a full range of experiences and embracing the good ones, seeing all that the world has to offer. In the end we were always just stardust. Might as well enjoy it when we are stardust with a consciousness of our own.
- For some reason or the Universe s /dev/random I was born here as a biological being, and from my experience I understood living is hard and the best way to live is by embracing it. Loving everyone and everything around you. Be happy and joyful until you naturally say good bye to this world.
- Life is being fucked by everything and you just have to figure out and try to stick to the things worth being fucked for
Note: Following was transcribed from a audio message.
- There are five conditions to become a life to survive in the environment. I think there s five conditions by the biological definitions and reproduction is one of the factor virus is not considered a life form because it cannot reproduce on its own but technically it s kind of a life because it reproduces using the DNA ability this is the biological definition.
Do you want a philosophical definition?
My definition is kind of the same except that you get life experiences along with it as a human.
Extra benefits is that you are not an NPC. All other organisms are NPCs.
But humans can interpret the world and change it to their liking.
That is life in the case of a human.
But then many humans are mostly NPCs.
But they still can change the life.
Okay, fuck this. Where is this even going?
A human is an exception in the case of life, because human is not an NPC.
Human can interrupt the world, human can change it to its liking,
which is why we are such a successful organism on this planet.
That is life to me. That s a human.
But all of this is kind of meaningless, because
the biological impurity of a human being still exists, so you still have the
urges to reproduce, which kind of makes
it like just another organism. But then, humans are yet to evolve
to overcome that biological imperative.
I m grateful for all the replies, outlooks, and subsequent conversations I got to have after this question with everyone. After all, it was a deeply personal question. It does fit in nicely with my definition of life: Life is all about experiences and all the transient relationships one gets to have with folks we meet on the way.
The
WWW::Mechanize::Chrome Saga: A Comprehensive Narrative of PR #104
This document synthesizes the extensive work performed from March
13th to March 20th, 2026, to harden, stabilize, and refactor the WWW::Mechanize::Chrome library and its test suite. This
effort involved deep dives into asynchronous programming,
platform-specific bug hunting, and strategic architectural
decisions.
Part I:
The Quest for Cross-Platform Stability (March 13 16)
The initial phase of work focused on achieving a green test suite
across a variety of Linux distributions and preparing for a new release.
This involved significant hardening of the library to account for
different browser versions, OS-level security restrictions, and
filesystem differences.
Key Milestones &
Engineering Decisions:
Fedora & RHEL-family Success: A major effort
was undertaken to achieve a 100% pass rate on modern Fedora 43 and
CentOS Stream 10. This required several key engineering decisions to
handle modern browser behavior:
Decision: Implement Asynchronous DOM Serialization
Fallback. Synchronous fallbacks in an async context are
dangerous. To prevent Resource was not cached errors during saveResources, we implemented a fully asynchronous fallback
in _saveResourceTree. By chaining _cached_document with DOM.getOuterHTML
messages, we can reconstruct document content without blocking the event
loop, even if Chromium has evicted the resource from its cache. This
also proved resilient against Fedora s security policies, which often
block file:// access.
Decision: Truncate Filenames for Cross-Platform
Safety. To avoid File name too long errors,
especially on Windows where the MAX_PATH limit is 260
characters, filenameFromUrl was hardened. The filename
truncation was reduced to a more conservative 150
characters, leaving ample headroom for deeply nested CI
temporary directories. Logic was also added to preserve file extensions
during truncation and to sanitize backslashes from URI paths.
Decision: Expand Browser Discovery Paths. To
support RHEL-based systems out-of-the-box, the default_executable_names was expanded to include headless_shell and search paths were updated to include /usr/lib64/chromium-browser/.
Decision: Mitigate Race Conditions with Stabilization Waits
and Resilient Fetching. On fast systems, DOM.documentUpdated events could invalidate nodeIds immediately after navigation, causing XPath queries
to fail with Could not find node with given id . A small stabilization sleep(0.25s) was added after page loads to ensure the DOM
is settled. Furthermore, the asynchronous DOM fetching loop was hardened
to gracefully handle these errors by catching protocol errors and
returning an empty string for any node that was invalidated during
serialization, ensuring the overall process could complete.
Windows Hardening:
Decision: Adopt Platform-Aware Watchdogs. The test
suite s reliance on ualarm was a blocker for Windows, where
it is not implemented. The t::helper::set_watchdog function
was refactored to use standard alarm() (seconds) on Windows
and ualarm (microseconds) on Unix-like systems, enabling
consistent test-level timeout enforcement.
Version 0.77 Release:
Decision: Adopt SOP for Version Synchronization.
The project maintains duplicate version strings across 24+ files. A
Standard Operating Procedure was adopted to use a batch-replacement tool
to update all sub-modules in lib/ and to always run make clean and perl Makefile.PL to ensure META.json and META.yml reflect the new
version. After achieving stability on Linux, the project version was
bumped to 0.77.
Infrastructure & Strategic Work:
The ad2 Windows Server 2025 instance was restored and
optimized, with Active Directory demoted and disk I/O performance
improved.
A strategic proposal for the Heterogeneous Directory
Replication Protocol (HDRP) was drafted and published.
Part II: The
Great Async Refactor (March 17 18)
Despite success on Linux, tests on the slow ad2 Windows
host were still plagued by intermittent, indefinite hangs. This
triggered a fundamental architectural shift to move the library s core
from a mix of synchronous and asynchronous code to a fully non-blocking
internal API.
Key Milestones &
Engineering Decisions:
Decision: Expose a _future API.
Instead of hardcoding timeouts in the library, the core strategy was to
refactor all blocking methods (xpath, field, get, etc.) into thin wrappers around new non-blocking ..._future counterparts. This moved timeout management to
the test harness, allowing for flexible and explicit handling of
stalls.
# Example library implementationsub xpath($self, $query, %options) return$self->xpath_future($query, %options)->get;sub xpath_future($self, $query, %options) # Async implementation using $self->target->send_message(...)
Decision: Centralize Test Hardening in a Helper.
A dedicated test library, t/lib/t/helper.pm, was created to
contain all stabilization logic. Safe wrappers (safe_get, safe_xpath) were implemented there, using Future->wait_any to race asynchronous operations against
a timeout, preventing tests from hanging.
Decision: Refactor Node Attribute Cache.
Investigations into flaky checkbox tests (t/50-tick.t)
revealed that WWW::Mechanize::Chrome::Node was storing
attributes as a flat list ([key, val, key, val]), which was
inefficient for lookups and individual updates. The cache was refactored
to definitively use a HashRef, providing O(1) lookups
and enabling atomic dual-updates where both the browser property (via
JS) and the internal library attribute are synchronized
simultaneously.
Decision: Implement Self-Cancelling Socket
Watchdog. On Windows, traditional watchdog processes often
failed to detect parent termination, leading to 60-second hangs after
successful tests. We implemented a new socket-based watchdog in t::helper that listens on an ephemeral port; the background
process terminates immediately when the parent socket closes,
eliminating these cumulative delays.
Decision: Deep Recursive Refactoring & Form
Selection. To make the API truly non-blocking, the entire
internal call stack had to be refactored. For example, making get_set_value_future non-blocking required first making its
dependency, _field_by_name, asynchronous. This culminated
in refactoring the entire form selection API (form_name, form_id, etc.) to use the new asynchronous _future lookups, which was a key step in mitigating the
Windows deadlocks.
Evaluation Normalization: Implemented a _process_eval_result helper to centralize the parsing of
results from Runtime.evaluate. This ensures consistent
handling of return values and exceptions between synchronous
(eval_in_page) and asynchronous (eval_future)
calls.
Memory Cycle Mitigation: A significant memory
leak was discovered where closures attached to CDP event futures (like
for asynchronous body retrieval) would capture strong references to $self and the $response object, creating a
circular reference. The established rule is to now always use Scalar::Util::weaken on both $self and any
other relevant objects before they are used inside a ->then block that is stored on an object.
Context Propagation (wantarray): A
major regression was discovered where Perl s wantarray
context, which distinguishes between scalar and list context, was lost
inside asynchronous Future->then blocks. This caused
methods like xpath to return incorrect results (e.g., a
count instead of a list of nodes). The solution was to adopt the Async
Context Pattern : capture wantarray in the synchronous
wrapper, pass it as an option to the _future method, and
then use that captured value inside the future s final resolution
block.
Asynchronous Body Retrieval & Robust Content
Fallbacks: Fixed a bug where decoded_content()
would return empty strings by ensuring it awaited a __body_future. This was implemented by storing the
retrieval future directly on the response object
($response-> __body_future ). To make this more robust,
a tiered strategy was implemented: first try to get the content from the
network response, but if that fails (e.g., for about:blank
or due to cache eviction), fall back to a JavaScript XMLSerializer to get the live DOM content.
Signature Hardening: Fixed Too few arguments
errors when using modern Perl signatures with Future->then. Callbacks were updated to use optional
parameters (sub($result = undef) ... ) to gracefully
handle futures that resolve with no value.
XHTML Split-Brain Bug: Resolved a
long-standing Chromium bug (40130141) where content provided via setDocumentContent is parsed differently than content
loaded from a URL. A workaround was implemented: for XHTML documents,
WMC now uses a JavaScript-based XPath evaluation
(document.evaluate) against the live DOM, bypassing the
broken CDP search mechanism.
Derived Architectural Rules
& SOPs:
Rule: Always provide _future variants.
Every library method that interacts with the browser via CDP must have a
non-blocking asynchronous counterpart.
Rule: Centralize stabilization in the test layer.
All timeout and retry logic should reside in the test harness
(t/lib/t/helper.pm), not in the core library.
Rule: Explicitly propagate wantarray
context. Synchronous wrappers must capture the caller s context
and pass it down the Future chain to ensure correct
scalar/list behavior.
Rule: The entire call chain must be asynchronous.
To enable non-blocking timeouts, even a single hidden blocking call in
an otherwise asynchronous method will cause a stall.
SOP: Reduce Library Noise. Diagnostic messages
(warn, note, diag) should be
removed from library code before commits. All such messages should be
converted to use the internal $self->log('debug', ...)
mechanism, ensuring a clean TAP output for CI systems.
Part III: The MutationObserver Saga (March 19)
With most of the library refactored to be asynchronous, one stubborn
test, t/65-is_visible.t, continued to fail with timeouts.
This led to an ambitious, but ultimately unsuccessful, attempt to
replace the wait_until_visible polling logic with a more
modern MutationObserver.
Key Milestones & Challenges:
The Theory: The goal was to replace an inefficient repeat sleep loop with an event-driven MutationObserver in JavaScript that would notify Perl
immediately when an element s visibility changed.
Implementation & Cascade Failure: The
implementation proved incredibly difficult and introduced a series of
new, hard-to-diagnose bugs:
An incorrect function signature for callFunctionOn_future.
A critical unit mismatch, passing seconds from Perl to JavaScript s setTimeout, which expected milliseconds.
A fundamental hang where the MutationObserver s
JavaScript Promise would never resolve, even after the
underlying DOM element changed.
Debugging Maze: Multiple attempts to fix the checkVisibility JavaScript logic inside the observer
callback, including making it more robust by adding DOM tree traversal
and extensive console.log tracing, failed to resolve the
hang. This highlighted the opacity and difficulty of debugging complex,
cross-language asynchronous interactions, especially when dealing with
low-level browser APIs.
Procedural Learning:
Granular Edits
The effort was plagued by procedural missteps in using automated
file-editing tools. Initial attempts to replace large code blocks in a
single operation led to accidental code loss and match failures.
Decision: Adopt Delete, then Add Workflow.
Following forceful user correction, a new SOP was established for all
future modifications:
Isolate: Break the file into small, manageable
chunks (e.g., 250 lines).
Delete: Perform a delete operation by replacing
the old code block with an empty string.
Add: Perform an add operation by inserting the
new code into the empty space.
Verify: Verifying each atomic step before
proceeding. This granular process, while slower, ensured surgical
precision and regained technical control over the large Chrome.pm module.
The consistent failure of the MutationObserver approach
eventually led to the decision to abandon it in favor of stabilizing the
original, more transparent implementation.
Part IV:
Reversion and Final Stabilization (March 20)
After exhausting all reasonable attempts to fix the MutationObserver, a strategic decision was made to revert
to the simpler, more transparent polling implementation and fix it
correctly. This proved to be the correct path to a stable solution.
Key Milestones &
Engineering Decisions:
Decision: Perform Strategic Reversion. The MutationObserver implementation, when integrated via callFunctionOn_future with awaitPromise,
proved fundamentally unstable. Its JavaScript promise would consistently
fail to resolve, causing indefinite hangs. A decision was made to
revert all MutationObserver code from WWW::Mechanize::Chrome.pm and restore the original repeat sleep polling mechanism. A stable,
understandable solution was prioritized over an elegant but broken
one.
Decision: Correct Timeout Delegation in the
Harness. The root cause of the original timeout failure was
identified as a race condition in the t/lib/t/helper.pm
test harness. The safe_wait_until_* wrappers were
implementing their own timeout (via wait_any and sleep_future) that raced against the underlying polling
function s internal timeout. This led to intermittent failures on slow
machines. The helpers were refactored to delegate all timeout
management to the library s polling functions, ensuring a
single, authoritative timer controlled the operation.
Decision: Optimize Polling Performance. At the
user s request, the polling interval was reduced from 300ms to
150ms. This modest performance improvement reduced the
test suite s wallclock execution time by over a second while maintaining
stability.
Decision: Tune Test Watchdogs. The global watchdog
timeout was adjusted to 12 seconds, specifically calculated as 1.5x the
observed real execution time of the optimized test. This provides a
data-driven safety margin for CI.
Part
V: The Last Bug A Platform-Specific Memory Leak (March 20)
With all other tests passing, a single memory leak failure in t/78-memleak.t persisted, but only on the Windows ad2 environment. This required a different approach than
the timeout fixes.
Key Milestones:
The Bug: A strong reference cycle involving the on_dialog event listener was not being broken on Windows,
despite multiple attempts to fix it. Fixes that worked on Linux (such as
calling on_dialog(undef) in DESTROY) were not
sufficient on the Windows host.
The Diagnosis: The issue was determined to be a
deep, platform-specific interaction between Perl s garbage collector,
the IO::Async event loop implementation on Windows, and the Test::Memory::Cycle module. The cycle report was identical
on both platforms, but the cleanup behavior was different.
Failed Attempts: A series of increasingly
aggressive fixes were attempted to break the cycle, including:
Moving the on_dialog(undef) call from close() to DESTROY().
Explicitly deleteing the listener and callback
properties from the object hash in DESTROY.
Swapping between $self->remove_listener and $self->target->unlisten in a mistaken attempt to find
the correct un-registration method.
Pragmatic Solution: After exhausting all reasonable
code-level fixes without a resolution on Windows, the user opted to mark
the failing test as a known issue for that specific platform.
Final Fix: The single failing test in t/78-memleak.t was wrapped in a conditional TODO block that only executes on Windows
(if ($^O =~ /MSWin32/i)), formally acknowledging the bug
without blocking the build. This allows the test suite to pass in CI
environments while flagging the issue for future, deeper
investigation.
Part VI: CI Hardening (March
20)
A final failure in the GitHub Actions CI environment revealed one
last configuration flaw.
Key Milestones:
The Bug: The CI was running prove --nocount --jobs 3 -I local/ -bl xt t directly. This
command was missing the crucial -It/lib include path, which
is necessary for test files to locate the t::helper module.
This resulted in nearly all tests failing with Can't locate t/helper.pm in @INC.
The Investigation: An analysis of Makefile.PL revealed a custom MY::test block
specifically designed to inject the -It/lib flag into the make test command. This confirmed that make test is the correct, canonical way to run the test
suite for this project.
The Fix: The .github/workflows/linux.yml file was modified to replace
the direct prove call with make test in the Run Tests step. This ensures the CI environment runs the
tests in the exact same way as a local developer, with all necessary
include paths correctly configured by the project s build system.
Final Outcome
After this long and arduous journey, the WWW::Mechanize::Chrome test suite is now stable and
passing on all targeted platforms, with known
platform-specific issues clearly documented in the code. The project is
in a vastly more robust and reliable state.
In the Tor Project system Administrator's team (colloquially known as
TPA), we've recently changed how we take decisions, which means you'll
get clearer communications from us about upcoming changes or
targeted questions about a proposal.
Note that this change only affects the TPA team. At Tor, each team has
its own way of coordinating and making decisions, and so far this
process is only used inside TPA. We encourage other teams inside and
outside Tor to evaluate this process to see if it can improve your
processes and documentation.
The new process
We had traditionally been using a "RFC" ("Request For Comments")
process and have recently switched to "ADR" ("Architecture Decision
Record").
The ADR process is, for us, pretty simple. It consists of three
things:
a simpler template
a simpler process
communication guidelines separate from the decision record
The template
As team lead, the first thing I did was to propose a new template (in
ADR-100), a variation of the Nygard template. The TPA
variation of the template is similarly simple, as it has only 5
headings, and is worth quoting in full:
Context: What is the issue that we're seeing that is motivating
this decision or change?
Decision: What is the change that we're proposing and/or doing?
Consequences: What becomes easier or more difficult to do
because of this change?
More Information (optional): What else should we know? For
larger projects, consider including a timeline and cost estimate,
along with the impact on affected users (perhaps including existing
Personas). Generally, this includes a short evaluation of
alternatives considered.
Metadata: status, decision date, decision makers, consulted,
informed users, and link to a discussion forum
The previous RFC template had 17 (seventeen!) headings, which
encouraged much longer documents. Now, the decision record will be
easier to read and digest at one glance.
An immediate effect of this is that I've started using GitLab issues
more for comparisons and brainstorming. Instead of dumping in a
document all sorts of details like pricing or in-depth alternatives
comparison, we record those in the discussion issue, keeping the
document shorter.
The process
The whole process is simple enough that it's worth quoting in full as
well:
Major decisions are introduced to stakeholders in a meeting, smaller
ones by email. A delay allows people to submit final comments before
adoption.
Now, of course, the devil is in the details (and ADR-101), but the
point is to keep things simple.
A crucial aspect of the proposal, which Jacob Kaplan-Moss calls the
one weird trick, is to "decide who decides". Our previous process
was vague about who makes the decision and the new template (and
process) clarifies decision makers, for each decision.
Inversely, some decisions degenerate into endless discussions around
trivial issues because too many stakeholders are consulted, a
problem known as the Law of triviality, also known as the "Bike
Shed syndrome".
The new process better identifies stakeholders:
"informed" users (previously "affected users")
"consulted" (previously undefined!)
"decision maker" (instead of the vague "approval")
Picking those stakeholders is still tricky, but our definitions are
more explicit and aligned to the classic RACI matrix (Responsible,
Accountable, Consulted, Informed).
Communication guidelines
Finally, a crucial part of the process (ADR-102) is to decouple
the act of making and recording decisions from communicating about
the decision. Those are two radically different problems to
solve. We have found that a single document can't serve both purposes.
Because ADRs can affect a wide range of things, we don't have a
specific template for communications. We suggest the Five Ws
method (Who? What? When? Where? Why?) and, again, to keep things simple.
the RFC process "doesn't include any sort of decision-making framework"
"RFC processes tend to lead to endless discussion"
the process "rewards people who can write to exhaustion"
"these processes are insensitive to expertise", "power dynamics and
power structures"
And, indeed, I have been guilty of a lot of those issues. A verbose
writer, I have written extremely long proposals that I suspect no
one has ever fully read. Some proposals were adopted by exhaustion, or
ignored because not looping in the right stakeholders.
Our discussion issue on the topic has more details on the issues I
found with our RFC process. But to give credit to the old process, it
did serve us well while it was there: it's better than nothing, and it
allowed us to document a staggering number of changes and decisions
(95 RFCs!) made over the course of 6 years of work.
What's next?
We're still experimenting with the communication around decisions, as
this text might suggest. Because it's a separate step, we also have a
tendency to forget or postpone it, like this post, which comes a
couple of months late.
Previously, we'd just ship a copy of the RFC to everyone, which was
easy and quick, but incomprehensible to most. Now we need to write a
separate communication, which is more work but, hopefully, worth the
as the result is more digestible.
We can't wait to hear what you think of the new process and how it
works for you, here or in the discussion issue! We're particularly
interested in people that are already using a similar process, or that
will adopt one after reading this.
Note: this article was also published on the Tor Blog.
Version 0.0.25 of RcppSpdlog arrived
on CRAN right now, and will be
uploaded to Debian and built for r2u shortly along with a
minimal refresh of the documentation site. RcppSpdlog
bundles spdlog, a
wonderful header-only C++ logging library with all the bells and
whistles you would want that was written by Gabi Melman, and also includes fmt by Victor Zverovich. You can learn
more at the nice package
documention site.
This release fixes a minuscule cosmetic issue from the previous
release a week ago. We rely on two #defines that R sets to
signal to spdlog that we
are building in the R context (which matters for the R-specific logging
sink, and picks up something Gabi added upon my suggestion at
the very start of this package). But I use the same
#defines to now check in Rcpp that we are building with R and, in
this case, wrongly conclude R headers have already been installed so Rcpp (incorrectly) nags about that. The
solution is to add two #undefine and proceed as normal
(with Rcpp controlling and taking
care of R header includion too) and that is what we do here. All good
now, no nags from a false positive.
The NEWS entry for this release follows.
Changes in
RcppSpdlog version 0.0.25 (2026-01-15)
Ensure #define signaling R build (needed with spdlog)
is unset before including R headers to not falsely triggering message
from Rcpp
## 0.23 2025-12-20
commit be15aa25dea40aea66a8534143fb81b29d2e6c08
Author: C.J. Collier
Date: Sat Dec 20 22:40:44 2025 +0000
Fixes C-level test infrastructure and adds more test cases for upb_to_sv conversions.
- **Makefile.PL:**
- Allow extra_src in c_test_config.json to be an array.
- Add ASan flags to CCFLAGS and LDDLFLAGS for better debugging.
- Corrected echo newlines in test_c target.
- **c_test_config.json:**
- Added missing type test files to deps and extra_src for convert/sv_to_upb and convert/upb_to_sv test runners.
- **t/c/convert/upb_to_sv.c:**
- Fixed a double free of test_pool .
- Added missing includes for type test headers.
- Updated test plan counts.
- **t/c/convert/sv_to_upb.c:**
- Added missing includes for type test headers.
- Updated test plan counts.
- Corrected Perl interpreter initialization.
- **t/c/convert/types/**:
- Added missing test_util.h include in new type test headers.
- Completed the set of upb_to_sv test cases for all scalar types by adding optional and repeated tests for sfixed32 , sfixed64 , sint32 , and sint64 , and adding repeated tests to the remaining scalar type files.
- **Documentation:**
- Updated 01-xs-testing.md with more debugging tips, including ASan usage and checking for double frees and typos.
- Updated xs_learnings.md with details from the recent segfault.
- Updated llm-plan-execution-instructions.md to emphasize debugging steps.
## 0.22 2025-12-19
commit 2c171d9a5027e0150eae629729c9104e7f6b9d2b
Author: C.J. Collier
Date: Fri Dec 19 23:41:02 2025 +0000
feat(perl,testing): Initialize C test framework and build system
This commit sets up the foundation for the C-level tests and the build system for the Perl Protobuf module:
1. **Makefile.PL Enhancements:**
* Integrates Devel::PPPort to generate ppport.h for better portability.
* Object files now retain their path structure (e.g., xs/convert/sv_to_upb.o ) instead of being flattened, improving build clarity.
* The MY::postamble is significantly revamped to dynamically generate build rules for all C tests located in t/c/ based on the t/c/c_test_config.json file.
* C tests are linked against libprotobuf_common.a and use ExtUtils::Embed flags.
* Added JSON::MaybeXS to PREREQ_PM .
* The test target now also depends on the test_c target.
2. **C Test Infrastructure ( t/c/ ):
* Introduced t/c/c_test_config.json to configure individual C test builds, specifying dependencies and extra source files.
* Created t/c/convert/test_util.c and .h for shared test functions like loading descriptors.
* Initial t/c/convert/upb_to_sv.c and t/c/convert/sv_to_upb.c test runners.
* Basic t/c/integration/030_protobuf_coro.c for Coro safety testing on core utils using libcoro .
* Basic t/c/integration/035_croak_test.c for testing exception handling.
* Basic t/c/integration/050_convert.c for integration testing conversions.
3. **Test Proto:** Updated t/data/test.proto with more field types for conversion testing and regenerated test_descriptor.bin .
4. **XS Test Harness ( t/c/upb-perl-test.h ):** Added like_n macro for length-aware regex matching.
5. **Documentation:** Updated architecture and plan documents to reflect the C test structure.
6. **ERRSV Testing:** Note that the C tests ( t/c/ ) will primarily check *if* a croak occurs (i.e., that the exception path is taken), but will not assert on the string content of ERRSV . Reliably testing $@ content requires the full Perl test environment with Test::More , which will be done in the .t files when testing the Perl API.
This provides a solid base for developing and testing the XS and C components of the module.
## 0.21 2025-12-18
commit a8b6b6100b2cf29c6df1358adddb291537d979bc
Author: C.J. Collier
Date: Thu Dec 18 04:20:47 2025 +0000
test(C): Add integration tests for Milestone 2 components
- Created t/c/integration/030_protobuf.c to test interactions
between obj_cache, arena, and utils.
- Added this test to t/c/c_test_config.json.
- Verified that all C tests for Milestones 2 and 3 pass,
including the libcoro-based stress test.
## 0.20 2025-12-18
commit 0fcad68680b1f700a83972a7c1c48bf3a6958695
Author: C.J. Collier
Date: Thu Dec 18 04:14:04 2025 +0000
docs(plan): Add guideline review reminders to milestones
- Added a "[ ] REFRESH: Review all documents in @perl/doc/guidelines/**"
checklist item to the start of each component implementation
milestone (C and Perl layers).
- This excludes Integration Test milestones.
## 0.19 2025-12-18
commit 987126c4b09fcdf06967a98fa3adb63d7de59a34
Author: C.J. Collier
Date: Thu Dec 18 04:05:53 2025 +0000
docs(plan): Add C-level and Perl-level Coro tests to milestones
- Added checklist items for libcoro -based C tests
(e.g., t/c/integration/050_convert_coro.c ) to all C layer
integration milestones (050 through 220).
- Updated 030_Integration_Protobuf.md to standardise checklist
items for the existing 030_protobuf_coro.c test.
- Removed the single xt/author/coro-safe.t item from
010_Build.md .
- Added checklist items for Perl-level Coro tests
(e.g., xt/coro/240_arena.t ) to each Perl layer
integration milestone (240 through 400).
- Created perl/t/c/c_test_config.json to manage C test
configurations externally.
- Updated perl/doc/architecture/testing/01-xs-testing.md to describe
both C-level libcoro and Perl-level Coro testing strategies.
## 0.18 2025-12-18
commit 6095a5a610401a6035a81429d0ccb9884d53687b
Author: C.J. Collier
Date: Thu Dec 18 02:34:31 2025 +0000
added coro testing to c layer milestones
## 0.17 2025-12-18
commit cc0aae78b1f7f675fc8a1e99aa876c0764ea1cce
Author: C.J. Collier
Date: Thu Dec 18 02:26:59 2025 +0000
docs(plan): Refine test coverage checklist items for SMARTness
- Updated the "Tests provide full coverage" checklist items in
C layer plan files (020, 040, 060, 080, 100, 120, 140, 160, 180, 200)
to explicitly mention testing all public functions in the
corresponding header files.
- Expanded placeholder checklists in 140, 160, 180, 200.
- Updated the "Tests provide full coverage" and "Add coverage checks"
checklist items in Perl layer plan files (230, 250, 270, 290, 310, 330,
350, 370, 390) to be more specific about the scope of testing
and the use of Test::TestCoverage .
- Expanded Well-Known Types milestone (350) to detail each type.
## 0.16 2025-12-18
commit e4b601f14e3817a17b0f4a38698d981dd4cb2818
Author: C.J. Collier
Date: Thu Dec 18 02:07:35 2025 +0000
docs(plan): Full refactoring of C and Perl plan files
- Split both ProtobufPlan-C.md and ProtobufPlan-Perl.md into
per-milestone files under the perl/doc/plan/ directory.
- Introduced Integration Test milestones after each component
milestone in both C and Perl plans.
- Numbered milestone files sequentially (e.g., 010_Build.md,
230_Perl_Arena.md).
- Updated main ProtobufPlan-C.md and ProtobufPlan-Perl.md to
act as Tables of Contents.
- Ensured consistent naming for integration test files
(e.g., t/c/integration/030_protobuf.c , t/integration/260_descriptor_pool.t ).
- Added architecture review steps to the end of all milestones.
- Moved Coro safety test to C layer Milestone 1.
- Updated Makefile.PL to support new test structure and added Coro.
- Moved and split t/c/convert.c into t/c/convert/*.c.
- Moved other t/c/*.c tests into t/c/protobuf/*.c.
- Deleted old t/c/convert.c.
## 0.15 2025-12-17
commit 649cbacf03abb5e7293e3038bb451c0406e9d0ce
Author: C.J. Collier
Date: Wed Dec 17 23:51:22 2025 +0000
docs(plan): Refactor and reset ProtobufPlan.md
- Split the plan into ProtobufPlan-C.md and ProtobufPlan-Perl.md.
- Reorganized milestones to clearly separate C layer and Perl layer development.
- Added more granular checkboxes for each component:
- C Layer: Create test, Test coverage, Implement, Tests pass.
- Perl Layer: Create test, Test coverage, Implement Module/XS, Tests pass, C-Layer adjustments.
- Reset all checkboxes to [ ] to prepare for a full audit.
- Updated status in architecture/api and architecture/core documents to "Not Started".
feat(obj_cache): Add unregister function and enhance tests
- Added protobuf_unregister_object to xs/protobuf/obj_cache.c .
- Updated xs/protobuf/obj_cache.h with the new function declaration.
- Expanded tests in t/c/protobuf_obj_cache.c to cover unregistering,
overwriting keys, and unregistering non-existent keys.
- Corrected the test plan count in t/c/protobuf_obj_cache.c to 17.
## 0.14 2025-12-17
commit 40b6ad14ca32cf16958d490bb575962f88d868a1
Author: C.J. Collier
Date: Wed Dec 17 23:18:27 2025 +0000
feat(arena): Complete C layer for Arena wrapper
This commit finalizes the C-level implementation for the Protobuf::Arena wrapper.
- Adds PerlUpb_Arena_Destroy for proper cleanup from Perl's DEMOLISH.
- Enhances error checking in PerlUpb_Arena_Get .
- Expands C-level tests in t/c/protobuf_arena.c to cover memory allocation
on the arena and lifecycle through PerlUpb_Arena_Destroy .
- Corrects embedded Perl initialization in the C test.
docs(plan): Refactor ProtobufPlan.md
- Restructures the development plan to clearly separate "C Layer" and
"Perl Layer" tasks within each milestone.
- This aligns the plan with the "C-First Implementation Strategy" and improves progress tracking.
## 0.13 2025-12-17
commit c1e566c25f62d0ae9f195a6df43b895682652c71
Author: C.J. Collier
Date: Wed Dec 17 22:00:40 2025 +0000
refactor(perl): Rename C tests and enhance Makefile.PL
- Renamed test files in t/c/ to better match the xs module structure:
- 01-cache.c -> protobuf_obj_cache.c
- 02-arena.c -> protobuf_arena.c
- 03-utils.c -> protobuf_utils.c
- 04-convert.c -> convert.c
- load_test.c -> upb_descriptor_load.c
- Updated perl/Makefile.PL to reflect the new test names in MY::postamble 's $c_test_config .
- Refactored the $c_test_config generation in Makefile.PL to reduce repetition by using a default flags hash and common dependencies array.
- Added a fail() macro to perl/t/c/upb-perl-test.h for consistency.
- Modified t/c/upb_descriptor_load.c to use the t/c/upb-perl-test.h macros, making its output consistent with other C tests.
- Added a skeleton for t/c/convert.c to test the conversion functions.
- Updated documentation in ProtobufPlan.md and architecture/testing/01-xs-testing.md to reflect new test names.
## 0.12 2025-12-17
commit d8cb5dd415c6c129e71cd452f78e29de398a82c9
Author: C.J. Collier
Date: Wed Dec 17 20:47:38 2025 +0000
feat(perl): Refactor XS code into subdirectories
This commit reorganizes the C code in the perl/xs/ directory into subdirectories, mirroring the structure of the Python UPB extension. This enhances modularity and maintainability.
- Created subdirectories for each major component: convert , descriptor , descriptor_containers , descriptor_pool , extension_dict , map , message , protobuf , repeated , and unknown_fields .
- Created skeleton .h and .c files within each subdirectory to house the component-specific logic.
- Updated top-level component headers (e.g., perl/xs/descriptor.h ) to include the new sub-headers.
- Updated top-level component source files (e.g., perl/xs/descriptor.c ) to include their main header and added stub initialization functions (e.g., PerlUpb_InitDescriptor ).
- Moved code from the original perl/xs/protobuf.c to new files in perl/xs/protobuf/ (arena, obj_cache, utils).
- Moved code from the original perl/xs/convert.c to new files in perl/xs/convert/ (upb_to_sv, sv_to_upb).
- Updated perl/Makefile.PL to use a glob ( xs/*/*.c ) to find the new C source files in the subdirectories.
- Added perl/doc/architecture/core/07-xs-file-organization.md to document the new structure.
- Updated perl/doc/ProtobufPlan.md and other architecture documents to reference the new organization.
- Corrected self-referential includes in the newly created .c files.
This restructuring provides a solid foundation for further development and makes it easier to port logic from the Python implementation.
## 0.11 2025-12-17
commit cdedcd13ded4511b0464f5d3bdd72ce6d34e73fc
Author: C.J. Collier
Date: Wed Dec 17 19:57:52 2025 +0000
feat(perl): Implement C-first testing and core XS infrastructure
This commit introduces a significant refactoring of the Perl XS extension, adopting a C-first development approach to ensure a robust foundation.
Key changes include:
- **C-Level Testing Framework:** Established a C-level testing system in t/c/ with a dedicated Makefile, using an embedded Perl interpreter. Initial tests cover the object cache ( 01-cache.c ), arena wrapper ( 02-arena.c ), and utility functions ( 03-utils.c ).
- **Core XS Infrastructure:**
- Implemented a global object cache ( xs/protobuf.c ) to manage Perl wrappers for UPB objects, using weak references.
- Created an upb_Arena wrapper ( xs/protobuf.c ).
- Consolidated common XS helper functions into xs/protobuf.h and xs/protobuf.c .
- **Makefile.PL Enhancements:** Updated to support building and linking C tests, incorporating flags from ExtUtils::Embed , and handling both .c and .cc source files.
- **XS File Reorganization:** Restructured XS files to mirror the Python UPB extension's layout (e.g., message.c , descriptor.c ). Removed older, monolithic .xs files.
- **Typemap Expansion:** Added extensive typemap entries in perl/typemap to handle conversions between Perl objects and various const upb_*Def* pointers.
- **Descriptor Tests:** Added a new test suite t/02-descriptor.t to validate descriptor loading and accessor methods.
- **Documentation:** Updated development plans and guidelines ( ProtobufPlan.md , xs_learnings.md , etc.) to reflect the C-first strategy, new testing methods, and lessons learned.
- **Build Cleanup:** Removed ppport.h from .gitignore as it's no longer used, due to -DPERL_NO_PPPORT being set in Makefile.PL .
This C-first approach allows for more isolated and reliable testing of the core logic interacting with the UPB library before higher-level Perl APIs are built upon it.
## 0.10 2025-12-17
commit 1ef20ade24603573905cb0376670945f1ab5d829
Author: C.J. Collier
Date: Wed Dec 17 07:08:29 2025 +0000
feat(perl): Implement C-level tests and core XS utils
This commit introduces a C-level testing framework for the XS layer and implements key components:
1. **C-Level Tests ( t/c/ )**:
* Added t/c/Makefile to build standalone C tests.
* Created t/c/upb-perl-test.h with macros for TAP-compliant C tests ( plan , ok , is , is_string , diag ).
* Implemented t/c/01-cache.c to test the object cache.
* Implemented t/c/02-arena.c to test Protobuf::Arena wrappers.
* Implemented t/c/03-utils.c to test string utility functions.
* Corrected include paths and diagnostic messages in C tests.
2. **XS Object Cache ( xs/protobuf.c )**:
* Switched to using stringified pointers ( %p ) as hash keys for stability.
* Fixed a critical double-free bug in PerlUpb_ObjCache_Delete by removing an extra SvREFCNT_dec on the lookup key.
3. **XS Arena Wrapper ( xs/protobuf.c )**:
* Corrected PerlUpb_Arena_New to use newSVrv and PTR2IV for opaque object wrapping.
* Corrected PerlUpb_Arena_Get to safely unwrap the arena pointer.
4. **Makefile.PL ( perl/Makefile.PL )**:
* Added -Ixs to INC to allow C tests to find t/c/upb-perl-test.h and xs/protobuf.h .
* Added LIBS to link libprotobuf_common.a into the main Protobuf.so .
* Added C test targets 01-cache , 02-arena , 03-utils to the test config in MY::postamble .
5. **Protobuf.pm ( perl/lib/Protobuf.pm )**:
* Added use XSLoader; to load the compiled XS code.
6. **New files xs/util.h **:
* Added initial type conversion function.
These changes establish a foundation for testing the C-level interface with UPB and fix crucial bugs in the object cache implementation.
## 0.09 2025-12-17
commit 07d61652b032b32790ca2d3848243f9d75ea98f4
Author: C.J. Collier
Date: Wed Dec 17 04:53:34 2025 +0000
feat(perl): Build system and C cache test for Perl XS
This commit introduces the foundational pieces for the Perl XS implementation, focusing on the build system and a C-level test for the object cache.
- **Makefile.PL:**
- Refactored C test compilation rules in MY::postamble to use a hash ( $c_test_config ) for better organization and test-specific flags.
- Integrated ExtUtils::Embed to provide necessary compiler and linker flags for embedding the Perl interpreter, specifically for the t/c/01-cache.c test.
- Correctly constructs the path to the versioned Perl library ( libperl.so.X.Y.Z ) using $Config archlib and $Config libperl to ensure portability.
- Removed VERSION_FROM and ABSTRACT_FROM to avoid dependency on .pm files for now.
- **C Cache Test (t/c/01-cache.c):**
- Added a C test to exercise the object cache functions implemented in xs/protobuf.c .
- Includes tests for adding, getting, deleting, and weak reference behavior.
- **XS Cache Implementation (xs/protobuf.c, xs/protobuf.h):**
- Implemented PerlUpb_ObjCache_Init , PerlUpb_ObjCache_Add , PerlUpb_ObjCache_Get , PerlUpb_ObjCache_Delete , and PerlUpb_ObjCache_Destroy .
- Uses a Perl hash ( HV* ) for the cache.
- Keys are string representations of the C pointers, created using snprintf with "%llx" .
- Values are weak references ( sv_rvweaken ) to the Perl objects ( SV* ).
- PerlUpb_ObjCache_Get now correctly returns an incremented reference to the original SV, not a copy.
- PerlUpb_ObjCache_Destroy now clears the hash before decrementing its refcount.
- **t/c/upb-perl-test.h:**
- Updated is_sv to perform direct pointer comparison ( got == expected ).
- **Minor:** Added util.h (currently empty), updated typemap .
These changes establish a working C-level test environment for the XS components.
## 0.08 2025-12-17
commit d131fd22ea3ed8158acb9b0b1fe6efd856dc380e
Author: C.J. Collier
Date: Wed Dec 17 02:57:48 2025 +0000
feat(perl): Update docs and core XS files
- Explicitly add TDD cycle to ProtobufPlan.md.
- Clarify mirroring of Python implementation in upb-interfacing.md for both C and Perl layers.
- Branch and adapt python/protobuf.h and python/protobuf.c to perl/xs/protobuf.h and perl/xs/protobuf.c, including the object cache implementation. Removed old cache.* files.
- Create initial C test for the object cache in t/c/01-cache.c.
## 0.07 2025-12-17
commit 56fd6862732c423736a2f9a9fb1a2816fc59e9b0
Author: C.J. Collier
Date: Wed Dec 17 01:09:18 2025 +0000
feat(perl): Align Perl UPB architecture docs with Python
Updates the Perl Protobuf architecture documents to more closely align with the design and implementation strategies used in the Python UPB extension.
Key changes:
- **Object Caching:** Mandates a global, per-interpreter cache using weak references for all UPB-derived objects, mirroring Python's PyUpb_ObjCache .
- **Descriptor Containers:** Introduces a new document outlining the plan to use generic XS container types (Sequence, ByNameMap, ByNumberMap) with vtables to handle collections of descriptors, similar to Python's descriptor_containers.c .
- **Testing:** Adds a note to the testing strategy to port relevant test cases from the Python implementation to ensure feature parity.
## 0.06 2025-12-17
commit 6009ce6ab64eccce5c48729128e5adf3ef98e9ae
Author: C.J. Collier
Date: Wed Dec 17 00:28:20 2025 +0000
feat(perl): Implement object caching and fix build
This commit introduces several key improvements to the Perl XS build system and core functionality:
1. **Object Caching:**
* Introduces xs/protobuf.c and xs/protobuf.h to implement a caching mechanism ( protobuf_c_to_perl_obj ) for wrapping UPB C pointers into Perl objects. This uses a hash and weak references to ensure object identity and prevent memory leaks.
* Updates the typemap to use protobuf_c_to_perl_obj for upb_MessageDef * output, ensuring descriptor objects are cached.
* Corrected sv_weaken to the correct sv_rvweaken function.
2. **Makefile.PL Enhancements:**
* Switched to using the Bazel-generated UPB descriptor sources from bazel-bin/src/google/protobuf/_virtual_imports/descriptor_proto/google/protobuf/ .
* Updated INC paths to correctly locate the generated headers.
* Refactored MY::dynamic_lib to ensure the static library libprotobuf_common.a is correctly linked into each generated .so module, resolving undefined symbol errors.
* Overrode MY::test to use prove -b -j$(nproc) t/*.t xt/*.t for running tests.
* Cleaned up LIBS and LDDLFLAGS usage.
3. **Documentation:**
* Updated ProtobufPlan.md to reflect the current status and design decisions.
* Reorganized architecture documents into subdirectories.
* Added object-caching.md and c-perl-interface.md .
* Updated llm-guidance.md with notes on upb/upb.h and sv_rvweaken .
4. **Testing:**
* Fixed xt/03-moo_immutable.t to skip tests if no Moo modules are found.
This resolves the build issues and makes the core test suite pass.
## 0.05 2025-12-16
commit 177d2f3b2608b9d9c415994e076a77d8560423b8
Author: C.J. Collier
Date: Tue Dec 16 19:51:36 2025 +0000
Refactor: Rename namespace to Protobuf, build system and doc updates
This commit refactors the primary namespace from ProtoBuf to Protobuf
to align with the style guide. This involves renaming files, directories,
and updating package names within all Perl and XS files.
**Namespace Changes:**
* Renamed perl/lib/ProtoBuf to perl/lib/Protobuf .
* Moved and updated ProtoBuf.pm to Protobuf.pm .
* Moved and updated ProtoBuf::Descriptor to Protobuf::Descriptor (.pm & .xs).
* Removed other ProtoBuf::* stubs (Arena, DescriptorPool, Message).
* Updated MODULE and PACKAGE in Descriptor.xs .
* Updated NAME , *_FROM in perl/Makefile.PL .
* Replaced ProtoBuf with Protobuf throughout perl/typemap .
* Updated namespaces in test files t/01-load-protobuf-descriptor.t and t/02-descriptor.t .
* Updated namespaces in all documentation files under perl/doc/ .
* Updated paths in perl/.gitignore .
**Build System Enhancements (Makefile.PL):**
* Included xs/*.c files in the common object files list.
* Added -I. to the INC paths.
* Switched from MYEXTLIB to LIBS => ['-L$(CURDIR) -lprotobuf_common'] for linking.
* Removed custom keys passed to WriteMakefile for postamble.
* MY::postamble now sources variables directly from the main script scope.
* Added all :: $ common_lib dependency in MY::postamble .
* Added t/c/load_test.c compilation rule in MY::postamble .
* Updated clean target to include blib .
* Added more modules to TEST_REQUIRES .
* Removed the explicit PM and XS keys from WriteMakefile , relying on XSMULTI => 1 .
**New Files:**
* perl/lib/Protobuf.pm
* perl/lib/Protobuf/Descriptor.pm
* perl/lib/Protobuf/Descriptor.xs
* perl/t/01-load-protobuf-descriptor.t
* perl/t/02-descriptor.t
* perl/t/c/load_test.c : Standalone C test for UPB.
* perl/xs/types.c & perl/xs/types.h : For Perl/C type conversions.
* perl/doc/architecture/upb-interfacing.md
* perl/xt/03-moo_immutable.t : Test for Moo immutability.
**Deletions:**
* Old test files: t/00_load.t , t/01_basic.t , t/02_serialize.t , t/03_message.t , t/04_descriptor_pool.t , t/05_arena.t , t/05_message.t .
* Removed lib/ProtoBuf.xs as it's not needed with XSMULTI .
**Other:**
* Updated test_descriptor.bin (binary change).
* Significant content updates to markdown documentation files in perl/doc/architecture and perl/doc/internal reflecting the new architecture and learnings.
## 0.04 2025-12-14
commit 92de5d482c8deb9af228f4b5ce31715d3664d6ee
Author: C.J. Collier
Date: Sun Dec 14 21:28:19 2025 +0000
feat(perl): Implement Message object creation and fix lifecycles
This commit introduces the basic structure for ProtoBuf::Message object
creation, linking it with ProtoBuf::Descriptor and ProtoBuf::DescriptorPool ,
and crucially resolves a SEGV by fixing object lifecycle management.
Key Changes:
1. ** ProtoBuf::Descriptor :** Added _pool attribute to hold a strong
reference to the parent ProtoBuf::DescriptorPool . This is essential to
prevent the pool and its C upb_DefPool from being garbage collected
while a descriptor is still in use.
2. ** ProtoBuf::DescriptorPool :**
* find_message_by_name : Now passes the $self (the pool object) to the
ProtoBuf::Descriptor constructor to establish the lifecycle link.
* XSUB pb_dp_find_message_by_name : Updated to accept the pool SV* and
store it in the descriptor's _pool attribute.
* XSUB _load_serialized_descriptor_set : Renamed to avoid clashing with the
Perl method name. The Perl wrapper now correctly calls this internal XSUB.
* DEMOLISH : Made safer by checking for attribute existence.
3. ** ProtoBuf::Message :**
* Implemented using Moo with lazy builders for _upb_arena and
_upb_message .
* _descriptor is a required argument to new() .
* XS functions added for creating the arena ( pb_msg_create_arena ) and
the upb_Message ( pb_msg_create_upb_message ).
* pb_msg_create_upb_message now extracts the upb_MessageDef* from the
descriptor and uses upb_MessageDef_MiniTable() to get the minitable
for upb_Message_New() .
* DEMOLISH : Added to free the message's arena.
4. ** Makefile.PL :**
* Added -g to CCFLAGS for debugging symbols.
* Added Perl CORE include path to MY::postamble 's base_flags .
5. **Tests:**
* t/04_descriptor_pool.t : Updated to check the structure of the
returned ProtoBuf::Descriptor .
* t/05_message.t : Now uses a descriptor obtained from a real pool to
test ProtoBuf::Message->new() .
6. **Documentation:**
* Updated ProtobufPlan.md to reflect progress.
* Updated several files in doc/architecture/ to match the current
implementation details, especially regarding arena management and object
lifecycles.
* Added doc/internal/development_cycle.md and doc/internal/xs_learnings.md .
With these changes, the SEGV is resolved, and message objects can be successfully
created from descriptors.
## 0.03 2025-12-14
commit 6537ad23e93680c2385e1b571d84ed8dbe2f68e8
Author: C.J. Collier
Date: Sun Dec 14 20:23:41 2025 +0000
Refactor(perl): Object-Oriented DescriptorPool with Moo
This commit refactors the ProtoBuf::DescriptorPool to be fully object-oriented using Moo, and resolves several issues related to XS, typemaps, and test data.
Key Changes:
1. **Moo Object:** ProtoBuf::DescriptorPool.pm now uses Moo to define the class. The upb_DefPool pointer is stored as a lazy attribute _upb_defpool .
2. **XS Lifecycle:** DescriptorPool.xs now has pb_dp_create_pool called by the Moo builder and pb_dp_free_pool called from DEMOLISH to manage the upb_DefPool lifecycle per object.
3. **Typemap:** The perl/typemap file has been significantly updated to handle the conversion between the ProtoBuf::DescriptorPool Perl object and the upb_DefPool * C pointer. This includes:
* Mapping upb_DefPool * to T_PTR .
* An INPUT section for ProtoBuf::DescriptorPool to extract the pointer from the object's hash, triggering the lazy builder if needed via call_method .
* An OUTPUT section for upb_DefPool * to convert the pointer back to a Perl integer, used by the builder.
4. **Method Renaming:** add_file_descriptor_set_binary is now load_serialized_descriptor_set .
5. **Test Data:**
* Added perl/t/data/test.proto with a sample message and enum.
* Generated perl/t/data/test_descriptor.bin using protoc .
* Removed t/data/ from .gitignore to ensure test data is versioned.
6. **Test Update:** t/04_descriptor_pool.t is updated to use the new OO interface, load the generated descriptor set, and check for message definitions.
7. **Build Fixes:**
* Corrected #include paths in DescriptorPool.xs to be relative to the upb/ directory (e.g., upb/wire/decode.h ).
* Added -I../upb to CCFLAGS in Makefile.PL .
* Reordered INC paths in Makefile.PL to prioritize local headers.
**Note:** While tests now pass in some environments, a SEGV issue persists in make test runs, indicating a potential memory or lifecycle issue within the XS layer that needs further investigation.
## 0.02 2025-12-14
commit 6c9a6f1a5f774dae176beff02219f504ea3a6e07
Author: C.J. Collier
Date: Sun Dec 14 20:13:09 2025 +0000
Fix(perl): Correct UPB build integration and generated file handling
This commit resolves several issues to achieve a successful build of the Perl extension:
1. **Use Bazel Generated Files:** Switched from compiling UPB's stage0 descriptor.upb.c to using the Bazel-generated descriptor.upb.c and descriptor.upb_minitable.c located in bazel-bin/src/google/protobuf/_virtual_imports/descriptor_proto/google/protobuf/ .
2. **Updated Include Paths:** Added the bazel-bin path to INC in WriteMakefile and to base_flags in MY::postamble to ensure the generated headers are found during both XS and static library compilation.
3. **Removed Stage0:** Removed references to UPB_STAGE0_DIR and no longer include headers or source files from upb/reflection/stage0/ .
4. **-fPIC:** Explicitly added -fPIC to CCFLAGS in WriteMakefile and ensured $(CCFLAGS) is used in the custom compilation rules in MY::postamble . This guarantees all object files in the static library are compiled with position-independent code, resolving linker errors when creating the shared objects for the XS modules.
5. **Refined UPB Sources:** Used File::Find to recursively find UPB C sources, excluding /conformance/ and /reflection/stage0/ to avoid conflicts and unnecessary compilations.
6. **Arena Constructor:** Modified ProtoBuf::Arena::pb_arena_new XSUB to accept the class name argument passed from Perl, making it a proper constructor.
7. **.gitignore:** Added patterns to perl/.gitignore to ignore generated C files from XS ( lib/*.c , lib/ProtoBuf/*.c ), the copied src_google_protobuf_descriptor.pb.cc , and the t/data directory.
8. **Build Documentation:** Updated perl/doc/architecture/upb-build-integration.md to reflect the new build process, including the Bazel prerequisite, include paths, -fPIC usage, and File::Find .
Build Steps:
1. bazel build //src/google/protobuf:descriptor_upb_proto (from repo root)
2. cd perl
3. perl Makefile.PL
4. make
5. make test (Currently has expected failures due to missing test data implementation).
## 0.01 2025-12-14
commit 3e237e8a26442558c94075766e0d4456daaeb71d
Author: C.J. Collier
Date: Sun Dec 14 19:34:28 2025 +0000
feat(perl): Initialize Perl extension scaffold and build system
This commit introduces the perl/ directory, laying the groundwork for the Perl Protocol Buffers extension. It includes the essential build files, linters, formatter configurations, and a vendored Devel::PPPort for XS portability.
Key components added:
* ** Makefile.PL **: The core ExtUtils::MakeMaker build script. It's configured to:
* Build a static library ( libprotobuf_common.a ) from UPB, UTF8_Range, and generated protobuf C/C++ sources.
* Utilize XSMULTI => 1 to create separate shared objects for ProtoBuf , ProtoBuf::Arena , and ProtoBuf::DescriptorPool .
* Link each XS module against the common static library.
* Define custom compilation rules in MY::postamble to handle C vs. C++ flags and build the static library.
* Set up include paths for the project root, UPB, and other dependencies.
* **XS Stubs ( .xs files)**:
* lib/ProtoBuf.xs : Placeholder for the main module's XS functions.
* lib/ProtoBuf/Arena.xs : XS interface for upb_Arena management.
* lib/ProtoBuf/DescriptorPool.xs : XS interface for upb_DefPool management.
* **Perl Module Stubs ( .pm files)**:
* lib/ProtoBuf.pm : Main module, loads XS.
* lib/ProtoBuf/Arena.pm : Perl class for Arenas.
* lib/ProtoBuf/DescriptorPool.pm : Perl class for Descriptor Pools.
* lib/ProtoBuf/Message.pm : Base class for messages (TBD).
* **Configuration Files**:
* .gitignore : Ignores build artifacts, editor files, etc.
* .perlcriticrc : Configures Perl::Critic for static analysis.
* .perltidyrc : Configures perltidy for code formatting.
* ** Devel::PPPort **: Vendored version 3.72 to generate ppport.h for XS compatibility across different Perl versions.
* ** typemap **: Custom typemap for XS argument/result conversion.
* **Documentation ( doc/ )**: Initial architecture and plan documents.
This provides a solid foundation for developing the UPB-based Perl extension.
Introduction
I am Spaarsh Thakkar, a final-year Computer Science Engineering undergrad from India. My interests lie in research and systems. My recent work has been in and around Graphics Processing Units and I also hold a keen interest in Computer Networks. At the time of writing, I have been an open-source contributor for almost a year.
Proposal Description (as shown on GSoC Project Profile1)
Due to Debian s open-source nature, no Debian package in main can have a proprietary GPU package listed as a dependency. While AI and HPC workloads increasingly rely on GPU acceleration, many Debian packages still focus solely on CUDA, which is proprietary.
With the advent of ROCm, an open-source GPU computing platform, we can now integrate full-fledged AMD GPU support into Debian packages. This will improve the experience of developers working in AI/ML and HPC while positioning Debian as a strong OS choice for GPU-driven workloads. The proposal aims to aid in solving the aforementioned program by packaging several ROCm packages for debian and add ROCm support to some existing debian packages.
The deliverables are as follows:
New Debian packages with GPU support
Enhanced GPU support within existing Debian packages
More autopackagetests running on the Debian ROCm CI
Key Objectives
Enable ROCm in:
dbcsr
gloo
cp2k
Publish the following packages to debian apt archive:
hipblas-common
hipBLASlt
Work Report
1. Publishing hipblas-common to apt
This objective was successfully completed, resulting in hipblas-common being published in the apt repository2.
The process involved the following steps:
Securing sponsorship, which led to the package being accepted into the experimental branch of apt
Since the beginning of GSoC, the package has also been promoted to the unstable branch2.
2. DBCSR ROCm and Multi-Arch Support
During my GSoC project, I worked on extending the DBCSR (Distributed Block Compressed Sparse Row)7 package to improve its ROCm/HIP support, and handling multi-architecture GPU kernels in a way that is both practical for upstream maintainers and debian package developers.
The code changes can be found at my dbcsr fork here8.
ROCm/HIP Enablement
Enabled ROCm backend support to DBCSR, allowing GPU acceleration beyond CUDA by enabling HIP-based builds.
Investigated and resolved build issues specific to HIP kernels within DBCSR.
Multi-Architecture GPU Kernel Handling
(The following content was presented in greater detail at DebConf 25 as well. The presentation video can be found here9 and the presentation slide can be found here10).
DBCSR contains GPU kernels that are heavily optimized for specific architectures. By default, these are built for a single target architecture, which poses challenges for packaging where binaries need to support multiple possible GPU targets.
Explored different strategies for solving the multi-arch GPU kernel distribution problem, including:
Option 1: Fat binaries (embedding multiple GPU architectures into a single binary, with runtime dispatch). This is ideal for end-users but requires deeper changes upstream and is not straightforward with HIP/ROCm.
Option 2: Arch-specific libraries (e.g., libdbcsr.gfxXXX.a), where the alternatives system or explicit user selection would determine which one is used. This solves the problem but pushes complexity downstream into packaging and user configuration.
Option 3: Prefixed functions inside a single file, where kernels are compiled separately per architecture, functions are renamed with an arch prefix, and runtime logic in DBCSR decides which kernel to invoke. This shifts complexity upstream but could give a clean downstream experience.
I critically analyzed these options in the context of Debian packaging and upstream maintainability. Arch-specific .a files introduce exponential dependency complexity. The prefixed-function approach seemed like a plausible way forward, though it requires upstream buy-in.
After consulting with my mentor, these concerns were raised in the dbcsr repository as a discussion here11
Summary
My work involved:
Enabling HIP/ROCm support in DBCSR.
Prototyping strategies for handling GPU multi-arch builds.
Evaluating the trade-offs between upstream maintainability and downstream packaging complexity.
3. gloo, hipification and source code issues
One of the other packages that were targeted was gloo12. It is a collective communications library and has the implementations of different Machine Learning communication algorithms.
The code changes can be found at my gloo fork here13 (some changes have not be committed at the time of writing).
HIP/ROCm Enablement
Fixing old ROCm CMake functions
The upstream Gloo codebase still used old ROCm CMake functions that began with the hip_ prefix (for example, hip_add_executable). These functions have since been deprecated/removed. I updated the build system to use the modern ROCm CMake equivalents so that the package can build properly in a current ROCm environment.
Debian packaging changes
I modified debian/control to add a new package, libgloo-rocm, in addition to the existing packages. This allows proper separation and handling of ROCm-enabled builds in Debian.
First successful library build
After these changes, I was able to successfully build the library. However, I ran into issues when trying to produce the shared library: there were undefined symbol errors at link time.
Source Code Issue
On investigating the undefined symbol errors, I identified that these came from a lack of explicit template instantiation for some Gloo classes. Since C++ templates only get compiled when explicitly used or instantiated, this resulted in missing symbols in the shared library.
To solve this, I explored the source code and noticed that the HIP backend code was not natively written it was generated from the CUDA backend using a custom hipification script maintained by the repo.
I experimented with modifying the HIPification process itself, trying out hipify-perl14 instead of the repository s custom Python script.
I also tried tweaking the source code in places where template instantiations were missing, so that the ROCm build would correctly export the needed symbols.
Summary
The issue is still unresolved. The core problem lies in how the source code is structured: the HIP backend is almost entirely auto-generated from CUDA code, and the process does not handle template instantiations correctly. Because of this, the Debian package for Gloo with ROCm support is not yet ready for release, and further source-level fixes are required to make the ROCm build reliable.
4. cp2kCP2K15 is a quantum chemistry and solid state physics software package that can perform atomistic simulations of solid state, liquid, molecular, periodic, material, crystal, and biological systems.
HIP/ROCm Enablement
cp2k depends on dbcsr and hence, HIP/ROCm enablement in this package required the dbcsr16 package to get through.
Even though dbcsr isn t ready yet, it was worthwhile to plan how it shall be built with HIP/ROCm once we have dbcsr in place. Upon doing this, it was realized that the architecture-wise libraries provided by the dbcsr package will result in a complicated building process for cp2k.
No changes have been made to this package yet and more concrete steps shall be taken once the dbcsr package work is completed.
Summary
The multi-arch build process for cp2k maybe complicated by the one static-library-per-architecture method used in the dependent package, dbcsr.
Auxiliary Work & Activities
While working on the aformentioned GSoC Goals, there were a few other things that were also done.
libamdhip64-dev bug file17
While trying to enable HIP/ROCm in dbcsr, CMakeDetermineHIPCompiler.cmake was unable to find HIP runtime CMake package. After going through some similar issues faced by other developers earlier, it was decided to file a bug report under the libamdhip64-dev package.
After discussions with and trying the changes suggested by Cory (my mentor) under the bug, the issue was resolved.
Turns out, the wrong compiler was being used by me! The gcc compiler was supposed to be used and I was using hipcc. The bug was closed since it was not due an issue with the package.
Cory suggested that I add this info under the ROCm wiki page. It is yet to be done and hopefully I get it done soon.
DebConf25 Talk
After facing the multi-arch build dilemma with dbcsr (and also getting to know about the issues faced by other fellow package developers), I came to realise that this was more than a packaging, build or programming issue. GPU-packaging was facing a policy issue.
Hence, I decided to cover this problem in greater detail at my DebConf25 Virtual Presentation under the Outreach Session.
Shoutout to Cory for his support and Lucas Kanashiro for encouraging me to present my work!
Bi-Weekly AMD ROCm Meetings
Shortly after the Coding period started, Cory began the initiative of Bi-Weekly AMD ROCm Meetings18. Being a part of the meetings (participated in all but one!), seeing the work the other folks are doing and being able to discuss my own problems was a delight.
(Upcoming) IndiaFOSS 2025 Talk
After understanding the nuances and beauty of the debian packaging ecosystem in these months, I decided to spread the work about debian packaging and packaging software in general. My talk19 for the same got accepted in the upcoming IndiaFOSS 202520 conference!
I hope this beings more people towards the packaging ecosystem and to the debian developer ecosystem.
Conclusion
My GSoC time was fantastic! I plan to complete the work that I have started during my GSoC and beyond. Working with Cory21 and Utkarsh22 (a fellow GSoC 25 contributor under Cory) has been a very positive experience.
HIP/ROCm GPU-packaging is in a nascent stage. It is an exciting time to be in this space right now. The problems are new and never encountered before (CPU packaging isn t architecture specific!). The problems were shall face in the coming time, and our solutions to them will set a precendent for the future.
tl;dr: there is an attack in the wild which is triggering dangerous-but-seemingly-intended behaviour in the Oj JSON parser when used in the default and recommended manner, which can lead to everyone s favourite kind of security problem: object deserialization bugs!
If you have the oj gem anywhere in your Gemfile.lock, the quickest mitigation is to make sure you have Oj.default_options = mode: :strict somewhere, and that no library is overwriting that setting to something else.
Prologue
As a sensible sysadmin, all the sites I run send me a notification if any unhandled exception gets raised.
Mostly, what I get sent is error-handling corner cases I missed, but now and then things get more interesting.
In this case, it was a PG::UndefinedColumn exception, which looked something like this:
PG::UndefinedColumn: ERROR: column "xyzzydeadbeef" does not exist
This is weird on two fronts: firstly, this application has been running for a while, and if there was a schema problem, I d expect it to have made itself apparent long before now.
And secondly, while I don t profess to perfection in my programming, I m usually better at naming my database columns than that.
Something is definitely hinky here, so let s jump into the mystery mobile!
The column name is coming from outside the building!
The exception notifications I get sent include a whole lot of information about the request that caused the exception, including the request body.
In this case, the request body was JSON, and looked like this:
"name":":xyzzydeadbeef", ...
The leading colon looks an awful lot like the syntax for a Ruby symbol, but it s in a JSON string.
Surely there s no way a JSON parser would be turning that into a symbol, right?
Right?!?
Immediately, I thought that that possibly was what was happening, because I use Sequel for my SQL database access needs, and Sequel treats symbols as database column names.
It seemed like too much of a coincidence that a vaguely symbol-shaped string was being sent in, and the exact same name was showing up as a column name.
But how the flying fudgepickles was a JSON string being turned into a Ruby symbol, anyway?
Enter Oj.
Oj? I barely know aj
A long, long time ago, the standard Ruby JSON library had a reputation for being slow.
Thus did many competitors flourish, claiming more features and better performance.
Strong amongst the contenders was oj (for Optimized JSON ), touted as The fastest JSON parser and object serializer .
Given the history, it s not surprising that people who wanted the best possible performance turned to Oj, leading to it being found in a great many projects, often as a sub-dependency of a dependency of a dependency (which is how it ended up in my project).
You might have noticed in Oj s description that, in addition to claiming fastest , it also describes itself as an object serializer .
Anyone who has kept an eye on the security bug landscape will recall that object deserialization is a rich vein of vulnerabilities to mine.
Libraries that do object deserialization, especially ones with a history that goes back to before the vulnerability class was well-understood, are likely to be trouble magnets.
And thus, it turns out to be with Oj.
By default, Oj will happily turn any string that starts with a colon into a symbol:
How that gets exploited is only limited by the creativity of an attacker.
Which I ll talk about more shortly but first, a word from my rant cortex.
Insecure By Default is a Cancer
While the object of my ire today is Oj and its fast-and-loose approach to deserialization, it is just one example of a pervasive problem in software: insecurity by default.
Whether it s a database listening on 0.0.0.0 with no password as soon as its installed, or a library whose default behaviour is to permit arbitrary code execution, it all contributes to a software ecosystem that is an appalling security nightmare.
When a user (in this case, a developer who wants to parse JSON) comes across a new piece of software, they have by definition no idea what they re doing with that software.
They re going to use the defaults, and follow the most easily-available documentation, to achieve their goal.
It is unrealistic to assume that a new user of a piece of software is going to do things the right way , unless that right way is the only way, or at least the by-far-the-easiest way.
Conversely, the developer(s) of the software is/are the domain experts.
They have knowledge of the problem domain, through their exploration while building the software, and unrivalled expertise in the codebase.
Given this disparity in knowledge, it is tantamount to malpractice for the experts the developer(s) to off-load the responsibility for the safe and secure use of the software to the party that has the least knowledge of how to do that (the new user).
To apply this general principle to the specific case, take the Using section of the Oj README.
The example code there calls Oj.load, with no indication that this code will, in fact, parse specially-crafted JSON documents into Ruby objects.
The brand-user user of the library, no doubt being under pressure to Get Things Done, is almost certainly going to look at this Using example, get the apparent result they were after (a parsed JSON document), and call it a day.
It is unlikely that a brand-new user will, for instance, scroll down to the Further Reading section, find the second last (of ten) listed documents, Security.md , and carefully peruse it.
If they do, they ll find an oblique suggestion that parsing untrusted input is never a good idea .
While that s true, it s also rather unhelpful, because I d wager that by far the majority of JSON parsed in the world is untrusted , in one way or another, given the predominance of JSON as a format for serializing data passing over the Internet.
This guidance is roughly akin to putting a label on a car s airbags that driving at speed can be hazardous to your health : true, but unhelpful under the circumstances.
The solution is for default behaviours to be secure, and any deviation from that default that has the potential to degrade security must, at the very least, be clearly labelled as such.
For example, the Oj.load function should be named Oj.unsafe_load, and the Oj.load function should behave as the Oj.safe_load function does presently.
By naming the unsafe function as explicitly unsafe, developers (and reviewers) have at least a fighting chance of recognising they re doing something risky.
We put warning labels on just about everything in the real world; the same should be true of dangerous function calls.
OK, rant over.
Back to the story.
But how is this exploitable?
So far, I ve hopefully made it clear that Oj does some Weird Stuff with parsing certain JSON strings.
It caused an unhandled exception in a web application I run, which isn t cool, but apart from bombing me with exception notifications, what s the harm?
For starters, let s look at our original example: when presented with a symbol, Sequel will interpret that as a column name, rather than a string value.
Thus, if our save an update to the user code looked like this:
# request_body has the JSON representation of the form being submitted
body = Oj.load(request_body)
DB[:users].where(id: user_id).update(name: body["name"])
In normal operation, this will issue an SQL query along the lines of UPDATE users SET name='Jaime' WHERE id=42.
If the name given is Jaime O Dowd , all is still good, because Sequel quotes string values, etc etc.
All s well so far.
But, imagine there is a column in the users table that normally users cannot read, perhaps admin_notes.
Or perhaps an attacker has gotten temporary access to an account, and wants to dump the user s password hash for offline cracking.
So, they send an update claiming that their name is :admin_notes (or :password_hash).
In JSON, that ll look like "name":":admin_notes" , and Oj.load will happily turn that into a Ruby object of "name"=>:admin_notes .
When run through the above update the user code fragment, it ll produce the SQL UPDATE users SET name=admin_notes WHERE id=42.
In other words, it ll copy the contents of the admin_notes column into the name column which the attacker can then read out just by refreshing their profile page.
But Wait, There s More!
That an attacker can read other fields in the same table isn t great, but that s barely scratching the surface.
Remember before I said that Oj does object serialization ?
That means that, in general, you can create arbitrary Ruby objects from JSON.
Since objects contain code, it s entirely possible to trigger arbitrary code execution by instantiating an appropriate Ruby object.
I m not going to go into details about how to do this, because it s not really my area of expertise, and many others have covered it in detail.
But rest assured, if an attacker can feed input of their choosing into a default call to Oj.load, they ve been handed remote code execution on a platter.
Mitigations
As Oj s object deserialization is intended and documented behaviour, don t expect a future release to make any of this any safer.
Instead, we need to mitigate the risks.
Here are my recommended steps:
Look in your Gemfile.lock (or SBOM, if that s your thing) to see if the oj gem is anywhere in your codebase.
Remember that even if you don t use it directly, it s popular enough that it is used in a lot of places.
If you find it in your transitive dependency tree anywhere, there s a chance you re vulnerable, limited only by the ingenuity of attackers to feed crafted JSON into a deeply-hidden Oj.load call.
If you depend on oj directly and use it in your project, consider not doing that.
The json gem is acceptably fast, and JSON.parse won t create arbitrary Ruby objects.
If you really, really need to squeeze the last erg of performance out of your JSON parsing, and decide to use oj to do so, find all calls to Oj.load in your code and switch them to call Oj.safe_load.
It is a really, really bad idea to ever use Oj to deserialize JSON into objects, as it lacks the safety features needed to mitigate the worst of the risks of doing so (for example, restricting which classes can be instantiated, as is provided by the permitted_classes argument to Psych.load).
I d make it a priority to move away from using Oj for that, and switch to something somewhat safer (such as the aforementioned Psych).
At the very least, audit and comment heavily to minimise the risk of user-provided input sneaking into those calls somehow, and pass mode: :object as the second argument to Oj.load, to make it explicit that you are opting-in to this far more dangerous behaviour only when it s absolutely necessary.
To secure any unsafe uses of Oj.load in your dependencies, consider setting the default Oj parsing mode to :strict, by putting Oj.default_options = mode: :strict somewhere in your initialization code (and make sure no dependencies are setting it to something else later!).
There is a small chance that this change of default might break something, if a dependency is using Oj to deliberately create Ruby objects from JSON, but the overwhelming likelihood is that Oj s just being used to parse ordinary JSON, and these calls are just RCE vulnerabilities waiting to give you a bad time.
Is Your Bacon Saved?
If I ve helped you identify and fix potential RCE vulnerabilities in your software, or even just opened your eyes to the risks of object deserialization, please help me out by buying me a refreshing beverage.
I would really appreciate any support you can give.
Alternately, if you d like my help in fixing these (and many other) sorts of problems, I m looking for work, so email me.
Everybody is trying out AI assistants these days, so I figured I'd jump on that train and see how fast it derails.
I went with CodeRabbit because I've seen it on YouTube ads work, I guess.
I am trying to answer the following questions:
Did the AI find things that humans did not find (or didn't bother to mention)
Did the AI output help the humans with the review (useful summary etc)
Did the AI output help the humans with the code (useful suggestions etc)
Was the AI output misleading?
Was the AI output distracting?
To reduce the amount of output and not to confuse contributors, CodeRabbit was configured to only do reviews on demand.
What follows is a rather unscientific evaluation of CodeRabbit based on PRs in two Foreman-related repositories,
looking at the summaries CodeRabbit posted as well as the comments/suggestions it had about the code.
Ansible 2.19 support
PR: theforeman/foreman-ansible-modules#1848
summary posted
The summary CodeRabbit posted is technically correct.
This update introduces several changes across CI configuration, Ansible roles, plugins, and test playbooks. It expands CI test coverage to a new Ansible version, adjusts YAML key types in test variables, refines conditional logic in Ansible tasks, adds new default variables, and improves clarity and consistency in playbook task definitions and debug output.
Yeah, it does all of that, all right.
But it kinda misses the point that the addition here is "Ansible 2.19 support", which starts with adding it to the CI matrix and then adjusting the code to actually work with that version.
Also, the changes are not for "clarity" or "consistency", they are fixing bugs in the code that the older Ansible versions accepted, but the new one is more strict about.
Then it adds a table with the changed files and what changed in there.
To me, as the author, it felt redundant, and IMHO doesn't add any clarity to understand the changes.
(And yes, same "clarity" vs bugfix mistake here, but that makes sense as it apparently miss-identified the change reason)
And then the sequence diagrams
They probably help if you have a dedicated change to a library or a library consumer,
but for this PR it's just noise, especially as it only covers two of the changes (addition of 2.19 to the test matrix and a change to the inventory plugin), completely ignoring other important parts.
Overall verdict: noise, don't need this.
comments posted
CodeRabbit also posted 4 comments/suggestions to the changes.
Guard against undefined result.task
IMHO a valid suggestion, even if on the picky side as I am not sure how to make it undefined here.
I ended up implementing it, even if with slightly different (and IMHO better readable) syntax.
Valid complaint? Probably.
Useful suggestion? So-So.
Wasted time? No.
Inconsistent pipeline in when for composite CV versions
That one was funny! The original complaint was that the when condition used slightly different data manipulation than the data that was passed when the condition was true.
The code was supposed to do "clean up the data, but only if there are any items left after removing the first 5, as we always want to keep 5 items".
And I do agree with the analysis that it's badly maintainable code.
But the suggested fix was to re-use the data in the variable we later use for performing the cleanup.
While this is (to my surprise!) valid Ansible syntax, it didn't make the code much more readable as you need to go and look at the variable definition.
The better suggestion then came from Ewoud: to compare the length of the data with the number we want to keep.
Humans, so smart!
But Ansible is not Ewoud's native turf, so he asked whether there is a more elegant way to count how much data we have than to use list count in Jinja (the data comes from a Python generator, so needs to be converted to a list first).
And the AI helpfully suggested to use count instead!
However, count is just an alias for length in Jinja, so it behaves identically and needs a list.
Luckily the AI quickly apologized for being wrong after being pointed at the Jinja source and didn't try to waste my time any further.
Wouldn't I have known about the count alias, we'd have committed that suggestion and let CI fail before reverting again.
Valid complaint? Yes.
Useful suggestion? Nope.
Wasted time? Yes.
Apply the same fix for non-composite CV versions
The very same complaint was posted a few lines later, as the logic there is very similar just slightly different data to be filtered and cleaned up.
Interestingly, here the suggestion also was to use the variable.
But there is no variable with the data!
The text actually says one need to "define" it, yet the "committable suggestion" doesn't contain that part.
Interestingly, when asked where it sees the "inconsistency" in that hunk, it said the inconsistency is with the composite case above.
That however is nonsense, as while we want to keep the same number of composite and non-composite CV versions,
the data used in the task is different it even gets consumed by a totally different playbook so there can't be any real consistency between the branches.
Valid complaint? Yes (the expression really could use some cleanup).
Useful suggestion? Nope.
Wasted time? Yes.
I ended up applying the same logic as suggested by Ewoud above.
As that refactoring was possible in a consistent way.
Ensure consistent naming for Oracle Linux subscription defaults
One of the changes in Ansible 2.19 is that Ansible fails when there are undefined variables, even if they are only undefined for cases where they are unused.
CodeRabbit complains that the names of the defaults I added are inconsistent.
And that is technically correct.
But those names are already used in other places in the code, so I'd have to refactor more to make it work properly.
Once being pointed at the fact that the variables already exist,
the AI is as usual quick to apologize, yay.
The repository module was updated to support additional parameters for repository synchronization and authentication. New options were added for ansible collections, ostree, Python packages, and yum repositories, including authentication tokens, filtering controls, and version retention settings. All changes were limited to module documentation and argument specification.
But it doesn't add anything you'd not get from looking at the diff, especially as it contains a large documentation chunk explaining those parameters.
No sequence diagram this time.
That's a good thing!
Overall verdict: noise (even if the amount is small), don't need this.
comments posted
CodeRabbit generated two comments for this PR.
Interestingly, none of them overlapped with the issues ansible-lint and friends found.
get rid of the FIXMEs
Yepp, that's fair
Valid complaint? Yes.
Useful suggestion? Nope. (But it's not possible in this case!)
Wasted time? No.
add validation for the new parameters
Yepp, I forgot these (not intentionally!).
The diff it suggests is nonsense, as it doesn't take into account the existing Ansible and Yum validations, but it clearly has read them as the style etc of the new ones matches.
It also managed to group the parameters correctly by repository type, so it's something.
ifmodule.foreman_params['content_type']!='ansible_collection':invalid_list=[keyforkeyin['ansible_collection_requirements']ifkeyinmodule.foreman_params]ifinvalid_list:module.fail_json(msg="( 0 ) can only be used with content_type 'ansible_collection'".format(",".join(invalid_list)))++#Validateansible_collectionspecificparameters+ifmodule.foreman_params['content_type']!='ansible_collection':+invalid_list=[keyforkeyin['ansible_collection_auth_token','ansible_collection_auth_url']ifkeyinmodule.foreman_params]+ifinvalid_list:+module.fail_json(msg="( 0 ) can only be used with content_type 'ansible_collection'".format(",".join(invalid_list)))++#Validateostreespecificparameters+ifmodule.foreman_params['content_type']!='ostree':+invalid_list=[keyforkeyin['depth','exclude_refs','include_refs']ifkeyinmodule.foreman_params]+ifinvalid_list:+module.fail_json(msg="( 0 ) can only be used with content_type 'ostree'".format(",".join(invalid_list)))++#Validatepythonpackagespecificparameters+ifmodule.foreman_params['content_type']!='python':+invalid_list=[keyforkeyin['excludes','includes','package_types','keep_latest_packages']ifkeyinmodule.foreman_params]+ifinvalid_list:+module.fail_json(msg="( 0 ) can only be used with content_type 'python'".format(",".join(invalid_list)))++#Validateyumspecificparameter+ifmodule.foreman_params['content_type']!='yum'and'upstream_authentication_token'inmodule.foreman_params:+module.fail_json(msg="upstream_authentication_token can only be used with content_type 'yum'")
Interestingly, it also said "Note: If 'python' is not a valid content_type, please adjust the validation accordingly." which is quite a hint at a bug in itself.
The module currently does not even allow to create content_type=python repositories.
That should have been more prominent, as it's a BUG!
Valid complaint? Yes.
Useful suggestion? Mostly (I only had to merge the Yum and Ansible branches with the existing code).
Wasted time? Nope.
parameter persistence in obsah
PR: theforeman/obsah#72
summary posted
Mostly correct.
It did miss-interpret the change to a test playbook as an actual "behavior" change:
"Introduced new playbook variables for database configuration" there is no database configuration in this repository, just the test playbook using the same metadata as a consumer of the library.
Later on it does say "Playbook metadata and test fixtures", so unclear whether this is a miss-interpretation or just badly summarized.
As long as you also look at the diff, it won't confuse you, but if you're using the summary as the sole source of information (bad!) it would.
This time the sequence diagram is actually useful, yay.
Again, not 100% accurate: it's missing the fact that saving the parameters is hidden behind an "if enabled" flag something it did represent correctly for loading them.
Overall verdict: not really useful, don't need this.
comments posted
Here I was a bit surprised, especially as the nitpicks were useful!
Persist-path should respect per-user state locations (nitpick)
My original code used os.environ.get('OBSAH_PERSIST_PATH', '/var/lib/obsah/parameters.yaml') for the location of the persistence file.
CodeRabbit correctly pointed out that this won't work for non-root users and one should respect XDG_STATE_HOME.
Ewoud did point that out in his own review, so I am not sure whether CodeRabbit came up with this on its own, or also took the human comments into account.
The suggested code seems fine too just doesn't use /var/lib/obsah at all anymore.
This might be a good idea for the generic library we're working on here, and then be overridden to a static /var/lib path in a consumer (which always runs as root).
In the end I did not implement it, but mostly because I was lazy and was sure we'd override it anyway.
Valid complaint? Yes.
Useful suggestion? Yes.
Wasted time? Nope.
Positional parameters are silently excluded from persistence (nitpick)
The library allows you to generate both positional (foo without --) and non-positional (--foo) parameters, but the code I wrote would only ever persist non-positional parameters.
This was intentional, but there is no documentation of the intent in a comment which the rabbit thought would be worth pointing out.
It's a fair nitpick and I ended up adding a comment.
Valid complaint? Yes.
Useful suggestion? Yes.
Wasted time? Nope.
Enforce FQDN validation for database_host
The library has a way to perform type checking on passed parameters, and one of the supported types is "FQDN" so a fully qualified domain name, with dots and stuff.
The test playbook I added has a database_host variable, but I didn't bother adding a type to it, as I don't really need any type checking here.
While using "FQDN" might be a bit too strict here technically a working database connection can also use a non-qualified name or an IP address, I was positively surprised by this suggestion.
It shows that the rest of the repository was taken into context when preparing the suggestion.
Valid complaint? In the context of a test, no. Would that be a real command definition, yes.
Useful suggestion? Yes.
Wasted time? Nope.
reset_args() can raise AttributeError when a key is absent
This is a correct finding, the code is not written in a way that would survive if it tries to reset things that are not set.
However, that's only true for the case where users pass in --reset-<parameter> without ever having set parameter before.
The complaint about the part where the parameter is part of the persisted set but not in the parsed args is wrong as parsed args inherit from the persisted set.
The suggested code is not well readable, so I ended up fixing it slightly differently.
Valid complaint? Mostly.
Useful suggestion? Meh.
Wasted time? A bit.
Persisted values bypass argparse type validation
When persisting, I just yaml.safe_dump the parsed parameters, which means the YAML will contain native types like integers.
The argparse documentation warns that the type checking argparse does only applies to strings and is skipped if you pass anything else (via default values).
While correct, it doesn't really hurt here as the persisting only happens after the values were type-checked.
So there is not really a reason to type-check them again.
Well, unless the type changes, anyway.
Not sure what I'll do with this comment.
Valid complaint? Nah.
Useful suggestion? Nope.
Wasted time? Not much.
consider using contextlib.suppress
This was added when I asked CodeRabbit for a re-review after pushing some changes.
Interestingly, the PR already contained try: except: pass code before, and it did not flag that.
Also, the code suggestion contained import contextlib in the middle of the code, instead in the head of the file.
Who would do that?!
But the comment as such was valid, so I fixed it in all places it is applicable, not only the one the rabbit found.
A workaround was added to the _update_entity method in the ForemanAnsibleModule class to ensure that when updating a host, both content_view_id and lifecycle_environment_id are always included together in the update payload. This prevents partial updates that could cause inconsistencies.
Partial updates are not a thing.
The workaround is purely for the fact that Katello expects both parameters to be sent,
even if only one of them needs an actual update.
No diagram, good.
Overall verdict: misleading summaries are bad!
comments posted
Given a small patch, there was only one comment.
Implementation looks correct, but consider adding error handling for robustness.
This reads correct on the first glance.
More error handling is always better, right?
But if you dig into the argumentation, you see it's wrong.
Either:
we're working with a Katello setup and the host we're updating has content, so CV and LCE will be present
we're working with a Katello setup and the host has no content (yet), so CV and LCE will be "updated" and we're not running into the workaround
we're working with a plain Foreman, then both parameters are not even accepted by Ansible
The AI accepted defeat once I asked it to analyze things in more detail, but why did I have to ask in the first place?!
Valid complaint? Nope.
Useful suggestion? Nope.
Wasted time? Yes, as I've actually tried to come up with a case where it can happen.
Summary
Well, idk, really.
Did the AI find things that humans did not find (or didn't bother to mention)?
Yes. It's debatable whether these were useful (see e.g. the database_host example), but I tend to be in the "better to nitpick/suggest more and dismiss than oversee" team, so IMHO a positive win.
Did the AI output help the humans with the review (useful summary etc)?
In my opinion it did not.
The summaries were either "lots of words, no real value" or plain wrong.
The sequence diagrams were not useful either.
Luckily all of that can be turned off in the settings, which is what I'd do if I'd continue using it.
Did the AI output help the humans with the code (useful suggestions etc)?
While the actual patches it posted were "meh" at best, there were useful findings that resulted in improvements to the code.
Was the AI output misleading?
Absolutely! The whole Jinja discussion would have been easier without the AI "help".
Same applies for the "error handling" in the workaround PR.
Was the AI output distracting?
The output is certainly a lot, so yes I think it can be distracting.
As mentioned, I think dropping the summaries can make the experience less distracting.
What does all that mean?
I will disable the summaries for the repositories, but will leave the @coderabbitai review trigger active if someone wants an AI-assisted review.
This won't be something that I'll force on our contributors and maintainers, but they surely can use it if they want.
But I don't think I'll be using this myself on a regular basis.
Yes, it can be made "usable". But so can be vim ;-)
Also, I'd prefer to have a junior human asking all the questions and making bad suggestions, so they can learn from it, and not some planet burning machine.
Python's os.path.abspath
or Path.absolute
are great: you give them a path, which might not exist, and you get a path you
can use regardless of the current directory. os.path.abspath will also
normalize it, while Path will not by default because with Paths a normal
form is less needed.
This is great to normalize input, regardless of if it's an existing file you're
needing to open, or a new file you're needing to create.
In C++17, there is a filesystem library with
methods with enticingly similar names, but which are almost, but not quite,
totally unlike Python's abspath.
Because in my C++ code I need to normalize input, regardless of if it's an
existing file I'm needing to open or a new file I'm needing to create, here's
an apparently working Python-like abspath for C++ implemented on top of the
std::filesystem library:
std::filesystem::pathabspath(conststd::filesystem::path&path)// weakly_canonical is defined as "the result of calling canonical() with a// path argument composed of the leading elements of p that exist (as// determined by status(p) or status(p, ec)), if any, followed by the// elements of p that do not exist."//// This means that if no lead components of the path exist then the// resulting path is not made absolute, and we need to work around that.if(!path.is_absolute())returnabspath(std::filesystem::current_path()/path);// This is further and needlessly complicated because we need to work// around https://gcc.gnu.org/bugzilla/show_bug.cgi?id=118733unsignedretry=0;while(true)std::error_codecode;autoresult=std::filesystem::weakly_canonical(path,code);if(!code)// fprintf(stderr, "%s: ok in %u tries\n", path.c_str(), retry+1);returnresult;if(code==std::errc::no_such_file_or_directory)++retry;if(retry>50)throwstd::system_error(code);elsethrowstd::system_error(code);// Alternative implementation that however may not work on all platforms// since, formally, "[std::filesystem::absolute] Implementations are// encouraged to not consider p not existing to be an error", but they do// not mandate it, and if they did, they might still be affected by the// undefined behaviour outlined in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=118733//// return std::filesystem::absolute(path).lexically_normal();
I added it to my wobble
code repository, which is the thin repository of components I use to ease my
C++ systems programming.
Fun with -fsanitize=undefined and Picolibc
Both GCC and Clang support the -fsanitize=undefined flag which
instruments the generated code to detect places where the program
wanders into parts of the C language specification which are either
undefined or implementation defined. Many of these are also common
programming errors. It would be great if there were sanitizers for
other easily detected bugs, but for now, at least the undefined
sanitizer does catch several useful problems.
Supporting the sanitizer
The sanitizer can be built to either trap on any error or call
handlers. In both modes, the same problems are identified, but when
trap mode is enabled, the compiler inserts a trap instruction and
doesn't expect the program to continue running. When handlers are in
use, each identified issue is tagged with a bunch of useful data and
then a specific sanitizer handling function is called.
The specific functions are not all that well documented, nor are the
parameters they receive. Maybe this is because both compilers provide
an implementation of all of the functions they use and don't really
expect external implementations to exist? However, to make these useful in an
embedded environment, picolibc needs to provide a complete set of
handlers that support all versions both gcc and clang as the
compiler-provided versions depend upon specific C (and C++) libraries.
Of course, programs can be built in trap-on-error mode, but that makes
it much more difficult to figure out what went wrong.
Fixing Sanitizer Issues
Once the sanitizer handlers were implemented, picolibc could be
built with them enabled and all of the picolibc tests run to uncover
issues within the library.
As with the static analyzer adventure from last year, the vast bulk of
sanitizer complaints came from invoking undefined or
implementation-defined behavior in harmless ways:
Computing pointers past &array[size+1]. I found no cases where the
resulting pointers were actually used, but the mere computation is
still undefined behavior. These were fixed by adjusting the code to
avoid computing pointers like this. The result was clearer code,
which is good.
Signed arithmetic overflow in PRNG code. There are several linear
congruential PRNGs in the library which used signed integer
arithmetic. The rand48 generator carefully used unsigned short
values. Of course, in C, the arithmetic performed on them is done
with signed ints if int is wider than short. C specifies signed
overflow as undefined, but both gcc and clang generate the expected
code anyways. The fixes here were simple; just switch the
computations to unsigned arithmetic, adjusting types and inserting
casts as required.
Passing pointers to the middle of a data structure. For example,
free takes a pointer to the start of an allocation. The management
structure appears just before that in memory; computing the address
of which appears to be undefined behavior to the compiler. The only
fix I could do here was to disable the sanitizer in functions doing
these computations -- the sanitizer was mis-detecting correct code
and it doesn't provide a way to skip checks on a per-operator
basis.
Null pointer plus or minus zero. C says that any arithmetic with
the NULL pointer is undefined, even when the value being added or
subtracted is zero. The fix here was to create a macro, enabled
only when the sanitizer is enabled, which checks for this case and
skips the arithmetic.
Discarded computations which overflow. A couple of places computed
a value, then checked if that would have overflowed and discard the
result. Even though the program doesn't depend upon the
computation, its mere presence is undefined behavior. These were
fixed by moving the computation into an else clause in the
overflow check. This inserts an extra branch instruction, which is
annoying.
Signed integer overflow in math code. There's a common pattern
in various functions that want to compare against 1.0. Instead of
using the floating point equality operator, they do the computation
using the two 32-bit halves with ((hi - 0x3ff00000) lo)
== 0. It's efficient, but because most of these functions store the
'hi' piece in a signed integer (to make checking the sign bit
fast), the result is undefined when hi is a large negative
value. These were fixed by inserting casts to unsigned types as the
results were always tested for equality.
Signed integer shifts
This is one area where the C language spec is just wrong.
For left shift, before C99, it worked on signed integers as a bit-wise
operator, equivalent to the operator on unsigned integers. After that,
left shift of negative integers became undefined. Fortunately, it's
straightforward (if tedious) to work around this issue by just casting
the operand to unsigned, performing the shift and casting it back to
the original type. Picolibc now has an internal macro, lsl, which
does this:
Right shift is significantly more complicated to implement. What we
want is an arithmetic shift with the sign bit being replicated as the
value is shifted rightwards. C defines no such operator. Instead,
right shift of negative integers is implementation
defined. Fortunately, both gcc and clang define the >> operator on
signed integers as arithmetic shift. Also fortunately, C hasn't made
this undefined, so the program itself doesn't end up undefined.
The trouble with arithmetic right shift is that it is not equivalent
to right shift of unsigned values. Here's what Per Vognsen came up
with using standard C operators:
int
__asr_int(int x, int s)
return x < 0 ? ~(~x >> s) : x >> s;
When the value is negative, we invert all of the bits (making it
positive), shift right, then flip all of the bits back. Both GCC and
Clang seem to compile this to a single asr instruction. This function
is replicated for each of the five standard integer types and then the
set of them wrapped in another sizeof-selecting macro:
The lsl and asr macros use sizeof instead of the type-generic
mechanism to remain compatible with compilers that lack type-generic
support.
Once these macros were written, they needed to be applied where
required. To preserve the benefits of detecting programming errors,
they were only applied where required, not blindly across the whole
codebase.
There are a couple of common patterns in the math code using shift
operators. One is when computing the exponent value for subnormal
numbers.
for (ix = -1022, i = hx << 11; i > 0; i <<= 1)
ix -= 1;
This code computes the exponent by shifting the significand left by 11
bits (the width of the exponent field) and then incrementally shifting
it one bit at a time until the sign flips, which indicates that the
most-significant bit is set. Use of the pre-C99 definition of the left
shift operator is intentional here; so both shifts are replaced with
our lsl operator.
In the implementation of pow, the final exponent is computed as the
sum of the two exponents, both of which are in the allowed range. The
resulting sum is then tested to see if it is zero or negative to see
if the final value is sub-normal:
hx += n << 20;
if (hx >> 20 <= 0)
/* do sub-normal things */
In this case, the exponent adjustment, n, is a signed value and so
that shift is replaced with the lsl macro. The test value needs to
compute the correct the sign bit, so we replace this with the asr
macro.
Because the right shift operation is not undefined, we only use our
fancy macro above when the undefined behavior sanitizer is enabled. On
the other hand, the lsl macro should have zero cost and covers
undefined behavior, so it is always used.
Actual Bugs Found!
The goal of this little adventure was both to make using the undefined
behavior sanitizer with picolibc possible as well as to use the
sanitizer to identify bugs in the library code. I fully expected that
most of the effort would be spent masking harmless undefined behavior
instances, but was hopeful that the effort would also uncover real
bugs in the code. I was not disappointed. Through this work, I found
(and fixed) eight bugs in the code:
setlocale/newlocale didn't check for NULL locale names
qsort was using uintptr_t to swap data around. On MSP430 in
'large' mode, that's a 20-bit type inside a 32-bit representation.
random() was returning values in int range rather than long.
m68k assembly for memcpy was broken for sizes > 64kB.
freopen returned NULL, even on success
The optimized version of memrchr was always performing unaligned
accesses.
String to float conversion had a table missing four values. This
caused an array access overflow which resulted in imprecise values
in some cases.
vfwscanf mis-parsed floating point values by assuming that
wchar_t was unsigned.
Sanitizer Wishes
While it's great to have a way to detect places in your C code which
evoke undefined and implementation defined behaviors, it seems like
this tooling could easily be extended to detect other common
programming mistakes, even where the code is well defined according to
the language spec. An obvious example is in unsigned arithmetic. How
many bugs come from this seemingly innocuous line of code?
p = malloc(sizeof(*p) * c);
Because sizeof returns an unsigned value, the resulting computation
never results in undefined behavior, even when the multiplication
wraps around, so even with the undefined behavior sanitizer enabled,
this bug will not be caught. Clang seems to have an unsigned integer
overflow sanitizer which should do this, but I couldn't find anything
like this in gcc.
Summary
The undefined behavior sanitizers present in clang and gcc both
provide useful diagnostics which uncover some common programming
errors. In most cases, replacing undefined behavior with defined
behavior is straightforward, although the lack of an arithmetic right
shift operator in standard C is irksome. I recommend anyone using C to
give it a try.
When I a few days ago discovered that a security problem reported
against the theora library last year was still not fixed, and because
I was already up to speed on Xiph development, I decided it was time
to wrap up a new theora release. This new release was tagged in
the Xiph gitlab theora
instance Saturday. You can fetch the new release from
the Theora home page.
The list of changes since The 1.2.0alpha1 release from the CHANGES
file in the tarball look like this:
libteora 1.2.0beta1 (2025 March 15)
Bumped minor SONAME versions as methods changed constness
of arguments.
Updated libogg dependency to version 1.3.4 for ogg_uint64_t.
Updated doxygen setup.
Updated autotools setup and support scripts (#1467 #1800 #1987 #2318
#2320).
Added support for RISC OS.
Fixed mingw build (#2141).
Improved ARM support.
Converted SCons setup to work with Python 3.
Introduced new configure options --enable-mem-constraint and
--enable-gcc-sanitizers.
Fixed all known compiler warnings and errors from gcc and clang.
Improved examples for stability and correctness.
Variuos speed, bug fixes and code quality improvements.
Fixed build problem with Visual Studio (#2317).
Avoids undefined bit shift of signed numbers (#2321, #2322).
Avoids example encoder crash on bogus audio input (#2305).
Fixed musl linking issue with asm enabled (#2287).
Fixed some broken clamping in rate control (#2229).
Added NULL check _tc and _setup even for data packets (#2279).
Updated the documentation for theora_encode_comment() (#726).
Adjusted build to Only link libcompat with dump_video (#1587).
Corrected an operator precedence error in the visualization
code (#1751).
Fixed two spelling errors in the comments (#1804).
Avoid negative bit shift operation in huffdec.c (CVE-2024-56431).
Improved library documentation and specification text.
Adjusted library dependencies so libtheoraenc do not depend on
libtheoradec.
Handle fallout from CVE-2017-14633 in libvorbis, check return value
in encoder_example and transcoder_example.
There are a few bugs still being investigated, and my plan is to
wrap up a final 1.2.0 release two weekends from now.
As usual, if you use Bitcoin and want to show your support of my
activities, please send Bitcoin donations to my address
15oWEoG9dUPovwmUL9KWAnYRtNJEkP1u1b.
Another minor update 0.3.11 for our nanotime
package is now on CRAN. nanotime
relies on the RcppCCTZ
package (as well as the RcppDate
package for additional C++ operations) and offers efficient high(er)
resolution time parsing and formatting up to nanosecond resolution,
using the bit64
package for the actual integer64 arithmetic. Initially
implemented using the S3 system, it has benefitted greatly from a
rigorous refactoring by Leonardo who not only rejigged
nanotime internals in S4 but also added new S4 types for
periods, intervals and durations.
This release covers two corner case. Michael sent in a PR
avoiding a clang warning on complex types. We fixed an
issue that surfaced in a downstream package under sanitizier checks: R
extends coverage of NA to types such as integer or character which need
special treatment in non-R library code as they do not know . We
flagged (character) formatted values after we had called the
corresponding CCTZ function but that leaves potentiall undefined
values (from R s NA values for int, say, cast to
double) so now we flag them, set a transient safe value for
the call and inject the (character) representation "NA"
after the call in those spots. End result is the same, but without a
possibly slap on the wrist from sanitizer checks.
The NEWS snippet below has the full details.
Changes in version 0.3.11
(2025-01-10)
Explicit Rcomplex assignment accommodates pickier
compilers over newer R struct (Michael Chirico in #135 fixing
#134)
When formatting, NA are flagged before
CCTZ call to to not trigger santizier, and set to NA after
call (Dirk in #136)
Most of my Debian contributions this month were
sponsored by
Freexian, as well as one direct donation via
Liberapay (thanks!).
OpenSSH
I issued a bookworm
update
with a number of fixes that had accumulated over the last year, especially
fixing GSS-API key exchange which
wasquitebroken in bookworm.
base-passwd
A few months ago, the adduser maintainer started a discussion with me (as
the base-passwd maintainer) and the shadow maintainer about bringing all
three source packages under one team, since they often need to cooperate on
things like user and group names. I agreed, but hadn t got round to doing
anything about it until recently. I ve now officially moved it under team maintenance.
debconf
Gioele Barabucci has been working on eliminating duplicated code between
debconf and cdebconf, ultimately with the goal of migrating to cdebconf
(which I m not sure I m convinced of as a goal, but if we can make
improvements to both packages as part of working towards it then there s no
harm in that). I finally got round to reviewing and merging confmodule
changes in each of
debconf
and
cdebconf.
This caused an installer regression due
to a weirdness in cdebconf-udeb s packaging, which I fixed - sorry about that!
I ve also been dealing with a few patch submissions that had been in my
queue for a long time, but more on that next month if all goes well.
CI issues
I noticed and fixed a problem with Restrictions:
needs-sudo
in autopkgtest.
I fixed broken aptly
images
in the Salsa CI pipeline.
Python team
Last month, I mentioned some progress on
sorting out the multipart vs. python-multipart name conflict in Debian
(#1085728), and said that I thought we d
be able to finish it soon. I was right! We got it all done this month:
The Python 3.13 transition continues, and last month we were able to add it
to the supported Python versions in testing. (The next step will be to make
it the default.) I fixed lots of problems in aid of this, including:
Sphinx 8.0 removed some old intersphinx_mapping
syntax which turned out to
still be in use by many packages in Debian. The fixes for this were
individually trivial, but there were a lot of them:
I found that twisted 24.11.0 broke tests in
buildbot
and
wokkel,
and fixed those.
I packaged python-flatdict, needed for a
new upstream version of python-semantic-release.
I tracked down a test failure in
vdirsyncer (which I ve been using for some
years, but had never previously needed to
modify) and contributed a fix
upstream.
I fixed some packages to tolerate future versions of dh-python that will
drop their dependency on python3-setuptools:
I fixed django-cte to remove a
build-dependency on the obsolete python3-nose package.
I added Django 5.1 support to django-polymorphic. (There are a number of
other packages that still need work here.)
I fixed various other build/test failures:
I updated the team s library style
guide to remove material
related to Python 2 and early versions of Python 3, which is no longer
relevant to any current Python packaging work.
Other Python upstream work
I happened to notice a Twisted upstream
issue requesting the
removal of the deprecated twisted.internet.defer.returnValue, realized it
was still used in many places in Debian, and went on a PR-filing spree
informed by codesearch to try to reduce
the future impact of such a change on Debian:
At work, I've been maintaining a perl script that needs to run a number
of steps as part of a release workflow.
Initially, that script was very simple, but over time it has grown to do
a number of things. And then some of those things did not need to be run
all the time. And then we wanted to do this one exceptional thing for
this one case. And so on; eventually the script became a big mess of
configuration options and unreadable flow, and so I decided that I
wanted it to be more configurable. I sat down and spent some time on
this, and eventually came up with what I now realize is a
domain-specific language (DSL) in JSON, implemented by creating objects
in Moose, extensible by writing
more object classes.
Let me explain how it works.
In order to explain, however, I need to explain some perl and Moose
basics first. If you already know all that, you can safely skip ahead
past the "Preliminaries" section that's next.
Preliminaries
Moose object creation, references.
In Moose, creating a class is done something like this:
package Foo;
use v5.40;
use Moose;
has 'attribute' => (
is => 'ro',
isa => 'Str',
required => 1
);
sub say_something
my $self = shift;
say "Hello there, our attribute is " . $self->attribute;
The above is a class that has a single attribute called attribute.
To create an object, you use the Moose constructor on the class, and
pass it the attributes you want:
use v5.40;
use Foo;
my $foo = Foo->new(attribute => "foo");
$foo->say_something;
(output: Hello there, our attribute is foo)
This creates a new object with the attribute attribute set to bar.
The attribute accessor is a method generated by Moose, which functions
both as a getter and a setter (though in this particular case we made
the attribute "ro", meaning read-only, so while it can be set at object
creation time it cannot be changed by the setter anymore). So yay, an
object.
And it has methods, things that we set ourselves. Basic OO, all that.
One of the peculiarities of perl is its concept of "lists". Not to be
confused with the lists of python -- a concept that is called "arrays"
in perl and is somewhat different -- in perl, lists are enumerations of
values. They can be used as initializers for arrays or hashes, and they
are used as arguments to subroutines. Lists cannot be nested; whenever a
hash or array is passed in a list, the list is "flattened", that is, it
becomes one big list.
This means that the below script is functionally equivalent to the above
script that uses our "Foo" object:
use v5.40;
use Foo;
my %args;
$args attribute = "foo";
my $foo = Foo->new(%args);
$foo->say_something;
(output: Hello there, our attribute is foo)
This creates a hash %args wherein we set the attributes that we want
to pass to our constructor. We set one attribute in %args, the one
called attribute, and then use %args and rely on list flattening to
create the object with the same attribute set (list flattening turns a
hash into a list of key-value pairs).
Perl also has a concept of "references". These are scalar values that
point to other values; the other value can be a hash, a list, or another
scalar. There is syntax to create a non-scalar value at assignment time,
called anonymous references, which is useful when one wants to remember
non-scoped values. By default, references are not flattened, and this
is what allows you to create multidimensional values in perl; however,
it is possible to request list flattening by dereferencing the
reference. The below example, again functionally equivalent to the
previous two examples, demonstrates this:
use v5.40;
use Foo;
my $args = ;
$args-> attribute = "foo";
my $foo = Foo->new(%$args);
$foo->say_something;
(output: Hello there, our attribute is foo)
This creates a scalar $args, which is a reference to an anonymous
hash. Then, we set the key attribute of that anonymous hash to bar
(note the use arrow operator here, which is used to indicate that we
want to dereference a reference to a hash), and create the object using
that reference, requesting hash dereferencing and flattening by using a
double sigil, %$.
As a side note, objects in perl are references too, hence the fact that
we have to use the dereferencing arrow to access the attributes and
methods of Moose objects.
Moose attributes don't have to be strings or even simple scalars. They
can also be references to hashes or arrays, or even other objects:
package Bar;
use v5.40;
use Moose;
extends 'Foo';
has 'hash_attribute' => (
is => 'ro',
isa => 'HashRef[Str]',
predicate => 'has_hash_attribute',
);
has 'object_attribute' => (
is => 'ro',
isa => 'Foo',
predicate => 'has_object_attribute',
);
sub say_something
my $self = shift;
if($self->has_object_attribute)
$self->object_attribute->say_something;
$self->SUPER::say_something unless $self->has_hash_attribute;
say "We have a hash attribute!"
This creates a subclass of Foo called Bar that has a hash
attribute called hash_attribute, and an object attribute called
object_attribute. Both of them are references; one to a hash, the
other to an object. The hash ref is further limited in that it requires
that each value in the hash must be a string (this is optional but can
occasionally be useful), and the object ref in that it must refer to an
object of the class Foo, or any of its subclasses.
The predicates used here are extra subroutines that Moose provides if
you ask for them, and which allow you to see if an object's attribute
has a value or not.
The example script would use an object like this:
use v5.40;
use Bar;
my $foo = Foo->new(attribute => "foo");
my $bar = Bar->new(object_attribute => $foo, attribute => "bar");
$bar->say_something;
(output: Hello there, our attribute is foo)
This example also shows object inheritance, and methods implemented in
child classes.
Okay, that's it for perl and Moose basics. On to...
Moose Coercion
Moose has a concept of "value coercion". Value coercion allows you to
tell Moose that if it sees one thing but expects another, it should
convert is using a passed subroutine before assigning the value.
That sounds a bit dense without example, so let me show you how it
works. Reimaginging the Bar package, we could use coercion to
eliminate one object creation step from the creation of a Bar object:
package "Bar";
use v5.40;
use Moose;
use Moose::Util::TypeConstraints;
extends "Foo";
coerce "Foo",
from "HashRef",
via Foo->new(%$_) ;
has 'hash_attribute' => (
is => 'ro',
isa => 'HashRef',
predicate => 'has_hash_attribute',
);
has 'object_attribute' => (
is => 'ro',
isa => 'Foo',
coerce => 1,
predicate => 'has_object_attribute',
);
sub say_something
my $self = shift;
if($self->has_object_attribute)
$self->object_attribute->say_something;
$self->SUPER::say_something unless $self->has_hash_attribute;
say "We have a hash attribute!"
Okay, let's unpack that a bit.
First, we add the Moose::Util::TypeConstraints module to our package.
This is required to declare coercions.
Then, we declare a coercion to tell Moose how to convert a HashRef to
a Foo object: by using the Foo constructor on a flattened list
created from the hashref that it is given.
Then, we update the definition of the object_attribute to say that it
should use coercions. This is not the default, because going through the
list of coercions to find the right one has a performance penalty, so if
the coercion is not requested then we do not do it.
This allows us to simplify declarations. With the updated Bar class,
we can simplify our example script to this:
use v5.40;
use Bar;
my $bar = Bar->new(attribute => "bar", object_attribute => attribute => "foo" );
$bar->say_something
(output: Hello there, our attribute is foo)
Here, the coercion kicks in because the value object_attribute, which
is supposed to be an object of class Foo, is instead a hash ref.
Without the coercion, this would produce an error message saying that
the type of the object_attribute attribute is not a Foo object. With
the coercion, however, the value that we pass to object_attribute is
passed to a Foo constructor using list flattening, and then the
resulting Foo object is assigned to the object_attribute attribute.
Coercion works for more complicated things, too; for instance, you can
use coercion to coerce an array of hashes into an array of objects, by
creating a subtype first:
package MyCoercions;
use v5.40;
use Moose;
use Moose::Util::TypeConstraints;
use Foo;
subtype "ArrayOfFoo", as "ArrayRef[Foo]";
subtype "ArrayOfHashes", as "ArrayRef[HashRef]";
coerce "ArrayOfFoo", from "ArrayOfHashes", via [ map Foo->create(%$_) @ $_ ] ;
Ick. That's a bit more complex.
What happens here is that we use the map function to iterate over a
list of values.
The given list of values is @ $_ , which is perl for "dereference the
default value as an array reference, and flatten the list of values in
that array reference".
So the ArrayRef of HashRefs is dereferenced and flattened, and each
HashRef in the ArrayRef is passed to the map function.
The map function then takes each hash ref in turn and passes it to the
block of code that it is also given. In this case, that block is
Foo->create(%$_) . In other words, we invoke the create factory
method with the flattened hashref as an argument. This returns an object
of the correct implementation (assuming our hash ref has a type
attribute set), and with all attributes of their object set to the
correct value. That value is then returned from the block (this could be
made more explicit with a return call, but that is optional, perl
defaults a return value to the rvalue of the last expression in a
block).
The map function then returns a list of all the created objects, which
we capture in an anonymous array ref (the [] square brackets), i.e.,
an ArrayRef of Foo object, passing the Moose requirement of
ArrayRef[Foo].
Usually, I tend to put my coercions in a special-purpose package.
Although it is not strictly required by Moose, I find that it is
useful to do this, because Moose does not allow a coercion to be defined
if a coercion for the same type had already been done in a different
package. And while it is theoretically possible to make sure you only
ever declare a coercion once in your entire codebase, I find that doing
so is easier to remember if you put all your coercions in a specific
package.
Okay, now you understand Moose object coercion! On to...
Dynamic module loading
Perl allows loading modules at runtime. In the most simple case, you
just use require inside a stringy eval:
my $module = "Foo";
eval "require $module";
This loads "Foo" at runtime. Obviously, the $module string could be a
computed value, it does not have to be hardcoded.
There are some obvious downsides to doing things this way, mostly in the
fact that a computed value can basically be anything and so without
proper checks this can quickly become an arbitrary code vulnerability.
As such, there are a number of distributions on
CPAN to help you with the low-level stuff of
figuring out what the possible modules are, and how to load them.
For the purposes of my script, I used
Module::Pluggable. Its API
is fairly simple and straightforward:
package Foo;
use v5.40;
use Moose;
use Module::Pluggable require => 1;
has 'attribute' => (
is => 'ro',
isa => 'Str',
);
has 'type' => (
is => 'ro',
isa => 'Str',
required => 1,
);
sub handles_type
return 0;
sub create
my $class = shift;
my %data = @_;
foreach my $impl($class->plugins)
if($impl->can("handles_type") && $impl->handles_type($data type ))
return $impl->new(%data);
die "could not find a plugin for type " . $data type ;
sub say_something
my $self = shift;
say "Hello there, I am a " . $self->type;
The new concept here is the plugins class method, which is added by
Module::Pluggable, and which searches perl's library paths for all
modules that are in our namespace. The namespace is configurable, but by
default it is the name of our module; so in the above example, if there
were a package "Foo::Bar" which
has a subroutine handles_type
that returns a truthy value when passed the value of the type key in
a hash that is passed to the create subroutine,
then the create subroutine creates a new object with the passed
key/value pairs used as attribute initializers.
Let's implement a Foo::Bar package:
package Foo::Bar;
use v5.40;
use Moose;
extends 'Foo';
has 'type' => (
is => 'ro',
isa => 'Str',
required => 1,
);
has 'serves_drinks' => (
is => 'ro',
isa => 'Bool',
default => 0,
);
sub handles_type
my $class = shift;
my $type = shift;
return $type eq "bar";
sub say_something
my $self = shift;
$self->SUPER::say_something;
say "I serve drinks!" if $self->serves_drinks;
We can now indirectly use the Foo::Bar package in our script:
use v5.40;
use Foo;
my $obj = Foo->create(type => bar, serves_drinks => 1);
$obj->say_something;
output:
Hello there, I am a bar.
I serve drinks!
Okay, now you understand all the bits and pieces that are needed to
understand how I created the DSL engine. On to...
Putting it all together
We're actually quite close already. The create factory method in the
last version of our Foo package allows us to decide at run time which
module to instantiate an object of, and to load that module at run time.
We can use coercion and list flattening to turn a reference to a hash
into an object of the correct type.
We haven't looked yet at how to turn a JSON data structure into a hash,
but that bit is actually ridiculously trivial:
use JSON::MaybeXS;
my $data = decode_json($json_string);
Tada, now $data is a reference to a deserialized version of the JSON
string: if the JSON string contained an object, $data is a hashref; if
the JSON string contained an array, $data is an arrayref, etc.
So, in other words, to create an extensible JSON-based DSL that is
implemented by Moose objects, all we need to do is create a system that
takes hash refs to set arguments
has factory methods to create objects, which
uses Module::Pluggable to find the available object classes, and
uses the type attribute to figure out which object class to use
to create the object
uses coercion to convert hash refs into objects using these factory
methods
In practice, we could have a JSON file with the following structure:
... and then we could have a Moose object definition like this:
package MyDSL;
use v5.40;
use Moose;
use MyCoercions;
has "description" => (
is => 'ro',
isa => 'Str',
);
has 'actions' => (
is => 'ro',
isa => 'ArrayOfFoo'
coerce => 1,
required => 1,
);
sub say_something
say "Hello there, I am described as " . $self->description . " and I am performing my actions: ";
foreach my $action(@ $self->actions )
$action->say_something;
Now, we can write a script that loads this JSON file and create a new
object using the flattened arguments:
use v5.40;
use MyDSL;
use JSON::MaybeXS;
my $input_file_name = shift;
my $args = do
local $/ = undef;
open my $input_fh, "<", $input_file_name or die "could not open file";
<$input_fh>;
;
$args = decode_json($args);
my $dsl = MyDSL->new(%$args);
$dsl->say_something
Output:
Hello there, I am described as do stuff and I am performing my actions:
Hello there, I am a bar
I am serving drinks!
Hello there, I am a bar
In some more detail, this will:
Read the JSON file and deserialize it;
Pass the object keys in the JSON file as arguments to a constructor of
the MyDSL class;
The MyDSL class then uses those arguments to set its attributes,
using Moose coercion to convert the "actions" array of hashes into an
array of Foo::Bar objects.
Perform the say_something method on the MyDSL object
Once this is written, extending the scheme to also support a "quux" type
simply requires writing a Foo::Quux class, making sure it has a method
handles_type that returns a truthy value when called with quux as
the argument, and installing it into the perl library path. This is
rather easy to do.
It can even be extended deeper, too; if the quux type requires a list
of arguments rather than just a single argument, it could itself also
have an array attribute with relevant coercions. These coercions could
then be used to convert the list of arguments into an array of objects
of the correct type, using the same schema as above.
The actual DSL is of course somewhat more complex, and also actually
does something useful, in contrast to the DSL that we define here which just
says things.
Creating an object that actually performs some action when required is
left as an exercise to the reader.