Sunday, January 20, 2013

My blog has a new home at baulig.net

This weekend, I signed up for AWS and create an EC2 micro instance running Wordpress.  After playing around with it, I started to really like Wordpress because of its great plugin system - especially Crayon Syntax Highlighter.

So I got myself a domain name from GoDaddy and moved my blog to its new home at http://baulig.net/.

Crayon Syntax Highlighter makes it so much easier to quickly cut&paste some C# or XML into a blog post, without worrying about any HTML escaping or anything like that.  And it also looks much better - for instance, compare my latest WCF Config post on the old and the new blog.

Saturday, January 12, 2013

WCF Configuration without Configuration

Before Christmas, I worked on automatically creating WCF configuration from a WSDL document.

I got until the point where I can successfully create a ServiceEndpoint and its Bindig from the WSDL (ServiceContractGenerator.cs:843 in my baulig/work-wsdl-config2), but run into several problems when creating the .config file.

The first issue I ran into was merging the new configuration items that were generated from the WSDL into an existing app.config file. The main problem is distinguishing elements that the user manually put into the app.config, new items from the WSDL file and items from the WSDL file that were previously added automatically (running "Update Service Reference" twice in MonoDevelop shouldn't add configuration twice). Visual Studio uses the configuration.svcinfo / configuration91.svcinfo files to cache the elements that it added to the app.config, but their format is undocumented (it's XML, but there's a checksum element, I've no idea how to generate that and didn't find any information on the internet).

The second big issue is automatically configuring a WCF client without System.Configuration, so it can be used in MonoTouch.

Microsoft uses some .xml inside a .zip file for Silverlight (but I also couldn't find any specification for the format) and Mono is using the SilverlightClientConfigLoader class to parse an file. But this class is incomplete, only handles the very basic cases and doesn't provide any useful error reporting to the user.

And the third big issue is that our System.Configuration implementation is buggy and the many of the System.ServiceModel.Configuration APIs unimplemented.

Requirements

So I was thinking about a solution which satisfies the following requirements:
  1. Does not use Reflection or System.Configuration, so we can use it for the mobile platform.
  2. Allows automatic configuration of a WCF client from a WSDL document - so you simply do "Add Service Reference" in MonoDevelop and it sets you up just like Visual Studio does, without any manual editing of configuration files.
  3. Is at least somewhat compatible with the app.config format.

The Solution

The solution I finally came up with was a custom XML file format.

It is very similar to the section in the app.config file, but not identical. The main difference is that the name of each XML element is unique and doesn't depend on the context it's used in.

For instance, this is the app.config file format:

<bindings>
  <basichttpbinding>
    <binding allowcookies="True" closetimeout="00:15:00" />
  </basichttpbinding>
  <custombinding>
    <binding name="myCustomBinding" />
  </custombinding>
</bindings>
As you can see, the <binding> element has a different meaning depending on which section it's used in. I'm generating this:
<bindings>
  <basichttpbinding allowcookies="true" closetimeout="00:15:00">
  <custombinding name="myCustomBinding">
    <elements>
      <textmessageencoding messageversion="Soap12WSAddressingAugust2004" />
      <httptransport />
    </elements>
  </custombinding>
</bindings>
So the attribute names and their values are mostly the same, but I'm using different names for the elements to make them unique.

In addition to a reader and writer for this XML format, I'm also generating an XML Schema for it.

Basic Usage

The module has three modes of operation:
  1. Generating an XML document from a Collection. This would normally be done automatically from a tool which uses WsdlImporter.ImportAllEndpoints() to read the endpoints from a WSDL document.
  2. Reading a Collection back from the XML file. In MonoTouch, we’ll use this automatically from within the ChannelFactory initialization to create all the endpoints and bindings.
  3. Generate an XSD schema file. This is not strictly required, but I added some and constraints to sanity-check binding and endpoint names, so validating the XML document against the schema will catch some common configuration problems.

Sunday, December 23, 2012

Running a MonoMac application with a custom Mono Runtime

One situation that sometimes comes up during development is running a MonoMac application on a custom Mono Runtime.

When I did my last batch of improvements to MonoDevelop's "Add Web Reference", I had to do this a lot. Since I'm currently working on a few improvements in that area, the problem came up again, so I decided to share the magic that I'm using with you.

A MonoMac application always uses the runtime that's currently installed in /Library/Frameworks/Mono.framework/Versions/Current - and this path is hard-coded in the launcher script that it's using.

Well, I really didn't feel like manually compiling gtk-sharp and all that stuff just to quickly test something - and building and installing a new .dmg each time I changed one line of code would also be very tedious task.  All I really need to replace is
System.ServiceModel.dll, but just copying the dll for testing over the installed packages would be really ugly.

One great thing about Apple's .app's is that it bundles everything in one place, so you can easily make a backup copy of your 
/Applications/MonoDevelop.app or copy it to some other place.  So after backing it up, copied the newly compiled Add-In over /Contents/MacOS/lib/monodevelop/AddIns/MonoDevelop.WebReferences/.

That was the easy part, now I just had to make the installed /Applications/MonoDevelop.app with a different Mono runtime, which contains my System.ServiceModel.dll changes - and I didn't feel like messing without anything outside that Add-In directory.

So I took the launcher scrip from monodevelop/main/build/MacOSX/monostub.m and added some command-line arguments to run it outside the .app bundle and use an arbitrary Mono runtime.  I also setup the environment variables in a way that it still loads stuff like gtk-sharp from the installed Mono, so you don't have to manually compile all that stuff.

I put the result of this little magic into my workspace module on github: baulig/Provcon-Faust/tools/monomac-launcher.m.

You can run it like this:

monomac-launcher --mono=/Workspace/INSTALL --app=/Applications/MonoDevelop.app --exe=/Applications/MonoDevelop.app/Contents/MacOS/lib/monodevelop/bin/MonoDevelop.exe

Wednesday, December 5, 2012

WsdlExporter improvements

After last week's WsdlImporter Improvements, I have now finished another batch of changes improving the WsdlExporter.

  • We now export simple , currently supporting only those elements that WsdlImporter can import.
  • Implement  MetadataExporter.Errors and use it for error reporting.
  • Fixed WsdlExporter's caching to correclty deal with duplicate ExportContract() and ExportEndpoint() calls.
  • Emit depending on the binding's MessageVersion
    (FIXME: I didn't implement soap faults yet).
  • MetadataTests: Check whether the policy elements are correct.
  • MetadataTests: Add test containing simple [OperationContract] method for http and net.tcp; checks the /  elements.
  • New test to check WsdlExporter's behavior regarding duplicate contracts and endpoints.
  • ConnectionOrientedTransportBindingElement.cs, CustomBindingTests.cs, HttpTransportBindingElementTest.cs: Added test for custom message encodings.


  As a next step, I'll implement configuration file generation.  The idea is to make MonoDevelop's "Add Service Reference" automatically generate a configuration file, just like Visual Studio does.

 

Wednesday, November 28, 2012

Running the same NUnit tests multiple times, using different profiles

One thing I really miss in NUnit is an easy way of running the same tests multiple times using different profiles.  Ideally, there should be some way to create an abstract TestContext helper class and adding an instance of this class either as property on your [TestFixture] class or as an argument on your [Test] method.  Then, you would provide multiple implementations of the TestContext and have NUnit automatically run your tests with each of these implementations.

However, I found I cool workaround for this: you can make your test fixture class abstract and put the [TestFixture] attribute on each implementation.

I'm using this technique in Mono's WCF metadata unit tests: mcs/class/System.ServiceModel/Test/MetadataTests/ImportTests.cs is the main test fixture class and the tests inside it are run three times using a different TestContext:

  1. ImportTests_CreateMetadata.cs creates a new MetadataSet programmatically
  2. ImportTests_LoadMetadata.cs loads it from an XML file
  3. ImportTests_RoundTrip.cs creates a new MetadataSet programmatically, exports it into an XML string, then imports it back from that string
You can also make your [Test] methods virtual in the base class, then override it and add [Category] or other nunit attributes to it.

Monday, November 26, 2012

WSDL Import Improvements

A couple of weeks ago, I stumbled upon a post on stackoverflow where some guy has a problem importing a web reference with Mono.

In theory, it should be a simple problem: add a Web Reference in MonoDevelop, then copy an existing app.config file from some Windows box that's already successfully talking to that same service.  And then it should all work out of the box .... or not?

The reality is that this actually does not work.  See my answer on that stackoverflow post for the detailed technical reason.  In short, Visual Studio and Mono disagree about how to name and reference an endpoint in the app.config file.  You actually have to edit the app.config file and use the fully qualified name of your service contract interface to get this work.  Well, this sucks ...

I got busy with other things, but then picked it up again last week and investigated what needs to be done to do this cleanly in Mono.

The biggest missing piece is importing bindings and endpoints from a WSDL file, which previously was not supported at all.  Once you got that, generating the configuration is not that difficult anymore, considering that configuration support already exists in Mono.

After about a week of work, I just finished implementing some of the missing pieces in Mono's WsdlImporter.  We can now import the most basic and most commonly used bindings and endpoints from WSDL: BasicHttpBinding, NetTcpBinding and the new BasicHttpsBinding that was introduced in .NET 4.5.  One huge task was supporting WS-Policy - I only implemented the simple things here.

There are a bunch of new metadata samples and nunit tests in mcs/class/System.ServiceModel/Test/MetadataTests/, see the main commit message to find out which of these are already working.

Tuesday, November 13, 2012

Wish List for a Bug Tracking System

I don't want to say Bugzilla sucks. It has many great features and is probably one of the best Bug Tracking Systems out there.

However, there are a few things the Bugzilla developers could implement in a future version to make it even better:
  1. Auto-saved drafts: Nothing sucks more than to accidentally close your browser tab while you're writing a long bug report or comment and then all your progress is lost and you have to start over again.

    Often, you also have to lookup some external sources while writing your bug report, like looking up some reference links or generating code samples, test cases, lookup a commit id, etc.  Most of the time when I'm working with bugzilla, I have at least 3+ other tabs open in my browser and am also using at least one shell window.

    Being able to save a bug report / comment and edit it later would be really helpful here.
  2. Markup and previews: The current text-mode input really doesn't fit into the 21st century anymore.  There are many great sites such as github or stackoverflow which should how a good markup and preview could look like.

    Especially for a bug tracking system, it would be great if you could easily paste code samples and have them just look great.
  3. Editing: How often do you write a comment, then realize it has some typo in it - or you want to add something, for instance a commit id on github or something that you overlooked.
  4. Tracking sub-issues: Sometimes, additional problems that are related to the one you're currently fixing appear - either you discover them yourself or the bug reporter when he's testing your fix.  So people add comments to the bug report.  There are bugs with a lot of such comments, making it hard to keep track of which of these sub-issues are already fixed and which are not.

    And easy solution for this would be to make the initial bug report editable, allowing people to add / update sub-issues.

Tuesday, November 6, 2012

About Choice

I watched a DVD tonight. It started with the usual previews, but then - I don't even remember why I did this - I somehow saw myself pressing that 'menu' button on my remote. Well, usually this would simply produce the usual "operation prohibited by disk" message, forcing you to actually watch (or go to the kitchen and make yourself a sandwich) the previews and commercials. Not this time! There was also no annoying "FBI warning" or anything like that, pressing the menu key on my remote got me right into the DVD's main menu. But there was this menu items called "sneak peeks" and I got very curios what this could be - and I clicked on it before even watching the main feature. Well, it were these preview videos that I just skipped by pressing that 'menu' key. I really liked this :-) Dear DVD vendors: if you force people to watch your commercials before the main feature - well, then I'll simply put the DVD into the player, press Play and the main feature will be ready to be viewed when I come back from McDonald's. But if you give me the choice of watching your commercials whenever I want to - well, maybe I like your main feature so much that I'm wondering whether there's something else that I could purchase from you ...

Saturday, April 9, 2011

Limiting page faults on the HTC Desire HD

After several happy weeks with my HTC Desire HD, I made a rather shocking discovery this week:

HTC put some hack into the kernel to kill a process after encountering more than 10 page faults !

It was really hard to believe until I discovered this in arch/arm/mm/fault.c:

void
__do_user_fault(struct task_struct *tsk, unsigned long addr,
                unsigned int fsr, unsigned int sig, int code,
                struct pt_regs *regs)
{
        struct siginfo si;
        struct task_struct *g, *p, *selected = NULL;

#ifdef CONFIG_DEBUG_USER
        if (user_debug & UDBG_SEGV) {
                printk(KERN_DEBUG "%s: unhandled page fault (%d) at 0x%08lx, code 0x%03x\n",
                       tsk->comm, sig, addr, fsr);
                show_pte(tsk->mm, addr);
                show_regs(regs);
        }
#endif
        if (sig == SIGSEGV)
                tsk->segfault_count++;

        if (tsk->segfault_count > 10) {
                tsk->segfault_count = 0;
                printk(KERN_ERR "unhandled page fault at 0x%08lx, code 0x%03x\n",
                        addr, fsr);
                show_pte(tsk->mm, addr);
                show_regs(regs);

                do_each_thread(g, p) {
                        task_lock(p);
                        if (p == tsk)
                                selected = g;
                        task_unlock(p);
                } while_each_thread(g, p);

                if (selected) {
                        printk(KERN_ERR "%s: triggered too many segfaults, force killing parent: %s\n",
                                tsk->comm, selected->comm);
                        force_sig(SIGKILL, selected);
                        return;
                }
        }

        tsk->thread.address = addr;
        tsk->thread.error_code = fsr;
        tsk->thread.trap_no = 14;
        si.si_signo = sig;
        si.si_errno = 0;
        si.si_code = code;
        si.si_addr = (void __user *)addr;
        force_sig_info(sig, &si, tsk);
}

However, looking at the kernel sources wasn't that easy as it may look like - first, you have to actually get them. One of my coworkers pointed me at this interesting article:
http://www.freedom-to-tinker.com/blog/sjs/htc-willfully-violates-gpl-t-mobiles-new-g2-android-phone - and there's a link in it to a download location.

My kernel is 2.6.32.21-g1e30168, but for some reason, this doesn't work in Germany.

The entire story started about a month ago, where I discovered some very weird crashes while debugging on my device that nobody else in the team had. It was extremely frustrating for me and I kept thinking why me, what am I doing wrong here ?

After some investigation, it pretty much looked like something during variable evaluation was killing the app. We could insert a breakpoint, run to it, but it stopped at the breakpoint and I tried to evaluate some variables, the app crashes ... silently, without anything in adb logcat.

I wrote a simple test app and a soft debugger client application (both can be found in the martins-playground module on github) and soon discovered that we were only crashing during single-threaded invokes.

So what's the difference here ? Well, there's this bug in SDB - single-stepping isn't always disabled during single-threaded invokes. However, this should only impact performance and never cause the app to actually crash. But it gave me the idea ...

As a next step, I wrote a small native C application called NativeTest which installs a SIGSEGV handler and then creates 100 page faults in a loop.

The same thing can also be accomplished with something like this:


    for (int i = 0; i < 1000; i++) {
        try {
            object o = null;
            o.GetType ();
        } catch {
        }
    }

Compile something like that with Mono for Android and execute it on the device - it should not crash.

Luckily, Mono's JIT already has a feature called "explicit null checks" and I also have a patch for the Soft Debugger to check some variable instead of using page faults for single-step and breakpoint events.

However, I'm not entirely sure whether this really covers all possible scenarios where a page fault would normally be handled gracefully. And seeing something like this in their kernel also makes me a bit worried that there might be other surprises.

Monday, March 7, 2011

Connecting to the device

Today, I tried to find a good way of establishing a TCP connection to the SDB debugging session on the device.

Unfortunately, I didn't get my HTC Desire HD's Internet pass-through working. Tried on Windows 7, Windows Vista and Linux without any success. There's something very weird going on - whenever I try to activate Settings / Wireless & networks / Internet Pass-through, it says "Turning on ..." for about 1-2 minutes, then a message pops up that it can't find HTC Sync on the computer. However, internet actually does work during this time.

I'm very disappointed that this won't work, connecting the phone to the computer's network over USB would be very useful.

To make things worse, adb doesn't work while this option is activated.

Using USB tethering also isn't an option for me since this'd require the phone network be activated all the time.

Luckily, there's still the good old 'adb forward' and I just tested this with a small app.

Tuesday, March 1, 2011

Fixing the boot loader mess

After the last dist-upgrade from OpenSuSE 11.3 to 11.4, my boot loader and MBR was updated, causing me quite some headaches.

Now, I think I found the problem - my /etc/grub.conf was broken, it had a setup (hd0) line in it. I replaced that with

setup --stage2=/boot/grub/stage2 --force-lba (hd0,6) (hd0,6)
quit

I also created a script to set things up inside VMware:

root (hd1,6)
install (hd1,6)/boot/grub/stage1-isengard d (hd0) (hd1,6)/boot/grub/stage2-isengard (hd1,6)/boot/grub/menu-isengard.lst

Using a custom stage1-isengard should also make this more robust against future GRUB updates.

This should hopefully fix it for the next dist-upgrade, so we can close the bug. The remaining instructions from my old blog post should still be up-to-date.

Thursday, February 17, 2011

Fight These Evil Clones !

One thing I learned from past mistakes is that if you don't want to have any forks, any private versions of some Open Source Software, then you have to fight these from the beginning.

As soon as you create a local copy of something "for convenience", you set yourself up having a fork with plenty of local changes in a couple of months. These convenience copies tend to age pretty quickly.

By creating a local copy of something, you make it more difficult to use the upstream version than your local one. Each time you make some trivial change to one of these files, it becomes so easy to just commit your change to the local copy and persuade yourself that you'll submit it upstream later.

Having a local copy also means you can't quickly pull and test a new version of their code, but instead need to manually copy some files. Even if you use some automated script to do that, these files will appear as modified in your source revisioning system. The same goes for any edits that you may be made in your IDE. Since most source revisioning systems don't allow certain actions such as committing or pulling new upstream versions on dirty stage, you end up committing these changes locally.

The more your local copy has aged, the more difficult it will become to make modifications and submit these modifications to the upstream maintainers.

Let's say one our your customers files a bug in six months from now. When you start debugging, you'll most likely just use the latest version of your module - without updating all these upstream sources first. So you start tracking down this bad bug, edit a few files ... and when you're done, you realize that you also modified some files in one of these these upstream libraries.

Now, you often have the problem that your patch won't apply cleanly anymore against the latest upstream version.

With a local copy of some files, you don't have all these features anymore that a source revisioning system such as git provides to you. You can't easily make patches, get newer upstream versions, etc.

* * *

When I started to work on this new debugging engine, I made a promise to the MonoDevelop team, not to use any local forks of their software anymore, but instead submit all my changes upstream and have them integrated there.

Therefor, I created a system for MonoTools where you need a checked out copy of mono and monodevelop to build; I simply created a .sln that includes all the upstream .csproj's as project references. There are also binary copies of all these .dll's in a private module on svn.

There's nothing wrong with using binary copies of some upstream library in your project - provided that this binary is always build from the upstream sources. A binary .dll can easily be replaced with a newer versions - and as soon as you want to make any modifications to it, you're forced to checkout the upstream version from github.

Friday, February 11, 2011

A new Debugging Engine for Mono Tools and Mono for Android

Today, I finally finished the massive refactoring of our debugging engine that's used in Mono Tools and Mono for Android.

The biggest news is that this new engine is now using the unmodified, original debugging libraries from MonoDevelop and the managed pdb2mdb from Cecil.

As mentioned in an earlier post, Mono Tools was previously using a locally forked copy of these libraries with plenty of local changes. Cleaning these up was a huge and complicated process, and I'd especially like to thank Michael Hutchinson and Lluis Sanchez for their great help.

This was not only about getting a few patches into the upstream version, Michael and Lluis also showed me alternative, better ways of doing certain things, helped me eliminate local hacks and replace them with good and clean solutions.

As a result, I was also able to cleanup and redesign my code in the debugging engine a lot.

In the current version, we only use the public Mono.Debugging.Client APIs in Mono Tools and Mono for Android (with the only exception of Mono.Debugging.Soft.SoftDebuggerStartInfo). The Mono.Debugging.Client.DebuggerSession is now also responsible for creating the connection to SDB - by using either launch, connect or listen mode, depending on the Mono.Debugging.Soft.SoftDebuggerStartArgs that you use.

I also turned things upside-down by making the debugger session create the debugger engine (these COM objects that are used to communicate with Visual Studio) and not the other way around. This has the great benefit that we can re-use MonoDevelop connection and error handling code.

With my new build system, it's also very easy to pull a new version from MonoDevelop and integrate it in Mono Tools / Mono for Android, it's just a matter of checking out MonoDevelop, running some script to .zip up all the required sources, unzip and build them in Visual Studio and done. In theory, it's also possible to build on Linux, building in Visual Studio just makes it a lot easier to debug things.

There are still a few tiny issues that need to be figured out, but these shouldn't take too long.

My next step is doing a bug-fixing week or two, to finally process and fix this long list of outstanding bugs.

Saturday, January 29, 2011

MonoDevelop.MonoTools

This week, I cleaned up all the local patches that we did to the Mono.Debugging libraries, split them into smaller pieces and got them integrated in the upstream versions. Many thanks to Lluis and Michael for helping me out with this.

Things are looking really good now, I did some extensive refactoring in our debugging engine, and I'm now only using the official Mono.Debugging.Client API and not Mono.Debugging.Soft anymore. This also made many of the previously added protected virtual overloads unnecessary.

The soft-debugger specific code in MonoTools is now really tiny, almost everything now talks directly to the Mono.Debugging library, we don't even have a reference on Mono.Debugger.Soft.dll anymore.

There are still a few minor issues to sort out before I can start testing, but I'm really happy with this project. We can now finally use a MonoDevelop.MonoTools.dll that's compiled entirely from the original, unmodified sources which is a great step forward in terms of long-term maintainability.

Tuesday, January 11, 2011

Long term maintainability vs. the quick hack

This week, I started to review and cleanup local changes that we did to MonoDevelop's Mono.Debugging libraries in MonoTools. The plan is to clean this up as much as possible and get them integrated into the upstream version as far as possible.

When I wrote this code, I was under a lot of pressure. We had to deliver a product that our customers were waiting for, so this had to get done quickly. Since we were selling this to Windows people, we had to include and ship all the required libraries, we couldn't ask our customers to download and install MonoDevelop for Windows. So I simply copied the entire code into our internal repository, creating a fork. And whenever I needed to change something, I simply went ahead and did so - since the code lived withing our product's repository, I could just change whatever I wanted without the hassle of submitting patches through the original maintainers and getting them reviewed.

Today, we have the mess. Not only do I need to sync this with the upstream version, I also need to sync this between two different version control systems. Last time I did that was last summer, so the code has diverged significantly.

My plan for cleaning this up is breaking things down into smaller pieces and applying these individually to the upstream version.

Long-term, we still need to build our own version of these libraries for MonoTools for two main reasons: avoiding an external dependency, and I occasionally need to compile everything in Visual Studio to get source-level debugging. However, my plan is to host any source code changes in my private fork on github, so this can easily be kept in sync with the upstream version.

Ideally, the only thing in my private fork should be the build scripts and no local changes. One really cool thing about github is that you can comment on individual commits. In future, I'll use this extensively to document why a certain patch was necessary, what it's doing etc., etc.

One thing I also realized this week was that some of the larger patches could easily be significantly reduced by changing a few things on the MonoTools side. So hopefully this huge beast can be broken down into some really small individual patches.

Sunday, January 9, 2011

MDB is learning ARM

This week, I bought an HTC Desire HD. It's a really great Android phone (though the very little battery lifetime really sucks), I never want to miss a smartphone anymore. Having this cool new toy also made me very excited and enthusiastic about learning more about Android and the ARM architecture.

I only knew very little about ARM assembly language before I learned it this week - and how can you learn any better than by doing ?

So I started to hack again on the MDB and added ARM support to it. Adding support for a new hardware architecture was actually a lot easier than I expected. The biggest hassle was setting up some scripts to compile a 'mono' binary for armeabi.

Most of the architecture-specific stuff is implemented in managed code, in the backend/arch/ directory. The most important piece is the ARM instruction decoder, which is necessary for both single-stepping and stack unwinding. For single-stepping, we need to know whether the current instruction is a method call, a jump or a ret - speaking in x86's terms. On ARM, we treat BL as a method call and all other instructions that modify %pc as a jump.

Unlike the x86, ARM saves the return address of a method call in a special register called %lr - to return from that method, you simply set the program counter %pc to the return location that's stored in %lr - either by using a B or a MOV instruction.

While single-stepping, the debugger always steps by machine instructions using PTRACE_SINGLESTEP unless it's stepping over a method call - by setting a breakpoint on the next instruction and resuming execution with PTRACE_CONTINUE. Note that we also single-step by individual machine instructions if the user issued a next command.

A special case are managed trampolines and stepping over breakpoints.

Regarding stack unwinding, it pretty much looks like there is no "standard" prologue on the ARM like on the x86. where each method starts with push %ebp, mov %bp, %sp. On ARM, a method's prologue usually saves some registers on the stack and then sets either %fp or %ip to the current %sp.

In MDB, I wrote a basic instruction decoder which scans the entire prologue code and looks for instructions that save registers and setup %fp. At the moment, it aborts if it finds anything it doesn't recognize, but I did some tests with both managed and unmanaged frames and it seems to work just fine so far. I haven't done any LMF support yet, so crossing managed <-> native boundaries only works if all methods on the stack have debugging info; the stack unwinder needs to know the method's start address so it can scan its prologue.

Method invocations are already fully supported - this was surprisingly trivial thanks to the new generic invocation API, which moves most of the logic into architecture-independent code. In the old MDB, we had to write 5 different marshallers for different function signatures on each architecture. The new MDB only uses one - which takes a pointer as argument and returns a pointer. We always call the same C function and pass it a pointer to a data structure.

I just committed everything to my private forks, the code is in https://github.com/baulig/debugger/tree/last-hope and you need Mono from https://github.com/baulig/mono/tree/last-hope.

This currently works by copying a statically linked mdb-server, mono and mscorlib.dll to /data/data/martin in the Emulator and starting mdb-server from a shell, there is no Android integration yet. I'm only using the Android emulator as an emulator of the ARM architecture. Compiling Mono for the emulator is complicated and takes a lot of time and patience.

As a next step - whenever I find the time to work on this again - I want to look at Mono's xdebug and see how this can be integrated into MDB. The entire managed symbol file stuff in MDB is very old, so I'm planning to see whether we can reuse some of the newer code here - ideally, we could even use some code from SDB to get variables etc.

Wednesday, September 1, 2010

MDB's new backend

Over the last couple of days, I did some extensive refactoring in MDB's backend and completely rewrote it.

The new backend now lives out-of-process and is written in C++ and there's a managed C# counterpart which talks to the C++ classes over a wire protocol.

One big mistake I made in MDB's old backend was abstracting things in the wrong way. The old backend was basically just wrapping C functions like ptrace() or waitpid and making them accessible from managed code. The big problem with this was that these functions have very specific calling semantics which needed to be replicated on the managed side to use them correctly.

Take ptrace() as an example - this function has to be called from one special thread and from this thread only. Or waitpid() as another example - interrupting it isn't trivial and there is no easy way of waiting for both the child process and user input. Because of this, more and more hacks where added to the managed part of MDB - hacks which were designed to work around specific calling semantics of these system calls. All this stuff made porting MDB very difficult. For instance, when you want to port it to Windows, WaitForDebugEvent must be called from the thread that created the child process - so the "wait event loop" has to be completely different than on Linux.

Primary goal of the new backend is wrapping functionality, not functions ... like "step one instruction, give me an event when done" - it doesn't matter how exactly we wait for the target to stop again, all we're interested in is getting that event.

This doesn't imply rewriting all of MDB in C++, but doing a little bit more in C++ than was previously done in C will make the C# code so much cleaner and so much more portable. As an added benefit, all the managed code will be fully debuggable by a managed debugger - something that was impossible in the old MDB :-)

The backend refactoring is now done, and we can do multi-thread single-stepping, so this afternoon, I cross-compiled Mono (trunk) from Linux to Windows, enabled mdb support in the runtime and started to play around with it ...

Sunday, August 8, 2010

MDB getting ready for the next Millenium

There's one really cool thing about GitHub which I really appreciate a lot: you can create a private fork of a project and put your private changes there. And you can keep them there - for weeks, months, even years - they won't ever get lost. Until recently, I wasn't a big fan of long-lived private weekend projects - they tend to bit-rot, get lost, etc. etc. etc.

This all has so much improved since we switched to GitHub, so I started a really cool weekend-project which involves some huge MDB refactoring and also some cool new stuff :-)

The first thing I did was make MDB's "server" part (the unmanaged "libmonodebuggerserver.la" library) actually a "server" (a stand-alone executable called "mdb-server.exe"). This has three main advantages:

  • It gives me complete control over the process - I deal with signal handlers, signal blocking masks, threads and such as I want and there's no Mono or user-code getting into my way. One major problem in the current debugger code is that I have to call waitpid (and also interrupt it somehow) without knowing what some other user-created thread might be doing at the moment. This was a major headache when embedding MDB and also set some restrictions you might not even know about (for instance, it's strictly forbidden to use fork(), sigprocmask(), waitpid() and some other system calls inside the MDB process - if you need any of these, or can't guarantee they're not used, then you need to wrap the Mono.Debugger.dll library and use it in an external process).
  • It makes it possible to debug MDB's C# code with an IDE such as MonoDevelop, Visual Studio / MonoVS or even MDB itself.

    All operating systems that I can think of have this restriction of not letting you debug a debugger - this goes away by putting the "debugger" part of MDB into a separate process.
  • It makes it much easier to port MDB to other operating systems and/or hardware since you don't have to deploy the entire C# development environment to that machine - all you need is one statically linked binary ... which can even be cross-compiled from Linux.

I already set things up so that you can build the server independently from the C# pieces - my plan is to add some MonoDebugger.csproj in near future and then use xbuild to build the managed libraries. Long-term, I'd really like to use MonoDevelop to build, develop and debug MDB.

On the C# side, there's now a new abstract class called Mono.Debugger.Server.DebuggerServer which has two implementations - NativeDebuggerServer for the local [DllInvoke]'d library and RemoteDebuggerServer to talk to the external process. As part of this refactoring, I moved all [DllInvoke]s into the NativeDebuggerServer implementation and some other classes like ThreadManager have become abstract.

In this new server, we can also use a new event loop model for Linux. Since I now have full control about signal masks in all threads, I don't have to use hacks to interrupt waitpid() anymore. Instead, I now simply block SIGCHLD in all threads (there's only the main thread at the moment), sigwait() for it in one background thread and turn the signal into a select()-able event by using the "self-pipe trick".

The second big task is porting MDB to Windows and Android.

Windows is actually a bit more difficult on the server side because it requires me to build a different main event loop, whereas Android is Linux based and can thus reuse most of the Linux code.

The big difference between Windows and Linux is that the latter sends events for individual threads while the former always treats the entire process as being stopped or running.

From the C# code's perspective, there isn't so much of a difference since we now simply get an event from the remote server and don't need to worry about how it got it. There also isn't any managed wait loop anymore.

I'm really excited about this new code - I got basic single stepping almost working for all three platforms (breakpoints aren't done on ARM yet) and my next step is getting multi-threaded applications working.

It's certainly a very complex and time consuming challenge - but as I said earlier, there's no need to worry, it's all on GitHub in a private fork, no patches which might get lost over time ...

Sunday, June 6, 2010

Hackweek

This coming week is Hackweek V - and I picked a really cool project:

The ultimate goal is making MDB ready to debug moonlight and other "mixed-mode" applications.
Mixed mode means applications which are half unmanaged and half managed.

This requires quite a bit of work on mdb's unmanaged debugging support, but I definitely think it's worth it and it'll make mdb ready for the next century.

My battle plan looks like this:

  • Add support for the JIT's new dwarf debugging code
  • Integrate this into mdb's stack unwinding code

    We're already using the dwarf frame info for unwinding unmanaged stack frames, but not for managed code and there are some bad hacks in place to support things like trampolines.
  • Fix attaching and debugging embedded applications.
  • Fix a thousand bugs in the unmanaged debugging code.
  • See whether we can improve the debugging information from the JIT a bit, cleanup the old debugging code and make it more dwarf-based.

Wednesday, May 19, 2010

12 Years ago ...

Twelve years ago, on May 19th 1998, I officially started to work on GNOME by importing LibGTop into GNOME CVS.

In the meantime, GNOME has first migrated to SVN and then to GIT, but that revision still exists:
commit 33cdc01c1db3a1cafaeb63e50247072b82ef49ea in GIT.

Time to celebrate the anniversary :-)