• The shift key overrides NumLock

Perhaps not as well-known today as it was in the days when the arrow keys and numeric keypad shared space is that the shift key overrides NumLock.

If NumLock is on (as it usually is), then pressing a key on the numeric keypad while holding the shift key overrides NumLock and instead generates the arrow key (or other navigation key) printed in small print under the big digits.

(The shift key also overrides CapsLock. If you turn on CapsLock then hold the shift key while typing a letter, that letter comes out in lowercase.)

Perhaps you might decide that this little shift key quirk is completely insignificant, at least until you try to do something like assign Shift+Numpad0 as a hotkey and wonder why it doesn't work. Now you know.

• More dictionaries you didn't realize you needed

Apparently there are a lot of strange dictionaries out there.

Otherwise-well-respected German dictionary publisher Langenscheidt announced that it is producing a German-Woman/Woman-German dictionary. (Psst, Toronto Star, it's "Also sprachen die Fräulein"... Third person plural, past tense of strong verb, ending is "en". You're welcome.)

We also have The Hippie Dictionary which translates such words and phrases like "stay loose", "hey man", and "like".

• Even in computing, simultaneity is relative

Einstein discovered that simultaneity is relative. This is also true of computing.

People will ask, "Is it okay to do X on one thread and Y on another thread simultaneously?" Here are some examples:

• X = "close a handle" and Y = "use that handle".
• X = "call UnregisterWaitForSingleObject on a handle", Y = "call UnregisterWaitForSingleObject on that same handle".

You can answer this question knowing nothing about the internal behavior of those operations. All you need to know are some physics and the answers to much simpler questions about what is valid sequential code.

Let's do a thought experiment with simultaneity.

Since simultaneity is relative, any code that does X and Y simultaneously can be observed to have performed X before Y or Y before X, depending on your frame of reference. That's how the universe works.

So if it were okay to do them simultaneously, then it must also be okay to do them one after the other, since they do occur one after the other if you walk past the computer in the correct direction.

Is it okay to use a handle after closing it? Is it okay to unregister a wait event twice?

The answer to both questions is "No," and therefore it isn't okay to do them simultaneously either.

If you don't like using physics to solve this problem, you can also do it from a purely technical perspective.

Invoking a function is not an atomic operation. You prepare the parameters, you call the entry point, the function does some work, it returns. Even if you somehow manage to get both threads to reach the function entry point simultaneously (even though as we know from physics there is no such thing as true simultaneity), there's always the possibility that one thread will get pre-empted immediately after the "call" instruction has transferred control to the first instruction of the target function, while the other thread continues to completion. After the second thread runs to completion, the pre-empted thread gets scheduled and begins execution of the function body.

Under this situation, you effectively called the two functions one after the other, despite all your efforts to call them simultaneously. Since you can't prevent this scenario from occurring, you have to code with the possibility that it might actually happen.

Hopefully this second explanation will satisfy the people who don't believe in the power of physics. Personally, I prefer using physics.

• Why does Windows keep your BIOS clock on local time?

Even though Windows NT uses UTC internally, the BIOS clock stays on local time. Why is that?

There are a few reasons. One is a chain of backwards compatibility.

In the early days, people often dual-booted between Windows NT and MS-DOS/Windows 3.1. MS-DOS and Windows 3.1 operate on local time, so Windows NT followed suit so that you wouldn't have to keep changing your clock each time you changed operating systems.

As people upgraded from Windows NT to Windows 2000 to Windows XP, this choice of time zone had to be preserved so that people could dual-boot between their previous operating system and the new operating system.

Another reason for keeping the BIOS clock on local time is to avoid confusing people who set their time via the BIOS itself. If you hit the magic key during the power-on self-test, the BIOS will go into its configuration mode, and one of the things you can configure here is the time. Imagine how confusing it would be if you set the time to 3pm, and then when you started Windows, the clock read 11am.

"Stupid computer. Why did it even ask me to change the time if it's going to screw it up and make me change it a second time?"

And if you explain to them, "No, you see, that time was UTC, not local time," the response is likely to be "What kind of totally propeller-headed nonsense is that? You're telling me that when the computer asks me what time it is, I have to tell it what time it is in London? (Except during the summer in the northern hemisphere, when I have to tell it what time it is in Reykjavik!?) Why do I have to remember my time zone and manually subtract four hours? Or is it five during the summer? Or maybe I have to add. Why do I even have to think about this? Stupid Microsoft. My watch says three o'clock. I type three o'clock. End of story."

(What's more, some BIOSes have alarm clocks built in, where you can program them to have the computer turn itself on at a particular time. Do you want to have to convert all those times to UTC each time you want to set a wake-up call?)

• How to find the Internet Explorer binary

For some reason, some people go to enormous lengths to locate the Internet Explorer binary so they can launch it with some options.

The way to do this is not to do it.

If you just pass "IEXPLORE.EXE" to the ShellExecute function [link fixed 9:41am], it will go find Internet Explorer and run it.

```ShellExecute(NULL, "open", "iexplore.exe",
"http://www.microsoft.com", NULL,
SW_SHOWNORMAL);
```

The ShellExecute function gets its hands dirty so you don't have to.

(Note: If you just want to launch the URL generically, you should use

```ShellExecute(NULL, "open", "http://www.microsoft.com",
NULL, NULL, SW_SHOWNORMAL);
```

so that the web page opens in the user's preferred web browser. Forcing Internet Explorer should be avoided under normal circumstances; we are forcing it here because the action is presumably being taken response to an explicit request to open the web page specifically in Internet Explorer.)

If you want to get your hands dirty, you can of course do it yourself. It involves reading the specification from the other side, this time the specification on how to register your program's name and path ("Registering Application Path Information").

The document describes how a program should enter its properties into the registry so that the shell can launch it. To read it backwards, then, interpret this as a list of properties you (the launcher) need to read from the registry.

In this case, the way to run Internet Explorer (or any other program) the same way ShellExecute does is to look in HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\IEXPLORE.EXE (substituting the name of the program if it's not Internet Explorer you're after). The default value is the full path to the program and the the "Path" value specifies a custom path that you should prepend to the environment before launching the target program.

When you do this, don't forget to call the `ExpandEnvironmentStrings` function if the registry value's type is `REG_EXPAND_SZ`. (Lots of people forget about `REG_EXPAND_SZ`.)

Of course, my opinion is that it's much easier just to let ShellExecute do the work for you.

• Reading a contract from the other side: Application publishers

In an earlier article, I gave an example of reading a contract from the other side. Here's another example of how you can read a specification and play the role of the operating system.

I chose this particular example because somebody wanted to do this and didn't realize that everything they needed was already documented; they just needed to look at the documentation in a different light.

The goal today is to mimic the list of programs that appears on the "Add New Programs" page of the Add or Remove Programs control panel. Note that in order for this list to appear at all, you need to be on a domain, and for the list to be nonempty, your domain controller needs to publish applications for domain members to install. Consequently, I suspect many of my readers won't get to see any interesting results from this exercise, but then again, the point of exercise is not the result but merely the doing of it.

The documentation for the IAppPublisher interface describes how a publisher can register itself to appear in the list of programs that can be installed. All you have to do is read the documentation from the other side: Instead of reading documentation about a method and asking, "How would I implement this method?", read it and ask, "How would I call this method?"

The documentation says that an app publisher registers its CLSID under the specified registry key. Therefore, if you want to find all the app publishers, you need to enumerate that key.

```#define REGSTR_PATH_PUBLISHERS  \
L"Software\\Microsoft"      \
L"\\Windows\\CurrentVersion\\App Management\\Publishers"

HKEY hkPub;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, REGSTR_PATH_PUBLISHERS,
0, KEY_READ, &hkPub) == ERROR_SUCCESS) {
WCHAR szKey[MAX_PATH];
for (DWORD dwIndex = 0;
RegEnumKeyW(hkPub, dwIndex, szKey, MAX_PATH) == ERROR_SUCCESS;
dwIndex++) {
...
}
RegCloseKey(hkPub);
}
```

The documentation says that the subkeys have the CLSID in REG_SZ format, so that's what we read out.

```        WCHAR szCLSID[MAX_PATH];
LONG l = sizeof(szCLSID) - sizeof(WCHAR);
if (RegQueryValueW(hkPub, szKey, szCLSID, &l) == ERROR_SUCCESS)
szCLSID[l/sizeof(WCHAR)] = 0;
CLSID clsid;
if (SUCCEEDED(CLSIDFromString(szCLSID, &clsid))) {
...
}
}
```

Notice the extra care we take to avoid the problem of registry strings that aren't null-terminated, as discussed in an earlier entry.

The documentation quite explicitly states how this CLSID is used.

Add/Remove Programs creates an instance of your object by calling CoCreateInstance for your object and requests the approprite [sic] IAppPublisher interface when the Add New Programs view is populated.

Not much choice, now, is there. So we do what it says.

```            IAppPublisher *ppub;
if (SUCCEEDED(CoCreateInstance(clsid, NULL,
CLSCTX_ALL, IID_IAppPublisher,
(void**)&ppub))) {
...
ppub->Release();
}
```

Okay, now that we have an app publisher, we can invoke the various methods on it to get information from that publisher. If we were more ambitious, we could ask for the categories but today we're just going to be happy with enumerating the programs so we can print their names.

```              IEnumPublishedApps *penum;
if (SUCCEEDED(ppub->EnumApps(NULL, &penum))) {
IPublishedApp *papp;
while (penum->Next(&papp) == S_OK) {
...
papp->Release();
}
penum->Release();
}
```

The enumerator gives us an application interface, and we can use that interface to get information about the application and print it out.

```                  APPINFODATA info = { sizeof(info) };
if (SUCCEEDED(papp->GetAppInfo(&info)) &&
wprintf(L"%ls\n", info.pszDisplayName);
}
```

We ask only for the display name, since that's all we're interested in today. In a more complicated program, we may ask for other data and would probably not release the IPublishedApp interface immediately, but rather hang onto it so we could invoke some other more interesting method like IPublishedApp::Install.

(Note that we have to use the correct memory allocator to free the memory.)

Okay, let's assemble all this into a simple console program.

```#include <windows.h>
#include <ole2.h>
#include <shappmgr.h>
#include <stdio.h>

#define REGSTR_PATH_PUBLISHERS  \
L"Software\\Microsoft"      \
L"\\Windows\\CurrentVersion\\App Management\\Publishers"

int __cdecl main(int argc, char **argv)
{
if (SUCCEEDED(CoInitialize(NULL)) {
HKEY hkPub;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, REGSTR_PATH_PUBLISHERS,
0, KEY_READ, &hkPub) == ERROR_SUCCESS) {
WCHAR szKey[MAX_PATH];
for (DWORD dwIndex = 0;
RegEnumKeyW(hkPub, dwIndex, szKey, MAX_PATH) == ERROR_SUCCESS;
dwIndex++) {
WCHAR szCLSID[MAX_PATH];
LONG l = sizeof(szCLSID) - sizeof(WCHAR);
if (RegQueryValueW(hkPub, szKey, szCLSID, &l) == ERROR_SUCCESS)
szCLSID[l/sizeof(WCHAR)] = 0;
CLSID clsid;
if (SUCCEEDED(CLSIDFromString(szCLSID, &clsid))) {
IAppPublisher *ppub;
if (SUCCEEDED(CoCreateInstance(clsid, NULL,
CLSCTX_ALL, IID_IAppPublisher,
(void**)&ppub))) {
IEnumPublishedApps *penum;
if (SUCCEEDED(ppub->EnumApps(NULL, &penum))) {
IPublishedApp *papp;
while (penum->Next(&papp) == S_OK) {
APPINFODATA info = { sizeof(info) };
if (SUCCEEDED(papp->GetAppInfo(&info)) &&
wprintf(L"%ls\n", info.pszDisplayName);
}
papp->Release();
}
penum->Release();
}
ppub->Release();
}
}
}
}
RegCloseKey(hkPub);
}
CoUninitialize();
}
return 0;
}
```

When you run this program, a list of all programs published by your domain controller should go scrolling past. (As I noted at the beginning of this entry, you won't see much if your computer is not on a domain or if your domain controller doesn't publish any programs.)

Yes, this program is not very pretty, because prettiness was not my goal. In real life, a lot of the mess would be moved out into helper functions, and you can clean it up even more by using a smart pointer library, but the goal here was not to write a pretty program; it was to show how something could be done by reading the specification from the other side.

(Why don't I use a smart pointer library? Because I try to write in "raw" C++ in order to avoid arguments about whose smart pointer library is best, or why smart pointers are evil... It's easy to convert "raw" C++ to use a smart pointer library, but it's harder to convert from one smart pointer library to another.)

• Importance of alignment even on x86 machines, part 2

The various Interlocked functions (InterlockedIncrement, and so on) require that the variable being updated be properly aligned, even on x86, a platform where the CPU silently fixes unaligned memory access invisibly.

If you pass an unaligned pointer to one of the Interlocked functions, the operation will still succeed, but the result won't be atomic. Another processor may see a partially-completed update.

This is a particularly insidious bug since it happens only on multiprocessor machines under very tight timing conditions. You will be hard-pressed to reproduce this in the laboratory.

(A commenter stole my thunder and remarked on it yesterday.)

Moral of the story: Same as yesterday. Mind your alignment.

• The sociology of the mobile phone

It has become obvious by now that the mobile phone has changed the way people interact. These two papers were forwaded to me by a colleague, whose summary I am shamelessly lifting from heavily.

First is a short paper titled Exploring the implications for social identity of the new sociology of the mobile phone.

The much more fascinating (and much longer) one is The Effects of Mobile Telephones on Social and Individual Life [PDF]. Read about Flight, Suspension and Persistence—the three ways people deal with incoming calls. Learn how to tell an Innie from an Outie. Set up an Approximeeting. Are you a swift, an owl, a dove, a sparrow, a starling, or a peacock? Pick up some UK mobile phone lingo:

• "Gooseberry call": calling someone during their date to get a progress report.
• "Shagbile": the mobile phone your partner doesn't know about, used for affairs.
• "Sad": derogatory term for people who show off their phones. Enormous ritualization surrounds this.

"Shagbile" is the best. So Austin Powers.

• Importance of alignment even on x86 machines

Sometimes unaligned memory access will hang the machine.

Some video cards do not let you access all the video memory at one go. Instead, you are given a window into which you can select which subset of video memory ("bank") you want to see. For example, the EGA video card had 256K of memory, split into four 64K banks. If you wanted to access memory in the first 64K, you had to select bank zero into the window, but if you wanted to access memory in the second 64K, then you had to select bank one.

Bank-switching makes memory access much more complicated, For example, if you want to copy a block of memory into bank-switched memory, you have to check when you are going to cross a bank boundary and break the copy up into pieces. If you are doing something that requires non-sequential access (say, drawing a diagonal line), you have to check when your line is going to cross into another bank.

To simplify matters, Windows 95 had a driver called VFLATD that made bank-switched memory look flat to the rest of the system. Flattening the bank-switched memory model was also crucial for DirectDraw support; in particular, the IDirectDrawSurface::Lock method gave you direct access to a (seemingly) flat expanse of video memory. For example, if the application wanted to see a 256K surface and accessed memory in the first 64K of memory, the VFLATD driver would select bank zero and map the 64K physical memory window into the first 64K of the virtual 256K memory window.

This worked great as long as everybody uses only aligned memory accesses. But if you access unaligned memory, you can send VFLATD into an infinite loop and hang the machine.

Suppose you make an unaligned memory access that straddles two banks. This memory access can never be satisfied. A page fault is taken on the lower portion of the unaligned access, and VFLATD maps the lower bank into memory. Then a page fault is taken on the higher portion of the unaligned access, and VFLATD now has to map the upper bank; this unmaps the lower bank, since the video card is bank-switched and only one bank can be mapped ata time. Now a page fault is taken on the lower portion, and the infinite loop continues.

Moral of the story: Keep those memory accesses aligned, even on the x86, which most people would consider to be one where it is "safe" to violate alignment rules.

• Why do some structures end with an array of size 1?

Some Windows structures are variable-sized, beginning with a fixed header, followed by a variable-sized array. When these structures are declared, they often declare an array of size 1 where the variable-sized array should be. For example:

```typedef struct _TOKEN_GROUPS {
DWORD GroupCount;
SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY];
} TOKEN_GROUPS, *PTOKEN_GROUPS;
```

If you look in the header files, you'll see that ANYSIZE_ARRAY is #define'd to 1, so this declares a structure with a trailing array of size one.

With this declaration, you would allocate memory for one such variable-sized TOKEN_GROUPS structure like this:

```PTOKEN_GROUPS TokenGroups =
malloc(FIELD_OFFSET(TOKEN_GROUPS, Groups[NumberOfGroups]));
```
and you would initialize the structure like this:
```TokenGroups->GroupCount = NumberOfGroups;
for (DWORD Index = 0; Index = NumberOfGroups; Index++) {
TokenGroups->Groups[Index] = ...;
}
```

Many people think it should have been declared like this:

```typedef struct _TOKEN_GROUPS {
DWORD GroupCount;
} TOKEN_GROUPS, *PTOKEN_GROUPS;
```

(In this article, code that is wrong or hypothetical will be italicized.)

The code that does the allocation would then go like this:

```PTOKEN_GROUPS TokenGroups =
malloc(sizeof(TOKEN_GROUPS) +
NumberOfGroups * sizeof(SID_AND_ATTRIBUTES));
```

This alternative has two disadvantages, one cosmetic and one fatal.

First, the cosmetic disadvantage: It makes it harder to access the variable-sized data. Initializing the TOKEN_GROUPS just allocated would go like this:

```TokenGroups->GroupCount = NumberOfGroups;
for (DWORD Index = 0; Index = NumberOfGroups; Index++) {
((SID_AND_ATTRIBUTES *)(TokenGroups + 1))[Index] = ...;
}
```

The real disadvantage is fatal. The above code crashes on 64-bit Windows. The SID_AND_ATTRIBUTES structure looks like this:

```typedef struct _SID_AND_ATTRIBUTES {
PSID Sid;
DWORD Attributes;
} SID_AND_ATTRIBUTES, * PSID_AND_ATTRIBUTES;
```

Observe that the first member of this structure is a pointer, PSID. The SID_AND_ATTRIBUTES structure requires pointer alignment, which on 64-bit Windows is 8-byte alignment. On the other hand, the proposed TOKEN_GROUPS structure consists of just a DWORD and therefore requires only 4-byte alignment. sizeof(TOKEN_GROUPS) is four.

I hope you see where this is going.

Under the proposed structure definition, the array of SID_AND_ATTRIBUTES structures will not be placed on an 8-byte boundary but only on a 4-byte boundary. The necessary padding between the GroupCount and the first SID_AND_ATTRIBUTES is missing. The attempt to access the elements of the array will crash with a STATUS_DATATYPE_MISALIGNMENT exception.

Okay, you may say, then why not use a zero-length array instead of a 1-length array?

Because time travel has yet to be perfected.

Zero-length arrays did not become legal Standard C until 1999. Since Windows was around long before then, it could not take advantage of that functionality in the C language.

Page 356 of 406 (4,059 items) «354355356357358»