A window manager in 8086 assembly: drag, z-order, and the segment-register bug tax

A window manager is a data structure and a promise. The data structure is a table: one row per window, with an x, a y, a width, a height, a z-order. The promise is that the screen matches the table. Every feature a window manager has, dragging, stacking, focus, repaint, is a way of changing the table and then making the screen agree with it.

On the night of February 12, UnoDOS had the table and could not keep the promise. You could grab a title bar and drag, the mouse would move, and the window would stay exactly where it was. It took twenty-one commits and a little under twenty-two hours to find out why, and the why is a single missing prefix byte.

What the machine does not tell you

The OS at this point is 8086 real-mode assembly, a 5,802-line kernel.asm on a 1.44 MB floppy, running in CGA mode 4 at 320 by 200 in four colours. It has no memory protection and no flat address space. Every memory access is a pair, a segment register and an offset. Write mov ax, [si] and the CPU reads from DS:SI. Write mov ax, [bp+4] and it reads from SS:BP, because the 8086 designers assumed BP is for stack frames and gave it the stack segment as its default. The assembler accepts both without comment: no type, no warning, no trap. If DS and SS point at the same place the difference is invisible; if they do not, the instruction reads or writes perfectly good memory that is not the memory you meant.

In UnoDOS the kernel lives at segment 0x1000 and the stack at 0x0000. They are not the same place. Keep that in mind.

Build 110 to Build 126: seventeen commits of looking in the wrong place

The stretch opens with 01e3b156, February 12, 04:34: "Add mouse cursor and window dragging support (Build 110)". The body describes the design:

Cursor uses 3-layer architecture: IRQ12 handles cursor XOR drawing and drag state tracking, while actual window moves are deferred to event_get_stub to avoid reentrancy. Window manager functions use cursor lock counter to prevent XOR artifacts during screen updates.

An XOR cursor is drawn by flipping the pixels under it and erased by flipping them again. It costs no memory and it has one invariant: every draw must be paired with exactly one erase, or a cursor-shaped ghost stays on the screen forever. Much of the next week is that invariant being broken in new ways.

The first day's fixes are real and small. Build 114 (b708788e) catches the cursor being drawn twice, "preventing double-XOR (which erased instead of drawing)". Builds 115 through 118 are about how the drag looks: a title-bar flash, pixelation from off-screen writes, and then 192e67f2, Build 118, which draws first and clears only the exposed strips, citing the real machine: "eliminates the ~280ms blue-screen flash during dragging on real 8088 hardware (17,600 pixels -> ~900 for a typical 3px drag step = 19x faster)".

Build 119 (e1f6b209) is where the phrase in this essay's brief appears:

IRQ12 could fire between XOR draw and cursor_visible flag update when running in INT 0x80 context (STI enabled), causing ghost cursor artifacts and progressive display corruption. Fixed by wrapping cursor_hide/show in PUSHF/CLI...POPF for atomicity.

That is a correct diagnosis of a real race, and it is also the moment the stretch goes wrong, because all of these fixes are cosmetic. Under them the window still does not move; the agent has been polishing the appearance of a drag that is not happening. From Build 120 the commit messages stop claiming fixes and become an investigation, worth reading in order because they show a method working exactly as designed and still taking seven builds.

Build 120 (6d5411f3) plants three markers in video memory, one per stage of the drag pipeline. Build 121 (0977d107) reads them: "The drag_needs_update flag set by IRQ12 was never seen by mouse_process_drag (debug markers confirmed write but not read)". It replaces the flag with polling. The window still does not move. Build 122 (168eb32a) force-moves the window to (10,10) whenever the button is down. Build 123 (d96806d1) reports:

Build 122 confirmed mouse_process_drag IS called and sees drag_active=1, but win_move_stub doesn't move the window.

So the markers go inside win_move_stub: entry, handle value, validation passed, state, "INVALID path taken", "move completed successfully". Build 124 (0914664f) replaces pixel markers with letters at the bottom of the screen and states what success would look like: "1 2 3 E 0 V U D C !". Build 125 (0d936ffa) reports that the letters came out exactly right:

Build 124 showed full path 123E0VUDC! executes, but window doesn't move.

Read that twice. The function is entered, the handle is valid, the position is "updated" (the U), the frame is drawn (the D), and the window is where it was. Every checkpoint passes and the effect is absent. Build 125 prints the target coordinates in hex; Build 126 (38d5c5be) fixes the diagnostics' own rendering, because the hex was unreadable.

Build 127

82c5a8d1, February 13, 01:24: "Fix BP segment override bug in win_move_stub - window dragging works (Build 127)".

ROOT CAUSE: In x86 real mode, [BP+disp] defaults to SS segment, not DS. win_move_stub used BP as window table pointer but all [bp + WIN_OFF_*] accesses were hitting SS:BP (address 0x0000:offset in IVT/BIOS area) instead of DS:BP (address 0x1000:offset in kernel data). The window table was never actually updated, so win_draw_stub always redrew at the original position. Fix: Add explicit ds: segment override to all [bp + ...] accesses.

The diff is twenty lines in kernel.asm. Six instructions, mov ax, [bp + WIN_OFF_X] and its siblings, become mov ax, [ds:bp + WIN_OFF_X]. The U in the diagnostic string was honest: the code did update a position. It updated six bytes of the interrupt vector table area at 0x0000, and the window table at 0x1000 never heard about it. Then win_draw_stub read the table, correctly, and drew the window where the table said it was.

Nothing in the seven diagnostic builds could have found this, because every probe tested control flow, and control flow was fine. The bug was in the address of a data write, and a wrong address in real mode looks exactly like a right one until something reads the memory you meant. The architecture doc at v3.34.0 still explains why the kernel sits at 0x1000: "DS, ES and CS are all 0x1000 during kernel execution, so no segment manipulation is needed for kernel-internal addressing." True for DS, ES and CS. SS is 0x0000, and BP belongs to SS.

Two more builds close the range: Build 128 (e86c93c8) clears the content area on a move, and Build 129 (7902c99e) adds a drawing context, APIs 31 and 32, so apps "draw at (0,0) = top-left of content area, never see absolute coords". The kernel is 6,104 lines. The window manager, as a thing that keeps its promise, starts here.

The tax, before and after

I have called this a tax because it was paid repeatedly, and the history lets me itemise it. Before Build 127 the same class of bug had already been fixed, each time as if it were new: 05742a30 on January 22, "FIX: Set ES segment before drawing text"; df7b7a00, Build 015, which saves the caller's DS and ES at the syscall boundary after "the clock app showing garbled title 'SQRMU'"; f842a79e, Build 034, DS left pointing at the caller during file open; 26961681, Build 064, where cmpsb compared against the wrong ES and reported "KERNEL.BIN not found" even though disk reads worked; 1024f4a9, Build 083, font data read through the wrong DS.

After Build 127 it kept coming. acdae62c, Build 134, a day later: the inverted-string routine "read from kernel segment (DS=0x1000) instead of caller's segment, causing white garbage boxes". 67ad58e7, Build 150: the opposite mistake, "window title bars reading from wrong segment", because titles live in the kernel and the routine had just been taught to read the caller's. e123549a, Build 306: a VGA icon path read screen_pitch "without a segment override", so every icon landed at the wrong offset and appeared invisible. 8f82e329, Build 312: "Fix DS segment corruption in sprite drawing and pixel plotting", presenting as three unrelated symptoms, "Music app notes not rendering, Clock empty window, and Sysinfo crash on exit".

None of these are stupid. They are one fact, that the CPU will not tell you which segment you meant, surfacing through different routines as the kernel grew from one segment to a kernel, a shell and six application segments (099e00f1, Build 149). The lesson was re-learned per routine because there was nowhere for it to live except the routine.

What the project did about it

Three things, and they are the part of this story that transfers.

First, it wrote the rule down where the next agent would read it. c9329015, Build 135, eight hours after the fix, added a section to CLAUDE.md headed "BP/SS Segment Bug": "CRITICAL: In x86 real mode, [bp + displacement] defaults to the SS segment, NOT DS! ... Always use explicit [ds:bp + offset] override when accessing kernel data via BP." That file was deleted for the public release (29f7a50f, March 15, "Remove CLAUDE.md (AI assistant instructions)"), but the rule had already migrated to the developer guide, and at v3.34.0 it is item 5 of the common mistakes in docs/APP_DEVELOPMENT.md: "[BP + offset] defaults to the SS segment, not DS. This is a known x86 quirk. If you must use BP for data, write [ds:bp + offset]." The comment in win_move_stub itself, "NOTE: BP defaults to SS segment in x86 real mode!", is still at line 20,499 of a file that is now 23,285 lines.

Second, and more interesting, it changed the convention so the rule is needed less often. The Build 312 message says it plainly: CS overrides were added to the pixel and clear routines "so they work correctly regardless of DS value". The kernel's code segment is always 0x1000; DS is whatever the last routine left it. Addressing kernel data through [cs:...] makes a routine correct no matter who calls it, and you can watch the convention spread by counting: kernel.asm has four [cs: accesses at Build 127, nineteen at v3.15.0 two days later (f122a22f), 370 at Build 312, and 540 at v3.34.0. The BP form is used six times with its override and seven times without, and all seven read a real stack frame through mov bp, sp, the one case where the default is right.

Third, months later, the same principle was applied to a neighbouring silent bug. dc7f8641, June 11, the 8088 compatibility pass: the audit "found 1,153 non-8086 instruction sites across 21 files; on a real 8088 PUSHA/POPA execute as JO/JNO (silent control-flow corruption)". The sentence I keep: "'cpu 8086' directives in every converted file turn future regressions into assembly errors." The segment bug cannot be made an assembly error, because [bp+4] is legal and means something. Where the toolchain can be told to refuse, the project told it to.

Z-order, and the ghosts, for the record

Both belong just after this range, so briefly. Z-order is Builds 139 to 160, February 13-14: a7404880 introduces the stacking (a focused window goes to z=15, everything else is demoted); 7b329ac3 stops clicks falling through a window's body to a title bar behind it; d1726e7f drops draws from non-topmost windows; 228b6e6f removes that clipping because blocked apps were "leaving the window empty"; 63eebf97 and b7a57f7c put it back, differently. The drag was rewritten once more (310706b8) to the XOR outline that "moves on release", still the form the x86 build ships, and f122a22f, v3.15.0, is the first milestone to list "Z-order management".

The ghost cursor was the XOR invariant from Build 110 breaking on the boot path. Builds 221, 222 and 224 (e3ccdb2d, c7f7b829, 298b974a), February 17, chase a phantom at (160,100) through the CGA mode switch. Build 227 (0f5bbde7) names the root cause: the launcher's fast_clear_screen "wrote directly to CGA memory without hiding the mouse cursor, breaking the XOR invariant". The comment above that routine at v3.34.0 still says so: "Direct CGA writes break the XOR cursor invariant, leaving ghost cursors."

The lesson

Seven builds of instrumentation proved that every line of win_move_stub executed, and none of them could see that the line that mattered was writing to the wrong memory. A bug that leaves no trace in control flow will not be found by tracing control flow; when a class of bug is silent by construction, the fix is a convention that makes the wrong form hard to write, recorded where the next reader will see it, not a better debugger. The rule moved from a commit message to an agent instruction file to a developer guide to an addressing convention adopted 540 times, and only the last of those reduced the count. The next essay is about what the window manager was for: cooperative multitasking, and how many applications fit on one 1.44 MB floppy when the judge is a 486.

Sources: https://github.com/hmofet/unodos, commits 01e3b156 through 47ad7172 (Builds 110-129, February 12-13), in particular e1f6b209, 6d5411f3, 0977d107, 168eb32a, d96806d1, 0914664f, 0d936ffa, 82c5a8d1; earlier segment fixes 05742a30, df7b7a00, f842a79e, 26961681, 1024f4a9; later ones acdae62c, 67ad58e7, e123549a, 8f82e329; z-order a7404880, 7b329ac3, d1726e7f, 228b6e6f, 310706b8, 63eebf97, b7a57f7c, f122a22f; ghost cursor e3ccdb2d, c7f7b829, 298b974a, 0f5bbde7; c9329015 and 29f7a50f for CLAUDE.md; 099e00f1; dc7f8641; docs/ARCHITECTURE.md, docs/APP_DEVELOPMENT.md, kernel/kernel.asm and apps/launcher.asm at v3.34.0.

The OS in this piece runs in your browser. No install, no sign-up: boot it in a tab, or download it for any of 22 machines.

Get the next one

New essays roughly every other week: the war stories, the method, and the receipts. No spam, unsubscribe in one click.

Prefer a reader? RSS.