Help building a Dll for C in Delphi - c

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.

Related

Safely execute arbitrary Lua code with only C

I know that you can safely execute arbitrary code from Lua by whitelisting safe things with the Lua function setfenv. But if I do this through a script, not only is it untidy, but (user-moddable game) an unsuspecting user installing a mod could just click "replace all" or something when installing a mod into a folder, without thinking anything of it. I'm sure there are other ways it could be bypassed super-easily too.
Overall the safest way to be safe should be to do this with direct C calls, with no Lua code/strings involved in setting the sandbox. How can I do this?
Anything you code in a Lua script can also be performed in C via the Lua C API. But it's harder to follow in C than the equivalent Lua script. When I have wanted to have some protected Lua scripts for a host program I have done things like for example:
put them in a separate directory.
Encrypt them into an archive that only my C program knows the private key for.
Embedded them as multi-line strings in the C source code.
Embed the compiled scripts as binary strings in my C source code so that they not as easily hack-able via the binary edit of program's exe. (Sometimes I use a SHA of the scripts to prevent them from being edited within the exe)
...and so on.
You definitely want to protect the computer running your game from malicious scripts by using sandboxes. E.g no file system access. But note, that to also protect your host program from all forms of malicious scripts (e.g. hanging the game's Lua instance thread via a while 1 loop; or huge memory use, complex string.match calls for e.g.) you have to do more complex work and add more constraints to the environment given to mod scripts.
E.g. even a while 1 do end will still hang the WOW UI.
Hope that helps.
just don't use luaL_openlibs. Another option would be to have some lua code exist in your c program as a string or bytecode, that you execute before anything else.

Use functions from a different program

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.

erlang embedded into C

I'm looking to embed the Erlang VM into C code... Im familiar with ports, linkedin drivers, etc.
I want the C program to start the Erlang VM, and then pass messages to Erlang processes, and have those pass messages back to C code. I dont want the erlang VM to be the one that starts first and then invokes C code occasionally. I have my reasons.
I know that this negatively affects stability guarantees given by Erlang, meaning that when the master C code crashes it will taken down the Erlang VM also, since they're running in the same process. Im willing to live with those occurrences...
is this even possible?
The easiest way would be to just launch it as a separate process, and then use stdin and stdout to communicate. Just reading the docs of whatever platform you're targeting will let you know how to do that.
The only sane way to do this is to load the C code from the Erlang VM, not vice versa.
It's not possible out of the box, but since you have access to the Erlang source it's clearly possible to do whatever you want if you're willing to spend a lot of time modifying the code. It's not a good use of your time to go down this path.

what does driver program mean?

there is a quote from Algorithms for Java (sedgwick 2003) p. 135:
"we commonly use driver programs when developing or debugging adt iplementations"
what is meant by driver program?
google just gives me loads of info about programming drivers, clearly not related
In this context a driver program is just a program that uses the class or algorithm that you're developing. It's primarily used for testing your code while you develop it.
A Driver program, as I understand it, is just a simple class that instantiates the overall program you have created.
In University programs, we started learning Java by making very simple Drivers, that just passed in parameters to random classes and methods.
It's simply a program designed to call various APIs and pieces of logic you are working with. E.g. if you have a library that reads XML files, does some sort of transform on it, and writes the transformed data into another file, to work with that library you create a driver program which does nothing but call those 3 APIs and does error handling - e.g. it drives/directs your API to do its work.
A driver is generally a (relatively) simple executable program designed to exercise some component that isn't directly executable, like a library or ADT or test suite, etc. For example you might have a Table class that supports reading in CSV, and supports outputting to CSV and HTML. You might write a simple program that takes on the command line the name of an input CSV file and a format to output to so you can confirm the Table class does what you expect. All the driver would do is construct an instance of the Table and read in the file and use it to write out in the specified format.

fork/chroot equivalent for Windows server application

I have written a small custom web server application in C running on Linux. When the application receives a request it calls fork() and handles the request in a separate process, which is chrooted into a specific directory containing the files I want to make available.
I want to port the application to Windows, but neither fork() nor chroot() are available on this platform, and there don't seem to be any direct equivalents. Can you point me to a simple (and preferably well written) example of code that will provide this functionality in Windows? My C isn't all that good, so the simpler the better.
First of all, the Windows equivalent of chroot is RUNAS which is documented here. If you need to do this from a program, then studying this C++ source code should help you understand how to use the Windows API. It is not precisely the same as chroot() but Windows folk use it to create something like a chroot jail by creating a user with extremely limited permissions and only giving that user read permission on the application folder, and write permission on one folder for data.
You probably don't want to exactly emulate fork() on Windows because it doesn't sound like you need to go that far. To understand the Windows API for creating processes and how it differs from fork(), check Mr. Peabody Explains fork(). The actual current source code for Cygwin's fork implementation shows you the current state of the art.
The Microsoft documentation for CreateProcess() and CreateThread() are the place to look for more info on the differences between them.
And finally, if you don't want to learn all the nitty-gritty platform details, just write portable programs that work on Windows and Unix, why not just use the Apache Portable Runtime library itself. Here are some docs on process creation with some sample code, in C, to create a new process.
There's no such thing as fork() on Windows. You need to call CreateProcess() - this will start a separate process (mostly equivalent to calling fork() and then immediately exec() for the spawned process) and pass the parameters to it somehow. Since you seem to have all the data to process in a dedicated directory you can make use of lpCurrentDirectory parameter of CreateProcess() - just pass the directory path you previously used with chroot() there.
The absolutely simplest way of doing it is using Cygwin, the free Unix emulation layer for Windows. Download it and install a complete development environment. (Choose in the installer.) If you are lucky, you will be able to compile your program as is, no changes at all.
Of course there are downsides and some might consider this "cheating" but you asked for the simplest solution.
Without using a compatibility framework (Interix, Cygwin, ...) you're looking at using the Windows paradigm for this sort of thing.
fork/vfork is a cheap operation on UNIXes, which is why it's used often compared to multi-threading. the Windows equivalent - CreateProcess() - is by comparison an expensive operation, and for this reason you should look at using threads instead, creating them with CreateThread(). There's a lot of example code out there for CreateThread().
In terms of chroot(), Windows doesn't have this concept. There's libraries out there that claim to emulate what you need. However it depends why you want to chroot in the first place.
Reading comments, if it's simply to stop people going up the tree with ../../../../(etc), chroot would do the job, but it's no substitue for parsing input in the first place and making sure it's sane: i.e., if too many parents are specified, lock the user into a known root directory. Apache almost certainly does this as I've never had to create a chroot() environment for Apache to work...
Using fork/chroot is simply not how things are done on Windows. If you are concerned about security in subprocesses, maybe some form of virtualization or sandboxing is what you want to use. Passing complex information to the subprocess can be done by some form of RPC-solution.
It sounds to me as if you have designed your application in the Unix way, and now you want to run in on Windows without having to change anything. In that case, you may want to consider using Cygwin, but I'm not sure if/how Cygwin emulates chroot.
Consider SUA ( aka Windows Services for Unix ). It has nearly everything you need to port applications.
man chroot(interix)

Resources