• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
  • entries
    625
  • comments
    1446
  • views
    1006476

Hard lessons

Sign in to follow this  
Followers 0
ApochPiQ

1754 views

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
Sign in to follow this  
Followers 0


7 Comments


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

0

Share this comment


Link to comment

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?

1

Share this comment


Link to comment

Highly informative and interesting.

Thank you very much for this nice article :)

0

Share this comment


Link to comment
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.
0

Share this comment


Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now