WinDbg !locks command broken

It seems that the extremely useful !locks command is broken in 6.11.1.40x, the current and previous release of WinDbg from the debugging tools for Windows.

You’ll get errors like:

0:007> !locks
NTSDEXTS: Unable to resolve ntdll!RTL_CRITICAL_SECTION_DEBUG type
NTSDEXTS: Please check your symbols

The suggested solution seems to be to roll-back to version 6.10.3.233, available from here, or you can just replace the version of ntsdexts.dll in the c:\program files\debugging tools for windows (x86)\winxp directory with the one from the earlier release.

Judging by the error message, I’m guessing that the new version may work if you happen to be using a debug (checked) build of the Windows kernel, but I don’t have one around to try it with.

Posted in Debugging, WinDbg | Tagged , | 2 Comments

F# May CTP released

Well, what are you still doing here, get over to Don Syme’s blog and download it…!

Posted in .NET, F#, Software Development | Tagged | Leave a comment

IL analysis using F#

I recently needed to determine which functions were called by some of our F# code. Naively, you can use existing tools like ildasm, to disassemble a .NET DLL and then search the resulting IL source code for references. The obvious problem here though, is that you’re going to include all references whether or not they’re actually called. In some circumstances this isn’t too bad, but in our case we pull in a great deal of shared library code, so you’re likely to get lots of false positives.

There are some other options to more accurately determine whether the method you’re interested in is actually called: run the code, or “almost” run it, by simulating the operation of the CLR. To radically understate; this is quite a lot of work. Yet another option is to statically analyse the original source code. This is generally easier than dynamic evaluation, but there are some serious and well known problems doing it exhaustively, that can result in the complexity eventually converging with that of full dynamic analysis.

So broadly, we have 3 types of approches:


Approach


Implementation


Accuracy

Disassembly Easy Superset
Dynamic analysis Hard Exact
Static analysis Medium Medium

Anyone for a trade-off? Unsurprisingly I decided to look at implementing the third option. Although static analysis is normally performed on the source code itself, it’s actually easier for us to use the generated IL, it certainly requires less gnarly parsing. We can also take some short cuts based on the fact that we’re analysing F# code, more on that later.

We can use F#’s discriminated unions – a type that is constructed from one of many possible options – to describe the universe of IL instructions in a pretty concise way, e.g. (a partial example):

type inst =
    | Nop
    | Break
    | Ldarg_0
    | Ldc_i4 of int32
    | Newobj of meth
and field = FieldInfo
and meth = MethodBase
and typ = Type

This allows us to construct instances of inst by doing something like this in fsi (F# interactive):

> let i = Ldc_i4 2;;
val i : inst

You may have noticed that as well as the instructions that take simple types like int32, we also have ones that accept meth, which is an alias for System.Reflection.MethodBase, the base class for all methods, including constructors, which is what’s used to construct a Newobj.

Now we have this discrimated union defined, we need a way to build instances of it. In the IL byte stream, instructions are stored as opcodes, an unsigned 16bit integer. Firstly we need to get the raw bytes representing the IL. Using Reflection, it’s fairly easy given m of type MethodInfo:

    let body = m.GetMethodBody()
    let ilbytes = body.GetILAsByteArray()
    let ms = new IO.MemoryStream(ilbytes)
    ...

So now we have a stream of bytes, and we can use functions from System.IO to extract information in various sized pieces:

    let getByte _  = (byte (ms.ReadByte()))
    let i2 _ = readInt16 ms
    let i4 _ = readInt32 ms
    ...

As Harry Hill would say; “well, you get the idea with that”. It’s worth noting that these functions have a dummy argument (indicated by the
underscore). This is required because they have a side effect – reading from the stream, changing it’s state – which is not obvious to the compiler, so if we omitted it the function would only be called once. Although adding the dummy arg is required, it does have the unfortunate consequence that we have to pass something (normally unit) which can look a little ugly in the normally terse F# world.

As the ECMA CIL spec describes, IL opcodes consist of either 1 or 2 bytes, in which case the first is always 0xFE. Now we can begin to implement something serious. Given ms of type MemoryStream we can write something that will convert it to instructions:

    match ms.ReadByte() with
    | 0xFE as lb ->
        // Two byte instruction, read further byte
        let hb = getByte()
        let i = ((uint16 lb) <<< 8 ) + (uint16 hb)
        let t =
            match i with
            | 0xfe01us -> Ceq
    | _ as b ->
        let t =
            match b with
            | 0x0 -> Nop
            | 0x1f -> Ldc_i4_s (getByte())
            | 0x20 -> Ldc_i4 (i4())
            | 0x73 -> Newobj (meth())

So we now have a function that will go from a method to a list of opcodes and operands (MethodBase -> inst []). These are essentially the same steps we would perform if we were writing an interpreter for a textual language; taking the source and transforming it into an abstract syntax tree. In that case it’s a tree rather than a list, but the next step is pretty much the same anyway: we pattern match over it. This is the point where we can decide how we want to interpret the instruction stream.

        insts
        |> List.map (fun inst ->
            match inst with
            | Newobj(meth) ->
                printf "NEW: %s.%s\n" meth.DeclaringType.Namespace meth.DeclaringType.Name
            | _ ->
                ()

Here we need to make some compromises based on the problem domain. I’m not trying to create a general purpose static analyser, but one that will work on object code in a certain format – that generated by the F# compiler. As such we make some assumptions and use some knowledge about the internals of the compiler to get the result we’re after. To be specific we’re relying on the fact that the compiler generates types for closures, and we assume that closures will always be called, even though in reality they needn’t be.

So based on this, we can put together something that, given an entry point – a particular method on a type – can recurse through the code, following references to other methods and types via the Newobj, Call, Calli and Callvirt instructions. This will build up a graph of all types referenced directly from our starting point. We also use our intimate knowledge of the purpose of F#’s FastFunc type (from which all functions are derived) and always follow its Invoke method if we find an instance of that type, even if it’s not directly referenced.

There are some major caveats. Anything accessed purely via reflection will not be detected. And polymorphic objects passed in and accessed via interfaces will also be missed. Also, I don’t attempt to do full flow analysis; e.g. following branch instructions etc, as this isn’t a common pattern in fsc-generated IL.

Luckily in the particular cases I’m looking at, these shortcomings don’t have a significant impact. Instead, we end up with a reasonably straight-forward and useful way of determining whether a particular function is called. It’s already been used in anger to determine whether a buggy function was referenced from some release-candidate software.

As a little post-script: rather than writing your own library from the ground-up to do this, there are some “off-the-shelf” solutions that you can try. Notably the recently released CCI, a common compiler infrastructure out of Microsoft Research, that allows you to reverse engineer IL metadata. I haven’t had a chance to have a good look at this yet, but it seems to do what we need for call graph analysis. There’s also an API called AbstractIL – in the absil.dll assembly – that ships with and is used internally by the F# compiler toolset. This looks extremely powerful, but the API is complex and the documentation is poor. Depending on exactly what your motivation is for looking at this stuff, it’s worth checking if these ready-made libraries will do what you need.

Posted in .NET, F#, Software Development | Tagged , , | 2 Comments

Installing Windows SDK breaks F# Visual Studio integration

Beware! If you install the Windows SDK – perhaps to get access to the interesting looking WPF performance tools – you’ll find that it hoses your F# Visual Studio integration. I found that it causes intellisense tooltips to stop appearing, and the integrated F# interactive to crash Visual Studio. Both of these issues are a real pain; especially the inability to see the inferred types “live”, which is pretty much essential for F# development – where the focus is on compile time correctness.

I remembered seeing a post on that Windows SDK blog that I’d come across relating to a similar issue with the XAML editor (I’ve been doing some work with WPF recently, more on that in a later post) so thought I’d try the steps they recommend, in short, re-registering TextMgrP.dll:

regsvr32 "%CommonProgramFiles%\Microsoft Shared\MSEnv\TextMgrP.dll"

…and all my problems went away. Hope you find this useful.

Posted in F#, Visual Studio | Tagged , , , , | 5 Comments

Verifying dynamically generated IL

It’s safe to assume that when you use the C#, F# or (heaven forfend) VB.NET compilers, the IL generated for you will be correct. But, if you’re using Reflection.Emit to generate code “by hand” in a dynamic method or assembly it can be difficult to identify problems with the IL you emit. In the majority of cases the runtime will simply throw an InvalidProgramException. This is of course, exactly as you’d expect, as the JIT compiler (which generates architecture-specific machine code from the IL) is intended to be highly performant, rather than robust to errors which should’ve been dealt with earlier in the tool chain.

So what tools can you use to troubleshoot problems with dynamic IL? In a word: peverify.
Read More »

Posted in .NET, F#, Software Development | Tagged , , , , , | 2 Comments

Implementing INotifyPropertyChanged with F#

I like F# for a lot of things, but, man, is it a pain to support events. In C# it’s trivial to implement an interface like INotifyPropertyChanged consisting only of an event, but in F# you have to jump through some hoops to map native functions to delegates/events. F# is generally much terser than C# and other .NET languages, but not in this case. After spending some time the other day trying to figure out the right combination of syntax and helper functions (and unsucessfully googling for it), I thought I’d upload a bare-bones implementation here as an aide-memoire.

open System.ComponentModel
 
type MyObject() =
    let mutable propval = 0.0
 
    let event = Event<_, _>()
 
    interface INotifyPropertyChanged with
        member this.add_PropertyChanged(e) =
            event.Publish.AddHandler(e)
        member this.remove_PropertyChanged(e) =
            event.Publish.RemoveHandler(e)
 
    member this.MyProperty
        with get() = propval
        and  set(v) =
            propval <- v
            event.Trigger(this, new PropertyChangedEventArgs("MyProperty"))

It turns out that in F# version 1.9.6.16 there’s a slightly more concise syntax for this, as pointed out by Rei in the comments (thanks!). It uses the CLIEvent attribute to hook up the .NET event:

open System.ComponentModel
 
type MyObject() =
    let mutable propval = 0.0
 
    let propertyChanged = Event<_, _>()
    interface INotifyPropertyChanged with
        [<clievent>]
        member x.PropertyChanged = propertyChanged.Publish
 
    member this.MyProperty
        with get() = propval
        and  set(v) =
            propval <- v
            propertyChanged.Trigger(this, new PropertyChangedEventArgs("MyProperty"))
Posted in F# | Tagged , , | 4 Comments

Visual Studio Toggle Brackets Macro

After using a F# heavily for a while, I often found myself wanting to add brackets (or rather, parentheses) around some text. This is normally when adding a type specification to an argument in order to be able to use dot notation, e.g. going from:

let typeName t = t.Name

which causes “error FS0072: Lookup on object of indeterminate type based on information prior to this program point”, to the correct:

let typeName (t:Type) = t.Name

(These are obviously simplistic examples!)

So I broke out the Visual Studio macro editor for the first time in a while, and put together something to toggle brackets around the currently selected text. It’s naive, but, combined with Shift+Alt+Left Arrow to select the previous word, it’s effective:

Public Sub AddBrackets()

Dim s As Object = DTE.ActiveWindow.Selection()

If s.Text.StartsWith(“(”) And s.Text.EndsWith(“)”) Then

s.Text = s.Text.Substring(1, s.Text.Length – 2)

Else

s.Text = “(” + s.Text + “)”

End If

End Sub

Copy this text into a module within your macro project, and assign a suitable keystroke using Tools|Customize|Keyboard.

Posted in F#, Visual Studio | Tagged , , , , | Leave a comment

BattleFingers is here!

BattleFingers text

Well, I’ve done it: I’ve got my first game live on the AppStore. It’s been an interesting journey. I’m terribly bad at getting my hands on devkits and SDKs, having a play with them and then not doing anything constructive. This dates way back to things like the Playstation NetYaroze, which was pretty expensive, and with which I failed to produce anything concrete. So this time around all the pieces were in place: shiny new “gaming” kit, interesting SDK, low cost of entry. I was determined to create!

I’ll be making a series of posts on the process and details of creating it, in the interest of sharing the fun. In the meantime, you can find out more about the game here.

Posted in Gaming, Mac, Software Development, iPhone | Tagged , | Leave a comment

Twitter

I’m on twitter! Expect some random thoughts on software development and the like: http://twitter.com/voyce

I’ve added a widget to the sidebar to give you a flavour.

Posted in Uncategorized | Tagged | Leave a comment

F# CTP and Visual Studio integration

Just a quick note on an inconsistency in the F# 1.9.6.2 (CTP) release and it’s integration into Visual Studio: be aware that the standard VS environment variable $(TargetPath) is not getting set to what you’d expect. Rather than containing the full path to the output file it references the intermediate file typically in \obj\bin.

This can be a problem if you’ve got any tools set-up that try and do something with the built binary. Normally you can assume that referenced assemblies will also be in that directory, so you’d be able to load and execute your built file. If you’re pointing to a copy in the intermediate directory, that’s not the case.

It looks like it’s just an artifact of the way they’ve integrated the F# compiler (fsc.exe) with msbuild. The F# team are aware of this bug, so hopefully it’ll be fixed in the next drop.

Posted in F# | Tagged , , , , | Leave a comment