Microsoft’s Early Beginnings


Microsoft’s Early Beginnings

Maria
Today we’re following a Windows program from the moment you double-click it to the moment its code begins running. It’s a big journey: executable-file structure, virtual memory, CPU privilege levels, Windows objects, process and thread creation, and finally the loader’s work. Before we get there, the story starts with a much smaller computer-industry opportunity.

Michael
It’s 1975. Paul Allen sees the Altair 8800 on the cover of Popular Electronics and realizes that a computer at a price ordinary buyers could afford could create a market for software. He takes the magazine to his friend Bill Gates. They had wanted to start a software company, but consumer-grade computers had not really been available before.

Maria
They decide to pursue a deal to build a BASIC interpreter for the Altair. Gates tells MITS CEO Ed Roberts that they already have one, although they don’t yet. Roberts has heard similar claims, so he challenges them to bring a working demonstration to Albuquerque. Two months later, Allen arrives with completed software and successfully demonstrates it. The next month, Allen and Gates found Microsoft.

Michael
Microsoft later grows through additional contracts. In 1980, it has eight million dollars in revenue. IBM is building its personal computer and, under a tight deadline, asks Microsoft to provide an operating system. Microsoft buys an existing system called 86-DOS, modifies it, and licenses it to IBM as MS-DOS. In 1985, Microsoft releases Windows, a graphical interface running on top of DOS; Windows later evolves through releases such as Windows 95 and Windows XP into modern Windows.

Maria
That’s the historical backdrop. Now let’s establish the technical vocabulary we need to understand what happens when Windows launches an application. A process is a program that has been loaded for execution, together with the resources the system associates with it. A major resource is its address space: the set of virtual addresses that the process can use.

Michael
Why not just let every program access physical memory directly? Because it would be difficult to manage and unsafe: one program could read or overwrite another program’s data. Virtual memory gives each process its own address space, so addresses used by one process don’t simply let it reach another process’s memory.

Maria
On the x86-64 system described here, virtual addresses are translated through page tables. The usual arrangement has four levels of tables, with 512 entries in each table. Each table entry is 64 bits, so a table is 512 times 8 bytes: 4,096 bytes, exactly one typical memory page.

Michael
A virtual address uses nine bits to select an entry at each of the four table levels, followed by 12 bits to select a byte within the page. Those final 12 bits can represent 4,096 offsets, which is why they fit a 4-kilobyte page. The last-level entries identify physical pages; the earlier levels point to lower-level tables.

Maria
A page-table entry can carry more than an address. Its remaining bits can describe permissions, including whether a page is writable or executable. Typical pages are 4 kilobytes, though the system can also use larger pages of 2 megabytes or 1 gigabyte. That detail matters because memory access and permissions are managed in page-sized pieces.

Michael
Separate address spaces don’t mean that every physical page has to be unique. Two processes can have page tables that point to the same physical page—for example, to share a dynamic library and save memory. A shared page can be marked copy-on-write. If one process tries to modify it, the system gives that process a fresh physical copy, so its change doesn’t alter the page other programs are using.

Maria
Windows also maps much of its system code into the upper part of each application’s virtual address space. But mapping it there doesn’t mean an ordinary application can use it freely. The relevant pages are marked for kernel access, so trying to access them while running in user mode causes an exception.

Michael
That brings us to CPU privilege levels. A useful traditional picture is protection rings: lower-numbered rings have more privileges. Modern systems mainly use ring 0 for kernel mode and ring 3 for user mode, while rings 1 and 2 are not used in the arrangement described here. Privilege levels protect sensitive instructions and data, and help keep user-mode activity separate from kernel-mode resources.

Maria
An application still needs operating-system services, such as asking Windows to create a process. It makes that request through a system call. User-mode code prepares arguments and a service number identifying the requested operation, then executes the syscall instruction. A system call handler uses the number to find the appropriate operation through the system service dispatch table, or SSDT.

Michael
The CPU switches to kernel mode and transfers control to the system call handler. The handler can then run the requested privileged operation. That controlled transition is why a normal program can ask Windows to do something privileged without itself being allowed to perform the operation directly.

Maria
Let’s zoom out to the CPU. A simplified processor has cores, caches, a control unit, execution units, a memory management unit, and registers. The L3 cache is shared among cores; each core also has L2 and L1 caches. Lower-numbered caches are smaller but faster, and caches hold frequently used data and instructions.

Michael
The control unit fetches instructions and directs them to execution units. One example is the ALU, the arithmetic logic unit, which handles arithmetic and logical operations. A real processor has more kinds of execution units than this simplified picture. The memory management unit, or MMU, handles memory-related work, including virtual-memory translation.

Maria
Registers are tiny, fast storage locations used for the CPU’s current work. In x86-64, the instruction pointer RIP indicates the instruction being executed. A multi-core processor can run instructions on different cores at the same time. General-purpose registers such as RAX and RCX don’t have a single mandatory role, although conventions—such as often using RAX for a function’s return value—are common.

Michael
You can also refer to a smaller part of a register: EAX, for instance, refers to the lower 32 bits of RAX. RFLAGS is a bitfield holding conditions and configuration. One example is the zero flag: after a test, it can indicate that the tested value was zero. In user mode, only the EFLAGS portion is accessible, according to the source.

Maria
Segment registers have a history tied to segmentation, which became obsolete with virtual memory in the arrangement we’re discussing. Operating systems still use them for useful system pointers and structures. There are other system-oriented registers too; CR3, for example, stores the current program’s top-level page-table address.

Michael
A process can contain multiple threads. A thread is an execution context: it has a state represented by register values and the instructions it is running. Threads can run simultaneously on different cores. Each thread also has a fixed-size, readable and writable stack, used for function arguments and local variables.

Maria
A stack is often introduced as last-in, first-out, but the important practical idea here is that functions usually reserve their own portions of it, called stack frames. RSP is the stack pointer, which points to the top of the stack, and RBP is the base pointer for the current frame. Calling conventions determine how functions arrange arguments and other details; there are different conventions, so not every function call works identically.

Michael
In the simplified example, a call to a function named foo first saves the return address—the location to continue from afterward—and the previous base pointer. It then establishes a new base pointer, reserves four bytes for an integer, and initializes that space before putting the value five there. Initializing a stack value matters because old data from an earlier frame could otherwise remain in that location.

Maria
When foo finishes, the old base pointer is restored. The stack pointer then reaches the saved return address, and the return instruction puts that address back into the instruction pointer. Execution resumes after the call. Large items, such as an image, generally don’t belong on this fixed-size thread stack; the heap is used for that kind of allocation, though we’re not exploring the heap further here.

Michael
Now let’s look at the file Windows is going to launch. A Windows executable uses the Portable Executable format, or PE. Near its beginning is a DOS header, followed by a DOS stub: a small 16-bit program that typically prints, “This program cannot be run in DOS mode,” if someone tries to run it on an old DOS system. It’s a reminder of Microsoft’s emphasis on backwards compatibility.

Maria
The DOS header tells the system where to find the NT headers. Those include the file header, which records information such as the target architecture, and the optional header—which is important despite its name and includes information such as where the code begins. After the headers comes a section table describing the executable’s sections, including their names, sizes, and access attributes.

Michael
Sections hold different kinds of information: code, imported-function information, or resources such as images. Their attributes specify whether data is readable, writable, or executable. Those distinctions help enforce security. For example, code normally shouldn’t need to be writable; if a program tries to write to a non-writable code section, Windows raises an access violation and the program crashes.

Maria
Common PE sections include .text for executable code, .data for writable data, and .rdata for read-only data. The section table gives Windows the information it needs to set up the executable’s memory with appropriate protections.

Michael
So you double-click Notepad. The desktop and file-management program responsible for that action is explorer.exe. It uses the Windows API—a large collection of programming utilities—to request that the program start. The API is spread across libraries rather than stored in one giant file.

Maria
Libraries can be statically linked, meaning their contents are put into the executable, or dynamically linked. With dynamic linking, DLLs are available on disk and Windows maps the needed libraries into processes. That avoids putting a separate copy of the same library into every executable that uses it.

Michael
Three important Windows API-related DLLs are kernel32.dll, kernelbase.dll, and ntdll.dll. Kernel32 is a legacy layer retained for compatibility; its functions generally forward to kernelbase, the modern replacement. Many subsystem functions ultimately reach routines in ntdll.dll.

Maria
The Windows architecture also helps explain those layers. User processes run in user mode and depend on subsystem DLLs, which expose parts of the Windows API. For example, user32 provides functions for graphical interfaces and user input. Ntdll contains several kinds of routines: NT functions that wrap system calls, Zw functions that implement the same system calls for certain kernel-mode uses, and Rtl runtime-library helpers, which may or may not make system calls.

Michael
Those higher-level wrappers are useful because they can add argument parsing, validation, or error handling. Windows also has service processes, which generally don’t run in the context of a logged-in user, and system processes with specific system purposes, such as managing logins and logouts.

Maria
On the kernel-mode side, the executive contains higher-level components such as the memory manager and object manager. The kernel contains lower-level features including the scheduler, which decides when and for how long threads run. Device drivers support hardware such as graphics cards, and the hardware abstraction layer, or HAL, provides the hardware-specific implementation that varies across architectures.

Michael
Back to launching Notepad: explorer.exe calls CreateProcess, a Windows API function in kernelbase.dll. CreateProcess itself mostly hands the work to CreateProcessInternalW. That function gathers and formats arguments, then calls NtCreateUserProcess in ntdll. This is the system-call wrapper that transfers the request to the operating system.

Maria
The kernel-side system call handler is in ntoskrnl.exe, which contains much of the Windows executive and kernel. The dispatcher is called KiSystemCall64. It first executes swapgs, exchanging the GS segment-register value with the value in the IA32_KERNEL_GS_BASE model-specific register. That register points to the per-processor KPCR, or Processor Control Region.

Michael
Each processor core has its own KPCR, which contains core-specific information and a KPRCB, or Processor Control Block. The handler saves the old stack pointer and switches to the current processor’s kernel stack, then saves and adjusts the base pointer. A separate kernel stack helps keep kernel-mode execution apart from user-mode execution.

Maria
The handler proceeds to KiSystemServiceStart, which uses service-table information to find the requested operation. The SSDT holds offsets to system-call functions, and the service number supplied from user mode selects the function. Depending on flags, logging routines may also run. When the operation is complete, the system updates a system-call count in the processor control block, restores saved registers and the GS state, and returns with sysret.

Michael
The detailed kernel implementation is complicated and largely undocumented, so the explanation we’re giving is a simplified view. The key idea is that the system call number routes a request from user mode to the appropriate kernel operation. Here, that operation is NtCreateUserProcess.

Maria
NtCreateUserProcess starts by opening the executable file with IoCreateFileEx. It then creates a section object for mapping the executable into memory, using MmCreateSpecialImageSection. To understand that, we need to understand Windows objects: they represent resources the system tracks, such as processes, files, threads, and sections.

Michael
Different object types contain information specific to their resource, but they share an object header. The object manager manages their lifetimes. The header includes counts such as reference count and handle count; when those counts reach zero, the object manager can remove the object unless it is marked permanent.

Maria
User-mode programs don’t directly access Windows objects. They open handles, which act like keys for interacting with an object through the Windows API, and those handles carry permissions. A process’s open handles are kept in a table associated with that process. When a handle is no longer needed, code should close it with CloseHandle so Windows can track when the object is no longer in use.

Michael
Kernel-mode code can access objects directly, so it can instead manage references with ObReferenceObject and ObDereferenceObject. Another important piece is an object’s security descriptor, which includes ownership information and points to two access-control lists. The SACL specifies which actions and users should generate audit logs; the DACL specifies who has which permissions.

Maria
An ACL contains zero or more access-control entries, or ACEs. An ACE can grant or deny access to a user, with a mask specifying which permissions apply. The mask includes object-specific rights, standard rights such as deleting or changing ownership, and generic rights such as read, write, execute, or all.

Michael
Each ACE also identifies the affected user or entity with a security identifier, or SID. A SID is a unique identifier the system uses for an entity it can authenticate. Its familiar string form begins with S and uses hyphens to make the pieces readable, but the SID isn’t stored as that string.

Maria
In the string representation, the revision number identifies the SID version; the source says that version is 1. The authority identifies the component that issued it—for example, authority 5 means the Windows security subsystem. Subauthorities supply the remaining identifying information. In one common pattern, a domain identifier is followed by a relative identifier, or RID, that identifies the particular entity.

Michael
Now back to section objects. A file-backed section represents a file mapped into memory. In the example, CreateFile opens an existing file with read and write access, GetFileSize obtains its size, and CreateFileMapping creates a section. Despite the API name, CreateFileMapping calls NtCreateSection under the hood and returns a handle.

Maria
After checking that the handles are valid, MapViewOfFile maps the file’s pages into the process’s address space. The program can then read or modify the file through memory. In the example, it reads and prints “hello world,” changes the contents to “goodbye world,” and calls FlushViewOfFile to write the modified pages back. It then unmaps the view and closes the handles.

Michael
There’s a small but useful API lesson in that example: CreateFile signals failure with INVALID_HANDLE_VALUE, which is negative one, while CreateFileMapping is checked against nullptr, which is zero. Windows API functions can have inconsistencies like that, so you need to check each function’s documentation rather than assume every failure value is the same.

Maria
Another API detail is the A and W suffixes on string-taking functions. W variants use wide strings, the standard on Windows today. A variants accept regular strings and generally convert them to wide strings before doing their work, converting outputs back when needed. The A forms remain for simplicity and backwards compatibility.

Michael
A page-backed section, by contrast, doesn’t represent a file. It can be used to share memory between processes. One process creates and names a section, maps a view, and writes “hello world.” Another process opens the named section, maps its own view, and reads the same contents.

Maria
Although an object header doesn’t contain its name, a named object has an additional name-information header placed before the object header. That gives the system a way to locate the section by name. The example’s result—a second program printing the first program’s message—shows how the mapped memory can be shared.

Michael
With the executable section ready, NtCreateUserProcess calls PspAllocateProcess to create the executive process object, or EPROCESS. This important kernel object represents the process and points to information such as its process ID and handle table. At the top of it is a KPROCESS structure, separating kernel-specific data from information used by the executive.

Maria
PspAllocateProcess creates the object through ObCreateObjectEx, initializes it, and assigns an access token. An access token carries permissions. When you log in, LSASS assigns a token to your session, and processes you launch receive a copy of it.

Michael
The process also needs an address space. MmCreateProcessAddressSpace initializes its working-set list. A working set is the set of memory pages a process currently has loaded in physical memory. Windows guarantees each process a minimum working-set size and has a maximum as well; the kernel and each session also have working sets.

Maria
A session is associated with a logon, including a remote connection, and one 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. The purpose of sessions is to isolate different user interfaces.

Michael
MmCreateProcessAddressSpace also allocates virtual address descriptors, or VADs. They form trees whose nodes describe allocated regions of virtual memory. An application can request memory with VirtualAlloc, specifying details such as the size, address, and protections.

Maria
Two important VirtualAlloc flags are MEM_RESERVE and MEM_COMMIT. Reserving a region sets it aside without charging the memory to the system; trying to write to it without committing can cause an access violation. Committing charges the region, and you can reserve and commit together. A VAD node records the region, but page-table entries aren’t necessarily created immediately.

Michael
When the process accesses a region without a page-table entry, a page fault occurs. The system checks the appropriate VAD. If there’s a matching committed region, it can create the needed page-table entry. If the entry already exists, there’s no need to look up the VAD for that access.

Maria
After setting up the address space and VADs, Windows maps the executable section into it. The process object also gets a Process Environment Block, or PEB, in user-mode memory. The PEB provides information user-mode code needs, such as the loaded-DLL list, the executable’s base address, and a flag indicating whether the program is being debugged.

Michael
The address-space setup also maps ntdll.dll into the process. Next, Windows creates the initial thread. PspAllocateThread creates an ETHREAD executive thread object, sets up the user stack, and allocates a Thread Environment Block, or TEB. Each thread has its own TEB for user-mode thread information.

Maria
KeInitThread sets up the KTHREAD structure within the ETHREAD, creates a kernel stack, and initializes the thread context. The context records the state needed to resume the thread, and in this description it is stored on the kernel stack. Scheduling details determine when that thread will actually run.

Michael
PspInsertProcess creates and returns a handle to the process. PspInsertThread performs more scheduling setup and calls KeStartThread, which updates the process’s thread count and adds the thread to its list. A handle to the new thread is created, and KeReadyThread puts it in a deferred-ready state: it is ready to run on a particular core but is not running yet.

Maria
The system call returns to CreateProcessInternalW. That user-mode function then asks the Client Server Runtime Subsystem, or CSRSS, to register the new process. It sends information such as the process and thread handles, the PEB address, and the section-object handle through an Advanced Local Procedure Call, or ALPC.

Michael
CSRSS is a system process that keeps track of processes and threads in its session, with handles open to them. ALPC is the inter-process communication mechanism used for this message; the source notes that its implementation is undocumented and doesn’t go into the protocol’s details.

Maria
CreateProcessInternalW’s final step is to resume the thread, which has been suspended until then. The thread begins in the kernel function KxStartUserThread. The Kx prefix indicates an architecture-specific implementation; Microsoft documentation also refers to this startup routine as KiStartUserThread.

Michael
Because this thread hasn’t previously made a transition from user mode to kernel mode, the startup routine builds a trap frame on the kernel stack. A trap frame describes the CPU state at the moment of a transition. It sets that frame up so execution will begin in LdrInitializeThunk in ntdll—the image loader.

Maria
One of the loader’s major jobs is to initialize the loader database, pointed to by the Ldr field in the PEB. It records the DLLs loaded into the process. To determine which libraries the executable needs, the loader parses the Import Directory Table, or IDT, in the PE file.

Michael
The IDT’s location is found through the PE optional header’s data directories. Its value is an offset, so you add it to the executable’s base address in memory. The table may be in a section called .idata or in part of an .rdata section. It contains IMAGE_IMPORT_DESCRIPTOR records, and the data-directory information gives the descriptor count.

Maria
Each import descriptor identifies a library by name and provides offsets to two tables: the Import Name Table, or INT, through OriginalFirstThunk, and the Import Address Table, or IAT, through FirstThunk. Their entries describe functions the program imports from that library—functions its code will call.

Michael
The INT provides the function names or ordinals, where an ordinal is a number identifying a function. Initially the INT and IAT are equal. The loader finds each imported function in the library’s export information and writes its address into the corresponding IAT entry. Then the program can use the resolved address to call that function.

Maria
The same issue applies to the DLLs themselves: a loaded library may import functions from other libraries, so those imports need resolving too. The source’s illustrative code isn’t exactly how Windows’s loader works; for instance, it uses the loader to load libraries and skips steps the real loader handles.

Michael
And import resolution is only part of the loader’s job. It also initializes the heap, handles shims, relocates images, and does more. Once it has completed its work, it calls the application’s entry point. That’s the transition from a carefully constructed process to the application’s own startup code.

Maria
So the double-click that looked like one simple action involved a chain: Explorer called the Windows API, the API reached a system call, the kernel created process and thread objects, memory was mapped and protected, CSRSS registered the process, and the loader resolved DLL imports before calling the entry point.

Michael
The big picture is that Windows combines isolation with controlled sharing. Virtual address spaces separate processes, permissions restrict access, handles mediate user-mode access to objects, and system calls provide a safe route to privileged operations. At the same time, sections and shared libraries let processes share memory where that’s useful.

Maria
And every layer contributes something different: the PE file describes what should be loaded, the memory manager builds the address space, the scheduler manages when threads run, the object manager tracks system resources, and the loader connects the executable to its libraries. Once you see those pieces working together, launching an application feels less like magic and more like a sequence of understandable steps.

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