C++ Handle Segfault in Plugins

Started by
1 comment, last by Brain 9 years ago

So I'm making a small game as a hobby project, and I'd like to implement plugin support. I've been trying to think of the best way to do this, and so far, it looks like using shared libraries that are loaded in at run time is my best bet.

So I made a shared library loading system and small API for some of the game features, and it's all going well... But then I made a mistake in my test plugin that caused a segfault, and brought down the whole game with it!

Is there a better way to do plugins that means they can be loaded in at run-time, but don't cause the whole game to crash if there is a bug in the plugin? Or a simple way to isolate segfaults so I can just unload the shared library if it causes a segfault? I'm using shared libraries because it seemed like the logical choice, but is there a better option that anyone can recommend?

Advertisement

You can spawn multiple processes, and communicate with the plugin via IPC... but that's really heavyweight.

On Windows, you can use SEH (the __try{} __except(){} statement) to catch segfaults and other crashes -- you'd put any call to the plugin inside one of these blocks.

Not sure what the Linux/Mac equivalent is.

[edit] This looks promising: https://code.google.com/p/segvcatch/ [/edit]

However, trying to continue after a crash is kinda dangerous. Who knows what kind of half-completed state the plugin put the program in before the crash. You'll also have to do a lot of work to isolate/buffer all the communication that goes back the other way (from the plugin to the core application).

Yeah, separate processes is the only safe way. You can use shared memory and ReadprocessMemory etc, you still need to be careful what the other process has sent.

This works best when the number of plugin calls is few and far between but generally detailed in scope, e.g. An initialization call.

This is because context switches between processes is more expensive than thread switches or simple dll function calls, but it can be worth it.

I did something like this with plugins in an irc bot, which got called several times a second. They communicated by WM_USER windows messages and it worked quite well.

I would be interested to know what you finally come up with :)

This topic is closed to new replies.

Advertisement