18

On typical computers like Mac, Windows, Linux, iOS, etc., when a user launches a program/binary/app, is the static portion of the program always loaded entirely into memory before execution starts? Does this include all of the segments/sections of data in the program like strings and any other embedded BLOB data? Let's say I embedded a huge image file into the binary (e.g. in the __DATA segment). Would this image data be loaded entirely into memory upon launch?

Synthetix
  • 2,035
  • 3
  • 24
  • 30
  • 13
    On systems with paging-support, usually almost everything (including programs) is faulted in on-demand. – EOF Jul 30 '15 at 11:45

1 Answers1

28

Under OS X, Windows, Linux, and iOS executables are not loaded into RAM when executed. Instead the executable is mapped into the virtual address space of the process. When the process accesses a mapped page of the executable that hasn't loaded into RAM yet, the CPU generates a page fault which the OS handles by reading the page into RAM.

So if you put a huge image file in the data section of your executable, it won't be loaded into RAM until your program first accesses it. A huge image file probably takes of multiple pages of memory (which are generally 4K in size), so if your program only accesses part of the image only part of the image will be loaded into RAM.

Note that under Windows, and maybe other operating systems, there's an significant exception to this. Under Windows an operating system service called the prefetcher will start preloading into memory the parts of any file that it predicts the program will access during start up. It makes these predictions based on the recorded start up access patterns of previous runs of the program. Since "any file" includes the executable itself, along with any DLLs or data files it uses, this means parts of the executable will be preloaded into RAM when the process start. This also means that if the program usually displays a large image at program startup (eg. a splash screen) then the preloader will load the image into RAM whether its stored as part of the executable or as a separate data file.

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
  • 5
    There is also another exception on Windows, if the /SWAPFILE flag was set during linking the entire executable will be read in ahead of time. Generally used for executables intended to be run over an unreliable network or from removable media. – Harry Johnston Jul 30 '15 at 21:50
  • Note that that linker flag is /SWAPRUN, and only applies when the executable is run from the network or removable media. Also, this affects all file accesses, which caused issues for the Windows XP developers (among others); Explorer would page in the entirety of every /SWAPFILE:NET executable in a directory to show their icons (which are packaged into the executable). – Zaaier Jun 01 '23 at 20:51