Position-independent code


In computing, position-independent code or position-independent executable is a body of machine code that, being placed somewhere in the primary memory, executes properly regardless of its absolute address. PIC is commonly used for shared libraries, so that the same library code can be loaded in a location in each program address space where it will not overlap any other uses of memory. PIC was also used on older computer systems lacking an MMU, so that the operating system could keep applications away from each other even within the single address space of an MMU-less system.
Position-independent code can be executed at any memory address without modification. This differs from absolute code, which must be loaded at a specific location to function correctly, and load-time locatable code, in which a linker or program loader modifies a program before execution so it can be run only from a particular memory location. Generating position-independent code is often the default behavior for compilers, but they may place restrictions on the use of some language features, such as disallowing use of absolute addresses. Instructions that refer directly to specific memory addresses sometimes execute faster, and replacing them with equivalent relative-addressing instructions may result in slightly slower execution, although modern processors make the difference practically negligible.

History

In early computers such as the IBM 701 and IBM System/360, code was position-dependent: each program was built to be loaded into, and run from, a particular address. Where a multitasking operating system allowed multiple jobs to be run using separate programs at the same time, operations had to be scheduled such that no two concurrent jobs would run programs that required the same load addresses. For example, both a payroll program and an accounts receivable program built to run at address 32K could not both be run at the same time.
IBM DOS/360 did not have the ability to relocate programs during loading. Sometimes multiple versions of a program were maintained, each built for a different load address. A special class of programs, called self-relocating programs, were coded to relocate themselves after loading. IBM OS/360 relocated executable programs when they were loaded into memory. Only one copy of the program was required, but once loaded the program could not be moved.
By way of comparison, on early segmented systems such as Burroughs MCP on the Burroughs B5000 and Multics, paging systems such as IBM TSS/360 or base and bounds systems such as GECOS on the GE 625 and EXEC on the UNIVAC 1107, code was inherently position-independent, since addresses in a program were relative to the current segment rather than absolute.
Position-independent code was developed to eliminate these restrictions for non-segmented systems. A position-independent program could be loaded at any address in memory.
The invention of dynamic address translation originally reduced the need for position-independent code because every process could have its own independent address space.
However, multiple simultaneous jobs using the same code created a waste of physical memory. If two jobs run entirely identical programs, dynamic address translation provides a solution by allowing the system simply to map two different jobs' address 32K to the same bytes of real memory, containing the single copy of the program.
Different programs may share common code. For example, the payroll program and the accounts receivable program may both contain an identical sort subroutine. A shared module gets loaded once and mapped into the two address spaces.

Technical details

Procedure calls inside a shared library are typically made through small procedure linkage table stubs, which then call the definitive function. This notably allows a shared library to inherit certain function calls from previously loaded libraries rather than using its own versions.
Data references from position-independent code are usually made indirectly, through Global Offset Tables, which store the addresses of all accessed global variables. There is one GOT per compilation unit or object module, and it is located at a fixed offset from the code. When a linker links modules to create a shared library, it merges the GOTs and sets the final offsets in code. It is not necessary to adjust the offsets when loading the shared library later.
Position independent functions accessing global data start by determining the absolute address of the GOT given their own current program counter value. This often takes the form of a fake function call in order to obtain the return value on stack or in a special register, which can then be stored in a predefined standard register. Some processor architectures, such as the Motorola 68000, Motorola 6809, WDC 65C816, Knuth's MMIX, ARM and x86-64 allow referencing data by offset from the program counter. This is specifically targeted at making position-independent code smaller, less register demanding and hence more efficient.

Windows DLLs

in Microsoft Windows use variant E8 of the CALL instruction. These instructions do not need to be fixed up when a DLL is loaded.
Some global variables are expected to contain an address of an object in data section respectively in code section of the dynamic library; therefore, the stored address in the global variable needs to be updated to reflect the address where the DLL was loaded to. The dynamic loader calculates the address referred to by a global variable and stores the value in such global variable; this triggers copy-on-write of a memory page containing such global variable. Pages with code and pages with global variables that do not contain pointers to code or global data remain shared between processes. This operation needs to be done in any OS that can load a dynamic library at arbitrary address.
In Windows Vista and later versions of Windows, the relocation of DLLs and executables is done by the kernel memory manager, which shares the relocated binaries across multiple processes. Images are always relocated from their preferred base addresses, achieving address space layout randomization.
Versions of Windows prior to Vista require system DLLs to be prelinked at non-conflicting fixed addresses at the link time in order to avoid runtime relocation of images. Runtime relocation in these older versions of Windows is performed by the DLL loader within the context of each process, and the resulting relocated portions of each image can no longer be shared between processes.
The handling of DLLs in Windows differs from the earlier OS/2 procedure from which it derives. OS/2 presents a third alternative and attempts to load DLLs that are not position-independent into a dedicated "shared arena" in memory, and maps them once they are loaded. All users of the DLL are able to use the same in-memory copy.

Multics

In Multics each procedure conceptually has a code segment and a linkage segment. The code segment contains only code and the linkage section serves as a template for a new linkage segment. Pointer register 4 points to the linkage segment of the procedure. A call to a procedure saves PR4 in the stack before loading it with a pointer to the callee's linkage segment. The procedure call uses an indirect pointer pair with a flag to cause a trap on the first call so that the dynamic linkage mechanism can add the new procedure and its linkage segment to the Known Segment Table, construct a new linkage segment, put their segment numbers in the caller's linkage section and reset the flag in the indirect pointer pair.

TSS

In IBM S/360 Time Sharing System each procedure may have a read-only public CSECT and a writable private Prototype Section. A caller loads a V-constant for the routine into General Register 15 and copies an R-constant for the routine's PSECT into the 19th word of the save area pointed to be GR13.
The Dynamic Loader does not load program pages or resolve address constants until the first page fault.

Position-independent executables

Position-independent executables are executable binaries made entirely from position-independent code. While some systems only run PIC executables, there are other reasons they are used. PIE binaries are used in some security-focused Linux distributions to allow PaX or Exec Shield to use address space layout randomization to prevent attackers from knowing where existing executable code is during a security attack using exploits that rely on knowing the offset of the executable code in the binary, such as return-to-libc attacks.
Apple's macOS and iOS fully support PIE executables as of versions 10.7 and 4.3, respectively; a warning is issued when non-PIE iOS executables are submitted for approval to Apple's App Store but there's no hard requirement yet and non-PIE applications are not rejected.
OpenBSD has PIE enabled by default on most architectures since OpenBSD 5.3, released on. Support for PIE in statically linked binaries, such as the executables in /bin and /sbin directories, was added near the end of 2014. openSUSE added PIE as a default in 2015-02. Beginning with Fedora 23, Fedora maintainers decided to build packages with PIE enabled as the default. Ubuntu 17.10 has PIE enabled by default across all architectures. Gentoo's new profiles now support PIE by default.
Android enabled support for PIEs in Jelly Bean and removed non-PIE linker support in Lollipop.