Larry Osterman's WebLog

Confessions of an Old Fogey
  • Larry Osterman's WebLog

    What’s wrong with this code, Part 23..


    I recently tracked down a bug that was causing problems in my code.  Once I figured out the bug, I realized it made a good “what’s wrong with this code”…

    #include "stdafx.h"
    #include <mmdeviceapi.h>
    IMMDeviceEnumerator *GetDeviceEnumerator()
        CComPtr<IMMDeviceEnumerator> deviceEnumerator;
        HRESULT hr = deviceEnumerator.CoCreateInstance(__uuidof(MMDeviceEnumerator));
        if (FAILED(hr))
            return NULL;
        return deviceEnumerator.Detach();
    int _tmain(int argc, _TCHAR* argv[])
            CComPtr<IMMDeviceEnumerator> deviceEnumerator(GetDeviceEnumerator());
            CComPtr<IMMDeviceCollection> deviceCollection;
            if (deviceEnumerator != NULL)
                HRESULT hr = deviceEnumerator->EnumAudioEndpoints(eAll, DEVICE_STATE_ACTIVE, &deviceCollection);
                if (SUCCEEDED(hr))
                    UINT deviceCount;
                    hr = deviceCollection->GetCount(&deviceCount);
                    if (SUCCEEDED(hr))
                        printf("There are %d audio endpoints on the machine\n", deviceCount);
        return 0;

    Simple code, right?  But there’s a nasty bug hidden in there, and it was NOT obvious to me what the bug was.

    As always, kudos to the person who gets the bug first.  And of course mea culpa's for bugs I accidentally included.

  • Larry Osterman's WebLog

    Anatomy of a Heisenbug


    I just spent a half an hour debugging a heisenbug and thought I’d pass on what was happening.


    I was running my unit tests for one of my features and they were reliably failing.  Unfortunately the instant I ran the test case under the debugger, the problem went away.  Problems that disappear under the debugger are a classic symptom of a heisenbug, this was no exception.

    If I attached the debugger AFTER the test started but before the failure hit, I was able to see the failure occur.  The problem only occurred when launching the app under the debugger.  At that point I realized what was happening.

    As MSDN says

    Processes that the debugger creates (also known as spawned processes) behave slightly differently than processes that the debugger does not create.

    Instead of using the standard heap API, processes that the debugger creates use a special debug heap. On Microsoft Windows XP and later versions of Windows, you can force a spawned process to use the standard heap instead of the debug heap by using the _NO_DEBUG_HEAP environment variable or the -hd command-line option.

    It turns out that I had added a member variable to a class and failed to initialize it in the constructor of the class.  When launched under the debugger, the debug heap initializes all allocated memory to a known value.  That means that when launched under the debugger the member variable had that known value, when launched without the debugger it was uninitialized and happened to have the value of 0.  For a number of reasons, this value caused the test to fail. 


    I hate heisenbugs, but I like it when they’re really easy to find like this one.

  • Larry Osterman's WebLog

    I'm So Excited!



    'nuf said.



    I know it's bragging, but I'm sorry - I really couldn't resist.  It's been a very long time.

  • Larry Osterman's WebLog

    Gotchas associated with using WM_PRINTCLIENT…


    Yesterday I mentioned WM_PRINTCLIENT and how awesome it is when trying to strictly control the drawing of your application.

    Part of the reason it took over a week to change the drawing model is that there are a number of serious gotcha’s associated with using WM_PRINTCLIENT and controlling your own drawing story.  The first is that not all controls support WM_PRINTCLIENT.  It turns out that some controls don’t support the WM_PRINTCLIENT, however if you search the documentation for WM_PAINT, you’ll find the following comment:

    “For some common controls, the default WM_PAINT message processing checks the wParam parameter. If wParam is non-NULL, the control assumes that the value is an HDC and paints using that device context.”

    That means that if you find a common control that doesn’t support WM_PRINTCLIENT, you can use WM_PAINT specifying wParam as the HDC[1].  Fortunately I didn’t run into this in my control.

    The next gotcha is that some controls (like buttons and toolbars etc) have animations that are launched when you mouse over the control.  These are often subtle (like the glow when you hover over a scrollbar thumb).  In order to continue to have these effects work, you need to let those controls paint themselves – in my experience it generally didn’t cause much of a problem with flickering, but your mileage might vary.


    The last gotcha is a very big one and hung me up for about half a day.  The WM_PRINTCLIENT message only paints the client area of a window.  If you have a window with the WM_HSCROLL or WM_VSCROLL style then you won’t be able to paint the scroll bar.  Instead you need to create your own scrollbar control (with CreateWindow) and use that instead of the built-in scroll styles.  There are ways you can convince the window to paint it’s non client region to an HDC but they are fraught with peril (one senior developer I was talking to about this problem described them as “unnatural acts”) and simply not worth the effort.




    [1] There’s also a corollary to that: If you ever send a WM_PAINT to a control you MUST ensure that wParam and lParam are 0 even though they’re documented as “not used”.

  • Larry Osterman's WebLog

    Larry’s new favorite windows message – WM_PRINTCLIENT


    As I’ve mentioned before, I’ve been fuddling around doing UI programming recently – it’s a bit different from my usual work deep in the bowels of the <insert whatever subsystem Larry happens to be working on (redirector, audio stack, POP3 server, whatever)>.


    I’ve been having a great deal of fun doing the whole “UI programmer” thingy (although my grandboss is right – once you start doing UI, everyone thinks that you’ve done it wrong) recently, and I’ve learned a ton of stuff.

    Most of the UI I work with is written as dialog box applications – for various reasons, many of the audio UI elements are actually dialog boxes[1].  As such, the system controls the actual drawing of the UI elements, especially if you specify the WS_CLIPCHILDREN window style.

    I recently had a bug where one of the UI elements wasn’t being painted correctly.  For a number of reasons, the element was being overwritten by another element.


    It took a lot of work to get to the scenario where the UI element got messed up, so I was going to ignore the problem (it was ugly but transient).  But then I got to browsing the web and I ran into this article.  The article had nothing to do with the order of painting in a dialog, but it DID mention a windows message that I hadn’t heard of before, WM_PRINTCLIENT.

    Hmm, that’s interesting.  WM_PRINTCLIENT says “The WM_PRINTCLIENT message is sent to a window to request that it draw its client area in the specified device context, most commonly in a printer device context.”.  Ooh, that’s interesting.  If I can just send a WM_PRINTCLIENT to each of the controls in the window, maybe I can control the order in which the controls are rendered, which would allow me to fix the problem (and remove a long-standing issue with the program in question).

    On Monday of last week, I came in and decided that I’d dedicate a couple of days to see if my idea might work – worst case I’d lose a couple of days of work, but if it did work it would be really cool.

    By mid-afternoon on Monday, I had come to the point where I realized that my crazy idea would actually work. 

    Skip forward one very long week of debugging and tweaking and I had fixed the problem – I had rebuilt the painting algorithm for this application and it worked! 


    Right now I’m highly enamored of the WM_PRINTCLIENT message simply because it’s so darned useful in scenarios like mine.



    PS: It’s possible that I might be able to achieve similar results with the WS_EX_COMPOSITED window style but it’s not clear given some of the UI requirements for the application – I may play around with that idea over the next couple of weeks.


    [1] One of the reasons for the apps being dialog box based is that it makes it easier for localizers if the application is built on dialog boxes because it gives the localizers greater flexibility when translating the OS – if the preferred text in the destination language doesn’t fit, they can adjust the layout of the dialog to make the text fit.

  • Larry Osterman's WebLog

    What makes a bug a security bug?


    In my last post, I mentioned that security bugs were different from other bugs.  Daniel Prochnow asked:

    What is the difference between bug and vulnerability?

    In my point of view, in a production enviroment, every bug that may lead to a loss event (CID, image, $) must be considered a security incident.

    What do you think?

    I answered in the comments, but I think the answer deserves a bit more commentary, especially when Evan asked:

    “I’m curious to hear an elaboration of this.  System A takes information from System B.  The information read from System A causes a[sic] System B to act in a certain way (which may or may not lead to leakage of data) that is unintended.  Is this a security issue or just a bug?”

    Microsoft Technet has a definition for a security vulnerability:

    “A security vulnerability is a flaw in a product that makes it infeasible – even using the product properly – to prevent an attacker from usurping privileges on the user’s system, regulating it’s operation, compromising data on it or assuming ungranted trust.”

    IMHO, that’s a bit too lawyerly, although the article does an excellent job of breaking down the definition and making it understandable.

    Crispin Cowan gave me an alternate definition, which I like much better:

    Security is the preservation of:

    · Confidentiality: your secret stuff stays secret

    · Integrity: your data stays intact

    · Availability: your systems and data remain available

    A vulnerability is a bug such that an attacker can compromise one or more of the above properties


    In Evan’s example, I think there is a security bug, but maybe not.  For instance, it’s possible that System A validates (somehow) that System B hasn’t been compromised.  In that case, it might be ok to trust the data read from System B.  That’s part of the reason for the wishy-washy language of the official vulnerability definition.

    To me, the key concept in determining if a bug is a security bug or not is that of an unauthorized actor.  If an authorized user performs operations on a file to which the user has access and the filesystem corrupts their data, it’s a bug (a bad bug that MUST be fixed, but a bug nonetheless).  If an unauthorized user can cause the filesystem to corrupt the data of another user, that’s a security bug.

    When a user downloads a file from the Internet, they’re undoubtedly authorized to do that.  They’re also authorized to save the file to the local system.  However the program that reads the file downloaded from the Internet cannot trust the contents of the file (unless it has some way of ensuring that the file contents haven’t been tampered with[1]).  So if there’s a file parsing bug in the program that parses the file, and there’s no check to ensure the integrity of the file, it’s a security bug.


    Michael Howard likes using this example:

    char foo[3];
    foo[3] = 0;

    Is it a bug?  Yup.  Is it a security bug?  Nope, because the attacker can’t control anything.  Contrast that with:

        int value;
    } buf;
    char foo[3];

    _read(fd, &buf, sizeof(buf));
    foo[buf->value] = 0;

    That’s a 100% gen-u-wine security bug.


    Hopefully that helps clear this up.



    [1] If the file is cryptographically signed with a signature from a known CA and the certificate hasn’t been revoked, the chances of the file’s contents being corrupted are very small, and it might be ok to trust the contents of the file without further validation. That’s why it’s so important to ensure that your application updater signs its updates.

  • Larry Osterman's WebLog

    Go see Shrek the Musical. Right now!


    We just got back home from seeing Shrek the Musical which is currently in try-outs at the Fifth Avenue Theatre here in Seattle.


    This show's going to be BIG when it hits Broadway.  I'm talking Hairspray big.

    It's one of the funniest shows I've seen in a really long time.  The main characters are brilliant, and the writing is very funny. 

    Brian D'Arcy James was great as Shrek and Sutton Foster as Fiona was uncannily like the movie version.  It was scary at times.

    I was particularly struck by the scene where they introduced Fiona.  They had three actresses playing the part of Fiona - at age 7, 15 and 25ish, they each sang part of the same song.  It was beautiful and really touching.

    Not surprisingly the show had some rough moments, but in it still was one of the best shows I've seen in a long while.

    One very nice touch in the show is that just as the movie of Shrek had lots of clever references to classic fairy tales, the musical version of Shrek is filled with clever references to other Broadway shows[1].   For instance, there's a scene where the fairy tale characters are all interviewed by Lord Farquaad (the villain).  The characters all stand in a line on stage and Farquaad interviews them using the "G_d Mike" (as Daniel calls it).  The characters then sing a clever song about how they want Farquaad to pick them.  It's a pastiche of A Chorus Line.  Other shows we saw referenced were Wicked, The Lion King, Avenue Q[2], High School Musical and others.



    Over the past few years, I've seen 6 different shows on tryouts in Seattle: Hairspray, Princesses, The Wedding Singer, Young Frankenstein, Lone Star Love and Shrek.  After seeing the shows, I've accurately predicted how 5 of the six would do (Princesses and Lone Star Love disappeared, The Wedding Singer was a pretty good success, Young Frankenstein was funny and was a hit but isn't nearly as good as The Producers was, and of course Hairspray was utterly huge).  I honestly think that Shrek could top Hairspray.  It is THAT good.


    So go see Shrek if you can.  If you can't see it in Seattle, get tickets to see it on Broadway.  You won't be disappointed.




    [1] Disclaimer: The show I saw is in VERY early tryouts.  So far, they've had exactly 4 performances in front of a live audience.  It's entirely possible that anything or everything I saw tonight might change before it hits Broadway.

    [2] The Avenue Q reference was when the character of Pinocchio, played by John Tartaglia says that he's going to make a mix tape for someone else (if you've seen Avenue Q, in it Princeton makes a mix tape for Kate Monster).  What makes this bit particularly funny is that John Tartaglia originated the role of Princeton in Avenue Q.

  • Larry Osterman's WebLog

    Linus Torvalds is “Fed up with the ‘security circus’”


    There’s been a lot of discussion on the intertubes about some comments that Linus Torvalds, the creator of Linux has made about security vulnerabilities and disclosure.

    Not surprisingly, there’s been a fair amount of discussion amongst the various MSFT security folks about his comments and about the comments about his comments (are those meta-comments?).


    The whole thing started with a posting from Linus where he says:

    Btw, and you may not like this, since you are so focused on security, one reason I refuse to bother with the whole security circus is that I think it glorifies - and thus encourages - the wrong behavior.

    It makes "heroes" out of security people, as if the people who don't just fix normal bugs aren't as important.

    He also made some (IMHO) unprofessional comments about the OpenBSD community, but I don’t think that’s relevant to my point.

    Linus has followed up his initial post with an interview with Network World where he commented:

    “You need to fix things early, and that requires a certain level of disclosure for the developers," Torvalds states, adding, "You also don't need to make a big production out of it."”


    "What does the whole security labeling give you? Except for more fodder for either of the PR camps that I obviously think are both idiots pushing for their own agenda?" Torvalds says. "It just perpetrates that whole false mind-set" and is a waste of resources, he says.

    As a part of our internal discussion, Crispin Cowan pointed out that Linus doesn’t issue security updates for Linux, instead the downstream distributions that contain the Linux kernel issue security fixes.

    That comment was the catalyst – after he made the comment, I realized that I think I understand the meaning behind Linus’ comments.

    IMHO, Linus is thinking about security bugs as an engineer.  And as an engineer, he’s completely right (cue the /. trolls: “MSFT engineer thinks that Linux inventor is right about something!”). 

    As a software engineer, I fully understand where Linus is coming from: From a strict engineering standpoint, security bugs are no different from any other bugs, and treating them as somehow “special” denigrates other bugs.  It’s only when you consider the consequences of security bugs that they become more interesting.

    A non security bug can result in an unbootable system or the loss of data on the affected machine.  And they can be very, very bad.  But security bugs are special because they’re bugs that allow a 3rd party to mess with your system in ways that you didn’t intend.

    Simply put, your customers data is at risk from security bugs in a way that normal defects aren’t.  There are lots of bad people out there who would just love to exploit any security defect in your product.  Security updates are more than just “PR”, they provide critical information that customers use to help determine the risk associated with taking a fix.

    Every time your customer needs to update the software on their computer, they take the risk that the update will break something (that’s a large part of the reason that that MSFT takes it’s time when producing security fixes – we test the heck out of stuff to reduce the risk to our customers).  But because the bad guys can use security vulnerabilities to compromise their customers data, your customers want to roll out security fixes faster than they roll out other fixes.

    That’s why it’s so important to identify security fixes – your customers use this information for risk management.  It’s also why Microsoft’s security bulletins carry mitigating factors that would help identify if customers are at risk.  For example MS08-045 which contains a fix for CVE-2008-2257 has a mitigating factor that mentions that in Windows Server 2003 and Windows Server 2008 the enhanced security configuration mode mitigates this vulnerability.  A customer can use that information to know if they will be affected by MS08-045.

    But Linus’ customers aren’t the users of Linux.  They are the people who package up Linux distribution.  As Crispin commented, the distributions are the ones that issue the security bulletins and they’re the ones that work with their customers to ensure that the users of the distribution are kept safe.

    By not clearly identifying which fixes are security related fixes, IMHO Linus does his customers a disservice – it makes the job of the distribution owner harder because they can’t report security defects to their customers.  And that’s why reporting security bug fixes is so important.

    Edit: cleared out some crlfs

    Edit2: s/Linus/Linux/ :)

  • Larry Osterman's WebLog

    The SS_PATHELLIPSIS, SS_ENDELLIPSIS and SS_WORDELLIPSIS styles force static controls to disable word wrap.


    I didn’t find this in the documentation for the static standard window so I figured I’d put it out in my blog in the hopes that someone else won’t get stuck on this problem.

    The Windows “static” control has a number of styles that control how the control draws text.  They can be extremely useful when controlling how the control lays out text.

    I recently had to write code that draws the name of an audio endpoint into a relatively size constrained static text control.  No problem, right[1]?


    Well what happens if the name of the endpoint is somewhat longer? No problem, the SS_CENTER style will wrap the words.

    Headset Microphone

    But sometimes the endpoint name is longer than “Headset Microphone”.  In fact the user can set the endpoint name to anything they want.

    Long Headset M

    Uck, that looks ugly.

    Fortunately the static control has an option SS_WORDELLIPSIS that looks like it should be perfect for me:

    “Windows NT or later: Truncates any word that does not fit in the rectangle and adds ellipses.”

    That sounds exactly like what I want.  But when I added SS_WORDELLIPSIS, I got:

    Long He...



    Hold on, that’s not right, what happened to the rest of my text?

    After a bit of digging, I finally figured out what was going on (by trial an error removing all the various static control styles I specified).


    It turns out that this behavior is by design, even though I couldn’t find any documentation of it.  If you specify any of the ellipsis styles for the static control, the control becomes a single line control.  The only way I’ve found to fix this is to make the static control an owner draw control and use the DrawThemeText (or DrawText) API specifying the DT_WORDBREAK | DT_ENDELLIPSIS option.

    I’ve filed a documentation bug to ensure that this gets fixed sometime in the near future.

    [1] I’ve approximated what was going on in my UI with HTML tables, this is a rough approximation to show more-or-less what was going on.

    ETA: Thanks to Drew and Lindseth for reviewing this.

    Edit: Fixed word wrap in edit control.

  • Larry Osterman's WebLog

    Why doesn’t Windows support amplification of audio samples?


    Nils Arthur asked in another post:

    While we are talking volume controls. Could you explain why it's only possible to lower the volume in Windows (i.e. setting a volume between 0% and 100%) and not raise it (i.e setting it higher than 100%)?

    Before I get into the the answer, let me define some terms:  Attenuation means reducing the amplitude of a signal from a baseline - so if the signal is a full range sine wave going from 1.0 to -1.0, if you attenuate it to 50%, you get a sine wave from 0.5 to -0.5.  I wrote about it (with pictures :)) in this post.

    The answer to Nils' question is both simple and complicated.

    The simple part of the answer: Because most PC audio hardware only supports attenuation and not amplification.

    Now for the complicated parts of the answer: We only support what the hardware allows for master volume.  And most hardware only supports attenuation.  There are a lot of reasons for that, but the primary one is that it's dramatically cheaper (and uses less power) to attenuate signals than it is to amplify them.

    The other issue w.r.t. amplification/attenuation is signal quality. As I mentioned in the post on volume above, you can attenuate a sample in the digital domain without loss of fidelity.  However when you attempt to amplify a signal in the digital domain, it clips.   That means that amplification MUST be done in the analog domain.  Again, this goes to hardware costs - because amplification needs to be done in the analog domain, it means that the audio hardware needs to have an amplifier that can be digitally controlled, which is (again) more expensive.  The audio hardware doesn't even have to support hardware volume - if Windows doesn't find a hardware volume control, it simply inserts a master volume into the audio pipeline.

    Some audio hardware DOES support amplification, but the audio volume controls map the volume control from low to high into a range from 0..100 because it's dramatically simpler to represent that to the user.

    That means that if an audio solution presents a hardware volume from -96.0dB to +3dB (there are a number of them that do that), we'll map that 99dB range into a 0.0 to 1.0 range that maps nicely into a slider.  We've thought about differentiating between attenuation and amplification in the volume UI, but the reality is that the net effect is the same whether we represent amplification or not.

    You can see if your audio hardware supports amplification by going to the multimedia control panel.  Select the audio endpoint you want to check, go to the "Properties" dialog.  On that dialog, check the "Levels" tab, the hardware master volume control is present there.  You can right click on the text box and change the units from linear to dB, you can then move the slider around to see the dB range.  Or you could write some code and call the IAudioEndpointVolume::GetVolumeRange API, which will return the information directly.

  • Larry Osterman's WebLog

    Remembering Aaron Reynolds


    Last Saturday I received an email from Tandy Trower, a long time Microsoft employee letting me know that Aaron Reynolds had unexpectedly passed away.  It threw me for a loop, Aaron isn’t that much older than I am and I'm not used to hearing about people I knew dying unexpectedly.  Even though it’s been over a week, I’m still a bit rocky about it.


    Aaron was one of the early MS-DOS and Windows developers, and I looked on him as one of my mentors back when I was a new hire at Microsoft.  He was the original author of the MS-NET redirector which I later inherited, so I spent a fair amount of time asking Aaron what this or that mysterious piece of code did.

    Aaron was often gruff, it was sometimes an adventure going to his office to ask him a question.  You’d knock on the door and if he was busy he would continue to work for as long as 5 to 10 minutes until he had finished whatever it was he was dealing with and only then would he check to see if you were still there.  But once you had his attention, he would patiently explain with great detail everything you needed to know about your problem.  And he always knew the answer.


    He was a font of knowledge about Windows and DOS, as Tandy said in his email: “To this day there is probably code inside Windows that only Aaron really understood why it was there.”


    I haven’t seen Aaron in a few years, but my boss tells me that he used to see him every week or so at Seattle Mariners games, Aaron had Diamond Club seats and rarely missed a home game.


    He will be missed by all who knew him.

  • Larry Osterman's WebLog

    THIS is what a Windows PC should look like…


    We had a neighborhood picnic on Saturday at our neighbors house.  While we were chatting in the kitchen, I noticed their new computer.

    They had an HP TouchSmart computer, and I have to say that I was blown away by it.  I really liked the industrial design and the touch interface is really smooth.



    All in all a machine that I’d be happy put in my kitchen.  It wouldn’t work as a desktop PC for me (I prefer to have more customizability than you can get in an all-in-one), but for our kitchen PC (which we almost never upgrade) it would be absolutely perfect.  


    I wish more OEMs spent as much time as HP clearly has on making their machines beautiful.

  • Larry Osterman's WebLog

    What’s wrong with this code, Part 22 – the answers


    The other day, I wrote about measuring the dimensions of a piece of text using the DrawText API.

    My code worked just great when I initially tested it (obviously it’s a part of a larger chunk of code that does more complicated work).  The problem showed up when I started testing it on a machine running in High DPI mode (144DPI).

    The code in question measured some text and then used that text to set the size of a button, when working in low DPI mode (96DPI), the font that is chosen had font metrics that closely matched the font that was used when painting the button.  The problem was that the button font that was used in high DPI mode had dramatically larger font metrics than the low DPI font. 

    As a result, the rectangle returned by the initial DrawText call didn’t match the rectangle that was used when the button was painted.  That meant that the button text overflowed the button.


    The fix to the code is to retrieve the font that is going to be used to draw the button and to use SelectObject to set the font in the memory DC to match the button font.  Once I made that change, the button drew perfectly.

    Here’s the corrected code (new code in red):

       HDC hdc = CreateCompatibleDC(NULL); 
       RECT rcText = {0, 0, 88, 34}; 
       HFONT hFont = reinterpret_cast<HFONT>(SendMessage(m_hWndControl, WM_GETFONT, 0, 0)); 
       HFONT hFontOld = reinterpret_cast<HFONT>(SelectObject(hdc, hFont)); 
       CAtlString string; 
       string.Format(L"Text String occupies: %d x %d pixels", rcText.right - rcText.left, rcText.bottom -; 
       MessageBox(hWnd, string, L"String Size", 0); 
       SelectObject(hdc, hFontOld); 


    And yeah, I’m sure this is old-hat to experienced Windows UI programmers, but it stumped me for several hours so I figured I’d write it up for the blog in case someone else hits the same problem.

    Kudos and omissions:

    Aaron Ballman caught that I forgot to call DeleteDC when I was done with using the DC.  Stupid boneheaded mistake.

    Shog9 and Ivo caught the root cause (selecting the wrong font).


    And Eldan caught the Large Fonts implication.  There are other ways of catching this, but HighDPI is the easiest.

    I also agree with his assertion that font handling of GDI is “complicated”.  On the other hand, the alternative is adding a dozen parameters to the DrawText API (you’d have to add foreground color, background color, font, etc to the call, which would complicate the API dramatically). 


    PS For those who care about such things: When I’m testing UI changes, I start with standard DPI, then I retest the changes in HighDPI and again using high contrast mode.  Testing in high contrast mode also tests the code in a non themed mode, which helps to catch bugs where I accidentally depended on the theming logic.

  • Larry Osterman's WebLog

    What’s wrong with this code, part 22 – Drawing Text…


    Recently I’ve been working on something that I’ve never done before in my almost 24 years at Microsoft. 


    For the past 23ish years, I’ve been a plumber – all the work I’ve done has been under the covers.  But for the next version of Windows, I decided to stretch my boundaries a bit and try some UI programming.  I’ve just spent the past few days working on a cool change to the volume control (it’s not important what it is, and most people will never know about the change, but those that do will probably agree with me :)).

    As part of the change, I needed to measure the dimensions of a text string.  This is a dummy version of some code I wrote, I simply called DrawText with the DT_CALCRECT into a memory DC that I created.

    BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
       HWND hWnd;
       hInst = hInstance; // Store instance handle in our global variable
       hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
          CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
       if (!hWnd)
          return FALSE;
       HDC hdc = CreateCompatibleDC(NULL);
       RECT rcText = {0, 0, 88, 34};
       CAtlString string;
       string.Format(L"Text String occupies: %d x %d pixels", rcText.right - rcText.left, rcText.bottom -;
       MessageBox(hWnd, string, L"String Size", 0);
       ShowWindow(hWnd, nCmdShow);
       return TRUE;

    This is just code I took by using Visual Studio to create a Windows Win32 project and inserting the code between “BEGIN LARRYS CODE” and “END LARRYS CODE”.  The meat of the code is just 3 lines of code.

    Even though there’s almost no code here, it still has a bug in it that was quite subtle and took me several hours to find.

  • Larry Osterman's WebLog

    Oh Wow, Dr. Horrible is AWESOME!


    Someone just pointed me to, which is Joss Whedon’s newest epic.

    The first two acts are up on the web (the final act will go up on Saturday).

    They are spectacularly cool, especially to a musical nut.  I knew that Neil Patrick Harris had great musical chops (after all, he did Assassins on Broadway) but the rest was just fantastic.


    Well worth checking out, there are some really funny bits.  They did a truly great job on it.

  • Larry Osterman's WebLog

    Whatever happened to Wave Out Mix?


    The Intertubes are all atwitter with reports that  Dell and other OEMs colluded with the RIAA to disable the Wave Out Mix option on new laptops.

    Wow, what a tempest in a teapot.  I just LOVE watching conspiracy theories as the echo chamber does it’s magic.


    And of course it’s almost certainly hogwash (I don’t know for sure, but I do know that some of the rumors are totally stupid).

    First off, what is Wave Out Mix?  It’s an option that some audio manufacturers added to their audio hardware (Creative calls it “What U Hear”).  Typically the Wave Out Mix is implemented by connecting the analog output from the DAC (Digital-to-Audio Converter) to a specific input on the ADC (Analog-to-Digital Converter) which is labeled as “Wave Out Mix”.

    If you record on the Wave Out Mix input, you will capture the samples that are being played via Wave Out.


    In Windows Vista, by default we only enable microphone, line in and digital inputs to the audio hardware (the theory being that users typically only want to be able to listen to those inputs).  If the audio solution offers other inputs, they’re still there but we bury them somewhat. 

    You can find those additional inputs in mmsys if you start the sound control panel and go to the “Recording” tab.  If you right click and select “Show Disabled Devices” you can enable those alternate inputs.

    In addition, these days many OEMs don’t bother adding the Wave Out Mix support.  It costs slightly more to order chips with Wave Out Mix support than it does to order chips without the functionality, and OEMs are incredibly cost conscious.  The other reason is that for those OEMs that implemented the Wave Out Mix with an analog tap, you can achieve almost the same results with a $2.50 analog cable run between the output and the line in input of the machine.


    Part of the reason that I know that this is just a conspiracy theory running rampant is that Windows Vista built the support for the Wave Out Mix input directly into the operating system.  If you pass the AUDCLNT_STREAMFLAGS_LOOPBACK flag to the IAudioClient::Initialize method, then the audio system will initialize the engine in loopback mode.  You can start capturing data off that IAudioClient object and you’ll get the post-mix output for the endpoint. 

    The loopback support was designed primarily for use by AEC functionality (which needs to be able to know what samples are being played), but it also allows you to perform essentially the same functionality as the Wave Out Mix hardware used to do.

    If you want to play with the loopback functionality, the WinAudio SDK sample application allows you to capture using the loopback functionality.

  • Larry Osterman's WebLog

    In which Larry goes back to college for the first time in over 20 years.


    Last weekend we dropped Daniel off at Carnegie-Mellon for summer school (the CMU drama school’s pre-college musical theater program).  It was essentially the first time I’d gone back to CMU since I graduated (we visited for a couple of hours back in 1992, but we spent most of the time visiting friends in the area and very little time on campus). 

    We got in on Friday afternoon, got our car and headed in.  I have to admit that it felt quite strange seeing all the landmarks as we drove in from the airport.  We got onto 376 and headed west towards CMU. 

    We drove around the campus pointing out all the relevant locations to Daniel and Sharron.  Then we parked the car and took an impromptu tour of the campus.

    Even after 25 years, the campus hasn’t changed very much.  They’ve built a couple of new buildings on the cut (a large swatch of lawn that runs from Forbes Ave to the Hunt Library).  I like the new performing arts center (not surprisingly, they have a killer theater), but not the new campus center (the space itself seems to be fine, I just dislike how the building looks).

    My biggest shock happened when we entered Doherty Hall.  I hadn’t realized it, but the building still had the same smell to it.  I know it’s weird, but I associate memories with odors, and Doherty has a distinct smell that is still there.  I was also surprised that they hadn’t really changed the two big lecture halls in Doherty.  We then wandered over to Science^H^H^H^H^H^HWean hall and started looking at the various professors offices.  Wean 7500 (the big lecture hall in Wean) also hasn’t changed in the past 25 years (although they did upgrade the lobby outside the lecture hall, go figure that one).

    We continued outside and eventually wandered up to Squirrel Hill to get dinner…

    Saturday was spent moving Daniel into his dorm room and attending various and sundry orientations, many of which were quite good (and some were utterly tedious).  Vaguely humorously, I ran into one father who was dropping his daughter off for the pre-college musical theater program.  He mentioned that his son was working at Microsoft for the summer :).  Strange world. 


    Sunday we went to Kennywood, which is Pittsburgh’s main amusement park (with some utterly killer roller coasters).  Fortunately it was threatening rain, so the crowds were light.  Again Kennywood is almost exactly as I remembered it; I have to say I was really impressed with what they’d done with the place – even though it’s on a major road, it feels both cozy and expansive at the same time.

    Sunday evening we went to the O’s for dinner; we’d spent the past 15 or so years raving about the place to our kids, we figured it would be a shame not to go there.  The hot dogs were just as good as I’d remembered.  After dinner, we caught up with a friend from college and spent a couple of hours catching up on old times (which wasn’t nearly enough time). 

    Monday we flew back to Seattle, we’re still tired from the trip, but it was a HUGE amount of fun.  I hadn’t realized just how much I had missed Pittsburgh all these years. 

  • Larry Osterman's WebLog

    BillG Memories, Part 2


    Not surprisingly, as a peon, I don’t get to interact with Bill very often, so my few interactions are almost by definition memorable.

    I’ve posted this story before, but it deserves to be recycled in honor of Bill’s last few days.

    This happened back in the mid 1980’s, we were doing a project review for Lan Manager 1.0 with him. 

    One portion of the meeting was about my component, DOS Lan Manager (basically an enhanced version of the MS-NET redirector, with support for a fair number of the Lan Manager APIs on the client).  My boss and I were given the job of presenting the data for that portion.

    One of the slides (not Powerpoint, it didn’t exist at the time – Lucite slides on an overhead projector) we had covered the memory footprint of the DOS Lan Manager redirector.

    For DOS LM 1.0, the redirector took up 64K of RAM.

    And Bill went ballistic.

    “What do you mean 64K?  When we wrote BASIC, it only took up 8K of RAM.  What the f*k do you think idiots think you’re doing?  Is this thing REALLY 8 F*ing BASIC’s?”

    The only answer we could give him was “Yes”J.

    To this day, I sometimes wonder if he complains that Windows XP is “16,000 F*ing BASIC’s”.

    We didn't ignore Bill's comment, btw (you never want to do that).  We worked on reducing the footprint of the DOS redirector by first moving the data into LIM Extended memory, next by moving the code into expanded memory.  For LAN Manager 2.1, we finally managed to reduce the below 640K footprint of the DOS redirector to 128 bytes.  It took a lot of work, and some truly clever programming, but it did work.

    Since the last one was recycled, here’s a bonus BillG memory.  I may have discussed this one in the past in a C9 video but I can’t find any references on my blog about it.

    Shortly after my 15th anniversary at Microsoft, I got an invitation to a dinner at BillG’s house for all the employees with more than 15 years of service (I had just squeaked into that rather elite group).  There were about 100 of us with our significant others at the dinner, and not surprisingly Bill was totally mobbed (even among groups of old-timers Bill still gets loads of people pestering him, I guess it goes with the territory).  About half way through the dinner, Bill’s daughter and her nanny came out to play on the swings before bedtime. 

    Bill immediately disentangled himself from his various conversations and went over to the swing-set and spent about 20 minutes pushing his daughter on the swings.  He could have ignored her and let the nanny deal with it, he could have simply given his daughter good night kisses and gone back to the party, but he didn’t.  He blew all these hideously senior Microsoft people off and went to spend time with his daughter.

    That was when I realized how much parenthood had changed Bill for the better.

  • Larry Osterman's WebLog

    BillG Memories, part 1…


    I’m going to be out of town tomorrow, so I won’t be able to post this on Bill’s last full time day at Microsoft, but I wanted to post a couple of anecdotes about Bill.

    This one actually comes from Valorie, it was her first interaction with Bill…


    Valorie was an intern back during the summer of 1985 in the Word group (she was working on testing Word for the ATT 3B5 minicomputer (yeah, we had a version of Word for Xenix machines back then)).


    She was late at work one night and she noticed this madman skipping down the hall leaping at the ceiling tiles trying to tip them out of their frames.  She thought this was weird, but back in those days all sorts of strange things happened.  Employees used to have softball games in the hall (which were eventually stopped when someone accidentally smashed a relight with a bat), the Windows team used to climb onto the roof of the building and have impromptu jam sessions on the roof of the building.  Stuff like that happened fairly regularly, so a crazy man running down the hall swatting at the ceiling wasn’t a big deal.

    She asked Libby, the person in the office next to her who the madman was and Libby replied: “Oh, that’s just my brother.” 

    Valorie chalked it up to nepotism – over the years were a lot of siblings working at Microsoft (just off the top of my head, I can think of at least 4 pairs of siblings working there at the time), so she thought nothing of it.


    Until a couple of days later when she noticed that her neighbors nameplate said:

    Libby Gates

    Valorie had several more interactions with Bill when she worked with Nathan Myhrvold, but this one was by far the most memorable.  I absolutely love the image of Bill Gates, skipping down the hall swatting at the ceiling, it’s SO different from the stereotypical image people have of Bill.


    I have a couple of other BillG stories I want to tell, but they’ll have to wait until I come back next week.

  • Larry Osterman's WebLog

    Hold on, Oliver the Wonder Pony and his rider are ranked 14th in the Nation?




    In the past, I've written about Oliver, the pony we bought a couple of years ago for my daughter to ride.  Sharron's long given up riding, but fortunately a young woman in our barn, Margaret Odom decided to take a flier on Oliver and the two have fallen in love.


    Margaret's been doing really well on Oliver and we've always known that she's a skilled rider and that Oliver is a talented horse, but we just got notified that she's been invited to compete for the National Junior Dressage Championships in California next weekend (June 21-22).  Margaret is one of 12 junior riders nationally to receive this invitation.

    She'll be competing in the same venue as the US Olympic dressage team will be holding the trials for the US National Dressage Team, and she'll be competing before the same judges as the National team.


    8we05 odom oliver ceb (Small)

    This is absolutely huge, and I want to give her and Oliver a huge shout out.  I'm just bummed that we can't be there to watch her compete.


  • Larry Osterman's WebLog

    Who's on that banner?


    For whatever reason, various groups at Microsoft love to run banners and posters that promote their products on campus.  I'm not sure why they do it, I'd think that their money would be better spent advertising to (say) customers as opposed to advertising to co-workers, but hey, I don't control their budget.

    Recently there's been a relatively cryptic series of banners circulating near my building that originally was a series of pictures of the back of people's heads, and recently changed to a series of faces (all with no text).

    Yesterday I was on a shuttle with one of the PMs in my group and the conversation went something like this:

    PM: Do you have any idea what those banners are advertising?

    Me: Yeah, I figured it out a couple of weeks ago on my walk. They're Microsoft Advertising.

    PM: I know it's Microsoft advertising, it's blindingly obvious that they're advertising something.

    Me: No, it's Microsoft Advertising.

    PM (somewhat exasperated): I know it's advertising.  I'm just trying to figure out what they're advertising.

    Me: Microsoft Advertising.

    PM: If you don't know, then why did you tell me you knew what they were?


    Bud and Lou would be proud.

  • Larry Osterman's WebLog

    Off to the 5th Avenue Awards tonight!


    Tonight we're going to be attending the 2008 5th Avenue High School Musical Awards show.  It's the local equivalent of the Tony awards for High School musical productions.  This year Daniel won an Honorable Mention for his performance as Brownlow in Overlake's production of Oliver!  In addition, his cast mate Nick Wright has been nominated for an award for his role as Mr. Bumble.

    It's cool to see Daniel and Nick's hard work being recognized.

  • Larry Osterman's WebLog

    News Flash: Spaces are legal characters in both filenames and passwords!


    I recently figured out a problem that I've been having with one of our internal tools.  The tool is used to automatically deploy our daily builds (extremely handy when you're doing that every other day to several test machines).  As a part of the tool, you need to include the password for a test account.

    We normally use the tool from an automatic test harness, essentially I enter the 4 or 5 parameters to the test and it automatically runs the tool (and other stuff if necessary).

    The problem I had was that I would enter my account and password but the tool kept failing after reporting invalid parameter errors.  It worked perfectly when I used a different account that is used by our testers, but when I tried using my preferred test account it kept on failing with some kind of command line parsing error.

    Eventually I tracked down the actual command line being passed by the harness into the tool and I was immediately able to see the problem.


    Being a security geek, my "password" is actually a passphrase - the theory is that passphrases are harder to crack than passwords because they are drawn from a larger dictionary.  So my passwords tend to be things like "The rain in Spain falls mainly on the plain".

    In this case, the test harness took my password and passed it to the tool as follows (assuming that the command line for the test tool is "testtool.exe -useuser <username> <password>:

    testtool.exe -useuser testaccount The rain in Spain falls mainly on the plain

    Doh!  Either the test tool or the test harness wasn't handling the spaces correctly.  I tried an experiment and ran the test tool manually:

    testtool.exe -useuser testaccount "The rain in Spain falls mainly on the plain"

    and it worked!  So it appears that the problem was that the test harness wasn't correctly handling the spaces in my password.


    So I went to the maintainer of the test harness and described the problem to him.

    His response?  "I never knew you could have spaces in a password!  Wow, I didn't even think of that."



    On Microsoft operating systems, spaces have been legal in filenames since MS-DOS 2.0 (about 1982) and in passwords since MS-NET 1.0 (about 1984).  I'm astonished that 25 years later there are people who still don't know that.

  • Larry Osterman's WebLog

    Cool Schwag :)


    Not surprisingly, I'm the security contact for my small part of the Windows organization (it's called the Devices&Media group, which is within the WEX division).  As such, I'm responsible for providing security guidance and reviewing the threat models for our group (I've done a lot of them over the past few months :)).

    Earlier this morning, one of the PMs for one of the teams in D&M stopped by my office with a thank you gift for the work I've done with his team.  He had noticed my 20 year old office tool kit and his team decided to replace it with something newer (and way cooler):



    I sent them a private thank-you, but I've got to say publicly that I'm really touched - it was extraordinarily nice of them and I truly appreciate it.



    PS: before anyone asks, the photo was taken with the toolkit resting on a test laptop (it's an old Toshiba M5).  In the background, you can see the Blibbet Hat I had made about 20 years ago at a local fair.

  • Larry Osterman's WebLog

    More proof that crypto should be left to the experts


    Apparently two years ago, someone ran a static analysis tool named "Valgrind" against the source code to OpenSSL in the Debian Linux distribution.  The Valgrind tool reported an issue with the OpenSSL package distributed by Debian, so the Debian team decided that they needed to fix this "security bug".


    Unfortunately, the solution they chose to implement apparently removed all entropy from the OpenSSL random number generator.  As the OpenSSL team comments "Had Debian [contributed the patches to the package maintainers], we (the OpenSSL Team) would have fallen about laughing, and once we had got our breath back, told them what a terrible idea this was."


    And it IS a terrible idea.  It means that for the past two years, all crypto done on Debian Linux distributions (and Debian derivatives like Ubuntu) has been done with a weak random number generator.  While this might seem to be geeky and esoteric, it's not.  It means that every cryptographic key that has been generated on a Debian or Ubuntu distribution needs to be recycled (after you pick up the fix).  If you don't, any data that was encrypted with the weak RNG can be easily decrypted.


    Bruce Schneier has long said that cryptography is too important to be left to amateurs (I'm not sure of the exact quote, so I'm using a paraphrase).  That applies to all aspects of cryptography (including random number generators) - even tiny changes to algorithms can have profound effects on the security of the algorithm.   He's right - it's just too easy to get this stuff wrong.


    The good news is that there IS a fix for the problem, users of Debian or Ubuntu should read the advisory and take whatever actions are necessary to protect their data.

Page 5 of 33 (819 items) «34567»