• The Old New Thing

    No, we're not going to play Stairway to Heaven, and please tell everbody else in your area code to stop calling me

    • 26 Comments

    Some time ago, I told the story of how one employee's phone received calls intended for a local radio station's contest line due to people dialing seven digits instead of ten and defaulting to the wrong area code.

    Upon reading that story, a colleague of mine pointed out that one of the conference rooms in his building has a similar problem. The direct line for the conference room is identical to the request line for a local radio station, save for the area code. People who work in the building know never to answer the phone in that conference room.

    (Although apparently there have been a couple of pranks involving the call-forwarding function on the conference room telephone.)

  • The Old New Thing

    How is it possible to run Wordpad by just typing its name even though it isn't on the PATH?

    • 29 Comments

    In a comment completely unrelated to the topic, Chris Capel asks how Wordpad manages to run when you type its name into the Run dialog even though the command prompt can't find it? In other words, the Run dialog manages to find Wordpad even though it's not on the PATH.

    Chris was unable to find anywhere I discussed this issue earlier, but it's there, just with Internet Explorer as the application instead of Wordpad.

    It's through the magic of App Paths.

    App Paths was introduced in Windows 95 to address the path pollution problem. Prior to the introduction of App Paths, typing the name of a program without a fully-qualified path resulted in a search along the path, and if it wasn't found, then that was the end of that. File not found. As a result, it became common practice for programs, as part of their installation, to edit the user's AUTOEXEC.BAT and add the application's installation directory to the path.

    This had a few problems.

    First of all, editing AUTOEXEC.BAT is decidedlly nontrivial since batch files can have control flow logic like IF and CALL and GOTO. Finding the right SET PATH=... or PATH ... command is an exercise in code coverage analysis, especially since MS-DOS 6 added multi-config support to CONFIG.SYS, so the value of the CONFIG environment variable is determined at runtime. If you wanted to avoid hanging your setup program, you would have to solve the Halting Problem. (You can't just stick at PATH ... at the beginning because it might get wiped out by a later PATH command, and you can't just stick it at the end, because control might never reach last line of the batch file.)

    And of course, very few uninstall programs would take the time to undo the edits the installer performed, and even if they tried, there's no guarantee that the undo would be successful, since the user (or another installer!) may have edited the AUTOEXEC.BAT file in the meantime.

    Even if you postulate the existence of the AUTOEXEC.BAT editing fairy who magically edits your AUTOEXEC.BAT for you, you still run into the PATH length limit. The maximum length of a command line was 128 characters in MS-DOS, and if each program added itself to the PATH, it wouldn't be long before the PATH reached its maximum length.

    Pre-emptive Yuhong Bao irrelevant detail that has no effect on the story: Windows 95 increased the maximum command line length, but the program being launched needed to know where to look for the "long command line". And that didn't help existing installers which were written against the old 128-character limit. Give them an AUTOEXEC.BAT with a line longer than 128 characters and you had a good chance that you'd hit a buffer overflow bug.

    On top of the difficulty of adding more directories to the PATH, there was the recognition that this was another case of using a global setting to solve a local problem. It seemed wasteful to add a directory to the path just so you could find one file. Each additional directory on the path slowed down path sarching operations, even the ones unrelated to locating that one program.

    Enter App Paths. The idea here is that instead of adding your application directory to the path, you just create an entry under the App Paths key saying, "If somebody is looking to execute contoso.exe, I put it over here." Instead of adding an entire directory to the path, you just add a single file, and it's used only for application execution purposes, so it doesn't slow down other path search operations like loading DLLs.

    (Note that the old documentation on App Paths has been superseded by the new documentation linked above.)

    Now that there was a place to store information associated with a particular application, you may as well use it for other stuff as well. A secondary source of path pollution came from applications which added not only the application directory to the path, but also a helper directory where the application kept its DLLs. To address this, an additional Path value specified which directories your application wanted to be added to the path before it was executed. Over time, additional attributes were added to the App Paths key, such as the UseUrl value we saw some time ago.

    When you type the name of a program into the Run dialog (with no path), the Shell­Execute function checks if the name corresponds to an application registered under App Paths. If so, then it uses the registration information to launch the application. Hooray, applications can be run by just typing their name without requiring them to modify the global path.

    Note that this extra lookup is performed only by the Sh­ellExecute family of functions, so if you use Create­Process or Search­Path, you'll still get ERROR_FILE_NOT_FOUND.

    Now, the intent was that the registered full path to the application is the same as the registered short name, just with a full path in front. For example, wordpad.exe registers the full path of %ProgramFiles%\Windows NT\Accessories\WORDPAD.EXE. But there's no check that the two file names match. The Pbrush folks took advantage of this by registering an application path entry for pbrush.exe with a full path of %SystemRoot%\System32\mspaint.exe: That way, when somebody types pbrush into the Run dialog, they get redirected to mspaint.exe.

    Sneaky.

  • The Old New Thing

    How do I disable windowless control support in dialog boxes?

    • 12 Comments

    A customer wanted to know how to disable windowless control support in dialog boxes. "The customer has a CommandButton ActiveX control on his dialog box, and using Get­Dlg­Item to get the window handle of the command button succeeded with VC 6.0, but when compiled with VC 9.0, it does not create a window. I'm guessing that this is caused by Dialog­Box's support for windowless controls. Is it possible to disable support for windowless controls?"

    The question on its face is somewhat puzzling, because dialog boxes don't "support" or "not support" windowless controls. It's like asking, "I want rice that doesn't support meat. My customer is a vegetarian and cannot eat meat." Rice doesn't support meat, and it doesn't not-support meat. If you don't want meat, then don't add meat. And if you don't want windowless controls on your dialog box, then don't create windowless controls.

    I was also not sure what the customer meant by CommandButton, because Win32 command buttons are not ActiveX controls. The customer must be referring to something else also called Command­Button, in which case the customer should also consult the documentation for that something else to see if there's a way to control its windowed/windowless behavior.

    The customer liaison gave some more details: "My customer uses Get­Dlg­Item to get the handle of a specific window. This method worked in VC 6.0 since VC 6.0 doesn't support windowless controls. But VC 9.0 added support for windowless controls in dialog boxes, which breaks my customer's code. Is there a way to disable support for windowless controls in dialog boxes?"

    It took a few more questions, but eventually we figured out that the customer was not using raw Win32 dialog boxes (as Dialog­Box suggested in the original question) but rather MFC dialog boxes, and the CommandButton in question is a Microsoft Forms 2.0 CommandButton control.

    "The customer simply wants to continue using his code without modification. He is already using the Microsoft Forms 2.0 CommandButton control, and he is already using Get­Dlg­Item to obtain its handle, but that technique no longer works."

    The pieces started to fall into place, and somebody from the Visual Studio team provided an explanation: The version of MFC which comes with Visual Studio 2000 added support for hosting windowless ActiveX controls. By default, the MFC hosting code permits controls to be added as windowless controls if the control requests it. To force all controls to be windowed, you need to provide a custom class which derives from COle­Control­Site and overrides IOle­In­Place­Site­Windowless::Can­Windowless­Activate to return S_FALSE. Then override the dialog's CWnd::Create­Control­Site method to return an instance of this class instead of the default control site.

    I haven't actually tested this to see if it works, but the customer didn't come back, so either it worked, or they decided that we were jerks and didn't want to waste their time with us any more.

  • The Old New Thing

    Why is secur32.dll called secur32.dll and not secure32.dll?

    • 22 Comments

    Many years ago, in a discussion of why you shouldn't name your DLL "security.dll", I dug a bit into the history behind the DLL. Here are some other useless tidbits about that file.

    Originally, there were two DLLs called security.dll. One was the 32-bit version and one was the 16-bit version. They could coexist because the 32-bit version was in the system32 directory and the 16-bit version was in the system directory.

    And then Windows 95 showed up and screwed up everything.

    Windows 95 did not have separate system32 and system directories. All the system files, both 16-bit and 32-bit, were lumped together in a single system directory. When the Security Support Provider Interface was ported to Windows 95, this created a problem, for it would require two files in the same directory to have the same name. Since the 16-bit version had seniority (because your Windows 95 installation may have been an upgrade install over Windows 3.1, which would have been the 16-bit version), it was the 32-bit version that had to be renamed.

    Okay, so why secur32.dll? Well, security32.dll was too long, since it exceeded the classic 8.3 limit, and Windows NT supported being run on FAT volumes (which necessarily did not support long file names, since long file names on FAT didn't exist until Windows 95). Okay, but why secur32.dll instead of secure32.dll, which still fits inside the 8.3 constraints?

    Nobody knows for sure any more; the person who chose the name left Microsoft a long time ago. Perhaps because secur32.dll looked better than securi32.dll. Maybe he couldn't count.

  • The Old New Thing

    How do I find the original name of a hard link?

    • 35 Comments

    A customer asked, "Given a hardlink name, is it possible to get the original file name used to create it in the first place?"

    Recall that hard links create an alternate name for a file. Once that alternate name is created, there is no way to tell which is the original name and which is the new name. The new file does not have a "link back to the original"; they are both links to the underlying file content. This is an old topic, so I won't go into further detail. Though this question does illustrate that many people continue to misunderstand what hard links are.

    Anyway, once you figure out what the customer is actually asking, you can give a meaningful answer: "Given the path to a file, how can I get all the names by which the file can be accessed?" The answer is Find­First­File­NameW.

    Note that the names returned by the Find­First­File­NameW family of functions are relative to the volume mount point. To convert it to a full path, you need to append it to the mount point. Something like this:

    typedef void (*ENUMERATEDNAMEPROC)(__in PCWSTR);
    
    void ProcessOneName(
        __in PCWSTR pszVolumeRoot,
        __in PCWSTR pszLink,
        __in ENUMERATEDNAMEPROC pfnCallback)
    {
      wchar_t szFile[MAX_PATH];
      if (SUCCEEDED(StringCchCopy(szFile, ARRAYSIZE(szFile), pszVolumeRoot)) &&
          PathAppend(szFile, pszLink)) {
       pfnCallback(szFile);
      }
    }
    
    void EnumerateAllNames(
        __in PCWSTR pszFileName,
        __in ENUMERATEDNAMEPROC pfnCallback)
    {
     // Supporting paths longer than MAX_PATH left as an exercise
     wchar_t szVolumeRoot[MAX_PATH];
     if (GetVolumePathName(pszFileName, szVolumeRoot, ARRAYSIZE(szVolumeRoot))) {
      wchar_t szLink[MAX_PATH];
      DWORD cchLink = ARRAYSIZE(szLink);
      HANDLE hFind = FindFirstFileNameW(pszFileName, 0, &cchLink, szLink);
      if (hFind != INVALID_HANDLE_VALUE) {
       ProcessOneName(szVolumeRoot, szLink, pfnCallback);
       while (cchLink = ARRAYSIZE(szLink),
              FindNextFileNameW(hFind, &cchLink, szLink)) {
        ProcessOneName(szVolumeRoot, szLink, pfnCallback);
       }
       FindClose(hFind);
      }
     }
    }
    
    // for demonstration purposes, we just print the name
    void PrintEachFoundName(__in PCWSTR pszFile)
    {
     _putws(pszFile);
    }
    
    int __cdecl wmain(int argc, wchar_t **argv)
    {
     for (int i = 1; i < argc; i++) {
      EnumerateAllNames(argv[i], PrintEachFoundName);
     }
     return 0;
    }
    

    Update: Minor errors corrected, as noted by acq and Adrian.

  • The Old New Thing

    Some mailing lists come with a negative service level agreement, but that's okay, because everybody is in on the joke

    • 14 Comments

    As I noted some time ago, there's a mailing list devoted to chatting among people who work in a particular cluster of buildings. It's not a technical support mailing list, but people will often ask a technical question on the off chance that somebody can help, in the same way that you might ask your friends for some help with something.

    Of course, one consequence of this is that the quality of the responses is highly variable. While there's a good chance that somebody will help you with your problem, there's also a good chance that a technical question will receive a highly unhelpful response just for fun, in the same way your friend might respond to a question with a funny but unhelpful answer. (And there's also a good chance that a technical question will get both types of replies.) You don't complain about this because, well, that's what you sort of expect when you use this mailing list.

    An illustration of this principle comes from the following thread:

    When I do ABC, I get XYZ. How do I get DEF?

    A short while later, the same person replied to his own question.

    Nevermind. I found the right mailing list to ask this question.

    That didn't stop somebody from responding:

    This mailing list is the correct place to send all questions. You have to use a different mailing list to get answers, though.
  • The Old New Thing

    The danger of making the chk build stricter is that nobody will run it

    • 31 Comments

    Our old pal Norman Diamond suggested that Windows should go beyond merely detecting dubious behavior on debug builds and should kill the application when it misbehaves.

    The thing is, if you make an operating system so strict that the slightest misstep results in lightning bolts from the sky, then nobody would run it.

    Back in the days of 16-bit Windows, as today, there were two builds, the so-called retail build, which had assertions disabled, and the so-called debug build, which had assertions enabled and broke into the debugger if an application did something suspicious. (This is similar to today's terms checked and free.)

    Now, the Windows development team is big on self-hosting. After all, if you are writing the operating system, you should be running it, too. What's more, it was common to self-host the debug version of the operating system, since that's the one with the extra checks and assertions that help you flush out the bugs.

    As it happens, the defect tracking system we used back in the day triggered a lot of these assertions. As I recall, refreshing a query resulted in about 50 parameter validation errors caught and reported by Windows. This made using the defect tracking system very cumbersome because you had to babysit the debugger and hit "i" (for ignore) 50 times each time you refreshed a query.

    (As I noted in my talk at Reflections|Projections 2009, the great thing about defect tracking systems is that you will hate every single one you use. Sure, the new defect tracking system may have some new features and be easier to use and run faster, but all that does is delay the point at which you begin hating it.)

    If Windows had taken the stance that the slightest error resulted in the death of the application, then it would have been impossible for a member of the Windows development team to run the defect tracking system program itself, because once it hit the first of those 50 parameter validation error reports, the program would have been killed, and the defect tracking system would have been rendered useless.

    Remember, don't change program semantics in the debug build. That just creates Heisenbugs.

    I remember that at one point the Windows team asked the people who supported the defect tracking system, "Hey, your program has a lot of problems that are being reported by the Windows debug build. Can you take a look at it?"

    The response from the defect tracking system support team was somewhat ironic: "Sorry, we don't support running the defect tracking system on a debug build of Windows. We found that the debug version of Windows breaks into the debugger too much."

  • The Old New Thing

    Using the wrong HINSTANCE in RegisterClass is like identity theft

    • 19 Comments

    Last year, I left you with a teaser for a problem that resulted in the CResource­Exception being thrown.

    Studying the function that threw the exception revealed that it was thrown due to a failed call to Register­Class. And studying the parameters that were passed to Register­Class revealed that HINSTANCE parameter did not match the DLL. Instead of being the instance handle of the DLL, it was the instance handle of the host application.

    Okay, now let's apply what we learned a few years ago about the significance of the HINSTANCE parameter passed to the Register­Class function. By passing the HINSTANCE of the host application, the class was registered against the namespace of the host rather than the namespace of the DLL. It's like signing up for a credit card using somebody else's name or checking a book out of the library with somebody else's library card.

    In this case, the module in question was a plug-in. It tried to register a class called, say, My­Class, and instead of registering against itself, it registered against the host application. Fortunately, the host application didn't have a class called My­Class, so the incorrect registration didn't cause a conflict. The book got checked out to the wrong person, but as far as the library can tell, nothing has gone wrong. It merely looks like the host application checked out a book.

    So why did the call to Register­Class fail? Because some other plug-in made the same mistake. Plug-in B also registered its class against the host application, and by an amazing coincidence, its class was also called My­Class. (If you look at how MFC auto-generates class names, you can see that this name collision can happen quite easily.) If both plug-ins had registered their classes properly, there would have been no problem, because each class would have been registered against their respective DLLs, and no conflict would have arisen. But instead, two wrongs make a wronger, and since both plug-ins incorrectly registered their classes against the host, the first plug-in to register succeeds, and the second one crashes.

    (One might argue that this is another special case of What if two programs did this?)

    Both plug-ins tried to sign up for a credit card in the name of the host application. The first one got the card, and the second one was informed by the credit card company, "Your application was denied because you already have a card from us."

    Why did these plug-ins register against the host application instead of against their own library cards? I don't know for sure, but my guess is that it was due to ignorance.¹ When reading the documentation, they found that they needed to fill in the hInstance member of the WNDCLASS structure. Gosh, where do I get an HINSTANCE from? Oh wait, I found a function that returns an HINSTANCE: Get­Module­Handle. And hey look, if I pass NULL, a valid HINSTANCE comes out. I'll just set wndclass.hInstance = Get­Module­Handle(NULL); and try it. Hey, look, it works!

    Footnote

    ¹ This reminds me of a story that took place at an administrative hearing. The government agency representative presented as evidence that the other party admitted in a telephone conversation to being ignorant of the applicable regulations.

    The other party angrily interrupted.

    "I'm not ignorant! I simply didn't know what the rules were."

    The judge patiently explained, "That's what the word ignorant means."

  • The Old New Thing

    Photoshop meme: Mark Reynolds casually eating sunflower seeds

    • 3 Comments

    July 7, 2011: David Ortiz hits a home run against the Baltimore Orioles. As he rounds third base, Orioles third baseman Mark Reynolds casually finishes off a package of sunflower seeds (photo 6 in the slide show).

    An Internet meme is born.

    Follow the hilarity.

  • The Old New Thing

    What is that horrible grinding noise coming from my floppy disk drive?

    • 41 Comments

    Wait, what's a floppy disk drive?

    For those youngsters out there, floppy disks are where we stored data before the invention of the USB earring. A single floppy disk could hold up to two seconds of CD-quality audio. This may not sound like a lot, but it was in fact pretty darned awesome, because CDs hadn't been invented yet either.

    Anyway, if you had a dodgy floppy disk (say, because you decided to fold it in half), you often heard a clattering sound from the floppy disk drive as it tried to salvage what data it could from the disk. What is that sound?

    That sound is recalibration.

    The floppy disk driver software kept getting errors back from the drive saying "I can't find any good data." The driver figures, "Hm, maybe the problem is that the drive head is not positioned where I think it is." You see, floppy drives do not report the actual head position; you have to infer it by taking the number of "move towards the center" commands you have issued and subtracting the number of "move towards the edge" commands. The actual location of the drive head could differ from your calculations due to an error in the driver, or it could just be that small physical errors have accumulated over time, resulting in a significant difference between the theoretical and actual positions. (In the same way that if you tell somebody to step forward ten steps, then backward ten steps, they probably won't end up exactly where they started.)

    To get the logical and physical positions back in sync, the driver does what it can to get the drive head to a known location. It tells the hardware, "Move the drive head one step toward the edge of the disk. Okay, take another step. One more time. Actually, 80 more times." Eventually, the drive head reaches the physical maximum position, and each time the driver tells the hardware to move the head one more step outward, it just bumps against the physical boundary of the drive hardware and makes a click sound. If you issue at least as many "one more step outward" commands as there are steps from the innermost point of the disk to the edge, then the theory is that at the end of the operation, the head is in fact at track zero. At that point, you can set your internal "where is the drive head?" variable to zero and restart the original operation, this time with greater confidence that the drive head is where you think it is.

    The amount of clattering depends on where the drive head was when the operation began. If the drive head were around track 40, then the first 40 requests to move one step closer to the center would do exactly that, and then next 43 requests would make a clicking noise. On the other hand, if the drive head were closer to track zero already, then nearly all of the requests result in the drive head bumping against the physical boundary of the drive hardware, and you get a longer, noisier clicking or grinding sound.

    You can hear the recalibration at the start of this performance.

    Bonus floppy drive music.

    Bonus reading: Tim Paterson, author of DOS, discusses all those floppy disk formats.

Page 121 of 450 (4,497 items) «119120121122123»