text
stringlengths
1
7.76k
source
stringlengths
17
81
784 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 10.6.3 Implementation of the Linux File System In this section we will first look at the abstractions supported by the Virtual File System layer. The VFS hides from higher-level processes and applications the differences among many types of file systems supported by Linux, whether they are residing on local devices or are stored remotely and need to be accessed over the network. Devices and other special files are also accessed through the VFS layer. Next, we will describe the implementation of the first widespread Linux file system, ext2, or the second extended file system. Afterward, we will discuss the improvements in the ext4 file system. A wide variety of other file systems are also in use. All Linux systems can handle multiple disk partitions, each with a different file system on it. The Linux Virtual File System In order to enable applications to interact with different file systems, imple- mented on different types of local or remote devices, Linux takes an approach used in other UNIX systems: the Virtual File System (VFS). VFS defines a set of basic file-system abstractions and the operations which are allowed on these abstrac- tions. Invocations of the system calls described in the previous section access the VFS data structures, determine the exact file system where the accessed file be- longs, and via function pointers stored in the VFS data structures invoke the corres- ponding operation in the specified file system. Figure 10-30 summarizes the four main file-system structures supported by VFS. The superblock contains critical information about the layout of the file sys- tem. Destruction of the superblock will render the file system unreadable. The i- nodes (short for index-nodes, but never called that, although some lazy people drop the hyphen and call them inodes) each describe exactly one file. Note that in Linux, directories and devices are also represented as files, thus they will have cor- responding i-nodes. Both superblocks and i-nodes have a corresponding structure maintained on the physical disk where the file system resides. Object Description Operation Superblock specific file-system read inode, sync fs Dentr y director y entr y, single component of a path create, link I-node specific file d compare, d delete File open file associated with a process read, write Figure 10-30. File-system abstractions supported by the VFS. In order to facilitate certain directory operations and traversals of paths, such as /usr/ast/bin, VFS supports a dentry data structure which represents a directory entry. This data structure is created by the file system on the fly. Directory entries
clipped_os_Page_784_Chunk7001
SEC. 10.6 THE LINUX FILE SYSTEM 785 are cached in what is called the dentry cache. For instance, the dentry cache would contain entries for /, /usr, /usr/ast, and the like. If multiple processes access the same file through the same hard link (i.e., same path), their file object will point to the same entry in this cache. Finally, the file data structure is an in-memory representation of an open file, and is created in response to the open system call. It supports operations such as read, wr ite, sendfile, lock, and other system calls described in the previous section. The actual file systems implemented underneath the VFS need not use the exact same abstractions and operations internally. They must, however, implement file-system operations semantically equivalent to those specified with the VFS ob- jects. The elements of the operations data structures for each of the four VFS ob- jects are pointers to functions in the underlying file system. The Linux Ext2 File System We next describe one of the most popular on-disk file systems used in Linux: ext2. The first Linux release used the MINIX 1 file system and was limited by short file names and 64-MB file sizes. The MINIX 1 file system was eventually re- placed by the first extended file system, ext, which permitted both longer file names and larger file sizes. Due to its performance inefficiencies, ext was replaced by its successor, ext2, which is still in widespread use. An ext2 Linux disk partition contains a file system with the layout shown in Fig. 10-31. Block 0 is not used by Linux and contains code to boot the computer. Following block 0, the disk partition is divided into groups of blocks, irrespective of where the disk cylinder boundaries fall. Each group is organized as follows. The first block is the superblock. It contains information about the layout of the file system, including the number of i-nodes, the number of disk blocks, and the start of the list of free disk blocks (typically a few hundred entries). Next comes the group descriptor, which contains information about the location of the bitmaps, the number of free blocks and i-nodes in the group, and the number of di- rectories in the group. This information is important since ext2 attempts to spread directories evenly over the disk. Boot Block group 0 Super– Group block descriptor Block group 1 Block bitmap Data blocks I–node bitmap I–nodes Block group 2 Block group 3 Block group 4 ... Figure 10-31. Disk layout of the Linux ext2 file system.
clipped_os_Page_785_Chunk7002
786 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 Tw o bitmaps are used to keep track of the free blocks and free i-nodes, respect- iv ely, a choice inherited from the MINIX 1 file system (and in contrast to most UNIX file systems, which use a free list). Each map is one block long. With a 1-KB block, this design limits a block group to 8192 blocks and 8192 i-nodes. The former is a real restriction but, in practice, the latter is not. With 4-KB blocks, the numbers are four times larger. Following the superblock are the i-nodes themselves. They are numbered from 1 up to some maximum. Each i-node is 128 bytes long and describes exactly one file. An i-node contains accounting information (including all the information re- turned by stat, which simply takes it from the i-node), as well as enough informa- tion to locate all the disk blocks that hold the file’s data. Following the i-nodes are the data blocks. All the files and directories are stor- ed here. If a file or directory consists of more than one block, the blocks need not be contiguous on the disk. In fact, the blocks of a large file are likely to be spread all over the disk. I-nodes corresponding to directories are dispersed throughout the disk block groups. Ext2 makes an effort to collocate ordinary files in the same block group as the parent directory, and data files in the same block as the original file i-node, pro- vided that there is sufficient space. This idea was borrowed from the Berkeley Fast File System (McKusick et al., 1984). The bitmaps are used to make quick decis- ions regarding where to allocate new file-system data. When new file blocks are al- located, ext2 also preallocates a number (eight) of additional blocks for that file, so as to minimize the file fragmentation due to future write operations. This scheme balances the file-system load across the entire disk. It also performs well due to its tendencies for collocation and reduced fragmentation. To access a file, it must first use one of the Linux system calls, such as open, which requires the file’s path name. The path name is parsed to extract individual directories. If a relative path is specified, the lookup starts from the process’ cur- rent directory, otherwise it starts from the root directory. In either case, the i-node for the first directory can easily be located: there is a pointer to it in the process de- scriptor, or, in the case of a root directory, it is typically stored in a predetermined block on disk. The directory file allows file names up to 255 characters and is illustrated in Fig. 10-32. Each directory consists of some integral number of disk blocks so that directories can be written atomically to the disk. Within a directory, entries for files and directories are in unsorted order, with each entry directly following the one be- fore it. Entries may not span disk blocks, so often there are some number of unused bytes at the end of each disk block. Each directory entry in Fig. 10-32 consists of four fixed-length fields and one variable-length field. The first field is the i-node number, 19 for the file colossal, 42 for the file voluminous, and 88 for the directory bigdir. Next comes a field rec len, telling how big the entry is (in bytes), possibly including some padding after the name. This field is needed to find the next entry for the case that the file
clipped_os_Page_786_Chunk7003
SEC. 10.6 THE LINUX FILE SYSTEM 787 19 (a) 42 F 8 F 10 88 D 6 bigdir colossal voluminous Unused 19 (b) F 8 88 D 6 bigdir colossal Unused Unused I-node number Entry size Type File name length Figure 10-32. (a) A Linux directory with three files. (b) The same directory af- ter the file voluminous has been removed. name is padded by an unknown length. That is the meaning of the arrow in Fig. 10-32. Then comes the type field: file, directory, and so on. The last fixed field is the length of the actual file name in bytes, 8, 10, and 6 in this example. Finally, comes the file name itself, terminated by a 0 byte and padded out to a 32-bit boundary. Additional padding may follow that. In Fig. 10-32(b) we see the same directory after the entry for voluminous has been removed. All the removeal has done is increase the size of the total entry field for colossal, turning the former field for voluminous into padding for the first entry. This padding can be used for a subsequent entry, of course. Since directories are searched linearly, it can take a long time to find an entry at the end of a large directory. Therefore, the system maintains a cache of recently accessed directories. This cache is searched using the name of the file, and if a hit occurs, the costly linear search is avoided. A dentry object is entered in the dentry cache for each of the path components, and, through its i-node, the directory is searched for the subsequent path element entry, until the actual file i-node is reached. For instance, to look up a file specified with an absolute path name, such as /usr/ast/file, the following steps are required. First, the system locates the root di- rectory, which generally uses i-node 2, especially when i-node 1 is reserved for bad-block handling. It places an entry in the dentry cache for future lookups of the root directory. Then it looks up the string ‘‘usr’’ in the root directory, to get the i- node number of the /usr directory, which is also entered in the dentry cache. This i- node is then fetched, and the disk blocks are extracted from it, so the /usr directory can be read and searched for the string ‘‘ast’’. Once this entry is found, the i-node
clipped_os_Page_787_Chunk7004
788 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 number for the /usr/ast directory can be taken from it. Armed with the i-node num- ber of the /usr/ast directory, this i-node can be read and the directory blocks locat- ed. Finally, ‘‘file’’ is looked up and its i-node number found. Thus, the use of a rel- ative path name is not only more convenient for the user, but it also saves a sub- stantial amount of work for the system. If the file is present, the system extracts the i-node number and uses it as an index into the i-node table (on disk) to locate the corresponding i-node and bring it into memory. The i-node is put in the i-node table, a kernel data structure that holds all the i-nodes for currently open files and directories. The format of the i- node entries, as a bare minimum, must contain all the fields returned by the stat system call so as to make stat work (see Fig. 10-28). In Fig. 10-33 we show some of the fields included in the i-node structure supported by the Linux file-system layer. The actual i-node structure contains many more fields, since the same struc- ture is also used to represent directories, devices, and other special files. The i- node structure also contains fields reserved for future use. History has shown that unused bits do not remain that way for long. Field Bytes Description Mode 2 File type, protection bits, setuid, setgid bits Nlinks 2 Number of directory entr ies pointing to this i-node Uid 2 UID of the file owner Gid 2 GID of the file owner Size 4 File size in bytes Addr 60 Address of first 12 disk blocks, then 3 indirect blocks Gen 1 Generation number (incremented every time i-node is reused) Atime 4 Time the file was last accessed Mtime 4 Time the file was last modified Ctime 4 Time the i-node was last changed (except the other times) Figure 10-33. Some fields in the i-node structure in Linux. Let us now see how the system reads a file. Remember that a typical call to the library procedure for invoking the read system call looks like this: n = read(fd, buffer, nbytes); When the kernel gets control, all it has to start with are these three parameters and the information in its internal tables relating to the user. One of the items in the in- ternal tables is the file-descriptor array. It is indexed by a file descriptor and con- tains one entry for each open file (up to the maximum number, usually defaults to 32). The idea is to start with this file descriptor and end up with the corresponding i-node. Let us consider one possible design: just put a pointer to the i-node in the file-descriptor table. Although simple, unfortunately this method does not work.
clipped_os_Page_788_Chunk7005
SEC. 10.6 THE LINUX FILE SYSTEM 789 The problem is as follows. Associated with every file descriptor is a file position that tells at which byte the next read (or write) will start. Where should it go? One possibility is to put it in the i-node table. However, this approach fails if two or more unrelated processes happen to open the same file at the same time because each one has its own file position. A second possibility is to put the file position in the file-descriptor table. In that way, every process that opens a file gets its own private file position. Unfortun- ately this scheme fails too, but the reasoning is more subtle and has to do with the nature of file sharing in Linux. Consider a shell script, s, consisting of two com- mands, p1 and p2, to be run in order. If the shell script is called by the command s >x it is expected that p1 will write its output to x, and then p2 will write its output to x also, starting at the place where p1 stopped. When the shell forks off p1, x is initially empty, so p1 just starts writing at file position 0. However, when p1 finishes, some mechanism is needed to make sure that the initial file position that p2 sees is not 0 (which it would be if the file posi- tion were kept in the file-descriptor table), but the value p1 ended with. The way this is achieved is shown in Fig. 10-34. The trick is to introduce a new table, the open-file-description table, between the file descriptor table and the i-node table, and put the file position (and read/write bit) there. In this figure, the parent is the shell and the child is first p1 and later p2. When the shell forks off p1, its user structure (including the file-descriptor table) is an exact copy of the shell’s, so both of them point to the same open-file-description table entry. When p1 finishes, the shell’s file descriptor is still pointing to the open-file description containing p1’s file position. When the shell now forks off p2, the new child auto- matically inherits the file position, without either it or the shell even having to know what that position is. However, if an unrelated process opens the file, it gets its own open-file-de- scription entry, with its own file position, which is precisely what is needed. Thus the whole point of the open-file-description table is to allow a parent and child to share a file position, but to provide unrelated processes with their own values. Getting back to the problem of doing the read, we hav e now shown how the file position and i-node are located. The i-node contains the disk addresses of the first 12 blocks of the file. If the file position falls in the first 12 blocks, the block is read and the data are copied to the user. For files longer than 12 blocks, a field in the i-node contains the disk address of a single indirect block, as shown in Fig. 10-34. This block contains the disk addresses of more disk blocks. For ex- ample, if a block is 1 KB and a disk address is 4 bytes, the single indirect block can hold 256 disk addresses. Thus this scheme works for files of up to 268 KB. Beyond that, a double indirect block is used. It contains the addresses of 256 single indirect blocks, each of which holds the addresses of 256 data blocks. This mechanism is sufficient to handle files up to 10 + 216 blocks (67,119,104 bytes). If
clipped_os_Page_789_Chunk7006
790 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 Mode i-node Link count Uid Gid File size Times Addresses of first 12 disk blocks Single indirect Double indirect Triple indirect Parent's file- descriptor table Child's file- descriptor table Unrelated process file- descriptor table Open file description File position R/W Pointer to i-node File position R/W Pointer to i-node Pointers to disk blocks Triple indirect block Double indirect block Single indirect block ` Figure 10-34. The relation between the file-descriptor table, the open-file-de- scription-table, and the i-node table. ev en this is not enough, the i-node has space for a triple indirect block. Its point- ers point to many double indirect blocks. This addressing scheme can handle file sizes of 224 1-KB blocks (16 GB). For 8-KB block sizes, the addressing scheme can support file sizes up to 64 TB. The Linux Ext4 File System In order to prevent all data loss after system crashes and power failures, the ext2 file system would have to write out each data block to disk as soon as it was created. The latency incurred during the required disk-head seek operation would be so high that the performance would be intolerable. Therefore, writes are delay- ed, and changes may not be committed to disk for up to 30 sec, which is a very long time interval in the context of modern computer hardware. To improve the robustness of the file system, Linux relies on journaling file systems. Ext3, a successor of the ext2 file system, is an example of a journaling file system. Ext4, a follow-on of ext3, is also a journaling file system, but unlike
clipped_os_Page_790_Chunk7007
SEC. 10.6 THE LINUX FILE SYSTEM 791 ext3, it changes the block addressing scheme used by its predecessors, thereby sup- porting both larger files and larger overall file-system sizes. We will describe some of its features next. The basic idea behind a journaling file system is to maintain a journal, which describes all file-system operations in sequential order. By sequentially writing out changes to the file-system data or metadata (i-nodes, superblock, etc.), the opera- tions do not suffer from the overheads of disk-head movement during random disk accesses. Eventually, the changes will be written out, committed, to the appropriate disk location, and the corresponding journal entries can be discarded. If a system crash or power failure occurs before the changes are committed, during restart the system will detect that the file system was not unmounted properly, traverse the journal, and apply the file-system changes described in the journal log. Ext4 is designed to be highly compatible with ext2 and ext3, although its core data structures and disk layout are modified. Regardless, a file system which has been unmounted as an ext2 system can be subsequently mounted as an ext4 system and offer the journaling capability. The journal is a file managed as a circular buffer. The journal may be stored on the same or a separate device from the main file system. Since the journal opera- tions are not "journaled" themselves, these are not handled by the same ext4 file system. Instead, a separate JBD (Journaling Block Device) is used to perform the journal read/write operations. JBD supports three main data structures: log record, atomic operation handle, and transaction. A log record describes a low-level file-system operation, typically resulting in changes within a block. Since a system call such as wr ite includes changes at multiple places—i-nodes, existing file blocks, new file blocks, list of free blocks, etc.—related log records are grouped in atomic operations. Ext4 noti- fies JBD of the start and end of system-call processing, so that JBD can ensure that either all log records in an atomic operation are applied, or none of them. Finally, primarily for efficiency reasons, JBD treats collections of atomic operations as transactions. Log records are stored consecutively within a transaction. JBD will allow portions of the journal file to be discarded only after all log records be- longing to a transaction are safely committed to disk. Since writing out a log entry for each disk change may be costly, ext4 may be configured to keep a journal of all disk changes, or only of changes related to the file-system metadata (the i-nodes, superblocks, etc.). Journaling only metadata gives less system overhead and results in better performance but does not make any guarantees against corruption of file data. Several other journaling file systems maintain logs of only metadata operations (e.g., SGI’s XFS). In addition, the reliability of the journal can be further improved via checksumming. Ke y modification in ext4 compared to its predecessors is the use of extents. Extents represent contiguous blocks of storage, for instance 128 MB of contiguous 4-KB blocks vs. individual storage blocks, as referenced in ext2. Unlike its prede- cessors, ext4 does not require metadata operations for each block of storage. This
clipped_os_Page_791_Chunk7008
792 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 scheme also reduces fragmentation for large files. As a result, ext4 can provide faster file system operations and support larger files and file system sizes. For instance, for a block size of 1 KB, ext4 increases the maximum file size from 16 GB to 16 TB, and the maximum file system size to 1 EB (Exabyte). The /proc File System Another Linux file system is the /proc (process) file system, an idea originally devised in the 8th edition of UNIX from Bell Labs and later copied in 4.4BSD and System V. Howev er, Linux extends the idea in several ways. The basic concept is that for every process in the system, a directory is created in /proc. The name of the directory is the process PID expressed as a decimal number. For example, /proc/619 is the directory corresponding to the process with PID 619. In this direc- tory are files that appear to contain information about the process, such as its com- mand line, environment strings, and signal masks. In fact, these files do not exist on the disk. When they are read, the system retrieves the information from the ac- tual process as needed and returns it in a standard format. Many of the Linux extensions relate to other files and directories located in /proc. They contain a wide variety of information about the CPU, disk partitions, devices, interrupt vectors, kernel counters, file systems, loaded modules, and much more. Unprivileged user programs may read much of this information to learn about system behavior in a safe way. Some of these files may be written to in order to change system parameters. 10.6.4 NFS: The Network File System Networking has played a major role in Linux, and UNIX in general, right from the beginning (the first UNIX network was built to move new kernels from the PDP-11/70 to the Interdata 8/32 during the port to the latter). In this section we will examine Sun Microsystem’s NFS (Network File System), which is used on all modern Linux systems to join the file systems on separate computers into one logical whole. Currently, the dominant NSF implementation is version 3, intro- duced in 1994. NSFv4 was introduced in 2000 and provides several enhancements over the previous NFS architecture. Three aspects of NFS are of interest: the archi- tecture, the protocol, and the implementation. We will now examine these in turn, first in the context of the simpler NFS version 3, then we will turn to the enhance- ments included in v4. NFS Architecture The basic idea behind NFS is to allow an arbitrary collection of clients and ser- vers to share a common file system. In many cases, all the clients and servers are on the same LAN, but this is not required. It is also possible to run NFS over a
clipped_os_Page_792_Chunk7009
SEC. 10.6 THE LINUX FILE SYSTEM 793 wide area network if the server is far from the client. For simplicity we will speak of clients and servers as though they were on distinct machines, but in fact, NFS al- lows every machine to be both a client and a server at the same time. Each NFS server exports one or more of its directories for access by remote clients. When a directory is made available, so are all of its subdirectories, so ac- tually entire directory trees are normally exported as a unit. The list of directories a server exports is maintained in a file, often /etc/exports, so these directories can be exported automatically whenever the server is booted. Clients access exported di- rectories by mounting them. When a client mounts a (remote) directory, it be- comes part of its directory hierarchy, as shown in Fig. 10-35. Client 1 Client 2 Server 1 Server 2 / /usr /usr/ast /usr/ast/work /bin /bin cat cp Is mv sh a b c d e /proj2 /proj1 /projects /mnt /bin Mount / Figure 10-35. Examples of remote mounted file systems. Directories are shown as squares and files as circles. In this example, client 1 has mounted the bin directory of server 1 on its own bin directory, so it can now refer to the shell as /bin/sh and get the shell on server 1. Diskless workstations often have only a skeleton file system (in RAM) and get all their files from remote servers like this. Similarly, client 1 has mounted server 2’s directory /projects on its directory /usr/ast/work so it can now access file a as /usr/ast/work/proj1/a. Finally, client 2 has also mounted the projects directory and can also access file a, only as /mnt/proj1/a. As seen here, the same file can have different names on different clients due to its being mounted in a different place in the respective trees. The mount point is entirely local to the clients; the server does not know where it is mounted on any of its clients.
clipped_os_Page_793_Chunk7010
794 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 NFS Protocols Since one of the goals of NFS is to support a heterogeneous system, with cli- ents and servers possibly running different operating systems on different hard- ware, it is essential that the interface between the clients and servers be well de- fined. Only then is anyone able to write a new client implementation and expect it to work correctly with existing servers, and vice versa. NFS accomplishes this goal by defining two client-server protocols. A proto- col is a set of requests sent by clients to servers, along with the corresponding replies sent by the servers back to the clients. The first NFS protocol handles mounting. A client can send a path name to a server and request permission to mount that directory somewhere in its directory hierarchy. The place where it is to be mounted is not contained in the message, as the server does not care where it is to be mounted. If the path name is legal and the directory specified has been exported, the server returns a file handle to the client. The file handle contains fields uniquely identifying the file-system type, the disk, the i-node number of the directory, and security information. Subsequent calls to read and write files in the mounted directory or any of its subdirectories use the file handle. When Linux boots, it runs the /etc/rc shell script before going multiuser. Com- mands to mount remote file systems can be placed in this script, thus automatically mounting the necessary remote file systems before allowing any logins. Alterna- tively, most versions of Linux also support automounting. This feature allows a set of remote directories to be associated with a local directory. None of these re- mote directories are mounted (or their servers even contacted) when the client is booted. Instead, the first time a remote file is opened, the operating system sends a message to each of the servers. The first one to reply wins, and its directory is mounted. Automounting has two principal advantages over static mounting via the /etc/rc file. First, if one of the NFS servers named in /etc/rc happens to be down, it is impossible to bring the client up, at least not without some difficulty, delay, and quite a few error messages. If the user does not even need that server at the moment, all that work is wasted. Second, by allowing the client to try a set of ser- vers in parallel, a degree of fault tolerance can be achieved (because only one of them needs to be up), and the performance can be improved (by choosing the first one to reply—presumably the least heavily loaded). On the other hand, it is tacitly assumed that all the file systems specified as al- ternatives for the automount are identical. Since NFS provides no support for file or directory replication, it is up to the user to arrange for all the file systems to be the same. Consequently, automounting is most often used for read-only file sys- tems containing system binaries and other files that rarely change. The second NFS protocol is for directory and file access. Clients can send messages to servers to manipulate directories and read and write files. They can
clipped_os_Page_794_Chunk7011
SEC. 10.6 THE LINUX FILE SYSTEM 795 also access file attributes, such as file mode, size, and time of last modification. Most Linux system calls are supported by NFS, with the perhaps surprising ex- ceptions of open and close. The omission of open and close is not an accident. It is fully intentional. It is not necessary to open a file before reading it, nor to close it when done. Instead, to read a file, a client sends the server a lookup message containing the file name, with a request to look it up and return a file handle, which is a structure that identi- fies the file (i.e., contains a file system identifier and i-node number, among other data). Unlike an open call, this lookup operation does not copy any information into internal system tables. The read call contains the file handle of the file to read, the offset in the file to begin reading, and the number of bytes desired. Each such message is self-contained. The advantage of this scheme is that the server does not have to remember anything about open connections in between calls to it. Thus if a server crashes and then recovers, no information about open files is lost, because there is none. A server like this that does not maintain state information about open files is said to be stateless. Unfortunately, the NFS method makes it difficult to achieve the exact Linux file semantics. For example, in Linux a file can be opened and locked so that other processes cannot access it. When the file is closed, the locks are released. In a stateless server such as NFS, locks cannot be associated with open files, because the server does not know which files are open. NFS therefore needs a separate, ad- ditional mechanism to handle locking. NFS uses the standard UNIX protection mechanism, with the rwx bits for the owner, group, and others (mentioned in Chap. 1 and discussed in detail below). Originally, each request message simply contained the user and group IDs of the caller, which the NFS server used to validate the access. In effect, it trusted the cli- ents not to cheat. Several years’ experience abundantly demonstrated that such an assumption was—how shall we put it?—rather naive. Currently, public key crypto- graphy can be used to establish a secure key for validating the client and server on each request and reply. When this option is used, a malicious client cannot imper- sonate another client because it does not know that client’s secret key. NFS Implementation Although the implementation of the client and server code is independent of the NFS protocols, most Linux systems use a three-layer implementation similar to that of Fig. 10-36. The top layer is the system-call layer. This handles calls like open, read, and close. After parsing the call and checking the parameters, it invokes the second layer, the Virtual File System (VFS) layer. The task of the VFS layer is to maintain a table with one entry for each open file. The VFS layer additionally has an entry, a virtual i-node, or v-node, for every open file. V-nodes are used to tell whether the file is local or remote. For remote files, enough information is provided to be able to access them. For local files, the
clipped_os_Page_795_Chunk7012
796 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 Client kernel Server kernel System call layer Buffer cache Buffer cache Virtual file system layer Virtual file system layer Local FS 1 Local FS 1 Local FS 2 Local FS 2 NFS client NFS server Driver Driver Driver Driver Message to server Message from client Local disks Local disks V- node Figure 10-36. The NFS layer structure file system and i-node are recorded because modern Linux systems can support multiple file systems (e.g., ext2fs, /proc, FAT , etc.). Although VFS was invented to support NFS, most modern Linux systems now support it as an integral part of the operating system, even if NFS is not used. To see how v-nodes are used, let us trace a sequence of mount, open, and read system calls. To mount a remote file system, the system administrator (or /etc/rc) calls the mount program specifying the remote directory, the local directory on which it is to be mounted, and other information. The mount program parses the name of the remote directory to be mounted and discovers the name of the NFS server on which the remote directory is located. It then contacts that machine, ask- ing for a file handle for the remote directory. If the directory exists and is available for remote mounting, the server returns a file handle for the directory. Finally, it makes a mount system call, passing the handle to the kernel. The kernel then constructs a v-node for the remote directory and asks the NFS client code in Fig. 10-36 to create an r-node (remote i-node) in its internal tables to hold the file handle. The v-node points to the r-node. Each v-node in the VFS layer will ultimately contain either a pointer to an r-node in the NFS client code, or a pointer to an i-node in one of the local file systems (shown as dashed lines in Fig. 10-36). Thus, from the v-node it is possible to see if a file or directory is local or remote. If it is local, the correct file system and i-node can be located. If it is remote, the remote host and file handle can be located.
clipped_os_Page_796_Chunk7013
SEC. 10.6 THE LINUX FILE SYSTEM 797 When a remote file is opened on the client, at some point during the parsing of the path name, the kernel hits the directory on which the remote file system is mounted. It sees that this directory is remote and in the directory’s v-node finds the pointer to the r-node. It then asks the NFS client code to open the file. The NFS client code looks up the remaining portion of the path name on the remote server associated with the mounted directory and gets back a file handle for it. It makes an r-node for the remote file in its tables and reports back to the VFS layer, which puts in its tables a v-node for the file that points to the r-node. Again here we see that every open file or directory has a v-node that points to either an r-node or an i-node. The caller is given a file descriptor for the remote file. This file descriptor is mapped onto the v-node by tables in the VFS layer. Note that no table entries are made on the server side. Although the server is prepared to provide file handles upon request, it does not keep track of which files happen to have file handles out- standing and which do not. When a file handle is sent to it for file access, it checks the handle, and if it is valid, uses it. Validation can include verifying an authentica- tion key contained in the RPC headers, if security is enabled. When the file descriptor is used in a subsequent system call, for example, read, the VFS layer locates the corresponding v-node, and from that determines whether it is local or remote and also which i-node or r-node describes it. It then sends a message to the server containing the handle, the file offset (which is maintained on the client side, not the server side), and the byte count. For efficiency reasons, transfers between client and server are done in large chunks, normally 8192 bytes, ev en if fewer bytes are requested. When the request message arrives at the server, it is passed to the VFS layer there, which determines which local file system holds the requested file. The VFS layer then makes a call to that local file system to read and return the bytes. These data are then passed back to the client. After the client’s VFS layer has gotten the 8-KB chunk it asked for, it automatically issues a request for the next chunk, so it will have it should it be needed shortly. This feature, known as read ahead, im- proves performance considerably. For writes an analogous path is followed from client to server. Also, transfers are done in 8-KB chunks here, too. If a wr ite system call supplies fewer than 8 KB of data, the data are just accumulated locally. Only when the entire 8-KB chunk is full is it sent to the server. Howev er, when a file is closed, all of its data are sent to the server immediately. Another technique used to improve performance is caching, as in ordinary UNIX. Servers cache data to avoid disk accesses, but this is invisible to the clients. Clients maintain two caches, one for file attributes (i-nodes) and one for file data. When either an i-node or a file block is needed, a check is made to see if it can be satisfied out of the cache. If so, network traffic can be avoided. While client caching helps performance enormously, it also introduces some nasty problems. Suppose that two clients are both caching the same file block and
clipped_os_Page_797_Chunk7014
798 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 one of them modifies it. When the other one reads the block, it gets the old (stale) value. The cache is not coherent. Given the potential severity of this problem, the NFS implementation does sev- eral things to mitigate it. For one, associated with each cache block is a timer. When the timer expires, the entry is discarded. Normally, the timer is 3 sec for data blocks and 30 sec for directory blocks. Doing this reduces the risk somewhat. In addition, whenever a cached file is opened, a message is sent to the server to find out when the file was last modified. If the last modification occurred after the local copy was cached, the cache copy is discarded and the new copy fetched from the server. Finally, once every 30 sec a cache timer expires, and all the dirty (i.e., mod- ified) blocks in the cache are sent to the server. While not perfect, these patches make the system highly usable in most practical circumstances. NFS Version 4 Version 4 of the Network File System was designed to simplify certain opera- tions from its predecessor. In contrast to NSFv3, which is described above, NFSv4 is a stateful file system. This permits open operations to be invoked on remote files, since the remote NFS server will maintain all file-system-related structures, including the file pointer. Read operations then need not include absolute read ranges, but can be incrementally applied from the previous file-pointer position. This results in shorter messages, and also in the ability to bundle multiple NFSv3 operations in one network transaction. The stateful nature of NFSv4 makes it easy to integrate the variety of NFSv3 protocols described earlier in this section into one coherent protocol. There is no need to support separate protocols for mounting, caching, locking, or secure opera- tions. NFSv4 also works better with both Linux (and UNIX in general) and Win- dows file-system semantics. 10.7 SECURITY IN LINUX Linux, as a clone of MINIX and UNIX, has been a multiuser system almost from the beginning. This history means that security and control of information was built in very early on. In the following sections, we will look at some of the security aspects of Linux. 10.7.1 Fundamental Concepts The user community for a Linux system consists of some number of registered users, each of whom has a unique UID (User ID). A UID is an integer between 0 and 65,535. Files (but also processes and other resources) are marked with the
clipped_os_Page_798_Chunk7015
SEC. 10.7 SECURITY IN LINUX 799 UID of their owner. By default, the owner of a file is the person who created the file, although there is a way to change ownership. Users can be organized into groups, which are also numbered with 16-bit inte- gers called GIDs (Group IDs). Assigning users to groups is done manually (by the system administrator) and consists of making entries in a system database tel- ling which user is in which group. A user could be in one or more groups at the same time. For simplicity, we will not discuss this feature further. The basic security mechanism in Linux is simple. Each process carries the UID and GID of its owner. When a file is created, it gets the UID and GID of the creat- ing process. The file also gets a set of permissions determined by the creating proc- ess. These permissions specify what access the owner, the other members of the owner’s group, and the rest of the users have to the file. For each of these three cat- egories, potential accesses are read, write, and execute, designated by the letters r, w, and x, respectively. The ability to execute a file makes sense only if that file is an executable binary program, of course. An attempt to execute a file that has ex- ecute permission but which is not executable (i.e., does not start with a valid head- er) will fail with an error. Since there are three categories of users and 3 bits per category, 9 bits are sufficient to represent the access rights. Some examples of these 9-bit numbers and their meanings are given in Fig. 10-37. Binar y Symbolic Allowed file accesses 111000000 rwx– – – – – – Owner can read, write, and execute 111111000 rwxrwx– – – Owner and group can read, write, and execute 110100000 rw–r– – – – – Owner can read and write; group can read 110100100 rw–r– –r– – Owner can read and write; all others can read 111101101 rwxr–xr–x Owner can do everything, rest can read and execute 000000000 – – – – – – – – – Nobody has any access 000000111 – – – – – –rwx Only outsiders have access (strange, but legal) Figure 10-37. Some example file-protection modes. The first two entries in Fig. 10-37 allow the owner and the owner’s group full access, respectively. The next one allows the owner’s group to read the file but not to change it, and prevents outsiders from any access. The fourth entry is common for a data file the owner wants to make public. Similarly, the fifth entry is the usual one for a publicly available program. The sixth entry denies all access to all users. This mode is sometimes used for dummy files used for mutual exclusion be- cause an attempt to create such a file will fail if one already exists. Thus if multiple processes simultaneously attempt to create such a file as a lock, only one of them will succeed. The last example is strange indeed, since it gives the rest of the world more access than the owner. Howev er, its existence follows from the protection rules. Fortunately, there is a way for the owner to subsequently change the protec- tion mode, even without having any access to the file itself.
clipped_os_Page_799_Chunk7016
800 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 The user with UID 0 is special and is called the superuser (or root). The superuser has the power to read and write all files in the system, no matter who owns them and no matter how they are protected. Processes with UID 0 also have the ability to make a small number of protected system calls denied to ordinary users. Normally, only the system administrator knows the superuser’s password, al- though many undergraduates consider it a great sport to try to look for security flaws in the system so they can log in as the superuser without knowing the pass- word. Management tends to frown on such activity. Directories are files and have the same protection modes that ordinary files do except that the x bits refer to search permission instead of execute permission. Thus a directory with mode rwxr–xr–x allows its owner to read, modify, and search the directory, but allows others only to read and search it, but not add or remove files from it. Special files corresponding to the I/O devices have the same protection bits as regular files. This mechanism can be used to limit access to I/O devices. For ex- ample, the printer special file, /dev/lp, could be owned by the root or by a special user, daemon, and have mode rw– – – – – – – to keep everyone else from directly accessing the printer. After all, if everyone could just print at will, chaos would re- sult. Of course, having /dev/lp owned by, say, daemon with protection mode rw– – – – – – – means that nobody else can use the printer. While this would save many innocent trees from an early death, sometimes users do have a legitimate need to print something. In fact, there is a more general problem of allowing con- trolled access to all I/O devices and other system resources. This problem was solved by adding a new protection bit, the SETUID bit, to the 9 protection bits discussed above. When a program with the SETUID bit on is executed, the effective UID for that process becomes the UID of the executable file’s owner instead of the UID of the user who invoked it. When a process at- tempts to open a file, it is the effective UID that is checked, not the underlying real UID. By making the program that accesses the printer be owned by daemon but with the SETUID bit on, any user could execute it, and have the power of daemon (e.g., access to /dev/lp) but only to run that program (which might queue print jobs for printing in an orderly fashion). Many sensitive Linux programs are owned by the root but with the SETUID bit on. For example, the program that allows users to change their passwords, passwd, needs to write in the password file. Making the password file publicly writable would not be a good idea. Instead, there is a program that is owned by the root and which has the SETUID bit on. Although the program has complete access to the password file, it will change only the caller’s password and not permit any other access to the password file. In addition to the SETUID bit there is also a SETGID bit that works analo- gously, temporarily giving the user the effective GID of the program. In practice, this bit is rarely used, however.
clipped_os_Page_800_Chunk7017
SEC. 10.7 SECURITY IN LINUX 801 10.7.2 Security System Calls in Linux There are only a small number of system calls relating to security. The most important ones are listed in Fig. 10-38. The most heavily used security system call is chmod. It is used to change the protection mode. For example, s = chmod("/usr/ast/newgame", 0755); sets newgame to rwxr–xr–x so that everyone can run it (note that 0755 is an octal constant, which is convenient, since the protection bits come in groups of 3 bits). Only the owner of a file and the superuser can change its protection bits. System call Description s = chmod(path, mode) Change a file’s protection mode s = access(path, mode) Check access using the real UID and GID uid = getuid( ) Get the real UID uid = geteuid( ) Get the effective UID gid = getgid( ) Get the real GID gid = getegid( ) Get the effective GID s = chown(path, owner, group) Change owner and group s = setuid(uid) Set the UID s = setgid(gid) Set the GID Figure 10-38. Some system calls relating to security. The return code s is −1 if an error has occurred; uid and gid are the UID and GID, respectively. The param- eters should be self explanatory. The access call tests to see if a particular access would be allowed using the real UID and GID. This system call is needed to avoid security breaches in pro- grams that are SETUID and owned by the root. Such a program can do anything, and it is sometimes needed for the program to figure out if the user is allowed to perform a certain access. The program cannot just try it, because the access will al- ways succeed. With the access call the program can find out if the access is allow- ed by the real UID and real GID. The next four system calls return the real and effective UIDs and GIDs. The last three are allowed only for the superuser. They change a file’s owner, and a process’ UID and GID. 10.7.3 Implementation of Security in Linux When a user logs in, the login program, login (which is SETUID root) asks for a login name and a password. It hashes the password and then looks in the pass- word file, /etc/passwd, to see if the hash matches the one there (networked systems work slightly differently). The reason for using hashes is to prevent the password
clipped_os_Page_801_Chunk7018
802 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 from being stored in unencrypted form anywhere in the system. If the password is correct, the login program looks in /etc/passwd to see the name of the user’s pre- ferred shell, possibly bash, but possibly some other shell such as csh or ksh. The login program then uses setuid and setgid to give itself the user’s UID and GID (remember, it started out as SETUID root). Then it opens the keyboard for stan- dard input (file descriptor 0), the screen for standard output (file descriptor 1), and the screen for standard error (file descriptor 2). Finally, it executes the preferred shell, thus terminating itself. At this point the preferred shell is running with the correct UID and GID and standard input, output, and error all set to their default devices. All processes that it forks off (i.e., commands typed by the user) automatically inherit the shell’s UID and GID, so they also will have the correct owner and group. All files they create also get these values. When any process attempts to open a file, the system first checks the protec- tion bits in the file’s i-node against the caller’s effective UID and effective GID to see if the access is permitted. If so, the file is opened and a file descriptor returned. If not, the file is not opened and −1 is returned. No checks are made on subsequent read or wr ite calls. As a consequence, if the protection mode changes after a file is already open, the new mode will not affect processes that already have the file open. The Linux security model and its implementation are essentially the same as in most other traditional UNIX systems. 10.8 ANDROID Android is a relatively new operating system designed to run on mobile de- vices. It is based on the Linux kernel—Android introduces only a few new con- cepts to the Linux kernel itself, using most of the Linux facilities you are already familiar with (processes, user IDs, virtual memory, file systems, scheduling, etc.) in sometimes very different ways than they were originally intended. In the fiv e years since its introduction, Android has grown to be one of the most widely used smartphone operating systems. Its popularity has ridden the ex- plosion of smartphones, and it is freely available for manufacturers of mobile de- vices to use in their products. It is also an open-source platform, making it cus- tomizable to a diverse variety of devices. It is popular not only for consumer- centric devices where its third-party application ecosystem is advantageous (such as tablets, televisions, game systems, and media players), but is increasingly used as the embedded OS for dedicated devices that need a graphical user interface (GUI) such as VOIP phones, smart watches, automotive dashboards, medical de- vices, and home appliances. A large amount of the Android operating system is written in a high-level lan- guage, the Java programming language. The kernel and a large number of low-
clipped_os_Page_802_Chunk7019
SEC. 10.8 ANDROID 803 level libraries are written in C and C++. However a large amount of the system is written in Java and, but for some small exceptions, the entire application API is written and published in Java as well. The parts of Android written in Java tend to follow a very object-oriented design as encouraged by that language. 10.8.1 Android and Google Android is an unusual operating system in the way it combines open-source code with closed-source third-party applications. The open-source part of Android is called the Android Open Source Project (AOSP) and is completely open and free to be used and modified by anyone. An important goal of Android is to support a rich third-party application envi- ronment, which requires having a stable implementation and API for applications to run against. However, in an open-source world where every device manufac- turer can customize the platform however it wants, compatibility issues quickly arise. There needs to be some way to control this conflict. Part of the solution to this for Android is the CDD (Compatibility Definition Document), which describes the ways Android must behave to be compatible with third party applications. This document by itself describes what is required to be a compatible Android device. Without some way to enforce such compatibility, how- ev er, it will often be ignored; there needs to be some additional mechanism to do this. Android solves this by allowing additional proprietary services to be created on top of the open-source platform, providing (typically cloud-based) services that the platform cannot itself implement. Since these services are proprietary, they can restrict which devices are allowed to include them, thus requiring CDD compatibil- ity of those devices. Google implemented Android to be able to support a wide variety of propri- etary cloud services, with Google’s extensive set of services being representative cases: Gmail, calendar and contacts sync, cloud-to-device messaging, and many other services, some visible to the user, some not. When it comes to offering com- patible apps, the most important service is Google Play. Google Play is Google’s online store for Android apps. Generally when devel- opers create Android applications, they will publish with Google Play. Since Google Play (or any other application store) is the channel through which applica- tions are delivered to an Android device, that proprietary service is responsible for ensuring that applications will work on the devices it delivers them to. Google Play uses two main mechanisms to ensure compatibility. The first and most important is requiring that any device shipping with it must be a compatible Android device as per the CDD. This ensures a baseline of behavior across all de- vices. In addition, Google Play must know about any features of a device that an application requires (such as there being a GPS for performing mapping naviga- tion) so the application is not made available on devices that lack those features.
clipped_os_Page_803_Chunk7020
804 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 10.8.2 History of Android Google developed Android in the mid-2000s, after acquiring Android as a startup company early in its development. Nearly all the development of the Android platform that exists today was done under Google’s management. Early Development Android, Inc. was a software company founded to build software to create smarter mobile devices. Originally looking at cameras, the vision soon switched to smartphones due to their larger potential market. That initial goal grew to ad- dressing the then-current difficulty in developing for mobile devices, by bringing to them an open platform built on top of Linux that could be widely used. During this time, prototypes for the platform’s user interface were imple- mented to demonstrate the ideas behind it. The platform itself was targeting three key languages, JavaScript, Java, and C++, in order to support a rich application-de- velopment environment. Google acquired Android in July 2005, providing the necessary resources and cloud-service support to continue Android development as a complete product. A fairly small group of engineers worked closely together during this time, starting to develop the core infrastructure for the platform and foundations for higher-level application development. In early 2006, a significant shift in plan was made: instead of supporting multi- ple programming languages, the platform would focus entirely on the Java pro- gramming language for its application development. This was a difficult change, as the original multilanguage approach superficially kept everyone happy with ‘‘the best of all worlds’’; focusing on one language felt like a step backward to engineers who preferred other languages. Trying to make everyone happy, howev er, can easily make nobody happy. Building out three different sets of language APIs would have required much more effort than focusing on a single language, greatly reducing the quality of each one. The decision to focus on the Java language was critical for the ultimate quality of the platform and the development team’s ability to meet important deadlines. As development progressed, the Android platform was developed closely with the applications that would ultimately ship on top of it. Google already had a wide variety of services—including Gmail, Maps, Calendar, YouTube, and of course Search—that would be delivered on top of Android. Knowledge gained from im- plementing these applications on top of the early platform was fed back into its de- sign. This iterative process with the applications allowed many design flaws in the platform to be addressed early in its development. Most of the early application development was done with little of the underly- ing platform actually available to the developers. The platform was usually run- ning all inside one process, through a ‘‘simulator’’ that ran all of the system and
clipped_os_Page_804_Chunk7021
SEC. 10.8 ANDROID 805 applications as a single process on a host computer. In fact there are still some remnants of this old implementation around today, with things like the Applica- tion.onTer minate method still in the SDK (Software Dev elopment Kit), which Android programmers use to write applications. In June 2006, two hardware devices were selected as software-development targets for planned products. The first, code-named ‘‘Sooner,’’ was based on an existing smartphone with a QWERTY keyboard and screen without touch input. The goal of this device was to get an initial product out as soon as possible, by leveraging existing hardware. The second target device, code-named ‘‘Dream,’’ was designed specifically for Android, to run it as fully envisioned. It included a large (for that time) touch screen, slide-out QWERTY keyboard, 3G radio (for fast- er web browsing), accelerometer, GPS and compass (to support Google Maps), etc. As the software schedule came better into focus, it became clear that the two hardware schedules did not make sense. By the time it was possible to release Sooner, that hardware would be well out of date, and the effort put on Sooner was pushing out the more important Dream device. To address this, it was decided to drop Sooner as a target device (though development on that hardware continued for some time until the newer hardware was ready) and focus entirely on Dream. Android 1.0 The first public availability of the Android platform was a preview SDK re- leased in November 2007. This consisted of a hardware device emulator running a full Android device system image and core applications, API documentation, and a development environment. At this point the core design and implementation were in place, and in most ways closely resembled the modern Android system architec- ture we will be discussing. The announcement included video demos of the plat- form running on top of both the Sooner and Dream hardware. Early development of Android had been done under a series of quarterly demo milestones to drive and show continued process. The SDK release was the first more formal release for the platform. It required taking all the pieces that had been put together so far for application development, cleaning them up, documenting them, and creating a cohesive dev elopment environment for third-party developers. Development now proceeded along two tracks: taking in feedback about the SDK to further refine and finalize APIs, and finishing and stabilizing the imple- mentation needed to ship the Dream device. A number of public updates to the SDK occurred during this time, culminating in a 0.9 release in August 2008 that contained the nearly final APIs. The platform itself had been going through rapid development, and in the spring of 2008 the focus was shifting to stabilization so that Dream could ship. Android at this point contained a large amount of code that had never been shipped as a commercial product, all the way from parts of the C library, through the Dalvik interpreter (which runs the apps), system, and applications.
clipped_os_Page_805_Chunk7022
806 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 Android also contained quite a few novel design ideas that had never been done before, and it was not clear how they would pan out. This all needed to come together as a stable product, and the team spent a few nail-biting months wonder- ing if all of this stuff would actually come together and work as intended. Finally, in August 2008, the software was stable and ready to ship. Builds went to the factory and started being flashed onto devices. In September Android 1.0 was launched on the Dream device, now called the T-Mobile G1. Continued Development After Android’s 1.0 release, development continued at a rapid pace. There were about 15 major updates to the platform over the following 5 years, adding a large variety of new features and improvements from the initial 1.0 release. The original Compatibility Definition Document basically allowed only for compatible devices that were very much like the T-Mobile G1. Over the following years, the range of compatible devices would greatly expand. Key points of this process were: 1. During 2009, Android versions 1.5 through 2.0 introduced a soft keyboard to remove a requirement for a physical keyboard, much more extensive screen support (both size and pixel density) for lower- end QVGA devices and new larger and higher density devices like the WVGA Motorola Droid, and a new ‘‘system feature’’ facility for de- vices to report what hardware features they support and applications to indicate which hardware features they require. The latter is the key mechanism Google Play uses to determine application compatibility with a specific device. 2. During 2011, Android versions 3.0 through 4.0 introduced new core support in the platform for 10-inch and larger tablets; the core plat- form now fully supported device screen sizes everywhere from small QVGA phones, through smartphones and larger ‘‘phablets,’’ 7-inch tablets and larger tablets to beyond 10 inches. 3. As the platform provided built-in support for more diverse hardware, not only larger screens but also nontouch devices with or without a mouse, many more types of Android devices appeared. This included TV devices such as Google TV, gaming devices, notebooks, cameras, etc. Significant development work also went into something not as visible: a cleaner separation of Google’s proprietary services from the Android open-source platform. For Android 1.0, significant work had been put into having a clean third-party application API and an open-source platform with no dependencies on proprietary
clipped_os_Page_806_Chunk7023
SEC. 10.8 ANDROID 807 Google code. However, the implementation of Google’s proprietary code was often not yet cleaned up, having dependencies on internal parts of the platform. Often the platform did not even hav e facilities that Google’s proprietary code need- ed in order to integrate well with it. A series of projects were soon undertaken to address these issues: 1. In 2009, Android version 2.0 introduced an architecture for third par- ties to plug their own sync adapters into platform APIs like the con- tacts database. Google’s code for syncing various data moved to this well-defined SDK API. 2. In 2010, Android version 2.2 included work on the internal design and implementation of Google’s proprietary code. This ‘‘great unbundling’’ cleanly implemented many core Google services, from delivering cloud-based system software updates to ‘‘cloud-to-device messaging’’ and other background services, so that they could be de- livered and updated separately from the platform. 3. In 2012, a new Google Play services application was delivered to de- vices, containing updated and new features for Google’s proprietary nonapplication services. This was the outgrowth of the unbundling work in 2010, allowing proprietary APIs such as cloud-to-device mes- saging and maps to be fully delivered and updated by Google. 10.8.3 Design Goals A number of key design goals for the Android platform evolved during its de- velopment: 1. Provide a complete open-source platform for mobile devices. The open-source part of Android is a bottom-to-top operating system stack, including a variety of applications, that can ship as a complete product. 2. Strongly support proprietary third-party applications with a robust and stable API. As previously discussed, it is challenging to maintain a platform that is both truly open-source and also stable enough for proprietary third-party applications. Android uses a mix of technical solutions (specifying a very well-defined SDK and division between public APIs and internal implementation) and policy requirements (through the CDD) to address this. 3. Allow all third-party applications, including those from Google, to compete on a level playing field. The Android open source code is
clipped_os_Page_807_Chunk7024
808 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 designed to be neutral as much as possible to the higher-level system features built on top of it, from access to cloud services (such as data sync or cloud-to-device messaging APIs), to libraries (such as Google’s mapping library) and rich services like application stores. 4. Provide an application security model in which users do not have to deeply trust third-party applications. The operating system must pro- tect the user from misbehavior of applications, not only buggy appli- cations that can cause it to crash, but more subtle misuse of the device and the user’s data on it. The less users need to trust applications, the more freedom they hav e to try out and install them. 5. Support typical mobile user interaction: spending short amounts of time in many apps. The mobile experience tends to involve brief interactions with applications: glancing at new received email, receiv- ing and sending an SMS message or IM, going to contacts to place a call, etc. The system needs to optimize for these cases with fast app launch and switch times; the goal for Android has generally been 200 msec to cold start a basic application up to the point of showing a full interactive UI. 6. Manage application processes for users, simplifying the user experi- ence around applications so that users do not have to worry about closing applications when done with them. Mobile devices also tend to run without the swap space that allows operating systems to fail more gracefully when the current set of running applications requires more RAM than is physically available. To address both of these re- quirements, the system needs to take a more proactive stance about managing processes and deciding when they should be started and stopped. 7. Encourage applications to interoperate and collaborate in rich and secure ways. Mobile applications are in some ways a return back to shell commands: rather than the increasingly large monolithic design of desktop applications, they are targeted and focused for specific needs. To help support this, the operating system should provide new types of facilities for these applications to collaborate together to cre- ate a larger whole. 8. Create a full general-purpose operating system. Mobile devices are a new expression of general purpose computing, not something simpler than our traditional desktop operating systems. Android’s design should be rich enough that it can grow to be at least as capable as a traditional operating system.
clipped_os_Page_808_Chunk7025
SEC. 10.8 ANDROID 809 10.8.4 Android Architecture Android is built on top of the standard Linux kernel, with only a few signifi- cant extensions to the kernel itself that will be discussed later. Once in user space, however, its implementation is quite different from a traditional Linux distribution and uses many of the Linux features you already understand in very different ways. As in a traditional Linux system, Android’s first user-space process is init, which is the root of all other processes. The daemons Android’s init process starts are different, however, focused more on low-level details (managing file systems and hardware access) rather than higher-level user facilities like scheduling cron jobs. Android also has an additional layer of processes, those running Dalvik’s Java language environment, which are responsible for executing all parts of the system implemented in Java. Figure 10-39 illustrates the basic process structure of Android. First is the init process, which spawns a number of low-level daemon processes. One of these is zygote, which is the root of the higher-level Java language processes. appN phone system_server Dalvik Dalvik Dalvik zygote Daemons System processes App processes app1 app2 Dalvik Dalvik installd servicemanager init adbd Kernel Dalvik Figure 10-39. Android process hierarchy. Android’s init does not run a shell in the traditional way, since a typical Android device does not have a local console for shell access. Instead, the daemon process adbd listens for remote connections (such as over USB) that request shell access, forking shell processes for them as needed. Since most of Android is written in the Java language, the zygote daemon and processes it starts are central to the system. The first process zygote always starts
clipped_os_Page_809_Chunk7026
810 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 is called system server, which contains all of the core operating system services. Ke y parts of this are the power manager, package manager, window manager, and activity manager. Other processes will be created from zygote as needed. Some of these are ‘‘persistent’’ processes that are part of the basic operating system, such as the tele- phony stack in the phone process, which must remain always running. Additional application processes will be created and stopped as needed while the system is running. Applications interact with the operating system through calls to libraries pro- vided by it, which together compose the Android framework. Some of these li- braries can perform their work within that process, but many will need to perform interprocess communication with other processes, often services in the sys- tem server process. Figure 10-40 shows the typical design for Android framework APIs that inter- act with system services, in this case the package manager. The package manager provides a framework API for applications to call in their local process, here the PackageManager class. Internally, this class must get a connection to the corres- ponding service in the system server. To accomplish this, at boot time the sys- tem server publishes each service under a well-defined name in the service man- ager, a daemon started by init. The PackageManager in the application process retrieves a connection from the service manager to its system service using that same name. Once the PackageManager has connected with its system service, it can make calls on it. Most application calls to PackageManager are implemented as interprocess communication using Android’s Binder IPC mechanism, in this case making calls to the PackageManagerService implementation in the system server. The implementation of PackageManagerService arbitrates interactions across all client applications and maintains state that will be needed by multiple applications. 10.8.5 Linux Extensions For the most part, Android includes a stock Linux kernel providing standard Linux features. Most of the interesting aspects of Android as an operating system are in how those existing Linux features are used. There are also, however, serveral significant extensions to Linux that the Android system relies on. Wake Locks Power management on mobile devices is different than on traditional comput- ing systems, so Android adds a new feature to Linux called wake locks (also called suspend blockers) for managing how the system goes to sleep. On a traditional computing system, the system can be in one of two power states: running and ready for user input, or deeply asleep and unable to continue
clipped_os_Page_810_Chunk7027
SEC. 10.8 ANDROID 811 Application process System server Application Code PackageManager PackageManagerService Service manager "package" Binder IPC Binder IPC Binder IPC Figure 10-40. Publishing and interacting with system services. executing without an external interrupt such as pressing a power key. While run- ning, secondary pieces of hardware may be turned on or off as needed, but the CPU itself and core parts of the hardware must remain in a powered state to handle incoming network traffic and other such events. Going into the lower-power sleep state is something that happens relatively rarely: either through the user explicitly putting the system to sleep, or its going to sleep itself due to a relatively long inter- val of user inactivity. Coming out of this sleep state requires a hardware interrupt from an external source, such as pressing a button on a keyboard, at which point the device will wake up and turn on its screen. Mobile device users have different expectations. Although the user can turn off the screen in a way that looks like putting the device to sleep, the traditional sleep state is not actually desired. While a device’s screen is off, the device still needs to be able to do work: it needs to be able to receive phone calls, receive and process data for incoming chat messages, and many other things. The expectations around turning a mobile device’s screen on and off are also much more demanding than on a traditional computer. Mobile interaction tends to be in many short bursts throughout the day: you receive a message and turn on the device to see it and perhaps send a one-sentence reply, you run into friends walking
clipped_os_Page_811_Chunk7028
812 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 their new dog and turn on the device to take a picture of her. In this kind of typical mobile usage, any delay from pulling the device out until it is ready for use has a significant negative impact on the user experience. Given these requirements, one solution would be to just not have the CPU go to sleep when a device’s screen is turned off, so that it is always ready to turn back on again. The kernel does, after all, know when there is no work scheduled for any threads, and Linux (as well as most operating systems) will automatically make the CPU idle and use less power in this situation. An idle CPU, however, is not the same thing as true sleep. For example: 1. On many chipsets the idle state uses significantly more power than a true sleep state. 2. An idle CPU can wake up at any moment if some work happens to become available, even if that work is not important. 3. Just having the CPU idle does not tell you that you can turn off other hardware that would not be needed in a true sleep. Wake locks on Android allow the system to go in to a deeper sleep mode, with- out being tied to an explicit user action like turning the screen off. The default state of the system with wake locks is that the device is asleep. When the device is running, to keep it from going back to sleep something needs to be holding a wake lock. While the screen is on, the system always holds a wake lock that prevents the device from going to sleep, so it will stay running, as we expect. When the screen is off, however, the system itself does not generally hold a wake lock, so it will stay out of sleep only as long as something else is holding one. When no more wake locks are held, the system goes to sleep, and it can come out of sleep only due to a hardware interrupt. Once the system has gone to sleep, a hardware interrupt will wake it up again, as in a traditional operating system. Some sources of such an interrupt are time- based alarms, events from the cellular radio (such as for an incoming call), incom- ing network traffic, and presses on certain hardware buttons (such as the power button). Interrupt handlers for these events require one change from standard Linux: they need to aquire an initial wake lock to keep the system running after it handles the interrupt. The wake lock acquired by an interrupt handler must be held long enough to transfer control up the stack to the driver in the kernel that will continue processing the event. That kernel driver is then responsible for acquiring its own wake lock, after which the interrupt wake lock can be safely released without risk of the sys- tem going back to sleep. If the driver is then going to deliver this event up to user space, a similar hand- shake is needed. The driver must ensure that it continues to hold the wake lock un- til it has delivered the event to a waiting user process and ensured there has been an
clipped_os_Page_812_Chunk7029
SEC. 10.8 ANDROID 813 opportunity there to acquire its own wake lock. This flow may continue across subsystems in user space as well; as long as something is holding a wake lock, we continue performing the desired processing to respond to the event. Once no more wake locks are held, however, the entire system falls back to sleep and all proc- essing stops. Out-Of-Memory Killer Linux includes an ‘‘out-of-memory killer’’ that attempts to recover when mem- ory is extremely low. Out-of-memory situations on modern operating systems are nebulous affairs. With paging and swap, it is rare for applications themselves to see out-of-memory failures. However, the kernel can still get in to a situation where it is unable to find available RAM pages when needed, not just for a new allocation, but when swapping in or paging in some address range that is now being used. In such a low-memory situation, the standard Linux out-of-memory killer is a last resort to try to find RAM so that the kernel can continue with whatever it is doing. This is done by assigning each process a ‘‘badness’’ lev el, and simply killing the process that is considered the most bad. A process’s badness is based on the amount of RAM being used by the process, how long it has been running, and other factors; the goal is to kill large processes that are hopefully not critical. Android puts special pressure on the out-of-memory killer. It does not have a swap space, so it is much more common to be in out-of-memory situations: there is no way to relieve memory pressure except by dropping clean RAM pages mapped from storage that has been recently used. Even so, Android uses the standard Linux configuration to over-commit memory—that is, allow address space to be al- located in RAM without a guarantee that there is available RAM to back it. Over- commit is an extremely important tool for optimizing memory use, since it is com- mon to mmap large files (such as executables) where you will only be needing to load into RAM small parts of the overall data in that file. Given this situation, the stock Linux out-of-memory killer does not work well, as it is intended more as a last resort and has a hard time correctly identifying good processes to kill. In fact, as we will discuss later, Android relies extensively on the out-of-memory killer running regularly to reap processes and make good choices about which to select. To address this, Android introduces its own out-of-memory killer to the kernel, with different semantics and design goals. The Android out-of-memory killer runs much more aggressively: whenever RAM is getting ‘‘low.’’ Low RAM is identified by a tunable parameter indicating how much available free and cached RAM in the kernel is acceptable. When the system goes below that limit, the out-of-memory killer runs to release RAM from elsewhere. The goal is to ensure that the system never gets into bad paging states, which can negatively impact the user experience when foreground applications are competing for RAM, since their execution be- comes much slower due to continual paging in and out.
clipped_os_Page_813_Chunk7030
814 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 Instead of trying to guess which processes should be killed, the Android out-of-memory killer relies very strictly on information provided to it by user space. The traditional Linux out-of-memory killer has a per-process oom adj pa- rameter that can be used to guide it toward the best process to kill by modifying the process’ overall badness score. Android’s out-of-memory killer uses this same pa- rameter, but as a strict ordering: processes with a higher oom adj will always be killed before those with lower ones. We will discuss later how the Android system decides to assign these scores. 10.8.6 Dalvik Dalvik implements the Java language environment on Android that is responsi- ble for running applications as well as most of its system code. Almost everything in the system service process—from the package manager, through the window manager, to the activity manager—is implemented with Java language code ex- ecuted by Dalvik. Android is not, however, a Java-language platform in the traditional sense. Java code in an Android application is provided in Dalvik’s bytecode format, based around a register machine rather than Java’s traditional stack-based bytecode. Dalvik’s bytecode format allows for faster interpretation, while still supporting JIT (Just-in-Time) compilation. Dalvik bytecode is also more space efficient, both on disk and in RAM, through the use of string pooling and other techniques. When writing Android applications, source code is written in Java and then compiled into standard Java bytecode using traditional Java tools. Android then introduces a new step: converting that Java bytecode into Dalvik’s more compact bytecode representation. It is the Dalvik bytecode version of an application that is packaged up as the final application binary and ultimately installed on the device. Android’s system architecture leans heavily on Linux for system primitives, in- cluding memory management, security, and communication across security bound- aries. It does not use the Java language for core operating system concepts—there is little attempt to abstract away these important aspects of the underlying Linux operating system. Of particular note is Android’s use of processes. Android’s design does not rely on the Java language for isolation between applications and the system, but rather takes the traditional operating system approach of process isolation. This means that each application is running in its own Linux process with its own Dalvik environment, as are the system server and other core parts of the platform that are written in Java. Using processes for this isolation allows Android to leverage all of Linux’s features for managing processes, from memory isolation to cleaning up all of the resources associated with a process when it goes away. In addition to processes, instead of using Java’s SecurityManager architecture, Android relies exclusively on Linux’s security features.
clipped_os_Page_814_Chunk7031
SEC. 10.8 ANDROID 815 The use of Linux processes and security greatly simplifies the Dalvik environ- ment, since it is no longer responsible for these critical aspects of system stability and robustness. Not incidentally, it also allows applications to freely use native code in their implementation, which is especially important for games which are usually built with C++-based engines. Mixing processes and the Java language like this does introduce some chal- lenges. Bringing up a fresh Java-language environment can take a second, even on modern mobile hardware. Recall one of the design goals of Android, to be able to quickly launch applications, with a target of 200 msec. Requiring that a fresh Dalvik process be brought up for this new application would be well beyond that budget. A 200-msec launch is hard to achieve on mobile hardware, even without needing to initialize a new Java-language environment. The solution to this problem is the zygote native daemon that we briefly men- tioned previously. Zygote is responsible for bringing up and initializing Dalvik, to the point where it is ready to start running system or application code written in Java. All new Dalvik-based processes (system or application) are forked from zygote, allowing them to start execution with the environment already ready to go. It is not just Dalvik that zygote brings up. Zygote also preloads many parts of the Android framework that are commonly used in the system and application, as well as loading resources and other things that are often needed. Note that creating a new process from zygote involves a Linux fork, but there is no exec call. The new process is a replica of the original zygote process, with all of its preinitialized state already set up and ready to go. Figure 10-41 illustrates how a new Java application process is related to the original zygote process. After the fork, the new process has its own separate Dalvik environment, though it is sharing all of the preloaded and initialed data with zygote through copy-on-write pages. All that now remains to have the new running process ready to go is to give it the correct identity (UID etc.), finish any initialization of Dalvik that requires starting threads, and loading the application or system code to be run. In addition to launch speed, there is another benefit that zygote brings. Because only a fork is used to create processes from it, the large number of dirty RAM pages needed to initialize Dalvik and preload classes and resources can be shared between zygote and all of its child processes. This sharing is especially important for Android’s environment, where swap is not available; demand paging of clean pages (such as executable code) from ‘‘disk’’ (flash memory) is available. However any dirty pages must stay locked in RAM; they cannot be paged out to ‘‘disk.’’ 10.8.7 Binder IPC Android’s system design revolves significantly around process isolation, be- tween applications as well as between different parts of the system itself. This re- quires a large amount of interprocess-communication to coordinate between the different processes, which can take a large amount of work to implement and get
clipped_os_Page_815_Chunk7032
816 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 Preloaded resources Preloaded classes Dalvik Copy-on-write Dalvik Preloaded classes Preloaded resources Application classes and resources App process Zygote Figure 10-41. Creating a new Dalvik process from zygote. right. Android’s Binder interprocess communication mechanism is a rich general- purpose IPC facility that most of the Android system is built on top of. The Binder architecture is divided into three layers, shown in Fig. 10-42. At the bottom of the stack is a kernel module that implements the actual cross-process interaction and exposes it through the kernel’s ioctl function. (ioctl is a gener- al-purpose kernel call for sending custom commands to kernel drivers and mod- ules.) On top of the kernel module is a basic object-oriented user-space API, al- lowing applications to create and interact with IPC endpoints through the IBinder and Binder classes. At the top is an interface-based programming model where ap- plications declare their IPC interfaces and do not otherwise need to worry about the details of how IPC happens in the lower layers. Binder Kernel Module Rather than use existing Linux IPC facilities such as pipes, Binder includes a special kernel module that implements its own IPC mechanism. The Binder IPC model is different enough from traditional Linux mechanisms that it cannot be ef- ficiently implemented on top of them purely in user space. In addition, Android does not support most of the System V primitives for cross-process interaction (semaphores, shared memory segments, message queues) because they do not pro- vide robust semantics for cleaning up their resources from buggy or malicious ap- plications. The basic IPC model Binder uses is the RPC (remote procedure call). That is, the sending process is submitting a complete IPC operation to the kernel, which
clipped_os_Page_816_Chunk7033
SEC. 10.8 ANDROID 817 Platform / Application Interface definitions Method calls Ilnterface / aidl transact() onTransact() IBinder / Binder Binder user space Result codes command Codes ioctl() Binder kernel module Figure 10-42. Binder IPC architecture. is executed in the receiving process; the sender may block while the receiver ex- ecutes, allowing a result to be returned back from the call. (Senders optionally may specify they should not block, continuing their execution in parallel with the receiver.) Binder IPC is thus message based, like System V message queues, rath- er than stream based as in Linux pipes. A message in Binder is referred to as a transaction, and at a higher level can be viewed as a function call across proc- esses. Each transaction that user space submits to the kernel is a complete operation: it identifies the target of the operation and identity of the sender as well as the complete data being delivered. The kernel determines the appropriate process to receive that transaction, delivering it to a waiting thread in the process. Figure 10-43 illustrates the basic flow of a transaction. Any thread in the orig- inating process may create a transaction identifying its target, and submit this to the kernel. The kernel makes a copy of the transaction, adding to it the identity of
clipped_os_Page_817_Chunk7034
818 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 the sender. It determines which process is responsible for the target of the transac- tion and wakes up a thread in the process to receive it. Once the receiving process is executing, it determines the appropriate target of the transaction and delivers it. Process 1 Process 2 Transaction To: Object1 From: Process 1 (Data) Object1 Thread pool Transaction To: Object1 (Data) Thread pool Kernel Transaction To: Object1 From: Process 1 (Data) T1 T1 T2 T2 Ta Figure 10-43. Basic Binder IPC transaction. (For the discussion here, we are simplifying the the way transaction data moves through the system as two copies, one to the kernel and one to the receiving process’s address space. The actual implementation does this in one copy. For each process that can receive transactions, the kernel creates a shared memory area with it. When it is handling a transaction, it first determines the process that will be receiving that transaction and copies the data directly into that shared address space.) Note that each process in Fig. 10-43 has a ‘‘thread pool.’’ This is one or more threads created by user space to handle incoming transactions. The kernel will dis- patch each incoming transaction to a thread currently waiting for work in that proc- ess’s thread pool. Calls into the kernel from a sending process however do not need to come from the thread pool—any thread in the process is free to initiate a transaction, such as Ta in Fig. 10-43. We hav e already seen that transactions given to the kernel identify a target ob- ject; howev er, the kernel must determine the receiving process. To accomplish this, the kernel keeps track of the available objects in each process and maps them to other processes, as shown in Fig. 10-44. The objects we are looking at here are simply locations in the address space of that process. The kernel only keeps track of these object addresses, with no meaning attached to them; they may be the loca- tion of a C data structure, C++ object, or anything else located in that process’s ad- dress space. References to objects in remote processes are identified by an integer handle, which is much like a Linux file descriptor. For example, consider Object2a in
clipped_os_Page_818_Chunk7035
SEC. 10.8 ANDROID 819 Process 2—this is known by the kernel to be associated with Process 2, and further the kernel has assigned Handle 2 for it in Process 1. Process 1 can thus submit a transaction to the kernel targeted to its Handle 2, and from that the kernel can de- termine this is being sent to Process 2 and specifically Object2a in that process. Process 1 Process 1 Process 2 Object1a Object1a Object2a Object2a Object2b Object2b Object1b Object1b Handle 2 Handle 2 Handle 1 Handle 1 Handle 2 Handle 2 Handle 3 Handle 3 Process 2 Kernel Figure 10-44. Binder cross-process object mapping. Also like file descriptors, the value of a handle in one process does not mean the same thing as that value in another process. For example, in Fig. 10-44, we can see that in Process 1, a handle value of 2 identifies Object2a; howev er, in Process 2, that same handle value of 2 identifies Object1a. Further, it is impossible for one process to access an object in another process if the kernel has not assigned a hand- le to it for that process. Again in Fig. 10-44, we can see that Process 2’s Object2b is known by the kernel, but no handle has been assigned to it for Process 1. There is thus no path for Process 1 to access that object, even if the kernel has assigned handles to it for other processes. How do these handle-to-object associations get set up in the first place? Unlike Linux file descriptors, user processes do not directly ask for handles. In- stead, the kernel assigns handles to processes as needed. This process is illustrated in Fig. 10-45. Here we are looking at how the reference to Object1b from Process 2 to Process 1 in the previous figure may have come about. The key to this is how a transaction flows through the system, from left to right at the bottom of the fig- ure. The key steps shown in Fig. 10-45 are: 1. Process 1 creates the initial transaction structure, which contains the local address Object1b. 2. Process 1 submits the transaction to the kernel. 3. The kernel looks at the data in the transaction, finds the address Ob- ject1b, and creates a new entry for it since it did not previously know about this address.
clipped_os_Page_819_Chunk7036
820 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 Process 1 Process 1 Process 2 Object1b Object2a Object2a Object1b Handle 2 Handle 2 Handle 1 Handle 2 Handle 3 Handle 3 Handle 1 1 3 4 6 5 6 8 Transaction Transaction Transaction Transaction To: Handle 2 To: Handle 2 To: Object2a From: Process 1 From: Process 1 To: Object2a From: Process 1 Data Data Object1b Data Data Data Data Object1b Handle 3 Data Data Handle 3 Process 2 Kernel 7 2 Figure 10-45. Transferring Binder objects between processes. 4. The kernel uses the target of the transaction, Handle 2, to determine that this is intended for Object2a which is in Process 2. 5. The kernel now rewrites the transaction header to be appropriate for Process 2, changing its target to address Object2a. 6. The kernel likewise rewrites the transaction data for the target proc- ess; here it finds that Object1b is not yet known by Process 2, so a new Handle 3 is created for it. 7. The rewritten transaction is delivered to Process 2 for execution. 8. Upon receiving the transaction, the process discovers there is a new Handle 3 and adds this to its table of available handles. If an object within a transaction is already known to the receiving process, the flow is similar, except that now the kernel only needs to rewrite the transaction so that it contains the previously assigned handle or the receiving process’s local ob- ject pointer. This means that sending the same object to a process multiple times will always result in the same identity, unlike Linux file descriptors where opening the same file multiple times will allocate a different descriptor each time. The Binder IPC system maintains unique object identities as those objects move be- tween processes. The Binder architecture essentially introduces a capability-based security model to Linux. Each Binder object is a capability. Sending an object to another process grants that capability to the process. The receiving process may then make use of whatever features the object provides. A process can send an object out to another process, later receive an object from any process, and identify whether that received object is exactly the same object it originally sent out.
clipped_os_Page_820_Chunk7037
SEC. 10.8 ANDROID 821 Binder User-Space API Most user-space code does not directly interact with the Binder kernel module. Instead, there is a user-space object-oriented library that provides a simpler API. The first level of these user-space APIs maps fairly directly to the kernel concepts we have covered so far, in the form of three classes: 1. IBinder is an abstract interface for a Binder object. Its key method is transact, which submits a transaction to the object. The imple- mentation receiving the transaction may be an object either in the local process or in another process; if it is in another process, this will be delivered to it through the Binder kernel module as previously dis- cussed. 2. Binder is a concrete Binder object. Implementing a Binder subclass gives you a class that can be called by other processes. Its key meth- od is onTransact, which receives a transaction that was sent to it. The main responsibility of a Binder subclass is to look at the transaction data it receives here and perform the appropriate operation. 3. Parcel is a container for reading and writing data that is in a Binder transaction. It has methods for reading and writing typed data—inte- gers, strings, arrays—but most importantly it can read and write refer- ences to any IBinder object, using the appropriate data structure for the kernel to understand and transport that reference across processes. Figure 10-46 depicts how these classes work together, modifying Fig. 10-44 that we previously looked at with the user-space classes that are used. Here we see that Binder1b and Binder2a are instances of concrete Binder subclasses. To per- form an IPC, a process now creates a Parcel containing the desired data, and sends it through another class we have not yet seen, BinderProxy. This class is created whenever a new handle appears in a process, thus providing an implementation of IBinder whose transact method creates the appropriate transaction for the call and submits it to the kernel. The kernel transaction structure we had previously looked at is thus split apart in the user-space APIs: the target is represented by a BinderProxy and its data is held in a Parcel. The transaction flows through the kernel as we previously saw and, upon appearing in user space in the receiving process, its target is used to de- termine the appropriate receiving Binder object while a Parcel is constructed from its data and delivered to that object’s onTransact method. These three classes now make it fairly easy to write IPC code: 1. Subclass from Binder. 2. Implement onTransact to decode and execute incoming calls. 3. Implement corresponding code to create a Parcel that can be passed to that object’s transact method.
clipped_os_Page_821_Chunk7038
822 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 Process 1 Binder1b Binder1b Binder1b Parcel transact() BinderProxy (Handle 2) BinderProxy (Handle 3) onTransact() Parcel Binder1b Binder2b Binder2a Process 1 Process 2 Process 2 Handle 1 Handle 1 Handle 2 Handle 3 Handle 3 Handle 3 Handle 2 Transaction Transaction To: Handle 2 From: Process 1 To: Binder2a From: Process 1 Data Data Data Data Data Data Data Data Kernel Figure 10-46. Binder user-space API. The bulk of this work is in the last two steps. This is the unmarshalling and marshalling code that is needed to turn how we’d prefer to program—using sim- ple method calls—into the operations that are needed to execute an IPC. This is boring and error-prone code to write, so we’d like to let the computer take care of that for us. Binder Interfaces and AIDL The final piece of Binder IPC is the one that is most often used, a high-level in- terface-based programming model. Instead of dealing with Binder objects and Parcel data, here we get to think in terms of interfaces and methods. The main piece of this layer is a command-line tool called AIDL (for Android Interface Definition Language). This tool is an interface compiler, taking an ab- stract description of an interface and generating from it the source code necessary to define that interface and implement the appropriate marshalling and unmar- shalling code needed to make remote calls with it. Figure 10-47 shows a simple example of an interface defined in AIDL. This interface is called IExample and contains a single method, print, which takes a sin- gle String argument. package com.example interface IExample { void print(Str ing msg); } Figure 10-47. Simple interface described in AIDL.
clipped_os_Page_822_Chunk7039
SEC. 10.8 ANDROID 823 An interface description like that in Fig. 10-47 is compiled by AIDL to gener- ate three Java-language classes illustrated in Fig. 10-48: 1. IExample supplies the Java-language interface definition. 2. IExample.Stub is the base class for implementations of this inter- face. It inherits from Binder, meaning it can be the recipient of IPC calls; it inherits from IExample, since this is the interface being im- plemented. The purpose of this class is to perform unmarshalling: turn incoming onTransact calls in to the appropriate method call of IExample. A subclass of it is then responsible only for implementing the IExample methods. 3. IExample.Proxy is the other side of an IPC call, responsible for per- forming marshalling of the call. It is a concrete implementation of IExample, implementing each method of it to transform the call into the appropriate Parcel contents and send it off through a transact call on an IBinder it is communicating with. Binder IExample IExample.Stub IExample.Proxy IBinder Figure 10-48. Binder interface inheritance hierarchy. With these classes in place, there is no longer any need to worry about the mechanics of an IPC. Implementors of the IExample interface simply derive from IExample.Stub and implement the interface methods as they normally would. Cal- lers will receive an IExample interface that is implemented by IExample.Proxy, al- lowing them to make regular calls on the interface. The way these pieces work together to perform a complete IPC operation is shown in Fig. 10-49. A simple print call on an IExample interface turns into: 1. IExample.Proxy marshals the method call into a Parcel, calling trans- act on the underlying BinderProxy. 2. BinderProxy constructs a kernel transaction and delivers it to the ker- nel through an ioctl call. 3. The kernel transfers the transaction to the intended process, delivering it to a thread that is waiting in its own ioctl call.
clipped_os_Page_823_Chunk7040
824 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 4. The transaction is decoded back into a Parcel and onTransact called on the appropriate local object, here ExampleImpl (which is a sub- class of IExample.Stub). 5. IExample.Stub decodes the Parcel into the appropriate method and arguments to call, here calling print. 6. The concrete implementation of print in ExampleImpl finally ex- ecutes. Process 1 Kernel Process 2 Examplelmpl IExample print("hello") print("hello") IExample.Proxy IExample.Stub transact({print hello}) onTransact({print hello}) Binder BinderProxy ioctl() ioctl() binder_module Figure 10-49. Full path of an AIDL-based Binder IPC. The bulk of Android’s IPC is written using this mechanism. Most services in Android are defined through AIDL and implemented as shown here. Recall the previous Fig. 10-40 showing how the implementation of the package manager in the system server process uses IPC to publish itself with the service manager for other processes to make calls to it. Tw o AIDL interfaces are involved here: one for the service manager and one for the package manager. For example, Fig. 10-50 shows the basic AIDL description for the service manager; it contains the getSer- vice method, which other processes use to retrieve the IBinder of system service interfaces like the package manager. 10.8.8 Android Applications Android provides an application model that is very different from the normal command-line environment in the Linux shell or even applications launched from a graphical user interface. An application is not an executable file with a main entry point; it is a container of everything that makes up that app: its code, graphical re- sources, declarations about what it is to the system, and other data.
clipped_os_Page_824_Chunk7041
SEC. 10.8 ANDROID 825 package android.os interface IServiceManager { IBinder getService(Str ing name); void addService(Str ing name, IBinder binder); } Figure 10-50. Basic service manager AIDL interface. An Android application by convention is a file with the apk extension, for Android Package. This file is actually a normal zip archive, containing everything about the application. The important contents of an apk are: 1. A manifest describing what the application is, what it does, and how to run it. The manifest must provide a package name for the applica- tion, a Java-style scoped string (such as com.android.app.calculator), which uniquely identifies it. 2. Resources needed by the application, including strings it displays to the user, XML data for layouts and other descriptions, graphical bit- maps, etc. 3. The code itself, which may be Dalvik bytecode as well as native li- brary code. 4. Signing information, securely identifying the author. The key part of the application for our purposes here is its manifest, which ap- pears as a precompiled XML file named AndroidManifest.xml in the root of the apk’s zip namespace. A complete example manifest declaration for a hypothetical email application is shown in Fig. 10-51: it allows you to view and compose emails and also includes components needed for synchronizing its local email storage with a server even when the user is not currently in the application. Android applications do not have a simple main entry point which is executed when the user launches them. Instead, they publish under the manifest’s <applica- tion> tag a variety of entry points describing the various things the application can do. These entry points are expressed as four distinct types, defining the core types of behavior that applications can provide: activity, receiver, service, and content provider. The example we have presented shows a few activities and one declara- tion of the other component types, but an application may declare zero or more of any of these. Each of the different four component types an application can contain has dif- ferent semantics and uses within the system. In all cases, the android:name attrib- ute supplies the Java class name of the application code implementing that compo- nent, which will be instantiated by the system when needed.
clipped_os_Page_825_Chunk7042
826 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.email"> <application> <activity android:name="com.example.email.MailMainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <categor y android:name="android.intent.categor y.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.email.ComposeActivity"> <intent-filter> <action android:name="android.intent.action.SEND" /> <categor y android:name="android.intent.categor y.DEFAULT" /> <data android:mimeType="*/*" /> </intent-filter> </activity> <ser vice android:name="com.example.email.SyncSer vice"> </ser vice> <receiver android:name="com.example.email.SyncControlReceiver"> <intent-filter> <action android:name="android.intent.action.DEVICE STORAGE LOW" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.DEVICE STORAGE OKAY" /> </intent-filter> </receiver> <provider android:name="com.example.email.EmailProvider" android:author ities="com.example.email.provider.email"> </provider> </application> </manifest> Figure 10-51. Basic structure of AndroidManifest.xml. The package manager is the part of Android that keeps track of all application packages. It parses every application’s manifest, collecting and indexing the infor- mation it finds in them. With that information, it then provides facilities for clients to query it about the currently installed applications and retrieve relevant infor- mation about them. It is also responsible for installing applications (creating stor- age space for the application and ensuring the integrity of the apk) as well as ev erything needed to uninstall (cleaning up everything associated with a previously installed app).
clipped_os_Page_826_Chunk7043
SEC. 10.8 ANDROID 827 Applications statically declare their entry points in their manifest so they do not need to execute code at install time that registers them with the system. This design makes the system more robust in many ways: installing an application does not require running any application code, the top-level capabilities of the applica- tion can always be determined by looking at the manifest, there is no need to keep a separate database of this information about the application which can get out of sync (such as across updates) with the application’s actual capabilities, and it guar- antees no information about an application can be left around after it is uninstalled. This decentralized approach was taken to avoid many of these types of problems caused by Windows’ centralized Registry. Breaking an application into finer-grained components also serves our design goal of supporting interoperation and collaboration between applications. Applica- tions can publish pieces of themselves that provide specific functionality, which other applications can make use of either directly or indirectly. This will be illus- trated as we look in more detail at the four kinds of components that can be pub- lished. Above the package manager sits another important system service, the activity manager. While the package manager is responsible for maintaining static infor- mation about all installed applications, the activity manager determines when, where, and how those applications should run. Despite its name, it is actually responsible for running all four types of application components and implementing the appropriate behavior for each of them. Activities An activity is a part of the application that interacts directly with the user through a user interface. When the user launches an application on their device, this is actually an activity inside the application that has been designated as such a main entry point. The application implements code in its activity that is responsi- ble for interacting with the user. The example email manifest shown in Fig. 10-51 contains two activities. The first is the main mail user interface, allowing users to view their messages; the sec- ond is a separate interface for composing a new message. The first mail activity is declared as the main entry point for the application, that is, the activity that will be started when the user launches it from the home screen. Since the first activity is the main activity, it will be shown to users as an appli- cation they can launch from the main application launcher. If they do so, the sys- tem will be in the state shown in Fig. 10-52. Here the activity manager, on the left side, has made an internal ActivityRecord instance in its process to keep track of the activity. One or more of these activities are organized into containers called tasks, which roughly correspond to what the user experiences as an application. At this point the activity manager has started the email application’s process and an instance of its MainMailActivity for displaying its main UI, which is associated
clipped_os_Page_827_Chunk7044
828 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 with the appropriate ActivityRecord. This activity is in a state called resumed since it is now in the foreground of the user interface. Activity manager in system_server process Email app process MailMainActivity Task: Email ActivityRecord (MailMainActivity) RESUMED Figure 10-52. Starting an email application’s main activity. If the user were now to switch away from the email application (not exiting it) and launch a camera application to take a picture, we would be in the state shown in Fig. 10-53. Note that we now hav e a new camera process running the camera’s main activity, an associated ActivityRecord for it in the activity manager, and it is now the resumed activity. Something interesting also happens to the previous email activity: instead of being resumed, it is now stopped and the ActivityRecord holds this activity’s saved state. Activity manager in system_server process Camera app process Email app process MailMainActivity CameraMainActivity Task: Camera ActivityRecord (CameraMainActivity) ActivityRecord (MailMainActivity) Saved state STOPPED RESUMED Task: Email Figure 10-53. Starting the camera application after email. When an activity is no longer in the foreground, the system asks it to ‘‘save its state.’’ This involves the application creating a minimal amount of state infor- mation representing what the user currently sees, which it returns to the activity
clipped_os_Page_828_Chunk7045
SEC. 10.8 ANDROID 829 manager and stores in the system server process, in the ActivityRecord associated with that activity. The saved state for an activity is generally small, containing for example where you are scrolled in an email message, but not the message itself, which will be stored elsewhere by the application in its persistent storage. Recall that although Android does demand paging (it can page in and out clean RAM that has been mapped from files on disk, such as code), it does not rely on swap space. This means all dirty RAM pages in an application’s process must stay in RAM. Having the email’s main activity state safely stored away in the activity manager gives the system back some of the flexibility in dealing with memory that swap provides. For example, if the camera application starts to require a lot of RAM, the sys- tem can simply get rid of the email process, as shown in Fig. 10-54. The Activi- tyRecord, with its precious saved state, remains safely tucked away by the activity manager in the system server process. Since the system server process hosts all of Android’s core system services, it must always remain running, so the state saved here will remain around for as long as we might need it. Activity manager in system_server process Camera app process CameraMainActivity Task: Camera ActivityRecord (CameraMainActivity) ActivityRecord (MailMainActivity) Task: Email Saved state STOPPED RESUMED Figure 10-54. Removing the email process to reclaim RAM for the camera. Our example email application not only has an activity for its main UI, but in- cludes another ComposeActivity. Applications can declare any number of activities they want. This can help organize the implementation of an application, but more importantly it can be used to implement cross-application interactions. For ex- ample, this is the basis of Android’s cross-application sharing system, which the ComposeActivity here is participating in. If the user, while in the camera applica- tion, decides she wants to share a picture she took, our email application’s Com- poseActivity is one of the sharing options she has. If it is selected, that activity will
clipped_os_Page_829_Chunk7046
830 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 be started and given the picture to be shared. (Later we will see how the camera application is able to find the email application’s ComposeActivity.) Performing that share option while in the activity state seen in Fig. 10-54 will lead to the new state in Fig. 10-55. There are a number of important things to note: 1. The email app’s process must be started again, to run its ComposeAc- tivity. 2. However, the old MailMainActivity is not started at this point, since it is not needed. This reduces RAM use. 3. The camera’s task now has two records: the original CameraMainAc- tivity we had just been in, and the new ComposeActivity that is now displayed. To the user, these are still one cohesive task: it is the cam- era currently interacting with them to email a picture. 4. The new ComposeActivity is at the top, so it is resumed; the previous CameraMainActivity is no longer at the top, so its state has been saved. We can at this point safely quit its process if its RAM is need- ed elsewhere. Activity manager in system_server process Email app process ActivityRecord (ComposeActivity) ActivityRecord (CameraMainActivity) ActivityRecord (MailMainActivity) Saved state Saved state STOPPED STOPPED RESUMED Task: Camera ComposeActivity CameraMainActivity Camera app process Task: Email Figure 10-55. Sharing a camera picture through the email application. Finally let us look at would happen if the user left the camera task while in this last state (that is, composing an email to share a picture) and returned to the email
clipped_os_Page_830_Chunk7047
SEC. 10.8 ANDROID 831 application. Figure 10-56 shows the new state the system will be in. Note that we have brought the email task with its main activity back to the foreground. This makes MailMainActivity the foreground activity, but there is currently no instance of it running in the application’s process. Activity manager in system_server process Email app process Camera app process MailMainActivity ComposeActivity CameraMainActivity Saved state Saved state STOPPED STOPPED RESUMED Task: Email Task: Camera ActivityRecord (MailMainActivity) ActivityRecord (ComposeActivity) ActivityRecord (CameraMainActivity) Figure 10-56. Returning to the email application. To return to the previous activity, the system makes a new instance, handing it back the previously saved state the old instance had provided. This action of restoring an activity from its saved state must be able to bring the activity back to the same visual state as the user last left it. To accomplish this, the application will look in its saved state for the message the user was in, load that message’s data from its persistent storage, and then apply any scroll position or other user-inter- face state that had been saved. Services A service has two distinct identities: 1. It can be a self-contained long-running background operation. Com- mon examples of using services in this way are performing back- ground music playback, maintaining an active network connection (such as with an IRC server) while the user is in other applications, downloading or uploading data in the background, etc.
clipped_os_Page_831_Chunk7048
832 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 2. It can serve as a connection point for other applications or the system to perform rich interaction with the application. This can be used by applications to provide secure APIs for other applications, such as to perform image or audio processing, provide a text to speech, etc. The example email manifest shown in Fig. 10-51 contains a service that is used to perform synchronization of the user’s mailbox. A common implementation would schedule the service to run at a regular interval, such as every 15 minutes, starting the service when it is time to run, and stopping itself when done. This is a typical use of the first style of service, a long-running background op- eration. Figure 10-57 shows the state of the system in this case, which is quite simple. The activity manager has created a ServiceRecord to keep track of the ser- vice, noting that it has been started, and thus created its SyncService instance in the application’s process. While in this state the service is fully active (barring the en- tire system going to sleep if not holding a wake lock) and free to do what it wants. It is possible for the application’s process to go away while in this state, such as if the process crashes, but the activity manager will continue to maintain its Ser- viceRecord and can at that point decide to restart the service if desired. Activity manager in system_server process Email app process SyncService ServiceRecord (SyncService) STARTED Figure 10-57. Starting an application service. To see how one can use a service as a connection point for interaction with other applications, let us say that we want to extend our existing SyncService to have an API that allows other applications to control its sync interval. We will need to define an AIDL interface for this API, like the one shown in Fig. 10-58. package com.example.email interface ISyncControl { int getSyncInterval(); void setSyncInterval(int seconds); } Figure 10-58. Interface for controlling a sync service’s sync interval. To use this, another process can bind to our application service, getting access to its interface. This creates a connection between the two applications, shown in Fig. 10-59. The steps of this process are:
clipped_os_Page_832_Chunk7049
SEC. 10.8 ANDROID 833 1. The client application tells the activity manager that it would like to bind to the service. 2. If the service is not already created, the activity manager creates it in the service application’s process. 3. The service returns the IBinder for its interface back to the activity manager, which now holds that IBinder in its ServiceRecord. 4. Now that the activity manager has the service IBinder, it can be sent back to the original client application. 5. The client application now having the service’s IBinder may proceed to make any direct calls it would like on its interface. Activity manager in system_server process Email app process 2. Create 3. Return 4. Send 1. Bind Client app process 5. Call service SyncService IBinder IBinder IBinder IBinder IBinder ServiceRecord (SyncService) STOPPED Figure 10-59. Binding to an application service. Receivers A receiver is the recipient of (typically external) events that happen, generally in the background and outside of normal user interaction. Receivers conceptually are the same as an application explicitly registering for a callback when something interesting happens (an alarm goes off, data connectivity changes, etc), but do not require that the application be running in order to receive the event. The example email manifest shown in Fig. 10-51 contains a receiver for the application to find out when the device’s storage becomes low in order for it to stop synchronizing email (which may consume more storage). When the device’s storage becomes low, the system will send a broadcast with the low storage code, to be delivered to all receivers interested in the event. Figure 10-60 illustrates how such a broadcast is processed by the activity man- ager in order to deliver it to interested receivers. It first asks the package manager
clipped_os_Page_833_Chunk7050
834 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 for a list of all receivers interested in the event, which is placed in a Broadcast- Record representing that broadcast. The activity manager will then proceed to step through each entry in the list, having each associated application’s process create and execute the appropriate receiver class. Activity manager in system_server process Calendar app process Email app process Browser app process SyncControlReceiver SyncControlReceiver CleanupReceiver BroadcastRecord DEVICE_STORAGE_LOW SyncControlReceiver (Calendar app) SyncControlReceiver (Email app) CleanupReceiver (Browser app) Figure 10-60. Sending a broadcast to application receivers. Receivers only run as one-shot operations. When an event happens, the system finds any receivers interested in it, delivers that event to them, and once they hav e consumed the event they are done. There is no ReceiverRecord like those we have seen for other application components, because a particular receiver is only a tran- sient entity for the duration of a single broadcast. Each time a new broadcast is sent to a receiver component, a new instance of that receiver’s class is created. Content Providers Our last application component, the content provider, is the primary mechan- ism that applications use to exchange data with each other. All interactions with a content provider are through URIs using a content: scheme; the authority of the URI is used to find the correct content-provider implementation to interact with. For example, in our email application from Fig. 10-51, the content provider specifies that its authority is com.example.email.provider.email. Thus URIs operat- ing on this content provider would start with content://com.example.email.provider.email/ The suffix to that URI is interpreted by the provider itself to determine which data within it is being accessed. In the example here, a common convention would be that the URI
clipped_os_Page_834_Chunk7051
SEC. 10.8 ANDROID 835 content://com.example.email.provider.email/messages means the list of all email messages, while content://com.example.email.provider.email/messages/1 provides access to a single message at key number 1. To interact with a content provider, applications always go through a system API called ContentResolver, where most methods have an initial URI argument indicating the data to operate on. One of the most often used ContentResolver methods is query, which performs a database query on a given URI and returns a Cursor for retrieving the structured results. For example, retrieving a summary of all of the available email messages would look something like: quer y("content://com.example.email.provider.email/messages") Though this does not look like it to applications, what is actually going on when they use content providers has many similarities to binding to services. Fig- ure 10-61 illustrates how the system handles our query example: 1. The application calls ContentResolver.query to initiate the operation. 2. The URI’s authority is handed to the activity manager for it to find (via the package manager) the appropriate content provider. 3. If the content provider is not already running, it is created. 4. Once created, the content provider returns to the activity manager its IBinder implementing the system’s IContentProvider interface. 5. The content provider’s Binder is returned to the ContentResolver. 6. The content resolver can now complete the initial query operation by calling the appropriate method on the AIDL interface, returning the Cursor result. Content providers are one of the key mechanisms for performing interactions across applications. For example, if we return to the cross-application sharing sys- tem previously described in Fig. 10-55, content providers are the way data is ac- tually transferred. The full flow for this operation is: 1. A share request that includes the URI of the data to be shared is creat- ed and is submitted to the system. 2. The system asks the ContentResolver for the MIME type of the data behind that URI; this works much like the query method we just dis- cussed, but asks the content provider to return a MIME-type string for the URI.
clipped_os_Page_835_Chunk7052
836 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 Activity manager in system_server process Email app process ProviderRecord (EmailProvider) EmailProvider ContentResolver 1. query() Client app process 3. Create IBinder IContentProvider.Stub IContentProvider.Proxy 4. Return 5. Return 2. Look up Authority IBinder IBinder 6. query() Figure 10-61. Interacting with a content provider. 3. The system finds all activities that can receive data of the identified MIME type. 4. A user interface is shown for the user to select one of the possible re- cipients. 5. When one of these activities is selected, the system launches it. 6. The share-handling activity receives the URI of the data to be shared, retrieves its data through ContentResolver, and performs its ap- propriate operation: creates an email, stores it, etc.. 10.8.9 Intents A detail that we have not yet discussed in the application manifest shown in Fig. 10-51 is the <intent-filter> tags included with the activities and receiver decla- rations. This is part of the intent feature in Android, which is the cornerstone for how different applications identify each other in order to be able to interact and work together. An intent is the mechanism Android uses to discover and identify activities, receivers, and services. It is similar in some ways to the Linux shell’s search path, which the shell uses to look through multiple possible directories in order to find an executable matching command names given to it. There are two major types of intents: explicit and implicit. An explicit intent is one that directly identifies a single specific application component; in Linux shell terms it is the equivalent to supplying an absolute path to a command. The
clipped_os_Page_836_Chunk7053
SEC. 10.8 ANDROID 837 most important part of such an intent is a pair of strings naming the component: the package name of the target application and class name of the component within that application. Now referring back to the activity of Fig. 10-52 in application Fig. 10-51, an explicit intent for this component would be one with package name com.example.email and class name com.example.email.MailMainActivity. The package and class name of an explicit intent are enough information to uniquely identify a target component, such as the main email activity in Fig. 10-52. From the package name, the package manager can return everything needed about the application, such as where to find its code. From the class name, we know which part of that code to execute. An implicit intent is one that describes characteristics of the desired compo- nent, but not the component itself; in Linux shell terms this is the equivalent to supplying a single command name to the shell, which it uses with its search path to find a concrete command to be run. This process of finding the component match- ing an implicit intent is called intent resolution. Android’s general sharing facility, as we previously saw in Fig. 10-55’s illus- tration of sharing a photo the user took from the camera through the email applica- tion, is a good example of implicit intents. Here the camera application builds an intent describing the action to be done, and the system finds all activities that can potentially perform that action. A share is requested through the intent action android.intent.action.SEND, and we can see in Fig. 10-51 that the email applica- tion’s compose activity declares that it can perform this action. There can be three outcomes to an intent resolution: (1) no match is found, (2) a single unique match is found, or (3) there are multiple activities that can handle the intent. An empty match will result in either an empty result or an exception, depending on the expectations of the caller at that point. If the match is unique, then the system can immediately proceed to launching the now explicit intent. If the match is not unique, we need to somehow resolve it in another way to a single result. If the intent resolves to multiple possible activities, we cannot just launch all of them; we need to pick a single one to be launched. This is accomplished through a trick in the package manager. If the package manager is asked to resolve an intent down to a single activity, but it finds there are multiple matches, it instead resolves the intent to a special activity built into the system called the ResolverActivity. This activity, when launched, simply takes the original intent, asks the package manager for a list of all matching activities, and displays these for the user to select a single desired action. When one is selected, it creates a new explicit intent from the original intent and the selected activity, calling the system to have that new activity started. Android has another similarity with the Linux shell: Android’s graphical shell, the launcher, runs in user space like any other application. An Android launcher performs calls on the package manager to find the available activities and launch them when selected by the user.
clipped_os_Page_837_Chunk7054
838 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 10.8.10 Application Sandboxes Traditionally in operating systems, applications are seen as code executing as the user, on the user’s behalf. This behavior has been inherited from the command line, where you run the ls command and expect that to run as your identity (UID), with the same access rights as you have on the system. In the same way, when you use a graphical user interface to launch a game you want to play, that game will ef- fectively run as your identity, with access to your files and many other things it may not actually need. This is not, however, how we mostly use computers today. We run applica- tions we acquired from some less trusted third-party source, that have sweeping functionality, which will do a wide variety of things in their environment that we have little control over. There is a disconnect between the application model sup- ported by the operating system and the one actually in use. This may be mitigated by strategies such as distinguishing between normal and ‘‘admin’’ user privileges and warning the first time they are running an application, but those do not really address the underlying disconnect. In other words, traditional operating systems are very good at protecting users from other users, but not in protecting users from themselves. All programs run with the power of the user and, if any of them misbehaves, it can do all the damage the user can do. Think about it: how much damage could you do in, say, a UNIX environment? You could leak all information accessible to the user. You could perform rm -rf * to give yourself a nice, empty home directory. And if the program is not just buggy, but also malicious, it could encrypt all your files for ransom. Running everything with ‘‘the power of you’’ is dangerous! Android attempts to address this with a core premise: that an application is ac- tually the developer of that application running as a guest on the user’s device. Thus an application is not trusted with anything sensitive that is not explicitly approved by the user. In Android’s implementation, this philosophy is rather directly expressed through user IDs. When an Android application is installed, a new unique Linux user ID (or UID) is created for it, and all of its code runs as that ‘‘user.’’ Linux user IDs thus create a sandbox for each application, with their own isolated area of the file system, just as they create sandboxes for users on a desktop system. In other words, Android uses an existing feature in Linux, but in a novel way. The result is better isolation. 10.8.11 Security Application security in Android revolves around UIDs. In Linux, each process runs as a specific UID, and Android uses the UID to identify and protect security barriers. The only way to interact across processes is through some IPC mechan- ism, which generally carries with it enough information to identify the UID of the
clipped_os_Page_838_Chunk7055
SEC. 10.8 ANDROID 839 caller. Binder IPC explicitly includes this information in every transaction deliv- ered across processes so a recipient of the IPC can easily ask for the UID of the caller. Android predefines a number of standard UIDs for the lower-level parts of the system, but most applications are dynamically assigned a UID, at first boot or in- stall time, from a range of ‘‘application UIDs.’’ Figure 10-62 illustrates some com- mon mappings of UID values to their meanings. UIDs below 10000 are fixed assignments within the system for dedicated hardware or other specific parts of the implementation; some typical values in this range are shown here. In the range 10000–19999 are UIDs dynamically assigned to applications by the package man- ager when it installs them; this means at most 10,000 applications can be installed on the system. Also note the range starting at 100000, which is used to implement a traditional multiuser model for Android: an application that is granted UID 10002 as its identity would be identified as 110002 when running as a second user. UID Purpose 0 Root 1000 Core system (system ser ver process) 1001 Telephony ser vices 1013 Low-level media processes 2000 Command line shell access 10000–19999 Dynamically assigned application UIDs 100000 Start of secondar y users Figure 10-62. Common UID assignments in Android When an application is first assigned a UID, a new storage directory is created for it, with the files there owned by its UID. The application gets free access to its private files there, but cannot access the files of other applications, nor can the other applications touch its own files. This makes content providers, as discussed in the earlier section on applications, especially important, as they are one of the few mechanisms that can transfer data between applications. Even the system itself, running as UID 1000, cannot touch the files of applica- tions. This is why the installd daemon exists: it runs with special privileges to be able to access and create files and directories for other applications. There is a very restricted API installd provides to the package manager for it to create and manage the data directories of applications as needed. In their base state, Android’s application sandboxes must disallow any cross-application interactions that can violate security between them. This may be for robustness (preventing one app from crashing another app), but most often it is about information access. Consider our camera application. When the user takes a picture, the camera application stores that picture in its private data space. No other applications can
clipped_os_Page_839_Chunk7056
840 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 access that data, which is what we want since the pictures there may be sensitive data to the user. After the user has taken a picture, she may want to email it to a friend. Email is a separate application, in its own sandbox, with no access to the pictures in the camera application. How can the email application get access to the pictures in the camera application’s sandbox? The best-known form of access control in Android is application permissions. Permissions are specific well-defined abilities that can be granted to an application at install time. The application lists the permissions it needs in its manifest, and prior to installing the application the user is informed of what it will be allowed to do based on them. Figure 10-63 shows how our email application could make use of permissions to access pictures in the camera application. In this case, the camera application has associated the READ PICTURES permission with its pictures, saying that any application holding that permission can access its picture data. The email applica- tion declares in its manifest that it requires this permission. The email application can now access a URI owned by the camera, such as content://pics/1; upon receiv- ing the request for this URI, the camera app’s content provider asks the package manager whether the caller holds the necessary permission. If it does, the call suc- ceeds and appropriate data is returned to the application. Package manager in system_server process Camera app process PicturesProvider Authority: "pics" ComposeActivity Email app process Receive data Open content://pics/1 Check Allow Email package UID Granted permissions READ_CONTACTS READ_PICTURES INTERNET Browser package UID Granted permissions INTERNET Figure 10-63. Requesting and using a permission. Permissions are not tied to content providers; any IPC into the system may be protected by a permission through the system’s asking the package manager if the caller holds the required permission. Recall that application sandboxing is based
clipped_os_Page_840_Chunk7057
SEC. 10.8 ANDROID 841 on processes and UIDs, so a security barrier always happens at a process boundary, and permissions themselves are associated with UIDs. Given this, a permission check can be performed by retrieving the UID associated with the incoming IPC and asking the package manager whether that UID has been granted the correspon- ding permission. For example, permissions for accessing the user’s location are enforced by the system’s location manager service when applications call in to it. Figure 10-64 illustrates what happens when an application does not hold a per- mission needed for an operation it is performing. Here the browser application is trying to directly access the user’s pictures, but the only permission it holds is one for network operations over the Internet. In this case the PicturesProvider is told by the package manager that the calling process does not hold the needed READ PICTURES permission, and as a result throws a SecurityException back to it. Package manager in system_server process Camera app process PicturesProvider Authority: "pics" Security exception Open content://pics/1 Check Browser app process BrowserMainActivity Deny Email package UID Granted permissions READ_CONTACTS READ_PICTURES INTERNET Browser package UID Granted permissions INTERNET Figure 10-64. Accessing data without a permission. Permissions provide broad, unrestricted access to classes of operations and data. They work well when an application’s functionality is centered around those operations, such as our email application requiring the INTERNET permission to send and receive email. However, does it make sense for the email application to hold a READ PICTURES permission? There is nothing about an email application that is directly related to reading your pictures, and no reason for an email applica- tion to have access to all of your pictures. There is another issue with this use of permissions, which we can see by re- turning to Fig. 10-55. Recall how we can launch the email application’s Com- poseActivity to share a picture from the camera application. The email application
clipped_os_Page_841_Chunk7058
842 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 receives a URI of the data to share, but does not know where it came from—in the figure here it comes from the camera, but any other application could use this to let the user email its data, from audio files to word-processing documents. The email application only needs to read that URI as a byte stream to add it as an attachment. However, with permissions it would also have to specify up-front the permissions for all of the data of all of the applications it may be asked to send an email from. We hav e two problems to solve. First, we do not want to give applications ac- cess to wide swaths of data that they do not really need. Second, they need to be given access to any data sources, even ones they do not have a priori knowledge about. There is an important observation to make: the act of emailing a picture is ac- tually a user interaction where the user has expressed a clear intent to use a specific picture with a specific application. As long as the operating system is involved in the interaction, it can use this to identify a specific hole to open in the sandboxes between the two applications, allowing that data through. Android supports this kind of implicit secure data access through intents and content providers. Figure 10-65 illustrates how this situation works for our picture emailing example. The camera application at the bottom-left has created an intent asking to share one of its images, content://pics/1. In addition to starting the email compose application as we had seen before, this also adds an entry to a list of ‘‘granted URIs,’’ noting that the new ComposeActivity now has access to this URI. Now when ComposeActivity looks to open and read the data from the URI it has been given, the camera application’s PicturesProvider that owns the data behind the URI can ask the activity manager if the calling email application has access to the data, which it does, so the picture is returned. This fine-grained URI access control can also operate the other way. There is another intent action, android.intent.action.GET CONTENT, which an application can use to ask the user to pick some data and return to it. This would be used in our email application, for example, to operate the other way around: the user while in the email application can ask to add an attachment, which will launch an activity in the camera application for them to select one. Figure 10-66 illustrates this new flow. It is almost identical to Fig. 10-65, the only difference being in the way the activities of the two applications are com- posed, with the email application starting the appropriate picture-selection activity in the camera application. Once an image is selected, its URI is returned back to the email application, and at this point our URI grant is recorded by the activity manager. This approach is extremely powerful, since it allows the system to maintain tight control over per-application data, granting specific access to data where need- ed, without the user needing to be aware that this is happening. Many other user interactions can also benefit from it. An obvious one is drag and drop to create a similar URI grant, but Android also takes advantage of other information such as current window focus to determine the kinds of interactions applications can have.
clipped_os_Page_842_Chunk7059
SEC. 10.8 ANDROID 843 Activity manager in system_server process Camera app process Granted URIs Task: Pictures SEND content://pics/1 Saved state STOPPED RESUMED ActivityRecord (ComposeActivity) ActivityRecord (CameraActivity) To: ComposeActivity URI: content://pics/1 Allow Check PicturesProvider Authority: "pics" ComposeActivity Email app process Open content://pics/1 Receive data Figure 10-65. Sharing a picture using a content provider. A final common security method Android uses is explicit user interfaces for al- lowing/removing specific types of access. In this approach, there is some way an application indicates it can optionally provide some functionally, and a sys- tem-supplied trusted user interface that provides control over this access. A typical example of this approach is Android’s input-method architecture. An input method is a specific service supplied by a third-party application that al- lows the user to provide input to applications, typically in the form of an on-screen keyboard. This is a highly sensitive interaction in the system, since a lot of person- al data will go through the input-method application, including passwords the user types. An application indicates it can be an input method by declaring a service in its manifest with an intent filter matching the action for the system’s input-method protocol. This does not, however, automatically allow it to become an input meth- od, and unless something else happens the application’s sandbox has no ability to operate like one. Android’s system settings include a user interface for selecting input methods. This interface shows all available input methods of the currently installed applica- tions and whether or not they are enabled. If the user wants to use a new input method after they hav e installed its application, they must go to this system settings interface and enable it. When doing that, the system can also inform the user of the kinds of things this will allow the application to do.
clipped_os_Page_843_Chunk7060
844 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 Activity manager in system_server process Camera app process PicturesProvider Authority: "pics" ComposeActivity Email app process Granted URls Allow Check Open content://pics/1 Receive data To: ComposeActivity URI: content://pics/1 Task: Pictures ActivityRecord (PicturePickerActivity) ActivityRecord (ComposeActivity) Saved state RESUMED STOPPED RECEIVE content://pics/1 GET Figure 10-66. Adding a picture attachment using a content provider. Even once an application is enabled as an input method, Android uses fine- grained access-control techniques to limit its impact. For example, only the appli- cation that is being used as the current input method can actually have any special interaction; if the user has enabled multiple input methods (such as a soft keyboard and voice input), only the one that is currently in active use will have those features available in its sandbox. Even the current input method is restricted in what it can do, through additional policies such as only allowing it to interact with the window that currently has input focus. 10.8.12 Process Model The traditional process model in Linux is a fork to create a new process, fol- lowed by an exec to initialize that process with the code to be run and then start its execution. The shell is responsible for driving this execution, forking and execut- ing processes as needed to run shell commands. When those commands exit, the process is removed by Linux. Android uses processes somewhat differently. As discussed in the previous section on applications, the activity manager is the part of Android responsible for managing running applications. It coordinates the launching of new application processes, determines what will run in them, and when they are no longer needed.
clipped_os_Page_844_Chunk7061
SEC. 10.8 ANDROID 845 Starting Processes In order to launch new processes, the activity manager must communicate with the zygote. When the activity manager first starts, it creates a dedicated socket with zygote, through which it sends a command when it needs to start a process. The command primarily describes the sandbox to be created: the UID that the new process should run as and any other security restrictions that will apply to it. Zygote thus must run as root: when it forks, it does the appropriate setup for the UID it will run as, finally dropping root privileges and changing the process to the desired UID. Recall in our previous discussion about Android applications that the activity manager maintains dynamic information about the execution of activities (in Fig. 10-52), services (Fig. 10-57), broadcasts (to receivers as in Fig. 10-60), and content providers (Fig. 10-61). It uses this information to drive the creation and management of application processes. For example, when the application launcher calls in to the system with a new intent to start an activity as we saw in Fig. 10-52, it is the activity manager that is responsible for making that new application run. The flow for starting an activity in a new process is shown in Fig. 10-67. The details of each step in the illustration are: 1. Some existing process (such as the app launcher) calls in to the activ- ity manager with an intent describing the new activity it would like to have started. 2. Activity manager asks the package manager to resolve the intent to an explicit component. 3. Activity manager determines that the application’s process is not al- ready running, and then asks zygote for a new process of the ap- propriate UID. 4. Zygote performs a fork, creating a new process that is a clone of itself, drops privileges and sets its UID appropriately for the application’s sandbox, and finishes initialization of Dalvik in that process so that the Java runtime is fully executing. For example, it must start threads like the garbage collector after it forks. 5. The new process, now a clone of zygote with the Java environment fully up and running, calls back to the activity manager, asking ‘‘What am I supposed to do?’’ 6. Activity manager returns back the full information about the applica- tion it is starting, such as where to find its code. 7. New process loads the code for the application being run.
clipped_os_Page_845_Chunk7062
846 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 8. Activity manager sends to the new process any pending operations, in this case ‘‘start activity X.’’ 9. New process receives the command to start an activity, instantiates the appropriate Java class, and executes it. System_server process Application process Activity instance Application code Android framework PackageManagerService startActivity() ActivityManagerService "Who am I?" Load this app s code Instantiate this class Zygote process Create a new process Resolve Intent 2 1 3 5 6 8 9 7 4 Figure 10-67. Steps in launching a new application process. Note that when we started this activity, the application’s process may already have been running. In that case, the activity manager will simply skip to the end, sending a new command to the process telling it to instantiate and run the ap- propriate component. This can result in an additional activity instance running in the application, if appropriate, as we saw previously in Fig. 10-56. Process Lifecycle The activity manager is also responsible for determining when processes are no longer needed. It keeps track of all activities, receivers, services, and content providers running in a process; from this it can determine how important (or not) the process is. Recall that Android’s out-of-memory killer in the kernel uses a process’s oom adj as a strict ordering to determine which processes it should kill first. The activity manager is responsible for setting each process’s oom adj appropriately
clipped_os_Page_846_Chunk7063
SEC. 10.8 ANDROID 847 based on the state of that process, by classifying them into major categories of use. Figure 10-68 shows the main categories, with the most important category first. The last column shows a typical oom adj value that is assigned to processes of this type. Categor y Description oom adj SYSTEM The system and daemon processes −16 PERSISTENT Always-r unning application processes −12 FOREGROUND Currently interacting with user 0 VISIBLE Visible to user 1 PERCEPTIBLE Something the user is aware of 2 SERVICE Running background services 3 HOME The home/launcher process 4 CACHED Processes not in use 5 Figure 10-68. Process importance categories. Now, when RAM is getting low, the system has configured the processes so that the out-of-memory killer will first kill cached processes to try to reclaim enough needed RAM, followed by home, service, and on up. Within a specific oom adj level, it will kill processes with a larger RAM footprint before smaller ones. We’v e now seen how Android decides when to start processes and how it cate- gorizes those processes in importance. Now we need to decide when to have proc- esses exit, right? Or do we really need to do anything more here? The answer is, we do not. On Android, application processes never cleanly exit. The system just leaves unneeded processes around, relying on the kernel to reap them as needed. Cached processes in many ways take the place of the swap space that Android lacks. As RAM is needed elsewhere, cached processes can be thrown out of active RAM. If an application later needs to run again, a new process can be created, restoring any previous state needed to return it to how the user last left it. Behind the scenes, the operating system is launching, killing, and relaunching processes as needed so the important foreground operations remain running and cached proc- esses are kept around as long as their RAM would not be better used elsewhere. Process Dependencies We at this point have a good overview of how individual Android processes are managed. There is a further complication to this, however: dependencies between processes. As an example, consider our previous camera application holding the pictures that have been taken. These pictures are not part of the operating system; they are
clipped_os_Page_847_Chunk7064
848 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 implemented by a content provider in the camera application. Other applications may want to access that picture data, becoming a client of the camera application. Dependencies between processes can happen with both content providers (through simple access to the provider) and services (by binding to a service). In either case, the operating system must keep track of these dependencies and man- age the processes appropriately. Process dependencies impact two key things: when processes will be created (and the components created inside of them), and what the oom adj importance of the process will be. Recall that the importance of a process is that of the most im- portant component in it. Its importance is also that of the most important process that is dependent on it. For example, in the case of the camera application, its process and thus its con- tent provider is not normally running. It will be created when some other process needs to access that content provider. While the camera’s content provider is being accessed, the camera process will be considered at least as important as the process that is using it. To compute the final importance of every process, the system needs to main- tain a dependency graph between those processes. Each process has a list of all services and content providers currently running in it. Each service and content provider itself has a list of each process using it. (These lists are maintained in records inside the activity manager, so it is not possible for applications to lie about them.) Walking the dependency graph for a process involves walking through all of its content providers and services and the processes using them. Figure 10-69 illustrates a typical state processes can be in, taking into account dependencies between them. This example contains two dependencies, based on using a camera-content provider to add a picture attachment to an email as dis- cussed in Fig. 10-66. First is the current foreground email application, which is making use of the camera application to load an attachment. This raises the cam- era process up to the same importance as the email app. Second is a similar situa- tion, the music application is playing music in the background with a service, and while doing so has a dependency on the media process for accessing the user’s mu- sic media. Consider what happens if the state of Fig. 10-69 changes so that the email ap- plication is done loading the attachment, and no longer uses the camera content provider. Figure 10-70 illustrates how the process state will change. Note that the camera application is no longer needed, so it has dropped out of the foreground importance, and down to the cached level. Making the camera cached has also pushed the old maps application one step down in the cached LRU list. These two examples give a final illustration of the importance of cached proc- esses. If the email application again needs to use the camera provider, the pro- vider’s process will typically already be left as a cached process. Using it again is then just a matter of setting the process back to the foreground and reconnecting with the content provider that is already sitting there with its database initialized.
clipped_os_Page_848_Chunk7065
SEC. 10.9 SUMMARY 849 Process State Impor tance system Core par t of operating system SYSTEM phone Always running for telephony stack PERSISTENT email Current foreground application FOREGROUND camera In use by email to load attachment FOREGROUND music Running background service playing music PERCEPTIBLE media In use by music app for accessing user’s music PERCEPTIBLE download Downloading a file for the user SERVICE launcher App launcher not current in use HOME maps Previously used mapping application CACHED Figure 10-69. Typical state of process importance Process State Impor tance system Core par t of operating system SYSTEM phone Always running for telephony stack PERSISTENT email Current foreground application FOREGROUND music Running background service playing music PERCEPTIBLE media In-use by music app for accessing user’s music PERCEPTIBLE download Downloading a file for the user SERVICE launcher App launcher not current in use HOME camera Previously used by email CACHED maps Previously used mapping application CACHED+1 Figure 10-70. Process state after email stops using camera 10.9 SUMMARY Linux began its life as an open-source, full-production UNIX clone, and is now used on machines ranging from smartphones and notebook computers to supercomputers. Three main interfaces to it exist: the shell, the C library, and the system calls themselves. In addition, a graphical user interface is often used to sim- plify user interaction with the system. The shell allows users to type commands for execution. These may be simple commands, pipelines, or more complex struc- tures. Input and output may be redirected. The C library contains the system calls and also many enhanced calls, such as printf for writing formatted output to files. The actual system call interface is architecture dependent, and on x86 platforms consists of roughly 250 calls, each of which does what is needed and no more. The key concepts in Linux include the process, the memory model, I/O, and the file system. Processes may fork off subprocesses, leading to a tree of processes.
clipped_os_Page_849_Chunk7066
850 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 Process management in Linux is different compared to other UNIX systems in that Linux views each execution entity—a single-threaded process, or each thread with- in a multithreaded process or the kernel—as a distinguishable task. A process, or a single task in general, is then represented via two key components, the task struc- ture and the additional information describing the user address space. The former is always in memory, but the latter data can be paged in and out of memory. Proc- ess creation is done by duplicating the process task structure, and then setting the memory-image information to point to the parent’s memory image. Actual copies of the memory-image pages are created only if sharing is not allowed and a memo- ry modification is required. This mechanism is called copy on write. Scheduling is done using a weighted fair queueing algorithm that uses a red-black tree for the tasks’ queue management. The memory model consists of three segments per process: text, data, and stack. Memory management is done by paging. An in-memory map keeps track of the state of each page, and the page daemon uses a modified dual-hand clock algo- rithm to keep enough free pages around. I/O devices are accessed using special files, each having a major device num- ber and a minor device number. Block device I/O uses the main memory to cache disk blocks and reduce the number of disk accesses. Character I/O can be done in raw mode, or character streams can be modified via line disciplines. Networking devices are treated somewhat differently, by associating entire network protocol modules to process the network packets stream to and from the user process. The file system is hierarchical with files and directories. All disks are mounted into a single directory tree starting at a unique root. Individual files can be linked into a directory from elsewhere in the file system. To use a file, it must be first opened, which yields a file descriptor for use in reading and writing the file. Inter- nally, the file system uses three main tables: the file descriptor table, the open-file-description table, and the i-node table. The i-node table is the most im- portant of these, containing all the administrative information about a file and the location of its blocks. Directories and devices are also represented as files, along with other special files. Protection is based on controlling read, write, and execute access for the owner, group, and others. For directories, the execute bit means search permission. Android is a platform for allowing apps to run on mobile devices. It is based on the Linux kernel, but consists of a large body of software on top of Linux, plus a small number of changes to the Linux kernel. Most of Android is written in Java. Apps are also written in Java, then translated to Java bytecode and then to Dalvik bytecode. Android apps communicate by a form of protected message passing call- ed transactions. A special Linux kernel model called the Binder handles the IPC. Android packages are self contained and have a manifest desccribing what is in the package. Packages contain activities, receivers, content providers, and intents. The Android security model is different from the Linux model and carefully sand- boxes each app because all apps are regarded as untrustworthy.
clipped_os_Page_850_Chunk7067
SEC. 10.9 SUMMARY 851 PROBLEMS 1. Explain how writing UNIX in C made it easier to port it to new machines. 2. The POSIX interface defines a set of library procedures. Explain why POSIX stan- dardizes library procedures instead of the system-call interface. 3. Linux depends on gcc compiler to be ported to new architectures. Describe one advan- tage and one disadvantage of this dependency. 4. A directory contains the following files: aardvark ferret koala porpoise unicorn bonefish grunion llama quacker vicuna capybara hyena marmot rabbit weasel dingo ibex nuthatch seahorse yak emu jellyfish ostrich tuna zebu Which files will be listed by the command ls [abc]*e*? 5. What does the following Linux shell pipeline do? grep nd xyz | wc –l 6. Write a Linux pipeline that prints the eighth line of file z on standard output. 7. Why does Linux distinguish between standard output and standard error, when both default to the terminal? 8. A user at a terminal types the following commands: a | b | c & d | e | f & After the shell has processed them, how many new processes are running? 9. When the Linux shell starts up a process, it puts copies of its environment variables, such as HOME, on the process’ stack, so the process can find out what its home direc- tory is. If this process should later fork, will the child automatically get these vari- ables, too? 10. About how long does it take a traditional UNIX system to fork off a child process under the following conditions: text size = 100 KB, data size = 20 KB, stack size = 10 KB, task structure = 1 KB, user structure = 5 KB. The kernel trap and return takes 1 msec, and the machine can copy one 32-bit word every 50 nsec. Text segments are shared, but data and stack segments are not. 11. As multimegabyte programs became more common, the time spent executing the fork system call and copying the data and stack segments of the calling process grew proportionally. When fork is executed in Linux, the parent’s address space is not cop- ied, as traditional fork semantics would dictate. How does Linux prevent the child from doing something that would completely change the fork semantics?
clipped_os_Page_851_Chunk7068
852 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 12. Why are negative arguments to nice reserved exclusively for the superuser? 13. A non-real-time Linux process has priority levels from 100 to 139. What is the default static priority and how is the nice value used to change this? 14. Does it make sense to take away a process’ memory when it enters zombie state? Why or why not? 15. To what hardware concept is a signal closely related? Give two examples of how sig- nals are used. 16. Why do you think the designers of Linux made it impossible for a process to send a signal to another process that is not in its process group? 17. A system call is usually implemented using a software interrupt (trap) instruction. Could an ordinary procedure call be used as well on the Pentium hardware? If so, under what conditions and how? If not, why not? 18. In general, do you think daemons have higher or lower priority than interactive proc- esses? Why? 19. When a new process is forked off, it must be assigned a unique integer as its PID. Is it sufficient to have a counter in the kernel that is incremented on each process creation, with the counter used as the new PID? Discuss your answer. 20. In every process’ entry in the task structure, the PID of the parent is stored. Why? 21. The copy-on-write mechanism is used as an optimization in the fork system call, so that a copy of a page is created only when one of the processes (parent or child) tries to write on the page. Suppose a process p1 forks processes p2 and p3 in quick succession. Explain how a page sharing may be handled in this case. 22. What combination of the sharing flags bits used by the Linux clone command corre- sponds to a conventional UNIX fork call? To creating a conventional UNIX thread? 23. Tw o tasks A and B need to perform the same amount of work. However, task A has higher priority, and needs to be given more CPU time. Expain how will this be achieved in each of the Linux schedulers described in this chapter, the O(1) and the CFS scheduler. 24. Some UNIX systems are tickless, meaning they do not have periodic clock interrupts. Why is this done? Also, does ticklessness make sense on a computer (such as an em- bedded system) running only one process? 25. When booting Linux (or most other operating systems for that matter), the bootstrap loader in sector 0 of the disk first loads a boot program which then loads the operating system. Why is this extra step necessary? Surely it would be simpler to have the boot- strap loader in sector 0 just load the operating system directly. 26. A certain editor has 100 KB of program text, 30 KB of initialized data, and 50 KB of BSS. The initial stack is 10 KB. Suppose that three copies of this editor are started si- multaneously. How much physical memory is needed (a) if shared text is used, and (b) if it is not? 27. Why are open-file-descriptor tables necessary in Linux?
clipped_os_Page_852_Chunk7069
CHAP. 10 PROBLEMS 853 28. In Linux, the data and stack segments are paged and swapped to a scratch copy kept on a special paging disk or partition, but the text segment uses the executable binary file instead. Why? 29. Describe a way to use mmap and signals to construct an interprocess-communication mechanism. 30. A file is mapped in using the following mmap system call: mmap(65536, 32768, READ, FLAGS, fd, 0) Pages are 8 KB. Which byte in the file is accessed by reading a byte at memory ad- dress 72,000? 31. After the system call of the previous problem has been executed, the call munmap(65536, 8192) is carried out. Does it succeed? If so, which bytes of the file remain mapped? If not, why does it fail? 32. Can a page fault ever lead to the faulting process being terminated? If so, give an ex- ample. If not, why not? 33. Is it possible that with the buddy system of memory management it ever occurs that two adjacent blocks of free memory of the same size coexist without being merged into one block? If so, explain how. If not, show that it is impossible. 34. It is stated in the text that a paging partition will perform better than a paging file. Why is this so? 35. Give two examples of the advantages of relative path names over absolute ones. 36. The following locking calls are made by a collection of processes. For each call, tell what happens. If a process fails to get a lock, it blocks. (a) A wants a shared lock on bytes 0 through 10. (b) B wants an exclusive lock on bytes 20 through 30. (c) C wants a shared lock on bytes 8 through 40. (d) A wants a shared lock on bytes 25 through 35. (e) B wants an exclusive lock on byte 8. 37. Consider the locked file of Fig. 10-26(c). Suppose that a process tries to lock bytes 10 and 11 and blocks. Then, before C releases its lock, yet another process tries to lock bytes 10 and 11, and also blocks. What kinds of problems are introduced into the semantics by this situation? Propose and defend two solutions. 38. Explain under what situations a process may request a shared lock or an exclusive lock. What problem may a process requesting an exclusive lock suffer from? 39. If a Linux file has protection mode 755 (octal), what can the owner, the owner’s group, and everyone else do to the file? 40. Some tape drives hav e numbered blocks and the ability to overwrite a particular block in place without disturbing the blocks in front of or behind it. Could such a device hold a mounted Linux file system?
clipped_os_Page_853_Chunk7070
854 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 41. In Fig. 10-24, both Fred and Lisa have access to the file x in their respective directories after linking. Is this access completely symmetrical in the sense that anything one of them can do with it the other one can, too? 42. As we have seen, absolute path names are looked up starting at the root directory and relative path names are looked up starting at the working directory. Suggest an efficient way to implement both kinds of searches. 43. When the file /usr/ast/work/f is opened, several disk accesses are needed to read i-node and directory blocks. Calculate the number of disk accesses required under the as- sumption that the i-node for the root directory is always in memory, and all directories are one block long. 44. A Linux i-node has 12 disk addresses for data blocks, as well as the addresses of sin- gle, double, and triple indirect blocks. If each of these holds 256 disk addresses, what is the size of the largest file that can be handled, assuming that a disk block is 1 KB? 45. When an i-node is read in from the disk during the process of opening a file, it is put into an i-node table in memory. This table has some fields that are not present on the disk. One of them is a counter that keeps track of the number of times the i-node has been opened. Why is this field needed? 46. On multi-CPU platforms, Linux maintains a runqueue for each CPU. Is this a good idea? Explain your answer? 47. The concept of loadable modules is useful in that new device drivers may be loaded in the kernel while the system is running. Provide two disadvantages of this concept. 48. Pdflush threads can be awakened periodically to write back to disk very old pages— older than 30 sec. Why is this necessary? 49. After a system crash and reboot, a recovery program is usually run. Suppose this pro- gram discovers that the link count in a disk i-node is 2, but only one directory entry references the i-node. Can it fix the problem, and if so, how? 50. Make an educated guess as to which Linux system call is the fastest. 51. Is it possible to unlink a file that has never been linked? What happens? 52. Based on the information presented in this chapter, if a Linux ext2 file system were to be put on a 1.44-MB floppy disk, what is the maximum amount of user file data that could be stored on the disk? Assume that disk blocks are 1 KB. 53. In view of all the trouble that students can cause if they get to be superuser, why does this concept exist in the first place? 54. A professor shares files with his students by placing them in a publicly accessible di- rectory on the Computer Science department’s Linux system. One day he realizes that a file placed there the previous day was left world-writable. He changes the permis- sions and verifies that the file is identical to his master copy. The next day he finds that the file has been changed. How could this have happened and how could it have been prevented? 55. Linux supports a system call fsuid. Unlike setuid, which grants the user all the rights of the effective id associated with a program he is running, fsuid grants the user who is
clipped_os_Page_854_Chunk7071
CHAP. 10 PROBLEMS 855 running the program special rights only with respect to access to files. Why is this fea- ture useful? 56. On a Linux system, go to /proc/#### directory, where #### is a decimal number cor- responding to a process currently running in the system. Answer the following along with an explanation: (a) What is the size of most of the files in this directory? (b) What are the time and date settings of most of the files? (c) What type of access right is provided to the users for accessing the files? 57. If you are writing an Android activity to display a Web page in a browser, how would you implement its activity-state saving to minimize the amount of saved state without losing anything important? 58. If you are writing networking code on Android that uses a socket to download a file, what should you consider doing that is different than on a standard Linux system? 59. If you are designing something like Android’s zygote process for a system that will have multiple threads running in each process forked from it, would you prefer to start those threads in zygote or after the fork? 60. Imagine you use Android’s Binder IPC to send an object to another process. You later receive an object from a call into your process, and find that what you have received is the same object as previously sent. What can you assume or not assume about the cal- ler in your process? 61. Consider an Android system that, immediately after starting, follows these steps: 1. The home (or launcher) application is started. 2. The email application starts syncing its mailbox in the background. 3. The user launches a camera application. 4. The user launches a Web browser application. The web page the user is now viewing in the browser application requires inceasingly more RAM, until it needs everything it can get. What happens? 62. Write a minimal shell that allows simple commands to be started. It should also allow them to be started in the background. 63. Using assembly language and BIOS calls, write a program that boots itself from a flop- py disk on a Pentium-class computer. The program should use BIOS calls to read the keyboard and echo the characters typed, just to demonstrate that it is running. 64. Write a dumb terminal program to connect two Linux computers via the serial ports. Use the POSIX terminal management calls to configure the ports. 65. Write a client-server application which, on request, transfers a large file via sockets. Reimplement the same application using shared memory. Which version do you expect to perform better? Why? Conduct performance measurements with the code you have written and using different file sizes. What are your observations? What do you think happens inside the Linux kernel which results in this behavior? 66. Implement a basic user-level threads library to run on top of Linux. The library API should contain function calls like mythreads init, mythreads create, mythreads join,
clipped_os_Page_855_Chunk7072
856 CASE STUDY 1: UNIX, LINUX, AND ANDROID CHAP. 10 mythreads exit, mythreads yield, mythreads self, and perhaps a few others. Next, im- plement these synchronization variables to enable safe concurrent operations: mythreads mutex init, mythreads mutex lock, mythreads mutex unlock. Before start- ing, clearly define the API and specify the semantics of each of the calls. Next imple- ment the user-level library with a simple, round-robin preemptive scheduler. You will also need to write one or more multithreaded applications, which use your library, in order to test it. Finally, replace the simple scheduling mechanism with another one which behaves like the Linux 2.6 O(1) scheduler described in this chapter. Compare the performance your application(s) receive when using each of the schedulers. 67. Write a shell script that displays some important system information such as what processes you are running, your home directory and current directory, processor type, current CPU utilization, etc.
clipped_os_Page_856_Chunk7073
11 CASE STUDY 2: WINDOWS 8 Windows is a modern operating system that runs on consumer PCs, laptops, tablets and phones as well as business desktop PCs and enterprise servers. Win- dows is also the operating system used in Microsoft’s Xbox gaming system and Azure cloud computing infrastructure. The most recent version is Windows 8.1. In this chapter we will examine various aspects of Windows 8, starting with a brief history, then moving on to its architecture. After this we will look at processes, memory management, caching, I/O, the file system, power management, and final- ly, security. 11.1 HISTORY OF WINDOWS THROUGH WINDOWS 8.1 Microsoft’s dev elopment of the Windows operating system for PC-based com- puters as well as servers can be divided into four eras: MS−DOS, MS−DOS-based Windows, NT-based Windows, and Modern Windows. Technically, each of these systems is substantially different from the others. Each was dominant during different decades in the history of the personal computer. Figure 11-1 shows the dates of the major Microsoft operating system releases for desktop computers. Below we will briefly sketch each of the eras shown in the table. 857
clipped_os_Page_857_Chunk7074
858 CASE STUDY 2: WINDOWS 8 CHAP. 11 Year MS−DOS Notes MS-DOS based Windows NT-based Windows Modern Windows 1981 1.0 Initial release for IBM PC 1983 2.0 Suppor t for PC/XT 1984 3.0 Suppor t for PC/AT 1990 3.0 Ten million copies in 2 years 1991 5.0 Added memory management 1992 3.1 Ran only on 286 and later 1993 NT 3.1 1995 7.0 95 MS-DOS embedded in Win 95 1996 NT 4.0 1998 98 2000 8.0 Me 2000 Win Me was infer ior to Win 98 2001 XP Replaced Win 98 2006 Vista Vista could not supplant XP 2009 7 Significantly improved upon Vista 2012 8 First Modern version 2013 8.1 Microsoft moved to rapid releases Figure 11-1. Major releases in the history of Microsoft operating systems for desktop PCs. 11.1.1 1980s: MS-DOS In the early 1980s IBM, at the time the biggest and most powerful computer company in the world, was developing a personal computer based the Intel 8088 microprocessor. Since the mid-1970s, Microsoft had become the leading provider of the BASIC programming language for 8-bit microcomputers based on the 8080 and Z-80. When IBM approached Microsoft about licensing BASIC for the new IBM PC, Microsoft readily agreed and suggested that IBM contact Digital Re- search to license its CP/M operating system, since Microsoft was not then in the operating system business. IBM did that, but the president of Digital Research, Gary Kildall, was too busy to meet with IBM. This was probably the worst blun- der in all of business history, since had he licensed CP/M to IBM, Kildall would probably have become the richest man on the planet. Rebuffed by Kildall, IBM came back to Bill Gates, the cofounder of Microsoft, and asked for help again. Within a short time, Microsoft bought a CP/M clone from a local company, Seattle Computer Products, ported it to the IBM PC, and licensed it to IBM. It was then renamed MS-DOS 1.0 (MicroSoft Disk Operating System) and shipped with the first IBM PC in 1981.
clipped_os_Page_858_Chunk7075
SEC. 11.1 HISTORY OF WINDOWS THROUGH WINDOWS 8.1 859 MS-DOS was a 16-bit real-mode, single-user, command-line-oriented operat- ing system consisting of 8 KB of memory resident code. Over the next decade, both the PC and MS-DOS continued to evolve, adding more features and capabili- ties. By 1986, when IBM built the PC/AT based on the Intel 286, MS-DOS had grown to be 36 KB, but it continued to be a command-line-oriented, one-applica- tion-ata-time, operating system. 11.1.2 1990s: MS-DOS-based Windows Inspired by the graphical user interface of a system developed by Doug Engel- bart at Stanford Research Institute and later improved at Xerox PARC, and their commercial progeny, the Apple Lisa and the Apple Macintosh, Microsoft decided to give MS-DOS a graphical user interface that it called Windows. The first two versions of Windows (1985 and 1987) were not very successful, due in part to the limitations of the PC hardware available at the time. In 1990 Microsoft released Windows 3.0 for the Intel 386, and sold over one million copies in six months. Windows 3.0 was not a true operating system, but a graphical environment built on top of MS-DOS, which was still in control of the machine and the file sys- tem. All programs ran in the same address space and a bug in any one of them could bring the whole system to a frustrating halt. In August 1995, Windows 95 was released. It contained many of the features of a full-blown operating system, including virtual memory, process management, and multiprogramming, and introduced 32-bit programming interfaces. However, it still lacked security, and provided poor isolation between applications and the operating system. Thus, the problems with instability continued, even with the subsequent releases of Windows 98 and Windows Me, where MS-DOS was still there running 16-bit assembly code in the heart of the Windows operating system. 11.1.3 2000s: NT-based Windows By end of the 1980s, Microsoft realized that continuing to evolve an operating system with MS-DOS at its center was not the best way to go. PC hardware was continuing to increase in speed and capability and ultimately the PC market would collide with the desktop, workstation, and enterprise-server computing markets, where UNIX was the dominant operating system. Microsoft was also concerned that the Intel microprocessor family might not continue to be competitive, as it was already being challenged by RISC architectures. To address these issues, Micro- soft recruited a group of engineers from DEC (Digital Equipment Corporation) led by Dave Cutler, one of the key designers of DEC’s VMS operating system (among others). Cutler was chartered to develop a brand-new 32-bit operating system that was intended to implement OS/2, the operating system API that Microsoft was jointly developing with IBM at the time. The original design documents by Cut- ler’s team called the system NT OS/2.
clipped_os_Page_859_Chunk7076
860 CASE STUDY 2: WINDOWS 8 CHAP. 11 Cutler’s system was called NT for New Technology (and also because the orig- inal target processor was the new Intel 860, code-named the N10). NT was de- signed to be portable across different processors and emphasized security and reliability, as well as compatibility with the MS-DOS-based versions of Windows. Cutler’s background at DEC shows in various places, with there being more than a passing similarity between the design of NT and that of VMS and other operating systems designed by Cutler, shown in Fig. 11-2. Year DEC operating system Characteristics 1973 RSX-11M 16-bit, multiuser, real-time, swapping 1978 VAX/VMS 32-bit, vir tual memor y 1987 VAXELAN Real-time 1988 PRISM/Mica Canceled in favor of MIPS/Ultrix Figure 11-2. DEC operating systems developed by Dave Cutler. Programmers familiar only with UNIX find the architecture of NT to be quite different. This is not just because of the influence of VMS, but also because of the differences in the computer systems that were common at the time of design. UNIX was first designed in the 1970s for single-processor, 16-bit, tiny-memory, swapping systems where the process was the unit of concurrency and composition, and fork/exec were inexpensive operations (since swapping systems frequently copy processes to disk anyway). NT was designed in the early 1990s, when multi- processor, 32-bit, multimegabyte, virtual memory systems were common. In NT, threads are the units of concurrency, dynamic libraries are the units of composition, and fork/exec are implemented by a single operation to create a new process and run another program without first making a copy. The first version of NT-based Windows (Windows NT 3.1) was released in 1993. It was called 3.1 to correspond with the then-current consumer Windows 3.1. The joint project with IBM had foundered, so though the OS/2 interfaces were still supported, the primary interfaces were 32-bit extensions of the Windows APIs, called Win32. Between the time NT was started and first shipped, Windows 3.0 had been released and had become extremely successful commercially. It too was able to run Win32 programs, but using the Win32s compatibility library. Like the first version of MS-DOS-based Windows, NT-based Windows was not initially successful. NT required more memory, there were few 32-bit applica- tions available, and incompatibilities with device drivers and applications caused many customers to stick with MS-DOS-based Windows which Microsoft was still improving, releasing Windows 95 in 1995. Windows 95 provided native 32-bit programming interfaces like NT, but better compatibility with existing 16-bit soft- ware and applications. Not surprisingly, NT’s early success was in the server mar- ket, competing with VMS and NetWare.
clipped_os_Page_860_Chunk7077
SEC. 11.1 HISTORY OF WINDOWS THROUGH WINDOWS 8.1 861 NT did meet its portability goals, with additional releases in 1994 and 1995 adding support for (little-endian) MIPS and PowerPC architectures. The first major upgrade to NT came with Windows NT 4.0 in 1996. This system had the power, security, and reliability of NT, but also sported the same user interface as the by-then very popular Windows 95. Figure 11-3 shows the relationship of the Win32 API to Windows. Having a common API across both the MS-DOS-based and NT-based Windows was impor- tant to the success of NT. This compatibility made it much easier for users to migrate from Windows 95 to NT, and the operating system became a strong player in the high-end desktop market as well as servers. However, customers were not as willing to adopt other processor architectures, and of the four architectures Windows NT 4.0 supported in 1996 (the DEC Alpha was added in that release), only the x86 (i.e., Pentium fam- ily) was still actively supported by the time of the next major release, Windows 2000. Win32 application program Win32 application programming interface Windows 3.0/3.1 Windows 95/98/98SE/Me Windows NT/2000/Vista/7 Windows 8/8.1 Win32s Figure 11-3. The Win32 API allows programs to run on almost all versions of Windows. Windows 2000 represented a significant evolution for NT. The key technolo- gies added were plug-and-play (for consumers who installed a new PCI card, elim- inating the need to fiddle with jumpers), network directory services (for enterprise customers), improved power management (for notebook computers), and an im- proved GUI (for everyone). The technical success of Windows 2000 led Microsoft to push toward the dep- recation of Windows 98 by enhancing the application and device compatibility of the next NT release, Windows XP. Windows XP included a friendlier new look- and-feel to the graphical interface, bolstering Microsoft’s strategy of hooking con- sumers and reaping the benefit as they pressured their employers to adopt systems with which they were already familiar. The strategy was overwhelmingly suc- cessful, with Windows XP being installed on hundreds of millions of PCs over its first few years, allowing Microsoft to achieve its goal of effectively ending the era of MS-DOS-based Windows.
clipped_os_Page_861_Chunk7078
862 CASE STUDY 2: WINDOWS 8 CHAP. 11 Microsoft followed up Windows XP by embarking on an ambitious release to kindle renewed excitement among PC consumers. The result, Windows Vista, was completed in late 2006, more than fiv e years after Windows XP shipped. Win- dows Vista boasted yet another redesign of the graphical interface, and new securi- ty features under the covers. Most of the changes were in customer-visible experi- ences and capabilities. The technologies under the covers of the system improved incrementally, with much clean-up of the code and many improvements in per- formance, scalability, and reliability. The server version of Vista (Windows Server 2008) was delivered about a year after the consumer version. It shares, with Vista, the same core system components, such as the kernel, drivers, and low-level librar- ies and programs. The human story of the early development of NT is related in the book Show- stopper (Zachary, 1994). The book tells a lot about the key people involved and the difficulties of undertaking such an ambitious software development project. 11.1.4 Windows Vista The release of Windows Vista culminated Microsoft’s most extensive operating system project to date. The initial plans were so ambitious that a couple of years into its development Vista had to be restarted with a smaller scope. Plans to rely heavily on Microsoft’s type-safe, garbage-collected .NET language C# were shelved, as were some significant features such as the WinFS unified storage sys- tem for searching and organizing data from many different sources. The size of the full operating system is staggering. The original NT release of 3 million lines of C/C++ that had grown to 16 million in NT 4, 30 million in 2000, and 50 million in XP. It is over 70 million lines in Vista and more in Windows 7 and 8. Much of the size is due to Microsoft’s emphasis on adding many new features to its products in every release. In the main system32 directory, there are 1600 DLLs (Dynamic Link Libraries) and 400 EXEs (Executables), and that does not include the other directories containing the myriad of applets included with the op- erating system that allow users to surf the Web, play music and video, send email, scan documents, organize photos, and even make movies. Because Microsoft wants customers to switch to new versions, it maintains compatibility by generally keeping all the features, APIs, applets (small applications), etc., from the previous version. Few things ever get deleted. The result is that Windows was growing dra- matically release to release. Windows’ distribution media had moved from floppy, to CD, and with Windows Vista, to DVD. Technology had been keeping up, how- ev er, and faster processors and larger memories made it possible for computers to get faster despite all this bloat. Unfortunately for Microsoft, Windows Vista was released at a time when cus- tomers were becoming enthralled with inexpensive computers, such as low-end notebooks and netbook computers. These machines used slower processors to save cost and battery life, and in their earlier generations limited memory sizes. At
clipped_os_Page_862_Chunk7079
SEC. 11.1 HISTORY OF WINDOWS THROUGH WINDOWS 8.1 863 the same time, processor performance ceased to improve at the same rate it had previously, due to the difficulties in dissipating the heat created by ever-increasing clock speeds. Moore’s Law continued to hold, but the additional transistors were going into new features and multiple processors rather than improvements in sin- gle-processor performance. All the bloat in Windows Vista meant that it per- formed poorly on these computers relative to Windows XP, and the release was never widely accepted. The issues with Windows Vista were addressed in the subsequent release, Windows 7. Microsoft invested heavily in testing and performance automation, new telemetry technology, and extensively strengthened the teams charged with improving performance, reliability, and security. Though Windows 7 had rela- tively few functional changes compared to Windows Vista, it was better engineered and more efficient. Windows 7 quickly supplanted Vista and ultimately Windows XP to be the most popular version of Windows to date. 11.1.5 2010s: Modern Windows By the time Windows 7 shipped, the computing industry once again began to change dramatically. The success of the Apple iPhone as a portable computing de- vice, and the advent of the Apple iPad, had heralded a sea-change which led to the dominance of lower-cost Android tablets and phones, much as Microsoft had dom- inated the desktop in the first three decades of personal computing. Small, portable, yet powerful devices and ubiquitous fast networks were creating a world where mobile computing and network-based services were becoming the dominant paradigm. The old world of portable computers was replaced by machines with small screens that ran applications readily downloadable from the Web. These ap- plications were not the traditional variety, like word processing, spreadsheets, and connecting to corporate servers. Instead, they provided access to services like Web search, social networking, Wikipedia, streaming music and video, shopping, and personal navigation. The business models for computing were also changing, with advertising opportunities becoming the largest economic force behind computing. Microsoft began a process to redesign itself as a devices and services company in order to better compete with Google and Apple. It needed an operating system it could deploy across a wide spectrum of devices: phones, tablets, game consoles, laptops, desktops, servers, and the cloud. Windows thus underwent an even bigger ev olution than with Windows Vista, resulting in Windows 8. Howev er, this time Microsoft applied the lessons from Windows 7 to create a well-engineered, per- formant product with less bloat. Windows 8 built on the modular MinWin approach Microsoft used in Win- dows 7 to produce a small operating system core that could be extended onto dif- ferent devices. The goal was for each of the operating systems for specific devices to be built by extending this core with new user interfaces and features, yet provide as common an experience for users as possible. This approach was successfully
clipped_os_Page_863_Chunk7080
864 CASE STUDY 2: WINDOWS 8 CHAP. 11 applied to Windows Phone 8, which shares most of the core binaries with desktop and server Windows. Support of phones and tablets by Windows required support for the popular ARM architecture, as well as new Intel processors targeting those devices. What makes Windows 8 part of the Modern Windows era are the funda- mental changes in the programming models, as we will examine in the next sec- tion. Windows 8 was not received to universal acclaim. In particular, the lack of the Start Button on the taskbar (and its associated menu) was viewed by many users as a huge mistake. Others objected to using a tablet-like interface on a desktop ma- chine with a large monitor. Microsoft responded to this and other criticisms on May 14, 2013 by releasing an update called Windows 8.1. This version fixed these problems while at the same time introducing a host of new features, such as better cloud integration, as well as a number of new programs. Although we will stick to the more generic name of ‘‘Windows 8’’ in this chapter, in fact, everything in it is a description of how Windows 8.1 works. 11.2 PROGRAMMING WINDOWS It is now time to start our technical study of Windows. Before getting into the details of the internal structure, however, we will take a look at the native NT API for system calls, the Win32 programming subsystem introduced as part of NT- based Windows, and the Modern WinRT programming environment introduced with Windows 8. Figure 11-4 shows the layers of the Windows operating system. Beneath the applet and GUI layers of Windows are the programming interfaces that applica- tions build on. As in most operating systems, these consist largely of code libraries (DLLs) to which programs dynamically link for access to operating system fea- tures. Windows also includes a number of programming interfaces which are im- plemented as services that run as separate processes. Applications communicate with user-mode services through RPCs (Remote-Procedure-Calls). The core of the NT operating system is the NTOS kernel-mode program (ntoskrnl.exe), which provides the traditional system-call interfaces upon which the rest of the operating system is built. In Windows, only programmers at Microsoft write to the system-call layer. The published user-mode interfaces all belong to operating system personalities that are implemented using subsystems that run on top of the NTOS layers. Originally NT supported three personalities: OS/2, POSIX and Win32. OS/2 was discarded in Windows XP. Support for POSIX was finally removed in Win- dows 8.1. Today all Windows applications are written using APIs that are built on top of the Win32 subsystem, such as the WinFX API in the .NET programming model. The WinFX API includes many of the features of Win32, and in fact many
clipped_os_Page_864_Chunk7081
SEC. 11.2 PROGRAMMING WINDOWS 865 Hardware abstraction layer (hal.dll) Hypervisor (hvix, hvax) Drivers: devices, file systems, network NTOS executive layer (ntoskrnl.exe) GUI driver (Win32k.sys) NTOS kernel layer (ntoskrnl.exe) Kernel mode User mode Native NT API, C/C++ run-time (ntdll.dll) NT services: smss, lsass, services, winlogon, Win32 subsystem process (csrss.exe) Modern broker processes Windows Services Windows Desktop Apps Modern Windows Apps Process lifetime mgr AppContainer COM WinRT: .NET/C++, WWA/JS Modern app mgr Subsystem API (kernel32) Dynamic libraries (ole, rpc) GUI (shell32, user32, gdi32) [.NET: base classes, GC] Desktop mgr(explorer) Figure 11-4. The programming layers in Modern Windows. of the functions in the WinFX Base Class Library are simply wrappers around Win32 APIs. The advantages of WinFX have to do with the richness of the object types supported, the simplified consistent interfaces, and use of the .NET Common Language Run-time (CLR), including garbage collection (GC). The Modern versions of Windows begin with Windows 8, which introduced the new WinRT set of APIs. Windows 8 deprecated the traditional Win32 desktop experience in favor of running a single application at a time on the full screen with an emphasis on touch over use of the mouse. Microsoft saw this as a necessary step as part of the transition to a single operating system that would work with phones, tablets, and game consoles, as well as traditional PCs and servers. The GUI changes necessary to support this new model require that applications be rewritten to a new API model, the Modern Software Dev elopment Kit, which in- cludes the WinRT APIs. The WinRT APIs are carefully curated to produce a more consistent set of behaviors and interfaces. These APIs have versions available for C++ and .NET programs but also JavaScript for applications hosted in a brow- ser-like environment wwa.exe (Windows Web Application). In addition to WinRT APIs, many of the existing Win32 APIs were included in the MSDK (Microsoft Development Kit). The initially available WinRT APIs were not sufficient to write many programs. Some of the included Win32 APIs were chosen to limit the behavior of applications. For example, applications can- not create threads directly with the MSDK, but must rely on the Win32 thread pool to run concurrent activities within a process. This is because Modern Windows is
clipped_os_Page_865_Chunk7082
866 CASE STUDY 2: WINDOWS 8 CHAP. 11 shifting programmers away from a threading model to a task model in order to dis- entangle resource management (priorities, processor affinities) from the pro- gramming model (specifying concurrent activities). Other omitted Win32 APIs in- clude most of the Win32 virtual memory APIs. Programmers are expected to rely on the Win32 heap-management APIs rather than attempt to manage memory re- sources directly. APIs that were already deprecated in Win32 were also omitted from the MSDK, as were all ANSI APIs. The MSDK APIs are Unicode only. The choice of the word Modern to describe a product such as Windows is sur- prising. Perhaps if a new generation Windows is here ten years from now, it will be referred to as post-Modern Windows. Unlike traditional Win32 processes, the processes running modern applications have their lifetimes managed by the operating system. When a user switches away from an application, the system gives it a couple of seconds to save its state and then ceases to give it further processor resources until the user switches back to the application. If the system runs low on resources, the operating system may termi- nate the application’s processes without the application ever running again. When the user switches back to the application at some time in the future, it will be re- started by the operating system. Applications that need to run tasks in the back- ground must specifically arrange to do so using a new set of WinRT APIs. Back- ground activity is carefully managed by the system to improve battery life and pre- vent interference with the foreground application the user is currently using. These changes were made to make Windows function better on mobile devices. In the Win32 desktop world applications are deployed by running an installer that is part of the application. Modern applications have to be installed using Win- dows’ AppStore program, which will deploy only applications that were uploaded into the Microsoft on-line store by the developer. Microsoft is following the same successful model introduced by Apple and adopted by Android. Microsoft will not accept applications into the store unless they pass verification which, among other checks, ensures that the application is using only APIs available in the MSDK. When a modern application is running, it always executes in a sandbox called an AppContainer. Sandboxing process execution is a security technique for iso- lating less trusted code so that it cannot freely tamper with the system or user data. The Windows AppContainer treats each application as a distinct user, and uses Windows security facilities to keep the application from accessing arbitrary system resources. When an application does need access to a system resource, there are WinRT APIs that communicate to broker processes which do have access to more of the system, such as a user’s files. As shown in Fig. 11-5, NT subsystems are constructed out of four compo- nents: a subsystem process, a set of libraries, hooks in CreateProcess, and support in the kernel. A subsystem process is really just a service. The only special prop- erty is that it is started by the smss.exe (session manager) program—the initial user-mode program started by NT—in response to a request from CreateProcess in Win32 or the corresponding API in a different subsystem. Although Win32 is
clipped_os_Page_866_Chunk7083
SEC. 11.2 PROGRAMMING WINDOWS 867 the only remaining subsystem supported, Windows still maintains the subsystem model, including the csrss.exe Win32 subsystem process. Subsystem process Program process Subsystem libraries Subsystem run-time library (CreateProcess hook) Subsystem kernel support NTOS Executive Local procedure call (LPC) Native NT system services User-mode Kernel-mode Native NT API,C/C++ run-time Figure 11-5. The components used to build NT subsystems. The set of libraries both implements higher-level operating-system functions specific to the subsystem and contains the stub routines which communicate be- tween processes using the subsystem (shown on the left) and the subsystem proc- ess itself (shown on the right). Calls to the subsystem process normally take place using the kernel-mode LPC (Local Procedure Call) facilities, which implement cross-process procedure calls. The hook in Win32 CreateProcess detects which subsystem each program re- quires by looking at the binary image. It then asks smss.exe to start the subsystem process (if it is not already running). The subsystem process then takes over responsibility for loading the program. The NT kernel was designed to have a lot of general-purpose facilities that can be used for writing operating-system-specific subsystems. But there is also special code that must be added to correctly implement each subsystem. As examples, the native NtCreateProcess system call implements process duplication in support of POSIX fork system call, and the kernel implements a particular kind of string table for Win32 (called atoms) which allows read-only strings to be efficiently shared a- cross processes. The subsystem processes are native NT programs which use the native system calls provided by the NT kernel and core services, such as smss.exe and lsass.exe (local security administration). The native system calls include cross-process facil- ities to manage virtual addresses, threads, handles, and exceptions in the processes created to run programs written to use a particular subsystem.
clipped_os_Page_867_Chunk7084
868 CASE STUDY 2: WINDOWS 8 CHAP. 11 11.2.1 The Native NT Application Programming Interface Like all other operating systems, Windows has a set of system calls it can per- form. In Windows, these are implemented in the NTOS executive layer that runs in kernel mode. Microsoft has published very few of the details of these native system calls. They are used internally by lower-level programs that ship as part of the operating system (mainly services and the subsystems), as well as kernel-mode device drivers. The native NT system calls do not really change very much from release to release, but Microsoft chose not to make them public so that applications written for Windows would be based on Win32 and thus more likely to work with both the MS-DOS-based and NT-based Windows systems, since the Win32 API is common to both. Most of the native NT system calls operate on kernel-mode objects of one kind or another, including files, processes, threads, pipes, semaphores, and so on. Fig- ure 11-6 gives a list of some of the common categories of kernel-mode objects sup- ported by the kernel in Windows. Later, when we discuss the object manager, we will provide further details on the specific object types. Object category Examples Synchronization Semaphores, mutexes, events, IPC ports, I/O completion queues I/O Files, devices, drivers, timers Program Jobs, processes, threads, sections, tokens Win32 GUI Desktops, application callbacks Figure 11-6. Common categories of kernel-mode object types. Sometimes use of the term object regarding the data structures manipulated by the operating system can be confusing because it is mistaken for object-oriented. Operating system objects do provide data hiding and abstraction, but they lack some of the most basic properties of object-oriented systems such as inheritance and polymorphism. In the native NT API, calls are available to create new kernel-mode objects or access existing ones. Every call creating or opening an object returns a result called a handle to the caller. The handle can subsequently be used to perform operations on the object. Handles are specific to the process that created them. In general handles cannot be passed directly to another process and used to refer to the same object. However, under certain circumstances, it is possible to duplicate a handle into the handle table of other processes in a protected way, allowing processes to share access to objects—even if the objects are not accessible in the namespace. The process duplicating each handle must itself have handles for both the source and target process. Every object has a security descriptor associated with it, telling in detail who may and may not perform what kinds of operations on the object based on the
clipped_os_Page_868_Chunk7085
SEC. 11.2 PROGRAMMING WINDOWS 869 access requested. When handles are duplicated between processes, new access restrictions can be added that are specific to the duplicated handle. Thus, a process can duplicate a read-write handle and turn it into a read-only version in the target process. Not all system-created data structures are objects and not all objects are kernel- mode objects. The only ones that are true kernel-mode objects are those that need to be named, protected, or shared in some way. Usually, they represent some kind of programming abstraction implemented in the kernel. Every kernel-mode object has a system-defined type, has well-defined operations on it, and occupies storage in kernel memory. Although user-mode programs can perform the operations (by making system calls), they cannot get at the data directly. Figure 11-7 shows a sampling of the native APIs, all of which use explicit handles to manipulate kernel-mode objects such as processes, threads, IPC ports, and sections (which are used to describe memory objects that can be mapped into address spaces). NtCreateProcess returns a handle to a newly created process ob- ject, representing an executing instance of the program represented by the Section- Handle. DebugPor tHandle is used to communicate with a debugger when giving it control of the process after an exception (e.g., dividing by zero or accessing invalid memory). ExceptPor tHandle is used to communicate with a subsystem process when errors occur and are not handled by an attached debugger. NtCreateProcess(&ProcHandle, Access, SectionHandle, DebugPor tHandle, ExceptPor tHandle, ...) NtCreateThread(&ThreadHandle, ProcHandle, Access, ThreadContext, CreateSuspended, ...) NtAllocateVir tualMemory(ProcHandle, Addr, Size, Type, Protection, ...) NtMapViewOfSection(SectHandle, ProcHandle, Addr, Size, Protection, ...) NtReadVir tualMemory(ProcHandle, Addr, Size, ...) NtWr iteVirtualMemor y(ProcHandle, Addr, Size, ...) NtCreateFile(&FileHandle, FileNameDescr iptor, Access, ...) NtDuplicateObject(srcProcHandle, srcObjHandle, dstProcHandle, dstObjHandle, ...) Figure 11-7. Examples of native NT API calls that use handles to manipulate ob- jects across process boundaries. NtCreateThread takes ProcHandle because it can create a thread in any process for which the calling process has a handle (with sufficient access rights). Simi- larly, NtAllocateVir tualMemory, NtMapViewOfSection, NtReadVir tualMemory, and NtWr iteVirtualMemor y allow one process not only to operate on its own address space, but also to allocate virtual addresses, map sections, and read or write virtual memory in other processes. NtCreateFile is the native API call for creating a new file or opening an existing one. NtDuplicateObject is the API call for duplicating handles from one process to another. Kernel-mode objects are, of course, not unique to Windows. UNIX systems also support a variety of kernel-mode objects, such as files, network sockets, pipes,
clipped_os_Page_869_Chunk7086
870 CASE STUDY 2: WINDOWS 8 CHAP. 11 devices, processes, and interprocess communication (IPC) facilities like shared memory, message ports, semaphores, and I/O devices. In UNIX there are a variety of ways of naming and accessing objects, such as file descriptors, process IDs, and integer IDs for SystemV IPC objects, and i-nodes for devices. The implementation of each class of UNIX objects is specific to the class. Files and sockets use dif- ferent facilities than the SystemV IPC mechanisms or processes or devices. Kernel objects in Windows use a uniform facility based on handles and names in the NT namespace to reference kernel objects, along with a unified imple- mentation in a centralized object manager. Handles are per-process but, as de- scribed above, can be duplicated into another process. The object manager allows objects to be given names when they are created, and then opened by name to get handles for the objects. The object manager uses Unicode (wide characters) to represent names in the NT namespace. Unlike UNIX, NT does not generally distinguish between upper- and lowercase (it is case preserving but case insensitive). The NT namespace is a hierarchical tree-structured collection of directories, symbolic links and objects. The object manager also provides unified facilities for synchronization, securi- ty, and object lifetime management. Whether the general facilities provided by the object manager are made available to users of any particular object is up to the ex- ecutive components, as they provide the native APIs that manipulate each object type. It is not only applications that use objects managed by the object manager. The operating system itself can also create and use objects—and does so heavily. Most of these objects are created to allow one component of the system to store some information for a substantial period of time or to pass some data structure to another component, and yet benefit from the naming and lifetime support of the object manager. For example, when a device is discovered, one or more device objects are created to represent the device and to logically describe how the device is connected to the rest of the system. To control the device a device driver is load- ed, and a driver object is created holding its properties and providing pointers to the functions it implements for processing the I/O requests. Within the operating system the driver is then referred to by using its object. The driver can also be ac- cessed directly by name rather than indirectly through the devices it controls (e.g., to set parameters governing its operation from user mode). Unlike UNIX, which places the root of its namespace in the file system, the root of the NT namespace is maintained in the kernel’s virtual memory. This means that NT must recreate its top-level namespace every time the system boots. Using kernel virtual memory allows NT to store information in the namespace without first having to start the file system running. It also makes it much easier for NT to add new types of kernel-mode objects to the system because the formats of the file systems themselves do not have to be modified for each new object type. A named object can be marked permanent, meaning that it continues to exist until explicitly deleted or the system reboots, even if no process currently has a
clipped_os_Page_870_Chunk7087
SEC. 11.2 PROGRAMMING WINDOWS 871 handle for the object. Such objects can even extend the NT namespace by provid- ing parse routines that allow the objects to function somewhat like mount points in UNIX. File systems and the registry use this facility to mount volumes and hives onto the NT namespace. Accessing the device object for a volume gives access to the raw volume, but the device object also represents an implicit mount of the vol- ume into the NT namespace. The individual files on a volume can be accessed by concatenating the volume-relative file name onto the end of the name of the device object for that volume. Permanent names are also used to represent synchronization objects and shared memory, so that they can be shared by processes without being continually recreat- ed as processes stop and start. Device objects and often driver objects are given permanent names, giving them some of the persistence properties of the special i- nodes kept in the /dev directory of UNIX. We will describe many more of the features in the native NT API in the next section, where we discuss the Win32 APIs that provide wrappers around the NT system calls. 11.2.2 The Win32 Application Programming Interface The Win32 function calls are collectively called the Win32 API. These inter- faces are publicly disclosed and fully documented. They are implemented as li- brary procedures that either wrap the native NT system calls used to get the work done or, in some cases, do the work right in user mode. Though the native NT APIs are not published, most of the functionality they provide is accessible through the Win32 API. The existing Win32 API calls rarely change with new releases of Windows, though many new functions are added to the API. Figure 11-8 shows various low-level Win32 API calls and the native NT API calls that they wrap. What is interesting about the figure is how uninteresting the mapping is. Most low-level Win32 functions have native NT equivalents, which is not surprising as Win32 was designed with NT in mind. In many cases the Win32 layer must manipulate the Win32 parameters to map them onto NT, for example, canonicalizing path names and mapping onto the appropriate NT path names, in- cluding special MS-DOS device names (like LPT:). The Win32 APIs for creating processes and threads also must notify the Win32 subsystem process, csrss.exe, that there are new processes and threads for it to supervise, as we will describe in Sec. 11.4. Some Win32 calls take path names, whereas the equivalent NT calls use hand- les. So the wrapper routines have to open the files, call NT, and then close the handle at the end. The wrappers also translate the Win32 APIs from ANSI to Uni- code. The Win32 functions shown in Fig. 11-8 that use strings as parameters are actually two APIs, for example, CreateProcessW and CreateProcessA. The strings passed to the latter API must be translated to Unicode before calling the un- derlying NT API, since NT works only with Unicode.
clipped_os_Page_871_Chunk7088
872 CASE STUDY 2: WINDOWS 8 CHAP. 11 Win32 call Native NT API call CreateProcess NtCreateProcess CreateThread NtCreateThread SuspendThread NtSuspendThread CreateSemaphore NtCreateSemaphore ReadFile NtReadFile DeleteFile NtSetInfor mationFile CreateFileMapping NtCreateSection Vir tualAlloc NtAllocateVir tualMemory MapViewOfFile NtMapViewOfSection DuplicateHandle NtDuplicateObject CloseHandle NtClose Figure 11-8. Examples of Win32 API calls and the native NT API calls that they wrap. Since few changes are made to the existing Win32 interfaces in each release of Windows, in theory the binary programs that ran correctly on any previous release will continue to run correctly on a new release. In practice, there are often many compatibility problems with new releases. Windows is so complex that a few seemingly inconsequential changes can cause application failures. And applica- tions themselves are often to blame, since they frequently make explicit checks for specific operating system versions or fall victim to their own latent bugs that are exposed when they run on a new release. Nevertheless, Microsoft makes an effort in every release to test a wide variety of applications to find incompatibilities and either correct them or provide application-specific workarounds. Windows supports two special execution environments both called WOW (Windows-on-Windows). WOW32 is used on 32-bit x86 systems to run 16-bit Windows 3.x applications by mapping the system calls and parameters between the 16-bit and 32-bit worlds. Similarly, WOW64 allows 32-bit Windows applications to run on x64 systems. The Windows API philosophy is very different from the UNIX philosophy. In the latter, the operating system functions are simple, with few parameters and few places where there are multiple ways to perform the same operation. Win32 pro- vides very comprehensive interfaces with many parameters, often with three or four ways of doing the same thing, and mixing together low-level and high-level functions, like CreateFile and CopyFile. This means Win32 provides a very rich set of interfaces, but it also introduces much complexity due to the poor layering of a system that intermixes both high- level and low-level functions in the same API. For our study of operating systems, only the low-level functions of the Win32 API that wrap the native NT API are rel- evant, so those are what we will focus on.
clipped_os_Page_872_Chunk7089
SEC. 11.2 PROGRAMMING WINDOWS 873 Win32 has calls for creating and managing both processes and threads. There are also many calls that relate to interprocess communication, such as creating, de- stroying, and using mutexes, semaphores, events, communication ports, and other IPC objects. Although much of the memory-management system is invisible to pro- grammers, one important feature is visible: namely the ability of a process to map a file onto a region of its virtual memory. This allows threads running in a process the ability to read and write parts of the file using pointers without having to expli- citly perform read and write operations to transfer data between the disk and mem- ory. With memory-mapped files the memory-management system itself performs the I/Os as needed (demand paging). Windows implements memory-mapped files using three completely different facilities. First it provides interfaces which allow processes to manage their own virtual address space, including reserving ranges of addresses for later use. Sec- ond, Win32 supports an abstraction called a file mapping, which is used to repres- ent addressable objects like files (a file mapping is called a section in the NT layer). Most often, file mappings are created to refer to files using a file handle, but they can also be created to refer to private pages allocated from the system pagefile. The third facility maps views of file mappings into a process’ address space. Win32 allows only a view to be created for the current process, but the underlying NT facility is more general, allowing views to be created for any process for which you have a handle with the appropriate permissions. Separating the creation of a file mapping from the operation of mapping the file into the address space is a dif- ferent approach than used in the mmap function in UNIX. In Windows, the file mappings are kernel-mode objects represented by a hand- le. Like most handles, file mappings can be duplicated into other processes. Each of these processes can map the file mapping into its own address space as it sees fit. This is useful for sharing private memory between processes without having to create files for sharing. At the NT layer, file mappings (sections) can also be made persistent in the NT namespace and accessed by name. An important area for many programs is file I/O. In the basic Win32 view, a file is just a linear sequence of bytes. Win32 provides over 60 calls for creating and destroying files and directories, opening and closing files, reading and writing them, requesting and setting file attributes, locking ranges of bytes, and many more fundamental operations on both the organization of the file system and access to individual files. There are also various advanced facilities for managing data in files. In addi- tion to the primary data stream, files stored on the NTFS file system can have addi- tional data streams. Files (and even entire volumes) can be encrypted. Files can be compressed, and/or represented as a sparse stream of bytes where missing regions of data in the middle occupy no storage on disk. File-system volumes can be organized out of multiple separate disk partitions using different levels of RAID
clipped_os_Page_873_Chunk7090
874 CASE STUDY 2: WINDOWS 8 CHAP. 11 storage. Modifications to files or directory subtrees can be detected through a noti- fication mechanism, or by reading the journal that NTFS maintains for each vol- ume. Each file-system volume is implicitly mounted in the NT namespace, accord- ing to the name given to the volume, so a file \ foo \ bar might be named, for ex- ample, \ Device \ HarddiskVolume \ foo \ bar. Internal to each NTFS volume, mount points (called reparse points in Windows) and symbolic links are supported to help organize the individual volumes. The low-level I/O model in Windows is fundamentally asynchronous. Once an I/O operation is begun, the system call can return and allow the thread which initi- ated the I/O to continue in parallel with the I/O operation. Windows supports can- cellation, as well as a number of different mechanisms for threads to synchronize with I/O operations when they complete. Windows also allows programs to speci- fy that I/O should be synchronous when a file is opened, and many library func- tions, such as the C library and many Win32 calls, specify synchronous I/O for compatibility or to simplify the programming model. In these cases the executive will explicitly synchronize with I/O completion before returning to user mode. Another area for which Win32 provides calls is security. Every thread is asso- ciated with a kernel-mode object, called a token, which provides information about the identity and privileges associated with the thread. Every object can have an ACL (Access Control List) telling in great detail precisely which users may ac- cess it and which operations they may perform on it. This approach provides for fine-grained security in which specific users can be allowed or denied specific ac- cess to every object. The security model is extensible, allowing applications to add new security rules, such as limiting the hours access is permitted. The Win32 namespace is different than the native NT namespace described in the previous section. Only parts of the NT namespace are visible to Win32 APIs (though the entire NT namespace can be accessed through a Win32 hack that uses special prefix strings, like ‘‘ \ \ .’ ’). In Win32, files are accessed relative to drive let- ters. The NT directory \ DosDevices contains a set of symbolic links from drive letters to the actual device objects. For example, \ DosDevices \ C: might be a link to \ Device \ HarddiskVolume1. This directory also contains links for other Win32 devices, such as COM1:, LPT:, and NUL: (for the serial and printer ports and the all-important null device). \ DosDevices is really a symbolic link to \ ?? which was chosen for efficiency. Another NT directory, \ BaseNamedObjects, is used to store miscellaneous named kernel-mode objects accessible through the Win32 API. These include synchronization objects like semaphores, shared memory, timers, communication ports, and device names. In addition to low-level system interfaces we have described, the Win32 API also supports many functions for GUI operations, including all the calls for manag- ing the graphical interface of the system. There are calls for creating, destroying, managing, and using windows, menus, tool bars, status bars, scroll bars, dialog boxes, icons, and many more items that appear on the screen. There are calls for
clipped_os_Page_874_Chunk7091
SEC. 11.2 PROGRAMMING WINDOWS 875 drawing geometric figures, filling them in, managing the color palettes they use, dealing with fonts, and placing icons on the screen. Finally, there are calls for dealing with the keyboard, mouse and other human-input devices as well as audio, printing, and other output devices. The GUI operations work directly with the win32k.sys driver using special in- terfaces to access these functions in kernel mode from user-mode libraries. Since these calls do not involve the core system calls in the NTOS executive, we will not say more about them. 11.2.3 The Windows Registry The root of the NT namespace is maintained in the kernel. Storage, such as file-system volumes, is attached to the NT namespace. Since the NT namespace is constructed afresh every time the system boots, how does the system know about any specific details of the system configuration? The answer is that Windows attaches a special kind of file system (optimized for small files) to the NT name- space. This file system is called the registry. The registry is organized into sepa- rate volumes called hives. Each hive is kept in a separate file (in the directory C: \ Windows \ system32 \ config \ of the boot volume). When a Windows system boots, one particular hive named SYSTEM is loaded into memory by the same boot program that loads the kernel and other boot files, such as boot drivers, from the boot volume. Windows keeps a great deal of crucial information in the SYSTEM hive, in- cluding information about what drivers to use with what devices, what software to run initially, and many parameters governing the operation of the system. This information is used even by the boot program itself to determine which drivers are boot drivers, being needed immediately upon boot. Such drivers include those that understand the file system and disk drivers for the volume containing the operating system itself. Other configuration hives are used after the system boots to describe infor- mation about the software installed on the system, particular users, and the classes of user-mode COM (Component Object-Model) objects that are installed on the system. Login information for local users is kept in the SAM (Security Access Manager) hiv e. Information for network users is maintained by the lsass service in the security hive and coordinated with the network directory servers so that users can have a common account name and password across an entire network. A list of the hives used in Windows is shown in Fig. 11-9. Prior to the introduction of the registry, configuration information in Windows was kept in hundreds of .ini (initialization) files spread across the disk. The reg- istry gathers these files into a central store, which is available early in the process of booting the system. This is important for implementing Windows plug-and-play functionality. Unfortunately, the registry has become seriously disorganized over time as Windows has evolved. There are poorly defined conventions about how the
clipped_os_Page_875_Chunk7092
876 CASE STUDY 2: WINDOWS 8 CHAP. 11 Hive file Mounted name Use SYSTEM HKLM \SYSTEM OS configuration infor mation, used by ker nel HARDWARE HKLM \HARDWARE In-memory hive recording hardware detected BCD HKLM \BCD* Boot Configuration Database SAM HKLM \SAM Local user account infor mation SECURITY HKLM \SECURITY lsass’ account and other security infor mation DEFAULT HKEY USERS \.DEFAULT Default hive for new users NTUSER.DAT HKEY USERS \<user id> User-specific hive, kept in home directory SOFTWARE HKLM \SOFTWARE Application classes registered by COM COMPONENTS HKLM \COMPONENTS Manifests and dependencies for sys. components Figure 11-9. The registry hives in Windows. HKLM is a shorthand for HKEY LOCAL MACHINE. configuration information should be arranged, and many applications take an ad hoc approach. Most users, applications, and all drivers run with full privileges and frequently modify system parameters in the registry directly—sometimes interfer- ing with each other and destabilizing the system. The registry is a strange cross between a file system and a database, and yet really unlike either. Entire books have been written describing the registry (Born, 1998; Hipson, 2002; and Ivens, 1998), and many companies have sprung up to sell special software just to manage the complexity of the registry. To explore the registry Windows has a GUI program called regedit that allows you to open and explore the directories (called keys) and data items (called values). Microsoft’s Po werShell scripting language can also be useful for walking through the keys and values of the registry as if they were directories and files. A more in- teresting tool to use is procmon, which is available from Microsoft’s tools’ Web- site: www.microsoft.com/technet/sysinternals. Procmon watches all the registry accesses that take place in the system and is very illuminating. Some programs will access the same key over and over tens of thousands of times. As the name implies, regedit allows users to edit the registry—but be very careful if you ever do. It is very easy to render your system unable to boot, or damage the installation of applications so that you cannot fix them without a lot of wizardry. Microsoft has promised to clean up the registry in future releases, but for now it is a huge mess—far more complicated than the configuration infor- mation maintained in UNIX. The complexity and fragility of the registry led de- signers of new operating systems—in particular—iOS and Android—to avoid any- thing like it. The registry is accessible to the Win32 programmer. There are calls to create and delete keys, look up values within keys, and more. Some of the more useful ones are listed in Fig. 11-10.
clipped_os_Page_876_Chunk7093
SEC. 11.2 PROGRAMMING WINDOWS 877 Win32 API function Description RegCreateKeyEx Create a new registr y key RegDeleteKey Delete a registry key RegOpenKeyEx Open a key to get a handle to it RegEnumKeyEx Enumerate the subkeys subordinate to the key of the handle RegQuer yValueEx Look up the data for a value within a key Figure 11-10. Some of the Win32 API calls for using the registry When the system is turned off, most of the registry information is stored on the disk in the hives. Because their integrity is so critical to correct system func- tioning, backups are made automatically and metadata writes are flushed to disk to prevent corruption in the event of a system crash. Loss of the registry requires reinstalling all software on the system. 11.3 SYSTEM STRUCTURE In the previous sections we examined Windows as seen by the programmer writing code for user mode. Now we are going to look under the hood to see how the system is organized internally, what the various components do, and how they interact with each other and with user programs. This is the part of the system seen by the programmer implementing low-level user-mode code, like subsystems and native services, as well as the view of the system provided to device-driver writers. Although there are many books on how to use Windows, there are many fewer on how it works inside. One of the best places to look for additional information on this topic is Microsoft Windows Internals, 6th ed., Parts 1 and 2 (Russinovich and Solomon, 2012). 11.3.1 Operating System Structure As described earlier, the Windows operating system consists of many layers, as depicted in Fig. 11-4. In the following sections we will dig into the lowest levels of the operating system: those that run in kernel mode. The central layer is the NTOS kernel itself, which is loaded from ntoskrnl.exe when Windows boots. NTOS itself consists of two layers, the executive, which containing most of the services, and a smaller layer which is (also) called the kernel and implements the underlying thread scheduling and synchronization abstractions (a kernel within the kernel?), as well as implementing trap handlers, interrupts, and other aspects of how the CPU is managed.
clipped_os_Page_877_Chunk7094
878 CASE STUDY 2: WINDOWS 8 CHAP. 11 The division of NTOS into kernel and executive is a reflection of NT’s VAX/VMS roots. The VMS operating system, which was also designed by Cutler, had four hardware-enforced layers: user, supervisor, executive, and kernel corres- ponding to the four protection modes provided by the VAX processor architecture. The Intel CPUs also support four rings of protection, but some of the early target processors for NT did not, so the kernel and executive layers represent a soft- ware-enforced abstraction, and the functions that VMS provides in supervisor mode, such as printer spooling, are provided by NT as user-mode services. The kernel-mode layers of NT are shown in Fig. 11-11. The kernel layer of NTOS is shown above the executive layer because it implements the trap and inter- rupt mechanisms used to transition from user mode to kernel mode. User mode Kernel mode System library kernel user-mode dispatch routines (ntdll.dll) Hardware abstraction layer Security monitor Object manager Config manager Executive run-time library Trap/exception/interrupt dispatch CPU scheduling and synchronization: threads, ISRs, DPCs, APCs NTOS kernel layer NTOS executive layer I/O manager Virtual memory Cache manager Procs and threads LPC File systems, volume manager, TCP/IP stack, net interfaces graphics devices, all other devices Hardware CPU, MMU, interrupt controllers, memory, physical devices, BIOS Drivers Figure 11-11. Windows kernel-mode organization. The uppermost layer in Fig. 11-11 is the system library (ntdll.dll), which ac- tually runs in user mode. The system library includes a number of support func- tions for the compiler run-time and low-level libraries, similar to what is in libc in UNIX. ntdll.dll also contains special code entry points used by the kernel to ini- tialize threads and dispatch exceptions and user-mode APCs (Asynchronous Pro- cedure Calls). Because the system library is so integral to the operation of the ker- nel, every user-mode process created by NTOS has ntdll mapped at the same fixed address. When NTOS is initializing the system it creates a section object to use when mapping ntdll, and it also records addresses of the ntdll entry points used by the kernel. Below the NTOS kernel and executive layers is a layer of software called the HAL (Hardware Abstraction Layer) which abstracts low-level hardware details like access to device registers and DMA operations, and the way the parentboard
clipped_os_Page_878_Chunk7095
SEC. 11.3 SYSTEM STRUCTURE 879 firmware represents configuration information and deals with differences in the CPU support chips, such as various interrupt controllers. The lowest software layer is the hypervisor, which Windows calls Hyper-V. The hypervisor is an optional feature (not shown in Fig. 11-11). It is available in many versions of Windows—including the professional desktop client. The hyper- visor intercepts many of the privileged operations performed by the kernel and emulates them in a way that allows multiple operating systems to run at the same time. Each operating system runs in its own virtual machine, which Windows calls a partition. The hypervisor uses features in the hardware architecture to protect physical memory and provide isolation between partitions. An operating system running on top of the hypervisor executes threads and handles interrupts on abstractions of the physical processors called virtual processors. The hypervisor schedules the virtual processors on the physical processors. The main (root) operating system runs in the root partition. It provides many services to the other (guest) partitions. Some of the most important services pro- vide integration of the guests with the shared devices such as networking and the GUI. While the root operating system must be Windows when running Hyper-V, other operating systems, such as Linux, can be run in the guest partitions. A guest operating system may perform very poorly unless it has been modified (i.e., para- virtualized) to work with the hypervisor. For example, if a guest operating system kernel is using a spinlock to synchro- nize between two virtual processors and the hypervisor reschedules the virtual processor holding the spinlock, the lock hold time may increase by orders of mag- nitude, leaving other virtual processors running in the partition spinning for very long periods of time. To solve this problem a guest operating system is enlight- ened to spin only a short time before calling into the hypervisor to yield its physi- cal processor to run another virtual processor. The other major components of kernel mode are the device drivers. Windows uses device drivers for any kernel-mode facilities which are not part of NTOS or the HAL. This includes file systems, network protocol stacks, and kernel exten- sions like antivirus and DRM (Digital Rights Management) software, as well as drivers for managing physical devices, interfacing to hardware buses, and so on. The I/O and virtual memory components cooperate to load (and unload) device drivers into kernel memory and link them to the NTOS and HAL layers. The I/O manager provides interfaces which allow devices to be discovered, organized, and operated—including arranging to load the appropriate device driver. Much of the configuration information for managing devices and drivers is maintained in the SYSTEM hive of the registry. The plug-and-play subcomponent of the I/O man- ager maintains information about the hardware detected within the HARDWARE hive, which is a volatile hive maintained in memory rather than on disk, as it is completely recreated every time the system boots. We will now examine the various components of the operating system in a bit more detail.
clipped_os_Page_879_Chunk7096
880 CASE STUDY 2: WINDOWS 8 CHAP. 11 The Hardware Abstraction Layer One goal of Windows is to make the system portable across hardware plat- forms. Ideally, to bring up an operating system on a new type of computer system it should be possible to just recompile the operating system on the new platform. Unfortunately, it is not this simple. While many of the components in some layers of the operating system can be largely portable (because they mostly deal with in- ternal data structures and abstractions that support the programming model), other layers must deal with device registers, interrupts, DMA, and other hardware fea- tures that differ significantly from machine to machine. Most of the source code for the NTOS kernel is written in C rather than assem- bly language (only 2% is assembly on x86, and less than 1% on x64). However, all this C code cannot just be scooped up from an x86 system, plopped down on, say, an ARM system, recompiled, and rebooted owing to the many hardware differ- ences between processor architectures that have nothing to do with the different in- struction sets and which cannot be hidden by the compiler. Languages like C make it difficult to abstract away some hardware data structures and parameters, such as the format of page-table entries and the physical memory page sizes and word length, without severe performance penalties. All of these, as well as a slew of hardware-specific optimizations, would have to be manually ported even though they are not written in assembly code. Hardware details about how memory is organized on large servers, or what hardware synchronization primitives are available, can also have a big impact on higher levels of the system. For example, NT’s virtual memory manager and the kernel layer are aware of hardware details related to cache and memory locality. Throughout the system NT uses compare&swap synchronization primitives, and it would be difficult to port to a system that does not have them. Finally, there are many dependencies in the system on the ordering of bytes within words. On all the systems NT has ever been ported to, the hardware was set to little-endian mode. Besides these larger issues of portability, there are also minor ones even be- tween different parentboards from different manufacturers. Differences in CPU versions affect how synchronization primitives like spin-locks are implemented. There are several families of support chips that create differences in how hardware interrupts are prioritized, how I/O device registers are accessed, management of DMA transfers, control of the timers and real-time clock, multiprocessor synchron- ization, working with firmware facilities such as ACPI (Advanced Configuration and Power Interface), and so on. Microsoft made a serious attempt to hide these types of machine dependencies in a thin layer at the bottom called the HAL, as mentioned earlier. The job of the HAL is to present the rest of the operating sys- tem with abstract hardware that hides the specific details of processor version, sup- port chipset, and other configuration variations. These HAL abstractions are pres- ented in the form of machine-independent services (procedure calls and macros) that NTOS and the drivers can use.
clipped_os_Page_880_Chunk7097
SEC. 11.3 SYSTEM STRUCTURE 881 By using the HAL services and not addressing the hardware directly, drivers and the kernel require fewer changes when being ported to new processors—and in most cases can run unmodified on systems with the same processor architecture, despite differences in versions and support chips. The HAL does not provide abstractions or services for specific I/O devices such as keyboards, mice, and disks or for the memory management unit. These facilities are spread throughout the kernel-mode components, and without the HAL the amount of code that would have to be modified when porting would be sub- stantial, even when the actual hardware differences were small. Porting the HAL itself is straightforward because all the machine-dependent code is concentrated in one place and the goals of the port are well defined: implement all of the HAL ser- vices. For many releases Microsoft supported a HAL Development Kit allowing system manufacturers to build their own HAL, which would allow other kernel components to work on new systems without modification, provided that the hard- ware changes were not too great. As an example of what the hardware abstraction layer does, consider the issue of memory-mapped I/O vs. I/O ports. Some machines have one and some have the other. How should a driver be programmed: to use memory-mapped I/O or not? Rather than forcing a choice, which would make the driver not portable to a ma- chine that did it the other way, the hardware abstraction layer offers three proce- dures for driver writers to use for reading the device registers and another three for writing them: uc = READ PORT UCHAR(por t); WRITE PORT UCHAR(por t, uc); us = READ PORT USHORT(por t); WRITE PORT USHORT(por t, us); ul = READ PORT ULONG(por t); WRITE PORT LONG(por t, ul); These procedures read and write unsigned 8-, 16-, and 32-bit integers, respectively, to the specified port. It is up to the hardware abstraction layer to decide whether memory-mapped I/O is needed here. In this way, a driver can be moved without modification between machines that differ in the way the device registers are im- plemented. Drivers frequently need to access specific I/O devices for various purposes. At the hardware level, a device has one or more addresses on a certain bus. Since modern computers often have multiple buses (PCI, PCIe, USB, IEEE 1394, etc.), it can happen that more than one device may have the same address on different buses, so some way is needed to distinguish them. The HAL provides a service for identifying devices by mapping bus-relative device addresses onto systemwide log- ical addresses. In this way, drivers do not have to keep track of which device is connected to which bus. This mechanism also shields higher layers from proper- ties of alternative bus structures and addressing conventions. Interrupts have a similar problem—they are also bus dependent. Here, too, the HAL provides services to name interrupts in a systemwide way and also provides ways to allow drivers to attach interrupt service routines to interrupts in a portable
clipped_os_Page_881_Chunk7098
882 CASE STUDY 2: WINDOWS 8 CHAP. 11 way, without having to know anything about which interrupt vector is for which bus. Interrupt request level management is also handled in the HAL. Another HAL service is setting up and managing DMA transfers in a de- vice-independent way. Both the systemwide DMA engine and DMA engines on specific I/O cards can be handled. Devices are referred to by their logical ad- dresses. The HAL implements software scatter/gather (writing or reading from noncontiguous blocks of physical memory). The HAL also manages clocks and timers in a portable way. Time is kept track of in units of 100 nanoseconds starting at midnight on 1 January 1601, which is the first date in the previous quadricentury, which simplifies leap-year computa- tions. (Quick Quiz: Was 1800 a leap year? Quick Answer: No.) The time services decouple the drivers from the actual frequencies at which the clocks run. Kernel components sometimes need to synchronize at a very low lev el, espe- cially to prevent race conditions in multiprocessor systems. The HAL provides primitives to manage this synchronization, such as spin locks, in which one CPU simply waits for a resource held by another CPU to be released, particularly in situations where the resource is typically held only for a few machine instructions. Finally, after the system has been booted, the HAL talks to the computer’s firmware (BIOS) and inspects the system configuration to find out which buses and I/O devices the system contains and how they hav e been configured. This infor- mation is then put into the registry. A summary of some of the things the HAL does is given in Fig. 11-12. Device registers Device addresses Interrupts DMA Timers Spin locks Firmware Disk RAM Printer 1. 2. 3. MOV EAX,ABC ADD EAX,BAX BNE LABEL MOV EAX,ABC MOV EAX,ABC ADD EAX,BAX BNE LABEL MOVE AX,ABC ADD EAX,BAX BNE LABEL Hardware abstraction layer Figure 11-12. Some of the hardware functions the HAL manages. The Kernel Layer Above the hardware abstraction layer is NTOS, consisting of two layers: the kernel and the executive. ‘‘Kernel’’ is a confusing term in Windows. It can refer to all the code that runs in the processor’s kernel mode. It can also refer to the
clipped_os_Page_882_Chunk7099
SEC. 11.3 SYSTEM STRUCTURE 883 ntoskrnl.exe file which contains NTOS, the core of the Windows operating system. Or it can refer to the kernel layer within NTOS, which is how we use it in this sec- tion. It is even used to name the user-mode Win32 library that provides the wrap- pers for the native system calls: kernel32.dll. In the Windows operating system the kernel layer, illustrated above the execu- tive layer in Fig. 11-11, provides a set of abstractions for managing the CPU. The most central abstraction is threads, but the kernel also implements exception han- dling, traps, and several kinds of interrupts. Creating and destroying the data struc- tures which support threading is implemented in the executive layer. The kernel layer is responsible for scheduling and synchronization of threads. Having support for threads in a separate layer allows the executive layer to be implemented using the same preemptive multithreading model used to write concurrent code in user mode, though the synchronization primitives in the executive are much more spe- cialized. The kernel’s thread scheduler is responsible for determining which thread is executing on each CPU in the system. Each thread executes until a timer interrupt signals that it is time to switch to another thread (quantum expired), or until the thread needs to wait for something to happen, such as an I/O to complete or for a lock to be released, or a higher-priority thread becomes runnable and needs the CPU. When switching from one thread to another, the scheduler runs on the CPU and ensures that the registers and other hardware state have been saved. The scheduler then selects another thread to run on the CPU and restores the state that was previously saved from the last time that thread ran. If the next thread to be run is in a different address space (i.e., process) than the thread being switched from, the scheduler must also change address spaces. The details of the scheduling algorithm itself will be discussed later in this chapter when we come to processes and threads. In addition to providing a higher-level abstraction of the hardware and han- dling thread switches, the kernel layer also has another key function: providing low-level support for two classes of synchronization mechanisms: control objects and dispatcher objects. Control objects are the data structures that the kernel layer provides as abstractions to the executive layer for managing the CPU. They are allocated by the executive but they are manipulated with routines provided by the kernel layer. Dispatcher objects are the class of ordinary executive objects that use a common data structure for synchronization. Deferred Procedure Calls Control objects include primitive objects for threads, interrupts, timers, syn- chronization, profiling, and two special objects for implementing DPCs and APCs. DPC (Deferred Procedure Call) objects are used to reduce the time taken to ex- ecute ISRs (Interrupt Service Routines) in response to an interrupt from a partic- ular device. Limiting time spent in ISRs reduces the chance of losing an interrupt.
clipped_os_Page_883_Chunk7100