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 Starts and Runs a Program

From Microsoft’s beginnings to the personal computer

In 1975, Paul Allen noticed a magazine cover featuring the Altair 8800, a personal computer released by Micro Instrumentation and Telemetry Systems (MITS). Allen and his friend Bill Gates had long considered starting a software company, but affordable consumer computers had not previously been available. The Altair suggested a new opportunity: software could be developed for machines that individuals and smaller organizations could afford.

Allen and Gates sought a contract to develop a BASIC interpreter for the Altair. Gates told MITS that they already had a working interpreter, although they did not. MITS challenged them to demonstrate one in Albuquerque. Allen produced the completed software and gave the demonstration, securing the opportunity. Allen and Gates founded Microsoft the following month.

Microsoft grew through additional software contracts. In 1980, IBM asked Microsoft to provide an operating system for its forthcoming personal computer. Microsoft acquired an existing system called 86-DOS, modified it, and licensed it to IBM as MS-DOS. Microsoft later released Windows in 1985 as a graphical interface that ran on top of DOS. Windows subsequently developed into later versions such as Windows 95 and Windows XP, as well as modern releases.


Memory and process isolation

Units of data

Computers represent information as bits. Larger amounts of data are described using units such as:

  • A byte contains eight bits.

  • A word is a commonly used unit whose size depends on context. In the terminology used here, a word contains sixteen bits.

  • A double word is twice the size of a word.

  • A quadruple word is four times the size of a word.

The term word can vary between systems and technical contexts, so its size should not always be assumed to be universal.

Processes and address spaces

When a program is running in memory, it is called a process. A process is not just the program’s code: it is a running instance with its own resources and execution state.

A key way the operating system isolates processes is by giving each one its own virtual address space. Physical memory is ultimately accessed byte by byte, but allowing every program to directly manipulate physical memory would be difficult to manage and unsafe. A program could otherwise read or overwrite memory belonging to other programs or to the operating system.

Virtual memory provides each process with an address space that appears private. The operating system and processor translate virtual addresses into physical memory locations. Different processes can therefore use the same virtual address without necessarily referring to the same physical memory.

Pages and page tables

Virtual memory is organized into pages. The page tables associated with a process describe which physical memory pages correspond to particular regions of its virtual address space, and what operations are allowed on those pages.

A common x86-64 arrangement uses four levels of page tables. Each table contains 512 entries. Each entry is 64 bits wide, so a table occupies 4096 bytes—also the size of a standard memory page.

A virtual address is divided into portions used for page-table lookup and a portion used as an offset within the final page:

  • Nine bits index the first page-table level.

  • The next nine bits index the second level.

  • The next nine bits index the third level.

  • The next nine bits index the fourth level.

  • The final twelve bits specify the byte offset within a standard page.

The final twelve bits allow 2122^{12}212 possible offsets, corresponding to 4096 bytes. Thus, the standard page size is 4 kilobytes, and pages are aligned on boundaries matching that size.

The 512 entries in a table follow from each entry’s size: a 4096-byte page can hold 512 entries of 8 bytes each. Page-table entries do not use all of their bits solely to store a pointer. Other bits encode permissions and attributes, such as whether a page is writable or executable.

Standard 4-kilobyte pages are common, but systems can also use larger page sizes. The material describes 2-megabyte pages as huge pages and 1-gigabyte pages as giant pages.

Sharing pages and copy-on-write

Separate virtual address spaces do not mean that every process must have a separate physical copy of every page. Multiple processes can have page-table entries that refer to the same physical page. This is useful for shared code, including dynamically linked libraries, because it reduces physical memory use.

If a shared page must not be modified in place, the operating system can mark it for copy-on-write. When a process attempts to write to such a page:

  1. The system creates a new physical copy of the page.

  2. It updates the writing process’s page-table entry to point to the new copy.

  3. The process modifies its private copy, leaving other processes’ shared page unchanged.

This approach allows pages to be shared until a process actually needs to modify one.


CPU permissions and system calls

Protection rings and privilege

Processors support different privilege levels, often illustrated as protection rings. In the conventional ring model, lower-numbered rings have more privileges. Modern Windows systems mainly use:

  • Ring 3, called user mode, for ordinary applications.

  • Ring 0, called kernel mode, for the operating system’s privileged code.

Rings 1 and 2 are generally not used in the systems described here. Privilege levels restrict access to sensitive instructions and data. For example, pages containing kernel code can be mapped into the virtual address space of an application but marked as accessible only in kernel mode. An attempt to access such a page from user mode causes an exception, usually resulting in the offending program being terminated.

System calls

Applications still need to request privileged services—for example, creating a process—without being allowed to perform privileged operations directly. They do so through system calls.

A user-mode program prepares arguments describing the requested operation and specifies a service number identifying it. The program then invokes the processor’s syscall instruction. The system uses the service number to select the appropriate function from the System Service Dispatch Table (SSDT).

The syscall instruction transfers execution into kernel mode and directs the processor to a system-call handler. The handler dispatches the requested operation to the corresponding kernel function. In this way, the operating system mediates access to protected functionality.


CPU components and execution state

Caches and execution units

A CPU contains multiple functional components. A simplified view includes:

  • Caches, which store frequently used data and instructions to reduce access time. A typical processor has an L3 cache shared by its cores and L1 and L2 caches associated with each core. Lower-numbered cache levels are smaller but faster. A processor may have multiple L1 or L2 caches for different purposes.

  • A control unit, which fetches instructions and directs them to the appropriate execution resources.

  • Execution units, such as an arithmetic logic unit (ALU), which performs arithmetic and logical operations. Real processors have additional kinds of execution units.

  • A memory management unit (MMU), which handles memory-management tasks, including virtual-memory translation.

  • Registers, small storage locations used by the processor to hold values needed during current execution.

The discussion of processor-specific features is limited to the x86-64 architecture.

Registers

Registers provide the CPU with very fast access to data. In 64-bit systems, register widths vary: general-purpose registers are 64 bits, while some vector registers can be wider, reaching 512 bits.

Important register groups include:

  • RIP, the instruction pointer, tracks the instruction position for a core. Each core has its own execution state, allowing different cores to execute different instructions simultaneously.

  • General-purpose registers such as RAX and RCX hold values used by code. They do not have one mandatory purpose, although conventions often assign them common roles; for example, RAX is often used for a function’s return value.

  • Subregister names can refer to part of a larger register. For example, EAX refers to the lower 32 bits of RAX.

  • RFLAGS records processor conditions and configuration as a bitfield. Its zero flag indicates whether a tested result was zero. User-mode code can access only the EFLAGS portion; other parts are reserved or restricted.

  • Segment registers, which originated in segmentation mechanisms that became largely obsolete with virtual memory. Operating systems still use them for system-related information and pointers.

  • CR3, which identifies the current process’s top-level page table and is used in virtual-address translation.

Processes, threads, and scheduling

A process can contain multiple threads. A thread is an execution context: it has a state that includes the register values and other information needed to execute a particular sequence of instructions. The operating system’s scheduler decides when and for how long threads run. On a multicore processor, threads can execute simultaneously on different cores.


The thread stack and function calls

Each thread has a fixed-size, readable and writable region of memory called its stack. It is used to manage function arguments, local variables, return addresses, and other execution data.

A stack is commonly described as last-in, first-out: the most recently added item is ordinarily the first removed. Actual thread-stack use does not have to follow a single simple pattern, but functions typically reserve portions of the stack for their own use. Each such portion is a stack frame.

Two registers are especially associated with the stack:

  • RSP, the stack pointer, identifies the current top of the stack.

  • RBP, the base pointer, commonly identifies the base of the current stack frame.

A simplified function call proceeds as follows:

  1. The call stores the address of the instruction to return to.

  2. The function saves the previous frame’s base pointer.

  3. The function sets its base pointer for its own frame.

  4. It reserves space for local data, such as an integer variable.

  5. It uses the reserved space as needed.

Initializing local stack storage can be important because the memory may contain leftover data from an earlier use. When the function finishes, it restores the previous base pointer. A return instruction then retrieves the saved return address and resumes execution after the call.

Functions are not all called in exactly the same way. Calling conventions specify details such as how arguments are passed and how registers or stack space are used. Different conventions suit different contexts.

The stack is limited in size and is not appropriate for very large data, such as an image. Such allocations are generally made from the heap, which is a different region of memory.


Portable Executable files

PE structure

Windows executable files use the Portable Executable (PE) format. The format supports multiple architectures and includes information that Windows needs to load and run a program.

Near the beginning of a PE file are:

  • The DOS header, the first chunk of file information. It contains values that help locate later headers.

  • The DOS stub, a small legacy 16-bit program intended for execution under DOS. It commonly displays the message “This program cannot be run in DOS mode.” Its presence reflects a compatibility feature retained by Microsoft.

  • The NT headers, including the file header and optional header.

  • The section table, which describes the file’s sections.

The file header records information such as the executable’s target architecture. The optional header is important despite its name; it includes information such as where the program’s code is located and provides data-directory entries used to find structures such as the import directory.

Sections and memory protections

A PE section is a region of the executable dedicated to particular data. Sections can hold code, imported-function information, or resources such as images. Entries in the section table describe each section’s name, size, and attributes, including whether its contents should be readable, writable, or executable.

Common section names include:

  • .text: usually contains executable code.

  • .data: usually contains data that can be written.

  • .rdata: usually contains data intended to be read but not written.

When Windows loads an executable, it configures the process’s address space using these sections and their protections. If the program attempts to write to a read-only section—for example, its code section—the system raises an access-violation exception and the program will generally crash. Separating read, write, and execute permissions helps limit unintended or unsafe memory access.


Windows APIs and dynamic libraries

The Windows API

Windows provides programmers with the Windows API, a large collection of functions for interacting with the operating system. It is not one enormous library. Instead, its functions are organized across multiple libraries that programs can link to.

A program can link a library in two broad ways:

  • Static linking places the needed library contents directly into the executable.

  • Dynamic linking uses a separate dynamically linked library, or DLL, that can be loaded into memory and shared by multiple processes.

Dynamic linking can reduce duplicated code in physical memory because several processes can use the same library pages.

Important Windows DLLs

Several DLLs are particularly important to the Windows API:

  • kernel32.dll provides legacy API functions and is retained for compatibility. Many of its functions forward to newer implementations.

  • kernelbase.dll contains modern implementations for many functions associated with the Windows API.

  • ntdll.dll provides a lower-level interface between user-mode code and the operating system.

Other subsystem DLLs expose particular categories of functionality. For example, user32 provides functions related to graphical interfaces and user input.

A and W function variants

Many Windows API functions that accept strings have variants with an A or W suffix:

  • The W variants use wide strings, which are the standard form in modern Windows.

  • The A variants use regular, narrower strings and are retained for compatibility and convenience. They commonly convert input strings to wide strings and convert string outputs as needed.

Different functions may use different conventions for indicating failure. For example, one API may use an invalid-handle value, while another may use a null pointer. Programs therefore need to follow each function’s documented behavior rather than assume a uniform rule.


The organization of Windows

Windows can be viewed as having user-mode and kernel-mode parts. A process’s user-mode code requests operating-system services through APIs and system calls; privileged operating-system components carry out operations that require kernel access.

User-mode components

User mode contains ordinary application processes and other processes that run without full kernel privilege. Some important categories are:

  • User processes, which run applications and use subsystem DLLs.

  • Service processes, which generally operate independently of a logged-in user. Windows Defender is one example.

  • System processes, which perform specific operating-system tasks. A logon manager, which manages logins and logouts, is one example.

Subsystem DLLs often call into ntdll.dll. Its routines include:

  • NT or native functions, which commonly act as wrappers for system calls.

  • Zw functions, which provide related system-call functionality for kernel code in certain circumstances.

  • Rtl functions, which are runtime-library helpers and may or may not perform system calls.

Higher-level API wrappers often make programming simpler by adding argument processing, validation, or error handling before reaching the lower-level routines.

Kernel-mode components

The kernel-mode side includes several layers:

  • The executive provides higher-level operating-system components, including the memory manager and object manager.

  • The kernel includes lower-level mechanisms such as the scheduler.

  • Device drivers control and interact with hardware devices.

  • The hardware abstraction layer (HAL) provides a hardware-specific implementation that varies across architectures.

The kernel is also where the scheduler makes decisions about which thread runs and when.


How a system call reaches its kernel function

For x86-64 Windows, the system-call path uses processor-specific setup before dispatching to the requested system service.

The kernel system-call handler is commonly identified as KiSystemCall64. Its work includes:

  1. Executing the swapgs instruction. This exchanges the current GS segment-register value with the value stored in the IA32_KERNEL_GS_BASE model-specific register.

  2. Using that register to access the Processor Control Region (KPCR) associated with the current processor. Each core has its own KPCR, containing processor-specific information.

  3. Accessing the Processor Control Block (KPRCB), which is part of the processor-specific structures.

  4. Saving the user-mode stack pointer and switching to the kernel stack associated with the processor. This separate stack helps isolate kernel execution from user execution.

  5. Saving the relevant base-pointer state and preparing the kernel stack for handling the request.

  6. Continuing into KiSystemServiceStart, which uses service-table information to locate and invoke the requested system-call function.

  7. Restoring saved state, swapping GS back, and returning to user mode with the sysret instruction.

The service descriptor table holds information about system-service tables. The SSDT contains offsets to the actual system-call functions, and the service number supplied from user mode identifies the appropriate entry. Depending on system flags, logging routines may also run. The system can update a per-processor count of the system calls that have been executed.

A large amount of kernel implementation detail is not documented publicly. Understanding the path therefore relies in part on debugging information, community research, and reverse engineering. The precise internal implementation can be more complex than a simplified overview suggests.


Windows objects, handles, and security

Objects and object management

Windows represents many resources as objects, including processes, threads, and files. Objects of different types contain information specific to the resource they represent, but they share an object header.

The object manager manages object lifetimes. An object header can include information such as:

  • A reference count, which tracks kernel-mode references.

  • A handle count, which tracks open handles.

When the relevant counts reach zero, the object manager can remove the object, unless it is marked as permanent.

User-mode programs do not generally access kernel objects directly. Instead, they open handles. A handle is a process-specific reference that acts as a controlled means of interacting with an object through the Windows API. Handles carry access permissions and are stored in a table associated with the process. When a program finishes using a handle, it should close it with CloseHandle, so the object manager can track whether the object is still needed.

Kernel-mode code can access objects directly and does not need handles in the same way. It can indicate that an object is in use by calling ObReferenceObject to increase its reference count, then ObDereferenceObject to decrease it when finished.

Security descriptors, ACLs, and ACEs

A Windows object can have a security descriptor, which contains security information such as the object’s owner and references to two access control lists:

  • The System Access Control List (SACL) specifies which operations, performed by whom, should be recorded in audit logs.

  • The Discretionary Access Control List (DACL) specifies who is allowed or denied particular access to the object.

An ACL contains zero or more Access Control Entries (ACEs). An ACE identifies a security principal, specifies whether access is allowed or denied, and defines the relevant permissions.

An ACE includes:

  • A type, such as access allowed or access denied.

  • A mask, whose bits represent permissions. Some bits represent rights specific to the object; others represent standard rights such as deleting the object, changing its owner, or modifying its access descriptor. Generic rights include categories such as read, write, execute, or all access.

  • A Security Identifier (SID) identifying the user or other entity to which the entry applies.

Security Identifiers

A SID is a unique identifier for an entity that Windows can authenticate. SIDs are commonly displayed as strings with an initial S and hyphens separating their components, but they are stored in a structured binary form rather than as ordinary strings.

The displayed components include:

  • A revision number, indicating the SID format version. The material describes version 1 as the version in use.

  • An authority, stored across 48 bits, which identifies the component that issued the SID. An authority value of 5 indicates the Windows security subsystem.

  • Subauthorities, which further identify the entity. In some SID formats, a subauthority sequence includes a domain identifier followed by a relative identifier.

On a standalone computer, the domain identifier corresponds to a unique identifier associated with that device. In an Active Directory network, it identifies the domain that manages the entity’s security information. A Relative Identifier (RID) commonly appears at the end and distinguishes a particular entity within its domain or subauthority context.


Section objects and shared memory

A section object represents memory that can be mapped into a process. Sections are useful both for mapping files into memory and for sharing memory between processes.

File-backed sections

A file-backed section represents a file that can be mapped into a process’s address space. A typical sequence using the Windows API is:

  1. Open an existing file or create one with CreateFile.

  2. Check the returned handle using the failure convention specified for that function.

  3. Obtain information such as the file’s size.

  4. Create a file-backed section with CreateFileMapping.

  5. Map a view of the section into the process with MapViewOfFile.

  6. Read or modify the mapped memory.

  7. If the memory was modified and the changes should be written back, call FlushViewOfFile.

  8. Unmap the view and close the opened handles.

Despite its name, CreateFileMapping is a higher-level API; internally, it calls NtCreateSection to create the section object.

For example, a program could map a text file containing “hello world,” print its contents, replace them with “goodbye world,” and flush the changes back to the file.

Page-backed sections

A page-backed section is not associated with a particular file. It can provide shared memory for separate processes.

A typical example works as follows:

  1. One process creates a section without supplying a file handle and gives it a name.

  2. The process maps a view of the section and writes data into it.

  3. A second process opens the named section.

  4. The second process maps its own view and reads the shared data.

If the first process writes “hello world,” the second process can read that same content through its mapped view.

Windows objects can be named so that processes can locate them. When an object has a name, an additional object name information header is placed before the usual object header, even though the basic object header does not itself contain the object’s name.


Creating a process

Starting from a desktop action

When a user double-clicks an application such as Notepad, the desktop’s file-management process, explorer.exe, initiates the launch. Explorer is also responsible for elements such as the desktop, taskbar, and file-explorer windows.

To start the program, Explorer calls CreateProcess, a Windows API utility. The public function does relatively little itself. It calls CreateProcessInternalW, which gathers and formats the required arguments and eventually calls NtCreateUserProcess in ntdll.dll. That system call transfers control to the kernel.

The kernel implementation is associated with ntoskrnl.exe, which contains most of the Windows executive and kernel. The system-call dispatcher routes the NtCreateUserProcess request to its corresponding kernel function.

The exact process-creation path has many conditions and helper functions. The following description presents its main stages rather than every branch and implementation detail.

Opening the executable and creating the process object

The process-creation routine first opens the executable file, using a function such as IoCreateFileEx. It then creates a section object for the executable, using a function such as MmCreateSpecialImageSection. This section makes it possible to map the executable into memory.

The kernel then creates an executive process object, commonly called an EPROCESS. It represents the process and points to information such as its process identifier and handle table. At the beginning of the EPROCESS is a KPROCESS structure, which separates information used specifically by the kernel from other information maintained by the executive.

The EPROCESS is created through the object manager, using a function such as ObCreateObjectEx, and then initialized. It receives an access token, which represents the security identity and permissions associated with the process. When a user logs in, the Local Security Authority Subsystem Service (LSASS) assigns a token to the session. Processes subsequently launched in that context receive copies of the token.

Address space, working set, and virtual address descriptors

The system builds the process’s address space with a routine such as MmCreateProcessAddressSpace. It initializes a working set, the set of memory pages the process currently has resident in physical memory.

Windows manages working sets for several categories of memory:

  • Each process has a process working set.

  • The kernel has a system working set.

  • Each session has a session working set.

A working set has minimum and maximum limits. Windows guarantees a minimum number of pages for a process, while also controlling how large the working set can become.

A session is associated with a login to the desktop or a remote connection. A session exists even at the login screen, before a user has fully logged in. Sessions contain window stations, which hold desktops and clipboard state. Desktops contain windows, menus, and hooks. The system maintains session zero for system processes. Sessions help isolate the user interfaces associated with different logons.

The system also creates Virtual Address Descriptors (VADs). VADs form a tree whose nodes describe regions allocated in a process’s virtual address space.

Applications can request memory through VirtualAlloc. Such a request can specify an address, a size, a memory type, and protections. Two important allocation flags are:

  • MEM_RESERVE, which reserves a region of virtual address space without committing the memory to the system.

  • MEM_COMMIT, which commits the region and charges it against the system’s available commit capacity.

Using both flags reserves and commits the region. A reserved but uncommitted region cannot be safely used as ordinary writable memory; attempting to write to it can cause an access violation.

Creating a VAD does not necessarily create all the corresponding page-table entries immediately. When the program accesses an address that has not yet been mapped, a page fault occurs. The system consults the appropriate VAD to determine whether the address is part of a valid allocation and whether it is committed. If so, the system can establish the needed mapping. If the mapping already exists, the VAD does not need to be consulted for that access.

The executable’s section object is mapped into this address space. The system also creates and initializes a Process Environment Block (PEB) in user memory. The PEB contains information for user-mode routines, including the image’s base address, a list of loaded DLLs, and flags such as whether the process is being debugged. ntdll.dll is also mapped into the process.


Creating the initial thread

A process needs a thread to begin executing its code. The kernel creates an executive thread object, commonly called an ETHREAD, through a routine such as PspAllocateThread.

The thread setup includes:

  • A user-mode stack.

  • A Thread Environment Block (TEB), which stores information for user-mode code about that thread. Each thread has its own TEB.

  • A KTHREAD structure, which holds kernel-related thread data.

  • A kernel stack and an initialized thread context.

The thread context captures the processor state needed for execution. The scheduler is responsible for deciding when a thread runs and on which processor.

Process and thread insertion routines complete additional setup. The kernel returns a handle to the process, creates a handle to the new thread, updates the process’s thread count and thread list, and performs scheduling-related initialization. The new thread can be placed in a deferred-ready state: it is prepared to run on a processor but is not yet executing.


CSRSS registration and resuming the thread

After the kernel’s process-creation work returns to CreateProcessInternalW, that function communicates with the Client/Server Runtime Subsystem (CSRSS). CSRSS is a system process that tracks processes and threads within a session. The message sent to it can include process and thread handles, the PEB address, and the section-object handle.

This communication uses Advanced Local Procedure Call (ALPC), a local interprocess communication mechanism. The details of ALPC are beyond the scope of the process-creation overview.

The initial thread remains suspended while setup is completed. CreateProcessInternalW eventually resumes it. The thread begins through a kernel function identified as KxStartUserThread (also referred to in documentation as KiStartUserThread). The Kx prefix indicates a processor-architecture-specific implementation.

Normally, a transition from user mode to kernel mode leaves a trap frame on the kernel stack. A trap frame records the CPU state at the transition. Because this thread has not yet made such a transition, the startup routine constructs a trap frame itself and sets it up to begin at the user-mode function LdrInitializeThunk in ntdll.dll.


Loading DLLs and resolving imports

The loader database

LdrInitializeThunk, also known as the image loader, performs important user-mode initialization. One of its jobs is to create and initialize the loader database, referenced by the Ldr field of the PEB. This database tracks the DLLs loaded into the process.

The loader needs to determine which libraries and functions the executable requires. It does so by examining the PE file’s Import Directory Table (IDT).

Import descriptors and lookup tables

The optional header’s data directories identify the import directory. The import directory’s value is an offset relative to the executable’s base address. Following that offset leads to a sequence of IMAGE_IMPORT_DESCRIPTOR structures, which may be stored in a dedicated .idata section or as part of an .rdata section.

Important fields in each import descriptor include:

  • Name, which identifies the library 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 functions that the program imports from a library. An imported function may be identified by its name or by an ordinal, a number representing a specific exported function.

Initially, the INT and IAT contain corresponding lookup information. The loader uses that information to locate each function in the library’s export table. After locating a function, it places the function’s address in the corresponding IAT entry. The program can then call the function through the address recorded in the IAT.

Once the IAT has been filled with function addresses, it no longer serves the same name-lookup purpose as the INT. This is why the original lookup information is maintained separately.

A loaded DLL may itself import functions from other DLLs. The loader must therefore resolve the imports of dependencies as well, not merely those of the main executable. The loader also performs additional work, including initializing the heap, applying shims, and relocating images. Once its initialization work is complete, it calls the executable’s entry point.

The central sequence is therefore: Windows maps the executable and creates its process and initial thread; the initial thread starts the user-mode loader; and the loader maps required libraries, resolves their imported functions, and transfers control to the program’s entry point.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent