Do processes have their own memory? - windows

I've been reading about the functions of Threads and Process. One major difference between a process and a thread is that a thread shares the resources with the process from which it has been created whereas a process will have its own set of resources. I wanted to test this, so I opened up my Task Manager and opened MS Word and in the task manager, there was a new process called WINWORD.EXE loaded and I again opened another MS Word(Keeping the previous one opened) yet the Task Manager shows only one WINWORD.EXE process running. I just don't get it, since two MS Words are needed to be considered as two separate process(as they don't share resources).

There only is one process in that case. It's just that Word is implemented in such a way that it prevents you creating multiple processes. When you try to start another one, the new process forwards the request to the existing process, and the window is shown by the existing process.
But yes, separate processes do indeed have distinct and isolated address spaces. Try your experiment with a simple program, for instance Notepad.

Related

Relationship between windows exe and processes

I've been trying to understand the relationship between applications, instances, exes and processes.
When i open two different word files on my windows laptop, 2 different 'Processes' show up in Task manager. I can independently kill each one
When i open Process Explorer - I can only see 1 instance of WINWORD.exe. I can't seem to find the processes related to each of the files i opened. Can someone explain whether each file has an associated process or a single process is used to host multiple files?
There's a mixup of several concepts here; executables, processes, what "opening a file" means and "whatever Task Manager shows in its processes tab", which is mostly a lie.
Double-clicking on a document generally1 boils down to a look up on the file extension in the registry and launching the associated executable, passing the path to the clicked file as command line argument.
Whenever an executable is launched, the kernel spawns a process (which roughly means, allocates some virtual memory for it and creates its main thread of execution) and loads the executable in it ("copies"2 it in memory, loads its dependencies and in general performs a lot of tasks necessary to be able to execute the machine code that is stored in it).
What happens next depends entirely on the code of the executable. Most programs will keep executing in the new process; some instead will look for an instance of the program already executing (which may or may not be the same executable), and communicate to it that a new instance has been launched (possibly forwarding to the existing instance the arguments obtained on the command line). This is generally the case for applications where there's a lot of data to share between different instances (so, to save e.g. memory) or where there's interaction between e.g. the various opened documents that is less cumbersome to implement in a single process (IPC is often a pain).
When instead you open a file e.g. from the File → Open menu of an application, that's generally done in the same process; again, when you actually click open it's up to the application to decide whether to open it inside the same process, or to spawn a different one for the other document.
The important concept here, though, is that if you see different top-level windows (≈ windows that you see in the taskbar) it does not mean they come from different processes, a single process may spawn multiple top-level windows (and indeed applications that deal with multiple files in multiple windows often do that). Also, remember that the fact that the 1 open file = 1 window (or 1 application, for what that matters) is just a GUI concept; you may have files that are handled concurrently by multiple processes (databases are a common instance of this).
As for Task Manager: the processes tab doesn't really list processes as they are seen by the system; some are grouped according to some unspecified rule/heuristics, some other processes are expanded to show sub-components (e.g. the various svchost.exe processes); processes that have multiple top-level windows, in particular, are shown "as if" having sub-processes. Clicking on "End task" on these fake sub-processes will actually send a "polite" quit request to the associated window, which will be handled in an application-specific way.
Ultimately, you shouldn't really think too hard about what is shown here. What are actually the "real" processes as understood by the operating system kernel is what is shown in the "Details" tab, which should match what you see in Process Exporer. If you do kill the process here, you'll see that all windows that are managed by it disappear.
I say "generally" because it's actually a lot more complicated than that; file association can do some really complicated stuff that avoids process creation, generally to directly communicate to an already running program that it has to load another file, essentially skipping the middleman described in the section that follows.
In quotes because it's smarter than that; what is generally done is a copy-on-write file mapping, which instructs the OS virtual memory manager to load the parts of the executable that are needed from disk when they are accessed in memory, and to copy on the fly the sections that are modified.

Diagnosing Win32 RegisterClass leak

We are trying to troubleshoot a nasty problem on a production server where the server will start misbehaving after running for awhile.
Diagnostics have led us to believe there may be a bug in a DLL that is used by one of the processes running on this server that is resulting in a global atom leak. The assumed vector is a process that is calling RegisterClass without a corresponding UnregisterClass (and the class name is using a random number as part of the name, so it's a different class name each time the process starts).
This article provided some information: https://blogs.msdn.microsoft.com/ntdebugging/2012/01/31/identifying-global-atom-table-leaks/
But we are reluctant to attempt kernel mode debugging on a production server, so we have tried installing windbg and using the !gatom command to list atoms for a given session.
I use windbg to attach to a process in one of the sessions (these processes are running as Windows Services if that matters), then invoke the !gatom command. The returned atom list doesn't have any window classes in it.
Then I read this: https://blogs.msdn.microsoft.com/oldnewthing/20150429-00/?p=44984
and it sounds like there is a separate atom table for windows classes. And no way to query it. I was hoping that we'd be able to actually see how many windows class atoms have been registered, and see if that list gets bigger over time, indicating a leak.
The documentation on !gatom is sparse, and I'm hoping I can get some expert confirmation or recommendations on how to proceed.
Does anyone have any ideas on how we can get at the list of registered Windows classes on a production server?
More detail about what happens when the server starts to misbehave:
We run many instances (>50) of the same application as separately registered services running from isolated executables and DLLs - so each of those 50 instances has their own private executables and DLLs.
During their normal run, the processes unload and reload a DLL (about every hour). There is a windows class used that's part of a "session handle" used by the DLL (the session handle is part of the registered windows class name), and that session handle is unique each time the DLL is loaded. So every hour, there is an additional Window class registration, made by a DLL (our service stays running).
After some period of time, the system will get into a state where further attempts to load the DLL in question fail. This may happen for one of the services, then gradually over time, other services will start to have the same problem.
When this happens, restarting the service does not fix the problem. The only way that we've found to get things running properly again is to reboot the server.
We are monitoring memory commit load, and we are well within the virtual memory of the server. We are even within the physical memory size.
I just did a code review the vendor of the DLL, and it looks like they are not actually calling RegisterClass from the DLL itself (they only make one RegisterClass call from the DLL, and it's a static string - not a different class name for each session). The DLL launches an EXE, and that EXE is the one that registers the session specific class name. Their EXE does call UnregisterClass (and even if it didn't, the EXE is terminated when we unload their DLL, so it seems that this may not be what is going on).
I am now out of bullets on this one. The behavior seems like some sort of resource leak or pool exhaustion. The next time this happens, I will try connecting to the failing process with windbg and see what the application atom pool looks like - but I'm not hopeful that is going to shed any light.
Update: The excellent AtomTableMonitor tool has narrowed the problem to rogue RegisterWindowMessage. I'm going to ask a more specific question focused on this exact issue: Diagnosing RegisterWindowsMessage leak
You may try using this standalone global atom monitor
The application appears to have capabilities to monitor atoms in services
that run in a different session
btw if you have narrowed it to RegisterWindowMessage
then spy++ can log the Registered messages system wide along with thread and process
spy++ (i am using it from vs2015 community)
ctrl+m select all windows in system
in the messages tab clear all and select registered
and start logging
you can also save the log (it is plain text in-spite of strange extension )
powershell -c "gc spy++.sxl -Tail 3"
<000152> 001F01A4 P message:0xC1B2 [Registered:"nsAppShell:EventID"] wParam:00000000 lParam:06EDFCE0 time:4:2
7:49.584 point:(408, 221)
<000153> 001F01A4 P message:0xC1B2 [Registered:"nsAppShell:EventID"] wParam:00000000 lParam:06EDFCE0 time:4:2
7:49.600 point:(408, 221)
<000154> 001F01A4 P message:0xC1B2 [Registered:"nsAppShell:EventID"] wParam:00000000 lParam:06EDFCE0 time:4:2
7:49.600 point:(408, 221)

What's the best way to stop multiple instances of a Windows app being launched?

Many Windows apps (like Skype or MSN for instance) don't let you start multiple instances, rather trying to run it a 2nd time just leaves the existing version running.
Is this typically done in some simple way - the start-menu shortcut is a 'wrapper' app around the main app - or is there some registry magic you can do to delegate the problem to Windows itself?
Specifically dealing with Win32 here (unmanaged C++) but happy to hear more general solutions as long as they are workable on Windows XP or later.
EDIT: this seems the best duplicate.
Named Mutex or similar OS-specfic named object. If it exists - app is running.
Lock file somewhere (in temporary directory, etc - create it on program start, remove on program end). Linux software frequently operates this way (some programs store PID in lockfile), but it isn't safe - if you suddenly lose power (electricity cut off), it is possible that lock file won't be deleted.
And you can always enum all running processes and try to find yourself.
There could be more ways to do it, but those are the first ones I could think of.
As far as i remember, there exist system-wide Mutexes. Set Mutex on first launch, if on launch already set, immediately exit.
Use CreateMutex() call an prepend the name with "Global\" should to the trick.
I just check to see if the process is already running: if it's not start the application, if it's already running bring the window to foreground. The check is done in the Main method.
I get the process name with System.Diagnostics.Process.GetCurrentProcess().ProcessName and check if it's already running System.Diagnostics.Process.GetProcessesByName(). If there are more than 1 processes focus the first of them and then exit.

How to force programs out of swap file when a resources-intensive batch finishes?

We use employees' desktops for CPU-intensive simulation during the night. Desktops run Windows - usually Windows XP. Employees don't log off, they just lock the desktops, switch off their monitors and go.
Every employee has a configuration file which he can edit to specify when he is most likely out of office. When that time comes a background program grabs data for simulation from the server, spawns worker processes, watches them, gets results and sends them to the server. When the time specified by the employee elapses simulation stops so that normal desktop usage is not interfered.
The problem is that simuation consumes a lot of memory, so when the worker processes run they force other programs into the swap file. So when the employee comes all the programs he left are luggish and slow until he opens them one by one so that they are unswapped.
Is there a way the program can force other programs out of swap file when it stops simulation so that they again run smoothly?
Loop through system and user processes, starting with one that uses most memory (aside from your background application) or one that is used most by the employee, and send the process a WM_ACTIVATEAPP message. That should have the same effect as "clicking" an application window icon of said process in the taskbar.

HOWTO: Tag a process

I am using CreateProcessAsUser() to make processes. I would like to tag some of them so that later on, given a process ID/handle I can work out whether or not it was I who launched them.
Are there any techniques for marking a process natively like this. I want my solution to be stateless, hence a table of PIDs is not suitable - nor is checking the parent of the process to see if I made it (the processes are reparented).
Any ideas? Thanks!
if you are targeting Windows Vista or Windows Server 2008, then you may use InitializeProcThreadAttributeList() and add the attribute list to the process through the STARTUPINFOEX structure when calling CreateProcess(). however, you have to destroy the attribute list yourself before the process terminates, and it does not seem to be the case from what i understand...
if the process have a window, you can also use window properties, but here again you have to destroy the property list when the window is destroyed, and you don't control this neither...
i am afraid you will have to resort to something else. can you explain why a table of PIDs is unsuitable ? i suspect it is because your "launcher" may terminate and have to find its processes again when it is restarted. in this case you should consider serializing those informations to disk when starting a process, and read them back when restarting (plus some additional checks to verify the validity of the serialized informations).

Resources