Multiple instance of a dll in c++ - c++

I have 10.000 devices and I want to control them by one c++ application. Devices are server and I can control them only by dll. Dll is written for MFC and it wasn't written by me so i cant chance anything on it.
Dll establishs the TCP/IP communication between devices and my application.Every device has different variables. I need to open a new thread for each incoming connection and load an instance of my dll. I couldn't load the different instances of a dll for each thread. everytime it is using the same dll and same data.
How can load multiple instance of a dll ?
Is there any way to do it with c++.
Thanks in Advance

If the data are static it is not possible to have more instance in the same process. You have to modify the dll to have some sort of per context data ( usually class instance would do ). As a general suggestion anyway, never starts up to 10000 thread on a process, this will kill the performance. Write a thread pool and let manage the client be served by that pool.

Your situation does not sound hopeful.
Windows will not load more than one instance of a DLL within a given process, ever. If the DLL itself doesn't have the functionality to connect to multiple servers, you would have to create a separate process for each server you need to connect to. In practice, this would be a Bad Idea.
You COULD use LoadLibrary() and UnloadLibrary() to "restart" the DLL multiple times and switch frantically between the different servers that way. Sort of a LoadLibrary()... mess with server... UnloadLibrary()... do it againandagainandagain situation. It would be painful and slow, but might work for you.

The only (ugly) way to load a dll multiple times is for every new load you make a copy of the original dll with a unique name in a location that you're in control of.
Load the copy with LoadLibrary and setup appropiate function-pointers (GetProcAddress(...)) to functions in newly loaded dll for use in your program.
After you're done with it Unload the copy with FreeLibrary and remove the copy from disk.

I don't see an easy solution to this, as previously covered, you can't create multiple instances of a DLL within an app.
There may be a horrible solution, which is to write a lightweight proxy to listen for inbound requests, and spawn a new instance of the real app on each request, and forward traffic to it - there should be a way to load a new copy of a DLL in each instance (technically you'll be re-opening the same loaded DLL, but it should have separate data spaces).
However, with 10k devices, performance will be horrible. It sounds like the best solution is either to re-implement the protocol (either use a published spec, or reverse-engineer it).

Related

Require specific event completion before application launch

I'm working on an application (DLL) that logs specific WIN32 calls using Detours. It is injected into a target application that passes the filter. It has to absolutely log every call that the application makes, starting from the first instruction in the application's entry point.
I now am looking for a way to make my application (the one that always runs) inject the DLL as fast as possible, preferably without the target application making any other calls.
Is there any way to achieve this?
You could use the AppInit_DLLs registry key to load a dll into a process. The dll is loaded during DLL_PROCESS_ATTACH of User32.dll. For regular applications this should happen prior to running any application code.
Keep in mind though that AppInit_DLLs should be renamed Deadlock_Or_Crash_Randomly_DLLs.
As far as I know, there's no straightforward way of doing this in Windows.
Your options are:
Hooking the CreateProcess (or lower) function in all processes. When a new process is created, change the arguments to create it as suspended, inject, and resume if needed.
Using a driver.

Prevent McAfee Dlls injection

I have a process that doing some inline hooks on WinSock module (Send and Receive functions).
On a machine with McAfee I can see that two dlls are being injected into my process:
hipi.dll
hipqa.dll
Both are also doing probably inline hooking on those functions and I get collisions and unwanted behaviors. Is there an option to prevent/unload those dlls so they will not interfere?
10x,
Guy
There are many scenario to achieve DLL injection(Hooking), BTW, you must learn more about how stuff works behind every method, the most common one is by using CreateRemoteThread() API function, then you must to inject your security DLL on every process and hook/redirect/deny any call to CreateRemoteThread() or any "dangerous" API call.
PS: BUT keep in your mind:
user-mode hooking can NEVER be an option to apply additional security
checks in any safe manner. If you only want
to “sandbox” a dedicated process, you know well about, and the process in fact doesn’t know about
EasyHook, this might succeed! But don’t ever attempt to write any security software based on user
mode hooking. It won’t work, I promise you…
You have 2 options.
Add an exclusion for your process so that McAfee doesn't attempt to scan it. I don't use McAfee's products, but I would assume that this would be a relatively straightforward process.
Uninstall McAfee
The easiest solution is to just unhook the affected functions. I had to do the same to work around some Dell crapware. It's not excessively hard, even though it requires some understanding of x86 assembly. You have to disable DEP, make the patched code writeable, find the original instructions, and copy them back. Finding the original instructions probably means disassembling the patch.
Another alternative is simply to hook it at a different place. For example, hook the IAT instead and then when you are done with whatever you want, forward execution back to the real function where it will then go through McAfee's hook.
I've had to deal with something similar once. Read their own hook assembly stub, so you can figure out how to hook in a way you chain to their hook after yours.
I'd imagine that McAfee are performing DLL injection from kernel-mode. They are likely finding the address of the KeServiceDescriptorTable (exported by NTOSKRNL on 32-bit systems and the address to it is leaked on 64-bit environments by KiSystemServiceRepeat -> close to KiSystemCall64 found by the IA32_LSTAR Model Specific Register) and then locating NtCreateThreadEx from the service table, or they're using KeInitializeApc and KeInsertQueueApc (both exported by NTOSKRNL) for APC injection (custom NtQueueApcThread wrapper). That would be logical considering they are a security vendor with a lot of resources, I doubt they'd be injecting from user-mode.
The likelihood is they are abusing PsSetCreateProcessNotifyRoutineEx or PsSetLoadImageNotifyRoutineEx to detect new process creation. The first one is not as good as the latter, the latter is better for filtering of NTDLL.DLL since it is the first module loaded into every single process, and signifies the process has actually started up properly and is just about ready to execute its own code (after the Windows module loads, and because McAfee will need to wait for Win32 modules like kernel32.dll to be loaded otherwise they'll crash the process if they use the Win32 API at all in their injected modules).
You can try intercepting LdrInitializeThunk or KiUserApcDispatcher, but honestly, there's not much you can do. McAfee will find a way to inject into your process no matter what you do, because they have control from kernel-mode. If you develop process protection via a variety of kernel-mode callbacks from a driver, they'll bypass it using non-exported routines located via pattern match scanning of ntoskrnl.exe, or exported routines which don't invoke the callback notification APIs. If you locally patch routines invoked for thread creation/APC locally in your own process when performed by a remote attacker, they'll find ways to prevent this and bypass it (e.g. patch the patched routines in the address space of your process back to the original, inject, then re-patch the bytes back).
You're playing with fire if you want to stop security software with the privileges McAfee has. It is similar to how Anti-Cheat cannot stop game hackers who have kernel-mode access, and go do drastic measures of even flagging Debug Mode/Test Mode enabled nowadays.

Problems with running multiple instances of an application?

I have a client application (C++, Windows) that opens sockets, connects to a server, makes requests, receive responses and notifications. It does logging and saves preferences locally. What can be problems if I try to run multiple instances of this application which is prevented presently?
Are you having a particular problem you are seeing? ie - is the application crashing when you execute a second instance?
From your description, you could fail to open the executable if the second application
Tries to open the same socket the first opens
Tries to open the same file the first opens
Outside of that, more detail is needed.
Sounds a little bit like a Web browser ;)
And like a typical Web browser, if your application is implemented correctly, you'll be able to run multiple instances fine.
Unfortunately, there are ways to botch the implementation, for example:
Exclusively lock log or configuration files for prolonged periods, thus "stalling" other instances.
Just plain ignore the concurrent access to files, leading to all sorts of possible corruptions.
Act not just as a client but as a server as well, and listen to a hard-coded port (so the second instance will fail while attempting to open the same port).
Incorrectly declare a mutex as "public" (and therefore shared between processes) instead of "private", leading to slow-downs and possibly deadlocks.
There is a limit for number of GDI handles per session. If you application uses excessive handles, multiple instances taken together might reach that limit, even when each of them individually observes the 10000 handles-per-process limit.
Be a CPU hog (e.g. through busy waiting). One CPU hog on a modern multicore CPU might pass unnoticed, but once the number of instances exceeds the number of CPU cores that's another story!
Be a memory hog.
Mismanage UI:
Use UI tricks such as "always on top" windows - multiple such windows on the screen at the same time is no fun!
Mismanage the taskbar notification area (e.g. display a tray icon for each instance). Will technically "work" but having excessive number of tray icons is not pleasant, especially if application does not also have a "regular" taskbar button.
Etc etc... Essentially whenever there is a shared resource (be it a filesystem, network, CPU, memory, screen or whatever), care must be taken when concurrently using it.
If your application is opening port for listening, only one instance could use that one particular port. If application is connecting to the remote host, OS will always pick the next available port so multiple instances can run in parallel in this case.
If all instances are sharing the same log and/or configuration file, parallel write might corrupt those files so writing operations should be protected by some synchronisation object (e.g. mutex).
By problems I presume you mean that multiple applications each do not create their own workspace for logging and preferences. Which would result in one instance overwriting and access data made by the other, resulting in undesired, and unpredictable results.
If you have access to the source code of the application I would suggest extending the application to create a folder with name that contains time stamped plus randon number to hold the session data - i.e. the logs and the preferences. This way, multiple instances can operate without interfering with one another.
However bear in mind that some preferences may be best made global - to save you having to set the preferences each time you load a new instance. It depends on your application and what it is doing as to what these global preferences may be.
If you don't have access to the source then the other option for multiple instances would be via virtualisation, multiples OSs on same machine each OS running one instance of the app.

How can I update an in-use COM DLL?

One part of some software I have written is a COM dll.
Other software uses this COM dll.
My software has an update function where it will download a newer version of the dll, but the update will fail if the dll is in use because the file cannot be deleted or written to.
The question is, how can I update a COM dll that is in use?
I have considered popping up a message asking the user to close any applications that are using the DLL if it is in use, if this is the best solution how would I go about detecting if the COM dll was in use before popping up the message?
Thanks in advance.
You cannot update it in place for existing applications, but one way to do this would be to save it with a different file name or different folder and call DllRegisterServer on the DLL to register it under the new name. New applications which begin using your object should now use the new version.
If this is just a matter of detecting whether you can replace the file then it is easy. Just try to open it with a share flag that denies reading. That's going to fail if the DLL is loaded in another process. Use _fsopen() or CreateFile(). Beware of the race condition.
Detecting which processes have the file loaded is a harder problem, CreateToolhelp32Snapshot() and Process32First/Next plus Module32First/Next to enumerate processes and the DLLs they have loaded. Still tough to generate a good diagnostic for the user, the process name isn't that helpful.
When you have downloaded the update, you must launch a third program (which you write) that does not have any dependancies on your COM component, or any other piece that is to be updated. This launcher, or bootstrapper, must shut down all your pieces, uninstall them, and install the update. When the update is installed you may then re-launch your application.
If you need also to download updates to the updater itself, your main program can do that.
Here is a simple solution for you. Create a wrapper DLL, which will be used by the other processes. Inside that DLL you explicitly load/unload your DLL, which is subject to updates. Of course you will have to suspend all callers when an update process kicks in.

How to load a DLL as a local server

I really need help...
I have implemented a COM component (i.e A.dll) with IDL, also coded a wrapper DLL (B.dll) for that component. I have implemented required export functions for DLL "A" and registered it with "regsvr32.exe".
Problem is that I have 3 EXE files that uses B.dll to access methods of A.dll. But, I could not manage to create a local server for A.dll, therefore every EXE loads a new A.dll and B.dll. I want to load A.dll only once, and need to realize this functionality in B.dll. Last statement is open for discussion also.
However, I could not manage to find any useful example or resource regarding this problem. Any help will be appreciated, thanks in advance.
A DLL mediated by COM is known as an in-process server. Which suggests your problem: it will always be mapped into the memory space of its clients, just like any other DLL. Similarly any DLLs it loads will be mapped into the original process. It is not clear from your question why you don't want to use a DLL. If it is to save resources then consider that only data will be duplicated; the code will only be loaded once. If it is because you want them to share data, then consider using shared memory. If you really want all three .exe's to be served by an instance then what you need is a COM local server, which will be implemented by an .exe, not a .dll.
There's no such thing as "create a local server". In-proc server has to be loaded into each consumer process, there's no way around that - each consumer is a separate process, so it has its own copy of code and data.
In order to have a single process executing COM server code for all of the consumers you have to create an out-proc server. To do the latter you can either reengineer your COM server or try to use COM+ server application. This way you can have a separate process running the COM server code several consumers can connect to.