Why is a code segment common to different instances of the same program

I wanted to know why a segment of code is shared across different instances of the same program.

For example: Consider running P1.exe, if another copy of P1.exe is running, the code segment will be propagated to both running instances. Why is this so?

Your answer will be much appreciated.

Thanks in advance.

+2


source to share


4 answers


If the segment of code in question is being loaded from a DLL, the operating system may be smart and reuse an already loaded library. This is one of the main points of using dynamically loaded library code, which allows code to be shared across multiple processes.

Not sure if Windows is smart enough to do this with regular EXE code sections, but that would be smart if possible.



It can also be virtual memory tricking you; the two processes may look like they have the same thing at the same address, but that address is virtual, so they do map to physical memory mappings.

+5


source


The code is usually read-only, so it would be wasteful to make multiple copies of it.

Also, Windows (at least I can't speak for other OSes at this level) uses the paging framework to inject page code directly from the executable, as if it were a paging file. Since you are dealing with the same executable, this is a search query from the same location at the same location.



Self-modifying code is actually no longer supported by modern operating systems. Generating new code is possible (by setting the correct flags when allocating memory), but this is separate from the original code segment.

+2


source


The code segment is (presumably) static (not changing), so there is no reason not to use it for multiple instances.

+1


source


EDIT: Oh maybe I misinterpreted the question. I thought he was asking why both processes have the same value in the code segment register.

To start at a basic level, Segmentation is just a way to implement memory isolation and partitioning. Paging is another way to achieve this. For the most part, anything you can achieve through segmentation, you can achieve through paging. Thus, most modern operating systems on x86 forego use sharding at all, instead relying entirely on paging objects.

Due to this, all processes will usually run under a trivial segment (Base = 0, Limit = 4GB, Privilege level = 3), which means that the code / data segment registers do not play any real role in determining the physical address, and are simply used to set the privilege level of a process. All processes usually run with the same privilege, so they must all have the same value in the segment register.

0


source







All Articles