An interactive reading of the leaked Windows XP source code

Source: lr0.org
21 points by dgv 6 hours ago on lobsters | 4 comments

Windows XP turns 25 very soon.Windows XP anniversaryI was writing this in Sept 2026, as of time of editing, XP is 25 and many weeks old It came out on the 25th of October 2001, a lot of people learned what a computer is on it, maybe not for the best as I argued before.

Six years ago an image board user leaked Windows Server 2003 source code along with other older leaks and I was expecting to read some kind of analysis and people digging into it, perhaps someone finally validating claims about the NSA backdoor or some fun readings, kind of Computer History Museum stuff. I really enjoy reading historical code, especially now that most code I read is LLM generated, I was expecting someone doing something with that leak very soon, but so far all what I could find are low-quality videos showing funny comments in the source code and looking for curses.

I wanted to know what was going on, how they built it, because the development of Windows really predates a lot of the things I know about building software. So last month I started having inside looks into the source.

The demos in the blog post run the code visualized, with a great help of LLM free usage, I was able to port them to JavaScript, if I had to approximate something, the demo says so. A few of them load data that also shipped inside retail XP files (for example the boot bitmaps are resources in ntoskrnl.exe, and the compatibility entries end up in sysmain.sdb).

Abandoned projects

Windows XP shell has an unshipped alternative to the familiar Start menu, behind a build flag called FEATURE_STARTPAGE, a full-screen "Start page prototype", written in DirectUI. Press Start and, instead of a menu, the desktop rises over your open windows as a page with "Welcome" and your name in large Trebuchet, reminded me a bit of the beloved Windows 8 Metro Start Menu. It stays off unless a registry value called FaultID is set to 101. The comments say FaultID is a decoy. They picked 101 because it would be hard to guess.

shell/explorer/tray.cpp, lines 206 to 211

// FaultID is a decoy so that hackers won't think of trying to enable this feature.
LONG lRet = SHRegGetUSValue(REGSTR_PATH_EXPLORER, TEXT("FaultID"), &dwType, &dwData, &cbData, FALSE, &dwDefault, sizeof(dwDefault));
if (lRet == ERROR_SUCCESS && dwData == 101)  // Some random value not easily guessed
    s_fEnabled = TRUE;
else
    s_fEnabled = FALSE;

One detail if you were thinking of trying this on a copy of XP. Explorer checks FaultID. It still needs a build with FEATURE_STARTPAGE defined for there to be anything to switch on. I don't see one in the tree, which as far as I can tell rules out the page in retail XP.

For the version on my blog I had the original artwork and the markup for the page. The rest is a browser putting it on the screen. I put the familiar XP panel next to the reconstructed page.

Source-backed reconstruction of Explorer's unshipped Start page.

The unshipped Start page reconstructed from original artwork.
The unshipped Start page, reconstructed from its original artwork. The interactive reconstruction is available on a larger screen.

I was talking about alternative Start menus, but even the Start button could have looked quite different. There is a theme under shell/themes/themedir/candy where you get a rounded Start button, glassy little radio buttons and push buttons that look like shiny capsules. It looks an awful lot like early Mac OS X to me, especially beside the blue and green of XP. Apple introduced Aqua in January 2000. The date in Candy's metadata is July 13, 2000, for the last update.

shell/themes/themedir/candy/themes.ini, lines 5 to 14

[documentation]
DisplayName = Candy
LastUpdated = 07/13/00
ToolTip = Ryan's Candy Skeme (for internal use only)
Author = t-ryanb
Company = Microsoft Corporation
Copyright = Copyright © Microsoft Corporation, 2000
URL = http://www.microsoft.com
Version = .10
Description = Whistler skin with eye candy

In the blog demo the pictures are from Candy and Luna. I put together the controls I had images for, so you can hold the button down or move the mouse over it, tick the checkbox, etc. The browser still does the layout and the text (on a smaller screen it's just a picture). There's been coverage of Candy since the 2020 leak. The source gives little indication why work on Candy stopped.

Reconstructed Candy and Luna windows. Candy has glossy capsule buttons and a flat blue title bar; Luna has the familiar bright blue XP frame.
Selected Candy and Luna controls, reconstructed from the original bitmaps. Candy is incomplete. The interactive preview is available on a larger screen.

Active Window

Window text

Advanced Appearance

About Display Properties

Candy .10
Ryan's Candy Skeme (for internal use only)
Author: t-ryanb
Last updated: 07/13/00

Selected Candy and Luna controls reconstructed from original bitmaps. Text and layout are browser-rendered. Candy is incomplete and excluded from the normal theme build.

Candy definitions · Original buttons
Luna definitions · Source manifest

There is actually a note of that kind in shell/ext/neptune, three lines somebody left to explain the continued existence of a whole directory. Even at the time they figured the code probably wouldn't compile. They hung on to it “if we ever want to pillage it”.

shell/ext/neptune/neptune.txt, lines 1 to 3

This directory is for long-term storage of old code from the Neptune project.
This code probably doesn't compile; it isn't intended to.  It's here so that
the work we did then isn't lost if we ever want to pillage it.

One thing they might have wanted again was the bit that lets you take files and folders in the shell and copy them to a WebDAV server. You even get the address of somebody's test server, http://aidanl:8088/dav/aidanl/. The little driver gathers up the files and folders, makes a DAVStorage object for that address and copies them into it.

Suppose all your data lived on the server. What would you keep on the PC? Ben Slivka, who did the RedShark prototype in 1998 with Joe Belfiore and Steve Capps, describes a secure cache you could work with even if the connection went down. In their Neptune service you'd organise your work into projects. Reading the mail from February 1999, I don't think the fight was really over the cache. Brad Schick opened the discussion by asking who Neptune should serve.

… target AOL customers …

Schick circulated a memo proposing a shift away from the existing Windows market. Brad Schick, February 7, 1999, page 4.

Slivka thought they were going to lose if they tried to win the Internet through Windows.

… win the Internet using Windows is a losing strategy.

He agreed with Schick and wanted separate mandates for the Windows and Internet teams. They could still work together where it helped both. Ben Slivka, February 10, 1999, page 3.

Brad Silverberg wanted the team to set its release schedule without taking on Windows's compatibility obligations.

… compatible with existing apps […] windows release schedules …

Silverberg asked whether Neptune would have to run applications like Office. He thought the project needed a separate name and an independent team so it could address the needs of connected consumers and ship without waiting for the next Windows release. He pointed to Internet Explorer as a precedent for releasing separately. Brad Silverberg, February 14, 1999, pages 2–3.

David Cole wanted the connected experience in Windows itself.

… simple connected user experience in Windows.

Cole wanted that experience available to all Windows users and said the IE team was calling it IE 5.5. He used Neptune for the broader work of making PCs simpler and more useful. He supported doing both. David Cole, February 10, 1999, pages 3–4.

Abandoned web

Some of the web stuff is even older. In multimedia/danim/doc/homepage there's Microsoft's homepage for ActiveVRML, and the bit of animation they used their web language for there was a blinking star. They had a much wider use in mind, you can see it in the 1996 research report. An image or a sound or some geometry could have a value that varied with time. If I were making an animation I could describe continuous motion and discrete events, then leave the work of producing the frames to the engine. The star on their page takes two definitions.

multimedia/danim/doc/homepage/homepage.avr, lines 26 to 37

starImage(x, y, delay) =
    let
        s0 = dimImage    until after(delay) => function(x) . s1;
        s1 = brightImage until after(0.25) => function(x) . s0;
    in
        transformImage(
            translate(
                x * backXSize,
                y * backYSize
            ),
            s0
        );

One is s0, the dim star, which waits for a delay and becomes s1. The other is s1, the bright star, which waits a quarter of a second and becomes s0 again. Those dated web graphics also have a place in the history of functional reactive programming. Conal Elliott wrote in 1997 that ActiveVRML was where both Fran and DirectAnimation came from. With Fran the idea went into Haskell and what we'd call functional reactive programming. With DirectAnimation you could use some of the same ideas alongside imperative programming from a mainstream language. That one ended up being bundled with Internet Explorer.

I reconstructed the homepage from its original images and the timings in that script.

Reconstruction of Microsoft's original ActiveVRML homepage animation.

Still of the reconstructed ActiveVRML homepage.
ActiveVRML's homepage, reconstructed from its original images and animation script. The animation is disabled at this screen size.

In July 1998 Microsoft proposed putting HTML on the faces of a cube. You could turn it to find something else to read, and the menu bars could bend out of your way. The name was Chromeffects and it was an add-on for Windows 98. You wrote the page in HTML and XML and got animation, sound and 3D from DirectX. Come November, Microsoft said it was stepping back to rethink Chromeffects after hearing from developers. Its Windows source sits in multimedia/danim/src/lm/chrome.

multimedia/danim/src/lm/chrome/src/factory.cpp, lines 3 to 15

// File: factory.cpp
// Author: jeff ort
// Date Created: Sept 26, 1998
//
// Abstract: Implementation of CCrBehaviorFactory object which implements
//           the chromeffects factory for DHTML behaviors
//
// Modification List:
// Date     Author      Change
// 09/26/98 jeffort     Created this file
// 10/21/98 jeffort     Changed FindBehavior from using class to using the tag
//                      to determine the behavior type being created
// 11/12/98 markhal     FindBehavior now accepts null arguments

Classic spam filter

Outlook Express has, in inetcore/outlookexpress/oejunk, a machine-learned spam filter from 1998. Robert Rounthwaite's header describes a support vector machine that checks the mail as it comes in.

inetcore/outlookexpress/oejunk/junkeng.cpp, lines 1 to 6

/*

  SVMHANDLER.CPP
  (c) copyright 1998 Microsoft Corp

  Contains the class encapsulating the Support Vector Machine used to do on the fly spam detection

The model, junkmail.lko, is a plain text file with four constants for a sigmoid (the engine reads two of them), a threshold that's subtracted from the score before the sigmoid, three cut-offs for the sensitivity setting (the default, the strictest and the loosest; the two settings in between are halfway points), and 1,264 weighted features: 1,230 words and phrases to look for in the body, 22 in the subject, and 12 hand-written rules.

inetcore/outlookexpress/setup/cab/junkmail.lko, lines 3 to 12

aa =  1.000000 bb =  0.000000 cc =  -5.825104 dd =  -3.615463
Threshold =  1.090667 dThresh =  0.990028
mThresh =  0.999978 lThresh =  0.986543
NumDim = 1264
Weights
-0.717402  5:16
 0.323676  1:4:FREE
 0.319125  1:5:MONEY
 0.380937  1:6:REMOVE
-0.306643  2:2:RE

In that file you can tell where a word has to appear by the number at the start of the feature. For example 1: is something to look for in the body of the message, 2: in the subject line, 5: is one of their hand-written rules. All the engine does with the features that turned up is total their weights and subtract the threshold. Have a look at the end of _DblDoSVMCalc and there's the conversion of that number x to 1/(1 + e^(cx + d)).

inetcore/outlookexpress/oejunk/junkeng.cpp, lines 1042 to 1048

// Apply threshold;
dblAccum -= m_dblThresh;

// Apply sigmoid
dblResult = (1 / (1 + exp((m_dblCC * dblAccum) + m_dblDD)));

return dblResult;

There happen to be two numbers in there worth looking up, cc = -5.825104 and dd = -3.615463. They're the constants this filter uses for what is now the standard Platt scaling of an SVM score into a probability. John Platt actually came up with the scaling for this filter if you go by David Heckerman's memoir. In the 1998 paper by Heckerman, Eric Horvitz, Susan Dumais and Mehran Sahami, the filter was naive Bayes. Many of the features are already there in the paper. The SVM did a better job, hence Platt's version in the source. It makes for a nice record of email at the time too, because FREE, MONEY, REMOVE, !!! and OPPORTUNITY were votes for junk, while EDU, THANKS and FORWARDED went the other way. The strongest feature they had was being addressed to you directly (-0.717).

It never shipped switched on, because of a greeting card company. The filter was in the Outlook Express that came with the Internet Explorer 5 beta in 1998, off by default, and with its threshold turned towards "catch more" it sent Blue Mountain Arts' e-cards to the junk folder. Heckerman says his team promised a fix by the end of the week; before the week was out Blue Mountain sued, the press decided Microsoft was trying to kill a competitor, a court ordered Microsoft to help Blue Mountain's mail get through (Microsoft's statement, December 1998), and "the spam filter was promptly removed from Outlook Express".

In XP's Outlook Express the settings page is still there. Put a non-zero value under the meaningless name bhgcc in HKLM\Software\Microsoft\Outlook Express\5.0, and a Junk Mail page appears in the message rules. Outlook Express checks once as it starts up (c_szRegJunkMailOn is the string "bhgcc", and Athena was Outlook Express's code name).

inetcore/outlookexpress/mailnews/shell/instance.cpp, lines 340 to 356

void _CheckForJunkMail()
{
    HKEY hkey;
    DWORD dw=0, cb;

    if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, c_szRegRoot, 0, KEY_QUERY_VALUE, &hkey))
    {
        cb = sizeof(dw);
        RegQueryValueEx(hkey, c_szRegJunkMailOn, 0, NULL, (LPBYTE)&dw, &cb);

        if (dw)
            g_dwAthenaMode |= MODE_JUNKMAIL;

        RegCloseKey(hkey);
    }

}

XP's setup deletes oejunk.dll and its model, junkmail.lko, when it installs Outlook Express, and the model is commented out of the install package under CONDITIONAL_JUNKMAIL. But XP's upgrade database lists an oejunk.dll among Internet Explorer 5's files and a 28,370-byte junkmail.lko among the system files of Windows 98 Second Edition, and the model in this tree is 27,099 bytes with Unix line endings, exactly 28,370 with Windows ones, with the same checksum setup records. So the filter a lawsuit took out of Outlook Express very probably went out anyway, switched off, with Windows 98 Second Edition in 1999. Microsoft finally shipped machine-learned spam filtering in MSN 8 in 2002, because, Heckerman writes, a programmer on that team found the old code and sneaked it in.

Loading the model

The 1998 model from junkmail.lko, all 1,264 features, with the matching rules ported from junkutil.cpp and junkeng.cpp. Try the presets, then write a message. The biggest push towards "legitimate" is being addressed directly to you, an empty To line counts against you more than any word does, and dating the same spam 1998 is enough to get it into the inbox.

About the backdoor

Of all the stories I had in mind when I started looking at the leak, the NSA one seemed the easiest to put a question to. A very odd name had once fallen out of a Microsoft binary. What did the thing with that name actually do?

That accusation is _NSAKEY. In 1999 a researcher poking at a Windows NT service pack found that the part of Windows that checks cryptographic modules carried two public keys, and that a leftover debug symbol had named the second one _NSAKEY. The possibility that Microsoft had given the NSA a separate signing key quickly made news around the world. Microsoft said the second key was a backup in case the first was ever lost, and that its name came from work on export rules. The name alone couldn't establish who held the corresponding private key.

Now there's a source tree to put beside that story. The Windows code for verifying signatures on cryptographic providers calls the two production keys KEY and KEY2. It also distinguishes keys for development and test builds. The pair in the shipping configuration agrees with the number the researcher found in 1999.

mergedcomponents/advapi32/cryptapi.c, lines 5318 to 5339

    if (CRYPT_SUCCEED == (fRet = CheckSignature(rgbKey, 128, pbSig,
                                                cbSig, pbHash, fUnknownLen)))
    {
        fRet = TRUE;
        goto Ret;
    }

#ifdef MS_INTERNAL_KEY
    if (CRYPT_SUCCEED == (fRet = CheckSignature(rgbMSKey, 128, pbSig,
                                                cbSig, pbHash, fUnknownLen)))
    {
        fRet = TRUE;
        goto Ret;
    }
#endif

    if (CRYPT_SUCCEED == (fRet = CheckSignature(rgbKey2, 128, pbSig,
                                                cbSig, pbHash, fUnknownLen)))
    {
        fRet = TRUE;
        goto Ret;
    }

Nothing around KEY2 calls it a backup, an escrow, a spare or the NSA's. I couldn't find the string nsakey in this tree. The change log starts in December 1994, records “Increased signature key to 1024 bits” in April 1995 and “Added Microsoft's signing key” that September. It doesn't say when or why the second one came along. Both are public keys for verifying signatures. Seeing them in Windows tells us nothing about decrypting somebody's data, and the public half doesn't identify the custodian of the private half. Microsoft's backup explanation fits what I found, but I can't prove it from this code.

I looked at the rest of the usual suspects too, with help. Windows does carry Microsoft's test root certificates. On an ordinary installation these were not trusted by default, and for HTTPS there is a dated comment, “On July 26, 2000, disabled the use of the test root”. In the account code the cases I found turned out to belong to domain setup or to autologon configured by the administrator. The network destinations I identified included the crash reporter at watson.microsoft.com, Windows Update, time.windows.com and Passport. These were identifiable Microsoft services. I didn't find a hidden login or a covert reporting destination in the cases I examined.

There are places where the engineers recorded their security worries quite plainly. Comments in the C runtime, the kernel and the DNS server explain why particular features were withheld from ordinary builds. I also found a developer's removal note in the 64-bit Terminal Server source. It concerned an administrative feature absent from the 32-bit version most people ran. A note like that records what the developer wanted done. It doesn't settle what finally shipped. I found no evidence for the alleged backdoor in the code I examined.

What you can find a government doing in Windows is deciding where people may encrypt things. NTLM once looked up the default locale in IsEncryptionPermitted. Standard French as the language or France as the country was enough for it to decline encryption. Whoever maintained the code put the paperwork right next to it, “permission to remove FRANCE check obtained 08-21-1999”.

ds/security/protocols/msv_sspi/encrypt.cxx, lines 53 to 57

//
// sfield: permission to remove FRANCE check obtained 08-21-1999
//

#if 0

By the time of this source the routine returned true on every machine. The old test was still there, excluded from the build, and the description still said to check France. French rules had changed that March to allow the use and import of systems up to 128 bits under specified conditions. I don't know whose approval the note referred to in August. A function with practically nothing left to do had kept the date the restriction came out.

An American export restriction survives in the Windows service for protecting an application's stored secrets, DPAPI. In GetSaltForExportControl the programmer describes the defect in the key Windows has just derived. The thing could have more than forty secret bits.

ds/security/cryptoapi/secstor/dpapisvc/capiprim.cpp, lines 214 to 226

// USEC -- (US Export Controls)
DWORD GetSaltForExportControl(
        HCRYPTPROV  hProv,
        HCRYPTKEY   hKey,
        PBYTE*      ppbSalt,
        DWORD*      pcbSalt)

{
    DWORD dwRet;

    // fix bug: derived keys will be > 40 bits in length

    // fix is to stomp derived key with exposed salt (Provider knows what is legal!!)

The provider supplied the allowable amount of salt. Windows supplied fresh random bytes for it, then saved those bytes with the result, so whoever had the encrypted data had that part too. A provider without salt support gave the helper nothing to replace. It mattered which provider and key type were in use, and DPAPI here already defaulted to 3DES. On January 18, 2000 Microsoft announced that the relaxed American rules let it put 128-bit encryption in Windows 2000 for customers worldwide. There's a Mozilla announcement with the same date that I think puts the old regime rather well. People working on the browser could finally publish the security source and accept changes from developers abroad.

The blue screen

The file responsible for the blue screen is base/ntos/ke/bugcheck.c, although if you go by what Mark Lucovsky put at the top of the file back in 1990 you would think you were reading stubs.c. KeBugCheck2 stops the other processors and takes over the display. The blue part is literally a rectangle, 640 by 480, and it sets white as the colour for printing on it.

base/ntos/ke/bugcheck.c, lines 979 to 989

if (InbvIsBootDriverInstalled()) {

    InbvAcquireDisplayOwnership();

    InbvResetDisplay();
    InbvSolidColorFill(0,0,639,479,4); // make the screen blue
    InbvSetTextColor(15);
    InbvInstallDisplayStringFilter((INBV_DISPLAY_STRING_FILTER)NULL);
    InbvEnableDisplayString(TRUE);     // enable display string
    InbvSetScrollRegion(0,0,639,475);  // set to use entire screen
}

Something I like about the big names printed on that screen is that you can go looking for the error message and be looking in exactly the right place and still find an empty line. Open base/ntos/nls/bugcodes.mc at 0x7A, for instance. That's an empty English message, one of 160 in a list of 227 fatal codes. The detail you need to know is in another program altogether, sdktools/mc, which builds the messages and substitutes the name when there's nothing else to use. Go down one entry to 0x7B (Windows can't find the disk it needs to start) and there's advice written for the user. When you get that one you don't see the name. Whether someone had intended to write all 160 messages and never got around to it, I have no idea.

base/ntos/nls/bugcodes.mc, lines 670 to 681

MessageId=0x007A Facility=Kernel Severity=Fatal SymbolicName=KERNEL_DATA_INPAGE_ERROR
Language=English
.

MessageId=0x007B Facility=Kernel Severity=Fatal SymbolicName=INACCESSIBLE_BOOT_DEVICE
Language=English
Check for viruses on your computer. Remove any newly installed
hard drives or hard drive controllers. Check your hard drive
to make sure it is properly configured and terminated.
Run CHKDSK /F to check for hard drive corruption, and then
restart your computer.
.

Another thing about looking up a blue screen is quite a lot of the diagnosis has happened before you ever get to see it. Suppose the original error was IRQL_NOT_LESS_OR_EQUAL, 0xA. KeBugCheck2 has the address of the instruction that went wrong. Its first checks are for instructions in the pool and system-PTE allocators, which can change the number to one of three codes saying a driver corrupted something. If it was an instruction in a driver you get DRIVER_IRQL_NOT_LESS_OR_EQUAL, 0xD1. There's another possibility, that the instruction really is in the kernel but the memory it touched belongs to a driver. For this one you get 0xD3 and the filename goes on screen.

base/ntos/ke/bugcheck.c, lines 666 to 678

case IRQL_NOT_LESS_OR_EQUAL:

    ExecutionAddress = (PVOID)BugCheckParameter4;

    if (ExecutionAddress >= ExPoolCodeStart && ExecutionAddress < ExPoolCodeEnd) {
        KiBugCheckData[0] = DRIVER_CORRUPTED_EXPOOL;
    }
    else if (ExecutionAddress >= MmPoolCodeStart && ExecutionAddress < MmPoolCodeEnd) {
        KiBugCheckData[0] = DRIVER_CORRUPTED_MMPOOL;
    }
    else if (ExecutionAddress >= MmPteCodeStart && ExecutionAddress < MmPteCodeEnd) {
        KiBugCheckData[0] = DRIVER_CORRUPTED_SYSPTES;
    }

It does much the same with a page fault. What you saw on the screen was already somebody's theory about whose fault it was. Now suppose the screen said 0x0000008E. You restart and there's 1000008e in that little “Windows has recovered from a serious error” report. It was the same crash both times. XP, once it had finished drawing the screen, added a flag (0x10000000) to certain codes when writing out a small memory dump. In Microsoft's documentation you can find the second number under the old name with an _M on the end.

There's at least one case where it knows exactly whom to blame. The PS/2 keyboard driver on a suitably configured XP machine let the operator request a crash dump. Its code is 0xE2, MANUALLY_INITIATED_CRASH. The English message reads “The end-user manually generated the crashdump.”

STOP CODE

IN THE DUMP

PALETTE

CURSOR

    A blue screen drawn the way bootvid draws it: palette slot 4 for the background, slot 15 for the text, and the 8 by 13 font from bootdata.c, fourteen pixels a line. The texts are the ones in the message file, including the empty ones that come out as symbolic names. Compare the first two scenarios: the same 0x0000000A becomes 0x000000D1 when the failing instruction was in the driver, and 0x000000D3 when it was in the kernel touching an address inside the driver. The machine details are made up; the rules are the kernel's, down to the dump counter redrawing itself with a bare carriage return.

    Abandoned Talisman

    How much of a graphics workstation could you get into a cheap PC? Microsoft's 1996 answer was Talisman, which saved some of the work of drawing a 3D scene by keeping pictures of the objects in it. Objects would be rendered into separate image layers. Between fresh 3D renders, hardware could move, rotate, scale and skew those layers, then composite them at the display's refresh rate.

    The XP tree preserves substantial unfinished DirectDraw work for that model. ddsprite.c has over three thousand lines implementing SetSpriteDisplayList, that was checking transforms, filtering and alpha support, clipping sprites, and collecting the sprites from different windows into a master list for the driver. A nearby colour-key check in ddsckey.c was disabled with the explanation "Talisman overlay sprite might not use overlay surface!" But ddsprite.c is commented out of the source list, and the callback that would expose the operation is behind POSTPONED2.

    multimedia/directx/dxg/dd/ddraw/main/ddcallbk.c, lines 712 to 716

    #ifdef POSTPONED2
        ddSurface7Callbacks.AlphaBlt = (LPVOID)DD_Surface_AlphaBlt;
        ddSurface7Callbacks.SetSpriteDisplayList = (LPVOID)DD_Surface_SetSpriteDisplayList;
        ddSurface7Callbacks.Resize = (LPVOID)DD_Surface_Resize;
    #endif //POSTPONED2
    

    John Carmack had tried a similar shortcut in Quake. In a 1997 interview he described saving a rendered model as a sprite and putting the same picture up again in the next frame. It worked for too few frames before they had to draw the model again. He also argued that faster, cheaper memory had weakened Talisman's original premise. Asked what Microsoft should do with it, he said, "It should just quietly go away."

    Even with Carmack's objection you can see how much work had already gone into it. For instance, each application could supply sprites, and Windows had to gather them up before giving the driver the list.

    Talisman Test comparing a freshly rendered gold torus, blue sphere and colored cubes with reused image layers.

    Talisman Test shows freshly rendered 3D beside reused flat layers, with different lighting and intersections.
    A simplified illustration of reused image layers. The interactive graphics test is available on a larger screen.

    A lot of XP was a web page

    By 2001 there were web pages in all sorts of places you wouldn't have thought to open in IE. User Accounts is one. The first-run screens, Help and Support, System Restore, Remote Assistance and the photo publishing wizards are others. Even the Find and Print Preview dialogs in IE use its engine this way. The pages are HTML with script that can ask C++ objects to do things for them. You see some of the pages loose on disk. For the ones built into DLLs and EXEs the resource scripts list 345 entries marked HTML, which includes things like a stylesheet or an image so you shouldn't read that as 345 pages. This is also where you run into a limit of what got leaked. JScript, VBScript, Windows Script Host, MSXML, you can read their interfaces, but try following one of those into the actual engine. In the case of XMLHTTP my one lead is a WinHTTP source file thanking the MSXML people for the code. The path it gives starts with inetcore\xml, which is missing.

    inetcore/winhttp/v5.1/ihttprequest/httprequest.cxx, lines 8 to 9

    * Much of this code was stolen from our Xml-Http friends over in
    * inetcore\xml\http\xmlhttp.cxx. Thanks very much!

    There are 253 HTML files in base/ntsetup/oobe, where the first-run setup lives. The XP build uses them to make 122 pages. According to the notes they were ported "from the Millenium source tree", so there's some Windows Me you're looking at on your first XP boot. I don't know why these pages and their scripts all need a pass through the C preprocessor before they're ready for the CD. None has a #if or even a #include. About all I can see it doing here is stripping the comments. There are also 122 names the scripts on those pages can ask for on window.external. HasTablet, CalledFromMsn and InHighContrastMode are the sort of things setup wants to know. PlayBackgroundMusic is something it wants done. Twelve names give it another object, and for each of those some C++ programmer had to write the table saying which names that object answers to.

    base/ntsetup/oobe/msobmain/sysclock.cpp, lines 25 to 41

    DISPATCHLIST SystemClockExternalInterface[] =
    {
        { L"set_TimeZone",          DISPID_SYSTEMCLOCK_SETTIMEZONE          },
        { L"set_Time",              DISPID_SYSTEMCLOCK_SETTIME              },
        { L"set_Date",              DISPID_SYSTEMCLOCK_SETDATE              },
    
        // new oobe2 methods below, others are currently unused
    
        { L"Init",                  DISPID_SYSTEMCLOCK_INIT                 },
        { L"get_AllTimeZones",      DISPID_SYSTEMCLOCK_GETALLTIMEZONES      },
        { L"get_TimeZoneIdx",       DISPID_SYSTEMCLOCK_GETTIMEZONEIDX       },
        { L"set_TimeZoneIdx",       DISPID_SYSTEMCLOCK_SETTIMEZONEIDX       },
        { L"set_AutoDaylight",      DISPID_SYSTEMCLOCK_SETAUTODAYLIGHT      },
        { L"get_AutoDaylight",      DISPID_SYSTEMCLOCK_GETAUTODAYLIGHT      },
        { L"get_DaylightEnabled",   DISPID_SYSTEMCLOCK_GETDAYLIGHT_ENABLED  },
        { L"get_TimeZonewasPreset", DISPID_SYSTEMCLOCK_GETTIMEZONEWASPRESET }
    };

    Take get_AllTimeZones. You might expect a list of names to fill the box with. It hands the page one string with the OPTION tags around all the time zones already, so into the select box it goes.

    base/ntsetup/oobe/html/newoobe/timezone.htx, lines 49 to 51

    <script language="javascript">
    document.write(window.parent.external.SystemClock.get_AllTimeZones);
    </script>

    If you remember the little question mark that talked you through setup, its lines of dialogue account for 7,185 lines of JScript, including 751 calls to Agent_Speak. What do you do about the speech balloon in a language for which you haven't got a speech engine? In Chinese and Japanese they padded the line with zero-width spaces to give you time to read it. Even the music starts in JScript. A call to window.external.PlayBackgroundMusic() points an embedded Windows Media Player at title.wma. The design note wanted people to be able to develop a module “with little help from OOBE development”. PC makers even had an OEM API for replacing the question mark with a character they chose. The people writing the main page had plenty of trouble. Four times they explain in a comment that they had to resort to a hack to make the selected item in a menu visible. Farther on somebody has added “these hacks dont work anymore”.

    User Accounts came out of the control-panel file nusrmgr.cpl as an HTML Application. That is a page you run as a program with mshta.exe. There's no browser window around it. You saw this one on Home or on a Professional machine outside a domain. On 64-bit Windows and in the other cases you got the old dialog. One detail I like in the HTML version is where it puts the window sizing. It asks for at most 730 by 530 pixels before the declaration that makes the page an application. If you reversed those two you'd see the window change size.

    shell/cpls/nusrmgr/html/nusrmgr.hta, lines 19 to 38

      // Set the initial size of the window.  This must come before
      // the HTA:APPLICATION tag, otherwise we'd see the window resize
      var cxWidth  = Math.min(730, screen.availWidth);
      var cyHeight = Math.min(530, screen.availHeight);
      window.resizeTo(cxWidth, cyHeight);
      window.moveTo((screen.availWidth - cxWidth) / 2, (screen.availHeight - cyHeight) / 4);
    </SCRIPT>
    
    <HTA:APPLICATION
      id=idUM
      applicationName="User Account Manager"
      contextMenu=no
      icon=users.ico
      scroll=no
      scrollFlat=yes
      selection=no
      singleInstance=yes
      version=1.0
      innerBorder=on
    />

    What became of an HTML attribute once the browser had read it? In this page scroll and scrollFlat set flags on the hosted browser. Others can go right down to an ordinary Win32 window style. Trident defines caption=yes as WS_CAPTION, though User Accounts doesn't use that one. The Franklin Gothic for the headings is in the page. To get the colours right under Luna, a page behaviour asks the theme manager for the current scheme and loads cpwebvw.css from the theme DLL. The blue, olive green and silver versions thus come with different instructions for colouring the same page.

    One of the User Accounts tasks is an offer to associate your local login with a .NET Passport. The wizard could save the credentials, so the online identity would work for single sign-on. In WinInet, the Windows HTTP client, the constructor tests for Whistler, XP's name during development. It clears _fDisableTweener there and sets it on older systems. Clear the disable flag and Passport 1.4 is supported by default.

    inetcore/wininet/handles/hinet.cxx, lines 708 to 715

    if (GlobalPlatformWhistler)
    {
        _fDisableTweener = FALSE; // Tweener (Passport1.4 is enabled by default for Windows XP)
    }
    else
    {
        _fDisableTweener = TRUE; // by default disable Tweener for downlevels
    }

    You still had to agree to the association in the wizard. For some idea why that particular offer was sitting next to the ordinary account settings, look at Microsoft's March 2001 announcement of HailStorm, subsequently .NET My Services. Passport was to establish who you were. Your calendar, contacts and documents could then be made available to programs on whichever device you were at, including an XP computer.

    The consumer service Microsoft meant to host itself was shelved in 2002. The New York Times spoke to Microsoft's Charles Fitzgerald about the change. Passport survived it. In 2005 the company's identity architect Kim Cameron made the distinction quite nicely. On MSN, Microsoft was already in a relationship with the customer. On another company's site neither the proprietor nor the customer particularly wanted to bring Microsoft into it. In Cameron's judgment, “Passport failed in its mission of being an identity system for the Internet.” The client code for that mission had made it into Control Panel.

    System Restore and Help and Support run on a small in-house framework called Mars, which wraps IE's engine in a window declared in XML. System Restore's window is one trusted Trident panel called Contents. It fills the window and loads start.htm from rstrui.exe.

    admin/pchealth/sr/shell/marsui/srframe.xml, lines 1 to 12

    <Mars_App>
       <!-- the "Panels" tag contains all panels that will be created initially -->
       <Panels>
          <!-- here's our cool DHTML dynamic content -->
          <Panel PanelType="Trident" Trusted="true">
             <Name>Contents</Name>
             <Layout>
                <Position>Window</Position>
             </Layout>
             <StartUrl>res://rstrui.exe/start.htm</StartUrl>
          </Panel>
       </Panels>

    System Restore's scriptable object, CRestoreShell, has called itself "merely a dummy ActiveX control" since the XP rewrite, a wrapper in front of the class that does the work. A behaviour on the pages cancels F5, Ctrl+N, dragging and text selection everywhere, and the context menu and Backspace outside text boxes.

    admin/pchealth/sr/shell/res/rstrui.htc, lines 53 to 70

    switch ( event.keyCode )
    {
    case VK_F5 :    // Disable refresh!
    {
        event.cancelBubble = true;
        event.returnValue =  false;
        return false;
    }
    
    case VK_N :
    {
        if( event.ctrlKey == true )
        {
            event.cancelBubble = true;
            event.returnValue =  false;
            return false;
        }
        break;

    The calendar with the restore dates in bold is a general-purpose calendar behaviour from 1999, forked for System Restore with a numbered list of "Changes for SR UI" at the top. Help and Support uses five Mars panels, and its pages come from hcp://system/. It needed a fix inside IE itself. After a redraw bug moved its navigation bar a few pixels, IE6 learned to recognise the Help Center (a flag called _fInWindowsXP_HSS) and skip drawing a border for it. The email approving the fix is pasted into an interface file, ending "!!NEVER!! change GUID for SID_SMarsPanel and IMarsPanel." Remote Assistance is 69 more HTML files, under the code name Salem.

    XP was also moving away from all this. Windows 98, Me and 2000 drew folders with HTML templates called folder.htt, and XP replaced them with native task panes in DirectUI, the markup from the Start page prototype. If an administrator switched the old view back on, Explorer hashed a folder's template and compared it with 18 MD5 fingerprints of the stock 98, Me and 2000 ones, so it could swap those for the new view and leave customised ones alone. By SP1 even Add or Remove Programs had a DirectUI version, with the old HTML one still compiled in beside it.

    The browser's place inside Windows was also being negotiated in court. XP SP1 added Set Program Access and Defaults, the Add or Remove Programs page for choosing competing browsers and other programs and hiding access to Microsoft's equivalents. Microsoft's SP1 announcement explicitly ties these changes to its antitrust settlement. The implementation leaves a very literal trace. Hiding Internet Explorer sets the hidden and system attributes on iexplore.exe, while leaving it on disk. That decision then has to spread through the rest of the shell. The code that supplies Open With's applications checks for those attributes before offering IE.

    shell/shell32/fassoc.cpp, lines 559 to 565

    //  however, if the EXE has been marked as superhidden, 
    //  then the consent decree UI has hidden the app
    //  and it should not show up under the open with either
    if (fRet)
    {
        fRet = !(IS_SYSTEM_HIDDEN(GetFileAttributes(szExe)));
    }

    "Consent decree UI" is a comment in the file-association code. A legal remedy has become a test of two filesystem attribute bits.

    But another path in the same shell shows how much work it took to make a default browser mean what it said. A music folder's task pane offered "Shop for music online". Its handler gets the shopping URL and passes it to the current shell browser.

    shell/shell32/fstree.cpp, lines 820 to 826

    // Nope - look for the regular music buy URL
    hr = pThis->_GetShoppingBrowsePidl(pv, psiItemArray, pbc, &c_BuyMusic, &pidl);
    if (SUCCEEDED(hr))
    {
        hr = pThis->_BrowseObject(pidl, SBSP_NEWBROWSER);           
        ILFree(pidl);
    }

    _BrowseObject asks the current shell browser to navigate, with SBSP_NEWBROWSER requesting a new window. Following the call takes you through shdocvw into Windows's browser-frame machinery. It can reuse an existing built-in window or create one. It does not go through the user's registered alternative browser. On 15 January 2004, the Justice Department identified this exact shopping task as violating Section III.H of the final judgment because it opened IE even when the user had selected Netscape, Opera or Mozilla. Microsoft agreed to remove the override, without necessarily accepting the Department's interpretation. This SP1 tree predates that remedy. The distinction between opening a URL and telling the built-in browser to navigate it ended up in a federal compliance advisory.

    The script ran on the same objects web developers were using at the time, and some of it is recognisable. XMLHttpRequest is in the published interface definitions as a 14-member COM interface, much of it recognisable in today's API. Two members the web never took up were responseBody and responseStream. In inetcore/webcontrols there's a 374-line behaviour from 2000 that turns an element into a web-service client, calling SOAP services asynchronously through XMLHTTP. It isn't part of the XP build, and it looks like an early version of the WebService behaviour Microsoft later offered as a download.

    inetcore/webcontrols/src/netmethd/webserv.htc, lines 338 to 355

    var fAsync = mode == "async";
    __aryCall[iC].xmlHttp.open("POST", oService.soap.uri, fAsync);
    __aryCall[iC].xmlHttp.setRequestHeader("SOAPAction",
                                oService.soap.methods[args[1]].soapAction);
    __aryCall[iC].xmlHttp.setRequestHeader("Content-Type", "text/xml");
    
    var szPayload = "<?xml version='1.0'?>"
            + "<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>"
            + "<Body>"
            + szParams
            + "</Body>"
            + "</Envelope>";
    
    if (fAsync)
    {
        __aryCall[iC].xmlHttp.send(szPayload);
        __aryCall[iC].xmlHttp.onreadystatechange = getResult;
    }

    That's the pattern that got named AJAX five years later. It does set onreadystatechange after calling send(), though, the reverse of the usual order. The rest of IE6 is here too, and it explains a few things web developers remember. Its browser shell replaced a server's error page with a "friendly" page it generated when the body was 512 bytes or shorter (256 for a few codes), which is why people padded their custom 404 pages with junk.

    shell/shdocvw/dochostbsc.cpp, lines 444 to 450

    //
    // When an http error occurs the server generally returns a page.  The
    // threshold value this function returns is used to determine if the
    // server page is displayed (if the size of the returned page is greater than
    // the threshold) or if an internal error page is shown (if the returned page
    // is smaller than the threshold).
    //
    

    IE6's Privacy slider was doing more than choosing whether to accept cookies. It read a compact P3P statement in a site's HTTP headers about what the site said it did with the data, and compared it with the rules for the level you picked. The default Medium setting is two long strings of boolean expressions in inetcore/wininet/http/cookiepolicy.cxx, one for the site you're visiting and one for sites embedded in it. Alongside accept and reject, the cookie code has two decisions called "leash" and "downgrade".

    inetcore/wininet/http/cookie.cxx, lines 3373 to 3379

    // "leash" means that the cookie will only be used in 1st party context
    if (pState->dwPolicyState==COOKIE_STATE_LEASH)
        dwImpliedFlags |= INTERNET_COOKIE_IS_RESTRICTED;
    
    // "downgrade" option forces cookies to session
    if (pState->dwPolicyState==COOKIE_STATE_DOWNGRADE)
        dwImpliedFlags |= INTERNET_COOKIE_IS_SESSION;

    A leashed cookie can be sent when you visit the site that set it, but not when that site is embedded in somebody else's page. A downgraded cookie becomes a session cookie, so it is no longer saved for later browser sessions. Microsoft's flag definitions spell out those storage and sending rules. Windows was trying to have the browser read privacy policies for you. It could control when a cookie was sent and how long it survived. The promises about what the server did with the information were still the server's promises.

    The AlphaImageLoader filter exists, its header says, for "web pages that would like to display images that contain per pixel alpha", because ordinary PNGs went through a path that offered the decoder no surface with an alpha channel. The filter can stretch or crop an image but has only a TODO for tiling one, which is why you couldn't use it for a repeating background. CSS expression() values were handed to "the Trident recalc engine", which tracks dependencies between properties like a spreadsheet and always runs them as JavaScript. IE's conditional comments have an evaluator whose overview still shows an older syntax that could test the Java VM's version. A feature for client-side includes was never switched on.

    inetcore/mshtml/src/site/download/htmver.hxx, lines 16 to 20

    // To enable client-side <![include "http://www.foo.com/foo.htm"]> feature,
    // uncomment the following line
    
    // Not enabled for IE 5.0 - no time to test it
    // #define CLIENT_SIDE_INCLUDE_FEATURE

    On XP Professional you could be on the server end of the request as well. IIS 5.1 used Denali for Active Server Pages. There's a version each for XP and .NET Server in inetsrv/iis/svcs/cmp. The compiler replaces the literal HTML between pieces of script with numbered Response.WriteBlock calls. It recognises VBScript and three names for JavaScript, JScript, JavaScript and LiveScript, the name Netscape used before December 1995. Somebody left a 1996 “Microsoft ActiveX Server” credits page beside it, a list of numbers XOR-encoded using “Denali rocks!”. A marquee brings in the Denali Team, 129 people get thanks including Bill Gates, and Satchel Paige gets the last word about looking back. The build makes no mention of that page. The actual localhost page styles the product “Windows XP Server Internet Services”, presumably from before the rename. It also contains a rather optimistic comment about its JavaScript running before the ASP that generated it.

    Of the ASP applications I like Internet Printing best. You could read a shared printer's queue at the server's printers site. When the manufacturer supplied no status page, Windows asked the printer for its front-panel display over SNMP, using VBScript at the server. Each character went into a table cell against a grey background. The person trying to follow this in the code has the added pleasure of strBgnCol opening a row and strBgnRow opening a cell.

    printscan/print/spooler/inetsrv/aspapp/page1.asp, lines 91 to 119

    For i = 1 To iRow
        srcIndex = 1
        j = 1
        While j <= iColumn
            c = Mid (strArray(i - 1), srcIndex, 1)
    
            If c = "" Then
               tmpArray(j) = "&nbsp;"
            Else
                if Asc(c) <= 32 Then
                   tmpArray(j) = "&nbsp;"
                Else
                    If strLang = "JP" Then
                        tmpArray(j) = OleCvt.ToUnicode (c, 932)
                    Else
                        tmpArray(j) = c
                    End If
                End If
            End If
            j = j + 1
            srcIndex = srcIndex + 1
        Wend
    
        strHTML = strHTML & strBgnCol
        For j = 1 To iColumn
            strHTML = strHTML & strBgnRow & tmpArray(j) & strEndRow
        Next
        strHTML = strHTML & strEndCol
    Next

    Certificate Services in the server editions made allowances for IE, Netscape with KEYGEN, and “Lynx or other minimal browser”. The challenge in the Netscape form reads “provePequalsNP”. On XP Professional the IIS query extension for the Indexing Service, idq.dll, used .htx templates to format search results. Code Red spread through that component in July 2001, a month before XP was finished. Microsoft's bulletin MS01-033 dates the XP fix to Release Candidate 1. This tree already has the fix.

    The Indexing Service has a longer history than its web interface. It carries a piece of Cairo, Microsoft's early-1990s attempt to make documents searchable by their contents and properties as part of a much more ambitious operating-system design. The search engine was meant to live inside OFS, Cairo's proposed filesystem. There's a trace of the move out of it in svccatpx.hxx, the client-side proxy for the service catalog.

    inetsrv/query/h/svccatpx.hxx, lines 6 to 11

    //  File:       svccatpx.hxx
    //
    //  Contents:   client-side proxy to SVC catalog.
    //
    //  History:    28-Feb-1994     KyleP   Created
    //              16-Sep-1996     dlee    ported from ofs to cisvc
    

    Bartosz Milewski, who led the content-index work, wrote in December 2000 that his team had maintained two versions, the official one tied to OFS in the kernel, and another that ran in user mode against ordinary filesystems. He credits that second branch with letting the index survive OFS's cancellation. They had also used it to index NT's source code, making it valuable to developers who needed to find definitions and uses of functions. The component found a home in IIS, then Windows 2000. Microsoft's June 1996 announcement still explicitly sold the search technology, code-named Tripoli, as an element of Cairo.

    The header here is part of the live implementation. Asking the Indexing Service administration code to merge an index leads through ForceMasterMerge to the CSvcCatProxy class in that header, and the library is linked into Query.dll. The history says KyleP created the file on 28 February 1994 and dlee moved it from OFS to cisvc on 16 September 1996. A component designed to make a new kind of filesystem useful survived by becoming independent of that filesystem.

    XP's web services had a server side too, and some of it is here. When XP didn't know what program opened a file, it offered to "Use the Web service to find the appropriate program". The site that answered is in shell/tools/fileassoc (its notes begin "This project manages http://shell.windows.com/"), written in server-side JScript with an XML file per extension. It recommended RealPlayer, Winamp and CorelDRAW as readily as Microsoft's programs. The notes give the figures from the logs. PDF is far ahead with 231 requests (15.5660%), followed by the RealAudio playlist extension .ram with 137 (9.2318%), .rar with 89 (5.9973%), RealMedia .rm files with 78 (5.2561%), and .diz, the plain-text description inside a ZIP archive, with 37 (2.4933%).

    shell/tools/fileassoc/notes.txt, lines 399 to 406

    Count    Percent   Extension
    =======  =======   =========
        231  15.5660   pdf
        137  9.2318   ram           RAM Meta file (RealAudio)  (PlayList)
         89  5.9973   rar           www.winrar.com  (***)
         78  5.2561   rm            RealMedia Files
         37  2.4933   diz           ZIP Archive Product Description file (http://www.a-direct.com/fileid.html) (Use notepad, because always plain ascii)  (***)
         ------------------ 38.53%

    A version that would have looked the extension up in the background was switched off, an engineer explains, because they didn't want "to automatically submit the file extension of the user's file to the server without first asking for permission for personal privacy reasons". The Web Publishing and Online Print Ordering wizards work the other way round. The middle of the wizard is the provider's web page inside a native frame, the wizard's Next and Back buttons just call functions on that page, and the list of providers (MSN, Xdrive, Fujifilm, Kodak) was itself downloaded from shell.windows.com. Counting the Microsoft addresses hard-coded as strings into XP's code, I get about 280 across 24 hosts, and 161 of them go to redirectors (redir.dll and go.microsoft.com/fwlink) rather than to pages, presumably so Microsoft could move a page without patching Windows. Only one of the addresses I counted uses HTTPS, the activation address for Terminal Services licensing.

    Compatibility aka lies

    What I had in mind by calling it XP so far is really two somewhat different things. People who used Windows 2000 already knew the NT kernel and had good reason to worry about their games. For people coming from 95 or 98, XP was supposed to give them that kernel and still run all the stuff they had accumulated in the nineties. How? Well, look up windows/appcompat/db/dbu.xml. Seven megabytes of UTF-16, 1,988 programs from over 600 vendors, and instructions for Windows about what to do for each. There are 374 shims that get in between a program and a Windows function. There are twelve ready-made combinations of them (one is what you select by asking to run something in Windows 95 compatibility mode). Then there are 33 patches that actually change instructions in the running program. The busiest shim is hardly any code at all in principle. When asked which Windows it is, Win95VersionLie says 95. It's against 471 executables.

    windows/appcompat/db/dbu.xml, lines 2751 to 2757

    <SHIM NAME="Win95VersionLie" FILE="AcLayers.DLL" PURPOSE="GENERAL" ID="{D6C32382-0ABD-4BD2-AB9F-871F87EF0B6E}">
        <DESCRIPTION>
            Hooks the GetVersion and GetVersionEx APIs so that they return
            Windows 95 version credentials. Applications often check to
            ensure that they are running on a Win9x system, even though
            they will run OK on an NT based system.
        </DESCRIPTION>

    The part I found most interesting in this otherwise fairly tedious XML is that the testers got to leave notes. Most entries have them, dated, from the people finding the bugs and the engineers having to do something about them. There are 3,622, some in pretty exasperated English. If you're only on the Windows side of this you might say, well, a program should never have depended on that, it was a complete accident that it worked on 95. From the user's side this is a program that worked before they upgraded, and passing that observation on to the user doesn't do much to get it running. XP had to reproduce a fair number of those accidents.

    =EmulateHeap= is a funny name for it. HEAP.C says “Origin: Chicago”, and the thing in the XP compatibility library is the Windows 95 heap manager itself. That explains those 23 HEAPCHANGE entries under one engineer's name on 9 December 2000. Grim Fandango, M1 Tank Platoon II, BattleZone and others had been getting individual fixes for using freed memory, running past allocations or expecting a resized block to stay put. Give them back the allocator whose habits they'd depended on and the same fix does for the lot. Quicken 2001 went straight on that list (“An already released heap address was being accessed”). Joel Spolsky heard from a SimCity developer about Windows changing the allocator for SimCity to let the game use freed memory. Just look how many such favours one engineer could do in a day by XP.

    What was wrong with RollerCoaster Tycoon? Two bytes, to begin with. It had 16-bit stack operations that could leave a buffer two bytes out of alignment for the memory functions that took it. XP widened the operations in the running game to 32 bits. On exit it had to spare the game a call to a DirectDraw interface it had already released.

    windows/appcompat/db/dbu.xml, lines 3223 to 3234

    <PATCH NAME="RollerCoasterTycoon" ID="{AF2E1116-4D63-4912-B0A3-5537434E8583}">
        <DESCRIPTION>
            - This fixes the ORIGINAL rollercoaster tycoon (right off the cd) without
              expansion packs (version 1.08.164).
            - Removes the size overrides to prevent stack misalignment due to word push and
              pop instructions.
            - Jump around the IDirectDraw::Release to prevent an Access Violation on exit.
        </DESCRIPTION>
        <MATCH_BYTES MODULE="%EXE%" OFFSET="0x00026F40">66 ff 35 68</MATCH_BYTES>
        <WRITE_BYTES MODULE="%EXE%" OFFSET="0x00026F40">90 ff 35 68</WRITE_BYTES>
        <MATCH_BYTES MODULE="%EXE%" OFFSET="0x00026F4E">66 8f 05 68</MATCH_BYTES>
        <WRITE_BYTES MODULE="%EXE%" OFFSET="0x00026F4E">90 8f 05 68</WRITE_BYTES>

    XP kept three copies of that patch for three builds of rct.exe, telling them apart by file size and checksum. A neighbouring file called Tracks\Batflyer.TD4 helped identify the game. Final Fantasy VII's movies played upside down. Its fix disabled the UYVY and YUY2 video formats in the TrueMotion codec. Golden Nugget had 43 bytes of instructions made inert. Its entry ends with "What were they thinking?"

    The notes on the two Red Storm games (Force 21 and Dominant Species) take some reading. You could map a file on 9x and assume you'd get back an address above two gigabytes. Now run the same game on NT. It's the same file, and you're doing the same arithmetic on an address, only Windows is perfectly entitled to put it below two gigabytes. That's enough to change the sign in the calculation those games did and let them past a limit they used to observe.

    windows/appcompat/shims/specific/dominantspecies.cpp, lines 13 to 28

    DominantSpecies contains an invalid check code that looks like the following:
    
        mov  esi,A
        mov  eax,B
        sub  eax,esi
        cmp  eax,ebp
        jle  @@Loc
        mov  eax,ebp
    @@Loc:
    
    In a particular case: B=-1 and A<0x80000000 this jump will be incorrectly
    taken. The reason this works on Win9x is that A>0x80000000 because it's a
    memory mapped file. On NT, no user mode address can normally be >2GB.
    
    This shim patches the app with a 'cli' instruction so that it can perform
    some logic when the exception gets hit. This is admittedly slow.

    Why pick out Dominant Species for a fix at all? The note on its shim gives the reason. XP could correct just the comparison in that game. They'd considered arranging for mapped files in general to get high addresses, and found that “game performance suffers too much”.

    Explorer still answers to the name Program Manager, because Windows 3.1 installers created their icons by talking to Progman over DDE (the desktop window is still called Program Manager in Windows 11), and its table of workarounds is a list of 1993 software: WinFax Pro, cc:Mail, Discis's children's books, Alone in the Dark 2, which compares "PROGMAN" case-sensitively so the name is registered in capitals just for it, and "The Journeyman Project. This app causes damage to space-time. We fix it by generating a small HS-field around their installer." The kernel has a similar list. When you run an old .exe that isn't a Windows program, the memory manager decides where to send it partly by looking for other companies' copyright notices inside it, "Phar Lap Software, Inc.", "Copyright (C) Rational Systems, Inc." and "1-2-3 Preloader" for Lotus, all DOS programs dressed up as OS/2 ones, which go to the DOS box.

    NT also had a more general idea of compatibility. The same kernel could present itself to a program as one of several quite different operating systems, and one of those personalities was a little Unix environment implementing POSIX. If you're familiar with Unix, have a look at ttyname. You give it a file descriptor and it should tell you the name of the terminal the descriptor refers to.

    base/subsys/posix/client/stubs.c, lines 65 to 72

    char *
    __cdecl
    ttyname(int fildes)
    {
        static char s[7];
        s[0] = 0;
        return NULL;
    }

    Give ttyname any descriptor you like and you get NULL. There's a contemporary account of why that mattered. Stephen Walli, then at Softway Systems working on a fuller Unix environment, picked this very function for his 1997 USENIX paper. The standard permitted NULL if the system couldn't determine the terminal's name. This implementation was in the position of never being able to determine it. For a federal purchase that specified these interfaces, FIPS 151-2 required POSIX conformance. Walli could see how the purchasing requirement had been met. Someone trying to find out which terminal they had open still had a problem.

    Turn from ttyname to forksup.c in the memory manager and you get some idea of the work Microsoft did put into Unix. Calling fork gives the child what looks like a copy of its parent's address space. For a page that both processes only read, one physical copy will do. The memory manager has to give them separate copies when one writes to the page.

    base/ntos/mm/forksup.c, lines 108 to 115

    This routine stands on its head to produce a copy of the specified
    process's address space in the process to initialize.  This
    is done by examining each virtual address descriptor's inherit
    attributes.  If the pages described by the VAD should be inherited,
    each PTE is examined and copied into the new address space.
    
    For private pages, fork prototype PTEs are constructed and the pages
    become shared, copy-on-write, between the two processes.

    Softway's Unix was Interix. Microsoft acquired it when it bought Softway's assets in September 1999. Even the announcement encouraged customers eventually to move their programs to Win32. By the time XP went on sale the original POSIX subsystem was gone from the product. Its source is here, though, and the memory manager still includes forksup.c in the build. You can follow the federal requirement into the first implementation, the acquisition of a more useful one, and the survival of some of the work after the first one went away.

    Dan Lovinger put a small cache into NTFS in August 1995 for programs that expected the file system to “hold onto” information about a file even after its directory entry had gone. Take an editor saving yesterday's document. It writes a temporary file and replaces the old one with it. The new file can pick up the old creation date and DOS short name if it appears soon enough, under the same name in the same directory. This also works after a rename. NTFS calls it tunneling. Looking in that cache for yesterday's document would be a disappointment. All it kept was the metadata.

    base/ntos/fsrtl/tunnel.c, lines 509 to 514

    //    Information is retained in the tunnel cache for a fixed period of time.  MarkZ would
    //    assume that a value of 10 seconds would satisfy the vast majority of situations.  This
    //    could be controlled by the registry or could be a compilation constant.
    //
    //  Change: W95 times out at 15 seconds. Would be a registry value initialized at tunnel
    //  creation time, with a proposed default of 15 seconds.
    

    There are 256 entries on a workstation volume with the defaults. The original proposal gave it ten seconds. Further on someone records what 95 did, and the fifteen comes from there. On a create, NTFS looks for that remembered name before it sets the file's creation time. A fresh date means it didn't find tunneled data. You can lose an entry before the fifteen seconds are out, you can set other limits in the registry, and a case-sensitive POSIX open doesn't look in that cache at all.

    The compatibility database I mentioned earlier is searchable in the blog post. The testers' descriptions are quoted directly, with their names left out.

      All 1,988 entries in dbu.xml, with the fixes each one gets and the testers' notes (their names left out). Try RollerCoaster Tycoon, Quicken or SimCity, or the Blocked filter, which lists what XP refused to install or run at all; seven of those 46 are Microsoft's products, Windows Media Player 7 among them.

      Kernel32 hack for a children's game

      The compatibility database fixes most badly behaved programs from outside, with shims. These are fixed from inside Windows, usually by name. Even Kernel32, a library that ordinary Win32 programs load, has code for one children's game, Elmo's Preschool Deluxe. Its 16-bit helper wants to know how much memory there is, physical and virtual. Windows gives the helper an answer the game can live with.

      base/win32/client/module.c, lines 3968 to 3983

      // Sure, we could have checked this on a compat bit instead, but the ISV is the
      // Children's Television Workshop people and if they do this silliness in any
      // of their other apps, we'll get those fixed "for free".
      if ( 0 == lstrcmpi( lpszDll16, (LPCSTR)"mem16.dll" ) &&
           0 == lstrcmpi( lpszThunkFunc, (LPCSTR)"GetMemory" ) )
      {
          //
          // Elmo's Preschool Deluxe calls to a 16bit dll they ship just
          // to get physical and virtual mem.  Let's give 'em a pointer to our routine that
          // will give it numbers that makes it happy.
          //
          *ppfnThunk32Func = ReturnMem16Data;
         return(TRUE);
      }
      
      // Stub this function for King's Quest and Bodyworks 5.0 and other random Win 95 apps.
      

      Office 95 also had trouble with the heap. Consider just the case of starting Word 95 from a shortcut on the desktop. Depending on how that went, the heap could be asked to free a stray pointer. In amongst the code practically every program needed for its memory there is a check for this one Office mistake. Then there's a comment a few lines farther down for people who leave perfectly readable ASCII or Unicode text in the place reserved for the heap header. Somebody would like the record to show that these people are “dorks”.

      base/ntos/rtl/heap.c, lines 3528 to 3536

      //  Also refuse to free blocks that are not eight-byte aligned.
      //  The specific mistake in this case is Office95, which likes
      //  to free a random pointer when you start Word95 from a desktop
      //  shortcut.
      //
      //  As further insurance against mistakes, check the segment index
      //  to make sure it is less than HEAP_MAXIMUM_SEGMENTS (16). This
      //  should fix all the dorks who have ASCII or Unicode where the
      //  heap header is supposed to be.
      

      Quattro Pro for Windows programmed the VGA card directly whenever it found one, which made it crawl on NT, where every such access is trapped and emulated, so NT's 16-bit layer tells every Windows 3.x program that asks that there's no monitor at all: "So we lie to them here bl = 0 No monitor. That way they don't do direct VGA programming and run fast." You can also find a Windows 9x list view clearing a kilobyte of stack for an accounting program. Sage had been lucky with a value it never bothered to set. It used to come out zero and you could maximize the window. So the list view gives Sage its zeros back.

      shell/comctl32/v5/listview.c, lines 6611 to 6622

      // Crappy hack for Sage, which passes unitialized memory to SetWindowPlacement.
      // They used to get lucky and get zeros for the max position, but now they end
      // up with non-zero stack trash that causes bad things to happen when sage is
      // maximized.  Thus, zero a bunch of stack to save their tail...
      void ZeroSomeStackForSage()
      {
          BYTE aByte[1024];
      
          memset(aByte, 0, sizeof(aByte));
      
          aByte;
      }

      Paste a link in old CorelDraw and 16-bit OLE would spoil some memory. CorelDraw actually needed that to happen. This left the people doing 32-bit OLE with a peculiar little identification problem. How do you tell it's CorelDraw and you can go ahead and spoil the memory? CorelDraw sends a file moniker and gives its class ID as the path.

      com/ole32/olethunk/h/interop.hxx, lines 34 to 38

      #define OACF_CORELTRASHMEM  0x10000000  // CorelDraw relies on the fact that
                                              // OLE16 trashed memory during paste-
                                              // link.  Therefore, we'll go ahead
                                              // and trash it for them if this
                                              // flag is on.
      

      The Outlook Today page in Outlook 98 has an accommodation in IE, down to the column on the page. If the script error is at column 35 of line 36, IE doesn't put up the error dialog. The other place that gets the same treatment is column 28 of line 51.

      inetcore/mshtml/src/site/base/sholder.cxx, lines 928 to 933

      BOOL OutLook98HackReqd(CMarkup * pMarkup, ULONG uLine, ULONG uCol)
      {
          if (((36 == uLine) && (35 == uCol) ||
               (51 == uLine) && (28 == uCol)) &&
              !_tcsicmp( (TCHAR *)CMarkup::GetUrl(pMarkup), _T("outday://")))
              return TRUE;

      If a program crashed in a common dialog, it wasn't even necessarily that program that needed fixing. Hijaak, for example, was an image program that interfered with Explorer. The casualties could be other people's applications opening their common dialogs. Explorer had to supply a decoy that Hijaak would leave alone.

      shell/shell32/defview.cpp, lines 15308 to 15316

      //  We return no attributes (specifically, Hijaak looks for
      //  SFGAO_FILESYSTEM) and Hijaak will say, "Whoa, I don't know
      //  how to patch this guy; I'll leave it alone."
      
      STDAPI FakeHijaak_GetAttributesOf(void *_this, UINT cidl, LPCITEMIDLIST *apidl, ULONG *rgfInOut)
      {
          *rgfInOut = 0; // Move along, nothing to see here
          return S_OK;
      }

      Word 2.0 left a rectangle out of a call. At run time the 16-bit multimedia OLE handler retrieved the missing rectangle from three stack frames up. The Cirrus Logic display driver that came with XP also knows things about the program calling it that seem a little outside its line of work. One such thing is the dimensions of the pause box in WinBench 97. From that little window the driver could tell when the benchmark was between tests. Now the interesting bit is when to allocate memory. Do it early and PowerPoint gets a better score, but Access gets a worse one. The driver recognises the 300-by-150 pause bitmap, counts ten during Access and reserves space for eight full-screen bitmaps while the timing is paused.

      drivers/video/ms/laguna/disp/include/swat.h, lines 91 to 106

      WinBench 97 uses 300x150 size bitmaps for its pause box.  The pause box is
      showed when WinBench 97 has disabled timing and is loading more playback
      data from the hard disk.  So here we have a way to do some stuff when which
      will not be timed.  What we will do is allocate enough heap memory for 8
      full-screen device bitmaps.  This will make the PowerPoint test very happy
      since it is allocating these 8 full-screen device bitmaps during the slide
      show.  The only drawback is that NT will swap memory to hard disk in the
      background.  This will lower the Access score which we don't want.  That is
      why we have added a counter.  The Access test uses 10 300x150 bitmaps so we
      count down until Access has passed.  Then we will start pre-allocating heap
      space during each 300x150 bitmap request.
      
      But this will drop the CorelDRAW test a little which *will* show up in the
      overall score.  So one extra allocation is requested.  We will pre-allocate
      the heap memory during every full-screen device bitmap (see SWAT2) when the
      count down counter has reached zero.

      One of the GDI printer classes is dated 1991. Somebody called a variable in it ptlPrinterHackDiesAfterTheBeta. Here it is in the XP tree, ten years down the road.

      Minesweeper's hundred-slot queue

      Minesweeper ("by Robert Donner and Curt Johnson", and in its file header "WinMine (a.k.a. Mines, BombSquad, MineSweeper…)") has the best find in this article, but the well-known stuff first.

      The xyzzy cheat is defined in the code, and named after the magic word in Colossal Cave Adventure. Type X, Y, Z, Z, Y, hold Ctrl, and the top-left pixel of your screen turns black when the mouse is over a mine and white when it isn't. The pixel is set from the mouse-move handler in winmine.c.

      shell/osshell/ep/winmine/winmine.c, lines 628 to 647

      //
      // This is the cheat:
      // If you hold down the shift key and type 'XYZZY'
      // then when you hold down the control key, to upper
      // left hand corner pixel will show the state of the
      // mine field under the mouse.  Oh. joy.  I can win.
      //
      else if (iXYZZY != 0)
          if (((iXYZZY == cchXYZZY) && (wParam & MK_CONTROL))
             ||(iXYZZY > cchXYZZY))
          {
          xCur = xBoxFromXpos(LOWORD(lParam));
          yCur = yBoxFromYpos(HIWORD(lParam));
          if (fInRange(xCur, yCur))
              {
              HDC hDC = GetDC(NULL);
              SetPixel(hDC, 0, 0, fISBOMB(xCur, yCur) ? 0L : 0x00FFFFFFL);
              ReleaseDC(NULL, hDC);
              }
          }

      shell/osshell/ep/winmine/winmine.c, lines 557 to 566

      #ifdef XYZZY
              case VK_SHIFT:
                  if (iXYZZY >= cchXYZZY)
                      iXYZZY ^= 20;
                  break;
      
              default:
                  if (iXYZZY < cchXYZZY)
                      iXYZZY = (szXYZZY[iXYZZY] == (TCHAR) wParam) ? iXYZZY+1 : 0;
                  break;

      The definitions at the top of the file sit inside #ifndef DEBUG, as if the cheat were meant to stay out of some builds, but NT's build system calls its debug flag DBG, so every NT build of Minesweeper has the cheat compiled in.

      The first click has a couple of oddities. You can actually click where there's a mine, in which case the game looks across from the top left until it has an empty square to put it in. So in practice that mine tends to go to the corner. The clock goes to 1 when you let go of the button. Somebody even explained the choice to do it on release (“If we had started it earlier, the interval between tick 1 and 2 is not correct”). Another small thing about the first board is that you have at most 65,536 possible ones. The random generator only gets seeded at launch, with the low sixteen bits of the number of milliseconds since boot.

      The thing I found more interesting was in shell/osshell/ep/winmine/rtns.c. If you click a blank, the game opens the squares around it and it has to do the same for any of those that turn out to be blank. This is just a breadth-first flood fill. StepXY is the part that actually opens a square and puts it in the queue if the number of mines next to it is zero. In StepBox the entire working queue is an array of a hundred places (iStepMax), used as a ring so writing the next one after the last brings you back to position 0.

      shell/osshell/ep/winmine/rtns.c, lines 240 to 248

              if (cBombs != 0)
                      return;
      
              rgStepX[iStepMac] = x;
              rgStepY[iStepMac] = y;
      
              if (++iStepMac == iStepMax)
                      iStepMac = 0;
      }

      =StepBox= reads a square from the other end of that queue and visits all eight squares round it. It keeps at it until the read position is the same as the write position.

      shell/osshell/ep/winmine/rtns.c, lines 253 to 282

      VOID StepBox(INT x, INT y)
      {
              INT iStepCur = 0;
      
              iStepMac = 1;
      
      
              StepXY(x,y);
      
              if (++iStepCur != iStepMac)
      
                      while (iStepCur != iStepMac)
                              {
                              x = rgStepX[iStepCur];
                              y = rgStepY[iStepCur];
      
                              StepXY(x-1, --y);
                              StepXY(x,   y);
                              StepXY(x+1, y);
      
                              StepXY(x-1, ++y);
                              StepXY(x+1, y);
      
                              StepXY(x-1, ++y);
                              StepXY(x,   y);
                              StepXY(x+1, y);
      
                              if (++iStepCur == iStepMax)
                                      iStepCur = 0;
                              }

      How often do you think Minesweeper has a hundred zeros waiting to be looked at? In simulated Expert games the number got up to about 18 at most. An almost empty Custom board is quite a different game. The dialog lets you have just 10 mines for a board 30 squares across and 24 down. The queue can get so long that its two positions meet with a whole ring of work left to do. To the game that looks just like an empty ring, or it can start writing over squares still waiting for their turn. You can tell when this has happened just by looking at the board. There's an open zero with a square beside it that the game didn't open.

      The nice thing about this bug is it can't cost you a game. Anybody can see there's no mine next to that zero and uncover the neighbour for themselves, which might explain the lack of complaints. I couldn't find a description of it. The simulation gave about two cases in a million first clicks on random boards of this shape. It depends where the ten mines are, so I put a board in the post where it happens every time. There are 710 safe squares. From the marked one my faithful port opens 612 and leaves 30 zeros with a neighbour still closed. An ordinary correct fill from that very same square gets 706. People who've reverse-engineered the game have found the hundred-entry ring. In fact there's a reimplementation published this month that sets aside one entry per square, with a comment saying the ring “can never lap itself and drop a pending square”.

      CUSTOM FIELD, 30 BY 24, 10 MINES

      THE QUEUE, 100 SLOTS

      Read, iStepCur0 Write, iStepMac0 Waiting0 Overwritten0 Writes ahead of reads0

      Opened 0 of 710 safe squares

      Click the ringed square on the overflow board and watch the ring of a hundred slots while the cascade runs. The ring fills, the write position laps the read position and overwrites unread entries, and when the two finally meet the loop can't tell a full ring from an empty one, so it stops. The outlined squares are zeros that were opened without their neighbours; tick the correct flood fill to see the 94 squares XP leaves closed. The other tab is a faithful Minesweeper, seeded the way XP seeded it; with the board focused, type xyzzy and hold Ctrl over the squares (it's cheating, and it came from Microsoft).

      The boot screen is a black picture

      The first thing XP showed you was a black screen with the Windows flag, "Microsoft Windows XP Professional" (or Home Edition), and under it a thin rounded track. The three squares crawling through it were blue on Professional and green on Home Edition in this tree. They didn't measure anything. They looped for as long as it took to reach the logon screen.

      The obvious place to look for that picture is the kernel's base/ntos/init/boot.bmp. It's the right size, 640 by 480 in sixteen colours, run-length compressed to 14 kilobytes. Open it and there's absolutely nothing to see. Whoever made the bitmap set all sixteen colours to black. Twelve of the nineteen bitmaps in the kernel's resource script are like that. The colours you remember are in MainPalette in base/ntos/init/anim.c, which the header dates to August 2000 and attributes to Peter Alschitz.

      base/ntos/init/anim.c, lines 153 to 156

      RGBQUAD MainPalette [FULL_PALETTE_SIZE] = { {0,0,0,0}, {21,26,32,0}, {70,70,70,0}, {210,62,45,0},
                                                  {1,101,83,0}, {5,53,178,0}, {126,126,126,0}, {0,146,137,0},
                                                  {252,127,94,0}, {32,107,247,0}, {255,166,141,0}, {4,220,142,0},
                                                  {27,188,243,0}, {188,188,188,0}, {252,252,252,0}, {255,255,255,0} };

      Read its sixteen entries in bitmap order, blue, green, red and a spare byte. That makes 5, 53, 178, 0 a red and 210, 62, 45, 0 a blue. The flag and edition name are already on the screen before the kernel gives the video card any of these colours. So is a 22 by 9 pixel sprite in the top left. Windows reads three little 6 by 9 squares back out of the video memory there and blacks the corner out again. By the time you can see anything, the sprite those squares came from is gone. A thread brings up MainPalette in twenty steps at intervals of 80 milliseconds (the comment says 100). Once it has done that, the squares can be sent down the track.

      You might expect the fade to end on the colours somebody picked for the logo. It falls one step short, and you can work out just how bright XP got from the order of two operations in the thread.

      base/ntos/init/anim.c, lines 271 to 279

      case PLT_START:
          FadePalette ((UCHAR)(PaletteNum));
          FadePaletteColor (0, COLOR_FADE_TEXT); // #1 - color of fading text
          if ((++PaletteNum)>=FADE_GRADES) {
              PltRotBarStatus = PLT_CYCLE;
              FadingIn = TRUE;
              PaletteNum = 1;
          }
          break;

      =FadePalette= multiplies each colour by PaletteNum and divides by FADE_GRADES, which is 20. When PaletteNum reaches 20 the thread has already finished applying colours and switches to moving the squares. So the biggest multiplier the screen actually got was 19/20. The brightest white was 242, or 60 out of 63 by the time it went into the VGA's six-bit colour registers. People watched that logo come up at 95% brightness for about a decade. I doubt anybody noticed. The demo reads the real boot.bmp and puts it through the same fade.

      Loading bitmaps

      DAC

      EDITION

      The real boot.bmp and the other bitmaps from base/ntos/init, decoded by your browser, with the kernel's palette pushed through the original fade: twenty ticks of 80 ms, and the last one stops at 19/20, so the white reads 60 of 63. Turn on X-ray and press Replay to see what is in video memory while the screen is still black, including the sprite in the top-left corner that the squares are copied from. Server shows the ".net" version, and Home Edition's squares come out green, which is what the palette in this tree says. "Let the fade finish" shows the logo at the brightness it was drawn for.

      Windows Server 2003, still called Windows .NET Server when this code was written, didn't get a separate boot screen. The code in base/ntos/init/init.c draws the XP bitmap. On products other than the workstation it then alters the lettering.

      base/ntos/init/init.c, lines 409 to 416

      InbvBitBlt(Bitmap, 0, 0);
      //if (SharedUserData->NtProductType == NtProductServer) {
      if (SharedUserData->NtProductType != NtProductWinNt) {
          // make some fixes for server bitmap: remove "XP"
          UCHAR sav_copyright[64];
          InbvScreenToBufferBlt(sav_copyright, 413, 237, 7, 7, 8);
          InbvSolidColorFill(418,230,454,256,0);
          InbvBufferToScreenBlt(sav_copyright, 413, 237, 7, 7, 8);

      It copies the small registered-trademark sign after "Windows" into a buffer (called sav_copyright, although it's an R in a circle), paints a black rectangle over the letters XP, puts the sign back, and then the kernel stamps a small ".net" bitmap on top. The Server button in the blog demo does the same, in the same order and at the same coordinates.

      The squares don't measure the work, but the kernel does remember some of it. XP's cache manager records the memory pages used during boot, then reads them ahead of time on later boots, grouping reads that would otherwise send the disk head back and forth. The boot prefetcher, base/ntos/cache/prefboot.c, by Cenk Ergan in March 2000, has a particularly nice trick. It measures how long the video driver takes to initialise and saves that time in the registry. Next boot, while the video driver is busy, it reads pages that later parts of startup will need. Its budget is the previous delay, rounded down to whole seconds, multiplied by a configurable number of pages per second.

      base/ntos/cache/prefboot.c, lines 655 to 665

      //
      // Determine how many pages max we can prefetch in parallel to video
      // initialization.
      //
      
      VideoInitMaxPages = (VideoInitTime / 1000) * VideoInitPagesPerSecond;
      
      //
      // We can only prefetch pages used after winlogon in parallel to video
      // initialization. Determine exactly how many pages we will prefetch
      // starting from the last boot phase.
      

      The default is 1,500 pages per second, and it only uses this opportunity for pages needed after Winlogon starts. If there is no valid previous timing, this part of the budget is zero. The window system really calls the prefetcher immediately before and after InitVideo, so this is wired into normal startup. The logo's animation and the disk's activity are doing separate jobs. Behind the looping squares, Windows is using one piece of waiting to hide another. Mark Russinovich and David Solomon's 2001 account of XP's kernel explains the wider prefetch design.

      How the Start menu picks its six programs

      XP's Start menu has your browser and your mail client pinned at the top of the left column, and six programs you "use frequently" under them. I'd always assumed that list counted launches. It's a score, and the score decays when you stop using a program.

      The engine is called UserAssist and lives in shell/browseui/emclient. Its design note (shell/docs/uassist.txt, February 1998, from the Internet Explorer 5 days) counts time in sessions, which are roughly days. A new session starts when you open the Turn Off Computer dialog long enough after the last one, or after twelve hours with no keyboard or mouse input. "Long enough" is meant to be twelve hours and comes out at about ten and three quarters, because UserAssist's clock ticks in 53.7-second units that it treats as minutes. As uacount.h puts it, "currently we just assume a UATIME is exactly 1 minute, which it's not… easy enough to do, but we'll wait until i have time to do the math." Every time Explorer reads a program's score it first decays it by the number of sessions since it was last used, through a table in uacount.cpp marked "from mso-9 spec". MSO-9 is Office 9, better known as Office 2000, whose personalised menus hid the items you hadn't clicked lately. A few sessions without a program cost it a point, the losses grow from there, and thirty-one sessions after you last used it the score is gone. Its first row gives the thresholds in sessions, 3, 6, 9, 12, 17, 23, 29 and 31.

      shell/browseui/emclient/uacount.cpp, lines 240 to 245

      // from mso-9 spec
      // last used 'timTab' sessions ago => dec by >-of abs, pct
      // n.b. this table is non-cumulative
      static const int timTab[] = { 3, 6, 9, 12, 17, 23, 29,  31,  -1, };
      static const int absTab[] = { 1, 1, 1,  2,  3,  4,  5,   0,   0, };
      static const int pctTab[] = { 0, 0, 0, 25, 25, 50, 75, 100, 100, };

      The second row gives the points to lose, 1, 1, 1, 2, 3, 4, 5 and 0. The third gives percentages, 0, 0, 0, 25, 25, 50, 75 and 100. For each threshold a program has gone past or reached, its score loses that column's points or its percentage of what's left, whichever is bigger. So a program you haven't opened for twelve sessions has lost a point three times, and then two points or a quarter of what was left, whichever is more.

      Launching a program doesn't just add one either. The code decays the old score, adds one, and then bumps the result up to six if it's lower. That's how a single launch comes to be worth six.

      shell/browseui/emclient/uacount.cpp, lines 151 to 155

      // 981029 new incr algorithm per ie5 PM
      // UAC_MINCOUNT: initial inc starts at 6
      // _fNoDecay: but, UAssist2 doesn't do this
      if (_cCnt < UAC_MINCOUNT && !_fNoDecay)
          _cCnt = UAC_MINCOUNT;

      The header that defines that six files it under "tunable values for IncCount (talk to your neighborhood PM)", which I love.

      There's a fairly practical reason to care about the six. People examining a seized machine used the UserAssist entries in the registry to tell what had run on it. XP-era guides said the raw count started at five instead of zero, so you ought to subtract five. RegRipper, widely used for this work, subtracts five whenever the stored value is greater than five. It works beautifully for a first launch. Suppose you launched a program fifty times, then went 31 UserAssist sessions without using it before opening it again. The same calculation gives you one launch. As for the value names, the “encryption” is ROT13, with a comment about someday needing an international-aware scheme. Someday never came.

      There's another odd thing about a list of programs you use frequently. You can have one before you've used the computer. When Explorer first builds the Start panel, CreateInitialMFU in shell/explorer/desktop2/proglist.cpp fills the six positions with scores already assigned, 19 for the first one down to 14 for the last.

      shell/explorer/desktop2/proglist.cpp, lines 4145 to 4156

      // ASsert that the slots are evenly shared between MSFT and the OEM
      COMPILETIME_ASSERT(ARRAYSIZE(rgpidlMFU) % 2 == 0);
      
      // The OEM can provide up to four apps, and we will put as many
      // as fit into into bottom half.
      {
          MFUEnumerator mfuOEM;
          for (iSlot = ARRAYSIZE(rgpidlMFU)/2; iSlot < ARRAYSIZE(rgpidlMFU); iSlot++)
          {
              rgpidlMFU[iSlot] = mfuOEM.Next(&mex, TEXT("OEM%d"), 4, FALSE);
          }
      }

      A PC manufacturer could supply the bottom three entries. Microsoft filled what was left from its list, which in the original release included MSN Explorer, Windows Media Player, Movie Maker, the XP tour and the transfer wizard. SP1's longer list included Windows Messenger. Internet Explorer itself is on the list but gets passed over when it would duplicate the default browser pinned just above it. Given the argument in 2001 over who got to put what on the Windows desktop, I'd guess the lawyers took an interest in that condition. The demo starts with the same scores and lets you see what becomes of them a day at a time.

      PC MAKER'S PROGRAMS

      RUN

      seeded at first logonyour launches

      A plain copy of the left column of the Start panel, with the engine underneath ported from uacount.cpp and proglist.cpp: the decay table, the clamp to six, the first-logon seeding as XP first shipped, and the ROT13 in the registry. Run Notepad three times, press "Two weeks of use", run it once more and look at the registry pane; a forensics tool subtracting five would say you launched it once. "Two weeks away", with the computer switched off, costs a single session, because UserAssist counts sessions and a switched-off computer has none.

      FreeCell's game numbers

      FreeCell was Jim Horne's. His history line puts the first code in June 1991 and the Win32 port in October. If the title says “FreeCell Game #11982”, 11982 is the number that went into the C runtime's random generator. In ShuffleDeck in shell/osshell/ep/freecell/display.c the cards start out numbered zero to 51. Take rand() modulo the number left, give that card to the next column and fill its place with the last card still in the deck. Do this fifty-two times. Even rand() is here in base/crts/crtw32/misc/rand.c, a multiply and an add. The comment on srand() credits the BASIC random number generator. Anybody using that same generator and deal number could reproduce the game.

      My favourite comment in the leak is just above that shuffle. A game developer coming along later might quite reasonably think of improving it. The warning was to expect “the wrath of people who have invested a huge amount of time solving these games”. The shuffle algorithm was already public, so players could refer to a game by its number.

      shell/osshell/ep/freecell/display.c, lines 191 to 211

      //
      // Caution:
      //      This shuffle algorithm has been published to people all around. The intention
      //      was to let people track the games by game numbers. So far all the games between
      //      1 and 32767 except one have been proved to have a winning solution. Do not change
      //      the shuffling algorithm else you will incur the wrath of people who have invested
      //      a huge amount of time solving these games.
      //
      
      //      The game number can now be upto a million as the srand takes an integer but the
      //      the random value generated by rand() is only from 0 to 32767.
      //
      
      srand(gamenumber);
      for (i = 0; i < 52; i++)
      {
          j = rand() % wLeft;
          wLeft --;
          card[(i%8)+1][i/8] = deck[j];
          deck[j] = deck[wLeft];
      }

      Between 1994 and 1995 more than a hundred volunteers in Dave Ring's Internet FreeCell Project worked through the original 32,000 deals. The one nobody could win was 11982. Michael Keller keeps the history in his FreeCell FAQ. Now imagine changing either the shuffle or Microsoft's rand(). All those solved games would keep their numbers and acquire different cards. A detail of how one little game happened to work had become an API.

      There's a second comment in XP because FreeCell can now take a game number up to a million. The seed will take an integer that large. A value you get back from rand() is still between zero and 32,767, which makes a difference when the New Game command tries to choose a number for you. The dialog rather neglects to mention this.

      shell/osshell/ep/freecell/display.c, lines 698 to 709

      UINT GenerateRandomGameNum()
      {
          UINT wGameNum;
      
          srand((unsigned int)time(NULL));
          rand();
          rand();
          wGameNum = rand();
          while (wGameNum < 1 || wGameNum > MAXGAMENUMBER)
              wGameNum = rand();
          return wGameNum;
      }

      F2 deals from 1 to 32,767. The test against a MAXGAMENUMBER of one million never enters into it, so to see the remaining 967,233 deals you have to type a number into Select Game. Beneath the ordinary range are two more, -1 and -2. Someone laid those out by hand. According to Keller the joke goes back to Windows 95, and the dialog calls negative numbers special cases for unwinnable shuffles. In -1 the columns are each a single suit and the aces are buried under the odd cards. In -2 each ace is underneath its King, Queen, Jack, Ten, Nine and Eight at the bottom of a column.

      Solitaire repeats too, only it doesn't show you the numbers. In shell/osshell/games/sol/sol.c it seeds each deal with the Unix time modulo 32,768. That's 32,768 deals recurring every 9 hours, 6 minutes and 8 seconds. Two XP computers with the right time would deal the same cards if you started in the same second. The comment there is about a report that the games never changed, which the people working on it hadn't been able to reproduce.

      shell/osshell/games/sol/sol.c, lines 656 to 662

      // It was reported that games never changed.
      // We could not repro it so see if it happens
      // and output a message to the debugger.
      //
      
      Param= (INT) time(NULL);
      srand( igmCur = ((WORD) Param) & 0x7fff);

      FreeCell Game #1

      Dealt 0 games

      Any deal from -2 to 1,000,000, dealt by ShuffleDeck and the C runtime's rand(). Games 1, 617 and 11982 match the deals people have been publishing since the nineties; -1 and -2 are the hand-built ones. Press New Game a few times, then "Press once a second" and let it run for a few seconds: the count of different games stops at 32,767 and never moves again, although the dialog promises a million. With the demo focused, Ctrl+Shift+F10 opens the User-Friendly User Interface. (In real XP, New Game in the middle of a deal first asks whether you want to resign and counts a loss; I didn't bother with that.)

      Back in FreeCell, Ctrl+Shift+F10 opens a “User-Friendly User Interface”. The note says the strings needn't be translated. “Choose Abort to Win, Retry to Lose, or Ignore to Cancel.” The interesting part about Abort is that you still have to make a move. The next time the normal tidy-up asks Useless() whether a card can go home, it gets yes for everything. Off go the cards in the wrong order but with their usual graceful glide. Without the cheat, aces and twos can go straight home. For a higher card both opposite-colour cards one rank below it must already be there, so nobody on the table will need that card to play on.

      Internet Explorer could justify Arabic

      A few months ago I wrote about how much trouble the web still has with Arabic typography, and the heart of that article was a missing feature. Arabic can be justified by elongating the strokes inside words, the kashida. Browsers stretch the spaces between words, so you get rivers. I said there that Internet Explorer 5.5 implemented text-justify: kashida in 2000, and that the value was later dropped from the CSS drafts because nobody else implemented it. What I didn't say is how IE decided where to stretch, and that code is in this tree.

      IE does it in two steps. Trident, IE's layout engine, asks Uniscribe (the part of Windows that shapes complex scripts) what kind of justification point each glyph is, and Uniscribe answers with one of the Arabic classes listed in usp10.h. Then inetcore/mshtml/src/site/text/linesrv.cxx ranks those using another table and picks the best available place in each word to stretch, with ties going to the later letter. Uniscribe's letter table isn't in the tree, but Microsoft published the rules for IE 5.5 at the time, and Edo Smitshuijzen of the Khatt Foundation reproduces them.

      1. First comes the place after a tatweel already in the text,
      2. then after an initial or medial seen or sad (س ش ص ض),
      3. then before a final heh, teh marbuta or dal (ه ة د).
      4. Fourth comes the place before a final alef, tah, lam, kaf or gaf (ا ط ل ك گ).
      5. Fifth is before a medial ba-like letter that joins a final ra, ya or alef maqsura, so the join itself isn't stretched.
      6. Sixth is before a final ra, waw, ain, qaf or fa (ر و ع ق ف),
      7. and seventh before any other connected letter.
      8. IE adds one rank at the bottom that the published list doesn't have, before a medial ba-like letter (ب ت ث ن ي).

      If you've ever watched a calligrapher stretch a line, the top of that list looks familiar. The long stroke after an initial seen, and the pull before a final heh or alef, are where they usually stretch. The chosen place gets the first priority in the line layout (LineServices, also in the tree, under windows/richedit/lssrc) and the spaces get the second, so the slack in every justified line goes to kashidas first and only what's left goes to the spaces. In linesrv.cxx that's prior = 1 for the chosen letter (iBestPr) and prior = 2 for the space (iPropL), in a branch that only runs while the kashida share is exactly 100, which is what it is when nobody has set it.

      inetcore/mshtml/src/site/text/linesrv.cxx, lines 3832 to 3851

      case styleTextJustifyNotSet:
      case styleTextJustifyKashida:
      case styleTextJustifyAuto:
          if (flKashidaPct == 100)
          {
              if (iBestPr >= 0)
              {
                  rgExpType[iBestPr] = exptAddInkContinuous;
                  rgexpinfo[iBestPr].prior = 1;
                  rgexpinfo[iBestPr].duMax = lsexpinfInfinity;
                  rgexpinfo[iBestPr].fCanBeUsedForResidual = FALSE;
                  rgexpinfo[iBestPr].u.AddInkContinuous.duMin = iKashidaWidth;
              }
      
              rgExpType[iPropL] = exptAddInkContinuous;
              rgexpinfo[iPropL].prior = 2;
              rgexpinfo[iPropL].duMax = lsexpinfInfinity;
              rgexpinfo[iPropL].fCanBeUsedForResidual = TRUE;
              rgexpinfo[iPropL].u.AddInkContinuous.duMin = 1;
          }

      One IE-only value and two IE-only properties steer it. The value is text-justify: kashida, which is also what the default did, so justified Arabic in IE was elongated without anybody asking. The property text-kashida-space sets the share of the slack that goes to elongation instead of spaces. The other, text-kashida, breaks every line a little short on purpose so there's always something to elongate. As far as I can tell, text-kashida-space never worked as intended. CSS percentages are stored multiplied by a hundred, and linesrv.cxx reads the raw number.

      inetcore/mshtml/src/site/text/linesrv.cxx, lines 3579 to 3592

      if (!plsrun->_pPF->_cuvTextKashidaSpace.IsNull())
      {
          flKashidaPct = plsrun->_pPF->_cuvTextKashidaSpace.GetUnitValue();
      }
      
      if (flKashidaPct == 0)
      {
          iWhiteWidth = iKashidaWidth;
          iKashidaWidth = 1;
      }
      else if (flKashidaPct < 100)
      {
          iWhiteWidth = max((int)((float)iKashidaWidth * ((100 - flKashidaPct) / flKashidaPct)), 1);
      }

      So 50% arrives as 5000, which is neither 0 nor under 100 here and isn't exactly 100 in the priority code either. Every value from 2% to 100% lands in the same fallback branch, which gives the stretch and the space the same priority. Setting text-kashida-space: 100% explicitly turned kashida-first justification off.

      The blog demo justifies the paragraph that opened that article both ways, and has a switch that makes text-kashida-space work the way it was presumably meant to. My hand-set mockup there put the elongations where I thought they belonged, and IE's rules put them in the same place in 13 of the 17 words it justifies. In three of the four it disagrees with, IE goes for the stroke after a seen or sad, which the published rules rank above everything except a tatweel that is already there.

      CHROME, FIREFOX AND SAFARI, 2026

      الخط هندسة روحانية ظهرت بآلة جسمانية، وهو لسان اليد ورسول العقل، وسفير الضمير ووحي الفكر، وسلاح المعرفة وأنس الإخوان عند الفرقة.

      INTERNET EXPLORER 6 ON WINDOWS XP, FROM linesrv.cxx

      الخط هندسة روحانية ظهرت بآلة جسمانية، وهو لسان اليد ورسول العقل، وسفير الضمير ووحي الفكر، وسلاح المعرفة وأنس الإخوان عند الفرقة.

      203 px not set

      not set

      Letter classes follow the list Microsoft published for IE 5.5; Uniscribe's table is not in the source tree.

      The same passage and the same font, Amiri, on both sides. On the left, your browser's text-align: justify, which can only stretch the spaces. On the right, a reconstruction of IE6: one place per word, chosen with IE's ranking from the letter classes Microsoft published, then LineServices spending each line's slack on those places first. Tick "mark where each word stretches" to see the choices, and drag the width. text-kashida-space at 0% gives you what every browser does today, and "as built" and "as intended" switch between the percentage the code actually received and the one it was written for. The elongation is drawn with tatweel characters, so it looks straighter than a calligrapher's stroke.

      GDI had kashida code too, separate from IE's. Samer Arafeh wrote it for the complex-script language pack in March 1998, and it splices real tatweel glyphs into the text for programs that call GetCharacterPlacement with GCP_KASHIDA. XP's Arial and Times New Roman ship with OpenType justification tables listing kashida glyphs as short as an eighth of an em. So in 2001 Windows could elongate Arabic in GDI, in its fonts and in its browser, and the browser did it by default. Then IE lost, the kashida value was taken out of the CSS drafts, and the browsers I wrote about in my earlier article stretched the spaces. Last month a Chromium contributor filed an Intent to Prototype for CSS kashida justification, proposing text-justify: kashida and text-kashida-space as "previously supported in Internet Explorer and EdgeHTML", so IE's design might be coming back twenty-five years later. I hope they read the percentage properly this time.

      A couple of other Arabic details I liked. On a machine with a right-to-left keyboard installed, IE's Find dialog had three extra checkboxes, "Match diacritic", "Match kashida" and "Match alef hamza", all off by default. A search for محمد found مُحَمَّد and مـحـمـد, and ا matched أ, إ and آ. And when Windows mirrors a window for a right-to-left language, which it does by flipping the whole coordinate system (the SetLayout code by Mohamed Abdel-Hamid, December 1997), the help button's question mark comes out mirrored. That's fine for Arabic, whose ؟ is a mirrored question mark, and wrong for Hebrew, which uses the Latin one, so USER draws the question mark again, unmirrored, when the interface language is Hebrew.

      How licensing worked

      For a buyer of boxed Windows, the change in XP came after entering the twenty-five characters on the yellow sticker. That part was old. XP was the first Windows to ask a normal retail customer to activate the installed copy with Microsoft, by telephone or over the Internet, within thirty days. Microsoft had already tried it with Office in several countries. Its announcement for Windows and Office worldwide came in February 2001, and the example it gave a friendly name to was “casual copying”, one disc passing around a household or workplace.

      The part I wanted to read first is missing. Setup registers licdll.dll under the rather promising name “Windows Product Activation (WPA) Active X control”. You get its name, the names of a few other files, descriptions like “WPA license store” and “WPA balloon reminder”, and no source for the agent itself. On the other hand I could read pretty much every word Microsoft put in front of the customer, including what happened when the customer kept saying no. There's also an older licensing system for servers, considerably more of which survives.

      The five boxes live on three different setup pages. Buy the box and Windows sends you to “the yellow sticker on the back of your Windows CD folder”. Buy a computer with Windows on it and the answer is on “the lower section of your Certificate of Authenticity”. At work you were supposed to find your “License Agreement Administrator”. The boxes themselves turn everything into capitals and switch off the East Asian input method. Keys entered there, supplied in an unattended setup file, or given to the first-run wizard all reach pidgen.dll. The description in the DLL is “Pid3.0 generation”.

      base/ntsetup/syssetup/pid.c, lines 358 to 370

      //
      // eat spaces
      //
      if ((msg == WM_CHAR) && (wParam == VK_SPACE)) {
          return(0);
      }
      
      if ((msg == WM_CHAR)) {
          //
          // First override: if we have the max characters in the current edit
          // box, let's post the character to the next box and set focus to that
          // control.
          //
      

      There's even code for what becomes of a stray sixth character. It gets posted to the next box, just as backspace in an empty box takes you back one. Somebody wrote the error message twice. “The CD Key you entered is not valid.” on a retail CD, and “The Product Id you entered is not valid.” on the other two.

      There’s a build of pidgen.dll for each edition. They each carry two public keys as resources, one to recognise a product key issued for retail and one for a key issued through a PC maker. Setup could tell when the key belonged to a different edition.

      base/ntsetup/pidgen/pidgen/pidgen.rc, lines 14 to 27

      #ifdef BUILD_PRO
      1       BINK    DISCARDABLE        "00044.pub"
      2       BINK    DISCARDABLE        "00045.pub"
      #endif
      
      #ifdef BUILD_PER
      1       BINK    DISCARDABLE        "00042.pub"
      2       BINK    DISCARDABLE        "00043.pub"
      #endif
      
      #ifdef BUILD_TRIAL
      1       BINK    DISCARDABLE        "00000.pub"
      2       BINK    DISCARDABLE        "00001.pub"
      #endif

      PRO is Professional and PER is Personal, which is what the build called Home Edition. TRIAL was the pair the betas used. A Professional CD wouldn’t take a Home key or a retail installation an OEM one. The instruction to swap the beta pair for the final public keys at release is, I assume, why XP beta keys stopped working on the finished product. They left the server on the trial pair. The reason given was “we are not shipping SRV”. It was another year and a half before it shipped as Windows Server 2003.

      What pidgen hands back is two things. One is the Product ID you could read on the General tab of System Properties. The other is a binary record that setup puts in the registry as DigitalProductId.

      base/ntsetup/pidgen/pidgen/pidgen.cpp, lines 928 to 934

      wsprintfA(
          lpstrPid2,
          "%s-%03.3ld-%07.7ld-%s",
          lpstrRpc,
          (LONG)dwSeq1,
          (LONG)dwSeq2,
          szRand);

      The number on the screen had five digits for the product, three and seven worked out from the key’s serial number, and five more. On a copy that came with a PC the group of three was replaced by OEM. You could tell where your Windows came from without leaving System Properties.

      The binary record says more about how the copy was sold. Its header lists seven licence types.

      base/ntsetup/pidgen/inc/digpid.h, lines 22 to 30

      typedef enum {
          ltFPP,
          ltCCP,
          ltOEM,
          ltSelect,
          ltMLP,
          ltMOLP,
          ltMSDN
      } LICENSETYPE;

      FPP is the full packaged product, the box in the shop. CCP is the cheaper upgrade. The code calls the check “Compliance Checking”, since you had to own something to upgrade from. OEM was the computer maker’s copy. Select, MLP and MOLP were company licensing programmes (MOLP is Open License, if I’m reading the initials right), and MSDN was the developer subscription. An upgrade CD needed an upgrade key and a full CD a full key when you ran winnt32 from inside the old Windows. The PC makers had upgrade discs that came with full keys, so their media got an exception the comment describes as “broken by design”. There’s another comment on trying a clean install with an upgrade. “Bad user, bad.”

      base/ntsetup/winnt32/dll/eula.c, lines 1612 to 1621

      if (SourceInstallType != OEMInstall){
              // we want OEM FPP and CCP keys to be accepted by either media.  It seems like
              // there will be OEM CCP media, but only FPP keys, which is why we aren't
              // checking to make sure they match, as it's broken by design.
              if (UpgradeOnly != fStepUp){
                  // user is trying to do a clean install with upgrade only media.  Bad user, bad.
                  PidMatchesMedia = FALSE;
                  return FALSE;
              }
      }

      About ninety lines up, ValidatePidEx hands pidgen a made-up SKU ending in XYZZY. According to the comment the SKU mattered to system setup and hardly at all to winnt32. That makes another appearance for Colossal Cave’s magic word, after Minesweeper.

      Windows 2000’s volume media didn’t ask for a key at all. The superseded path is still in XP’s setup, commented out with a note about Select media. XP asked companies for a key too, which is why there’s a third version of the key page. Microsoft’s deployment guide says volume copies didn’t require activation. At the end of setup, Windows asks the licence agent whether this copy needs activating. On a volume installation it deletes both Activate Windows shortcuts.

      Service Pack 1 was the first time I found setup turning particular leaked keys away. Microsoft said in August 2002 that SP1 wouldn’t install on copies using either of two widely circulated volume keys, as The Register reported at the time. There’s a short list of rejected keys in SP1’s pidgen. The release build also rejects the range issued for the service pack’s beta. SP1 acquired a new message which Microsoft later quoted in its support article on changing a volume licence key.

      “The Product Key used to install Windows is invalid.”

      You were to go back to your administrator or the retailer for a valid one. If you suspected you'd been sold a pirated copy, the rest of the message invited you to write to Microsoft's Anti-Piracy Team and promised to keep whatever personal information you sent them in strict confidence.

      “Ready to activate Windows?” asked the first-boot wizard. It would take care of it over the Internet there and then, and in bold it promised “You don't need to give your name or other personal information when you activate Windows.” You could put it off for a few days. The version on the Start menu also let you call Microsoft. “Just four steps, and you're done…” was the page where you read a long installation ID to a person or an automated line, then typed the confirmation ID they read back to you. The little question mark tried to explain why, with the example of a bank asking you to activate a new credit or debit card. I liked the instructions for when the wizard itself failed. “Setup encountered and unexpected error. Please contact the SetupHot alias.” That's msoobe.exe telling a member of the public to write to an internal Microsoft mailing list. The “and” is in the file too.

      You can go through every page of the wizard looking for those thirty days. The number isn't there. Whoever drew the screen had to ask the licence agent how long you had left, and could commit in the text only to pestering you “every few days” or “periodically”. On the day the agent reported zero, the choice you'd been making all along had a new label. “No, log me off”.

      base/ntsetup/oobe/html/actshell.htx, lines 360 to 370

      var L_LogMeOff_Text = "N<u>o</u>, log me off";
      
      if (ndaysleft == "0")
      {
          g.act_par01_ZeroDays.style.display = "inline";
          g.act_spn3.innerHTML = L_LogMeOff_Text;
          if (window.external.HasTablet())
          {
              g.act_par03_Tablet.style.display = "inline";
          }
      }

      The limit is written down in TechNet. You got thirty days from installation, or sixty with an MSDN copy. When they ran out you couldn't log on interactively until you activated, though the services kept running on the machine. As for the balloons that spent the month reminding you, one program was called wpabaln.exe and all I've got of it is its name in the setup list. There's a second, oobebaln.exe, with its main file missing. Its messages are still there, down to the little “Click here to activate now…” and the name of the scheduled task, “Activation reminder”.

      base/ntsetup/oobe/oobebaln/msg.mc, lines 1 to 13

      MessageId=10001 SymbolicName=MSG_DAYS_LEFT
      Language=English
      %1!d! days left for activation.%0
      .
      
      MessageId=10002 SymbolicName=MSG_CLICK_TO_ACTIVATE
      Language=English
      Click here to activate now...%0
      .
      
      MessageId=10003 SymbolicName=MSG_CONTACT_ADMIN
      Language=English
      Please ask your administrator to activate this computer.%0

      “Activation is completely anonymous”, according to the privacy statement linked from both wizards. It also explained that Windows made an identification from the hardware in your PC. No name in it, no inventory of software or data, not even the make and model of the computer, Microsoft said. So how much of your machine could you replace before Windows thought it was activating a different one? Minor upgrades were fine, a complete overhaul might mean another activation. In July 2001 a Microsoft product manager told The Register you could change four pieces of hardware. The advice on the CD was to finish your planned upgrades before activating. That same month Fully Licensed, a German company that worked on copy protection, went through a release candidate and reported that what it sent was “completely innocuous”. They found you could get away with rather more changes than people had feared.

      PC makers could ship Windows already activated on their machines, which Microsoft described as “locked to a machine's firmware (BIOS)”. In the tree there are four oembios files marked “WPA tie file”, a component description identifying them as System-Locked Preinstallation files and setup copying them into place. The SP1 Windows Update client also asked the licence DLL for an encrypted copy of the product ID. It put that in the description of the machine it sent to the update servers.

      enduser/windows.com/iuengine/sysspec.cpp, lines 1161 to 1166

      //Note: Return value  is not checked because
      //Any failure to get the PID is not considered as a failure on the GetSystemSpec method
      //If the pid attribute is missing on the supported platforms  it is still considered as
      //an invalid pid case and no items will be returned in the catalog from the server
      //if there is any error bstrPID will  be null and it will not be added to
      //the systemspec xml
      

      The programmer’s comment is quite specific about what happened to a missing ID. The client could finish gathering the system information and send the request. On the platforms the check applied to, the server treated the missing ID as invalid and returned an empty catalogue. This is in 2002. Microsoft piloted Windows Genuine Advantage in September 2004 and made its validation a requirement for Windows Update in July 2005. Security updates remained available without validation through Automatic Updates and the Download Center.

      The server side is older and much bigger. NT’s License Logging service generally counted the connections other services accepted. The file server, dial-up, IIS, message queuing, Internet Printing, the Unix print service, telnet and Terminal Services each called NtLicenseRequest with the product name and the user, then gave the licence back when the user left. Telnet supplied the file server’s name. As far as the count went a telnet login looked like a mapped drive.

      net/tcpip/services/telnet/server/tlntsvr/telntsrv.cpp, line 1431

      Status = NtLicenseRequestA( "SMBServer", szVersion, &( pClient->m_hLicense), &NtLSData);

      What happened next depended on a choice the administrator made when installing the server. Per Server meant buying a number of simultaneous connections to one machine, at least five. The warnings began at about 90 to 95 percent of what you’d bought. For a while you could go over the limit with a warning that new requests “may not be granted”, and beyond that margin it turned them away. Per Seat meant buying a Client Access License for each computer to use the organisation’s servers. In this mode the service recorded who connected and directed the administrator to the Licensing tool to see how many licences to buy. The licence allowed one change from Per Server to Per Seat. The applet asks “Do you want to cancel this request?” and makes Yes the default.

      admin/netui/liccpa/dialogs.dlg, lines 61 to 69

      CAPTION "License Violation"
      FONT 8, "MS Shell Dlg"
      BEGIN
          LTEXT           "You have requested a change that violates the license agreement.  The license for this product only allows for a one-time change from a Per Server to a Per Seat configuration.",
                          401, 30, 6, 207, 29
          LTEXT           "Do you want to cancel this request?", 402, 30, 41, 207,
                          8
          DEFPUSHBUTTON   "&Yes", IDCANCEL, 45, 57, 40, 14
          PUSHBUTTON      "&No", IDOK, 101, 57, 40, 14

      The counts travelled up the network from each member server to a domain controller in the same site, and from there to a “site license master”. Whoever wrote the replication thread in ds/netapi/svcdlls/lls/server/repl.c describes its wait for work as waiting “to be given the opportunity to serve the greater good”.

      ds/netapi/svcdlls/lls/server/repl.c, lines 394 to 402

      //
      // Loop forever waiting to be given the opportunity to serve the
      // greater good.
      //
      for ( ; ; ) {
         //
         // Wait to be notified that there is work to be done
         //
         Status = NtWaitForSingleObject( ReplicationEvent, TRUE, NULL );

      A few lines further down, before it sends anything, “So they said, go replicate my son… Yeah, but first we must ask the master for permission.” The same code was compiled into Not For Resale editions with the count fixed at three or five connections for BackOffice kits, ten for a special NT Server. The applet holds the NFR edition of Small Business Server to two users. The 1996 readme has this just after the list. “Marketing forces being what they are, I'm sure more versions will appear.”

      Terminal Services counted its users in License Logging as TermService, but its licences came from a separate server. The messages call it the Hydra License Server, from Terminal Server’s old code name. Until it had been activated with Microsoft over the Internet, by web page or by telephone it could only issue temporary licences. Each licensing mode got a small policy class. There was Per Seat, Per Session (formerly Concurrent), Remote Desktop for Administration with its two connections, and XP’s single-user Remote Desktop. XP’s whole policy takes 63 lines and introduces itself as “A dummy licensing policy for Personal TS.” A small table in the module answers a different question, whether the client already has a licence included. The rows are other, Windows 2000, XP and later clients. In the Windows 2000 server column the other-client row is denied and the next three are allowed, which is where the entitlement for Windows 2000 and XP Professional clients comes from. The next two columns, XP-generation and later servers, deny a built-in licence to all four.

      termsrv/license/tlserver/tls236/request.cpp, lines 28 to 38

      #define DENY_BUILTIN                    0
      #define ALLOW_BUILTIN                   1
      
      
      static char LicenseTable[NUMBER_OF_CLIENT_OS][NUMBER_OF_TERMSRV_OS] =
      {
              {DENY_BUILTIN,  DENY_BUILTIN, DENY_BUILTIN },
              {ALLOW_BUILTIN, DENY_BUILTIN, DENY_BUILTIN },
              {ALLOW_BUILTIN, DENY_BUILTIN, DENY_BUILTIN },
              {ALLOW_BUILTIN, DENY_BUILTIN, DENY_BUILTIN }
      };

      To find its licence server, the terminal server tried the administrator’s list, then servers published in Active Directory, then the local domain or workgroup. The comment in efind.cpp is “TODO: add error codes/handling to all of this”. In Active Directory the code tries its site first. If that fails, it asks the other sites using a separate search filter.

      termsrv/license/tlserver/tlsapi/efind.cpp, lines 29 to 40

      #define LICENSE_SETTINGS                L"TS-Enterprise-License-Server"
      #define LICENSE_SETTINGS_FORMAT         L"LDAP://CN=%ws,CN=%ws,CN=%ws,%ws"
      #define LICENSE_SETTINGS_SIZE           CWSTR_SIZE(LICENSE_SETTINGS)
      #define LICENSE_SETTINGS_FORMAT_SIZE    CWSTR_SIZE(LICENSE_SETTINGS_FORMAT)
      #define SITES               L"sites"
      #define SITES_SIZE          CWSTR_SIZE(SITES)
      #define CONFIG_CNTNR        L"ConfigurationNamingContext"
      #define CONFIG_CNTNR_FORMAT L"LDAP://CN=%ws,%ws"
      #define CONFIG_CNTNR_FORMAT_SIZE    CWSTR_SIZE(CONFIG_CNTNR_FORMAT)
      #define ROOT_DSE_PATH       L"LDAP://RootDSE"
      #define ADS_PATH            L"ADsPath"
      #define SEARCH_FILTER       L"(CN=TS-Enterprise-LicenseServer)"

      Setup creates the object as TS-Enterprise-License-Server. The search of the other sites runs License and Server together, and I couldn’t find that spelling anywhere else in the tree. As far as I can tell, that search would miss the object. I haven’t been able to test it.

      Odds and ends

      • Many of the drivers that came with XP show 7/1/2001 and version 5.1.2535.0 in Device Manager, although XP was build 2600 and was finished in August. Both of those numbers are written down in tools/razzle.cmd.

        tools/razzle.cmd, lines 194 to 196

        @rem Set the default inf stamp date for WinXp.
        set STAMPINF_DATE=07/01/2001
        set STAMPINF_VERSION=5.1.2535.0

        Unless a component asks for a different date or version, those are the values the build stamps into its INF file.

      • Notepad decides whether a file without a byte-order mark is Unicode by asking IsTextUnicode. “If it doesn't, bug IsTextUnicode”, says the caller about the possibility of it getting the answer wrong. The heuristic compares how much the high and low bytes of each 16-bit unit vary. An ordinary English sentence can look like 16-bit text to that test. In the well-known four-word example the text comes back as 畂桳栠摩琠敨映捡獴.
      • Bliss, often called the most viewed photograph ever, is in the tree as a 51 KB JPEG. Setup converts it to a 1.4 MB BMP “since user can't handle .jpg's and we don't want to force Active Desktop on”.
      • XP’s graphical setup kept a couple of the developers’ debugging hooks in the shipping build. One carried the note “Can be turned off before we ship if we don't find use for this”. It stayed on, which is why setup pauses for two seconds before getting under way.
      • When the Pentium division bug turned up in 1994, NT gained a boot test that divided 4195835 by 3145727, multiplied the result by 3145727 again and checked that 4195835 came back.

        base/ntos/ke/i386/kernlini.c, lines 2234 to 2243

        Dividend = 4195835.0;
        Divisor  = 3145727.0;
        
        _asm {
            fld     Dividend
            fdiv    Divisor     ; test known faulty divison
            fmul    Divisor     ; Multiple quotient by divisor
            fcomp   Dividend    ; Compare product and dividend
            fstsw   ax          ; Move float conditions to ax
            sahf                ; move to eflags

        On a flawed chip NT could switch off the floating-point unit and handle those instructions in software in ntdll. The emulator’s files say “by Tim Paterson”. The Tim Paterson who wrote 86-DOS was back at Microsoft then, so I think it’s very likely him. In XP nothing sets the variable that runs the test. The code was still in the tree.

      • IE6 decides between its quirks and standards modes in one function. The Windows 2000 help files get special consideration because, as the comment points out, “Windows 2000 is already shipped”. One old doctype is a “Netscrape bookmark file”. In wininet you can also find HttpOnly, a cookie flag familiar from much later web applications. It debuted in IE6 SP1 in about a dozen lines of code.
      • There's an email thread in the font subsetter, windows/core/ntgdi/fondrv, complete with instructions to “Read this email thread in reverse order”. The subject in April 1996 was “Middle Dot”. Why should byte 0xB7 in the Windows character set show a bullet? In 1992 Word had been using the glyph to mark the spaces when you showed the formatting. The true middle dot ran into the letters next to it at small sizes. Apparently the decision still needed explaining four years later.
      • XP's first firewall put the log format on a separate line. The header of every log began “#Verson: 1.0”.
      • How does Explorer go from the list of files you're copying to a number of minutes left? In shell/shell32/copy.c a file counts for one point, a folder for one, and 32 KiB of data for another. Move within a drive and no points go on copying the data. Move to another drive and each file and folder counts twice since the old one has to be deleted after the new one is made. Every two seconds the dialog counts how many points it got through. To estimate the rate for the rest it gives that new speed one vote and the previous speed two, then divides the points left by the resulting average. It takes a while for news of a slow disk to get through to the dialog.

        shell/shell32/copy.c, lines 3101 to 3112

        else if (dwTimeLeft > 60)
        {
            // Note that dwTime is at least 2, so we only need a plural form
            LoadString(HINST_THISDLL, IDS_TIMEEST_MINUTES, szFmt, ARRAYSIZE(szFmt));
            dwTime = (dwTimeLeft / 60) + 1;
        }
        else
        {
            LoadString(HINST_THISDLL, IDS_TIMEEST_SECONDS, szFmt, ARRAYSIZE(szFmt));
            // Round up to 5 seconds so it doesn't look so random
            dwTime = ((dwTimeLeft+4) / 5) * 5;
        }

        The final adjustment is for the person sitting there watching. Seconds go up to the nearest five “so it doesn't look so random”. Over sixty seconds it's rounded up to minutes, over four hours the dialog stops offering a figure. A comment says it updates every ten seconds. The actual timer says 2,000 milliseconds. Raymond Chen wrote in 2004 that you can know the amount of work left perfectly well and still have to guess what the disk or the network will do next.

      What was cleaned out of the comments

      We have something better than an impression that the comments were tidied up. Kuro5hin quoted the Windows 2000 originals in 2004 in “We Are Morons: a quick look at the Win2k source”, counting “a dozen or so” f-words and s-words. Take XP SP1's C, C++, assembly and header files and search for the f-word. Zero. Take some of the surrounding words from the Kuro5hin piece and they're still here. There's a particularly obliging pair in shell32's util.cpp.

      In Windows 2000 the offending party is “the fucking alpha cpp compiler” which “seems to fuck up the goddam type "LPITEMIDLIST"”. After another few words for the compiler (“fucking peice of shit”) the writer explains passing the final parameter as a void pointer.

      the fucking alpha cpp compiler seems to fuck up the goddam type "LPITEMIDLIST", so to work around the fucking peice of shit compiler we pass the last param as an void *instead of a LPITEMIDLIST

      In the SP1 tree the instruction to the next programmer is the same. The description of the compiler has acquired a certain restraint.

      “alpha cpp compiler confused by the type "LPITEMIDLIST", so to work around this we pass the last param as an void *instead of a LPITEMIDLIST”.

      They left the space in “void *instead” just where it was. In another file “DOING SO FUCKS THE BUILD PROCESS” turns into “DOING SO MESSES UP THE BUILD PROCESS”. Rather nicely, whoever altered that line removed four exclamation marks from the end of it so the box it was drawn in still lined up.

      multimedia/media/verinfo/usa/verinfo.h, lines 1 to 8

      /*
       *      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       *      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       *      !!!!!!!IF YOU CHANGE TABS TO SPACES, YOU WILL BE KILLED!!!!!!!
       *      !!!!!!!!!!!!!!DOING SO MESSES UP THE BUILD PROCESS!!!!!!!!!!!!
       *      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       *      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       */

      Was it PoliCheck? Microsoft had such a tool, and Michael Kaplan wrote about it in 2010, but that doesn't tell us what ran on these files. Common controls still get “stinking piece of shit”, Notepad gets “such a #@@!@#@ an app”, and Calculator gets as far as explaining “what the [censored] I did here”. Leave the speech dictionaries aside and there are two traces of the f-word elsewhere. One's a label in a prebuilt DLL from the 16-bit compiler tools, cut off after 31 characters at JMPLOADZEROBECAUSETHISFUCKINGLA. In its source the same label now reads JMPLoadZeroBecauseThisLanguageHasNoFarConditionalJump. The other is on line 1252 of junkmail.lko, in the 1998 spam filter. For everything that went into getting that word out of the tree, the email model only gave it a weight of 0.028.

      As for “we are such morons”, the developers were talking amongst themselves. What went to the public SDK depended on hsplit, rewritten in 1996, which split a .w file into public and private headers. The complaint about a wizard redesign between IE4 and IE5 is in the private part of shell/published/inc/prsht.w. There were two unrelated wizard styles with similar names to accommodate. What people outside Microsoft saw of the discussion was one flag, PSH_WIZARD97.

      shell/published/inc/prsht.w, lines 407 to 420

      #if (_WIN32_IE >= 0x0400)
      //----- New flags for wizard97 -----------
      ;begin_internal
      // we are such morons.  Wiz97 underwent a redesign between IE4 and IE5
      // so we have to treat them as two unrelated wizard styles that happen to
      // have frighteningly similar names.
      #define PSH_WIZARD97IE4         0x00002000
      #define PSH_WIZARD97IE5         0x01000000
      ;end_internal
      #if (_WIN32_IE < 0x0500)
      #define PSH_WIZARD97            0x00002000
      #else
      #define PSH_WIZARD97            0x01000000
      #endif

      An exemption from checking a FAT volume gets explained as “a reasonable hack-o-rama to make BillG happy”. Gates had installed Beta 3 and got chkdsk on his machine. Setup wrote to the disk late in the installation. By the time of the check, other activity on the volume had left it temporarily looking dirty. The last sentence identifies the bigger trouble. FAT didn't have a journal.

      base/fs/fastfat/verfysup.c, lines 1137 to 1145

      //  This logic is a reasonable hack-o-rama to make BillG happy
      //  since his machine ran chkdsk after he installed Beta 3.  Why?
      //  'cause setup cracked a non-exclusive DASD handle near the
      //  end of setup, wrote some data, closed the handle and we
      //  set the verify bit ... came back around and saw that other
      //  arbitrary activity had left the volume in a temporarily dirty
      //  state.
      //
      //  Of course, the real problem is that we don't have a journal.
      

      Now read the FAT driver Microsoft published as an open sample on GitHub. “This logic is a reasonable change. Why?” Everything from the explanation to the sentence about the journal is still there. Only the account of BillG's machine has slipped out of the story.

      The swearing that survived

      You could still swear in print if you spelt things inventively. The file cache, on its way to waking the thread that writes to disk, calls a routine which under a particular condition will do nothing. The programmer had to go and read somebody else's source to find out that much. “I had to peak in the sources”, the comment begins, and “Sheeeeit!” is how it ends.

      base/ntos/cache/lazyrite.c, lines 737 to 738

      //  I had to peak in the sources to verify that this routine
      //  is a noop if the Flink is not NULL.  Sheeeeit!
      

      OLE had a master file defining extension interfaces for headers outside developers were going to use. The house rule at the top of it was “Keep random shit OUT of this subdirectory, or die.”

      com/published/idlole/oleext/oleext.idl, line 13

      //  Warning:    Keep random shit OUT of this subdirectory, or die.

      “We seem to have shipped this thing with a giant leak.” Disk Cleanup had already allocated a buffer by the time a cleaner could throw the pointer away. They went on allocating it because shipping customers might well have a cleaner expecting to get that buffer. The comment calls it “the dumbass part” and the variable put aside to save the buffer is wszDumbassLeakProtection.

      shell/applets/cleanup/cleanmgr/dmgrinfo.cpp, lines 593 to 599

      // We seem to have shipped this thing with a giant leak.  The object is supposted to set
      // pClientInfo[dwClient].wcsDescription to NULL if the registry value should be used instead
      // of the buffer.  However we just allocated a buffer for pClientInfo[dwClient].wcsDescription
      // in the code above (this is the dumbass part).  All the filters then set this pointer to
      // NULL and it's bye-bye buffer.  I can't simply not allocate this memory because some cleaners
      // might rely on being able to use this memory and we shipped it that way.
      LPWSTR wszDumbassLeakProtection = pClientInfo[dwClient].wcsDescription;

      The F1 help fix for the networking tools' IP address controls is described in exactly the same terms in three files, down to the two “f**king”s at the beginning and the “*SIGH*” at the end. rundll32 calls SetErrorMode to “turn off critical error bullshit”. The failure code for a crash dump, over in Windows Error Reporting, goes into dwAwShit. Somebody copying a warning into nine DirectShow files had exercised their editorial discretion. A “<deleted> person” had turned the damned level 4 warnings back on in the header.

      What Microsoft said about itself

      Program Manager still built as progman.exe. Whoever wrote this bit of its DDE code would have liked to ask a simple question about window state and couldn't. Their professional opinion of the Windows API is that “it really is the worst windowing system I have ever used.” I rather like the consolation they find for a lack of consistency in the design. “Luckily orthogonality doesn't affect stock prices :-)”.

      shell/osshell/progman/pmdde.c, lines 2203 to 2207

      // It would be nice if there was some way to query a SW_ value
      // but I guess it would too much to ask for windows to be even remotely
      // orthogonal.  I don't know who "designed" the Windows API but it
      // really is the worst windowing system I have ever used.
      // Luckily orthogonality doesn't affect stock prices :-)
      

      The person making FTP folders work in XP thought wininet could have done something about a bug where files looked like directories. The wininet team couldn't reproduce it. “It's no repro because I did this work around!”, says the person who had made the folders work.

      shell/ext/ftp/util.cpp, lines 658 to 662

      // NOTE: IE #30208: Currently broken in wininet.  The dorks in wininet never fixed this because
      //       they say it's no repro.  It's no repro because I did this work around!$#!@@#%!!!
      //
      //         I want to test the attribute flags but for some reason the FILE_ATTRIBUTE_DIRECTORY bit
      //         is also set for files!!!! (!@(*#!!!)
      

      In IIS somebody stopped in the middle of calculating the length of a redirect page to consider what a custom error file might contain. The writer doubted the calculation could handle a useful custom error page. The comment opens “This code is so @#$#%@%$.” By the end they're angry enough to suggest a beating for whoever wrote it.

      The longest complaint belongs to the IIS FTP server. A fix for idle timeouts had broken shutdown. With three days to go until K2 Beta 1 (IIS 4 in 1997), the author put in a temporary workaround and left “REMOVE THIS POST BETA 1 AND FIX USER_DATA PROPERLY!!!!”. The first line is “Geezsh, I hate my life.” The workaround was still there in 2002. One thing that did get attention, according to a March 1998 note, was a debug message about masking the FTP bug. Someone had sent the checked DLL to Ernst & Young and the message had caused “some embarrasment”.

      Microsoft's 16-bit network library read results from the DOS network emulation even when it didn't yet know that the call had worked. “IT DOESN'T LOOK AT THE RETURN CODE FIRST.” The next line attempts to do on paper one of Sam Kinison's screams.

      base/mvdm/vdmredir/vrnetapi.c, lines 1348 to 1351

      // This function tries to unpack BX entries from the enum buffer as
      // soon as control is returned after the call to the redir via DoIntx. BUT
      // IT DOESN'T LOOK AT THE RETURN CODE FIRST. As Sam Kinnison used to say
      // AAAAAAAAAAAAAAARRRRRGH AAAAAAARGHH AAAAAAARGHHHHHHH!!!!!!!
      

      In the DHCP, WINS and IPX consoles, the function for opening property sheets is called DoPropertiesOurselvesSinceMMCSucks. Health Monitor also has some advice for the next person who expects MMC to initialise it just once. “But you know those MMC clowns…” I like the solution in the dial-up Connect dialog, which can't identify its drop-down list because Windows didn't give the list a parent. It makes the thing 19,591 pixels wide, then goes looking for a window that wide on the desktop. With Office XP installed, Explorer puts Windows icons on images and on the Word, Excel, Access, PowerPoint and FrontPage web pages. The Office icons were deemed ugly, whereas “ours are so beautiful…office wont mind”. The loop to do it is headed “replace this ugly chicken”.

      The Microsoft SideWinder people told DirectInput that five or six polls would do. The Windows 9x code polls sixteen times “to shake the stick into submission”, with “They're wrong” for the hardware team's estimate. Then there's a delay looked up in the registry. It depends on the CPU, another thing SideWinder forgot to tell DirectInput, if you go by the comment. “What a bunch of lamers” in the earlier version has turned to “What a shame” in DirectX 8.

      Some comments are addressed to Microsoft at large. In August 1991 a resource compiler programmer found a way to handle Unicode files for the tool that built Windows' dialog boxes. “I'll be the first person to admit that this is an ugly solution, but hey, we're Microsoft :-)”. The state flags in the window manager's central header double as painting hints and carry an “AWESOME HACK ALERT!!!”. For a measure of its magnitude the comment suggests consulting the national debt.

      windows/core/ntuser/inc/user.h, lines 2849 to 2856

      /*** AWESOME HACK ALERT!!!
       *
       * The low byte of the WF?PRESENT state flags must NOT be the
       * same as the low byte of the WFBORDER and WFCAPTION flags,
       * since these are used as paint hint masks.  The masks are calculated
       * with the MaskWF macro below.
       *
       * The magnitude of this hack compares favorably with that of the national debt.
      

      A port in the DirectPlay multiplayer code will be familiar from old firewall guides. In the source the constant is 2234. The code forgot to convert it to network byte order, which made its real port 47624. “We are living with the mistake.”

      multimedia/directx/dplay/dplay/wsock/dpsp.h, lines 83 to 87

      // Oops! We forgot to convert these constants to net byte order in the code so we
      // are really using port 47624 (0xBA08) instead of 2234 (0x08BA)
      // We are living with the mistake.
      #define SERVER_STREAM_PORT 2234
      #define SERVER_DGRAM_PORT 2234

      Windows Write, the 16-bit word processor from Windows 1.0, still has a directory in the XP tree. Somebody following the build instructions couldn't quite get the WRITE.EXE they'd had in Windows 2.x and went round asking the people who'd been there. Their first finding was “Nobody wants this product or claims responsibility for it.” Everyone who'd worked on it, with it or even around it seems to have found it a nightmare.

      base/mvdm/wow16/write/readme.txt, lines 40 to 46

      The above procedure was not generating quite the same WRITE.EXE as we've
      previously had (Win 2.x).  In talking with anyone who's ever been involved
      at all, this is the information I have learned:
      
         1. Nobody wants this product or claims responsibility for it.
         2. It has been a nightmare for everyone who has worked on, with,
            or around it.

      They also had a file called EDM.EDM, on which the readme observes “hey, file naming is our specialty here at MS”.

      The Tweak UI PowerToy gave users access to settings Windows didn't have controls for. It encoded the names of the registry paths it used so they wouldn't turn up in a casual search for text. The source calls them “politically damaging strings”. There's a feedback link in window title bars with the old internal name Lame button, still visible in HTLAMEBUTTON, PLAMEBTNPROC and the label marked “formerly 'Lame…'”. The DLC driver for IBM's network protocol calls itself “a piece of garbage”. The packet pools in its memory header were attached to other things “lamprey-like”, and the writer proposed moving them to a ZombieList. The new fields were never enabled. The state machine gives its review, “The orginal IBM state machine sucks!!!”.

      I also found two comments addressed fairly directly to people who worked there. The listbox code remarks on the UI people being “sillier than your 'typical dumb user'” over a little-known Shift+F8 mode. A debugger extension for the window manager expects a tag by number. Give it the name instead and the error addresses a colleague by his first name and asks “How long have you been here?”

      What Microsoft said about everyone else

      Eventually you get to people outside Microsoft. The multiprocessor HAL, down between the kernel and the motherboard, needs an account of the buses on the machine. Normally it can ask the BIOS. Then comes the exception, identified by the manufacturer's name. “Compaq machines have their own special ways to be busted.” For a Compaq the HAL goes straight to probing the hardware.

      base/hals/halmps/i386/mpaddr.c, lines 971 to 976

      // Compaq machines have their own special ways to be busted.  So,
      // when dealing with Compaq, never believe their MP table at all.
      // Go straight to probing the hardware.
      //
      
      if (!strstr(PcMpTablePtr->OemId, "COMPAQ")) {

      An upgrade has to remove three Intel networking components. Somebody put that job in HrRemoveEvilIntelWinsockSPs, and at least gave the next fellow the bug number and an explanation: “a complete hack to cure RAID 332622, but it's all we can do this late in the ship cycle”. Sound Recorder's complaint is about Creative Labs. The card gives the buffer back marked done, then when Windows tries to release it the card says it's still playing. The author had thought Media Vision had the field to itself in this sort of “Creativity”.

      multimedia/media/sndrec32/soundrec/wave.c, lines 834 to 842

      //  because Creative Labs thinks they know what they are doing when
      //  they don't, we cannot rely on the unprepare succeeding like it
      //  should after they have posted the header back to us... they fail
      //  the waveInUnprepareHeader with WAVERR_STILLPLAYING (21h) even
      //  though the header has been posted back with the WHDR_DONE bit
      //  set!!
      //
      //  absolutely smurphingly brilliant! and i thought Media Vision was
      //  the leader in this type of 'Creativity'!! they have competition!
      

      The person decoding Intel cache descriptors had an undocumented formula to maintain. If Intel ever changed it, “the nice people at Intel better pray I'm dead before they break it or I'll hunt them down”. The parallel-port people seem to have had a quieter meeting with their vendor. The y in an LPTx.y name had given away where a device sat in a 1284.3 daisy chain, so the driver had to keep that odd spelling. The vendor had “apologized profusely” and promised to try to avoid undocumented interfaces, or at least to tell Microsoft when it used one.

      drivers/parallel/parport2/utils.c, lines 1570 to 1575

      // At least one vendor uses the y from LPTx.y to determine the
      // location of their device in the 1284.3 daisy chain.  We
      // have chastised this vendor for using this undocumented
      // interface and they have apologized profusely and promised
      // to try to avoid using undocumented interfaces in the future
      // (at least without telling us that they are doing so).
      

      WordPerfect used to open Control Panel hidden so it could talk to it. In the source it goes by NerdPerfect. The people dealing with this say “we are blowing off fixing the communication stuff”, which is how the Control Panel launcher came to disregard requests to open hidden. Lotus got a review in the themes engine's list of programs to leave alone when drawing title bars. The list is switched off in this build, but you can still read about WordPro, “a particularly poorly implemented app”, and a WordPerfect compatibility menu someone thought was “the elephant man of modern software”.

      shell/themes/uxtheme/handlers.cpp, lines 321 to 322

      L"WordPro",     // 285065: Lotus WordPro, a particularly poorly implemented app.
      L"SmartCtr",    //         It's WordPerfect compat menu is the elephant man of modern software.
      

      Or take a piece of padding in the structure Windows 9x kept for a thread. That old kernel code is here for 16-bit programs and the padding has to stay. Somebody at SAS got the internal layout and the statistics package reads something at a particular offset. “Whoever gave this internal structure to SAS is a bonehead. Break SAS and see what happen”. There's a little more invention in the 1992 NT User Manager. It needed accounts while an API was missing, so its fake users include Winnie The Pooh, “Soviet Union - NOT”, and one called “Unix Yuck”. The last one's description is “Unix - why ask why?”

      The rest of the jokes

      My favourite comment in the hardware abstraction layer is in the code for coming back from standby. It explains why the processor cache should be invalidated in case a stray gamma ray flipped a bit while the machine slept. “Honestly. Intel asked for this. I'm serious.” After all that insistence, the instruction itself has been commented out.

      base/hals/halacpi/i386/ixsstate.asm, lines 489 to 496

              ; Invalidate the processor cache so that any stray gamma
              ; rays (I'm serious) that may have flipped cache bits
              ; while in S1 will be ignored.
              ;
              ; Honestly.  Intel asked for this.  I'm serious.
              ;
      ;.586
      ;        invd

      The HAL has opinions about clocks. A power-management timer has given a reading earlier than the previous one, so “maybe it's time to upgrade that 200MHz CPU if you want fast boot!” A second complaint is spelled “We already had one decreasing read, looser!” Look up HalpPCIType2TruelyBogus if you want the longer treatment. On a multiprocessor machine with the old way of reading PCI configuration space, its fix involves stopping every processor. The description starts “This is a piece of work”, uses “bad” about ten times and still has more to say under “While I'm flaming.” In the register map for the multimedia timer that became HPET, four of the padding fields are called Unknown, Mystery, Secret and Abyss.

      If you ever got a stop sign on an office PC for trying to do something the administrator had forbidden, the function behind the box has a message for you. It's the popular misquotation of HAL 9000: “I'm sorry, Dave, I can't let you do that.”

      shell/shlwapi/util.cpp, lines 2652 to 2654

      // "I'm sorry, Dave, I can't let you do that."
      
      LWSTDAPI_(void) SHRestrictedMessageBox(HWND hwnd)

      Why does XP's Registry Editor put “Windows Registry Editor Version 5.00” at the head of a file it exports? Why not REGEDIT5? “Sit back, and I will tell ye a tale of woe.” The Windows 95 reader got as far as the character after REGEDIT. A 4 indicated the Windows 95 format. Anything else, which would have included a 5, went to the Windows 3.1 reader. The newer source actually quotes the offending line and observes, “Of course there won't be a version 5 of regedit. Version 4 was perfect!”

      Programs that WMI's command-line event consumer launched were allowed only so much time to finish. The method that arranges for one to be terminated is called ScheduleAssassination. It takes the program's process handle as hVictim and the appointed time as lastMeal.

      admin/wmi/wbem/winmgmt/esscomp/stdcons/wbemcons/prockiller.cpp, lines 26 to 28

      // hVictim is a handle to a process
      // last meal is the scheduled execution date
      HRESULT CProcKillerTimer::ScheduleAssassination(HANDLE hVictim, FILETIME lastMeal)

      Three sample events turn up in a debug WMI event viewer. The “Coffee machine” reported “Device off”. “Human Chicken” reported “Low Caffiene” because it “Can't operate coffee machine before drinking coffee”. Severity one was reserved for 12:30 on 14 January 1998 and the server was “Reality”. Event: “End of World”. Explanation: “The big guy is mad about everything”.

      admin/wmi/wbem/sdk/activex/controls/eventviewer/eventlist/eventlistctl.cpp, lines 281 to 285

      data->m_severity = 1;
      data->m_time = COleDateTime(1998, 1, 14, 12, 30, 0);
      data->m_EClass = _T("End of World");
      data->m_server = _T("Reality");
      data->m_desc = _T("The big guy is mad about everything");

      Terminal Services left a word in the user parameters of every account that had ever had its settings. CfgPresent was the marker for the presence of Citrix configuration data. In hex the word was 0xB00B1E55.

      termsrv/regapi/regup.c, lines 76 to 82

      /*
       *  WIN_CFGPRESENT is used to indicate that the Citrix configuration
       *  information is present in the User Parameters section of the user's
       *  SAM record.
       */
      #define WIN_CFGPRESENT L"CfgPresent"
      #define CFGPRESENT_VALUE 0xB00B1E55

      Oh_Freddled_Gruntbuggly does nothing. An IIS library on Alpha needed one function in it, so somebody obliged with the opening of the Vogon poem from The Hitchhiker's Guide to the Galaxy, in hitchhiker.cpp. An Active Directory cache page can be bfdfClean, bfdfUntidy, bfdfDirty or bfdfFilthy. “Banana” is the resource name of Task Manager's process context menu. DirectPlay could send a debugging message to stop a peer in its debugger. The log on one side says “sending DIE PIGGY. sayonara sucker”, on the other “THIS IS ONE DEAD PIGGY”. I've left out a name and extension. The sender is disabled in this build.

      One performance-counter DLL loses the train of thought halfway through a sentence: “First we have to a DestroyObject on all the objects that this process has created, this we do by - interrupt - missed what I was thinking !!!!”. The person hard-coding 1999 into a release script that expanded two-digit years reckoned they'd be dead in 2099, “sue me then.” Sound Recorder marks its writer's first goto in ten years, followed thirty-five lines later by the second. The 16-bit video code draws a frame the AVI player has told it to skip to compensate for a player bug. “Works fine in theory, but in theory, communism works!” In the kernel's user-mode security editor the unfinished privileges tab tells the user, “I'm sorry, but due to the lack of time and interest, individual privilege selection is not yet supported.” The ACPI bus driver describes talking to the power and plug-and-play firmware as “black magic”. After reading some of it I'd call that fair.

      Microsoft, Microsoft, Microsoft, Microsoft, Microsoft, Microsoft, Microsoft. Those are the seven forbidden words in the OEM Preinstallation Kit's check on the support text a PC maker could supply. The first is a literal string and the remaining six are variables that resolve to the same thing. “Now make sure they don't use any naughty words”, says the loop.

      base/ntsetup/opktools/files/wizard/opkinput.inf, lines 18 to 25

      [IllegalWords]
      Microsoft
      %msft_loc1%
      %msft_loc2%
      %msft_loc3%
      %msft_loc4%
      %msft_loc5%
      %msft_loc6%

      Where the source lived

      Raymond Chen dates the move from SLM to Source Depot to “shortly after Windows 2000 shipped”, which as far as I can tell makes XP the first Windows developed on it. SLM, the Source Library Manager, was pronounced “slime”. The clients cooperated to maintain one central copy and there were no branches. Source Depot was “an authorized fork of Perforce”. Three genuine slm.ini files went with a printer driver by accident. They still refer to //EIGOS100/SLM and a directory under the old NT/PRIVATE tree. A fourth, under enduser/speech/ce/public, was made expressly to fool an old tool called inallprj. It says quite plainly you are not enlisted in an SLM project.

      enduser/speech/ce/public/slm.ini, lines 2 to 6

      ****************************************************
      * This file is for faking "inallprj" to work under *
      * a Source Depot client -- you are *NOT* enlisted  *
      * in a SLM project here!!!                         *
      ****************************************************

      WinDiff retained the code Geraint Davies wrote in 1993 for getting old files out of SLM. When the Source Depot support went in next to it somebody annotated a common structure “shared, SD and SLM”. There are directions for the move in net/branch-reasons-and-info.txt. You could look up where an individual networking file went from the oldnt tree into newnt.

      Sixteen new depots for what used to be one tree. The root had one and so did each of the fifteen projects from admin to windows. There's a roster of all the servers in tools/whocheckedin.pl, whose header still calls the script sdout.cmd.

      tools/whocheckedin.pl, lines 15 to 30

      %depot_list = (("Admin" => "admindepot.sys-ntgroup.ntdev.microsoft.com:2002"),
                     ("Base" =>        "basedepot.sys-ntgroup.ntdev.microsoft.com:2003"),
                     ("COM" =>         "comdepot.sys-ntgroup.ntdev.microsoft.com:2004"),
                     ("Drivers" =>     "driversdepot.sys-ntgroup.ntdev.microsoft.com:2005"),
                     ("DS" =>          "dsdepot.sys-ntgroup.ntdev.microsoft.com:2006"),
                     ("EndUser" =>     "enduserdepot.sys-ntgroup.ntdev.microsoft.com:2007"),
                     ("InetCore" =>    "inetcoredepot.sys-ntgroup.ntdev.microsoft.com:2008"),
                     ("InetSrv" =>     "inetsrvdepot.sys-ntgroup.ntdev.microsoft.com:2009"),
                     ("MultiMedia" =>  "multimediadepot.sys-ntgroup.ntdev.microsoft.com:2010"),
                     ("Net" =>         "netdepot.sys-ntgroup.ntdev.microsoft.com:2011"),
                     ("PrintScan" =>   "printscandepot.sys-ntgroup.ntdev.microsoft.com:2012"),
                     ("Root" =>        "rootdepot.sys-ntgroup.ntdev.microsoft.com:2001"),
                     ("SdkTools" =>    "sdktoolsdepot.sys-ntgroup.ntdev.microsoft.com:2013"),
                     ("Shell" =>       "shelldepot.sys-ntgroup.ntdev.microsoft.com:2014"),
                     ("TermSrv"  =>    "termsrvdepot.sys-ntgroup.ntdev.microsoft.com:2015"),
                     ("Windows" =>     "windowsdepot.sys-ntgroup.ntdev.microsoft.com:2016"));

      The developer dealt with SDX 1.03, in tools/sdx.pl. Point SDXROOT at an enlistment, select the product, branch and projects wanted (there was an option for all projects), and sdx sync, submit or integrate did its work in every project one after another. In 2001 there were scripts both to catch a project pointing to a different branch from the enlistment root, checkdepots.pl, and to switch an entire enlistment, changelab.pl.

      Public was the place to go for another project's headers and libraries. The primary build machine for the branch checked them in. Add or remove a file and you had to put your mail name and reason in tools/publicchanges.txt. It says “KEEP THIS FILE SORTED…” twice. The file and its archive record 2,250 entries by 242 people, from “Mistake” and “Fix public screwup” to “use in conjunction with sputilsa.lib (temporary)”. Six build files require you to consult a named individual. “Any changes made without doing so will be summarily deleted”.

      =tools/buildmachines.txt= lists the labs actually building Windows. Lab01_N through Lab07_N, with no Lab05, and Lab10_N. changelab.pl would accept names as far as lab15_n. There was main, xpclient for the product, xpsp1 for the service pack and a QFE branch for hotfixes. VBL is what the scripts call a lab's build machines, presumably virtual build lab. All told the file contains 158 entries for 146 official machines across fourteen branches. Take the rule about primary machines at the head of the file and then look at the very first branch it lists.

      tools/buildmachines.txt, lines 1 to 9

      ; This file lists the official build machines for each branch.  It's layout
      ; s/b obvious (machinename,primary/secondary,branchname,arch,chk/fre,notifydl).  There can only be
      ; one primary build machine for any branch (that's the machine that will be
      ; checking in most of the published headers and libs).
      
      WINSEXPFI,primary,xpclnt_qfe,ia64,fre,qfebld
      WINSEXPFX,primary,XPCLNT_QFE,x86,fre,qfebld
      WINSEXPCI,primary,XPCLNT_QFE,ia64,chk,qfebld
      WINSEXPCX,primary,XPCLNT_QFE,x86,chk,qfebld

      One primary per branch is permitted. The first branch, QFE, has four, one for each combination of architecture and flavour. Fre means retail or free and chk means debug or checked. Main, xpclient, idx01 and idx02 also have four. 77 entries say distbuild, where several machines shared a build. The 158 entries break down as 82 x86, 72 Itanium, two AMD64 (one machine, two flavours of Cutler's port), and two axp64, lab machines for the old 64-bit Alpha.

      Read an RI in the comments to tools/sdx.pm and you can time an actual delivery. RI is reverse integration, lab up into main, whereas ordinary integration went back down to the lab. For build 2268 on 8 September 2000 Lab07 sent a change into each of seven depots. The entries start at five in the afternoon and cover a little over two minutes.

      tools/sdx.pm, lines 9842 to 9847

                     build  contrib
      build type op  branch branch  project    change/timestamp
      ----- ---- --- ------ ------- ---------- -------------------------
      2268  MAIN RI  main   lab07_n admin      15654 2000/09/08:17:00:04
      2268  MAIN RI  main   lab07_n base       10928 2000/09/08:17:00:21
      2268  MAIN RI  main   lab07_n com        1755 2000/09/08:17:00:29

      RI could also mean the deadline after which somebody hoped to tidy up. A driver kit copy script has an “extra split for a quick fix so we can RI”. A proper one “will be test and checked in for the next RI.”

      In 2017 Windows finally moved from Source Depot to Git. It had grown to 3.5 million files, 300 GB, 4,000 engineers and 440 branches, with 1,760 lab builds in a day.

      How it was built

      How did they get one Windows out every day when developing Windows 2000 had taken about 1,400 developers and 1,700 testers? Mark Lucovsky, one of the original NT engineers, gave a talk in August 2000 and described what they had been doing. You needed written permission to change the source. The build lab approved about a hundred changes a day and typed the sync and build commands in itself. In his words, “a developer that mistypes a build instruction can stop the build lab, which in turn stops over 5,000 people”. The lab branches let each lab run its builds, “100% hands off”. Ten in the morning and ten at night each got a “full synch and full build”, with failures detected and mailed to the team. Under tools you can read how much of what we now do in CI they had got working.

      The first thing you needed was a build window. tools/razzle.cmd, named after NT's old code name Razzle according to Chen, gave you “a pure system path”, because “16-bit tools sometimes puke on long paths”. The compilers from the tree went first. It picked the processor and, unless you asked otherwise, gave you a checked build with DBG=1 and the assertions intact. About 8,500 C files and headers have conditional DBG blocks. Then the command to build Windows was build. Its 20,335 lines are in sdktools/build and its history starts on 16 May 1989. It walked dirs files to find the directories and sources files to find out what one binary needed. There are 3,650 of the former and 13,139 of the latter. Minesweeper's sources, for example, identifies a program named winmine, lists its C files and asks for the Unicode definitions and the C runtime.

      shell/osshell/ep/winmine/sources, lines 1 to 19

      TARGETNAME=winmine
      TARGETPATH=obj
      TARGETTYPE=PROGRAM
      
      INCLUDES=.;..
      
      C_DEFINES=-DWIN32 -D_UNICODE -DUNICODE
      
      USE_MSVCRT=1
      
      MSC_WARNING_LEVEL=/W3 /WX
      
      SOURCES=winmine.c       \
              grafix.c        \
              pref.c          \
              rtns.c          \
              sound.c         \
              util.c          \
              res.rc

      Look at the makefile beside almost any one of those sources files and there's only one line of consequence. All the machinery is in tools/makefile.def, 4,532 lines of nmake shared across the tree. Some 7,125 little makefiles say they're for “all the components of NT OS/2”, as the project was called until 1990. build.exe sent nmake round three times, to generate files such as the MIDL interfaces and message tables, to compile, and to link. binplace then split out the debug symbols and put the binaries where placefil.txt told it to (19,593 entries). If a build had no errors, build.exe deleted the empty build.err. Everything else could watch for the existence of that one file. And an individual developer didn't have to build Windows just to try a change. PopulateFromVBL.pl gave you the lab's latest binaries to use with the project you'd compiled yourself.

      There is a per-processor makefile too. All the architectures use /WX to turn a compiler warning into an error. Two undocumented options caught my eye in the x86 makefile. Its comments translate them: /QIf asks for frame pointer omission records for every function, and /QIfdiv- tells the compiler not to generate a test for faulty Pentiums.

      tools/i386mk.inc, lines 202 to 206

      # Undocumented switch definitions
      # /QIfdiv- : Don't emit code to test for bad pentiums
      # /QIf     : Emit FPO records for every function
      
      ERATTA_FLAGS=/QIfdiv- /QIf

      The old 1994 Pentium division bug shows up in the kernel elsewhere in this article. Here every x86 file was compiled with an explicit instruction to leave out the compiler's check for it. You can date the compiler quite closely. tools/x86 contains pre-release binaries, with cl.exe identifying itself as 13.00.9176 from March 2001. Visual Studio .NET, the product it was being built for, appeared in February 2002 with 13.00.9466.

      An official binary carries the branch name. Somebody using a shared Terminal Services machine for a buddy build gets the branch and computer name, and an ordinary developer gets the branch and their user name. That's how you can look at the 112 stamped tools in tools/x86 and find that 91 came from somebody's machine or a shared one. One is a header tool for WOW64, which lets 32-bit software run on 64-bit Windows. It was built under Dave Cutler's user name, starting at 20:36 on New Year's Day 2001.

      Now follow a build in the lab. tools/timebuild.pl has most of the work written out in its running order, a condition on the left, the command it governs beside it.

      tools/timebuild.pl, lines 65 to 83

          '!NOSYNC         revert_public.cmd',
          '=CHECKSYNC      CHECKWARN      perl %sdxroot%\Tools\sendbuildstats.pl -warn -m revert_public failed',
          '=NOSCORCH       @echo SKIPPING scorch',
          '!NOSCORCH       nmake -lf makefil0 scorch_source',
          '!NOSCORCH       CHECKWARN      perl %sdxroot%\Tools\sendbuildstats.pl -warn -m scorch failed see %sdxroot%\build.scorch',
          '!NOSYNC         sdx sync ...<<timestamp>> -q -h > build.changes 2>&1',
          '=CHECKSYNC      CHECKWARN      perl %sdxroot%\Tools\sendbuildstats.pl -warn -m sdx sync failed',
          '!NOSYNC         sdx resolve -af',
          '=CHECKSYNC      CHECKWARN      perl %sdxroot%\Tools\sendbuildstats.pl -warn -m sdx resolve failed',
          '!NOSYNC         perl %sdxroot%\Tools\ChangesToFiles.pl build.changes > build.changedfiles 2>&1',
          '!NOSYNC         @echo BUILDDATE=<<BUILDDATE_timestamp>> > __blddate__',
      
      #   '                sdx delta > build.baseline',
      
          '!NOCLEANBUILD   build -cZP',
          '=NOCLEANBUILD   @echo NOT BUILDING CLEAN',
          '=NOCLEANBUILD   build -ZP',
          '                CHECKBUILDERRORS',
          '                CHECKFATAL      perl %sdxroot%\Tools\sendbuildstats.pl -too -buildfailure',

      Read !NOSYNC as unless you've asked to skip the sync, CHECKWARN as mail somebody if the previous step failed, CHECKFATAL as stop. The first casualties of a clean build were local modifications to the published headers and writable files that Source Depot hadn't supplied, removed by scorch_source. The sixteen depots were all synced to the same minute. That date went in the build. The script ran the clean build and if it failed, mailed the people who might have broken it.

      =2415.x86fre.main.001222-1745= was an example in the usage text. If build 2415 was to be a retail x86 build from main at 17:45 on 22 December 2000, timebuild could wait for that minute, sync every depot to it, then use it for the name. That's how you read 5.1.2600.1106 (xpsp1.020828-1920) on an SP1 machine: xpsp1 on 28 August 2002 at 19:20. The number in ntverp.h itself was “only modified by the official builder”. You can still read newver.pl, a “failed attempt at a auto-newver script, keeping for future reference”. Larry Osterman traces the round release number to Brian Valentine. NT used to advance one a day, but over on Exchange where Valentine came from they rounded up at a milestone. XP got 2600.

      It's one thing to notice that a file no longer compiles. Is its last editor the person to drag out of bed? sendbuildstats.pl took the broken paths, turned them into directories and asked what files in those directories had been synced since the last build. That gave it a set of changes and a set of people.

      tools/sendbuildstats.pl, lines 545 to 563

      for (<FD>) {
         my($project, $change, $dev, $date, $time, $sdpath, $type) = split;
      
         next unless $type;
      
         $_ = $sdpath;
      
         s|#.*||;               # strip #change
         s|//depot/[^/]*/||i;   # strip //depot/lab
         tr|/|\\|;              # / -> \
      
         $canonpath = CanonicalizeBuildPath $_;
         next unless $BuildFailure{$canonpath};
      
         print "Suspect $dev because of change $change affecting $canonpath\n"  if $Verbose and not $Pinged{$change};
         $Pinged{$change}++;
      
         $Checklist{$dev}++;
      }

      People on the list got the email directly and the lab got a copy. If the script came up empty, everyone who'd changed anything got the mail. Apparently the lab could acknowledge an error while the build was running. When the current build.err matched the saved build.fixed-err, the pipeline reported “Error file hasn't changed. Build errors ignored.”

      tools/checkbuild.cmd, lines 5 to 24

      REM Sleep 15 minutes
      sleep 900
      
      REM See if there's a build.err.  If not, retry.
      if "%_BuildBranch%" == "Lab01_N" goto Lab01_SpecialWork
      
      :CheckForBuildErrors
      if NOT exist %_ntbindir%\build.err goto top
      for %%a in (%_ntbindir%\build.err) do if %%~za EQU 0 goto top
      
      REM Is there a build.fixed-err?  If not, page 'em.
      if NOT exist %_ntbindir%\build.fixed-err goto PageBuildBreak
      
      REM Are the build break fixed?  If not, page 'em.
      set ERRORS=1
      for /f "delims=" %%i in ('fc %_ntbindir%\build.err %_ntbindir%\build.fixed-err') do (
          if "%%i" == "FC: no differences encountered" set ERRORS=0
      )
      
      if "%ERRORS%" == "0" goto top

      Every fifteen minutes tools/checkbuild.cmd compared the files. If they differed it sent “Build Break” to an email-to-pager gateway. syncbuild.cmd had a loop for running timebuild over and over, doing the sync, the build and the mail on each round. Chen remembers a four-processor Alpha doing this hourly for the shell team. Its message was “The Alpha AXP build is broken. Go fix it.”

      Eight hours for a complete Windows 2000 build on four processors, according to Lucovsky. Build Console 1.0 in sdktools/mtscript could spread the wait around. Its JScript service registered with remote COM. A web page could direct machines the code calls slaves. Main's x86 retail build had four distbuild machines feeding one postbuild host, Lab07's checked Itanium build had ten. A worker cleared the tree, synced on six threads, built and copied its output to the postbuild host. Then it waited for nextpass. In a sample for one depot on one machine, 13 April 2000, generating files took about six minutes, waiting for the others 48 minutes, and compiling 27 seconds. Another three hours and fourteen minutes including waits before linking was reported done. bcbuild.js knows what to tell a developer trying to publish files while the manager is busy. “Your Laptop is destoryed”.

      All that compiling gives you a directory full of binaries and somebody still has to turn it into CDs. postbuild.cmd reads a file called pbuild.dat. BEGIN starts a script that can run alongside the others and END waits for one to finish. To find the dependencies you read the comments. One says the catalog signer is waiting on the rule scripts, and the CD image maker waits on compression, which in turn waits on the catalog signer.

      tools/postbuildscripts/pbuild.dat, lines 64 to 77

      BEGIN %RazzleToolPath%\PostBuildScripts\symbolcd.cmd
      
      ; start 'bldrule' scripts first because catsign is waiting on them
      ; and cdimage is waiting on startcompress postcomp, which happens
      ; after catsign
      
      ; The 'bldrule' scripts themselves are ordered by the time
      ; of execution (my best guess)
      
      BEGIN %RazzleToolPath%\PostBuildScripts\admigration.cmd
      BEGIN %RazzleToolPath%\PostBuildScripts\adminpak.cmd
      BEGIN %RazzleToolPath%\PostBuildScripts\inetsrv.cmd -o CABGEN
      BEGIN %RazzleToolPath%\PostBuildScripts\deploytools.cmd
      BEGIN %RazzleToolPath%\PostBuildScripts\wmmkdcache.cmd

      There are 64 scripts in the postbuild. They compress most of the files with LZX (hence all the .dl_ and .sy_ names on the XP CD), compile catalogs of the files' hashes and sign them with a Microsoft test root the testers had to install. The real signature was a separate request. Other scripts index the symbols, put file sizes in the layout that Setup reads for its disk estimates, and assemble seven CD images from the same binaries, Home Edition through Datacenter Server. Hard links let them afford seven copies. A beta got its expiry date here, and a Microsoft Research tool obfuscated the activation files on x86. A failed script might leave its window open with “Possible error, sleeping 30 minutes” for whoever was in the lab. At the end postbuild decided it had failed if it could find the string “error:” in one log. Even writing the finish time to disk has a comment. A timestamp ending in 1 or 2 could accidentally turn its last digit into part of a redirection. They made the output descriptor explicit so they'd keep the whole time.

      tools/postbuild.cmd, lines 406 to 410

      REM note we have to use the funny syntax for the redirect here because
      REM the date time stamp ends in a number -- if that number is one or two,
      REM we'd accidentally redirect the wrong way and lose a digit from our string.
      REM
      echo %SDTimeStamp% 1>%MyCopyDir%\BuildFinishTime.txt 2>nul

      The people doing the international builds started with the US binaries with the same build number and added translated resources. Only the parts that needed compiling for a particular language got rebuilt. The postbuild readme asks you to take any new step, “multiply its execution time with 21 (7 Redmond-based languages and 14 Dublin-based languages) and assess whether its execution time is still acceptable”. By XP they were doing 25 languages. On top of that there was a pseudo-localised build to exercise the translation process without doing a translation, and a mirrored one, presumably to try right-to-left layout.

      How they knew a build worked

      Releasing the build was reserved for official machines. localrel.cmd looked for 10 GB of free space, moved the tree into a release directory named for the build and made latest point at it. release.cmd distributed it to the release servers with remote.exe. “Remote.exe always return 6, ignore the return value”. In the main lab there was also a boot-test machine for each product. autoboottest.pl reformatted its test partition and installed the new Windows unattended. A private option in winnt32 put text and GUI setup under the kernel debugger and setup's program under ntsd, so a crash in the middle of installing Windows could be examined there. autoboottest.pl also left a script in the new system's Startup folder. Whether that script ever ran was itself a test.

      tools/postbuildscripts/autoboottest.pl, lines 457 to 465

      REM Don't create a "booted" remote any longer! It's a security hole!
      REM call :LogMe "Create a remote for raiseall.pl"
      REM start \%BootTestDrive\%\\tools\\remote /S \"cmd.exe\" Booted
      
      REM  If no wait, start raiseall with quality bvt
      if not defined Wait (
         REM BUGBUG Wait 27 minutes before we try to raise the build to give release time to complete.
         sleep 1620
         call :LogMe "Raiseall to BVT on all release servers"

      You needed a logged-on desktop to get as far as Startup. From there the script allowed 27 minutes for the release to finish copying before asking the servers to raise the build to bvt. The celebrated build qualities are a small file in the logs and a latest link for each quality. You can read their order in the Perl script, beginning with pre, then bvt, tst, sav, idw, ids and finally idc.

      tools/postbuildscripts/raiseall.pl, lines 28 to 34

      my %Ordered_Qualities = ( pre => 1,
                                bvt => 2,
                                tst => 3,
                                sav => 4,
                                idw => 5,
                                ids => 6,
                                idc => 7 );

      The automatic steps stop at bvt. The only mention of setting tst in tools is in a usage example. A person had to take it farther. The scripts don't expand those abbreviations. Elsewhere BVT is build verification test. IDW, according to Chen, means Internal Developer Workstation, “builds stable enough to be self-hosted by the development team”. For the rest I'd be guessing. Microsoft's August 2001 PressPass account says a daily build went “to the 'Build Verification and Test' Lab for review and identification of new bugs caused by the changes”. That lab had people in it. An SP1 script mails it “Build is ready for BVT”, and assignbvt.pl, which could have set tests running by itself, is disabled in every branch's settings. You get another view of the BVT in the source of the products it tested. Passport has an assert commented out with “BVT Break!!!”. IE's window tracing is marked “DISABLED BY DEFAULT (1) for perf reasons (2) to pass BVT on initial checkin”.

      How much of this was still running? For the CRC check on builds going to Microsoft Japan we have the answer in writing. It “was turned off accidentally for over a month and nobody noticed, so going to comment it out for now”. There's also missingfilecheck.cmd. It refers to four scripts that are missing from the tree, and in the tree nothing calls it.

      You could fail a test well before your change got near a lab. Under inetsrv/iis/svcs/cmp/checkin the IIS team's ASP smoke tests print the filename followed by FAIL. Their instructions say “You will need to correct your problem before checking in”. An IIS that wouldn't shut down afterwards failed too. There are developer regression tests, or DRTs, in the shell, COM, WMI, ADSI and network redirector. For IE's HTML engine Trident you went to the Gauntlet, itself an HTML application at inetcore/mshtml/tools/whistgaunt.hta. Its wizard took your change, queued it on a server and had it built, tested and checked in on your behalf. Options commented out since suggest it once could have merged several people's changes too. Before getting past the mail page you had to give it four quite human pieces of information: who tested it, who reviewed the code, a summary, and the binaries affected.

      inetcore/mshtml/tools/whistgaunt.hta, lines 623 to 628

      case 2:
          fRet = fRet || VerifyValue(mail_tester, 'value', '', 'Tested By');
          fRet = fRet || VerifyValue(mail_codereview, 'value', '', 'Code Reviewer');
          fRet = fRet || VerifyValue(mail_summary, 'value', '', 'Summary');
          fRet = fRet || VerifyValue(mail_binaries, 'value', '', 'Binaries Affected');
          break;

      In other words, a developer was asking a web page for permission to check in. One option in the Gauntlet still said “Do a full ssync and clean build”. Ssync is what a sync was called back in SLM.

      On x86 razzle.cmd also put PREfast in everybody's path and updated it when a later version had been synced. This is the checker Microsoft later shipped with its compilers as /analyze. The other name that comes up is PREfix, the Microsoft Research simulator that looked at a whole program. Its public header supplies macros to tell it when a path is impossible. About 200 lines of comments are concerned with satisfying one checker or the other. ZDNet reported on a Lucovsky memo in February 2000. It said Windows 2000 was going out with “over 63,000 potential known defects” and more than 65,000 potential issues reported by PREfix, and that new code for Whistler, as XP was then called, wouldn't be checked in until they were fixed.

      Near the end you can put the machine's version of events beside the testers' version. Microsoft's PressPass piece says they were down to three bugs by 17 August 2001 and “the final build was finished at 3 a.m. Saturday morning”. Four CD burners turned out 1,000 copies for the testers in 12-minute passes. The testers signed off 4,300 items individually on an internal website. One team leader had pledged to eat a real bug for every 250 the developers fixed in a day.

      Who wrote it, and when

      How much of this was the work of any particular person? One courtesy the NT team did the reader before anybody had thought of a leak was to put an Author field in each file, usually along with a date. You can read much of the kernel in the order in which it was made.

      base/ntos/ke/eventobj.c, lines 1 to 16

      /*++
      
      Copyright (c) 1989  Microsoft Corporation
      
      Module Name:
      
          eventobj.c
      
      Abstract:
      
          This module implements the kernel event objects. Functions are
          provided to initialize, pulse, read, reset, and set event objects.
      
      Author:
      
          David N. Cutler (davec) 27-Feb-1989
      

      Read the dates on Dave Cutler's dispatcher objects. Events on 27 February 1989, semaphores the day after, timers on 2 March. On the 4th he did threads, the 5th APCs, the 6th DPCs and the 7th processes. Gary Kimura, Mark Lucovsky, Lou Perazzoli and Steve Wood have files dated that year too. Eleven years later Cutler is doing the AMD64 kernel, starting with initkr.c on 22 April 2000 and on into 2001, on a processor still in simulation. One register has to be written before another “to work around a bug in the simulator”. Forrest Foltz, porting the HAL, gets as far as “The simulator takes about a day to go through this, so for right” and never finishes the thought. And in one place the date is whatever you make of “2-Feby-2000”.

      You might expect the first 64-bit Windows to be in the directory for the first 64-bit XP you could buy. Instead look beside alpha. The memory manager in axp64 has an entry by Landy Wang on 2 June 1998, “Modifications for full 3-level 64-bit NT.” Someone took the trouble to draw where the addresses went.

      base/ntos/mm/axp64/mialpha.h, lines 30 to 38

          Virtual Memory Layout on the AXP64 is:
      
                       +------------------------------------+
      0000000000000000 | User mode addresses - 4tb          |
                       |                                    |
      000003FFFFFEFFFF |                                    | MM_HIGHEST_USER_ADDRESS
                       +------------------------------------+
      000003FFFFFF0000 | 64k No Access Region               | MM_USER_PROBE_ADDRESS
                       +------------------------------------+

      That is virtual address space for a program, with another terabyte reserved elsewhere in the map for the system cache. The machine could have a great deal less physical RAM. Raymond Chen recalls that the initial work on 64-bit Windows, code name Sundown, ran on Alpha because those processors already existed while Intel's Itanium was still a simulator. You can see the distinction in Microsoft's April 1999 WinHEC demonstration, first Windows 2000 on a Merced emulator, then a physical four-processor Alpha with seven gigabytes of RAM. A December 2001 account confirms that the internal 64-bit Alpha builds were never released. The shipping XP 64-Bit Edition targeted Itanium. The folder preserves the real hardware platform on which the common Windows codebase first made that transition.

      Some teams, mostly the graphics people and the 16-bit kernel, used an editor macro that stamped the exact time into their history blocks, down to the second. There are 370 unique stamps in the tree's C, header and assembly files, and 361 of them have a weekday that matches the calendar, a fair check on the dates an editor supplied. Fifty-eight fall between midnight and five in the morning, and fifty-seven of those belong to two people, Charles Whitmer and David Weise. Weise, whom Larry Osterman called the person "most responsible for the success of Windows 3.0", wrote a signal handler for the 16-bit kernel at 00:36 on Christmas Day 1989, months before Windows 3.0 shipped, and at 01:03 on 6 February 1990 he left a history note over one of its memory routines.

      base/mvdm/wow16/kernel31/2gmem.asm, lines 811 to 816

      ; History:                                                              ;
      ;                                                                       ;
      ;  Tue 06-Feb-1990 01:03:54  -by-  David N. Weise  [davidw]             ;
      ; I got no clue what the history of this thing is, all I know is        ;
      ; that I got to fix it fast to prevent selector leak.                   ;
      ;-----------------------------------------------------------------------;

      “I got no clue what the history of this thing is, all I know is that I got to fix it fast to prevent selector leak.” The stamp on the fix itself is forty-three minutes later.

      Charles Whitmer (chuckwh) David Weise (davidw) Everyone else

      BEFORE 05:00

      Counts by hour
      HOURWHITMERWEISEOTHERSALL

      Every machine-stamped byline in the tree's C, header and assembly files, by the hour it was written. Hover or tap a mark for the date and the note. Only Charles Whitmer and David Weise are named and coloured; everyone else stays anonymous.

      The clock can show you a whole succession of people in one function. HmgLock is the lock on GDI handles. Patrick Haluptzok wrote it in 1991, Charles Whitmer rewrote it in assembly in August 1992 (“The common case falls straight through”), and Cutler added routines in September. A year later, in September 1993, Michael Abrash “Tuned ASM code”. It would be about a year and a half before he went to id Software to work on Quake. In June 1995 Andrew Goossen “Rewrote for Kernel Mode” as graphics was being moved into the kernel for NT 4.0. That's five names in four years.

      The credits nobody saw

      The people who wrote Windows wanted their names on the screen, and in this part of the tree there are at least five credit rolls, all of them hidden or switched off one way or another.

      Next to the Beziers screensaver sits a file called winbez.pts that the build doesn't use. Every byte in it is inverted, so a search for text finds nothing. Flip the bits back and you get 468 names, sorted by first name, from Aaron Contorer to Zvi Berkovich, with Bill Gates, David Cutler, Helen Custer, Michael Abrash, James 'J' Allard and Jim Allchin somewhere in between (and no Steve Ballmer). The Beziers saver that did ship still has a secret mode in its window setup. Set bit 14 of its Width setting and it draws a spinning, pulsing ball of 1,500 dots instead of curves. The code around the ball still has the scaffolding for turning the dots into letters, a font, an off-screen bitmap for text, a text target for every dot and a picker over a list of strings. The list is empty, and the step that draws a string and sends the dots to it is gone.

      shell/osshell/control/scrnsave/bezier/ssbezier.c, lines 221 to 232

      if (gczScreen & (1 << 14)) {
          Init(hWnd);
      } else {
          ghbrushBack = GetStockObject(BLACK_BRUSH);
          ghpenBez    = CreatePen(PS_SOLID, 0, 0xff);
          ghpenErase  = CreatePen(PS_SOLID, 0, 0);
          SelectObject(ghdc,ghpenBez);
          SelectObject(ghdc,ghbrushBack);
      
          vInitPalette(ghdc);
          wTimer = SetTimer (hWnd, 1, 1, NULL);
      }

      The OpenGL 3D Text screensaver checked what you typed against a keyword table inverted the same way. "volcano" showed seventeen volcanoes of the Cascades, "i love nt" answered "good?", and "not evil" showed 813 names, which at nine or ten seconds a name could take over two hours. Video for Windows had a roll you opened by clicking A-V-I in Morse code on a playing video. The NT CD Player had one you reached, in mini mode with no disc in, by right-clicking its display with Ctrl and Shift held and then right-clicking again, "dedicated to Penelope Broomer". The ActiveMovie team built theirs as a DirectShow source filter that plays the credits as video.

      None of those credit rolls can be reached in XP. The keyword table is compiled out, the OpenGL savers are out of the build and their Direct3D rewrites have no keywords. The Morse knock is compiled out too, and XP ships a different CD Player. The rewrites lost a joke as well. The OpenGL 3D Pipes, set to mixed joints, drew a Utah teapot instead of a joint about once in a thousand. BLUE_MOON was 153, the random number that got you the teapot.

      multimedia/opengl/scrsave/pipes/nstate.cxx, lines 193 to 206

      #define BLUE_MOON 153
      
      int
      NORMAL_STATE::ChooseJointType( )
      {
          switch( jointStyle ) {
              case ELBOWS:
                  return ELBOW_JOINT;
              case BALLS:
                  return BALL_JOINT;
              case EITHER:
                  // draw a teapot once in a blue moon
                  if( ss_iRand(1000) == BLUE_MOON )
                      return( TEAPOT );

      The code that draws it is commented "Horrors! It's the teapot!", and XP's 3D Pipes doesn't have it.

      Microsoft later banned easter eggs from Windows outright, and Larry Osterman explained why in terms of Trustworthy Computing. You should be able to trust that there is nothing on your computer nobody planned, and hidden code can introduce security bugs. Fair enough. It's still a bit sad, because these rolls are the only lists I know of with all those names in one place, and you need a leak to read them.

      So I'll end with a short one that needs no decoding. Jim Horne, Wes Cherry, Robert Donner and Curt Johnson, David Norris and Hans Spiller, Chris Peters, Peter Alschitz, Mark Lucovsky, Lou Perazzoli, Robert Rounthwaite and the Microsoft Research spam team, David Weise, Charles Whitmer. And the people whose names turn up wherever Windows learned to read right to left. Samer Arafeh (the complex-script language pack in 1996, the kashida inserter in 1998, the Hijri adjustment in 1999), Mohamed Abdel-Hamid (the mirroring code, with his name spelled four different ways across the files, which anyone with an Arabic name will recognise), and Mohamed Sadek (GDI+'s bidirectional algorithm in 2000, and fifty-four comments signed with his Microsoft alias across the tree, two dozen of them in the shell, one of them over a table that nobody was to change without asking him first). And the testers in the compatibility database, whose names I left out on purpose, since none of them signed up to be in a blog post.

      Notes and further reading

      The copy I read is only part of the leak. By size, most of the 43 GB torrent was an archive of Microsoft patents, and most of the rest was older leaks (MS-DOS, NT 3.5 and 4, Windows 2000, Windows CE, the original Xbox, the Windows 10 Shared Source Kit and more) and some videos. The new part was one 2.9 GB archive holding two trees, XP SP1 and Windows Server 2003. I only read the XP one, and it isn't complete. Neither tree has Winlogon's source, so the XP that a developer compiled from it wouldn't install as it stood, while Server 2003, the more complete tree, did install once he put in a Winlogon from a retail copy. There's none of the activation code, as the licensing section says. There’s no Pinball or Spider Solitaire, although shell/osshell/games/dirs lists both. The compiler source is missing too, along with a handful of scripts that the build calls. One community guide to building the leak reckons the XP and Server 2003 source together are about 70% of the real thing.

      Every quote in the blog post was checked against the file it comes from. Its code blocks are copied straight out of the files with only tabs expanded and the common indentation taken off, and every count was made with rg over the tree. Where I say I couldn't find something, I mean I searched the tree and the web and came up empty, so it may still exist somewhere.

      #Programming #History #Microsoft