← Writing

eBPF on Windows, Two Years In

38 min readSystemsEbpfWindowsHvciVerifierPrevail
Contents

In a Windows 11 virtual machine with Memory Integrity switched on, eBPF for Windows v0.16.0 refused to JIT-compile a fifty-line BPF program before it had produced a single byte of machine code. The same program, translated ahead of time into C and built into an 11-kilobyte test-signed driver, loaded straight away and counted 100,001 socket binds out of 100,001. Its JIT-compiled twin, run with Memory Integrity off, lost up to 22 of them, because eighteen months after I last looked, the Windows JIT still cannot compile an atomic add.

That is the experiment Part 7 promised and did not run. In October 2022 I installed eBPF for Windows v0.5.0, wrote a bind counter, and noted that native mode, the path built for machines with Memory Integrity, would have to wait. This part comes back with the release that shipped two days ago, runs that experiment, and measures the rest of what changed: which of Part 7’s gaps have closed, which have not, what has left the core project altogether, and one place where the Windows verifier can now prove something the Linux one cannot.

This is Part 12 of a series on eBPF, written for C programmers who know what a process, a system call and a socket are, and nothing about kernel internals. It is the sequel to Part 7. Everything Windows-side ran on the same Hyper-V virtual machine, restored to a clean image and given eBPF for Windows v0.16.0, the release of 26 April. The Linux comparison ran on a mainline 6.7 kernel. The output is pasted from those runs, and the note at the end says exactly where and how.

Eighteen months, in one table

Part 7 ended with a list of what eBPF for Windows did not have next to Linux: tracing hooks, the perf event array, ring_buffer__poll, CO-RE, BTF-defined maps, global variables, the Linux bpf() ABI, and production-signed binaries. It also had a few things that were about to move: the JIT was the “typical” path, native mode was the addition, and XDP was one of the hooks in the core networking driver.

Thirteen releases later, the project is at v0.16.0. It is still a 0.x version, still flagged pre-release on GitHub, and still test-signed: in February a maintainer said in the project’s discussions that no Microsoft-signed binaries had been published, and the issue for a production-signing pipeline, open since June 2021, is still open. But a lot of the inside has changed, and not all of it in the direction of “more”. The table below is every change I think matters to someone writing programs, by the release that shipped it; the rows marked measured are the ones I ran on the VM for this post.

What changed between v0.5.0 and v0.16.0

Eighteen months of eBPF for Windows, October 2022 to April 2024, by the release that shipped each change. The last group is what is still missing next to Linux.

ReleaseKindWhat
v0.6.02023-02changedJIT becomes an optional installer featureThe ebpfsvc service, which verifies and JIT-compiles, moves into its own MSI feature (merged October 2022). Without it, only native drivers load.
v0.6.02023-02addedConnect redirectA cgroup/connect4 program can rewrite the destination address and port, through WFP's connect-redirect layer (merged November 2022).measured
v0.6.02023-02addedbpf_prog_test_run_optsRun a program on a supplied context without attaching it.
v0.7.02023-03addedAtomic instructions in bpf2cNative drivers can contain lock add; the uBPF JIT still cannot.measured
v0.9.02023-05changedNative-only builds shipA release flavour with no JIT; by June 2023 its JIT and interpreter code is compiled out.
v0.10.02023-08addedBTF-defined maps in .mapsThe map syntax libbpf 1.0 made the only one on Linux; v0.5.0 found "no maps section".measured
v0.11.02023-09addedTail-call limit 33, bpf_get_prandom_u32MAX_TAIL_CALL_CNT now matches Linux.
v0.12.02023-10addedLIBBPF_PIN_BY_NAMEMaps pinned by name at load, as libbpf does.
v0.13.02023-12goneXDP leaves netebpfext.sysOnly a test program type, xdp_test, remains in the core; real XDP is the separate xdp-for-windows driver's job.measured
v0.14.12024-02addedBatch map APIsbpf_map_lookup_batch and its update, delete and lookup-and-delete siblings.measured
v0.14.12024-02addedcpu=v4 instructions in bpf2cSign-extending loads and moves, sdiv and smod.
v0.15.02024-04changedInstaller reorganisedAll deployments go through the MSI; more than 64 CPUs supported.
v0.16.02024-04changedThe published MSI is native-onlyThe installer attached to the release has no ebpfsvc and no JIT feature; the JIT-capable one is inside a build archive.measured
—2024-04missingCO-RENo relocations; a program is recompiled per platform, not relocated per kernel.
—2024-04missingGlobal variablesNo .data/.bss; state lives in maps.
—2024-04missingPerf event array, ring_buffer__pollStill the same 13 map types; the ring buffer is callback-only.
—2024-04missingThe Linux bpf() ABIThe bpf() export still takes a Windows layout, so Go and Rust loaders cannot drive it directly.
—2024-04missingTracing hooksNo kprobes, tracepoints, uprobes or LSM; every hook in the core is a network hook.
—2024-04missingProduction signingEvery release is still test-signed and flagged pre-release.

Green is new, teal changed how things work, copper left the core, grey is still missing. Measured rows were also run on this part's VM. Release dates are the GitHub release dates; where a change merged earlier than the release that carried it, the text says when.

Three threads run through that table, and the rest of this post follows them in turn. The first is the language: BTF-defined maps, atomics in native code, batch map access, the cpu=v4 instructions. Programs written the way Linux programs are written now get further. The second is the execution model: JIT went from the default to an optional installer feature to something the release’s own MSI leaves out, and native mode went from the addition to the thing every build supports. The third is scope: XDP left the core, and connect redirect arrived, so the project is narrowing its own driver to socket-level hooks and pushing packet processing out to a separate one.

The first surprise: the installer has no JIT

I restored the VM to the clean checkpoint Part 7’s build left behind — Windows 11, Secure Boot off, test signing on, Memory Integrity off, nothing installed — and installed the Visual C++ redistributable, which the April 2024 install docs list as step one. Then I ran the MSI the way those docs say to install it with the JIT:

> msiexec /i ebpf-for-windows.0.16.0.msi ADDLOCAL=eBPF_Runtime_Components,eBPF_Runtime_Components_JIT /qn
msi exit 1603

The verbose log explains:

DEBUG: Error 2711:  The specified Feature name ('eBPF_Runtime_Components_JIT') not found in Feature Table.

The MSI attached to the v0.16.0 release has one feature, eBPF_Runtime_Components, and no JIT feature at all. Installed with just that, it gives you the two kernel drivers, the API DLL, netsh and bpftool, bpf2c — and no ebpfsvc.exe, the service that verifies and JIT-compiles programs at load time. The kernel driver’s debug-symbol path says what it is: x64\NativeOnlyRelease\EbpfCore.pdb. It is the native-only build, the configuration the project has published since v0.9.0 last May, with the JIT and interpreter compiled out. Asking it to load an ELF object, rather than a driver, fails:

> netsh ebpf add program bindcount.bpf.o
error 129: could not load program

This is new with this release. The v0.15.1 MSI from two and a half weeks earlier still contains ebpfsvc.exe and a JIT feature, and the install docs at the v0.16.0 tag still describe the JIT feature as “available on pre-release versions only” — which every release is. The JIT-capable MSI has not gone away: it is inside the release’s Build-x64-Release.zip archive, built from the ordinary x64\Release configuration, with both features. That is the one I used for everything below, because the point of this post is to compare the two paths, and only the x64 Release build has both. But it is worth sitting with what the default download now is. If you take eBPF for Windows v0.16.0 the obvious way, you get a runtime that loads only programs compiled ahead of time into drivers. The README still calls the JIT the typical path. The release artifact has quietly disagreed.

The bind counter, ported forward

Part 7’s program counted socket binds per process. Three things about it were dictated by what v0.5.0 could not do: its map was an old-style struct bpf_map_def in a section called maps, because BTF-defined maps were not supported; it incremented with a plain ++, because the uBPF JIT did not implement the atomic add and the program refused to load; and it loaded through the JIT because that was the path. Here is the same program written the way Part 1 wrote its Linux counterpart:

// bindcount.bpf.c — runs in the Windows kernel, once per bind()
#include "bpf_helpers.h"

#define NAME_LEN 64

typedef struct
{
    uint64_t count;
    uint8_t name[NAME_LEN]; // the tail of the image path
} entry_t;

struct
{
    __uint(type, BPF_MAP_TYPE_HASH);
    __type(key, uint64_t);
    __type(value, entry_t);
    __uint(max_entries, 1024);
} counts SEC(".maps");

SEC("bind")
bind_action_t
count_bind(bind_md_t* ctx)
{
    uint64_t pid = ctx->process_id;
    entry_t fresh = {0};
    entry_t* entry;

    if (ctx->operation != BIND_OPERATION_BIND)
        return BIND_PERMIT;

    entry = bpf_map_lookup_elem(&counts, &pid);
    if (entry) {
        __sync_fetch_and_add(&entry->count, 1);
        return BIND_PERMIT;
    }

    uint8_t* start = ctx->app_id_start;
    uint8_t* end = ctx->app_id_end;
    if (end - start > NAME_LEN)
        start = end - NAME_LEN;
#pragma unroll
    for (int i = 0; i < NAME_LEN; i++) {
        if (start + i >= end)
            break;
        fresh.name[i] = start[i];
    }
    fresh.count = 1;
    bpf_map_update_elem(&counts, &pid, &fresh, BPF_NOEXIST);
    return BIND_PERMIT;
}

Three lines differ from Part 7’s version, and each is a story.

The map is BTF-defined. The anonymous struct in SEC(".maps"), with __uint and __type encoding the map’s shape in debug information, is the form libbpf 1.0 made the only one on Linux. eBPF for Windows learned to read it in v0.10.0 last August. To see the difference, I took this file back to the v0.5.0-installed checkpoint, defined the two macros by hand (v0.5.0’s headers do not have them), and asked that release’s tooling about it:

> netsh ebpf show sections btfmaps_v05.bpf.o
error: Can't find any maps sections in file btfmaps_v05.bpf.o

On v0.16.0 the same source, compiled with -g so the BTF is there, describes its map exactly:

> netsh ebpf show sections bindcount.bpf.o

                                    Size
             Section       Type  (bytes)
====================  =========  =======
                bind     unspec     2896

                     Key  Value      Max
          Map Type  Size   Size  Entries  Name
==================  ====  =====  =======  ========
              hash     8     72     1024  counts

(The unspec in the Type column is cosmetic. netsh prints it for every .o file on this release, including ones it then loads as bind; for a .sys it prints the real type.)

The increment is atomic again. This is the line Part 7 had to delete, and it still cannot be JIT-compiled:

> netsh ebpf add program bindcount.bpf.o
error 131: could not load program
LMEM

The same opaque refusal as eighteen months ago. The uBPF submodule in v0.16.0 is from February 2024, and its x64 JIT still has no case for the atomic instruction; its validator rejects the opcode as unknown. What changed is the other path. Since v0.7.0 last March, bpf2c translates atomics, and in the C it generates for this program, line 33 of the source becomes:

InterlockedExchangeAdd64((volatile int64_t*)(uintptr_t)(r0 + OFFSET(0)), (uint64_t)r1);

an ordinary Windows interlocked add, which the C compiler turns into lock xadd. So the atomic increment exists on Windows now, but only in native mode. That turns out to matter, and a section below measures how much.

The copy loop is unrolled. This one I did not expect. Part 7’s program, compiled exactly as Part 7 compiled it — same clang 11.0.1, same v0.5.0 headers, no -g — passed v0.5.0’s verifier with “Program terminates within 249 instructions”. v0.16.0’s verifier rejects it:

> netsh ebpf show verification legacy05.bpf.o
Verification failed

Verification report:

38: Upper bound must be at most 65535 (valid_access(r5.offset) for comparison/subtraction)
38: Upper bound must be at most 65535 (r5.type == r1.type in {ctx, stack, packet})
42: Upper bound must be at most EBPF_STACK_SIZE (valid_access(r0.offset, width=1) for write)

3 errors

Instruction 38 is the comparison start + i >= end, and 42 is the store into fresh.name[i]. Both errors say the same thing: at those points PREVAIL no longer has an upper bound on i. The PREVAIL inside v0.16.0 is a March 2024 build, eighteen months newer than v0.5.0’s, and it handles loops differently; its success message on this release counts “loop iterations” where v0.5.0’s counted instructions. On this loop, whose exit tests a pointer comparison against the end of the context data rather than i alone, the newer analysis loses the bound. I tried rewriting the loop around an explicit length instead; that failed too, and added “Could not prove termination”. What works is to take the loop away from the verifier: #pragma unroll makes clang emit 64 copies of the body with a constant i in each, and there is nothing left for the analysis to lose.

> netsh ebpf show verification bindcount.bpf.o

Verification succeeded
Program terminates within 0 loop iterations

The cost is size: the program section went from 448 bytes to 2,896. The lesson is a familiar one from Linux, where a verifier upgrade can also change what passes, but it is worth stating plainly for Windows. A program that loaded on the project’s release from October 2022 does not load on its release from April 2024. Source compatibility with the verifier is not a promise the project makes across its own 0.x versions, and it is not one it kept.

Reading the map in one call

The user-space half is Part 7’s loader with one change: instead of walking the map a key at a time with bpf_map_get_next_key, it reads the whole thing with bpf_map_lookup_batch, one of the four batch functions added in v0.14.1 in February:

// bindcount.c — load, attach, wait, then read every entry in one call
struct bpf_map_batch_opts opts = {.sz = sizeof(opts)}; /* NULL crashes here, unlike Linux */
uint64_t out_batch;
uint32_t n = MAX_ENTRIES;

fd = bpf_object__find_map_fd_by_name(obj, "counts");
err = bpf_map_lookup_batch(fd, NULL, &out_batch, keys, values, &n, &opts);
if (err && errno != ENOENT) /* ENOENT means "that was the last batch" */
    n = 0;

The comment on the first line cost me two VM reboots. On Linux the opts argument is optional and NULL means defaults. The Windows implementation in v0.16.0 reads opts->flags before anything else, so passing NULL dereferences a null pointer inside EbpfApi.dll. The first time it took the loader down mid-call while a native driver was attached, and the process sat stuck in the kernel until I restarted the VM. Pass a zeroed options struct with its size set and it works.

Native mode, built for real

Part 7 ran bpf2c and stopped at the generated C. This time the C goes all the way to a driver.

The generator is the same tool, installed by the MSI alongside netsh and bpftool:

> bpf2c --bpf bindcount.bpf.o --sys bindcount_driver.c

The output is 1,173 lines for this program, against 428 for Part 7’s, almost all of the difference being the 64 unrolled copies of the loop. The shape is what Part 7 described — the program as a C function with the eleven BPF registers as locals, tables of helpers and maps, a hash of the program’s type information — with one addition that makes debugging pleasant: every generated statement now carries a #line directive pointing back at the BPF source, so a crash dump or a kernel debugger shows bindcount.bpf.c line numbers, not lines of generated C.

The file opens with #include <wdm.h> and #include <wsk.h>. It is a Windows driver, and it needs the Windows Driver Kit’s kernel-mode headers and libraries to compile. The project’s own build does this with a Visual Studio project per program; I did it by hand, which shows how little there is to it:

cl /kernel /O2 /Gy /GS ... bindcount_driver.c
link /DRIVER /SUBSYSTEM:NATIVE /ENTRY:GsDriverEntry /NXCOMPAT ... ntoskrnl.lib hal.lib netio.lib BufferOverflowFastFailK.lib

The result is a 9,728-byte kernel driver. Its section table is the interesting part for what comes next:

   .text   Execute Read
    bind   Execute Read
  .rdata   (read only)
   .data   Read Write
    maps   Read Write
programs   Read Write
    INIT   Execute Read

The BPF program sits in its own executable section named after the hook, bind; the map and program descriptors are data. No section is both writable and executable, and the image is marked NX-compatible. Windows drivers have to be signed to load, and with test signing on in the VM, a test signature from a certificate I made inside the VM is enough. Signed, it is 11,152 bytes. Then it loads the same way an ELF object does:

> netsh ebpf add program bindcount.sys
Loaded with ID 22

> netsh ebpf show programs

    ID  Pins  Links  Mode       Type           Name
======  ====  =====  =========  =============  ====================
    22     1      1  NATIVE     bind           count_bind

Mode NATIVE. Behind that one command, EbpfApi.dll registered the .sys as a kernel driver service under a GUID name (the System event log records “A service was installed in the system” with bindcount.sys as its file), started it, and the driver attached itself to ebpfcore.sys through the Network Module Registrar, handing over its program and map tables. No ebpfsvc was involved: the verification happened in bpf2c, on the build machine, before the C existed.

Turning Memory Integrity on

Hypervisor-enforced Code Integrity, which Windows calls Memory Integrity, needs virtualization-based security, which needs a hypervisor, which in this case means a hypervisor inside the VM. So the steps were: shut the VM down and expose virtualization extensions to it from the host (Set-VMProcessor -ExposeVirtualizationExtensions $true); inside the guest, set EnableVirtualizationBasedSecurity and the HypervisorEnforcedCodeIntegrity scenario’s Enabled value to 1 under HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard; reboot.

The first reboot taught me something. Device Guard reported virtualization-based security as enabled but not running, with Secure Boot among the required properties. This VM has Secure Boot off, because test signing needs it off, and by default VBS will not start without it. Setting RequirePlatformSecurityFeatures to 0, which asks for the hypervisor alone, and rebooting again got the state I wanted:

VirtualizationBasedSecurityStatus : 2
SecurityServicesRunning           : {1, 2}

Status 2 is “running”, and service 2 in the running list is HVCI. Test signing was still on, and ebpfcore.sys and netebpfext.sys, test-signed themselves, came up under it: the eBPF runtime starts on a Memory Integrity machine. That is the configuration in which this whole design is supposed to earn its keep, so here is the experiment, both paths through it, as a stepper. Switch Memory Integrity on and walk through again to see where the JIT path stops.

The same program, two ways into the kernel

The bind counter loaded by JIT and as a native driver on eBPF for Windows v0.16.0. Switch Memory Integrity on and step through again.

Memory Integrity

1One source file, one object

JIT path

clang -g -target bpf -O2 -c bindcount.bpf.c

The same ELF object feeds both paths: BPF bytecode in a section called bind, a BTF-defined map, line information.

Native path

clang -g -target bpf -O2 -c bindcount.bpf.c

Identical. Nothing about the object says how it will run.

2PREVAIL proves it safe

JIT path · at load time

netsh ebpf add program bindcount.bpf.o
  → ebpfsvc → PREVAIL

The user-mode service verifies the bytecode every time a program is loaded, on the machine that runs it.

Native path · at build time

bpf2c --bpf bindcount.bpf.o --sys bindcount_driver.c

bpf2c runs the same verifier before it writes a line of C. A program that fails never becomes a driver.

3Turning bytecode into machine code

Memory Integrity off

JIT path · uBPF in ebpfsvc

IOCTL resolve_helper (operation 0) → address
uBPF → x64 code

To compile calls and map references, the service first asks the kernel driver for helper and map addresses, then emits x64.

Memory Integrity on

JIT path · refused here

Operation id 0 not permitted due to system configuration
_ebpf_object_load_programs returned error 21

Blocked. ebpfcore.sys permits JIT-only operations only while HVCI is off, so the very first one, resolving a helper's address, is refused before any code exists. Error 21 is EBPF_BLOCKED_BY_POLICY; netsh prints error 131.

Native path · bpf2c, then the driver toolchain

1,173 lines of C → cl /kernel → link /DRIVER
→ bindcount.sys, 9,728 bytes → signtool

The machine code is made on the build machine by an ordinary C compiler, and the result is signed like any driver. No sections are both writable and executable.

4Into the kernel

Memory Integrity off

JIT path

ebpfcore.sys ← x64 code from ebpfsvc

The kernel driver takes code it did not generate or check, and makes it executable. This is exactly what HVCI exists to forbid.

Memory Integrity on

JIT path

(never reached)

Nothing to load. The service gave up at stage 3.

Native path · the Windows driver loader

new service <GUID>: kernel mode driver, demand start
→ started → Code Integrity checks the signature

ebpfapi.dll registers the .sys as a driver service and Windows loads it. With HVCI on, the signature check runs under the hypervisor; an unsigned copy is refused with Code Integrity event 3004 and netsh error 2.

5Attached and counting

Memory Integrity off

JIT path

Mode JIT   Type bind   count_bind
99,989 of 100,001 binds (plain ++)

It runs. The JIT cannot compile the atomic add, so this is the plain-increment version, and it loses counts.

Memory Integrity on

JIT path

netsh ebpf add program bindcount.bpf.o
error 131: could not load program

Not running. On a machine with Memory Integrity, JIT is not an option at all.

Native path

Mode NATIVE   Type bind   count_bind
100,001 of 100,001 binds (atomic add)

Loads and counts exactly, with Memory Integrity on or off. The native driver is the only one of the two that can carry the atomic add.

Teal is the JIT path, green the native path, copper a refusal. Both paths share the verifier; they differ in who makes the machine code and when. Under Memory Integrity only code that arrives as a signed image can run in the kernel, and native mode is the only path that produces one.

The JIT path first. The same ELF objects that loaded a few minutes earlier, each one:

> netsh ebpf add program plain.bpf.o
error 131: could not load program

> netsh ebpf add program relation.bpf.o
error 131: could not load program

> netsh ebpf add program redirect.bpf.o
error 131: could not load program

That is the same error 131 the atomic add produced, and it means nothing more specific than “something failed”; netsh prints the C errno, and errno has no word for “the hypervisor said no”. The real reason is in the runtime’s own trace. The install ships a Windows Performance Recorder profile for it, and recording one failed load with wpr -start ebpfforwindows.wprp shows, from the ebpfsvc process:

"Operation id %d not permitted due to system configuration", 0
"_ebpf_object_load_programs returned error", 21

Operation 0 is EBPF_OPERATION_RESOLVE_HELPER: before it can emit a call instruction, the JIT asks the kernel driver for the address of each helper the program uses. ebpfcore.sys marks every operation with the execution modes that need it, and the rule in its dispatch code is a single line: JIT is permitted only if HVCI is off. Resolving a helper address is needed only by the JIT, so with HVCI on it is refused, and the load ends with error 21, EBPF_BLOCKED_BY_POLICY. Part 7 quoted a different check, deeper in the driver, that refuses JIT code at the moment it is handed over. That check is still in v0.16.0, but a load never reaches it. This earlier one, which has been in the dispatch code since mid-2022, turns the JIT away at the first question it asks, before any code exists to be refused. Reading the source to find the refusal, as I did for Part 7, finds the check that looks right; running it under HVCI finds the one that fires.

Then the native path:

> netsh ebpf add program bindcount.sys
Loaded with ID 11

> netsh ebpf show programs

    ID  Pins  Links  Mode       Type           Name
======  ====  =====  =========  =============  ====================
    11     1      1  NATIVE     bind           count_bind

And running the loader and a bind generator against it, with Memory Integrity on, 100,001 binds were made and 100,001 counted.

The native path is not a loophole around Memory Integrity, and the last check shows why. I linked the same object again without signing it and asked for that to be loaded:

> netsh ebpf add program bindcount_unsigned.sys
error 2: could not load program

and the Code Integrity log said why: “Windows is unable to verify the image integrity of the file …\bindcount_unsigned.sys because file hash could not be found on the system.” Under HVCI, that check runs in the hypervisor-protected part of the system, out of reach of the kernel it is protecting. A native eBPF program goes through it the same way any driver does. That is the whole argument for native mode in one experiment: the JIT needs the kernel to make fresh pages executable, which Memory Integrity exists to prevent; a native program arrives as an ordinary signed image, which Memory Integrity exists to check. On this VM the signature is a test one, and test signing is on, so this proves the mechanism, not a deployment. On a production machine the same driver would need a real signature, and no release of this project has yet shipped one.

What the atomic add buys

Part 7 kept a plain entry->count++ and said that on a busy multi-core machine it could lose counts to races. Two CPUs can each load the old value, each add one, and each store, and one increment disappears. I had not measured it then. Now there are three versions to compare: the plain increment through the JIT, the plain increment as a native driver, and the atomic add as a native driver. The fourth combination, atomic through the JIT, does not load.

The load generator is a small Windows program that starts four threads, each of which creates a UDP socket, binds it to port 0, and closes it, 25,000 times, after one warm-up bind on the main thread so that the map entry exists before the threads race to create it. That is 100,001 binds from one process, every one of them through the bind hook and the same map entry. With Memory Integrity off I ran the three versions in turn, three rounds, and then two more runs with it on:

Binds the counter missed, out of 100,001

Four threads binding sockets as fast as they can, one counter attached. Each dot is a run; further right means more counts lost to two CPUs incrementing the same entry at once.

JIT, plain ++Memory Integrity off
12 ×299,989 counted, 2 runs 2299,979 counted
Native, plain ++Memory Integrity off
1100,000 counted 299,999 counted 499,997 counted
Native, atomic addMemory Integrity off
0 ×3100,001 counted, 3 runs
Native, plain ++Memory Integrity on
0100,001 counted
Native, atomic addMemory Integrity on
0100,001 counted
Table view
ProgramMemory IntegrityCounted, per run
JIT, plain ++off99,989, 99,989, 99,979
Native, plain ++off100,000, 99,999, 99,997
Native, atomic addoff100,001, 100,001, 100,001
Native, plain ++on100,001
Native, atomic addon100,001

Copper dots lost counts; green rings counted every bind. The plain increment is a load, an add and a store, so two CPUs can read the same old value and one increment vanishes. The atomic add cannot lose one. The JIT has no atomic row because v0.16.0's JIT cannot compile the instruction.

The plain increment lost counts in five of its six runs with Memory Integrity off: 12, 12 and 22 through the JIT, 1, 2 and 4 as a native driver. The atomic add lost none in any run. A smaller first trial, four threads of 2,500, showed the same thing at a tenth of the scale: 9,999 counted of 10,001.

Two cautions about reading more into it. The JIT’s losses are larger than native’s, and it is tempting to say the JIT’s code has a wider window between load and store; that may be true, but three runs each do not show it, and the rate of collisions depends on timing I did not control. And with Memory Integrity on, the plain native increment lost nothing in its one run. The bind generator took about twice as long under HVCI, so the threads spent more of their time elsewhere and collided less. A race that sometimes loses nothing is still a race. The point is only the direction, and that is unambiguous: on Windows today, the only way to write Part 1’s exact counter, with an atomic increment, is native mode.

Connect redirect

Part 7 listed the socket-address hooks — connect4/connect6 and recv_accept4/recv_accept6 — and noted that the connect-redirect hook was not there yet. It was merged a month after that post and shipped in v0.6.0. On Linux, a cgroup/connect4 program can rewrite the address a socket is about to connect to, which is how Cilium implements Kubernetes services without per-packet address translation; Part 11 covered that family of hooks. On Windows, the same section name now does the same thing, through the Windows Filtering Platform’s connect-redirect layer:

// redirect.bpf.c — send TCP connections for 192.0.2.10:80 to 127.0.0.1:8080
#include "bpf_endian.h"
#include "bpf_helpers.h"

#define IPPROTO_TCP 6

SEC("cgroup/connect4")
int
redirect(bpf_sock_addr_t* ctx)
{
    if (ctx->protocol == IPPROTO_TCP &&
        ctx->user_ip4 == bpf_htonl(0xC000020A) && // 192.0.2.10
        ctx->user_port == bpf_htons(80)) {
        ctx->user_ip4 = bpf_htonl(0x7F000001);    // 127.0.0.1
        ctx->user_port = bpf_htons(8080);
    }
    return BPF_SOCK_ADDR_VERDICT_PROCEED;         // let every connect() go ahead
}

192.0.2.10 is in a block reserved for documentation, so nothing answers there. The demonstration is a PowerShell script with two halves: a TCP listener on 127.0.0.1:8080 that replies “hello from 127.0.0.1:8080” to whoever connects, and a client that connects to 192.0.2.10:80 and prints what it hears. Before loading the program:

listener: nothing arrived in 5 s
client: connect to 192.0.2.10:80 timed out

After netsh ebpf add program redirect.bpf.o, which attaches it as type sock_addr:

listener: accepted a connection from 127.0.0.1:62163 on 127.0.0.1:8080
client: connected, socket reports remote end 192.0.2.10:80, server said: hello from 127.0.0.1:8080

The second line is the interesting one. The client’s socket still believes it is talking to 192.0.2.10 port 80; the redirect happened underneath it, at connect time, and from then on the connection is an ordinary loopback connection with no per-packet rewriting. That is the property that makes this hook useful for service load balancing, and it is the same property it has on Linux.

One detail in the header is worth a raised eyebrow if you read it rather than the code: the doc comment for the sock_addr hook lists BPF_SOCK_ADDR_VERDICT_PROCEED as “Block the socket operation” and ..._REJECT as “Allow”. The values (1 and 0) and the behaviour are the right way round; the comment has them swapped.

What left: XDP

The opposite movement is XDP. In v0.5.0, netebpfext.sys had an XDP hook built on the Windows Filtering Platform’s MAC-frame layers, and Part 7’s parity table counted it. In v0.13.0, last December, it was removed from the core driver. What remains is a program type called xdp_test, for the project’s own tests. The program type BPF_PROG_TYPE_XDP still exists in the headers, so a trivial XDP program verifies, but nothing in the core provides the hook:

> netsh ebpf show verification xdp.bpf.o

Verification succeeded
Program terminates within 0 loop iterations

> netsh ebpf add program xdp.bpf.o
error 22: could not load program

Change the section name to xdp_test and it loads and attaches, as Type xdp_test, to a hook that is there for testing and nothing else.

The reason is not that Windows gave up on fast packet processing. Microsoft has a separate project, xdp-for-windows, a separate driver built for high-rate packet I/O, which has had a stable release since August 2023. Real XDP on Windows is meant to come from there, as an extension driver that eBPF for Windows loads programs into, the same way netebpfext.sys provides the socket hooks. For now, though, the honest summary of April 2024 is that the eBPF for Windows release, on its own, has no XDP, and its install docs do not tell you where to get it.

That makes the core driver’s remit clear: bind, connect and accept at the socket layer, connect redirect, and sock_ops for connection events. Socket-level policy and load balancing are in; packet processing is someone else’s driver.

Parity: what closed, what did not

The library surface grew. EbpfApi.dll in v0.16.0 exports 128 functions, 102 of them libbpf-style, up from 95 in Part 7. The new names worth knowing are the four batch map functions used above, bpf_object__open_mem for loading an object from a buffer, and bpf_prog_test_run_opts, which runs a program once on a context you supply without attaching it anywhere — the way Linux programs are unit-tested. The general helpers went from 19 to 25, including bpf_get_prandom_u32, which the next section uses. The tail-call limit is 33, the same as Linux. And bpf2c understands the cpu=v4 instructions that recent Linux toolchains emit, the sign-extending loads and moves and signed division, so a native driver can be built from an object compiled for the newest instruction set. (The clang the project’s docs still pin, 11.0.1, cannot emit them itself; that is a gap between the project’s tools, not in the runtime.)

What did not close is mostly what Part 7 listed:

  • No CO-RE. There are still no relocations, so “compile once, run everywhere” means something different here: compile once per platform, against that platform’s headers.
  • No global variables. No .data or .bss; state still lives in maps.
  • The same thirteen map types. No perf event array, and the ring buffer still has only the callback form, ring_buffer__new, with no ring_buffer__poll.
  • No Linux bpf() ABI. The bpf export still takes a Windows layout of its arguments, so a loader written in Go or Rust against the Linux system call cannot simply point at this DLL.
  • No tracing. Every hook in the core is a network hook. There is still no Windows equivalent of a tracepoint or kprobe, which is why the program in this post counts binds rather than process starts, exactly as in Part 7.
  • No production signing. Every release is test-signed and marked pre-release.

The adoption story has moved in public, if not yet in shipping products. At KubeCon in Paris in March, two Microsoft engineers gave a talk at the co-located events called “Cilium Beyond Linux: Extending eBPF to Windows Infrastructure”, presenting Cilium’s layer-4 load balancing, network policy and observability on Windows as the plan, and listing the verifier, dynamically generated programs and tc programs among the hard parts. Those three are a fair summary of this post. The verifier is a separate implementation that does not accept exactly what Linux accepts. Dynamically generated programs are what Cilium compiles on each node, and with Memory Integrity on, the only way into the kernel is a signed driver built ahead of time. And tc has no hook here at all.

Two verifiers, one program, two answers

Part 7 broke the bind counter by removing a NULL check and showed both verifiers rejecting it by different routes: Linux walking paths and tracking a map_value_or_null type, PREVAIL computing an invariant over all paths and finding that the pointer’s range included zero. Same verdict, opposite method. The obvious follow-up is whether the different methods ever give different verdicts. They do, and the clearest case I found turns on a single relationship between two registers.

Here is one function, built for both kernels:

// relation.bpf.c — one function, built for both kernels
#ifdef WINDOWS
#include "bpf_helpers.h"
#define SECNAME "bind"
typedef bind_md_t ctx_t;
typedef bind_action_t ret_t;
#define OK BIND_PERMIT
#else
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
typedef unsigned long long uint64_t;
typedef unsigned int uint32_t;
#define SECNAME "socket"
typedef struct __sk_buff ctx_t;
typedef int ret_t;
#define OK 0
char LICENSE[] SEC("license") = "GPL";
#endif

struct val
{
    uint64_t slot[10];
};

struct
{
    __uint(type, BPF_MAP_TYPE_ARRAY);
    __type(key, uint32_t);
    __type(value, struct val);
    __uint(max_entries, 1);
} vals SEC(".maps");

SEC(SECNAME)
ret_t
relation(ctx_t* ctx)
{
    uint32_t key = 0;
    struct val* v = bpf_map_lookup_elem(&vals, &key);
    if (!v)
        return OK;

    uint64_t i = bpf_get_prandom_u32() & 0xff; // 0 to 255, and both verifiers know it
    uint64_t j = i + 1;         // j is i + 1, exactly
    asm volatile("" : "+r"(j)); // stop clang rewriting the test below in terms of i
    if (j > 10)
        return OK;              // so j <= 10, which means i <= 9
    v->slot[i] += 1;            // in bounds, if the verifier knows that i = j - 1
    return OK;
}

The program picks a random index i between 0 and 255, computes j = i + 1, and bounds-checks j, not i. If j is at most 10, then i is at most 9, and slot[i] is one of the ten slots. A human sees that immediately. The empty asm statement exists only to stop clang from seeing it too: without it, the optimiser rewrites j > 10 as i > 9 and the interesting part vanishes. With it, both compilers emit the same nine instructions for the body (Windows numbers the random helper 6, Linux 7; otherwise they are identical):

  9: call 7                ; bpf_get_prandom_u32
 10: r0 &= 255             ; i
 11: r1 = r0               ; j = i
 12: r1 += 1               ; j = i + 1
 13: if r1 > 10 goto +5
 14: r0 <<= 3              ; i * 8
 15: r6 += r0              ; &v->slot[i]
 16: r1 = *(u64 *)(r6 + 0)

Linux 6.7 rejects it. The log shows exactly where the knowledge is lost:

10: (57) r0 &= 255     ; R0_w=scalar(smin=smin32=0,smax=umax=smax32=umax32=255,var_off=(0x0; 0xff))
11: (bf) r1 = r0       ; R0_w=scalar(id=2,...,umax=255,...) R1_w=scalar(id=2,...,umax=255,...)
12: (07) r1 += 1       ; R1_w=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=256,var_off=(0x0; 0x1ff))
13: (25) if r1 > 0xa goto pc+5 ; R1_w=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=10,var_off=(0x0; 0xf))
14: (67) r0 <<= 3      ; R0_w=scalar(smin=smin32=0,smax=umax=smax32=umax32=2040,var_off=(0x0; 0x7f8))
15: (0f) r6 += r0      ; ...
16: (79) r1 = *(u64 *)(r6 +0)
invalid access to map value, value_size=80 off=2040 size=8
R6 max value is outside of the allowed memory range
processed 16 insns (limit 1000000) max_states_per_insn 0 total_states 1 peak_states 1 mark_read 1

Read instructions 11 and 12. After the copy r1 = r0, both registers carry id=2: the verifier knows they hold the same value, and if a branch later narrows one, it narrows the other too. Then r1 += 1, and the id is gone. r1 now has its own range, 1 to 256, and no recorded connection to r0. The branch at 13 narrows r1 to at most 10 and does nothing to r0, which is still 0 to 255. Multiplied by 8, that is an offset of up to 2,040 into an 80-byte value, and the access is refused. I ran this on 6.7; I also read the 6.8 verifier, and it has no rule that carries a relationship through an addition either.

PREVAIL accepts it:

> netsh ebpf show verification relation.bpf.o

Verification succeeded
Program terminates within 0 loop iterations

and its verbose output shows why, in the invariant it holds on the branch where j <= 10:

13:14:
  assume r1 <= 10;
  goto 14;

Post-invariant: [
    r0.svalue=[0, 9], r0.type=number, r0.uvalue=[0, 9],
    r1.svalue=[1, 10], r1.svalue=r0.svalue+1, r1.type=number, r1.uvalue=[1, 10], ...]

r1.svalue=r0.svalue+1 is a relation, not a range. PREVAIL’s numerical domain keeps constraints between variables, not only on each variable alone, so when it learns r1 <= 10 it can conclude r0 <= 9 by subtracting one. From there the access is r6 + r0 * 8 with r0 at most 9, inside the 80-byte value, and the program loads and attaches as a bind program.

The practical consequence is the one the KubeCon talk named. “Source-code compatibility” between the two platforms has a soft edge at the verifier. A program can be safe, compile on both, and be provably safe to one verifier and not the other, in either direction. Linux programmers already write in a style the Linux verifier can follow — bounds-check the register you are about to use, not a relative of it — and that style happens to suit PREVAIL too. The trouble comes from the other direction: code tuned until one verifier accepts it is tuned to that verifier.

What we covered

  • eBPF for Windows went from v0.5.0 to v0.16.0 in eighteen months, still 0.x, still pre-release, still test-signed. The MSI attached to v0.16.0 is the native-only build, with no JIT feature and no ebpfsvc; the JIT-capable MSI is inside the release’s build archive.
  • Part 7’s bind counter now uses a BTF-defined map (v0.5.0 found “no maps section”) and an atomic add, which the JIT still cannot compile (error 131, LMEM) but bpf2c turns into InterlockedExchangeAdd64. The newer PREVAIL rejects Part 7’s copy loop, which had to be unrolled.
  • Native mode, end to end: bpf2c produced 1,173 lines of C, the driver toolchain produced a 9,728-byte driver with no writable-and-executable section, and with a test signature it loaded as Mode NATIVE.
  • With Memory Integrity on, every JIT load was refused at its first JIT-only operation, resolving a helper’s address (EBPF_BLOCKED_BY_POLICY), while the signed native driver loaded and counted 100,001 of 100,001 binds. An unsigned copy was refused by Code Integrity.
  • Under four threads of binds, the plain increment lost counts in five of six runs (up to 22 of 100,001); the atomic add lost none.
  • Connect redirect works: a cgroup/connect4 program sent a connection for 192.0.2.10:80 to a local listener while the client’s socket still reported 192.0.2.10:80.
  • XDP left the core in v0.13.0. An XDP program verifies but cannot load; only the test type xdp_test remains, and real XDP is the job of the separate xdp-for-windows driver.
  • Parity gained batch map functions, bpf_prog_test_run_opts, cpu=v4 in bpf2c, 25 helpers and a tail-call limit of 33. Still missing: CO-RE, global variables, the perf event array, ring_buffer__poll, the Linux bpf() ABI, tracing hooks and production signing.
  • PREVAIL accepted a program that Linux 6.7 rejected, because it keeps the relation j = i + 1 that Linux loses at the addition; and it rejected a loop that Linux would walk.

A later part comes back to the Windows port once more, to see which of these gaps the next stretch of work closes.

A note on the evidence

What I ran, and where. Every Windows listing is pasted from a run on the Hyper-V Generation-2 virtual machine Part 7 built (4 vCPU, 8 GB) running a Windows 11 Enterprise evaluation image, Secure Boot off, test signing on, restored to its clean checkpoint first. I installed the Visual C++ redistributable, then eBPF for Windows v0.16.0: first the MSI attached to the release (which rejected the JIT feature and, installed without it, gave the native-only runtime), then, after uninstalling it, the ebpf-for-windows.msi from the same release’s Build-x64-Release.zip, with both features. All JIT and native runs used that second install. BPF objects were compiled in the VM with clang 11.0.1, the version the project’s April 2024 docs still require, against the headers of the release’s 0.16.0 NuGet package. The loader and the bind generator were built with the ordinary Windows C compiler against that package’s EbpfApi.lib. The native drivers were generated by the release’s own bpf2c in the VM, then compiled and linked on the host as WDM drivers against the kernel headers and libraries of a Windows Driver Kit preview package from April 2024, and test-signed with a certificate created in the VM. For the Memory Integrity runs I exposed virtualization extensions to the VM, enabled virtualization-based security and the HVCI scenario in the guest’s registry, dropped the Secure Boot requirement, and confirmed VirtualizationBasedSecurityStatus 2 and SecurityServicesRunning {1, 2} before loading anything. The .o files shown being refused under HVCI had loaded on the same install with HVCI off. The v0.5.0 comparison for BTF maps ran on the VM’s v0.5.0-installed checkpoint from Part 7. The Linux side of the verifier comparison ran in a KVM guest booting the mainline 6.7 kernel on an Ubuntu 23.04 userland, compiled there with clang 15 and loaded with a short libbpf 1.1 loader that prints the verifier log.

What I trimmed. Run-time timestamps, as in Part 1. The guest’s exact Windows build number is recorded in the lab notes rather than here. Program and map IDs and process IDs are as printed, each from one load. The link command line is shortened where marked, and the section table is dumpbin’s, reduced to names and permissions. The Linux verifier log is cut to the instructions from the random helper onwards, with two register-state lists elided where marked; PREVAIL’s verbose invariant is cut to the registers that matter and its program-counter labels kept. The netsh refusals under HVCI are three of the loads I tried; every .o file I tried was refused the same way. The trace lines are two of the several hundred events one failed load recorded.

The counts. Each bind-race run was one process making 100,001 UDP binds (one warm-up bind, then four threads of 25,000), with one counter attached, read back with one bpf_map_lookup_batch call. With Memory Integrity off, the three versions ran interleaved, three rounds: JIT plain increment 99,989, 99,989, 99,979; native plain 100,000, 99,999, 99,997; native atomic 100,001 three times. With it on, one run each: native atomic 100,001, native plain 100,001. Two of the off runs also caught a handful of binds from a system service, which I left out of the figure as they are a different map entry. I report counts, not rates; the bind generator’s own run time roughly doubled under Memory Integrity, but those timings come from different boots and I make no claim about them.

What I cited rather than ran. The release dates and the changes attributed to each release are from the project’s GitHub releases and pull requests, checked against its source at the v0.16.0 tag, where I also read the HVCI gate in ebpf_core.c and the operation numbering. The maintainer’s February statement about signing and the open signing issue are from the project’s discussions and issue tracker. The KubeCon talk is cited from its published abstract. The 6.8 verifier was read, not run. xdp-for-windows is described from its repository and release history.

What I’d still change. Three runs per condition is enough to show that a plain increment loses counts and an atomic one does not; it is not enough to say how the loss rate depends on the engine, and I have not tried. The native drivers were test-signed on a test-signing machine, so this shows that the mechanism works under Memory Integrity, not that a production signing path exists, which as of this release it does not. And the verifier comparison is one constructed program in each direction; a systematic comparison would take the Linux kernel’s own verifier test suite and run it through PREVAIL, which is a project, not a paragraph.

More