I'm attempting to get the module name for each thread in a process. Process explorer shows the name of the module associated with each thread no problem. I can enumerate all modules and all threads in my current process with no problems, and get data related to them. My current method of deducing the associated module is the following:
if(module.BaseAddress < thread.StartAddress && (module.BaseAddress + module.BaseMemorySize) > thread.StartAddress)
{
// this is our module ;)
}
Unfortunately, that doesn't seem to be a concrete way of doing it. The xfire_toucan.dll module shows in procexp fine:
1972 : xfire_toucan.dll!ToucanSendGamestatsConsoleLine_V1+0x80
In the list of modules, it shows with a base addr of 0x10000000 and a size of 0x26b000, giving us a max memory addr of 0x1026b000. However, the associated thread start address is 0x775e2ca0, which is part of an allocated block of memory in the process outside the module's main memory range.
Any idea how to get the module like ProcExp does?
I know C and C#, so either is fine, but my project is C# so that's preferred :]
Process explorer isn't showing you the module associated with each thread. Windows does not maintain this information. It's showing you the symbol name for the thread's entry point. This will usually (but not always) be a function in the module that started the thread. If you want to retrieve this sort of information in your program, you can use the debug help API. They're probably using the StackWalk64 function to retrieve the entry point name.
Related
Process.Handle is returning different values every time, is this correct?
From msdn, "The handle that the operating system assigned to the associated process when the process was started. The system uses this handle to keep track of process attributes."
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.handle?view=netcore-3.1
Isn't supposed to be constant if not unique?
Tried different ways of getting the process but the Handle is different everytime.
Ex:
Process.GetProcesses().FirstOrDefault(...)
OR
Process.GetProcessById(123)
OR
Process.GetProcessesByName("xyz")
I'm trying to hold a process id of a process that is launched by my application and this id will be used "later" to get the process from the running processes to stop it, if it is still running in a particular case. I don't want to check with name as the same application can be launched externally.
Trying to add another layer of validation to make sure any other process is not running with same id later(if my expected process is already stopped and the same id is used for restarting same application or any other application)
Is the Process.Handle property expected to be varying or Any other way to do the same?
It's "a handle for a process" not "the handle for a process". It is a quantity that allows a program to operate on a process, not the sole identifier of a process.
The same is true for any other Windows kernel handle. For example, if you open the same file twice by 'the usual methods', you'll have two different handles for the same thing.
As long as the process has not terminated or there is still one handle open that refers to the process, its process id is the actual unique identification. The id can be reused later however.
I can't answer why the documentation says what it does.
'm trying to hold a process id of a process that is launched by my application and this id will be used "later" to get the process from the running processes to stop it,
Just hold onto the Process instance, then you can skip the "get the process from the running processes".
You need to do this anyway to prevent the process ID from being reused. The process ID is constant for the lifetime of the process-tracking kernel data object, which really means "as long as either the process is alive or someone keeps an open handle to it". By keeping a Process object instance, you keep a handle open, and keep the process ID valid.
I have two separate programs, one is a console application, and the other one is a windows application.
My windows application:
Has a graphic interface, buttons, and others functions.
One of the buttons, named "research": when I click on it, I launch the console application with this line of code:
string strResult = ProcessHelper.LaunchProcessWaitForPipedResult("MyExecFile.exe", strArguments, 10 * 60 * 1000, true); // 10 mins max
My console Application:
do a query on all existing files in a directory.
My problem:
I want to create a progress-bar on the windows application to show the progress of the console application. The problem is I don't know how to pass this information between the two processes. The only restriction is to not use a database or file.
Given two processes in the same user session, and wanting to avoid any communication outside that session I would look at three options:
1. Using named pipes.
The parent process creates a named pipe using a random name (and confirms that name is not in use by opening it). It passes that name to the child process. A simple protocol is used that allows the child to send updates.
There are a number of challenges to overcome:
Getting the logic to ensure the name is unique right (named pipe names are global).
Ensuring no other process can connect (the default named pipe ACL limits connections to the session: this might be enough).
Handling the case where a different parent process does not support progress updates.
Handling the child or parent crashing.
Avoiding getting too clever with the communication protocol, but allowing room for growth (what happens when more than a simple progress bar is wanted?)
2. Using Shared Memory
In this case names of objects are, by default, local to the session. By default this is more secure.
The parent process creates a sufficiently large amount of shared memory (for a simple progress update: not much), a mutex and an event.
The parent process then, concurrently with the GUI waits for the event to be signalled, when it is it enters the mutex and reads the content of shared memory. It then unsets the event and leaves the mutex.
Meanwhile to send an update the child enters the mutex, updates and memory and sets the event before leaving the mutex.
The challenges here include:
Defining the layout of the shared memory. Without a shared assembly this is likely to be error prone.
Avoiding others using the shared memory and synchronisation objects. .NET makes things harder here: in Win32 I would make the handles inheritable thus not needing to name the objects (except for debugging) and pass to the child directly.
Getting the sequencing of shared memory, mutex and event correct is critical. Memory corruption and more subtle bugs await any errors.
It is harder to do variable length data with shared memory, not an issue for a simple progress count but customers always want more.
Summary
I would probably look at named pipes in the first place (or perhaps custom WMI types if I wanted greater flexibility). BUT I would do that only after trying everything to avoid needing multiple processes in the first place. A shared library plus console wrapper for others, while I use the library directly would be a far easier option.
If an executable is made to run as a window service and someones tries to edit its memory or inject some code into, this becomes harder?
I mean , since the process is shown only in the services list rather than the processlist it means that it is harder to hook it and there must be other methods of editing the memory/hooking the process .
Thanks in advance,
I am writing a piece of code whereby I am to iterate through the list of modules loaded by the System process (PID : 4). The following is the code I am using to achieve it.
Process process = Process.GetProcessById(4);
foreach (ProcessModule pMod in process.Modules)
{
Console.Write(pMod.FileName + " ");
}
Console.WriteLine();
This code is throwing an error of System.ComponentModel.Win32Exception, whenever it is trying to evaluate the list of Modules. In effect, any property read or method call is throwing the same error. Any other process is working fine and it is able to list all the modules correctly. Could anyone shed light on what might be causing this behavior.
The System "process" (with PID 4 on Windows machines) is actually not a process at all, it denotes a group of processes that have SYSTEM integrity.
Try to work with a real process PID (for instance, run Internet Explorer, and use it's PID) instead, see if you`ll get the exception.
The system process is not a real user mode process, it is the Windows kernel (for want of a better description). Therefore it cannot be examined as if it were a normal process.
In all WPF application I develop there is a global exception handler subscribed to AppDomain.CurrentDomain.UnhandledException which logs everything it can find and then shows a dialog box telling the user to contact the author, where the log file is etc. This works extremely well and both clients and me are very happy with it because it allows fixing problems fast.
However during development of a mixed WPF / C# / CLI / C++ application there are sometimes application crashes that do not make it to the aforementioned exception handler. Instead, a standard windows dialog box saying "XXX hast stopped working" pops up. In the details it shows eg
Problem Event Name: BEX
Application Name: XXX.exe
Fault Module Name: clr.dll
...
This mostly happens when calling back a managed function from within umanaged code, and when that function updates the screen. I didn't took me long to figure out the root cause of problem, but only because I can reproduce the crash at my machine and hook up the debugger: in all occasions the native thread was still at the point of calling the function pointer to the managed delegate that calls directly into C#/WPF code.
The real problem would be when this happens on a client machine: given that usually clients are not the best error reporters out there it migh take very, very long to figure out what is wrong when all they can provide me are the details above.
The question: what can I do to get more information for crashes like these? Is there a way to get an exception like this call a custom error handler anyway? Or get a process dump? When loading the symbols for msvcr100_clr0004.dll and clr.dll (loaded on the thread where the break occurrs), the call stack is like this:
msvcr100_clr0400.dll!__crt_debugger_hook()
clr.dll!___report_gsfailure() + 0xeb bytes
clr.dll!_DoJITFailFast#0() + 0x8 bytes
clr.dll!CrawlFrame::CheckGSCookies() + 0x2c3b72 bytes
Can I somehow hook some native C++ code into __crt_debugger_hook() (eg for writing a minidump)? Which leads me to an additional question: how does CheckGSCookies behave on a machine with no debugger installed, would it still call the same code?
update some clarification on the code: native C++ calls a CLI delegate (to which a native function pointer is acquired using GetFunctionPointerForDelegate which in turn calls a C# System.Action. This Action updates a string (bound to a WPF label) and raises a propertychanged event. This somehow invokes a buffer overflow (when updating very fast) in an unnamed thread that was not created directly in my code.
update looking into SetUnhandledExceptionFilter, which didn't do anything at first, I found this nifty article explaining how to catch any exception. It works, and I was able to write a minidump in an exception filter installed by using that procedure. The dump gives basically the same information as hooking the debugger: the real problem seems to be that the Status string is being overwritten (by being called from the native thread) while at the same time being read from the ui thread. All nice ans such, but it does require dll hooking which is not my favorite method to solve things. Another way would still be nice.
The .NET 4 version of the CLR has protection against buffer overflow attacks. The basic scheme is that the code writes a "cookie" at the end of an array or stack frame, then checks later if that cookie still has the original value. If it has changed, the runtime assumes that malware has compromised the program state and immediately aborts the program. This kind of abort does not go through the usual unhandled exception mechanism, that would be too exploitable.
The odds that your program is really being attacked are small of course. Much more likely is that your native code has a pointer bug and scribbles junk into a CLR structure or stack frame. Debugging that isn't easy, the damage is usually done well before the crash. One approach is to comment out code until the crash disappears.