Posts Tagged ‘.NET’

The Russian Doll Approach to Web Services

Here's an anecdote for the WTF inbox. I assure you this is very real, but I cannot divulge any of the specifics.

Some time ago a friend of mine was talking to a web services vendor, who was explaining his versioning scheme. The vendor's approach was to make all of the web service functions accept a single parameter describing the function being called, and the version of the function requested. Prototypically:

public object Foo(FunctionCallInfo)

And what is FunctionCallInfo, you ask? Why, it is a strict XML document adhering to a schema that he would provide.

My observation, which my friend also arrived at independently, was that this person was basically creating an implementation of web services inside of web services. So nat'ralists observe, a flea / Hath smaller fleas that on him prey.

XML: the cause of, and solution to, all of your development problems.

What would do in this situation?

A Real Head-Scratcher Courtesy The CLR And Office Teams

"Why the hell is this application insisting on loading an old version of the CLR?" I'm guessing that's what you're asking yourself if you've gotten here through your search engine of choice. Well, relax. I'm about to explain.

It is reasonably well-known that there are .config file settings that can force an application to load a specific CLR version. It is also possible to write unmanaged code using the hosting API's like CorBindToRuntimeEx to bind to a specific version. I'm not talking about either of these scenarios.

There is a set of undocumented (as far as I know) registry keys that can override either of these vectors. They are located here:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\policy\AppPatch\v2.0.50727.00000

If you take a look at this key on your own machine, you'll probably see a handful of applications listed.

The root of the Microsoft Office .NET Framework version bug

Applications can specify a target version of the framework that will be loaded into the process, even if there is no .config file present, and even if you write some C++ to call CorBindToCurrentRuntime. Mscoree will simply report that the current runtime is 1.1.4322, even if the user has 2.0 installed on their machine. This is, I suppose, superfically similar to the strategy used in the Image File Execution Options built into NT.

I can see where this would be handy–presumably Microsoft has a handful of .NET 1.1 apps in the wild that showed bugs against 2.0, and it's not exactly practical or foolproof to try to drop a .config file on those apps when installing the framework (naturally, somebody can just install the application after the framework, then be puzzled as to why it isn't working).

Good solution, right? It's a shame they fouled it up.

Notice that Word and Excel are both listed as special applications on my machine. I have these values on my laptop:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\policy\ AppPatch\v2.0.50727.00000\excel.exe\{2CCAA9FE-6884-4AF2-99DD-5217B94115DF}]
"Minimum File Version Number"="11.0.0.0"
"Maximum File Version Number"="11.0.9999.9999"
"Target Version"="v1.1.4322"

It appears as though the someone is trying to force a relatively older build of Excel/Word 2003 to load v1.1. Fair enough, the Excel build on my machine is up to 11.6 at this point. Unfortunately, those developers failed miserably in the attempt. Every single other application listed under AppPatch in my registry looks like this:

"Minimum File Version"="11.0.0.0"
"Maximum File Version"="11.0.9999.9999"
"Target Version"="v1.1.4322"

When the version filter isn't specified (or actually in this case, miswritten as "Minimum/Maximum File Version Number" instead of "Minimum/Maximum File Version"), all versions of the executable will load the target version. So these keys effectively break 2.0 addins for all versions of Word and Excel.

There is an update available that fixes this issue, here. The KB article that accompanies it doesn't really explain what the issue is, which is why I've summarized it here. Office update is not exactly an automatic affair like its Windows counterpart, so this bug makes it essentially impossible to write a fault-free Office addin that targets 2.0 and does not hack up the user's registry upon installation. I can't say I advocate doing that, but I would understand if you did. As for myself, I am most likely going to target 1.1 much longer than I had hoped would be necessary.

Generic and Threadsafe Singleton Implementation

I googled around, and couldn't find a generic singleton implementation that was 1) correct and 2) met all of my needs. This is a clever approach, but unfortunately it is limited to objects that are created by calls to constructors.

So I went ahead and wrote the singleton generic that I fully expect to be included in the next BCL. (Not really. It's completely straightforward. However, the Steelers won the super bowl yesterday, so I'm not really in a modest mood.)

I started out defining a class factory type, which is responsible for creating the an instance in a purposefully vague way. I also wrote the default version which just calls new().

ClassFactory object model

/// <summary>
/// Interface for objects that create instances of
/// another type.
/// </summary>
public interface IClassFactory<T> where T : class
{
        T CreateInstance();
}

/// <summary>
/// A default <see cref="IClassFactory"/> implementation,
/// which uses a parameterless constructor to create the
/// instance.
/// </summary>
public class DefaultClassFactory<T> : IClassFactory<T>
        where T : class, new()
{
        public T CreateInstance()
        {
                return new T();
        }
}

From there, I went for the slam dunk in writing both a singleton class with a class factory and a default version that doesn't require one.

Singleton object model

/// <summary>
/// A base (or helper) singleton class. Defines the
/// singleton instance.
/// </summary>
/// <typeparam name="T">
/// The type of the singleton object.
/// </typeparam>
/// <typeparam name="class_factory">
/// The type of the class factory to use to create an
/// instance of type <typeparamref name="T"/>.
/// </typeparam>
public class Singleton<T, class_factory>
    where T : class
    where class_factory : IClassFactory<T>, new()
{
    private static object _sync = new object();
    private static T _default;

    /// <summary>
    /// Gets the singleton instance.
    /// </summary>
    public static T Default
    {
        get
        {
            EnsureDefault();
            return _default;
        }
    }

    /// <summary>
    /// Ensures that the singleton has been created.
    /// </summary>
    private static void EnsureDefault()
    {
        if (_default == null)
        {
            lock (_sync)
            {
                if (_default == null)
                {
                     CreateDefault();
                }
             }
        }
    }

    /// <summary>
    /// Uses the class factory to create the instance.
    /// </summary>
    private static void CreateDefault()
    {
        class_factory cf = new class_factory();
        T value = cf.CreateInstance();

        // This ensures that writes in the creation of
        // the default instance won't be shuffled beyond
        // the write to _default. Only matters on multiproc
        // machines where the hardware allows this. Does
        // nothing on an x86.
        Thread.MemoryBarrier();
        _default = value;
    }
}

/// <summary>
/// A basic singleton type that can be used with objects
/// that are created with a parameterless constructor.
/// </summary>
public class Singleton<T> :
    Singleton<T, DefaultClassFactory<T>>
    where T : class, new()
{
}

(For more on why I added that call to Thread.MemoryBarrier(), see this writeup.)

Here's a really simple example that does not take advantage of the customizability:

public class Foo : Singleton<Foo>
{
}

If you can't use Singleton as a base class, you have to write a little more code.

public class Foo : Bar
{
    public static Foo Default
    {
        get { return Singleton<Foo>.Default; }
    }
}

A Meandering Static Locals Story

I was writing some C# code the other day and attempted to use a static local variable. This may only be because I've been spending so much time with C++ recently, but I was very surprised to find that it didn't work. "That's a shame," I thought. It's not as though I use static locals every day. I've been using C# for a few years and I was just getting around to discovering that it doesn't support them, after all. Nevertheless, I would say I use static locals exactly when I need them.

I was sure that VB.NET supported static locals. I thought that perhaps an Object Orientation zealot decreed that they weren't going into C#, even though that would not be typical of the attitude exhibited in the most recent C# whitepapers. As it turns out, that's not what happened at all. Static locals are a compiler feature, and not something implemented on the CLR level. Paul Vick explains:

Implementing static locals in the compiler was a gigantic pain in the ass, and we had a lot of arguments about whether they were worth the effort. There are times that I haven't been entirely convinced about it, but I think my thoughts on this are changing…

I suppose I have already conceded that there are more important things to spend time on. In the same post Paul discusses the relative merits of the keywords in either language.

We also felt that “Shared” is a lot more descriptive than “Static,” and I wonder whether C# would have chosen that term if they hadn't been stuck with the legacy of C, but… This is probably the most painful keyword divergence between the two languages in terms of documentation.

Something of a silly discussion, I think, since VB is teeming with its own historical oddities (to wit: Dim intArray(0) As Integer). But this does remind me of a story.

A while back I was debugging an odd issue where users of a web application were seeing each other's data "randomly." Our application has a set of links on one side of it that are customized to relate to the entity the user is viewing. A typical bug would be:

The top half of the links relate to entity 'A' (which is the right one), but the bottom half of the links relate to entity 'B,' which I was not looking at.

Compared to some other bugs I have worked on, this one was a piece of cake. I figured out pretty quickly that the developer of the control in question had written a big section of variables that looked like this:

Public Shared A As Integer
Public Shared B As String
Public Shared C As String
' …

These were used in the process of rendering the hyperlinks. I asked the developer why he'd done this, but he didn't know why. He had just seen the word "Shared" associated with member declarations in the past and thought that he needed to put it there.

He was typically more informed about keywords than this, so telling him that Shared was like "static" in other languages brought instant recognition. In fact he changed the code so that it looked like this (I'm doing this from memory, but I think this is pretty faithful to the original treasure):

' Shared == Static!! Shared variables are static!
Public A As Integer
Public B As String
Public C As String
' …

Faking Multiple Inheritance with Event Handlers

I'm going to take a page from the Book of Darrel and post some design patterns whenever I realize that I'm using them. I'd like to be careful because I think that there are a few camps when it comes to design patterns:

  1. Design patterns are very important, very specific, and are a great thing to quiz people about in an interview.
  2. Design patterns are more of a feel thing, something that is figured out when you're factoring code. There is no way you will not discover these on your own, if you are experienced and smart.

I lean to the second category. The quizzers tend to be solipsists and may know little else (you'll see the same attitude with plenty of other development topics).

Now that you know how to take my writing about design patterns, let's suppose that you want to make a Windows form that becomes a little translucent when it is inactive. That may or may not be annoying, but there is a very straightforward way to make it happen:

// Form that becomes transparent when it is inactive
public class Foo : Form
{
    private const double c_InactiveOpacity = 0.25d;
    private double _prevOpacity;

    protected override void OnDeactivate(EventArgs e)
    {
        _prevOpacity = this.Opacity;
        this.Opacity = c_InactiveOpacity;
        base.OnDeactivate(e);
    }

    protected override void OnActivated(EventArgs e)
    {
        this.Opacity = _prevOpacity;
        base.OnActivated(e);
    }

    public Foo()
    {
        _prevOpacity = 1.0d;
    }
}

Which works fine, unless you want TWO forms that do that, the second with a special base class not related to the heirarchy of the first.

public class Foo2 : SpecialForm
{
    // criminy
}

This conundrum could be resolved in a few ways:

  1. Ctrl+C, Ctrl+V.
  2. Multiple base classes.
  3. What I am going to call the "Extender Pattern."

If you picked the first option, I think it'd be better for both of us if you unsubscribed from my feed. The second option would work fine, but CLR languages don't support it. Some days this bothers me, but most days I think it's a good thing. Especially when I factor a solution that is just as elegant.

I'm calling that solution the "Extender Pattern" without bothering to find out if anyone has used this term to describe anything else. As I explained above, this is more about artistic sensibility than it is about hard rules and book learning. Not that I'm anti-book learning.

The basic idea is this: you have a set of components that support certain properties, methods, and events. The forms, in this case. You add in to the mix a set of small objects whose only responsibility is to wait for events from the components and make very directed changes to them.

So here is such a class for the problem stated above:

// Alters the target form's transparency level
// when it is activated/deactivated.
public class TransparencyExtender
{
    private Form _target;
    private double _prevOpacity;
    private const double c_opacity = 0.25d;

    public TransparencyExtender(Form target)
    {
        _target = target;
        _prevOpacity = target.Opacity;
        target.Activated +=
             new EventHandler(Activated);
        target.Deactivate +=
             new EventHandler(Deactivate);
    }

    void Deactivate(object sender, EventArgs e)
    {
        _prevOpacity = _target.Opacity;
        if (_prevOpacity >= c_opacity)
        {
            _target.Opacity = c_opacity;
        }
    }

    void Activated(object sender, EventArgs e)
    {
        _target.Opacity = _prevOpacity;
    }
}

Given this, we can write our forms very easily:

public class Foo : Form
{
    private TransparencyExtender _tExt =
        new TransparencyExtender(this);
}

public class Foo2 : SpecialForm
{
    private TransparencyExtender _tExt =
        new TransparencyExtender(this);
}

Keep in mind that I am not claiming that this is original. It's really the same as a small secondary base class in C++. However, I think there's value in looking at the same problem in different ways.

In a real application I'm working on, I've written a handful of other window/control styles that can be applied and removed on the fly or from the designer. Again, not original, but I like my little framework. Perhaps I'll post this someday, or turn it into a product.

I like event/message-driven programming the more I try to use it. I'm using Windows Forms as an example here, but it would be wrong to assume that's the only place this could be applied. I've done the same kinds of things in ASP.NET.

Concurrency Approaches Contrasted

Here are a few roughly-equivalent class declarations using different languages and libraries. I say "roughly equivalent" because the implementation details and performance characteristics may actually be quite different in each case. However, the end result of each is that a function on a member variable is called in a non-blocking fashion, synchronized (presumably against other operations on the same class) with the use of some resource A.


// Vanilla C# with locks
public class FooBar
{
    private object A = new object();
    private T _member = new T();
    private delegate void FooBarDel();

    public void Foo()
    {
        FooBarDel del = new FooBarDel(FooBar);
        del.BeginInvoke(
          new AsyncCallback(FooBarDone), del);
    }

    private void FooBar()
    {
        lock(A)
        {
            _member.DoSomething();
        }
    }

    // You can typically get away without this, but
    // the documentation recommends otherwise.
    private void FooBarDone(IAsyncResult r)
    {
        FooBarDel d = r.AsyncState;
        d.EndInvoke(r);
    }
}

// Comega using a chord join pattern
public class FooBar
{
    private T _member = new T();
    private async A();
    public async Foo() & A()
    {
        _member.DoSomething();
        A();
    }

    public FooBar()
    {
        A();
    }
}

// C# 2.0+ using CCR
public class FooBar
{
    private T _member = new T();
    private Port<int> _p = new Port<int>();

    public void Foo()
    {
        _p.Post(1);
    }

    public FooBar()
    {
        activate(!_p.with(delegate(int i)
        {
            _member.DoSomething();
        }));
    }
}

Looking at the other two examples I think it's clear that C# as it stands today is lacking. That's not exactly a groundbreaking statement, I realize, but I haven't seen many examples putting all of these together in one spot.

Comega is very elegant in a situation as simple as this. CCR also seems less mistake-prone than the plain C# version, but the example I picked isn't where CCR really shines.

(One thing I should say is that I'm not sure that the CCR example is correct or even compiles, since the library isn't public yet. I worked this out from reading the whitepaper [pdf]. It's only a few pages, so I recommend giving it a read.)

The goal of CCR has been to allow complex constructs such as this (also from the whitepaper) to be made easily, and dynamically if necessary:


    // The finish operation or the update operation
    // execute with exclusive control, whereas the
    // GetState and QueryState operations execute
    // concurrently. Operations of either type are
    // interleaved safely (using the '^' operator).
    activate(exclusive(p.with(DoneHandler),
        !p.with(UpdateState))
        ^
        concurrent(!p.with(GetState),
        !p.with(QueryState))
    );

Comega, on the other hand, provides static language features. The good news is that since CCR is just a library, it would be usable from a future C# (4.0, one would hope) that incorporated some of the ideas in Comega at the language level for the easier cases.

I had thought it was a shame that none of the Comega concurrency constructs had made it into the 3.0 C# specification. However, with CCR I think I can see why this is the case. CCR, or something like it, should offer a lot of power and flexibility well within the 3.0 timeframe without taking the risk of baking the 'wrong' keywords into C# itself.

Wrote a Concurrency Library for Everyone

Herb Sutter says the concurrency revolution is coming. This guy says, “*** you!! the concurrency revolution is coming!”

That is the kind of attitude we need in the industry. We need more in-your-face greeks and fewer genial mustachioed C++ architects. Call me crazy.

I know this is the type of enthusiasm that is typically found in insane people building anti-gravity machines in their backyards, but I think these guys might be on to something with their Concurrency and Coordination Runtime (CCR).

I highly recommend watching the video–even if you have no idea what these people are talking about. Seriously mind-blowing stuff.

Making a DataSet Read-Only

Let's say you're writing a component that makes a DataSet available to a number of clients. The DataSet is expected to persist in your application for a while, and be used in code written by many different developers.

You could carefully craft an email explaining that,

Hey everybody, this DataSet is shared. Please don't change the data in it for the purposes of your own piece of the application. That could create some odd bugs that would be really hard to track down. If you need to do something like that, please make a copy of the DataSet first.

I suppose you could do that, if you wanted to waste your time. You could always create a copy of the DataSet before handing it over to anybody, but that may introduce some unnecessary performance issues if the DataSet is large. It feels a little like punishing everyone for the bad behavior of a few. If you wanted to actually prevent such problems, you could write a clever class like this that acts like a "lock" on the DataSet.

/// <summary>
/// Class that ensures that clients keep their pesky hands
/// off of a particular dataset.
/// </summary>
internal class DataSetLock
{
    [Conditional("DEBUG")]
    public static void Install(DataSet ds)
    {
        if (ds == null)
        {
            throw new ArgumentNullException("ds");
        }
        EventHandler thrower = delegate(object sender, EventArgs e)
        {
            string msg = string.Format(
                "You can't change: {0}.", ds.DataSetName);
            throw new InvalidOperationException(msg);
        };

        foreach (DataTable t in ds.Tables)
        {
            t.RowChanging += new DataRowChangeEventHandler(thrower);
            t.RowDeleted += new DataRowChangeEventHandler(thrower);
            t.ColumnChanging += new DataColumnChangeEventHandler(thrower);
            t.TableClearing += new DataTableClearEventHandler(thrower);
            t.TableNewRow += new DataTableNewRowEventHandler(thrower);
        }
    }
    private DataSetLock() { }
}

The "lock" is really an anonymous method that we attach, willy nilly, to all of the change events in the DataSet. We use lexical closure to add the DataSet name passed in to the exception message dozens of caffeine-addled developer brains will be processing shortly. [Note: if you don't think it's lexical closure, go talk to this guy. He's really into the topic.]

I put the ConditionalAttribute on the Install method as well, so as long as you have reasonably good testing coverage this check will just be compiled away in retail code.

Here's a quick usage example:


static void Main(string[] args)
{
    DataSet ds = new DataSet();
    ds.DataSetName = "My Data Set";
    DataTable t = ds.Tables.Add();
    t.Columns.Add("foo", typeof(string));

    DataSetLock.Install(ds);

    // Pow!
    t.LoadDataRow(new object[] { "asdf" }, true);
}

This prints:

System.InvalidOperationException: You can't change: My Data Set.

Enjoy.

Monad Script to Scrub Perfmon Output

Here's the scenario: I had about eight hours of perfmon output, for several hundred counters sampled once per second. I wanted to put this into a database already containing the parsed IIS logs from the same machine, to try to correlate some of the resource utilization peaks with URL's.

The only snag was that Microsoft's LogParser couldn't handle the CSV files that perfmon generated. The input lines were far too long for it.

The call is from heroism. Will you accept the charges?

The solution I came up with was to hack together an MSH script that processed the files. It's not pretty (because it didn't have to be), but here it is.


#
# trim-perflog.msh
#   This pares down a set of enormous perfmon logs to a
#   size that can be managed by the Microsoft LogParser.
#
#   This finds the column indices that we're interested in,
#   then runs through each line in the input CSV file(s)
#   and pulls them out.
#

# The counters in the perfmon trace that we're interested in.
#
$counters =
"(PDH-CSV 4.0) (Eastern Standard Time)(300)",
"\\machine\.NET CLR Exceptions(w3wp)\# of Exceps Thrown / sec",
"\\machine\.NET CLR LocksAndThreads(w3wp)\Contention Rate / sec",
"\\machine\.NET CLR Memory(w3wp)\% Time in GC",
"\\machine\.NET CLR Remoting(w3wp)\Remote Calls/sec",
"\\machine\Process(w3wp)\Page Faults/sec",
"\\machine\Process(w3wp)\% Processor Time",
"\\machine\Process(w3wp)\% User Time",
"\\machine\Process(w3wp)\% Privileged Time",
"\\machine\Process(w3wp)\Private Bytes";

# Prettier names for the counters.
#
$columnAlias = "time", "exceptionsPerSecond",
"contentionPerSecond", "pctTimeInGC",
"remoteCallsPerSecond", "pageFaultsPerSecond",
"pctProcessorTime", "pctUserTime",
"pctPrivelegedTime", "privateBytes";

# Returns an array that contains the index of each of the
# $counters in the csv.
#
function getPerflogIndices
{
    param([System.String]$columns)

    $tokens = $columns.Split(',');
    for($i = 0; $i -lt $tokens.Length; $i++)
    {
        $t = $tokens[$i];
        $t = $t.Substring(1, $t.Length-2);
        $index = -1 ;
        for($j = 0; $j -lt $counters.Length; $j++)
        {
            if($t -eq $counters[$j])
            {
                $index = $j;
            }
        }
        if($index -ge 0)
        {
            write-object $i;
        }
    }
}

# writes a CSV line using the values in $array.
#
function write-array
{
    param([System.IO.StreamWriter]$writer, $array)
    $j = 0;
    $last = $array.Length;
    foreach($a in $array)
    {
        $writer.Write($a);
        if($j -ne $last)
        {
            $writer.Write(",");
        }
        $j++;
    }
    $writer.WriteLine();
}

# Writes a single line to the result CSV file.
# This requires:
#    $writer  - The output stream.
#    $ln      - A single line read from
#                the input stream.
#    $indices - The column indices of the
#                  subject perfmon counters.
#
function write-csv-line
{
    param([System.IO.StreamWriter]$writer,
       [System.String]$ln, [System.Object[]]$indices)

    $vals = $ln.Split(',');
    $j = 0;
    $last = $indices.Length - 1;
    foreach($i in $indices)
    {
        $writer.Write($vals[$i]);
        if($j -ne $last)
        {
            $writer.Write(",");
        }
        $j++;
    }
    $writer.WriteLine();
}

# Trims down the input CSV file. If $names is True,
# writes the names of the columns as the first line
# in the output.
function trim-perflog
{
    param([System.IO.FileInfo]$in, [System.Boolean]$names)

    $r = $in.OpenText();
    $ln = $r.ReadLine();
    $indices = getPerfLogIndices $ln;

    $wr = [System.IO.File]::AppendText($out);
    if($names)
    {
        write-array $wr $columnAlias;
    }
    while($r.Peek() -ge 0)
    {
        write-csv-line $wr $r.ReadLine() $indices;
    }
    $wr.Close();
}

$out = "c:\perflogs\output.csv";

trim-perflog c:\perflogs\prod_000005.csv True
trim-perflog c:\perflogs\prod_000006.csv False
trim-perflog c:\perflogs\prod_000007.csv False

The Debugger Extension, Part 6 - Scanning Threads

The Debugger Extension

We already have an extension that might be pretty useful in some scenarios, but another common situation is determining what a particular thread is doing. You might want to look at instances of a particular type on the stack of a thread that is maxing out your CPU, or you might want to look at two or more threads that appear to be deadlocked.

We can get something like this out of the extension we have written already if we alter it to search only the stack for the current thread. How do we do that? On an x86 machine, the stack looks something like this:

Thread Stack

Finding one end of the stack region is very easy. The top of the stack (but the "bottom" address, since the stack grows down) should always be in the ESP register. To get the base of the stack we need to be able to read an NT structure called the Thread Environment Block, or TEB.

The TEB is defined as follows in the Platform SDK.

typedef struct _TEB {
    BYTE Reserved1[1952];
    PVOID Reserved2[412];
    PVOID TlsSlots[64];
    BYTE Reserved3[8];
    PVOID Reserved4[26];
    PVOID ReservedForOle;
    PVOID Reserved5[4];
    PVOID TlsExpansionSlots;
} TEB, *PTEB;

We're all ecstatic that the TEB is undocumented when this allows the kernel team to freely implement new features, I guess, but this is no help to us right now. This is closer to what the TEB header really looks like.

typedef struct tagTEB_INTERNAL
{
    DWORD dwExceptionList;
    DWORD dwStackBase;
    DWORD dwStackLimit;
    DWORD lpTIB;
    DWORD lpFiberInfo;
    DWORD lpUserPointer;
    DWORD lpSelf;
    DWORD lpEnvironmentPointer;
    DWORD dwProcessId;
    DWORD dwThreadId;
    DWORD dwActiveRPCHandle;
    DWORD lpPEB;
    DWORD dwLastError;
    // More fields follow but are not included here.
} TEB_INTERNAL, *PTEB_INTERNAL;

I took that from chapter six of Microsoft Windows Internals by Mark Russinovich. He's done many useful and awe-inspiring things besides discovering the Sony Rootkit DRM. The DbgEng SDK exposes a method to us (IDebugSystemObjects::GetCurrentThreadTeb) that makes it trivial to write a function to read in this structure in the debugger (download the source if you want to see it).

We can now write a templated search function (much like those we wrote in part four) to search only the current stack. Since the stack will contain handles/pointers to the objects, we'll also need a function that searches with a level of indirection.

// Performs a range search on the current
// thread's stack.
//
template<class search_command>
inline void SearchStack(ULONG64 pattern)
{
    TEB_INTERNAL teb = {0};
    HRESULT hr = GetCurrentTEB(&teb);
    if( FAILED(hr) )
    {
        Out("Could not retrieve the TEB.\n");
        return;
    }

    ULONG64 esp = 0;
    hr = m_Registers->GetStackOffset(&esp);
    if( FAILED(hr) )
    {
        Out("Could not read the stack pointer.\n");
        return;
    }
    Out("Thread %d:\n", teb.dwThreadId);

    // Thunk the dword to a 64-bit integer.
    // Otherwise we'll take the previous dword
    // field in the TEB structure with us into
    // the Search call.
    ULARGE_INTEGER li = { teb.dwStackBase, 0L };
    this->SearchPointers<search_command>(
         pattern,
         esp,
         li.QuadPart);
}

// Searches for the pattern with a level
// of indirection.
//
template<class search_command>
inline void SearchPointers(ULONG64 pattern,
     ULONG64 start, ULONG64 end)
{
    search_command sc;
    int hits = 0;
    for(ULONG64 offs = start;
        offs <= end;
        offs += m_PtrSize)
    {
        ULONG64 ptr = 0;
        HRESULT hr = m_Data->ReadPointersVirtual(
            1L, offs, &ptr);
        ULONG64 ptrVal = 0;
        hr = m_Data->ReadPointersVirtual(
            1L, ptr, &ptrVal);
        if( hr == S_OK && ptrVal == pattern )
        {
            if( sc.HandleMatch(ptr) )
            {
                ++hits;
            }
        }
    }
    sc.ShowResults(hits);
}

The EngExtCpp framework makes it very easy to add a switch to enable searching with this method:

0:000> !atstat /?
!atstat [/s] <The MethodTable for SampleApp.ArbitraryType.>
  <The MethodTable for SampleApp.ArbitraryType.>
  /s - Searches only the current stack.
Displays statistics about ArbitraryType instances in memory.

That lets us build some cool composite commands in WinDbg like this:

0:000> ~*e!atstat /s 009131b0
Thread 2624:
Searching for ArbitraryTypes...
--------------------------------------------
01272bf8 : Purple
01272bf8 : Purple
01272bdc : Blue
01272bf8 : Purple
--------------------------------------------
Found 4 total instances.
Totals:
  Blue: 1
  Purple: 3

Thread 1924:
Searching for ArbitraryTypes...
--------------------------------------------
--------------------------------------------
Found 0 total instances.
Totals:

Thread 2096:
Searching for ArbitraryTypes...
--------------------------------------------
--------------------------------------------
Found 0 total instances.
Totals:

I think that's where we'll leave it for now. Not bad for a day of work or so, when you consider that we're empowered to crank out similar utilities in no time at all. I hope you've enjoyed the debugger extension series.