Running plugins in a sandbox - c++

I am designing a system in C/C++ which is extendible with all sort of plugins. There is a well defined C public API which mostly works with (const) char* and other pointer types. The plugins are compiled into .so or .dll files, and the main application loads them upon startup, and later unloads or reloads them upon request.
The plugins might come in from various sources, trustable or not so :)
Now, I would like to make sure, that if one plugin does something stupid (such as tries to free a memory which he was not supposed to free), this action does not bring down the entire system, but merely notices the main system about the misbehaving plugin for it in order to remove it from the queue.
The code calls are being done in the following manner:
const char* data = get_my_data();
for(int i = 0; i<plugins; i++)
{
plugins[i]->execute(data);
}
but if plugin[0] frees "by accident" the data string or overwrites it or by mistake jumps to address 0x0 this would bring down the entire system, and I don't want this. How can I avoid this kind of catastrophe. (I know, I can duplicate the data string ... this does not solve my problem :) )

Make a wrapper process for plugin and communicate with that wrapper through IPC.
In case of plugin failure your main process would be untouched

Simply put, you can't do that in the same process. If your plugins are written in C or C++, they can contain numerous sources of undefined behavior, meaning sources for undetectable unavoidable crashes. So you should either launch the plugins in their own processes like kassak suggested and let them crash if they want to, or use another language for your plugins, e.g. some intepreted scripting language like lua.

Have a look at http://msdn.microsoft.com/en-us/library/1deeycx5(v=vs.90).aspx
I use /EHa in one of my projects to help me catch exceptions from libraries that do stupid things. If you compile your code with this setting a normal try catch block will catch exceptions like devide by zero, etc.
Not sure if there is some equivalent for this on Linux -- please let me know if there is..

Related

How to contain catastrophic failure within a shared library plugin

What can one reasonably do to try to contain catastrophic failures (such as crashes) within a shared library plugin written in C++, beyond catching all exceptions using catch (...) { /* handle here */ }?
My situation is a bit peculiar so let me describe it in detail. The "plugins" extend Mathematica (a programming language). They must be compiled into shared libraries which export a number of C (not C++) functions all of which have the same signature (similar to argc, argv, etc.). These functions can use a simple API to handle "arguments", return a value, or call back to Mathematica. After the "plugin" is loaded, these C functions will be exposed as Mathematica functions.
My contribution here is a tool that takes the interface description of a C++ class and automatically generates these standard C functions to call class members. I want to generate code to try to catch failures and report on them. So far the only protection I have is catching all exceptions.
Note 1: I am not interested in trying to run the plugin in a separate process for performance reasons. The API that Mathematica provides give direct access to large numerical matrices within Mathematica. I absolutely want to avoid copying these. Mathematica also provides a different API for out-of-process plugins, which I do use when performance is not critical.
Note 2: I cannot change Mathematica itself, e.g. control how it loads shared libraries.
Note 3: I looked a bit at signal handlers, but I worry that it's not a good idea to set once since it will affect the host application, which I have no control over. I only want to catch failures within the plugin itself, not other parts of the host.
I think this should be possible to some extent because MATLAB does it: if a MATLAB "plugin" (i.e. MEX file written in C) crashes, it won't immediately bring down the entire application. Instead it shows an error like this:
Notice the "Attempt to Continue" button. This is precisely the kind of thing I want to do: report some information about the problem (such as which plugin misbehaved, if this can be found out) and give a last chance to the user to try to save their work, while warning them about the potential consequences of continuing.
I expect some answers to be platform specific. I'm interested in Windows, OS X and GNU/Linux.

Precompile script into objects inside C++ application

I need to provide my users the ability to write mathematical computations into the program. I plan to have a simple text interface with a few buttons including those to validate the script grammar, save etc.
Here's where it gets interesting. These functions the user is writing need to execute at multi-megabyte line speeds in a communications application. So I need the speed of a compiled language, but the usage of a script. A fully interpreted language just won't cut it.
My idea is to precompile the saved user modules into objects at initialization of the C++ application. I could then use these objects to execute the code when called upon. Here are the workflows I have in mind:
1) Testing(initial writing) of script: Write code in editor, save, compile into object (testing grammar), run with test I/O, Edit Code
2) Use of Code (Normal operation of application): Load script from file, compile script into object, Run object code, Run object code, Run object code, etc.
I've looked into several off the shelf interpreters, but can't find what I'm looking for. I considered JAVA, as it is pretty fast, but I would need to load the JAVA virtual machine, which means passing objects between C and the virtual machine... The interface is the bottleneck here. I really need to create a native C++ object running C++ code if possible. I also need to be able to run the code on multiple processors effectively in a controlled manner.
I'm not looking for the whole explanation on how to pull this off, as I can do my own research. I've been stalled for a couple days here now, however, and I really need a place to start looking.
As a last resort, I will create my own scripting language to fulfill the need, but that seems a waste with all the great interpreters out there. I've also considered taking an existing open source complier and slicing it up for the functionality I need... just not saving the compiled results to disk... I don't know. I would prefer to use a mainline language if possible... but that's not required.
Any help would be appreciated. I know this is not your run of the mill idea I have here, but someone has to have done it before.
Thanks!
P.S.
One thought that just occurred to me while writing this was this: what about using a true C compiler to create object code, save it to disk as a dll library, then reload and run it inside "my" code? Can you do that with MS Visual Studio? I need to look at the licensing of the compiler... how to reload the library dynamically while the main application continues to run... hmmmmm I could then just group the "functions" created by the user into library groups. Ok that's enough of this particular brain dump...
A possible solution could be use gcc (MingW since you are on windows) and build a DLL out of your user defined code. The DLL should export just one function. You can use the win32 API to handle the DLL (LoadLibrary/GetProcAddress etc.) At the end of this job you have a C style function pointer. The problem now are arguments. If your computation has just one parameter you can fo a cast to double (*funct)(double), but if you have many parameters you need to match them.
I think I've found a way to do this using standard C.
1) Standard C needs to be used because when it is compiled into a dll, the resulting interface is cross compatible with multiple compilers. I plan to do my primary development with MS Visual Studio and compile objects in my application using gcc (windows version)
2) I will expose certain variables to the user (inputs and outputs) and standardize them across units. This allows multiple units to be developed with the same interface.
3) The user will only create the inside of the function using standard C syntax and grammar. I will then wrap that function with text to fully define the function and it's environment (remember those variables I intend to expose?) I can also group multiple functions under a single executable unit (dll) using name parameters.
4) When the user wishes to test their function, I dump the dll from memory, compile their code with my wrappers in gcc, and then reload the dll into memory and run it. I would let them define inputs and outputs for testing.
5) Once the test/create step was complete, I have a compiled library created which can be loaded at run time and handled via pointers. The inputs and outputs would be standardized, so I would always know what my I/O was.
6) The only problem with standardized I/O is that some of the inputs and outputs are likely to not be used. I need to see if I can put default values in or something.
So, to sum up:
Think of an app with a text box and a few buttons. You are told that your inputs are named A, B, and C and that your outputs are X, Y, and Z of specified types. You then write a function using standard C code, and with functions from the specified libraries (I'm thinking math etc.)
So now your done... you see a few boxes below to define your input. You fill them in and hit the TEST button. This would wrap your code in a function context, dump the existing dll from memory (if it exists) and compile your code along with any other functions in the same group (another parameter you could define, basically just a name to the user.) It then runs the function using a functional pointer, using the inputs defined in the UI. The outputs are sent to the user so they can determine if their function works. If there are any compilation errors, that would also be outputted to the user.
Now it's time to run for real. Of course I kept track of what functions are where, so I dynamically open the dll, and load all the functions into memory with functional pointers. I start shoving data into one side and the functions give me the answers I need. There would be some overhead to track I/O and to make sure the functions are called in the right order, but the execution would be at compiled machine code speeds... which is my primary requirement.
Now... I have explained what I think will work in two different ways. Can you think of anything that would keep this from working, or perhaps any advice/gotchas/lessons learned that would help me out? Anything from the type of interface to tips on dynamically loading dll's in this manner to using the gcc compiler this way... etc would be most helpful.
Thanks!

Sharing an object between instances of a C++ DLL

Good morning all,
Forgive me if the title is not too clear, I'll try to explain more here:
I am currently working with the ASI for VBS2. VBS2 executes functions from a VBS2 DLL plugin. I have my own application which I want to use to modify variables within that plugin whilst it is being used, to change what is being executed by VBS2. I began by, foolish as it may be, directly changing the variables with my application whilst the VBS2 program was running.
When this did not work I tested and found that the VBS2 program was using a different instance of the "message" object, in which I was storing the variable, to the one being accessed by my application.
What I would like to do is have my application access the same instance of the object being accessed by VBS2. I have experimented a bit with
#pragma data_seg(".testseg")
Message msg;
void foo(...); //etc.
#pragma data_seg()
but for some reason or another it still appears there are two instances being used.
I would greatly appreciate any and all help, and would add that C++ is a new language to me so please be gentle. :)
Thanks,
M
You need to use linker flags to tell the linker to place that segment in sharable memory.
See http://msdn.microsoft.com/en-us/library/ms933104.aspx
I belive you need to add something like
#pragma comment(linker, "/SECTION:.testseg,RWS")
to your program.
I'm not sure, this may only work in a DLL...
If I understand correctly what you want, you can't do this with standard C/C++ tools. Your program and the other program live in separate memory spaces and they are completely insulated from each other. If your program has administrative privileges, you can attempt to read & write the memory space of the other process using WriteProcessMemory():
http://msdn.microsoft.com/en-us/library/ms681674%28v=VS.85%29.aspx
But then there's a problem of finding the right object in that memory space.
It's not clear whether you have the source for the plugin. If you do, there are other interprocess communication techniques that can be utilised. None as simple as just changing the variable, unfortunately.

Problem in using C dynamic loading routines

I have an application consisting of different modules written in C++.
One of the modules is meant for handling distributed tasks on SunGrid Engine. It uses the DRMAA API for
submitting and monitoring grid jobs.If the client doesn't supports grid, local machine should be used
The shared object of the API libdrmaa.so is linked at compile time and loaded at runtime.
If the client using my application has this ".so" everything is fine but in case the client doesn't have that ,
the application exits failing to load shared libraries.
To avoid this , I have replaced the API calls with function pointers obtained using dlsym() and dlopen().
Now I can use the local machine instead of grid if the call to dlopen doesn't succeeds and my objective is achieved.
The problem now is that the application now runs successfully for small testcases but with larger testcases it throws segmentation fault while the same code using dynamic loading works correctly.
Am I missing something while using dlsym() and dlopen()?
Is there any other way to achieve the same goal?
Any help would be appreciated.
Thanx,
It is very unlikely to be a direct problem with the code loaded via dlsym() - in the sense that the dynamic loading makes it seg-fault.
What it may be doing is exposing a separate problem, probably by moving stuff around. This probably means a stray (uninitialized) pointer that points somewhere 'legitimate' in the static link case but somewhere else in the dynamic link case - and the somewhere else triggers the seg-fault. Indeed, that is a benefit to you in the long run - it shows that there is a problem that otherwise might remain undetected for a long time.
I regard this as particularly likely since you mention that it occurs with larger tests and not with small ones.
As Jonathan Leffler says, the problem very likely exists in the case where you are using the API directly; it just hasn't caused a crash yet.
Your very first step when you get a SIGSEGV should be analyzing the resulting core dump (or just run the app directly under debugger), and looking where it crashed. I'll bet $0.02 that it's crashing somewhere inside malloc or free, in which case the problem is plain old heap corruption, and there are many heap-checker tools available to help you catch it. Solaris provides watchmalloc, which is a good start.
If you are throwing an exception across a extern "C" function then the application has to quit. This is because the C ABI does not have the facilities to propagate exceptions.
To counter this when using DLL's (or shared libs) you normally have a one C function that returns a C++ object. Then the remaining interaction is with that C++ object that was returned from the DLL.
This pattern suggests (and I stress suggests) a factory like object, thus your DLL should have a single extern "C" function that returns a void* which you can reinterpret_cast<> back into a C++ factory object.

Any improvements on the GCC/Windows DLLs/C++ STL front?

Yesterday, I got bit by a rather annoying crash when using DLLs compiled with GCC under Cygwin. Basically, as soon as you run with a debugger, you may end up landing in a debugging trap caused by RtlFreeHeap() receiving an address to something it did not allocate.
This is a known bug with GCC 3.4 on Cygwin. The situation arises because the libstdc++ library includes a "clever" optimization for empty strings. I spare you the details (see the references throughout this post), but whenever you allocate memory in one DLL for an std::string object that "belongs" to another DLL, you end up giving one heap a chunk to free that came from another heap. Hence the SIGTRAP in RtlFreeHeap().
There are other problems reported when exceptions are thrown across DLL boundaries.
This makes GCC 3.4 on Windows an unacceptable solution as soon as your project is based on DLLs and the STL. I have a few options to move past this option, many of which are very time-consuming and/or annoying:
I can patch my libstdc++ or rebuild it with the --enable-fully-dynamic-string configuration option
I can use static libraries instead, which increases my link time
I cannot (yet) switch to another compiler either, because of some other tools I'm using. The comments I find from some GCC people is that "it's almost never reported, so it's probably not a problem", which annoys me even more.
Does anyone have some news about this? I can't find any clear announcement that this has been fixed (the bug is still marked as "assigned"), except one comment on the GNU Radio bug tracker.
Thanks!
The general problem you're running into is that C++ was never really meant as a component language. It was really designed to be used to create complete standalone applications. Things like shared libraries and other such mechanisms were created by vendors on their own. Think of this example: suppose you created a C++ component that returns a C++ object. How is the C++ component know that it will be used by a C++ caller? And if the caller is a C++ application, why not just use the library directly?
Of course, the above information doesn't really help you.
Instead, I would create the shared libraries/DLLs such that you follow a couple of rules:
Any object created by a component is also destroyed by the same component.
A component can be safely unloaded when all of its created objects are destroyed.
You may have to create additional APIs in your component to ensure these rules, but by following these rules, it will ensure that problems like the one described won't happen.