OPERATING SYSTEMS**

Image

So far, we’ve examined a computer’s hardware and software. In this chapter, we look at a particular kind of software: operating systems. First, we cover the challenges of programming without an operating system (OS). Then we look at an overview of OSes. We spend the bulk of the chapter detailing some of the core capabilities of operating systems. In the projects, you have a chance to examine the workings of Raspberry Pi OS.

Programming Without an Operating System

Let’s begin by considering what it’s like to use and program a device without an OS. As you’ll see in a minute, operating systems provide an interface between hardware and other software. However, on a device without an OS, the software has direct access to the hardware. There are many examples of computers that work this way, but let’s focus on one type in particular: early video game consoles. If we look back at game consoles such as the Atari 2600, the Nintendo Entertainment System, or the Sega Genesis, we find hardware that runs code from a cartridge, with no operating system in place. Figure 10-1 illustrates the idea that the game’s software ran directly on the console hardware, with nothing in between.

image

Figure 10-1: Early video games ran directly on game console hardware, with no operating system.

To use such a system you simply inserted a cartridge and turned on the system to start the game. The game console ran only one program at a time—the game currently in the cartridge slot. On most systems of this kind, turning on the system without a cartridge inserted did nothing, since the CPU didn’t have any instructions to run. To switch to a different game, you needed to turn off the system, swap cartridges, and turn it back on. There was no concept of switching between programs while the system was running. Nor were any programs running in the background. A single program, the game, had the complete attention of the hardware.

As a programmer, making a game for a system like this meant taking responsibility for directly controlling hardware with code. Once the system powered up, the CPU began running the code on the cartridge. The game developer not only had to write software for the game’s logic but also had to initialize the system, control the video hardware, read the hardware state of the controller inputs, and so forth. Different console hardware had radically different designs, so a developer needed to understand the intricacies of the hardware they were targeting.

Fortunately for old-school game developers, a game console would retain the same hardware design, more or less, during the years it was manufactured. For example, all Nintendo Entertainment System (NES) consoles have the same type of processor, RAM, picture processing unit (PPU), and audio processing unit (APU). To be a successful NES developer you had to have a solid understanding of all this hardware, but at least the hardware was the same in every NES sold to gamers. Developers knew exactly what hardware would be in a system, so they could target their code to that specific hardware, which allowed them to squeeze every ounce of performance from the system. However, to port their game to another type of game console, they often had to rewrite a substantial portion of their code. Additionally, every game cartridge had to include similar code to accomplish fundamental tasks, such as initializing the hardware. Although developers could reuse code they had previously written for other games, this still meant different developers were solving the same challenges over and over, with varying degrees of success.

Operating Systems Overview

Operating systems provide a different model for programming, and in doing so, address many of the challenges associated with writing code that directly targets specific hardware. An operating system (OS) is software that communicates with computer hardware and provides an environment for the execution of programs. Operating systems allow programs to request system services, such as reading from storage or communicating over a network. OSes handle the initialization of a computer system and manage the execution of programs. This includes running multiple programs in parallel, or multitasking , ensuring that multiple programs can share time on the processor and share system resources. An OS puts boundaries in place to ensure that programs are isolated from each other and from the OS, and to ensure that users who share a system are granted appropriate access. You can think of an operating system as a layer of code between hardware and applications, as illustrated in Figure 10-2 .

image

Figure 10-2: An operating system acts as a layer between hardware and applications.

This layer provides a set of capabilities that abstract away the details of the underlying hardware, allowing software developers to focus on the logic of their software, rather than on communicating with specific hardware. As you might expect, this is very useful, given the diversity of today’s computing devices. Considering the amazing variety of hardware found in smartphones and PCs, writing code for each type of device is impractical. Operating systems hide the details of hardware and provide common services that applications can build on.

At a high level, the components included with an operating system can be categorized into two major buckets:

  • The kernel
  • Everything else

An operating system kernel is responsible for managing memory, facilitating device I/O, and providing a set of system services for applications. The kernel allows multiple programs to run in parallel and share hardware resources. It is the core part of an operating system, but it alone provides no way for end users to interact with the system.

Operating systems also include non-kernel components that are needed for a system to be of use. This includes the shell , a user interface for working with the kernel. The terms shell and kernel are part of a metaphor for operating systems, where the OS is thought of as a nut or seed. The kernel is at the core; a shell surrounds it. The shell can be either a command line interface (CLI) or a graphical user interface (GUI). Some examples of shells are the Windows shell GUI (including the desktop, Start menu, taskbar, and File Explorer), and the Bash shell CLI found on Linux and Unix systems.

Some capabilities of operating systems are provided by software that runs in the background, distinct from the kernel, known as daemons or services (not to be confused with kernel system services mentioned earlier). An example of such a service is Task Scheduler on Windows or cron on Unix and Linux, both of which allow the user to schedule programs to run at certain times.

Operating systems also commonly include software libraries for developers to build on. Such libraries include common code that many applications can leverage. Additionally, components of the operating system itself, such as the shell and services, use the functionality provided by such libraries.

When it comes to interacting with hardware, the kernel acts in partnership with device drivers. A device driver , or simply driver , is software designed to interact with specific hardware. An operating system’s kernel needs to work with a wide variety of hardware, so rather than designing the kernel to know how to interact with every hardware device in the world, software developers implement the code for specific devices in device drivers. Operating systems typically include a set of device drivers for common hardware and also provide a mechanism for installing additional drivers.

Most operating systems include a collection of basic applications like a text editor and calculator, often referred to collectively as utilities . A web browser is also a standard inclusion for many operating systems. Such utilities are arguably not truly part of the operating system and are rather simply applications, but in practice, most operating systems include this kind of software. Figure 10-3 provides a summarized view of the components included in an operating system.

image

Figure 10-3: An operating system includes multiple components.

As you can see in Figure 10-3 , at the foundation of the software stack, right above hardware, are the kernel and device drivers. Libraries provide functionality that applications build on, so libraries are shown as a layer between the kernel and applications. The shell, services, and utilities also build on libraries.

Operating System Families

Today, there are two dominant operating system families: Unix-like operating systems, and Microsoft Windows. As the name implies, Unix-like operating systems behave like a Unix operating system. Linux, macOS, iOS, and Android are all examples of Unix-like operating systems. Unix was first developed at Bell Labs and has a history that goes back to the 1960s. Unix initially ran on a PDP-7 minicomputer, but it has since been ported to many kinds of computers. Originally written in assembly language, Unix was later rewritten in C, allowing it to be compiled for various processors. Today it’s used on servers, and it has a strong presence on personal computers and smartphones thanks to Apple’s macOS and iOS, both of which are based on Unix. Unix supports multiple users, multitasking, and a unified, hierarchical directory structure. It has a robust command line shell, supported by well-defined standard command line tools that can be used together to accomplish complex tasks.

The Linux kernel was originally developed by Linus Torvalds, who set out to create an operating system that was similar to Unix. Linux isn’t Unix, but it’s certainly Unix-like. It behaves much like Unix while not including any Unix source code. A Linux distribution is an OS that’s a bundling of the Linux kernel with other software. The Linux kernel is open source , meaning its source code is freely available. Many distributions of Linux are available at no cost. A typical Linux distribution includes a Linux kernel and a collection of Unix-like components from the GNU project (pronounced “guh-new”).

GNU , a recursive acronym that stands for GNU’s Not Unix , is a software project started in the 1980s, with a goal of creating a Unix-like operating system as free software. The GNU project and Linux are separate efforts, but they have become closely associated. The release of the Linux kernel in 1991 prompted an effort to port GNU software to Linux. At the time, GNU didn’t have a complete kernel, whereas Linux lacked a shell, libraries, and so forth. Linux provided a kernel for GNU code to run upon, while the GNU project provided a shell, libraries, and utilities to Linux. In this way, the two projects are complementary, and together form a complete operating system.

Today, people commonly use the term Linux to refer to operating systems that are combinations of the Linux kernel and GNU software. This is somewhat controversial, since calling the entire OS “Linux” doesn’t recognize the large part that GNU software plays in many Linux distributions. That said, in this book I follow the prevalent convention of referring to the entire OS as Linux, rather than GNU/Linux or something similar.

Today, Linux is commonly found on servers and embedded systems, and it’s popular with software developers. The Android operating system is based on the Linux kernel, so Linux has a huge presence in the smartphone market. Raspberry Pi OS (previously called Raspbian) is also a Linux distribution that includes GNU software, and we’ll be using Raspberry Pi OS to explore Linux further. In general, in this book I’m going to lean on Linux rather than Unix when giving examples of Unix-like behavior.

Microsoft Windows is the dominant operating system on personal computers, including desktops and laptops. It also has a strong presence in the server space (Windows Server). Windows is unique in that it doesn’t trace its roots back to Unix. Early versions of Windows were based on MS-DOS (Microsoft Disk Operating System). Although popular in the home computer market, these early versions of Windows were not robust enough to compete against Unix-like operating systems in the server or high-end workstation market.

In parallel to the development of Windows, Microsoft partnered with IBM in the 1980s to create the OS/2 operating system, an intended successor to MS-DOS on the IBM PC. Microsoft and IBM disagreed on the direction of the OS/2 project, and in 1990, IBM took over development of OS/2, whereas Microsoft pivoted their efforts to another operating system they already had under development, Windows NT. Unlike the MS-DOS–based versions of Windows, Windows NT was based on a new kernel. Windows NT was designed to be portable across different hardware, be compatible with various types of software, support multiple users, and provide high levels of security and reliability. Microsoft hired Dave Cutler from Digital Equipment Corporation (DEC) to lead the work on Windows NT. He brought a number of former DEC engineers with him, and elements of the NT kernel’s design can be traced to Dave Cutler’s work on the VMS operating system at DEC.

In its early releases, Windows NT was positioned as a business-focused version of Windows that would coexist with the consumer-focused version of Windows. These two Windows versions were quite different in their implementations, but they shared a similar user interface and programming interface. The user interface similarities meant that users familiar with Windows could readily be productive on a Windows NT system. The common programming interface allowed software developed for DOS-based Windows to work, sometimes without alteration, on Windows NT. With the release of Windows XP in 2001, Microsoft brought the NT kernel to a consumer-focused release of Windows. Since the release of Windows XP, all versions of desktop and server Windows have been built upon the NT kernel.

Table 10-1 lists some operating systems and devices commonly in use today and the OS family for each.

Table 10-1: Common Operating Systems

OS or device Family Notes
Android Unix-like Android uses the Linux kernel, although otherwise, it isn’t very Unix-like. Its user experience and application programming interfaces are quite different from a typical Unix system.
iOS Unix-like iOS is based on the Unix-like open source Darwin operating system. Like Android, the iOS user experience and programming interface are different from a typical Unix system.
macOS Unix-like macOS is based on the Unix-like open source Darwin operating system.
PlayStation 4 Unix-like The PlayStation 4 OS is based on the Unix-like FreeBSD kernel.
Raspberry Pi OS Unix-like Raspberry Pi OS is a Linux distribution.
Ubuntu Unix-like Ubuntu is a Linux distribution.
Windows 10 Windows Windows 10 uses the Windows NT kernel.
Xbox One Windows Xbox One has an OS that uses the Windows NT kernel.

EXERCISE 10-1: GET TO KNOW THE OPERATING SYSTEMS IN YOUR LIFE

Choose a couple of computing devices that you own or use, say a laptop, smartphone, or game console. What operating system does each device run? To what operating system family (Windows, Unix-like, other) does each belong?

Kernel Mode and User Mode

An operating system is responsible for ensuring that the programs that run on it behave well. What does this mean in practice? Let’s look at some examples. Each program must not interfere with other programs or with the kernel. Users shouldn’t be able to modify system files. Applications must not be allowed to directly access hardware; all such requests must go through the kernel. Given these kinds of requirements, how can the operating system ensure that non-OS code complies with the mandates of the operating system? This is handled by leveraging a CPU capability that grants the operating system special rights while placing restrictions on other code; this is known as the privilege level of the code. A processor may offer more than two levels of privilege, but most operating systems only use two levels. The level of higher privilege is known as kernel mode , and the level of lower privilege is known as user mode . Kernel mode is also referred to as supervisor mode . Code running in kernel mode has full access to the system, including access to all memory, I/O devices, and special CPU instructions. Code running in user mode has limited access. Generally speaking, the kernel and many device drivers run in kernel mode, whereas everything else runs in user mode, as illustrated in Figure 10-4 .

image

Figure 10-4: The division of code that runs in user mode vs. kernel mode

Code allowed to run in kernel mode is trusted , whereas user mode code is untrusted . Code that runs in kernel mode has full access to everything on a system, so it better be trustworthy! By only allowing trusted code to run in kernel mode, the operating system can ensure that user mode code is well-behaved.

KERNEL MODE COMPONENTS IN WINDOWS

It’s worth noting that Microsoft Windows has a few other major components that run in kernel mode. In Windows, foundational kernel mode capabilities are actually split between two components: the kernel and the executive . The distinction is only relevant when discussing the internal architecture of Windows; the separation is not of concern to most software developers or users. In fact, the compiled machine code for both the kernel and the executive is contained in the same file ( ntoskrnl.exe ). I won’t distinguish between the Windows NT kernel and executive for the remainder of this book. Besides the kernel, executive, and device drivers, Windows has other major components that run in kernel mode. The Hardware Abstraction Layer (HAL) isolates the kernel, executive, and device drivers from differences in low-level hardware, such as variations in motherboards. The windowing and graphics system (win32k) provides capabilities for drawing graphics and programmatically interacting with user interface elements.

Processes

One of an operating system’s main functions is to provide a platform for programs to run. As we saw in the previous chapter, programs are sequences of machine instructions, typically stored in an executable file. However, a set of instructions stored in a file can’t actually perform any work on its own. Something needs to load the file’s instructions into memory and direct the CPU to run the program, all while ensuring the program doesn’t misbehave. That’s the job of the operating system. When an operating system starts a program, it creates a process , a running instance of that program. Earlier we covered things that run in user mode (such as the shell, services, and utilities)—each of these execute within a process. If code is running in user mode, it’s running within a process, as illustrated in Figure 10-5 .

A process is a container in which a program runs. This container includes a private virtual memory address space (more on this later), a copy of the program code loaded into memory, and other information about the state of the process. A program can be started multiple times, and each execution results in the operating system creating a new process. Each process has a unique identifier (a number) called a process identifier , a process ID , or just a PID .

image

Figure 10-5: Processes run in user mode

Other than initial processes started by the kernel, every process has a parent, the process that started it. This relationship of parent to child creates a tree of processes. If a child’s parent process terminates before the child, the child becomes an orphan process , meaning, not surprisingly, it has no parent. On Windows, the orphaned child process simply remains parentless. On Linux, an orphaned process is typically adopted by the init process , the first user mode process to start on a Linux system.

Figure 10-6 shows a process tree on Raspberry Pi OS. This view was generated using the pstree utility.

image

Figure 10-6: An example Linux process tree as shown by pstree

In Figure 10-6 , we see that the init process was systemd ; it was the first process to start, and it in turn started other processes. Child threads are shown with curly braces (more on threads soon). To generate this output, I ran the pstree command from a command line shell, and in the output, you can see that pstree itself is running, as expected. It’s the child of bash (the shell), which in turn is the child of sshd . In other words, you can tell from this output that I ran pstree from a Bash shell that was opened in a remote Secure Shell (SSH) session.

To see the process tree on a computer running Windows, I recommend that you use the Process Explorer tool that you can download from Microsoft. It’s a GUI application that gives you a rich view of the processes running on your computer.

NOTE

Please see Project #20 on page 218 , where you can look at running processes on your device .

Threads

By default, a program executes instructions sequentially, handling one task at a time. But what if a program needs to perform two or more tasks in parallel? For example, let’s say a program needs to perform some long-running calculation while updating the user interface at the same time, perhaps to show a progress bar. If the program is completely sequential, once the program begins its calculation, the user interface is neglected, since the CPU time allocated to the program must be spent elsewhere. The desired behavior is that the UI updates while the calculation runs—these are two separate tasks that need to happen in parallel. Operating systems provide this capability with threads of execution , or just threads . A thread is a schedulable unit of execution within a process. A thread runs within a process and can execute any program code loaded in that process.

The code run by a thread typically encompasses a particular task that a program wishes to accomplish. Since threads belong to a process, they share an address space, code, and other resources with all the other threads in that process. A process begins with one thread and may create other threads as needed when work needs to be handled in parallel. Each thread has an identifier called a thread ID , or TID . The kernel also creates threads to manage its work. Figure 10-7 illustrates the relationship between threads, processes, and the kernel.

In Windows, threads and processes are distinct object types. A process object is a container, and threads belong to a process. In Linux, the distinction is more nuanced. The Linux kernel represents both processes and threads using a single data type that serves as both a process and a thread. In Linux, a group of threads that share an address space and have a common process identifier are considered a process; there is no separate process type.

image

Figure 10-7: Threads belong to user mode processes or to the kernel.

The Linux terminology used to refer to the identifiers for processes and threads can be a bit confusing. In user mode, a process has a process ID (PID) and a thread has a thread ID (TID). This is just like Windows. However, the Linux kernel refers to the ID of a thread as a PID and the ID of a process as a thread group identifier (TGID) !

NOTE

Please see Project #21 on page 220 , where you can create your own thread .

What does it really mean for multiple threads to run in parallel? Let’s say your computer has 10 processes running, and each process has 4 threads. That’s 40 threads in user mode alone! We say that threads run in parallel, but can all 40 threads really run at the same time? No, not unless your computer has 40 processor cores, which it probably doesn’t. Each processor core can only run one thread at a time, so the number of cores in a device determines how many threads can run at once.

PHYSICAL AND LOGICAL CORES

Not all cores are equally capable of parallelism. A physical core is a hardware implementation of a core within a CPU. Logical cores represent the ability of a single physical core to run multiple threads at once (one thread per logical core). Intel refers to this capability as hyper-threading . As an example, the computer I’m using to write this book has two physical cores, each with two logical cores, for a total of four logical cores. This means that my computer can run four threads at once, although logical cores cannot achieve the full parallelism of physical cores.

So if we have 40 threads that need to run, but only 4 cores, what happens? The operating system implements a scheduler , a software component that’s responsible for ensuring that threads each get their turn to run. Different approaches are used across operating systems to implement scheduling, but the fundamental goal is the same: give threads time to run. A thread gets a short period of time to run (known as a quantum ), then the thread is suspended to allow another thread to run. Later, the first thread is scheduled again, and it picks up where it left off. This is mostly hidden from the thread’s code and the developer who wrote the application. From the perspective of the thread’s code, it’s running continuously, and developers write their multithreaded applications as if all their threads were running continuously in parallel.

Virtual Memory

Operating systems support multiple running processes, each of which need to use memory. Most of the time, one process does not need to read or write to the memory of another process, and in fact, it’s generally undesirable. We don’t want a misbehaving process stealing data or overwriting data in another process or, worse, in the kernel. Additionally, developers don’t want their process’s address space to become fragmented from the memory usage of other processes. For these reasons, operating systems do not grant user mode processes access to physical memory, and instead each process is presented with virtual memory —an abstraction that gives each process its own large, private address space.

In Chapter 7 , we covered memory addressing in which each physical byte in hardware is assigned an address. Such hardware memory addresses are called physical addresses . These addresses are typically hidden from user mode processes. Operating systems instead present processes with virtual memory , where each address is a virtual address . Each process is given its own virtual memory space to work in. To an individual process, memory appears as a large range of addresses. When a process writes to a certain virtual address, that address does not directly refer to a hardware memory location. The virtual address is translated to a physical address when needed, as shown in Figure 10-8 , but the details of this translation are hidden from the process.

The advantage of this approach is that each process is given a large, private range of virtual memory addresses that it can work with. In general, each process on a system is presented the same range of memory addresses. For example, each process might be given 2GB of virtual address space, from address 0x0000000 to 0x7FFFFFFF. This might seem problematic; what happens when two programs try to use the same memory address? Can one program overwrite or read another program’s data? Thanks to virtual addressing, this isn’t a problem.

The same virtual address for multiple programs maps to different physical addresses, so there’s no chance of one program accidentally accessing another’s data in memory. This means that the data stored at a certain virtual address is different across different processes—the virtual addresses may be the same, but the data stored there differs. That said, mechanisms are in place for programs to share memory if they need to. In older operating systems, memory space wasn’t so cleanly divided, leading to abundant opportunities for programs to corrupt memory in other programs or even in the operating system. Fortunately, all modern operating systems ensure separation of memory between processes.

image

Figure 10-8: Virtual address space for each process is mapped to physical memory

It’s important to understand that although the address range of a process may be 2GB in size (for example), that doesn’t mean that all 2GB of virtual memory is immediately available for the process to use. Only a subset of those addresses is backed by physical memory. Think back to the projects you performed in Chapters 8 and 9 ; those were actually virtual memory addresses that you were examining, not physical ones.

The kernel has a separate virtual address space to work in with a range of addresses that’s distinct from the address range assigned to user mode processes. Unlike user mode address space, kernel address space is shared by all code running in kernel mode. That means that any code running in kernel mode has access to everything in the kernel address space. This also gives such code the opportunity to modify the contents of any kernel memory. This reinforces the idea that code that runs in kernel mode must be trusted!

So how is virtual address space divided between user mode and kernel mode? Let’s look at 32-bit operating systems. As discussed in Chapter 7 , for a 32-bit system, memory addresses are represented as 32-bit numbers, which means 4GB of address space in total. This address space’s range of addresses must be split between kernel mode and user mode. For a 4GB address space, both Windows and Linux allow for a split of either 2GB user/2GB kernel or 3GB user/1GB kernel, based on a configuration setting. Figure 10-9 illustrates an even 2GB split of virtual memory.

image

Figure 10-9: Virtual address space on a 32-bit system with an even 2GB/2GB split

Keep in mind that we’re strictly concerned with virtual addresses here. A 32-bit system has 4GB of virtual address space regardless of how much physical memory it has. Let’s say a computer only has 1GB of RAM; it still has 4GB of virtual address space under a 32-bit OS. Recall that a virtual address range doesn’t represent mapped physical memory, only a range where physical memory can be mapped. That said, it’s certainly possible for the kernel and all running processes to request more bytes of virtual memory than the total size of RAM. In that situation, the operating system can move bytes of memory to secondary storage to make room in RAM for newly requested memory, a process known as paging . Typically, the least used memory gets paged first so that actively used memory can remain in RAM. When the paged memory is needed, the OS must load it back into RAM. Paging allows for greater virtual memory usage, at the cost of a performance hit incurred while bytes are moved to and from secondary storage. Keep in mind that secondary storage is significantly slower than RAM.

NOTE

Please see Project #22 on page 222 , where you can examine virtual memory .

With the arrival of 64-bit processors and operating systems came the potential for much, much larger address spaces. If we represented memory addresses with a full 64 bits, virtual address space would be about 4 billon times the size of 32-bit address space! However, such a large address space isn’t needed today, so 64-bit operating systems use a smaller number of bits to represent addresses. Different 64-bit operating systems on different processors use varying numbers of bits to represent an address. Both 64-bit Linux and 64-bit Windows support 48-bit addresses, which translates to 256TB of virtual address space, about 65,000 times the size of 32-bit address space—more than enough space for today’s typical application.

Application Programming Interface (API)

When most people think of an operating system, they think of the user interface, the shell. The shell is what people see, and it influences how people perceive the system. For example, a Windows user typically thinks of Windows as the taskbar, Start menu, desktop, and so forth. However, the user interface is actually only a small part of the operating system’s code, and it’s just an interface, the point where the system and the user meet. From the perspective of an application (or a software developer), interacting with the operating system isn’t defined by the UI, but by the operating system’s application programming interface (API) . APIs are not only for operating systems; any software that wants to allow a programmatic means of interaction can provide an API, but our focus here is specifically on OS APIs.

An OS API is a specification, defined in source code and described in documentation, that details how a program should interact with the OS. A typical OS API includes a list of functions (including their names, inputs, and outputs) and data structures needed for interacting with the operating system. Software libraries included with the operating system provide the implementation of the API specification. Software developers speak of “calling” or “using” an API as a shorthand way of saying that their code is invoking one of the functions specified in the API (and implemented in a software library).

In the same way that a UI defines an OS’s “personality” for users, the API defines the OS’s personality for applications. Figure 10-10 illustrates how users and applications interact with an operating system.

image

Figure 10-10: Operating system interfaces: UI for users; API for applications

As seen in Figure 10-10 , users interact with the operating system user interface, also known as the shell. The shell translates the user’s commands into API calls. The API then invokes internal operating system code to perform the requested action. Applications don’t need to go through the UI; they simply call the API directly. From this point of view, the shell interacts with the operating system API just like any other application.

Let’s look at an example of interfacing with operating systems via an API. Creating a file is a common capability of operating systems, something that both users and applications need to do. Graphical shells and command line shells provide simple ways for users to create files. However, an application doesn’t need to go through the GUI or CLI to create a file. Let’s examine how an application can go about creating a file programmatically.

For Unix or Linux systems, you can use an API function called open to create a file. The following C language example uses the open function to create a new file called hello.txt . The O_WRONLY flag indicates a write-only operation, and O_CREAT indicates that a file is to be created.

open("hello.txt", O_WRONLY|O_CREAT);

The same thing can be accomplished on Windows using the CreateFileA API function:

CreateFileA("hello.txt", GENERIC_WRITE, 0, NULL,
    CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);

Both of these examples use the C programming language. Operating systems are commonly written in C, so their APIs tend to be naturally suited for use in a C program. For programs written in other languages, the OS API must still be called when the program runs, but the programming language wraps that API call in its own syntax, hiding the details of the API from the developer. This allows for code that’s portable across operating systems. Even the C language does this, providing a standard library of functions that work on any operating system. These functions, in turn, must make an OS-specific API call when they run. Consider again the example of creating a file; in C we can instead use the fopen function as shown in the following code. This function is part of the C language’s standard library and works on any operating system.

fopen("hello.txt", "w");

As another example, we can use the following Python code to create a new file. This code works on any OS where a Python interpreter is installed. The Python interpreter takes care of calling the appropriate OS API on behalf of the application.

open('hello.txt', 'w')

For Unix-like operating systems, the API varies somewhat based on the specific flavor of Unix or Linux and the version of the kernel. However, most Unix-like operating systems comply with a standard specification, either in full or in part. This standard is known as the Portable Operating System Interface (POSIX) , and it provides a standard not only for the OS API, but also for the shell’s behavior and included utilities. POSIX provides a baseline for Unix-like operating systems, but a modern Unix-like OS often has its own API. Cocoa is Apple’s API for macOS, and there is a similar API for iOS known as Cocoa Touch . Android also has its own set of programming interfaces, collectively known as the Android Platform APIs .

The other major OS family, Windows, has its own API. The Windows API has grown and expanded over time. The original version of the Windows API was a 16-bit version now known as Win16 . When Windows was updated to a 32-bit operating system in the 1990s, a 32-bit version of the API, Win32 , was released. Now that Windows is a 64-bit operating system, there is a corresponding Win64 API. Microsoft also introduced a new API in Windows 10, the Universal Windows Platform (UWP) , with a goal of making app development consistent across various types of devices that run Windows.

NOTE

Please see Project #23 on page 224 , where you can try interacting with the Linux operating system API .

The User Mode Bubble and System Calls

As mentioned earlier, code that runs in user mode has limited access to the system. So what are some of the things that user mode code can do? It can read and write to its own virtual memory, and it can perform mathematical and logical operations. It can control the program flow of its own code. On the other hand, code running in user mode cannot access physical memory addresses, including addresses used for memory-mapped I/O. That means that it cannot, on its own, print text to a console window, get input from the keyboard, draw graphics to the screen, play a sound, receive touchscreen input, communicate over a network, or read a file from a hard drive! I like to say that “user mode code runs in a bubble” ( Figure 10-11 ). It cannot interact with the outside world, at least not without some help. Another way of stating this is that user mode code cannot directly perform I/O. The practical effect of this is that code running in user mode can do useful work, but it cannot share the results of that work without assistance.

image

Figure 10-11: A process runs in a user mode bubble. It can do math, perform logic, access virtual memory, and control program flow, but it cannot interact directly with the outside world.

You may wonder how it is that user mode applications interact with users. Of course, applications are somehow able to interact with the outside world, but how is that accomplished? The answer is that user mode code has one other important capability: it can request that kernel mode code perform work on its behalf. When user mode code requests that kernel mode code perform a privileged operation on its behalf, this is known as a system call , as illustrated in Figure 10-12 .

image

Figure 10-12: A user mode process can interact with the outside world with help from the kernel by making a system call.

For example, if user mode code needs to read from a file, it makes a system call to request that the kernel read certain bytes from a certain file. The kernel, working in conjunction with a storage device driver, performs the necessary I/O to read the file, and then provides the requested data back to the user mode process. This is illustrated in Figure 10-13 .

image

Figure 10-13: The kernel acts as an intermediary for user mode code that needs to access hardware resources, such as secondary storage.

The user mode code doesn’t need to know anything about the physical storage device or any related device drivers. The kernel provides an abstraction, encapsulating the details and allowing the user mode code to simply get things done. The example API functions we covered earlier, open and CreateFileA , work this way behind the scenes, using system calls to request privileged operations. Of course, there are constraints on what the kernel will allow. A user mode process cannot, for example, read a file that it does not have access to.

CPUs provide instructions specifically to facilitate system calls. On ARM processors, the SVC instruction (formerly SWI ) is used, and it’s referred to as a supervisor call . On x86 processors, the SYSCALL and SYSENTER instructions are available for this purpose. Both Linux and Windows implement a large number of system calls, and each call is identified with a unique number. For example, on Linux for ARM, the write system call (which writes to a file) is number 4. To make a system call, a program needs to load a certain processor register with the desired system call number, put any additional parameters in other specific registers, and then execute the system call instruction.

Although software developers can make system calls directly in machine code or assembly language, fortunately this isn’t needed in most cases. Operating systems and high-level programming languages provide capabilities for making system calls in a natural way for programmers, usually through the OS API or the language’s standard library. Programmers simply write code to perform an action and may not even realize that behind the scenes a system call is being made.

NOTE

Please see Project #24 on page 226 , where you can observe system calls made from programs .

APIs and System Calls

Earlier we covered the topic of an operating system’s API, and we just looked at system calls. How does an OS API differ from a system call? The two are related, but they are not equivalent. System calls define a mechanism for user mode code to request kernel mode services. The API describes a way for applications to interact with the operating system, regardless of whether kernel mode code is invoked. Some API functions make system calls, whereas other API functions do not require a system call. The specifics of this depend on the operating system.

Let’s first look at Linux. If we restrict our definition of Linux to the kernel, we could say that the Linux API is effectively a specification for using Linux system calls, since system calls are the programmatic interface to the kernel. However, operating systems based on Linux are more than the kernel. For example, consider Android, which uses the Linux kernel. Android has its own set of programming interfaces, the Android Platform APIs.

In the case of Microsoft Windows, the Windows NT kernel provides a set of system calls, made available through an interface known as the Native API. Application developers rarely use the Native API directly; it’s intended for use by operating system components. Instead, developers use the Windows API, which acts as a wrapper around the Native API. However, not all of the Windows API functions require a system call. Let’s look at a couple of examples from the Windows API. The Windows API function CreateFileW creates or opens a file. It’s a wrapper around the Native API NtCreateFile , which makes a system call to the kernel. In contrast, the Windows API function PathFindFileNameW (which finds a filename in a path) does not interact with the Native API or make any system calls. Creating a file requires the help of the kernel, whereas finding a filename in a path string only requires virtual memory access, something that can happen in user mode.

To recap, an operating system API describes the programmatic interface for the OS. System calls provide a mechanism for user mode code to request privileged kernel mode operations. Certain API functions rely on system calls, whereas others do not.

Operating System Software Libraries

As mentioned earlier, an operating system API describes the programmatic interface to an operating system. Although a technical interface description is helpful to a programmer, when a program runs, it needs a concrete method of invoking the API. This is accomplished with software libraries. An operating system’s software library is a collection of code, included with the OS, that provides an implementation of the OS API. That is, the library contains code that performs the operations described in the API specification. In Chapter 9 , we talked about the libraries available for programming languages: both the language’s standard library and additional libraries maintained by the community of developers who work in that language. The software libraries we’re discussing here are similar; the only difference is that these libraries are part of operating systems.

An OS library is similar to an executable program; it’s a file containing bytes of machine code. However, it typically has no entry point and therefore usually can’t run on its own. Instead, the library exports (makes available) a set of functions that can be used by programs. A program that makes use of a software library imports functions from that library and is said to link to that library.

Operating systems include a set of library files that export the various functions defined by the API. Some of these functions are just wrappers that immediately make a kernel system call. Other functions are fully implemented in user mode code contained in the library file itself. Others are somewhere in-between, implementing some logic in user mode while also making one or more system calls, as shown in Figure 10-14 .

In a typical Linux distribution, many of the available Linux kernel system calls are made available through the GNU C Library (or glibc ). This library also includes the C programming language’s standard library, including functions that do not require a system call. The primary glibc file is typically named something like libc.so.6 , where so means shared object and 6 indicates the version. Using this library, a software developer working in C or C++ can easily make use of capabilities provided by the Linux kernel and by the C runtime library. Given the ubiquity of this library in most Linux distributions, it’s reasonable to consider the functions in glibc as part of the standard Linux API.

image

Figure 10-14: The operating system API is implemented across a set of libraries. Some functions in those libraries make system calls to the kernel; others do not. User mode programs interact with the API.

NOTE

Please see Project #25 on page 227 , where you can try the GNU C Library .

The Microsoft Windows API is fairly extensive; it has grown to include many libraries over the years. The three fundamental Windows API library files are kernel32.dll , user32.dll , and gdi32.dll . System calls exported from the NT kernel are made available to user mode programs through kernel32.dll . System calls exported from win32k (the windowing and graphics system) are made available to user mode programs through user32.dll and gdi32.dll .

The dll extension on these files indicates that these are dynamic link libraries , similar to shared object ( .so ) files in Linux. That is, the dll file extension indicates that the file contains shared library code that a process can load and run. The 32 suffix in the filename was added as part of the 16-bit to 32-bit Windows transition. Today, 64-bit versions of Windows still retain the 32 suffix on these files for compatibility reasons. In fact, 64-bit versions of Windows include two versions of these files (same name, different directories), one for 32-bit applications and one for 64-bit applications.

NOTE

It’s possible for a program to invoke system calls without going through a software library. By setting values in processor registers and issuing a processor-specific instruction, such as SVC on ARM or SYSCALL on x86, a program can directly make a system call. However, this requires programming in assembly language, leading to source code that won’t work across processor architectures. Furthermore, an operating system’s API can include functions that aren’t implemented with a system call, so making direct system calls isn’t a replacement for the operating system’s software libraries .

WINDOWS SUBSYSTEM FOR LINUX

The Linux kernel and the Windows NT kernel expose different system calls, and their executables are stored in different formats, making software compiled for one OS incompatible with the other. However, in 2016, Microsoft announced the Windows Subsystem for Linux (WSL) , a Windows 10 feature that allows many 64-bit Linux programs to run, without modification, on Windows. In the first version of WSL, this was accomplished by intercepting system calls made by Linux executables and handling them within the NT kernel. A second version of WSL relies on a real Linux kernel to handle system calls. This Linux kernel runs in a virtual machine alongside the NT kernel. We’ll cover more on virtual machines in Chapter 13 .

Application Binary Interface

Now that we’ve covered the concept of an application programming interface (API) and how it relates to system calls and libraries, let’s examine a related concept, an ABI. An application binary interface (ABI) defines the machine code interface to a software library. This is in contrast to the API, which defines a source code interface. Generally speaking, an API is consistent across various processor families, whereas an ABI varies across processor families. A developer can write code that utilizes an operating system API, then compile the code for multiple processor types. The source code targets a common API, whereas the compiled code targets an architecture-specific ABI.

Once compiled, the resulting machine code adheres to the ABI for the target architecture. This means that at execution time, it’s really the ABI, not the API, that defines the interaction between compiled programs and software libraries. It’s important that the ABI exposed by OS libraries remains consistent over time. Such consistency allows older programs to continue to run on newer releases of the operating system without needing to be recompiled.

Device Drivers

Today’s computers support a wide variety of hardware devices, such as displays, keyboards, cameras, and so forth. These devices each implement an interface for input/output, allowing the device to communicate with the rest of the system. Different device types use different approaches for I/O; a Wi-Fi adapter has very different needs from a game controller. Even devices of the same general type may implement different I/O approaches. For example, two different models of video cards may communicate very differently with the rest of the system. Direct interactions with hardware are restricted to code running in kernel mode, but it isn’t reasonable to expect an operating system kernel to know how to communicate with every device out there. This is where device drivers come in. A device driver is software that interacts with a hardware device and provides a programmatic interface to that hardware.

Typically, a device driver is implemented as a kernel module , a file containing code that the kernel can load and execute in kernel mode. This is needed to allow drivers access to hardware. Because of this, device drivers have wide-ranging access, similar to the kernel itself, so only trusted drivers should be installed. The kernel works in conjunction with device drivers to interact with hardware on behalf of code running in user mode. This allows hardware interactions to occur without the operating system or applications knowing the details of how to work with specific hardware. This is a form of encapsulation. In some cases, drivers can execute in user mode (such as those using Microsoft’s User-Mode Driver Framework), but such an approach still requires some component in kernel mode, usually provided by the operating system, to handle hardware interactions.

NOTE

Please see Project #26 on page 230 , where you can see loaded kernel modules, including device drivers, on Raspberry Pi OS .

Filesystems

Nearly every computer has some kind of secondary storage, usually a hard disk drive (HDD) or a solid-state drive (SSD). Such devices are effectively containers of bits that can be read and written, and where data persists even when the system is powered down. Storage devices are divided into regions called partitions . Operating systems implement filesystems to organize the data on storage devices into files and directories. A partition must be formatted with a particular filesystem before it can be used by the operating system. Different OSes use different filesystems. Linux commonly uses the ext (extended) family of filesystems (ext2, ext3, ext4), whereas Windows uses FAT (File Allocation Table) and NTFS (NT File System). Some operating systems present storage as a volume , a logical abstraction built on one or more partitions. In such a system, filesystems reside on a volume rather than on a partition.

A file is a container of data, and a directory (also known as a folder) is a container of files or other directories. The contents of a file can be anything; the structure of the data stored within the file is determined by the program that wrote the file to storage. Unix-like systems organize their directory structure as a unified hierarchy of directories. The hierarchy starts at the root, designated with a single forward slash ( / ), and all other directories are descendants of the root. For example, library files are stored in /usr/lib , where usr is a subdirectory of the root, and lib is a subdirectory of usr . This unified hierarchy applies even when there is more than one storage device on the system. Additional storage devices are mapped to a location in the directory structure; this is known as mounting a device. For example, a USB drive could be mounted to /mnt/usb1 .

In contrast, Microsoft Windows assigns a drive letter (A–Z) to each volume. So rather than a unified directory structure, each drive has its own root and hierarchy of directories. Windows uses a backslash ( \ ) in its directory paths, and a colon ( : ) after a drive letter. For example, the Windows system files, stored on the C drive, are typically located under C:\windows\system32 . This convention dates back to DOS (and earlier), when drives A and B were reserved for floppy disks, and drive C represented an internal hard drive. To this day, drive C is typically used as the drive letter for the volume where Windows is installed.

NOTE

Please see Project #27 on page 230 , where you can check out the details of storage and files on Raspberry Pi OS .

Services and Daemons

Operating systems provide the ability for processes to automatically run in the background, without user interaction. Such processes are called services on Windows and daemons on Unix-like systems. A typical operating system includes a number of such services that run by default, such as a service to configure network settings, or a service that runs tasks on a schedule. Services are used to provide capabilities that aren’t tied to a specific user, don’t need to run in kernel mode, but do need to be available on demand.

Operating systems usually include a component responsible for managing services. Some services need to start when the OS boots; others need to run in response to a particular event. Often services should be restarted in the case of an unexpected failure. In Windows, the Service Control Manager ( SCM ) performs these types of functions. The SCM’s executable file is services.exe , which is started early in the Windows boot process and continues to run as long as Windows itself is running. Many modern Linux distributions have adopted systemd as the standard component for managing daemons, although other mechanisms can be used in Linux to start and manage daemons. As discussed earlier, systemd also acts as the init process, so it’s started very early in the Linux boot process and continues to run while the system is up.

The Unix and Linux term daemon comes from Maxwell’s demon, a hypothetical being described in a physics thought experiment. This creature worked in the background, much like a computer daemon. Outside of computing, daemon is typically pronounced just like “demon,” but when referring to background processes, “DAY-mon” is an equally acceptable pronunciation. Historically, service was a Windows-specific term, but now it is used on Linux as well, often to refer to daemons that are started by systemd .

NOTE

Please see Project #28 on page 231 , where you can check out services on Raspberry Pi OS .

Security

An operating system provides a security model for the code that runs on that OS. In this context, security means that software, and users of that software, should only have access to appropriate parts of the system. This may not seem like a big deal for a personal device like a laptop or smartphone. If only one user logs into a system, shouldn’t they have access to everything? Well, no, at least not by default. Users make mistakes, including running code that isn’t trustworthy. If a user accidentally runs malicious software on their device, the OS can help limit the damage by restricting that user’s access. On a shared system where multiple users log in, a user should not be able to read or modify another user’s data, at least not by default.

Operating systems make use of multiple techniques to provide security. Let’s look at just a few here. Simply putting applications in a user mode bubble goes a long way toward ensuring that software doesn’t intentionally or accidentally mess with other applications or with the kernel. Operating systems also implement filesystem security, ensuring that data stored in files can only be accessed by appropriate users and processes. Virtual memory itself can be secured—regions of memory can be marked as read only or as executable, helping to limit misuse of memory. Providing a login system for users allows the operating system to manage security based on the user’s identity. These are all baseline expectations of a modern operating system. Unfortunately, security vulnerabilities are regularly discovered in operating systems, allowing malicious actors to bypass the defenses of the OS. Keeping modern internet-connected operating systems up-to-date with the latest updates is critical to maintaining security.

Summary

In this chapter we covered operating systems, software that communicates with computer hardware and provides an environment for the execution of programs. You learned about the operating system kernel, non-kernel components, and the separation of kernel mode and user mode. We reviewed the two dominant operating system families: Unix-like operating systems and Microsoft Windows. You learned that a program runs in a container known as a process, and multiple threads can execute in parallel within that process. We looked at various aspects of programmatically interacting with an operating system: the API, system calls, software libraries, and the ABI. In the next chapter, we’ll move beyond single-device computing and examine the internet, looking at the various layers and protocols that make the internet possible.

PROJECT #20: EXAMINE RUNNING PROCESSES

Prerequisite: A Raspberry Pi, running Raspberry Pi OS. I recommend that you flip to Appendix B and read the entire “Raspberry Pi” section if you haven’t already.

In this project, you’ll look at processes running on a Raspberry Pi. The ps tool provides various views of running processes. Let’s begin with the following command, which provides a tree view of processes.

$ ps -eH

The output should look something like the following text. I’ve only reproduced a portion of it here.

    1 ?        00:00:10 systemd
   93 ?        00:00:09   systemd-journal
  133 ?        00:00:01   systemd-udevd
  233 ?        00:00:01   systemd-timesyn
  274 ?        00:00:02   thd
  275 ?        00:00:01   cron
  276 ?        00:00:00   dbus-daemon
  286 ?        00:00:03   rsyslogd
  287 ?        00:00:01   systemd-logind
  291 ?        00:00:08   avahi-daemon
  296 ?        00:00:00     avahi-daemon
  297 ?        00:00:01   dhcpcd
  351 tty1     00:00:00   agetty
  352 ?        00:00:00   agetty
  358 ?        00:00:00   sshd
 5016 ?        00:00:00     sshd
 5033 ?        00:00:00       sshd
 5036 pts/0    00:00:00         bash
 5178 pts/0    00:00:00           ps

The indentation level indicates a parent/child relationship. For example, in the preceding output, we see that systemd is the parent of systemd-journal , systemd-udevd , and so forth. Or inversely, we can see that ps (the command currently running) is the child of bash , which is the child of sshd , and so forth.

The displayed columns are as follows:

PID    The process ID

TTY    The associated terminal

TIME    The cumulative CPU time

CMD    The executable name

The number of processes running may surprise you when you run ps in this way! The operating system handles many things, and as a result, it’s normal for a large number of processes to run at any given time. Typically you see that the first process listed is PID 2, kthreadd . This is the parent of kernel threads, and the children you see listed under kthreadd are threads running in kernel mode. The other process to note is PID 1, the init process, the first user mode process that starts. In the preceding output, the init process is systemd . The Linux kernel starts both the init process and kthreadd , in that order, which ensures they are assigned PIDs 1 and 2, respectively.

Let’s take a look at the init process. This is the first user mode process to start, and the specific executable that runs can vary on different versions of Linux. You can use ps to find the command used to start PID 1:

$ ps 1

You should see output like the following:

  PID TTY      STAT   TIME COMMAND
    1 ?        Ss     0:03 /sbin/init

This tells you that the command used to kick off the init process was /sbin/init . So how does running /sbin/init result in systemd executing, as you saw in the earlier ps output? This happens because /sbin/init is actually a symbolic link to systemd . A symbolic link references another file or directory. You can see this with the following command:

$ stat /sbin/init
 
  File: /sbin/init -> /lib/systemd/systemd
  Size: 20              Blocks: 0          IO Block: 4096   symbolic link

In this output, you can see that /sbin/init is a symbolic link to /lib/systemd/systemd .

Another convenient view of the process tree can be generated by using the pstree tool, as mentioned earlier in this chapter. Running pstree presents a nicely formatted user mode process tree, starting with the init process. Give it a try:

$ pstree

Alternatively, if your Raspberry Pi is configured to boot to the desktop environment, you may also want to try the Task Manager application that’s included with Raspberry Pi OS. It provides a graphical view of running processes, as shown in Figure 10-15 .

image

Figure 10-15: Task Manager in Raspberry Pi OS

PROJECT #21: CREATE A THREAD AND OBSERVE IT

Prerequisite: A Raspberry Pi, running Raspberry Pi OS. See “Raspberry Pi” on page 341 .

In this project, you’ll write a program that creates a thread. You’ll then observe the thread running. Use the text editor of your choice to create a new file called threader.c in the root of your home folder. Enter the following C code into your text editor (you don’t have to preserve indentation and empty lines, but be sure to maintain line breaks).

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
 
void * mythread(void* arg) ❶
{
  while(1) ❷
  {
    printf("mythread PID: %d\n", (int)getpid()); ❸
    printf("mythread TID: %d\n", (int)syscall(SYS_gettid));
    sleep(5); ❹
  }
}
 
int main() ❺
{
  pthread_t thread;
 
  pthread_create(&thread, NULL, &mythread, NULL); ❻
 
  while(1) ❼
  {
    printf("main     PID: %d\n", (int)getpid()); ❽
    printf("main     TID: %d\n", (int)syscall(SYS_gettid));
    sleep(10); ❾
  }
 
  return 0;
}

Before continuing, let’s examine the source code. I won’t go into all the details here, but in summary, the program starts in the main function ❺ , which creates a thread ❻ that runs the function mythread ❶ . This means there are two threads, the main thread and mythread . Both threads run in an infinite loop ❷❼ , where every so often they print the PID and TID of the current thread ❸❽ . For variety, mythread prints about every 5 seconds ❹ , while main prints approximately every 10 seconds ❾ . This helps illustrate that the threads are in fact running in parallel and doing work on their own schedule. Let’s try it out.

Once the file is saved, use the GNU C Compiler ( gcc ) to compile your code into an executable file. The following command takes threader.c as an input and outputs an executable file named threader .

$ gcc -pthread -o threader threader.c

Now try running the code using the following command:

$ ./threader

The running program should output something like this, although the PID and TID numbers will be different:

main     PID: 2300
main     TID: 2300
mythread PID: 2300
mythread TID: 2301

As the program runs, expect the two threads to continue printing their PID and TID information. The TID and PID numbers won’t change for this instance of the program, since it’s the same process and threads running the entire time. You should see mythread print twice as often as main —every 5 seconds versus every 10 seconds.

Leave that program running and look at your list of running processes and threads. To do this, you need to open a second terminal window and run the following command (the | symbol can be entered with SHIFT- backslash right above ENTER , on US keyboards).

$ ps -e -T | grep threader
 2300  2300 pts/0    00:00:00 threader
 2300  2301 pts/0    00:00:00 threader

Adding the T option to the ps command shows threads as well as processes. The grep utility filters your output to only see the threader process information. In this output, the first column is the PID and the second column is the TID. So you can see that the output from ps matches the output from your program. The two threads share a PID but have different TIDs. Also, note that the main thread’s TID matches its PID. This is expected for the first thread in a process.

To halt execution of the threader program, you can press CTRL-C in the terminal window where it’s running. Or, from the second terminal window, you can use the kill utility, specifying the PID of the main thread, like so:

$ kill 2300

PROJECT #22: EXAMINE VIRTUAL MEMORY

Prerequisite: A Raspberry Pi, running Raspberry Pi OS. See “Raspberry Pi” on page 341 .

In this project, you’ll examine virtual memory usage on Raspberry Pi OS. Let’s begin with a look at how address space is divided between kernel mode and user mode. This project assumes you are running the 32-bit version of Raspberry Pi OS, meaning there is 4GB of virtual address space. Linux allows for a split of that 4GB as either 2GB user and 2GB kernel, or 3GB user and 1GB kernel. Lower addresses are used for user mode, and higher addresses are used for kernel mode. That means that in a 2:2 split, kernel mode addresses start at 0x80000000, and in a 3:1 split, kernel mode addresses start at 0xC0000000. You can see the start of kernel mode address space with this command:

$ dmesg | grep lowmem

If the dmesg command does not produce any output, simply restart your Raspberry Pi and then run the dmesg command again. The command should produce output similar to the following.

                   lowmem  : 0x80000000 - 0xbb400000   ( 948 MB)

If you’re wondering why you need to restart the Raspberry Pi if this command comes up empty, here’s some background information. The Linux kernel logs diagnostic messages to something called the kernel ring buffer, which the dmesg tool displays. The messages in the buffer are intended to give users some insight into the workings of the kernel. Only a limited number of messages are stored here; as newer messages are added, older messages are removed. The particular message we want to see (regarding lowmem ) is written when the system starts, so if your system has been running for a while, it may have been overwritten. Restarting the system ensures that the message is written again.

As you can see, on my system, kernel lowmem starts at 0x80000000 , indicating a 2:2 split. This means that user mode processes can use addresses 0x00000000 to 0x7fffffff . That range of addresses can reference 2GB of memory, and although the entire address space is available to every process, a typical process only actually needs to use a portion of that range. Certain addresses are mapped to physical memory, but others are left unmapped.

If your system returns a value of 0xc0000000 for the beginning of lowmem , then your system is running with a 3:1 split. This gives user mode processes 3GB of virtual address space, from 0x00000000 to 0xbfffffff .

Let’s pick a process and examine its virtual memory usage. Raspberry Pi OS uses Bash as its default shell process, so if you’re working from a command line in Raspberry Pi OS, at least one instance of bash should be running. Let’s find the PID of a bash instance:

$ ps | grep bash

This should output text similar to the following:

 2670 pts/0    00:00:00 bash

In my case, the PID of bash was 2670 . Now, run the following command to see the virtual memory mapping in the bash process. When you enter the command, be sure to replace <pid> with the PID returned on your system.

$ pmap <pid>

The output will be similar to the following, where each line represents a region of virtual memory in the process address space.

2670:   -bash
00010000    872K r-x-- bash
000f9000      4K r---- bash
000fa000     20K rw--- bash
000ff000     36K rw---   [ anon ]
00ee7000   1044K rw---   [ anon ]
76b30000     36K r-x-- libnss_files-2.24.so
76b39000     60K ----- libnss_files-2.24.so
76b48000      4K r---- libnss_files-2.24.so
76b49000      4K rw--- libnss_files-2.24.so
...
7ec2c000    132K rw---   [ stack ]
7ec74000      4K r-x--   [ anon ]
7ec75000      4K r----   [ anon ]
7ec76000      4K r-x--   [ anon ]
ffff0000      4K r-x--   [ anon ]
total     6052K

The first column is the region start address, the second column is the size of the region, the third column represents the permissions of the region ( r = read, w = write, x = execute, p = private, s = shared), and the final column is the region name. The region name is either a filename or a name that identifies the memory region if it isn’t mapped from a file.

You can see that almost every region in the output is within the expected user mode range of 0x00000000 to 0x7fffffff . The one exception is the last entry, which corresponds to the ARM CPU vector page, and represents a special case, as it’s outside the standard user mode address range. As you can see in the preceding output, this particular instance of bash only has a total of 6052K (about 6MB) of virtual memory mapped out of a possible 2GB, or around 0.3 percent.

PROJECT #23: TRY THE OPERATING SYSTEM API

Prerequisite: A Raspberry Pi, running the Raspberry Pi OS.

In this project, you’ll try invoking the operating system API in various ways. You’ll specifically focus on creating a file and writing some text to it. Use the text editor of your choice to create a file called newfile.c in the root of your home folder. Enter the following C code into your text editor.

#include <fcntl.h>
#include <unistd.h>
 
#define msg "Hello, file!\n" ❶
 
int main() ❷
{
  int fd; ❸
  fd = open("file1.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644); ❹
  write(fd, msg, sizeof(msg) - 1); ❺
  close(fd); ❻
  return 0; ❼
}

Before we continue, let’s examine the source code to understand exactly what it does. In short, the program uses three API functions, open , write , and close , to create a new file, write some text to it, and finally close the file. Our focus here is to see how the operating system’s API allows a program to interact with the computer’s hardware, specifically a storage device. Let’s go through the program in more detail.

After the requisite include statements, the next line defines msg as a text string ❶ that later will be written to the newly created file. The code then defines main , the entry point of the program  ❷ . Within main , an integer named fd is declared ❸ . Next, the OS API open function is called to create a new file named file1.txt ❹ . The other arguments passed to the open function specify the details of how the file should be opened. For simplicity, I won’t cover those details here, but feel free to research the meanings of these arguments. The open function returns a file descriptor, which is saved in the fd variable.

The write function is then used to write the msg text to file1.txt (identified by the file descriptor stored in fd ) ❺ . The write function requires inputs of both the data to write ( msg ) and the number of bytes to write, determined by sizeof(msg) - 1 . You subtract 1 because the C language terminates strings with a null character, and you don’t need to write that byte to the output file. The program is now finished working with the file and calls the close function on the file descriptor to indicate that the file is no longer in use ❻ . Finally, the program exits with a return code of 0 ❼ , indicating success.

Once the file is saved, use the GNU C Compiler ( gcc ) to compile the code into an executable file. The command below takes newfile.c as an input and generates an executable file named newfile .

$ gcc -o newfile newfile.c

Now try running the code using the following command. You won’t see any output, since the text is written to a file rather than the terminal.

$ ./newfile

To determine if the program ran successfully, you need to see if a file was created. The file should be named file1.txt and exist in your current directory. You can use the ls command to list the contents of the current directory and look for the file. Assuming file1.txt is present, you can see its contents using the cat command.

$ ls
$ cat file1.txt

This command should print Hello, file! to the terminal, since that’s the text the program wrote to the file. Or you can view the file’s properties in the File Manager application of the Raspberry Pi OS desktop, and you can open file1.txt in your text editor of choice.

When you use the C programming language you get a look at specifics of the OS API functions, since open , write , and close are defined as C functions. However, you aren’t limited to C when interacting with the OS. Other languages provide their own layer on top of the API, hiding some of the complexity from software developers. To illustrate this, let’s write an equivalent program in Python.

Use the text editor of your choice to create a file called newfile.py in the root of your home folder. Enter the following Python code into your text editor.

f = open('file2.txt', 'w') ❶
f.write('Hello from Python!\n'); ❷
f.close()

Before continuing, let’s examine the source code. This program effectively does the same thing as the previous program, except the output filename is different ( file2.txt ) ❶ , and the text written to that file is also different ❷ . In this case, Python happens to use the same names as the OS API ( open , write , close ), but these are not direct calls to the operating system; rather, they are calls into the Python standard library.

Once you’ve saved this code, you can run it. Remember that Python is an interpreted language, so rather than compiling your Python code, just run it using the Python interpreter, like so:

$ python3 newfile.py

To determine if the program ran successfully, you need to see if file2.txt was created with the expected contents. You can again use ls and cat to verify this, or you can look in the desktop File Manager to see the file.

$ ls
$ cat file2.txt

Although it may seem as if you’re just leveraging Python’s capabilities to manipulate a file, keep in mind that Python cannot do this on its own. The Python interpreter is making system API calls on your behalf when it runs your code. You’ll get to observe this in the next project.

PROJECT #24: OBSERVE SYSTEM CALLS

Prerequisite: Complete Project #23 .

In this project, you’ll observe the system calls made by the programs you wrote in Project #23 . To do this you’ll use a tool called strace , which traces system calls and prints the output to the terminal.

Open a terminal on your Raspberry Pi and use strace to run the newfile program you previously wrote in C and compiled:

$ strace ./newfile

The strace tool launches a program ( newfile in this case) and shows all the system calls that are made while that program runs. At the beginning of the output, you can see a number of system calls that represent the work required to load the executable file and required libraries. This is work that happens before the code you wrote runs; you can skip past that text. Near the end of the output, you should see text similar to the following:

openat(AT_FDCWD, "file1.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644) = 3
write(3, "Hello, file!\n", 13)        = 13
close(3)                              = 0

This should look familiar; it’s almost the same three API functions that you used to create file1.txt and write text to it. The C functions that you called from your program are just thin wrappers around the system calls of the same name, with the exception of open , which invokes the openat system call. The values after the equals signs are the return values from the three system calls. On my system, the openat function returned 3 , which is a number known as a file descriptor that refers to the opened file. You can see the file descriptor value used as a parameter to the subsequent calls to write and close . The write function returned 13 , the number of bytes written. The close function returned 0 , an indicator of success.

Now use the same approach to also check out the system calls made from the Python program you wrote in Project #23 .

$ strace python3 newfile.py

Expect to see even more output here, since strace is actually monitoring the Python interpreter, which in turn has to load newfile.py and run it. If you look near the end of the output, you should see calls to openat , write , and close , just as you did in the C program. This shows that despite the source code differences between C and Python, in the end, the same system calls are invoked to interact with files.

The strace tool can be used to quickly get an idea of how a program interacts with the operating system. For example, earlier in this chapter, we used the ps utility to get a list of processes. If you want to understand how ps works, you can run ps under strace , like so:

$ strace ps

Look at the output from this command to see what system calls ps makes.

PROJECT #25: USE GLIBC

Prerequisite: A Raspberry Pi, running Raspberry Pi OS.

In this project, you’ll write code to use the C library and examine the details of how this works. Use the text editor of your choice to create a new file called random.c in the root of your home folder. Enter the following C code into your text editor.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main()
{
  srand(time(0)); ❶
  printf("%d\n", rand()); ❷
  return 0;
}

This little program simply prints a random integer value to the terminal. The first thing the program does is call the srand function to seed the random number generator ❶ , a necessary step to ensure a unique sequence of numbers is generated. The current time, as returned from the time function, is used as the seed value. The next line prints out a random value returned from the rand function ❷ . To accomplish all of this, the program uses four functions from the C library ( time , srand , rand , and printf ).

Once the file is saved, you can use the GNU C Compiler ( gcc ) to compile the code into an executable file. The following command takes random.c as an input and outputs an executable file named random .

$ gcc -o random random.c

Now try running the code using the following command. The program should output a random number. Run it multiple times to confirm that it outputs different numbers. However, quickly running it twice may produce the same result, since the seed value returned from the time function only increments every second.

$ ./random

Once you’ve ensured that the program works, look at the libraries that the program imports. One way to do this is to run the readelf utility, like so:

$ readelf -d random | grep NEEDED

Look for the NEEDED sections in the output, like the following:

0x00000001 (NEEDED)                     Shared library: [libc.so.6]

This tells you that the libc.so.6 library is required for this program to run. This is expected, as this is the GNU C Library (also known as glibc ). In other words, because the program relies on functions in the C standard library, the operating system must load the libc.so.6 library file so that the library code is available. This is a good start, but what if you want to see the specific list of functions that the random program uses from this library? You can observe this with the following:

$ objdump -TC random

This gives you output like the following:

random:     file format elf32-littlearm
 
DYNAMIC SYMBOL TABLE:
00000000  w   D  *UND*  00000000              __gmon_start__
00000000      DF *UND*  00000000  GLIBC_2.4   srand
00000000      DF *UND*  00000000  GLIBC_2.4   rand
00000000      DF *UND*  00000000  GLIBC_2.4   printf
00000000      DF *UND*  00000000  GLIBC_2.4   time
00000000      DF *UND*  00000000  GLIBC_2.4   abort
00000000      DF *UND*  00000000  GLIBC_2.4   __libc_start_main

In the preceding output, in the rightmost column, you can see the expected four functions ( srand , rand , printf , and time ) along with some additional functions.

Now that you’ve established which glibc functions were imported by your random program, you may wish to see the list of all functions that are exported by glibc . These are the functions this library makes available for programs to use. You can get this information with the following command:

$ objdump -TC /lib/arm-linux-gnueabihf/libc.so.6

Sometimes it’s useful to see information about loaded libraries while you’re debugging a running process. Let’s try that by debugging the random program. To start, enter the following command:

$ gdb random

At this point gdb has loaded the file but no instructions have run yet. From the (gdb) prompt, enter the following to start running the program. The debugger halts execution once it reaches the beginning of the main function.

(gdb) start

Look at the loaded shared libraries:

(gdb) info sharedlibrary
From        To          Syms Read   Shared Object Library
0x76fcea30  0x76fea150  Yes         /lib/ld-linux-armhf.so.3 ❶
0x76fb93ac  0x76fbc300  Yes (*)     /usr/lib/arm-linux-gnueabihf/libarmmem-v71.so ❷
0x76e6e050  0x76f702b4  Yes         /lib/arm-linux-gnueabihf/libc.so.6 ❸
(*): Shared library is missing debugging information.

The first library, ld-linux-armhf.so.3 ❶ , is the Linux dynamic linker library. It’s responsible for loading other libraries. Linux ELF binaries are compiled to use a specific linker library; this information is in the ELF header of the compiled program. You can find the linker library for the random program using the following command from a terminal window (not in gdb ):

$ readelf -l random | grep interpreter
      [Requesting program interpreter: /lib/ld-linux-armhf.so.3]

As you can see in the preceding output, the linker library specified for the random program is ld-linux-armhf.so.3 , the same dynamic linker library we just discussed.

Take a look back at the info sharedlibrary output in gdb ; you can see that the second library listed is libarmmem-v71.so ❷ . This library is specified in the file /etc/ld.so.preload , a text file that lists libraries that load for every program that’s executed on the system.

Now move on to the third library, which is the one of interest, libc.so.6 ❸ , the GNU C Library ( glibc ). In the readelf and objdump output earlier you saw that this library was imported by the executable file, and here you can see that it did indeed successfully load while running. You can also see the specific address range where it loaded ( 0x76e6e050 to 0x76f702b4 ), and the specific directory path from which it loaded.

You can exit the debugger at any time by typing quit in gdb .

PROJECT #26: VIEW LOADED KERNEL MODULES

Prerequisite: A Raspberry Pi, running Raspberry Pi OS.

In this project, you’ll take a look at the loaded kernel modules, including device drivers, on Raspberry Pi OS. Device drivers are typically implemented as kernel modules on Linux, although not all kernel modules are device drivers. To list the loaded modules, you can either examine the contents of the /proc/modules file or use the lsmod tool like so:

$ lsmod

To view more details about a specific module, use the modinfo utility like so (using the snd module as an example):

$ modinfo snd

PROJECT #27: EXAMINE STORAGE DEVICES AND FILESYSTEMS

Prerequisite: A Raspberry Pi, running Raspberry Pi OS.

In this project, you’ll take a look at storage devices and filesystems. Let’s begin by listing the block devices, which is how Linux characterizes storage devices.

$ lsblk
NAME        MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
mmcblk0     179:0    0 29.8G  0 disk ❶
|−mmcblk0p1 179:1    0  256M  0 part /boot ❷
|_mmcblk0p2 179:2    0 29.6G  0 part / ❸

Here we see a single “disk” named mmcblk0 ❶ , which is the microSD card in the Raspberry Pi. You can see that it’s divided into two partitions of varying sizes. Partition 1 is mapped to the /boot directory in the unified directory structure ❷ , while partition 2 is mapped to the root ( / ) ❸ .

Now take a look at the overall usage of the storage device using the df command:

$ df -h -T
Filesystem     Type      Size  Used Avail Use% Mounted on
/dev/root      ext4       30G  3.0G   25G  11% / ❶
devtmpfs       devtmpfs  459M     0  459M   0% /dev
tmpfs          tmpfs     464M     0  464M   0% /dev/shm
tmpfs          tmpfs     464M  6.3M  457M   2% /run
tmpfs          tmpfs     5.0M  4.0K  5.0M   1% /run/lock
tmpfs          tmpfs     464M     0  464M   0% /sys/fs/cgroup
/dev/mmcblk0p1 vfat      253M   52M  202M  21% /boot ❷
tmpfs          tmpfs      93M     0   93M   0% /run/user/1000

This command lets you view the various mounted filesystems, their size, and how full they are. Only the root ❶ and /boot ❷ directories are mapped to storage devices. The others are temporary filesystems that reside in memory, not a persistent storage device.

You can get a view of the directories on your system by running the tree command. The parameters used here limit your output to directories only, and only go three levels deep in the hierarchy.

$ tree -d -L 3 /

You can also see a similar view from the desktop environment using the File Manager application.

PROJECT #28: VIEW SERVICES

Prerequisite: A Raspberry Pi, running Raspberry Pi OS.

In this project, you’ll look at services/daemons. Raspberry Pi OS uses the systemd init system, and it includes a utility called systemctl that you can use to see the state of services:

$ systemctl list-units --type=service --state=running

This should produce output similar to the following:

UNIT                      LOAD   ACTIVE SUB     DESCRIPTION
avahi-daemon.service      loaded active running Avahi mDNS/DNS-SD Stack
bluealsa.service          loaded active running BluezALSA proxy
bluetooth.service         loaded active running Bluetooth service
cron.service              loaded active running Regular background ...
dbus.service              loaded active running D-Bus System Message Bus
dhcpcd.service            loaded active running dhcpcd on all interfaces
[email protected]        loaded active running Getty on tty1
hciuart.service           loaded active running Configure Bluetooth Modems ...
rsyslog.service           loaded active running System Logging Service
ssh.service               loaded active running OpenBSD Secure Shell server
systemd-journald.service  loaded active running Journal Service
systemd-logind.service    loaded active running Login Service
systemd-timesyncd.service loaded active running Network Time Synchronization
systemd-udevd.service     loaded active running udev Kernel Device Manager
triggerhappy.service      loaded active running triggerhappy global hotkey daemon
[email protected]         loaded active running User Manager for UID 1000

If you aren’t automatically returned to a terminal prompt, hit Q in your terminal to exit the view of services. To see the details of a particular service, try this command, using cron.service as an example:

$ systemctl status cron.service

The output of this command includes the path and PID of the process that’s associated with the service. In the case of cron.service , the path on my system is /usr/sbin/cron , and it happened to be PID 367.

Another approach to viewing daemon processes is to view all the processes that are children of systemd , that is, PID 1. This is relevant since services are started by systemd and appear as child processes of PID 1. Note that this output may include more than just services/daemons, since orphaned processes are adopted by PID 1.

$ ps --ppid 1