Multiple calls to a dll from Dymola - c

I am implementing a model that requires to call a dll library twice, in order to receive from it specific values
the first call is to set up a system inside the library (for example, a powertrain from a catalogue of components and some design parameters)
the second call is to retrieve the performance of a component from such system (let's say the efficiency of a specific electric machine when used in that powertrain)
These two calls to the dll go together, and may be repeated during simulation time.
So far, I've only managed to interface my model to the dll through separate calls from Modelica external functions (one for the first call, one for the second). However, the state of the system is reset between the first and the second call.
Is there a way in Modelica to load a dll, call the same instance of
it multiple times, and eventually close it when the job is done?
Perhaps is it only possible to achieve such feature by bundling the
whole functionality in an external function?
Or am I attempting something that just doesn't work, because of some
technical aspects that I am not aware of? (I don't know, perhaps the
way it all gets compiled during translation)

If I understand this correctly, it looks like your external DLL has some kind of object pointer that is returned when you instantiate it, and this needs to be passed in at every subsequent function call to other functions in the DLL (to preserve the state).
So to do this in Modelica, you need to create an external object class. These are used to preserve state externally and has constructors and destructors to manage its memory. You can write small wrapper C functions to interface with your DLL functions that you can directly include in Modelica annotations, or write a wrapper lib.
Documentation
https://build.openmodelica.org/Documentation/ModelicaReference.Classes.ExternalObject.html
Simple Example
https://www.claytex.com/tech-blog/external-object-example-detecting-initial-rising-edge/
Detailed Example
https://github.com/modelica-3rdparty/ExternData/releases

Related

Execute or skip ld.so.preload shared library code based upon conditions

TL;DR: Can I just skip loading a shared library placed in ld.so.preload or specific code from it when executing a binary and RUID != UID?
Hi.
I'm writing a shared object, a library, that I load via ld.so.preload in order to hook some functions. I want to know if I can, based upon some conditions, skip loading such library or some parts of it.
Context: I'm working with TOCTTOU (Time To Check To Time To Use) vulnerability and I'm writing a userland library, that will be loaded via linux's loader ld.so.preload feature. The main idea is to hook all functions that operate with files, do some checkings and then call the original function so it's transparent to users and other programs.
Now, the thing is: As I don't want to overload the system and I want my library to have as little impact, overhead as possible, I'd like to execute it, that is, to hook the functions, only when RUID != EUID. That's one of the file-based TOCTTOU premises, it happens when the attacker has lesser privileges than the vulnerable application.
The only way that comes to my mind as of right now is to surround every function declaration with:
if(RUID == EUID){
call original function;
} else {
do my checkings;
call original function;
}
EDIT: The above code could be replaced by its equivalent, shorter:
if(RUID != EUID){
do my checkings;
}
call original function;
But that's actually pretty awful since I'm hooking almost 50 functions plus working with __attribute constructor and destructor and It'd mean to fill my code with if-else blocks in each and every single function.
Please bear in mind that ld.so.preload loads the listed libraries before any other library.
I'd like to know if there is any way of just not loading the library based upon the RUID != EUID condition or, alternatively, load the library but skip the hooking code.
Since my library is system-wide, I cannot create any wrapper for it.
You want to preload your library only into setuid or setgid programs.
Since the number of such programs on any system is quite small and statically known (you can find them all with a cron job every hour), the easiest solution is to create a wrapper for every such program.
The wrapper can itself be a single very small program that has the exact same setuid / setgid permissions as the "target" program, and performs an equivalent of
/bin/env "LD_PRELOAD=..." target-prog args

When do I need a function to run before or after main()?

GCC supports construtors/destructor functions which support running function before or after main():
The constructor attribute causes the function to be called automatically before execution enters main(). Similarly, the destructor attribute causes the function to be called automatically after main() completes or exit() is called. Functions with these attributes are useful for initializing data that is used implicitly during the execution of the program.
Here is an example from GeeksforGeeks.
When is the proper scenario of using this feature? Especially a function to be called before main(), what is the difference if we just place it in start of main()?
Such constructor and destructor functions are mainly useful when writing libraries.
If you are writing a library which needs to be initialised, then you would have to provide an initialisation function. But how would you ensure that it is run before any other of your library's functions? The use of the library would have to remember to call it, which they could easily forget.
One way to get the initialisation done automatically is to mark the function as a constructor.
See also: How to initialize a shared library on Linux
For the majority of scenarios there will be no difference. Everything that you want to do with global variables, singletons, memory, etc, you could theoretically do in main() and with plain static initializers.
The main scenario where this is marginally applicable is cross platform projects, where you would like to keep most of your common code in main, however on some platforms, mainly embedded ones, you would like to duplicate what the other OSes are doing before main - setting up environment variables, wiring standard file descriptors (stdin/stdout/stderr) to custom descriptors on your system, allocate your own custom memory manager - e.g., allocate your own stack for running main(), and so on.
From mine point of view, module constructor have their meaning when making shared modules.
Shared modules don't have an specific initialization routine (there is DllMain on Windows, but i has it´s limitations).
For example, Asterisk PBX abuses of constructors because is strongly based on modules, it injects a constructor on each module at compilation time.
This constructor gets called on dlload() and tells asterisk core whether the module has been loaded properly or not, allowing it to call specific functions on the module.
Suppose you have a global structure and you want to initialize memory to the structure before starting your program, you can put it inside the constructor, since it calls before main().
Similarly, if you want to free any existing memory before the end of the program you can do so in the destructor.

How to intercept C library calls in windows?

I have a devilish-gui.exe, a devilish.dll and a devilish.h from a C codebase that has been lost.
devilish-gui is still used from the customer and it uses devilish.dll
devilish.h is poorly documented in a 30-pages pdf: it exposes a few C functions that behave in very different ways according to the values in the structs provided as arguments.
Now, I have to use devilish.dll to write a new devilish-webservice. No, I can't rewrite it.
The documentation is almost useless, but since I have devilish-gui.exe I'd like to write a different implementation of the devilish.h so that it log function's call and arguments in a file, and than calls the original dll function. Something similar to what ltrace does on linux, but specialized for this weird library.
How can I write such "intercepting" dll on windows and inject it between devilish.dll and devilish-gui.exe?
A couple of possibilities:
Use Detours.
If you put your implementation of devilish.dll in the same directory as devilish-gui.exe, and move the real implementation of devilish.dll into a subdirectory, Windows will load your implementation instead of the real one. Your implementation can then forward to the real one. I'm assuming that devilish-gui isn't hardened against search path attacks.
Another approach would be to use IntelliTrace to collect a trace log of all the calls into devilish.dll.

Override a C function defined in a static library

I have a static library of C files, compiled with g++ on Cygwin. I wish to unit test one function that is defined in the library. That function calls another function defined in that library and I wish to override the dependency to replace it with my own version of that function. I can't modify what's in the static library, so this solution [ Override a function call in C ] doesn't apply.
Usually, I can write a .cpp file and include the .c file containing the function I want to unit test, which essentially extends that file with the code I add. It's a dirty trick I'd never use for production code but it's handy for unit testing C files, because it gives my test code access to static things in that C file. Then, I can write in my fake version of the dependency, and my unit test function that calls the function I'm testing. I compile my.cpp to get my.o, then link it with the static library. In theory, since the linker has found a definition for the dependency already (the one I provide) it won't look in the library and there will be no conflict. Usually this works, but now I'm getting a "multiple definition" error where the linker first finds my fake and then finds the real one. I don't know what might cause this and don't know what to look for. I also can't boil this down to a simple example because my simple examples don't have this problem.
Ideas please?
One possibility (admittedly, and ugly one, but...) is to extract the individual object files from the static library. If the function you're calling and the function it's calling are in separate object files, you can link against the object file containing the function you need to call, but not against the one containing the function it calls.
This only gives you granularity on the level of complete object files though, so if the two functions involved are both in the same object file, it won't work. If you really need to get things to work, and don't mind making a really minor modification to the object file in question, you may be able to use a binary editor to mark the second function as a weak external, which means it'll be used in the absence of any other external with the same name, but if another is provided, that will be used instead.
Whether that latter qualifies as "modifying the library" or not depends a bit on your viewpoint. It's not modifying the code in the library, but is modifying a bit of the object file wrapper around that code. My guess is that you'd rather not do it, but it may still be the cleanest way out of an otherwise untenable situation.
It turns out the reason the linker found both defintions of the function is that the faked function's source file defined a variable which is extern'ed in its header file. That unresolved external in the header file caused the linker to link the faked function's object file (the whole thing) to the tested function's file inside the library. So, it's impossible to extract the definition of the tested function without the definition for the dependency.
What I ended up doing was similar to Override a function call in C where I used a different function name instead of the same one, and a preprocessor directive to swap the two. I put the preprocessor directive and the fake function in a separate file which can be included in a unit test, so the production code in the library does not have to be touched. Plus, if I want to fake that same function for another unit test somewhere else, I can re-use the new file.
Depending on your platform and performance requirements, you might be able to use pin to dynamically modify the application and replace one function with another at runtime.
There's no direct example in the manual, but you could easily modify one of the sample pin tools to do this.

Inversion of Control or Dependency Injection -- anyone doing it in C?

See, for example, here
https://stackoverflow.com/questions/139299/difference-between-dependency-injection-di-inversion-of-control-ioc
to remind yourself what IoC and DI are.
The question and answer here
Is Inversion of Control specific to OO languages?
suggests that it does not require an OO language.
Now, my question: Anyone doing this in C?
I am asking because we write embedded C and are considering applying these methods, without changing our programming language.
Doing it in C all the time. The hint is given in the answer from Azder in your second link:
"When you give a Windows API function a pointer to a callback function, you give them the control of calling your function with their own parameters."
From this point of view, the concept is already used in the Standard library for the functions qsort() and bsearch().
On windows, you have COM which does something similar. You have an interface and provide an implementation in a DLL. You register the DLL and that process of registration makes an entry in the registry mapping the interface (UUID) and the DLL which provides the implementation. Based on this information, when you execute QueryInterface(), the COM service will load the corresponding DLL and create an instance of the implementation object, typecast it to the requested interface type and return.
This is IoC using COM. Since COM is implemented in 'C', I am sure it is just working out the details to get this working on your embedded system. Instead of registry, you will need a file to store that mapping between interface, implementation and DLL. This is done in Catia (from Dassault Systemes) in their CNext (V5/V6) architecture. It is called the Object modeler framework.
Steps to achieve this:
Define a naming convention for function that returns a pointer to an interface
Create a file with interface and DLL in which it is implemented
Implement the interface in a DLL and update the file in #2
In the main code, read the file and create a map of interface and DLL
When you need an interface, load the DLL if not loaded and get the address of the function that returns the pointer to interface (based on defined naming convention)
Ex: For IDoSomething interface, your function might be Get_IDoSomething().
Since we get the address of function based on name, it is done at runtime and not at compile time.
Invoke the function at the address you get from #5. You now have a pointer to the interface based on the implementation in DLL as specified in #3
You therefore tie the interface to its implementation at runtime.

Resources