February, 2013

  • The Old New Thing

    What does 1#J mean? A strange corner case of the printing of special values


    As a puzzle, commenter nobugz asks, "What kind of infinity is 1.#J?"

    double z = 0;
    printf("%.2f", 1/z);

    Now, the division by zero results in IEEE positive infinity, would would normally be printed as 1#INF. But the catch here is that the print format says "Display at most two places after the decimal point." But where is the decimal point in infinity?

    The Visual C runtime library arbitrarily decided that all of the exceptional values have one digit before the decimal (namely, the "1"). Actually, it turns out that this puzzle might be an answer to Random832's question, "What's the 1 for?" Maybe the 1 is there so that there is a digit at all.

    Okay, so now you have one digit before the decimal (the "1"), and now you need to show at most two places after the decimal. But "#INF" is too long to fit into two characters. The C runtime then says, "Well, then I'd better round it off to two places, then."

    The first character is "#". The second character is "I". Now we need to round it. That's done by inspecting the third character, which is "N". We all learned in grade school that you round up if the next digit is 5 or greater. And it so happens that the code point for "N" is numerically higher than the code point for "5", so the value is rounded up by incrementing the previous digit. Incrementing "I" gives you "J".

    That's why printing IEEE positive infinity to two places gives you the strange-looking "1#J". The J is an I that got rounded up.

    I doubt this behavior was intended; it's just a consequence of taking a rounding algorithm intended for digits and applying it to non-digits.

    Of course, in phonetics, rounding an i produces a ü. Imagine the nerdiness of rounding "1#INF" to two places and producing "1#Ü". That would have been awesome.

  • The Old New Thing

    Is there a way to specify an icon to appear next to a menu item via the resource template?


    The MENU­ITEM­INFO structure lets you specify a bitmap to appear next to the menu item. Is there a way to do this from a menu resource template?


    If you look at the format of menu templates, you'll see that there is nowhere to specify a bitmap.

    Which kind of makes sense, because it is the responsibility of the application to destroy the bitmap referenced by the hbmpItem member when the menu is destroyed, but if you created the menu from a template, you don't know what that handle is, so you can't destroy it either!

  • The Old New Thing

    When the option becomes so second-nature you forget that it's an option


    A user of the imaginary Program Q program wanted to write an automated test that created a table, then ran various sub-test which communicated among each other by updating that table.

    When my test tries to create a table, the program asks the following question:

    q install server -r testdb
    Setting up this machine to be a registered table server...
    Registered table servers must adhere to Microsoft information 
    security policies. See http://programq/policy for details.
    If you have questions, contact mailto:qpolicy.
    Do you agree to adhere to Microsoft policies regarding
    registered table servers (y/n/q)?

    Is there a way to suppress the question? I can't pre-create a single server that all the tests connect to, because multiple tests running simultaneously would end up colliding with each other. I would prefer that each test run on its own isolated table server, but when I try to install a table server on the machine being tested, I get the above prompt.

    Why not just create an unregistered table server instead? Just leave off the -r flag. Give your problem description, there appears to be no need for the table server to be registered.
    Ah, didn't know about the ability to create an unregistered server. Works great!

    The user was apparently so accustomed to creating registered table servers that he didn't realize that there was any other kind. My guess is that he had no idea what the -r flag did; he just cargo-culted it from somewhere.

    Remember: The target audience for Program Q is not non-technical end-users. The target audience is other programmers, and this person was clearly a programmer since he was writing an automated test!

  • The Old New Thing

    This code would be a lot faster if it weren't for the synchronization


    This is a story from a friend of a friend, which makes it probably untrue, but I still like the story.

    One of my colleagues jokingly suggested that we could speed up our code by adding these lines to our project

    #define EnterCriticalSection(p) ((void)0)
    #define LeaveCriticalSection(p) ((void)0)

    I replied, "You think you're joking, but you're not."

    According to legend, there was a project whose product was running too slow, so they spun off a subteam to see what architectural changes would help them improve their performance. The subteam returned some time later with a fork of the project that they had "tuned". And it was indeed the case that the performance-tuned version ran a lot faster.

    Later, the development team discovered that part of the "tuning" involved simply deleting all the synchronization. They didn't replace it with lock-free algorithms or anything that clever. They just removed all the critical sections.

  • The Old New Thing

    Dreaming up strange inventions: The combination urinal/bidet/washing machine


    I dreamed that a friend of mine was showing me her new appliance: A combination urinal/bidet/washing machine. As we loaded clothes into it, she said, "You okay in there, Stephanie?"

    A muffled voice emerged from within: "Just let me know when you're ready."

  • The Old New Thing

    Display a custom thumbnail for your application (and while you're at it, a custom live preview)


    By default, when the taskbar or any other application wants to display a thumbnail for a window, the result is a copy of the window contents shrunk down to the requested size. Today we're going to override that behavior and display a custom thumbnail.

    Take the program from last week and make these changes:

    #include <dwmapi.h>
    OnCreate(HWND hwnd, LPCREATESTRUCT lpcs)
      g_hicoAlert = LoadIcon(nullptr, IDI_EXCLAMATION);
      g_wmTaskbarButtonCreated = RegisterWindowMessage(
      BOOL fTrue = TRUE;
      DwmSetWindowAttribute(hwnd, DWMWA_FORCE_ICONIC_REPRESENTATION,
                            &fTrue, sizeof(fTrue));
      DwmSetWindowAttribute(hwnd, DWMWA_HAS_ICONIC_BITMAP,
                            &fTrue, sizeof(fTrue));
      return TRUE;

    We start by enabling custom thumbnails by setting the DWMWA_HAS_ICONIC_BITMAP attribute to TRUE. This overrides the default thumbnail generator and allows us to provide a custom one.

    Next is a helper function that I broke out from this program because it's useful on its own. It simply creates a 32bpp bitmap of the desired size and optionally returns a pointer to the resulting bits.

    HBITMAP Create32bppBitmap(HDC hdc, int cx, int cy,
                              RGBQUAD **pprgbBits = nullptr)
     BITMAPINFO bmi = { 0 };
     bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
     bmi.bmiHeader.biWidth = cx;
     bmi.bmiHeader.biHeight = cy;
     bmi.bmiHeader.biPlanes = 1;
     bmi.bmiHeader.biBitCount = 32;
     bmi.bmiHeader.biCompression = BI_RGB;
     void *pvBits;
     HBITMAP hbm = CreateDIBSection(hdc, &bmi,
               DIB_RGB_COLORS, &pvBits, NULL, 0);
     if (pprgbBits) *pprgbBits = static_cast<RGBQUAD*>(pvBits);
     return hbm;

    Next, we take our Paint­Content function and make it render into a DC instead:

    RenderContent(HDC hdc, LPCRECT prc)
     LOGFONTW lf = { 0 };
     lf.lfHeight = prc->bottom - prc->top;
     wcscpy_s(lf.lfFaceName, L"Verdana");
     HFONT hf = CreateFontIndirectW(&lf);
     HFONT hfPrev = SelectFont(hdc, hf);
     wchar_t wszCount[80];
     swprintf_s(wszCount, L"%d", g_iCounter);
     FillRect(hdc, prc, GetStockBrush(WHITE_BRUSH));
     DrawTextW(hdc, wszCount, -1, const_cast<LPRECT>(prc),
     SelectFont(hdc, hfPrev);

    In our case, we will want to render into a bitmap:

    GenerateContentBitmap(HWND hwnd, int cx, int cy)
     HDC hdc = GetDC(hwnd);
     HDC hdcMem = CreateCompatibleDC(hdc);
     HBITMAP hbm = Create32bppBitmap(hdcMem, cx,cy);
     HBITMAP hbmPrev = SelectBitmap(hdcMem, hbm);
     RECT rc = { 0, 0, cx, cy };
     RenderContent(hdcMem, &rc);
     SelectBitmap(hdcMem, hbmPrev);
     ReleaseDC(hwnd, hdc);
     return hbm;

    We can use this function when DWM asks us to generate a custom thumbnail or a custom live preview bitmap.

    UpdateThumbnailBitmap(HWND hwnd, int cx, int cy)
     HBITMAP hbm = GenerateContentBitmap(hwnd, cx, cy);
     DwmSetIconicThumbnail(hwnd, hbm, 0);
    UpdateLivePreviewBitmap(HWND hwnd)
     RECT rc;
     GetClientRect(hwnd, &rc);
     HBITMAP hbm = GenerateContentBitmap(hwnd, rc.right - rc.left,
                                         rc.bottom - rc.top);
     DwmSetIconicLivePreviewBitmap(hwnd, hbm, nullptr, 0);
     // WndProc
      UpdateThumbnailBitmap(hwnd, HIWORD(lParam), LOWORD(lParam));

    One of the quirks of the WM_DWM­SEND­ICONIC­THUMB­NAIL message is that it passes the x- and y-coordinates backwards. Most window messages put the x-coordinate in the low word and the y-coordinate in the high word, but WM_DWM­SEND­ICONIC­THUMB­NAIL does it the other way around.

    Since we're generating a custom thumbnail and live preview bitmap, we need to let the window manager know that the custom rendering is out of date and needs to be re-rendered: Invalidate the custom bitmaps when the counter changes.

    void OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
      switch (id) {
      case IDC_INCREMENT:
        InvalidateRect(hwnd, nullptr, TRUE);

    And finally, just to be interesting, we'll also stop rendering content into our main window.

    PaintContent(HWND hwnd, PAINTSTRUCT *pps)
        // do nothing

    Run this program and observe that the window comes up blank. Ah, but if you hover over the taskbar button, the custom thumbnail will appear, and that custom thumbnail has the number 0 in it. Click on the button in the thumbnail, and the number in the custom thumbnail increments.

    As a bonus, move the mouse over the thumbnail to trigger Aero Peek. The live preview bitmap contains the magic number! Move the mouse away, and the magic number vanishes.

    Now, this was an artificial example, so the effect is kind of weird. However, you can imagine using this in less artificial cases where the result is useful. You application might be a game, and instead of using the default thumbnail which shows a miniature copy of the game window, you can have your thumbnail be a tiny scoreboard or focus on a section of the board. For example, if you are a card game, the thumbnail might show just the cards in your hand.

    I can't think of a useful case for showing a live preview bitmap different from the actual window. The intended use for a custom live preview bitmap is for applications like Web browsers which want to minimize a tab's memory usage when it is not active. When a tab becomes inactive, the browser can destroy all graphics resources except for a bitmap containing the last-known-valid contents of the window, and use that bitmap for the thumbnail and live preview.

  • The Old New Thing

    Now that version 4 of the .NET Framework supports in-process side-by-side runtimes, is it now okay to write shell extensions in managed code?


    Many years ago, I wrote, "Do not write in-process shell extensions in managed code." Since I originally wrote that article, version 4 of the .NET Framework was released, and one of the features of that version is that it supports in-process side-by-side runtimes. Does that mean that it's now okay to write shell extensions in managed code?

    The answer is still no.

    The Guidance for implementing in-process extensions has been revised, and it continues the recommendation against writing shell extensions and Internet Explorer extensions (and other types of in-process extensions) in managed code, even if you're using version 4 or higher.

    Although version 4 addresses the side-by-side issue, it is still the case that the .NET Framework is a high-impact runtime, and that there are various part of COM interop in the .NET Framework that are not suitable for use in an extension model designed around native code.

    Note that managed code remains acceptable for out-of-process extensions.

  • The Old New Thing

    Isn't the CompletionKey parameter to CreateIoCompletionPort superfluous?


    When you associate a file handle with an I/O completion port with the Create­Io­Completion­Port function, you can pass an arbitrary pointer-sized integer called the Completion­Key which will be returned by the Get­Queued­Completion­Status function for every I/O that completes against that file handle. But isn't that parameter superfluous? If somebody wanted to associated additional data with a file handle, they could just extend the OVERLAPPED structure to contain that additional data.

    Yes, they could, so in a purely information-theoretical sense, the parameter is superfluous. And heated seats in your car are superfluous, too. But they sure are nice!

    From a purely information-theoretical point of view, a lot of things are superfluous. The GWLP_USER­DATA window bytes are not necessary, because you could just put the information in the window extra bytes. And window extra bytes are superfluous, since you could have just put them in properties. And properties are superfluous, since you could just have a hash table which maps window handles to "all the other data I want to associate with this window handle."

    But it's nice to have GWLP_USER­DATA.

    I find it interesting that people complain when Windows does not provide a convenience for some operation, and here's a case where it provides one, and then people complain that it's wasteful!

    It can be nice to have some information associated with the file handle (to record some general information, like the overall operation this file is responsible for) and different information associated with the I/O request (to record some specific information, like which phase of the operation most recently completed). That way, you don't have to try to pack the two pieces of information together.

    A more practical reason is that you may not be able to pass the extended OVERLAPPED through to the Read­File. For example, you may be calling another function which will in turn issue the Read­File, and that other function builds its own OVERLAPPED structure rather than letting you pass one in. In that case, you will thank your lucky stars that there's some redundant data elsewhere that will let you recover your state.

  • The Old New Thing

    What does -1.#IND mean?: A survey of how the Visual C runtime library prints special floating point values


    As every computer scientist knows, the IEEE floating point format reserves a number of representations for infinity and non-numeric values (collectively known as NaN, short for not a number). If you try to print one of these special values with the Visual C runtime library, you will get a corresponding special result:

    Output Meaning
    1#INF Positive infinity
    -1#INF Negative infinity
    1#SNAN Positive signaling NaN
    -1#SNAN Negative signaling NaN
    1#QNAN Positive quiet NaN
    -1#QNAN Negative quiet NaN
    1#IND Positive indefinite NaN
    -1#IND Negative indefinite NaN

    Positive and negative infinity are generated by arithmetic overflow, or when the mathematical result of an operation is infinite, such as taking the logarithm of positive zero. (Don't forget that IEEE floating point supports both positive and negative zero.) For math nerds: IEEE arithmetic uses affine infinity, not projective, so there is no point at infinity.

    Signaling and quiet NaNs are not normally generated by computations (with one exception noted below), but you can explicitly create one for a floating-point type by using the std::numeric_limits<T> class, methods signaling_NaN() and quiet_NaN().

    Recall that there is not just one signaling and quiet NaN, but rather a whole collection of them. The C runtime does not distinguish among them when printing, however. All signaling NaNs are reported as 1#SNAN, regardless of the signal bits. The C runtime does report the sign of the NaN, for what little that is worth.

    The weird one is the Indefinite NaN, which is a special type of quiet NaN generated under specific conditions. If you perform an invalid arithmetic operation like add positive infinity and negative infinity, or take the square root of a negative number, then the IEEE standard requires that the result be a quiet NaN, but it doesn't appear to specify what quiet NaN exactly. Different floating point processor manufacturers chose different paths. The term Indefinite NaN refers to this special quiet NaN, whatever the processor ends up choosing it to be.

    Some floating point processors generate a quiet NaN with the signal bits clear but the sign bit set. Setting the sign bit makes the result negative, so on those processors, you will see the indefinite NaN rendered as a negative indefinite NaN. (The x86 is one of these processors.)

    Other floating point processors generate a quiet NaN with the signal bits and the sign bit all clear. Clearing the sign bit makes the result positive, so on those processors, you will see the indefinite NaN rendered as a positive indefinite NaN.

    In practice, the difference is not important, because either way, you have an indefinite NaN.

  • The Old New Thing

    You can ask the compiler to answer your calling convention questions


    If you want to figure out some quirks of a calling convention, you can always ask the compiler to do it for you, on the not unreasonable assumption that the compiler understands calling conventions.

    "When a __stdcall function returns a large structure by value, there is a hidden first parameter that specifies the address the return value should be stored. But if the function is a C++ instance method, then there is also a hidden this parameter. Which goes first, the return value parameter or the this pointer?"

    This is another case of You don't need to ask me a question the compiler can answer more accurately.

    struct LargeStructure
     char x[256];
    class Something
     LargeStructure __stdcall TestMe();
    void foo(Something *something)
     LargeStructure x = something->TestMe();

    You could compile this into a program and then look in the debugger, or just ask the compiler to generate an assembly listing. I prefer the assembly listing, since it saves a few steps, and the compiler provides helpful symbolic names.

      00015 mov     eax, DWORD PTR _something$[ebp]
    ; LargeStructure x = something->TestMe();
      00018 lea     ecx, DWORD PTR _x$[ebp]
      0001e push    ecx
      0001f push    eax
      00020 call    ?TestMe@Something@@
                    ; Something::TestMe

    We see that the last thing pushed onto the stack (and therefore the top parameter on the stack at the point of the call) is the something parameter, which is the this for the function.

    Conclusion: The this pointer goes ahead of the output structure pointer.

Page 1 of 3 (29 items) 123