Hard lessons

Published July 25, 2013
Advertisement
I've learned three nasty lessons this week.


First, exception handling in C++ is a knotted mess of undefined behavior, especially when you start blending JIT compiled native code with C++ code that can throw exceptions.

Second, as a result of this, when testing code you should always run it under a debugger so you can tell if an exception is getting thrown and then eaten silently by the undefined behavior demons.

Third, after learning the first two lessons and ripping out a lot of hair, I came across a third: frame pointer omission is the ultimate enemy of accurate garbage collection.


The third one may bear some explanation.


Let's start at the beginning. There is an informal convention on X86 systems that involves creating what are known as stack frames. When you call a function using this convention, it stashes two important pieces of information on the machine stack: a return address (i.e. where the function goes back to when it's done) and a frame pointer. This pointer has the location of the next pair of return address/frame pointer values on the stack, forming a singly linked list of stack frames. When you find a frame with a NULL next pointer or return address, you know you've reached the end of the list.

This is a powerful tool because it lets us construct a call stack. The call stack is like a breadcrumb trail of how your code gets to where it's at in any given moment. While that's a nice debugging aid, it also serves a broader purpose in my schemes: it gives us a way to track where we are in the program and what variables are active, which is central to doing accurate garbage collection.

For review, there are two basic modes of garbage collection: accurate and conservative. In the former, we know where all the variables live and how to peek into their values, so we can always (more or less) construct an accurate picture of what memory the program is using and what memory can safely be reclaimed. Conservative garbage collectors, on the other hand, take the view that we should look at every possible variable on the machine stack. If it smells like a pointer, we assume it is one, and don't free whatever memory it might be pointing to.

Conservative collectors are kind of gross, but ultimately necessary for languages that do not generate enough metadata to support accurate collection. There are also minor performance tradeoffs involved, such that you may not want to pay for accurate collection if your stack is sufficiently small and scraping it is not too expensive. Anyways, the theoretical benefits and cons are unimportant; Epoch uses an accurate garbage collector, which is what matters for this story.

Now, back to frame pointers. There's obviously a tiny bit of overhead involved in setting up this linked list structure, but it has another cost that isn't as apparent: it consumes a register, typically EBP, on the processor at all times. Since EBP is being used to help maintain the linked list, it can't be used for more general-purpose stuff. On a CPU architecture like X86 that is hideously short on registers, this can be a problem.

So way back in the day someone figured out that they could simply not set up stack frames, because compilers are smart and can juggle all the stack shuffling a program does without getting confused. This buys an extra register and shaves off three or four instructions per function call. The name of this trick is Frame Pointer Omission, or FPO.

Pretty nifty, eh?

Except it's actually evil. I'll pause for a moment and let you figure out why.

That's right: with no frame pointer list, we can't tell where our program is or how it got there. This in turn compromises our ability to tell what memory is in use, because we can't really see what the program is doing.

Simple solution: disable FPO in garbage-collected programs!

And that is indeed what I did, many moons ago, in working on the Epoch GC initially.

That served me well until I realized the first two lessons of the week. Once I started running Epoch programs under a debugger, I noticed intermittent crashes that were actually being eaten by the undefined behavior monster (!!) and silently allowing the program to continue running while secretly mangling more and more memory over time.

See, 99% of the time, we'd mangle something that was already garbage and about to be freed anyways, so there's no code to find out that its data is borked. However, that nice little 1% of the time, we'd mangle something that was still in use, and all hell would break loose.

The root cause of all this was that something was being prematurely garbage collected. Ugh.

So I set out to trace exactly why things were getting collected while still alive in the program. Weirdly enough, it became more and more apparent that a specific pattern was occurring:

1. This manifested only in the Era IDE
2. The crash always included references to the Scintilla widget in the call stack
3. The exact same type of object was being prematurely collected every time
4. This object type was instantiated only when passing certain messages to and from Scintilla's widgets

Something about Scintilla was buggering up garbage collection... but what, and how?

After a lot of poking around in raw memory dumps and spending an inordinate amount of time combing through the GC code for bugs, I made the key discovery that unraveled the whole problem.

Sitting in the stack data, obscured by layers of gibberish from Scintilla's internal operations, were two stack frames that got "lost." Essentially, the linked list of frames skipped over both of these functions, and made a hole in the call stack.

Closer examination revealed that the missing stack frames both pointed to my code - i.e. there was some kind of interaction with Epoch code during the lost time period. Turns out that in that gap, an object was instantiated - and, you guessed it, it was exactly the same object that later got prematurely freed and caused one of the silent "crashes."

And what caused those missing frames to vanish in the first place? Why, FPO, of course. Scintilla is compiled with FPO enabled, which in turn means that calls that interact with it will mangle the call stack linked list of stack frames. Why they get mangled in this precise way is still a mystery to me, but it suffices to know that interacting with an FPO-enabled module causes the garbage collector to fail.

In hindsight, the whole thing is painfully obvious, but when chasing a bug like this the obvious can become suspect. I actually theorized that this was the problem early on, but ruled it out for reasons that turned out to be false. Oops.


Solving this will, sadly enough, probably not be easy. The only solutions I can think of border on falling back to conservative collection, which I really don't want to do. The standard fix to FPO in garbage collectors is to store extra debug metadata that allows you to reconstruct the call stack without the frame pointers, which is akin to what debuggers do anyways when generating call stacks from symbol data. Unfortunately, that doesn't at all solve the case of external libraries for which debug information is not available, and it's a slow thing to do at runtime anyways.

So that's been my week in a nutshell.


Developing a language can be a real bitch sometimes :-P
12 likes 7 comments

Comments

3Ddreamer

That's all good to know. I learned a lot.

Thanks,

Clinton

July 25, 2013 09:07 AM
Josip Mati?

Thanks for the lesson, I learned a lot and remembered some things from Computer Architecture course :)

July 25, 2013 09:47 AM
swiftcoder

What's to stop you recompiling Scintilla with FPO disabled? Or are you looking to solve this for the general case, rather than require that all linked libraries don't use FPO?

July 25, 2013 11:03 AM
Mike.Popoloski

You might want to take a look at how Mono handles frame pointer omission in a managed context and see if you can adapt that into your code generator. Since the code is actually kind of hard to navigate, I went ahead and linked some of the relevant areas for you:

https://github.com/mono/mono/blob/master/mono/mini/mini-x86.c#L969 - Cases where they're able to omit the FP.

https://github.com/mono/mono/blob/master/mono/mini/mini-x86.c#L1038

https://github.com/mono/mono/blob/master/mono/mini/mini-x86.c#L2408

They use a "save_lmf" variable that holds the Last Managed Frame and saves some metadata about it when they encounter a stack frame that jumps into a P/Invoke or other native call, and then they ensure that they reset it when they pop that frame again.

It might be a bit more troublesome to handle for your case, since you're not doing JIT and thus don't have some of the luxury of figuring out some of that stuff at runtime, but then again they have to go much further to make sure everything gets reset properly.

July 25, 2013 04:07 PM
Rakilonn

Highly informative and interesting.

Thank you very much for this nice article :)

July 27, 2013 10:35 PM
Krohm

This must have come at quite some effort!

July 29, 2013 08:10 AM
Washu
Now for one of those funny little questions... since I've decided to pickup and start committing again...

Where do I get started, seeing as how release is unable to run (afaict) most of the current epoch files.
July 31, 2013 01:26 AM
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Profile
Author
Advertisement
Advertisement