Use functions from a different program - c

I'm trying to make Wireshark call a functions from a different program. These 2 programs are independent from each other. Is there any way of linking these 2 programs and making Wireshark have the ability of calling a function from inside the second program?
I was thinking of adding the #include to the top of the code of the file which has the required functions. Would this be possible? (I'll be trying it in a while since VS2013 is currently installing.)
Is there any other way of making this possible?

There usually isn't a way for programA to call a function found in a separate executable programB. You have a variety of options — the main ones are:
The normal method is to make the function available in a shared library (DLL), and for both programs to use the DLL to call the function. The DLL might be linked at compile time or loaded at runtime. A similar technique puts the function in a static library that is linked with the executables.
The less common method is to create an RPC (remote procedure call) interface to the function and have both programs (or, at least, programA) use the RPC interface. There are many options for which RPC system to use.
You can also think of more esoteric techniques, such as exposing the function as a web service.

Related

Libcurl and curl_global_init in shared library loaded at runtime

I am developing a photo booth application that uses 3 modules to provide printing, capturing, and triggering functionality. The idea is that people can develop modules for it that extend this functionality. These modules are implemented as shared libraries that are loaded at runtime when the user clicks "start".
I am trying to implement a printer module that "prints" to a facebook image gallery. I want to use libcurl for this. My problem is with the initialization function: curl_global_init() The libcurl API documentation states that this function is absolutely not thread safe. From the docs:
This function is not thread safe. You must not call it when any other thread in the program (i.e. a thread sharing the same memory) is running. This doesn't just mean no other thread that is using libcurl. Because curl_global_init() calls functions of other libraries that are similarly thread unsafe, it could conflict with any other thread that uses these other libraries.
Elsewhere in the documentation it says:
The global constant situation merits special consideration when the code you are writing to use libcurl is not the main program, but rather a modular piece of a program, e.g. another library. As a module, your code doesn't know about other parts of the program -- it doesn't know whether they use libcurl or not. And its code doesn't necessarily run at the start and end of the whole program.
A module like this must have global constant functions of its own, just like curl_global_init() and curl_global_cleanup(). The module thus has control at the beginning and end of the program and has a place to call the libcurl functions.
...which seems to address the issue. However, this seems to imply that my module's init() and finalize() functions would be called at the program's beginning and end. Since the modules are designed to be swappable at runtime, there is no way I can do this. Even if I could, my application uses GLib, which per their documentation, it is never safe to assume there are no threads running:
...Since version 2.32, the GLib threading system is automatically initialized at the start of your program, and all thread-creation functions and synchronization primitives are available right away.
Note that it is not safe to assume that your program has no threads even if you don't call g_thread_new() yourself. GLib and GIO can and will create threads for their own purposes...
My question is: is there any way to safely call curl_global_init() in my application? Can I put the calls to curl_global_init() and curl_global_cleanup() in my module's init() and finalize() functions? Do I need to find another HTTP library?
First, you won't really find any other library without these restrictions since they are inherited by libcurl from 3rd party (SSL mostly) libraries with those restrictions. For example OpenSSL.
This said, the thread safe situation for global_init is very unfortunate and something we (in the curl project) really strongly dislike but cannot do much about as long as we use those other libraries. This also means that the exact situation for you depends on exactly which dependency libraries your libcurl is built to use.
You will in most situations be perfectly fine with calling curl_global_init() from your modules init() function the way you suggest. I can't guarantee this to be safe with 100% certainty of course since there are a few unknowns here that I cannot speak to.

Testing a C function which uses file descriptors

I am writing some functions which will be called with file descriptor arguments in production code.
During testing, how can 'inject' something which will let me confirm that the function makes the intended calls to lseek, write and so on?
Since you're on Linux, you can simply define the functions you want to stub inside your test program. The linker will deem these functions as local, and ignore those that will be dynamically loaded.
I used this successfully on Linux and Solaris with gcc.
Make sure to store the parameters they are invoked with and not to put assertions inside the stub functions, this will make them more reusable.
Depending on your operating system, the best solution is likely to be writing a "shim" library that gets dynamically linked in and intercepts the calls to the standard functions you're looking for, reporting out-of-band to the test harness. The libtrash library is a good example of how this works, and the code is readable; it implements a "trash can" for Linux by intercepting (some) calls to unlink and instead moving the links to a trash-can directory.

Catching a system call just before control enters a shared library

I have wrapped a number of system call function like write(), open() etc and LD-PRELOAD is used to override the original system calls. Moreover I have defined a few more functions and made this too a shred library.
I would like to catch all system calls from different application processes to these shared libraries before they enter the shared library. How can i do that?
Thanks
LD_PRELOAD is not necessarily a good way to interpose system calls, because a) it only allows you to intercept library calls and b) it only allows you to intercept library calls. ;)
A) While in general, system calls are wrapped by the shared libC in your system, no one prevents you from calling a system call yourself, e.g., but setting up the right register content and then issuing INT 0x80 on an x86 system. If the program you're interested in does so, you'll never catch those with LD_PRELOAD-based libc-interposition.
B) While in general, most programs use the shared libC in your system to make system calls, sometimes applications are linked statically, which means the libC code is part of the application and does not come from the shared lib. In such cases, LD_PRELOAD also does not help.
A comment already suggested to use strace/ltrace -- my generalized advice would be to have a look at ptrace() which both of these tools use and which should give you what you want without the need of modifying the kernel.
Patch-free User-level Link-time intercepting of system calls and interposing on library functions may do the trick but I have not tested it.
I'm pretty sure the only way you can do this is by modifying the system call table. HIDS systems (such as Samhain) will report this as an intrusion and Linux kernel developers frown upon this, heavily. The implementation details are very specific to the OS (i.e. what works on FreeBSD won't necessarily work on Linux), but the general implementation details are going to be the same. A kernel module might be a better way to go with cleaner, more standardized APIs.

Help building a Dll for C in Delphi

ive previously asked another questions about building my dll, but it seams like its heading in the wrong direction :) So I have reformulated and explained more her.
So what im trying to build is a dll that will work as an interface between my delphi program and some one else's C program.
What this dll must do is recive a String from the C program then send it to the delphi program where it will be combined with some data and stored, under the current user of my program.
How can i call a method in my Delphi program(running program) to store the message from the dll ?
Im using Delphi 5.
This is what ive got so far:
DLL:
//Parent application: MyDelphiApp
library MyDllLink;
uses
ShareMem,
SysUtils,
Classes,
Dialogs,
Main;// Main is a form from my delphi app. This is not allowed/recomended ?
{$R *.RES}
procedure Transfer(sMessage: PChar); stdcall;
begin
try
//If including Main in the uses clause, then this will also be wrong:
MainForm.StoreDllMessage(sMessage);
except
showmessage('Error');
end;
end;
exports
Transfer;
end.
Delphi app:
procedure TMainForm.StoreDllMessage(sMessage: String);
begin
//StoreMessage just stores it in a DB
StoreMessage(sMessage +' '+sCurrentUserName);
end;
I may be understanding this wrong but it seems like you want the same copy of the DLL to be loaded by both the C program and the Delphi program at the same time. You can't do that and can only really achieve it using a whole lot of work involving inter process communication. The applications will have separate process space and memory.
I would suggest a slightly different approach. In the DLL have a function called SendStringFromCApp and a function called GetStringIntoDelphiApp (or something suitable).
The C program will load a copy of the DLL as normal and call the SendStringFromCApp function. This function will store the passed in data in some common intermediate format (such as a simple database). It will treat the storage as a kind of queue and simply add data to this queue. A database is the most obvious choice but it could be as simple as a common directory and the data is stored as small text files with an increasing integer as the file name.
The Delphi program will load its own copy of the DLL and will call GetStringIntoDelphiApp which will read the first item from the queue/internal storage and process it as required and delete it from the store. Then it will read the next etc etc.
The benefit of this is that both the C and Delphi apps can run independently. Only the DLL needs a common config and the C program can continue to work even if the Delphi app isn't running and vice versa.
It's basically a producer-consumer queueing system for separate processes.
Like I said, I may have misunderstood the requirements!
For the easiest possible IPC try WM_COPYDATA with PostMessage or SendMessage
Microsoft doc:
http://msdn.microsoft.com/en-us/library/ms649011%28VS.85%29.aspx
Microsoft sample:
http://msdn.microsoft.com/en-us/library/ms649009%28v=VS.85%29.aspx
And much more info on google:
http://www.google.com/search?q=WM_COPYDATA&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:pt-BR:official&client=firefox-a
Try implementing an IPC (InterProcess Communication). You will have 3 separated processes.
The Delphi exe
Ths C program
A non windowed process (com service, exe, ...)
Use the non windowed as the server, the other 2 are clients.
See this for IPC in Delphi, and this for IPC in C. There is a lot of ways to do IPC. If you look for IPC in your favorite search engine I'm pretty sure that you will find a common way to do IPC for C and Delphi because it's just some win32 api ballet.
As loursonwinny says, IPC is the way to go.
You should understand that every DLL is loaded within the address space of a single application. Thus a DLL that is used by a Delphi and a C application will exist two times in memory. (Well, not completely, the code sections are shared, all data in the DLL exists twice.) So basically your DLL cannot simply share data between two processes.
There are exceptions, of course. For example, a keyboard hook could be created in a single DLL which is loaded in your Delphi application, then injected into the address space of the C process. Then the DLL can 'peek' into the memory space of the C application and capture some information. (Keyboard events with KeyHooks.) But KeyHooks and similar injectable DLL's will be noticed as "bad" by the average antivirus product. And for good reason, because this is behaviour you'd expect from a computer virus.
Another solution instead of IPC would be the use of a memory mapped file. There are several components available as open-source or commercially but you can also use the Windows API to create these.
The Windows API also provides techniques like Named Pipes and MailSlots, which can also be used for interprocess communication. It doesn't need to be TCP/IP but you will need some way for the two processes to communicate with one another. And this logic could indeed be build in a single DLL, where you'd define just two methods. One for the server, one for the client. It is a complicated technique, though. And Delphi 5 is a bit old so I don't know which solution would work best for you.
The DLL must callback to the Delphi program. When the Delphi program starts up, it'll register a callback function. Then the DLL knows what to call when it is invoked by the C program.
Example:
http://delphi.about.com/od/windowsshellapi/a/callback_delphi.htm
This example uses a callback to allow the windows API to call back into your delphi app. Same idea here, but instead of the Windows API, you're going to be called by your own DLL.

Dynamic modules with DLLs on Windows

I'm writing an application in C that can be extended at runtime by means of modules / shared objects / DLLs. Those modules may use the API of the existing program but may also provide new functions for use in later loaded modules, so there is the possibility for modules to have dependencies on each other.
My current approach under Linux is to have every module define a depends() function that returns a list of other module names it depends on. That way, I can compile and link every module for itself, load a module with dlopen() and RTLD_LAZY, resolve its dependencies first and then fully load it with RTLD_GLOBAL. This works just fine and does exactly what I want. It also allows me to replace a module with a different version without recompiling all other modules depending on it.
The actual problem arises when porting this to Windows. First, I haven't found any way to link a DLL without already providing it with the export symbol tables of all its dependencies. Is there one I've overlooked?
Second, LoadLibraryEx from the Windows API doesn't seem to be able to perform any lazy loading because instead of letting me handle dependencies, it goes ahead and loads all referenced DLLs itself before it even returns. Since I'd like to perform version checking as well before actually loading modules in the future, this it not at all what I want. Is there any way to circumvent this behaviour?
The third odd thing is that I cannot replace a DLL without recompiling all other modules depending on it. It actually does work sometimes, but usually wild things start to happen or the program segfaults.
Is it even possible to write a modular application like that on Windows? Any suggestions or different approaches are highly appreciated!
Update: Just to provide some clarification on how my modules use each others functions on Linux (which I would like to have on Windows as well): Every module just returns the name of another module it would like to call functions from in the described depends() function and includes its header, then calls the used functions directly in the code without any wrapping. This works because Linux does not require you to have all symbols resolved at link time for shared objects.
You can export all functions manually (using __declspec(dllexport)) and load them using GetProcAddress. In this case you need to know the signature of each function, and you're limited to C functions only, but this is going to work. If you compile both modules, your C functions can also return C++ classes, more on this later. Using GetProcAddress & LoadLibrary makes modules totally independent. Basically, you do the linking manually, but as I understand, this is what you do on Linux, right?
LoadLibary only loads the libraries a library is dependent on, so make sure they don't load depend on each other. Either they are really independent, or they aren't, if done properly, changing one library will not force a recompile of the other (as you don't link them together).
A good idea is to use something like COM, so make each of your libraries return an interface, instead of individual functions. That way, you can simply load a whole DLL and also link them easily together (passing a DLL -> passing an object). Look up XPCOM and COM, it's actually very easy to do.

Resources