1. Home
  2. Explore
  3. Computer Science
  4. Microsoft’s Early Beginnings

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Microsoft’s Early Beginnings

How Windows Turns an Executable into a Running Program

A program does not begin running simply because its file is opened. The operating system must interpret the file, create a protected environment for it, prepare memory and threads, load the libraries it depends on, and then begin executing its code.

To understand that process, it helps to start with the foundations: how programs use memory, how the processor controls access, and how code is organized on disk.

From early personal computers to software for the Altair

In 1975, Paul Allen noticed a Popular Electronics cover featuring the Altair 8800, a personal computer released by MITS the year before. Allen and his friend Bill Gates had been considering starting a software company, but affordable computers for ordinary consumers were not yet common. Most computer systems were expensive machines made for large businesses and research laboratories.

The Altair suggested a new opportunity. Allen and Gates proposed creating a version of BASIC, a programming language, for the computer. Gates told MITS that they already had a working interpreter, although they did not. MITS challenged them to demonstrate one. Allen eventually presented the completed software in Albuquerque, and the successful demonstration led to a contract. Allen and Gates then founded Microsoft.

Microsoft later took on a much larger operating-system project. When IBM was developing the IBM PC under a tight deadline, it needed an operating system. Microsoft bought an existing system called 86-DOS, modified it, and licensed it to IBM as MS-DOS. Microsoft released Windows in 1985 as a graphical interface that ran on top of DOS. Later versions, including Windows 95 and Windows XP, developed into the family of modern Windows systems.

This history introduces the central idea of the lesson: software depends on layers. An application relies on libraries and operating-system services; the operating system relies on the processor and hardware. Windows manages these layers so that programs can run without freely interfering with one another.

Memory, processes, and virtual addresses

Basic units of data

Computers represent information as bits. A byte contains 888 bits. A word is a commonly used unit whose size depends on the context; in the system described here, a word contains 161616 bits. A double word is twice that size, and a quadruple word is four times the size of a word.

These terms matter because software and processor documentation often describe data sizes in words and their multiples. Their exact meaning should be checked for the specific architecture or context being discussed.

A process gets its own address space

When an executable is loaded and begins running, it becomes a process. A process is not just the program’s code. It is the running application together with the resources and state the operating system associates with it.

A key resource is the process’s address space: the range of memory addresses that the process can use. If every process could directly read and write any location in physical memory, programs could accidentally or deliberately damage one another’s data. Managing all those physical locations directly would also be difficult.

Modern operating systems therefore use virtual memory. Each process works with virtual addresses in its own address space. The system translates those virtual addresses into locations in physical memory. This gives each process a more orderly and protected view of memory.

Pages and page tables

Memory is divided into fixed-size chunks called pages. A common page size is 444 kilobytes, or 409640964096 bytes. On the x86-64 system described here, ordinary pages are commonly mapped through a hierarchy of four levels of tables.

Each table has 512512512 entries. Since 512=29512 = 2^9512=29, each level uses 999 bits of the virtual address to select an entry. The address uses three such groups of bits to move through the first three levels and another group to select an entry at the final level. The final 121212 bits identify the byte’s position within a 409640964096-byte page, because 212=40962^{12} = 4096212=4096.

Each table entry is 646464 bits, or 888 bytes, wide. A table with 512512512 entries therefore occupies 409640964096 bytes—the same size as a standard page. The entries contain more than just pointers to lower-level tables or physical pages. Their remaining bits can hold control information, such as whether a page is writable or executable.

The system can also use larger pages, such as pages of 222 megabytes or 111 gigabyte, but those are beyond the basic page-table explanation here.

Shared pages and copy-on-write

Separate address spaces do not require every process to have a separate physical copy of every piece of memory. Two processes can have page tables that refer to the same physical page. Windows can use this to share dynamically linked libraries and save physical memory.

Sharing creates a safety issue if one process tries to modify a page used by other processes. Copy-on-write addresses this problem. A page is initially shared and marked so that a write triggers special handling. When a process attempts to write to it, the operating system creates a new physical copy of the page and changes the writing process’s page-table entry to point to that copy. The process can then modify its private copy without changing the page used by other processes.

Virtual memory gives each process its own view of memory, while still allowing the operating system to share physical pages safely when appropriate.

Think About It: If several applications use the same library, why might it be more efficient to share its pages than to give every application a separate physical copy?

CPU permissions and system calls

Protection rings and privilege

The processor has permission levels that restrict what code can do. These levels are commonly illustrated as protection rings: the lower the ring number, the greater the privilege. In the Windows model discussed here, the two important levels are:

  • Ring 3, or user mode, where ordinary application code runs.
  • Ring 0, or kernel mode, where privileged operating-system code runs.

Rings 1 and 2 are not used in the modern arrangement described here. The distinction between user and kernel mode protects sensitive instructions and data. Windows may map system pages into the upper portion of a process’s virtual address space, but user-mode code is not allowed to access those pages. An attempted access causes an exception and can crash the program.

This arrangement lets system code be present in a process’s address-space layout without making it freely available to the application.

System calls

Applications still need the operating system to perform privileged tasks, such as creating a process. They request these services through system calls.

A user-mode program prepares the arguments for the requested operation and specifies a system-call number, also called a service number. That number identifies an operation in the System Service Dispatch Table (SSDT). The program then executes the syscall instruction.

The processor switches to kernel mode and transfers control to a system-call handler. The handler uses the requested service number to locate and invoke the appropriate kernel function. In this way, applications can request privileged operations without being allowed to perform them directly.

The processor’s role in executing code

Caches, execution units, and memory management

A CPU contains several cooperating components. Caches store frequently used instructions and data so the processor can access them faster than it could access main memory. A common arrangement includes an L3 cache shared among the cores, plus L2 and L1 caches associated with individual cores. In general, lower-numbered caches are smaller but faster.

A control unit fetches instructions and directs them to the appropriate execution unit. An arithmetic logic unit (ALU) handles arithmetic and logical operations. Real processors contain additional execution units, but the ALU is enough to illustrate the basic idea.

The memory management unit (MMU) handles memory operations, including virtual-memory translation. Each CPU core can execute instructions. A processor with multiple cores can therefore execute work on more than one core at the same time.

Registers and the instruction pointer

Registers are small, fast storage locations inside the processor. They hold values needed in the current execution context. On a 646464-bit computer, register widths can range from 646464 bits to 512512512 bits.

The instruction pointer, called RIP in the x86-64 architecture, indicates the instruction being executed or the next instruction in the execution sequence. Each core has its own instruction pointer, so different cores can execute different instructions at the same time.

Registers such as RAX and RCX are general-purpose registers: they do not have only one mandatory use. However, conventions guide how software uses them. For example, RAX is often used to hold a function’s return value. A program can also refer to only part of a register. EAX, for example, refers to the lower 323232 bits of RAX.

The RFLAGS register stores condition and configuration bits. One example is the zero flag: after a suitable test, the flag is set if the tested value is zero. In user mode, only the portion called EFLAGS is accessible as described here; other bits are reserved or restricted.

Segment registers originated in an older memory-management approach called segmentation. With virtual memory, that approach is no longer used in the same way. Operating systems still use segment registers for system-related purposes, such as holding pointers to important structures.

Another important register is CR3, which identifies the first-level page table used to translate the current process’s virtual addresses.

Threads and their execution state

A process can contain one or more threads. A thread is an execution context: it has a state that allows the operating system to pause it and later resume it. That state includes the relevant register values and other information associated with its execution.

On a multicore processor, different threads can run on different cores simultaneously. Windows decides when and for how long each thread runs; that scheduling process is explained later.

Thread stacks and function calls

Each thread has a stack, a fixed-size region of readable and writable memory used to manage function arguments, local variables, and related execution information. A stack is traditionally described as last-in, first-out: the last item added is the first removed. In practice, functions typically reserve their own portions of the stack, called stack frames.

Two registers help manage the stack:

  • RSP, the stack pointer, points to the current top of the stack.
  • RBP, the base pointer, identifies the base of the current stack frame.

A simplified function call works like this. Before the function begins, the program preserves the address to which execution must return. It may also preserve the previous base pointer. The function then establishes its own stack frame, reserves space for local data, and carries out its work. When it finishes, it restores the previous base pointer and returns to the saved address, which is placed back into the instruction pointer.

Function calls can follow different calling conventions, which specify details such as how arguments are passed and which registers must be preserved. The exact sequence varies, so the example is a general explanation rather than a rule for every function.

Stack space is limited, so it is not normally used for large data such as an image. Large or dynamically managed allocations are typically handled through the heap instead.

Think About It: Why does a thread need its own execution state and stack if it already belongs to a process?

Executable files and the Portable Executable format

Windows executable files commonly use the Portable Executable (PE) format. The format supports multiple processor architectures and organizes the information Windows needs to load an application.

Headers and sections

Near the beginning of many PE files is a DOS header, followed by a DOS stub. The DOS stub is a small 161616-bit program intended for older DOS systems. It often displays the message “This program cannot be run in DOS mode.” This feature remains for historical and compatibility reasons.

The DOS header contains information that helps the system locate the NT headers. These include two important headers:

  • The file header records information such as the target architecture.
  • The optional header records important loading information, including where the executable’s code begins. Despite its name, it is essential to understanding the executable.

After the headers comes the section table. A section is a region of the executable assigned to a particular kind of data. The section table describes each section, including its name, size, and attributes. The attributes indicate whether the section should be readable, writable, or executable.

Common sections include:

  • .text, which typically contains executable code.
  • .data, which contains data intended to be writable.
  • .rdata, which contains data intended to be read-only.

These protections help prevent unsafe behavior. For instance, code normally should not be writable. If a program tries to write into a page marked as non-writable, Windows can raise an access violation and terminate the program.

Think About It: Why might it be safer to keep a program’s code in a non-writable section?

Windows APIs, libraries, and system architecture

The Windows API and DLLs

When a user double-clicks an application, explorer.exe—the program responsible for the desktop, taskbar, and File Explorer—initiates its execution. It uses the Windows API, a set of functions that lets programs request operating-system services through a relatively convenient interface.

The Windows API is spread across libraries rather than stored in one enormous file. A program can include library code directly in its executable through static linking, or it can rely on dynamic linking. Dynamic linking allows multiple programs to use the same library files, called dynamically linked libraries or DLLs, instead of each storing a separate copy of all the library code.

Three important DLLs in the Windows API are kernel32.dll, kernelbase.dll, and ntdll.dll. kernel32.dll is retained largely for compatibility; many of its functions forward to corresponding functions in kernelbase.dll.

A function name ending in A or W often indicates which kind of string encoding the function accepts or returns. The W version uses wide strings, which are standard in modern Windows programming. The A version uses regular strings and may convert them to or from wide strings internally. The variants exist partly for compatibility, so programmers need to check the behavior of the particular function they use.

User-mode subsystems and kernel-mode components

Windows has a user-mode side and a kernel-mode side. User applications and many supporting processes run in user mode. Subsystem DLLs expose portions of the Windows API. For example, user32 provides functions related to graphical interfaces and user input.

Many subsystem functions ultimately rely on ntdll.dll, which contains several kinds of routines:

  • NT routines act as wrappers for system calls.
  • Zw routines implement related system calls for use by kernel code in certain situations.
  • Rtl routines provide runtime helper functions, some of which may make system calls.

Applications commonly use higher-level DLL functions rather than calling ntdll routines directly because the higher-level functions can provide useful work such as argument validation, parsing, and error handling.

Windows also includes service processes, which generally do not run within the context of a logged-in user. Windows Defender is one example. System processes have specific operating-system roles; a logon manager, which handles logins and logouts, is one example.

On the kernel-mode side, the executive contains higher-level operating-system components, including the memory manager and object manager. The kernel provides lower-level functions such as scheduling. Device drivers support particular hardware. At the lowest level is the Hardware Abstraction Layer (HAL), whose implementation depends on the hardware architecture.

How a system call is dispatched

When explorer.exe starts an application, it calls CreateProcess through kernelbase.dll. That function relies on CreateProcessInternalW, which gathers and formats the information required for process creation. It then calls NtCreateUserProcess through ntdll.dll.

The system-call handler and the kernel functions that carry out system services reside in ntoskrnl.exe, which contains much of the Windows kernel and executive. The handler is known as KiSystemCall64; the “shadow” naming used for some related routines distinguishes a version that includes protections against the Meltdown hardware vulnerability.

At a high level, the system-call handler performs these tasks:

  1. It executes swapgs, which exchanges the current value of the GS segment register with the value stored in the IA32_KERNEL_GS_BASE model-specific register.
  2. This makes available a pointer to the current processor’s Processor Control Region (KPCR). Each processor core has its own KPCR, which holds core-specific information and includes a Processor Control Block (KPRCB).
  3. The handler saves the user-mode stack pointer and switches to a kernel stack. It also saves the base pointer as needed.
  4. The handler reaches the system-service dispatch logic. A service descriptor provides information about the SSDT, which contains offsets to system-call functions. The service number selects the requested function.
  5. The requested service runs. Depending on the relevant flags, logging routines may also run.
  6. Afterward, Windows updates the system-call count in the processor’s control block, restores saved state, swaps the segment-register values back, and returns to user mode with sysret.

This transition illustrates why a system call is more than a simple function call: it changes the processor’s privilege level and stack so the operating system can safely carry out an operation on the application’s behalf.

Think About It: Why does the system-call handler switch to a kernel stack instead of continuing to use the application’s user-mode stack?

Windows objects and access control

Objects, handles, and lifetime

Windows represents resources it needs to manage—such as processes, files, and threads—as Windows objects. Objects of different types have different kinds of information, but each begins with an object header. The header can contain information such as a reference count and a handle count.

The object manager, an executive component, manages object lifetimes. When the relevant counts reach zero, the object manager can remove the object, unless the object has been marked permanent.

User-mode programs generally do not access kernel objects directly. Instead, a process obtains a handle, which acts like a key that grants specified forms of access to an object. The handles a process has open are recorded in a table associated with that process. When a handle is no longer needed, the process should close it with CloseHandle; this helps the object manager determine when resources can be released.

Kernel-mode code can access objects directly and does not need handles in the same way. To show that it needs an object, it can increase the object’s reference count with ObReferenceObject and later decrease it with ObDereferenceObject.

Security descriptors, ACLs, and SIDs

Windows objects have security descriptors that record security information, such as who owns the object. A security descriptor points to two important lists:

  • A System Access Control List (SACL) specifies which operations, and by whom, should generate audit records.
  • A Discretionary Access Control List (DACL) specifies which users have which permissions on the object.

Each list contains zero or more Access Control Entries (ACEs). An ACE can allow or deny access. Its mask specifies the permissions affected. Some bits represent permissions specific to the object; others represent standard rights such as deleting an object, changing its owner, or modifying its access information. Generic rights include read, write, execute, and all-access categories.

An ACE also identifies the affected entity using a Security Identifier (SID). A SID identifies an entity the system can authenticate. A SID is often displayed in a readable string form, but it is stored as structured data rather than as a literal text string. In the displayed form, S marks the value as a SID, and hyphens separate its parts for readability.

A SID includes:

  • A revision number, identifying the SID format version. The material describes version 111 as the version in use.
  • An authority, a 484848-bit value identifying the component that issued it. An authority of 555 indicates the Windows security subsystem.
  • Subauthorities, which provide further identifying information.

Some subauthority patterns include a domain identifier and a relative identifier (RID). On a standalone computer, the domain identifier represents a unique identifier associated with the device. In an Active Directory network, it identifies the domain responsible for the entity’s security information. The RID identifies a specific entity within that context.

Section objects and mapped memory

A section object represents memory that Windows can map into one or more processes. There are two broad kinds.

File-backed sections

A file-backed section represents a file mapped into memory. A program can open a file with CreateFile, obtain its size, create a section with CreateFileMapping, and map part of that section into its address space using MapViewOfFile. Internally, creating a file mapping calls NtCreateSection.

Once the file is mapped, the program can interact with its contents through memory. If it modifies the mapped data and wants the changes written back to the file, it can call FlushViewOfFile. It can then unmap the view and close the handles it opened.

Windows API functions do not all signal failure in the same way. For example, CreateFile can return INVALID_HANDLE_VALUE, defined as negative one, while CreateFileMapping returns nullptr on failure. This is why function behavior should be checked individually rather than assumed to be consistent.

Page-backed sections

A page-backed section is not tied to a particular file. It provides a way for processes to share memory. One process can create a section without giving it a file handle, name it, map a view, and write data into it. Another process can open the named section, map a view, and read the same data.

When a named object is created, Windows stores the name in additional object information placed before the ordinary object header. The name lets another process find the shared section.

These section types show how memory mapping connects files, virtual memory, and interprocess sharing: a file can be represented in memory, or a region of memory can be shared without representing any file.

Think About It: What advantage does a named, page-backed section offer when two separate processes need to exchange data?

How Windows creates a process

Process creation involves much more than loading a file. Windows creates kernel objects, memory-management structures, a process environment, and an initial thread before allowing the application’s code to run.

Opening the executable and creating the process object

After CreateProcessInternalW calls NtCreateUserProcess, the kernel begins by opening the executable file with IoCreateFileEx. It then creates a section object for mapping the executable into memory with MmCreateSpecialImageSection.

The system next calls PspAllocateProcess, which creates the Executive Process object, or EPROCESS. The EPROCESS represents the process and points to information such as its process ID and handle table. At its beginning is the KPROCESS, which holds data used specifically by the lower-level kernel.

The object manager creates the object, and Windows fills in its fields. The process receives an access token, which holds permissions associated with the security context in which it runs. When a user logs in, the Local Security Authority Subsystem Service process (LSASS) assigns a token to the session. Processes subsequently started in that session receive a copy of it.

Address space, working sets, and VADs

Windows creates the new process’s address space through MmCreateProcessAddressSpace. It initializes the process’s working set, the set of memory pages currently loaded into physical memory for that process. Windows guarantees a minimum working-set size and also tracks a maximum. The kernel has its own system working set, and each session has a session working set as well.

A session is associated with a login to the desktop or a remote connection. A session exists even at the lock screen. Within a session are window stations, which hold desktops and clipboard state; desktops contain windows, menus, and hooks. Session zero exists for system processes. Sessions help isolate the different user-interface environments.

Windows also creates Virtual Address Descriptors (VADs). VADs are organized as trees whose nodes describe allocated regions of a process’s virtual address space.

An application can request memory through the Windows API function VirtualAlloc. It can specify a size, optional address, allocation type, and protection settings. Two important allocation flags are MEM_RESERVE and MEM_COMMIT:

  • MEM_RESERVE reserves an address range without committing the memory charge to the system. Writing to the reserved range without committing it causes a memory-access violation.
  • MEM_COMMIT commits the region so the process can use it.

Both flags can be applied together. In either case, Windows records the region in a VAD. Page-table entries are not necessarily created immediately. When the application first accesses an address without a corresponding page-table entry, a page fault occurs. Windows checks the relevant VAD. If the region is allocated and committed, the system can establish the needed page-table entry. If one already exists, that VAD lookup is unnecessary.

Once the address space is prepared, the executable’s section is mapped into it.

The PEB, the initial thread, and scheduling setup

Windows also creates a Process Environment Block (PEB) in the process’s address space. Like EPROCESS, it describes the process, but it is intended for user-mode routines. It contains information such as the list of loaded DLLs, the executable’s base address, and whether the program is being debugged. Windows maps ntdll.dll into the process as well.

The kernel then creates the initial thread. PspAllocateThread creates an Executive Thread object, or ETHREAD, sets up the user-mode stack, and allocates a Thread Environment Block (TEB). Each thread has its own TEB, which stores information the user-mode code needs about that thread.

KeInitThread sets up the KTHREAD, the kernel-specific part of the thread object. It also creates a kernel stack and initializes the thread’s context. The thread context is the saved state needed to resume execution.

After this setup, Windows inserts the process and thread into the appropriate system structures and creates handles for them. Scheduling-related functions add the thread to the process’s thread list, update the thread count, and prepare the thread to run. The new thread is placed in a deferred ready state: it is ready to run on a particular core but is not yet executing.

Registering the process with CSRSS

Before the application starts, CreateProcessInternalW sends information to the Client/Server Runtime Subsystem (CSRSS). This system process keeps track of processes and threads associated with its session. The message includes information such as process and thread handles, the PEB address, and the section-object handle.

The communication uses Advanced Local Procedure Call (ALPC), an interprocess communication mechanism. Once the required setup is complete, CreateProcessInternalW resumes the initial thread. Until then, that thread has been held in a suspended state.

Think About It: Why might Windows need to create both a kernel-side process structure such as EPROCESS and a user-mode structure such as the PEB?

Starting the thread and loading libraries

Entering user mode

The initial thread begins in a kernel routine called KxStartUserThread. The Kx prefix indicates an architecture-specific implementation. The processor needs a record of its state at the transition from kernel mode to user mode; this record is called a trap frame.

A trap frame is often constructed during a transition caused by a system call. The new thread has not yet made such a transition, so the starting routine builds the trap frame itself. It sets the state so execution will begin at LdrInitializeThunk in ntdll.dll, the routine that begins loading and initializing the executable’s dependencies.

The loader database and imported functions

One of the loader’s tasks is to create and initialize a loader database referenced by the PEB’s Ldr field. The database records DLLs loaded into the process’s address space.

The loader needs to know which libraries and functions the executable depends on. It finds this information in the PE file’s import directory. The directory information is in the optional header’s data directories; its address is an offset that must be added to the executable’s base address to locate the relevant data in memory. The import data can be stored in a dedicated .idata section or in part of an .rdata section.

The import directory contains a sequence of IMAGE_IMPORT_DESCRIPTOR structures. Each descriptor identifies a library and the functions the executable imports from it. Important fields include:

  • Name, which identifies the DLL to load.
  • OriginalFirstThunk, which points to the Import Name Table (INT).
  • FirstThunk, which points to the Import Address Table (IAT).

The INT and IAT contain sequences of IMAGE_THUNK_DATA structures describing imported functions. An import can identify a function by name or by ordinal, a number assigned to a specific function.

Before imports are resolved, the two tables can contain equivalent information. The loader uses the INT to identify each needed function, looks up the function in the DLL’s export information, and places the function’s address into the corresponding IAT entry. The program then uses the IAT to find the address to call. The DLL’s export information is another table that maps function names or ordinals to their addresses.

The loader also resolves dependencies of the DLLs it loads, since those libraries may themselves import functions from other libraries. As it loads modules, it updates the loader database. Import resolution is only part of the loader’s work: it also handles tasks such as initializing the heap, processing shims, and relocating images.

When initialization is complete, the loader calls the application’s entry point, and the program begins its own execution.

Comprehensive review

Windows turns a file into a running application through a chain of coordinated steps:

  1. Virtual memory gives the process its own address space. Page tables translate virtual addresses into physical pages, while permissions and copy-on-write help protect memory.
  2. CPU privilege levels separate ordinary application code from privileged operating-system code. System calls provide a controlled route for applications to request privileged services.
  3. Threads and registers preserve the state needed for execution. Each thread has its own stack and execution context, while the scheduler decides when it runs.
  4. The PE format describes an executable’s architecture, sections, permissions, and library dependencies.
  5. Windows APIs and DLLs let applications request operating-system services through layers of user-mode functions that ultimately reach system calls.
  6. Windows objects and handles let the system manage resources and limit how processes access them. Security descriptors, ACLs, ACEs, and SIDs specify ownership, permissions, and auditing.
  7. Process creation builds kernel structures, an address space, working-set and VAD information, a PEB, and an initial thread with its stack and TEB.
  8. The loader maps required DLLs, resolves imported functions through the INT and IAT, updates the loader database, and calls the executable’s entry point.

The result is not merely a program copied into memory. It is a protected, structured execution environment in which Windows has prepared the program’s memory, permissions, dependencies, process state, and first thread before its application code runs.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent